forked from cloudwego/abcoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspec.go
More file actions
421 lines (387 loc) · 10.5 KB
/
spec.go
File metadata and controls
421 lines (387 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
// Copyright 2025 CloudWeGo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package python
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/cloudwego/abcoder/lang/log"
lsp "github.com/cloudwego/abcoder/lang/lsp"
"github.com/cloudwego/abcoder/lang/uniast"
)
type PythonSpec struct {
repo string
topModuleName string
topModulePath string
sysPaths []string
}
func (c *PythonSpec) ProtectedSymbolKinds() []lsp.SymbolKind {
return []lsp.SymbolKind{}
}
func NewPythonSpec() *PythonSpec {
cmd := exec.Command("python", "-c", "import sys ; print('\\n'.join(sys.path))")
output, err := cmd.Output()
if err != nil {
log.Error("Failed to get sys.path: %v\n", err)
return nil
}
sysPaths := strings.Split(string(output), "\n")
// Match more specific paths first
sort.Slice(sysPaths, func(i, j int) bool {
return len(sysPaths[i]) > len(sysPaths[j])
})
log.Info("PythonSpec: using sysPaths %+v\n", sysPaths)
return &PythonSpec{sysPaths: sysPaths}
}
func (c *PythonSpec) WorkSpace(root string) (map[string]string, error) {
c.repo = root
rets := map[string]string{}
absPath, err := filepath.Abs(root)
if err != nil {
return nil, err
}
num_projfiles := 0
scanner := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
base := filepath.Base(path)
if base == "pyproject.toml" {
num_projfiles++
if num_projfiles > 1 {
panic("multiple pyproject.toml files found")
}
}
return nil
}
if err := filepath.Walk(root, scanner); err != nil {
return nil, err
}
c.topModulePath = absPath
// TODO: find a way to infer the module (project) name.
c.topModuleName = "current"
rets[c.topModuleName] = c.topModulePath
return rets, nil
}
// returns: modName, pkgPath, error
func (c *PythonSpec) NameSpace(path string, file *uniast.File) (string, string, error) {
if strings.HasPrefix(path, c.topModulePath) {
// internal module
modName := c.topModuleName
relPath, err := filepath.Rel(c.topModulePath, path)
if err != nil {
return "", "", err
}
// todo: handle __init__.py
relPath = strings.TrimSuffix(relPath, ".py")
pkgPath := strings.ReplaceAll(relPath, string(os.PathSeparator), ".")
return modName, pkgPath, nil
}
for _, sysPath := range c.sysPaths {
if strings.HasPrefix(path, sysPath) {
relPath, err := filepath.Rel(sysPath, path)
if err != nil {
return "", "", err
}
relPath = strings.TrimSuffix(relPath, ".py")
pkgPath := strings.ReplaceAll(relPath, string(os.PathSeparator), ".")
modPath := strings.Split(pkgPath, ".")
if len(modPath) >= 1 {
modName := modPath[0]
return modName, pkgPath, nil
}
panic(fmt.Sprintf("Malformed Namespace %s, pkgPath %s", path, pkgPath))
}
}
log.Error("Namespace not found for path: %s\n", path)
return "", "", fmt.Errorf("namespace not found for path: %s", path)
}
func (c *PythonSpec) ShouldSkip(path string) bool {
if !strings.HasSuffix(path, ".py") {
return true
}
return false
}
func (c *PythonSpec) IsDocToken(tok lsp.Token) bool {
return tok.Type == "comment"
}
func (c *PythonSpec) DeclareTokenOfSymbol(sym lsp.DocumentSymbol) int {
for i, t := range sym.Tokens {
if c.IsDocToken(t) {
continue
}
for _, m := range t.Modifiers {
if m == "declaration" {
return i
}
}
}
return -1
}
func (c *PythonSpec) IsEntityToken(tok lsp.Token) bool {
typ := tok.Type
return typ == "function" || typ == "variable" || typ == "property" || typ == "class" || typ == "type"
}
func (c *PythonSpec) IsStdToken(tok lsp.Token) bool {
panic("TODO")
}
func (c *PythonSpec) TokenKind(tok lsp.Token) lsp.SymbolKind {
switch tok.Type {
case "namespace":
return lsp.SKNamespace
case "type":
return lsp.SKObject // no direct match; mapped to Object conservatively
case "class":
return lsp.SKClass
case "enum":
return lsp.SKEnum
case "interface":
return lsp.SKInterface
case "struct":
return lsp.SKStruct
case "typeParameter":
return lsp.SKTypeParameter
case "parameter":
return lsp.SKVariable
case "variable":
return lsp.SKVariable
case "property":
return lsp.SKProperty
case "enumMember":
return lsp.SKEnumMember
case "event":
return lsp.SKEvent
case "function":
return lsp.SKFunction
case "method":
return lsp.SKMethod
case "macro":
return lsp.SKFunction
case "string":
return lsp.SKString
case "number":
return lsp.SKNumber
case "operator":
return lsp.SKOperator
default:
return lsp.SKUnknown
}
}
func (c *PythonSpec) IsMainFunction(sym lsp.DocumentSymbol) bool {
// XXX: maybe just use __main__?
return sym.Kind == lsp.SKFunction && sym.Name == "main"
}
func (c *PythonSpec) IsEntitySymbol(sym lsp.DocumentSymbol) bool {
typ := sym.Kind
return typ == lsp.SKObject || typ == lsp.SKMethod || typ == lsp.SKFunction || typ == lsp.SKVariable ||
typ == lsp.SKStruct || typ == lsp.SKEnum || typ == lsp.SKTypeParameter || typ == lsp.SKConstant || typ == lsp.SKClass
}
func (c *PythonSpec) IsPublicSymbol(sym lsp.DocumentSymbol) bool {
// builtin methods are exported
if strings.HasPrefix(sym.Name, "__") && strings.HasSuffix(sym.Name, "__") {
return true
}
if strings.HasPrefix(sym.Name, "_") {
return false
}
return true
}
func (c *PythonSpec) HasImplSymbol() bool {
return true
}
func invalidPos() lsp.Position {
return lsp.Position{
Line: -1,
Character: -1,
}
}
// returns interface, receiver, first method
func (c *PythonSpec) ImplSymbol(sym lsp.DocumentSymbol) (int, int, int) {
// reference: https://docs.python.org/3/reference/grammar.html
if sym.Kind != lsp.SKClass {
return -1, -1, -1
}
implType := -1
receiverType := -1
firstMethod := -1
// state 0: goto state -1 when we see a 'class'
state := 0
clsnamepos := invalidPos()
curpos := sym.Location.Range.Start
for i := range len(sym.Text) {
if state == -1 {
break
}
switch state {
case 0:
if i+6 >= len(sym.Text) {
// class text does not contain a 'class'
// should be an import
return -1, -1, -1
}
next6chars := sym.Text[i : i+6]
// heuristics should work with reasonable python code
if next6chars == "class " {
clsnamepos = curpos
state = -1
}
}
if sym.Text[i] == '\n' {
curpos.Line++
curpos.Character = 0
} else {
curpos.Character++
}
}
for i, t := range sym.Tokens {
if receiverType == -1 && clsnamepos.Less(t.Location.Range.Start) {
receiverType = i
}
}
return implType, receiverType, firstMethod
}
// returns: receiver, typeParams, inputParams, outputParams
func (c *PythonSpec) FunctionSymbol(sym lsp.DocumentSymbol) (int, []int, []int, []int) {
// FunctionSymbol do not return receivers.
// TODO type params in python (nobody uses them)
// reference: https://docs.python.org/3/reference/grammar.html
receiver := -1
// python actually has these but TODO
typeParams := []int{}
// Hell, manually parse function text to get locations of key tokens since LSP does not support this...
//
// state 0: goto state 1 when we see a def
// state 1: goto state 2 when we see a (
// state 2: we're in the param list.
// collect input params by checking entity tokens.
// goto state 3 when we see a )
// state 3: collect output params.
// finish when we see a :
state := 0
paren_depth := 0
// defpos := invalidPos()
lparenpos := invalidPos()
rparenpos := invalidPos()
bodypos := invalidPos()
curpos := sym.Location.Range.Start
for i := range len(sym.Text) {
if state == -1 {
break
}
switch state {
case 0:
if i+4 >= len(sym.Text) {
// function text does not contain a 'def'
// should be an import
return -1, []int{}, []int{}, []int{}
}
next4chars := sym.Text[i : i+4]
// heuristics should work with reasonable python code
if next4chars == "def " {
// defpos = curpos
state = 1
}
case 1:
if sym.Text[i] == '(' {
lparenpos = curpos
paren_depth = 1
state = 2
}
case 2:
if sym.Text[i] == ')' {
rparenpos = curpos
paren_depth -= 1
if paren_depth == 0 {
state = 3
}
}
case 3:
if sym.Text[i] == ':' {
bodypos = curpos
state = -1
}
}
if sym.Text[i] == '\n' {
curpos.Line++
curpos.Character = 0
} else {
curpos.Character++
}
}
paramsrange := lsp.Range{
Start: lparenpos,
End: rparenpos,
}
returnrange := lsp.Range{
Start: rparenpos,
End: bodypos,
}
inputParams := []int{}
outputParams := []int{}
for i, t := range sym.Tokens {
if paramsrange.Include(t.Location.Range) {
if c.IsEntityToken(t) {
inputParams = append(inputParams, i)
}
}
if returnrange.Include(t.Location.Range) {
if c.IsEntityToken(t) {
outputParams = append(outputParams, i)
}
}
}
return receiver, typeParams, inputParams, outputParams
}
func (c *PythonSpec) GetUnloadedSymbol(from lsp.Token, define lsp.Location) (string, error) {
panic("TODO")
}
func (c *PythonSpec) FileImports(content []byte) ([]uniast.Import, error) {
// Reference:
// https://docs.python.org/3/reference/grammar.html
// There are two types of imports in Python:
// import-as: on ONE line
// import xxx as x, yyy as y
// from-import: on ONE line
// from ... import *
// from ... import xxx as x, yyy as y
// or on POSSIBLY MULTIPLE lines, enclosed by parentheses
// from ... import ( xxx, yyy as y ... )
// And imports are simple stmts, so they MUST end with \n.
patterns := []string{
// Matches: import <anything> (on a single line)
`(?m)^import\s+(.*)$`,
// Matches: from <anything> import <anything> (on a single line, without parentheses)
`(?m)^from\s+(.*?)\s+import\s+([^()\n]*)$`,
// Matches: from <anything> import ( <anything> ) where <anything> can span multiple lines
`(?m)^from\s+(.*?)\s+import\s+\(([\s\S]*?)\)$`,
}
res := []uniast.Import{}
for _, p := range patterns {
re, err := regexp.Compile(p)
if err != nil {
return nil, fmt.Errorf("error compiling regex pattern '%s': %w", p, err)
}
matches := re.FindAllStringSubmatch(string(content), -1) // -1 to find all non-overlapping matches
for _, match := range matches {
res = append(res, uniast.Import{
Path: match[0],
})
}
}
return res, nil
}