-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathexport.go
More file actions
535 lines (499 loc) · 14.2 KB
/
export.go
File metadata and controls
535 lines (499 loc) · 14.2 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// 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 collect
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"github.com/cloudwego/abcoder/lang/log"
. "github.com/cloudwego/abcoder/lang/lsp"
"github.com/cloudwego/abcoder/lang/uniast"
"github.com/cloudwego/abcoder/lang/utils"
)
type dependency struct {
Location Location `json:"location"`
Symbol *DocumentSymbol `json:"symbol"`
}
func (c *Collector) fileLine(loc Location) uniast.FileLine {
var rel string
if c.internal(loc) {
rel, _ = filepath.Rel(c.repo, loc.URI.File())
} else {
rel = filepath.Base(loc.URI.File())
}
fileURI := string(loc.URI)
if c.cli == nil {
return uniast.FileLine{File: rel, Line: loc.Range.Start.Line + 1}
}
f := c.cli.GetFile(loc.URI)
text := ""
if f != nil {
text = f.Text
} else {
fd, err := os.ReadFile(loc.URI.File())
if err != nil {
return uniast.FileLine{File: rel, Line: loc.Range.Start.Line + 1}
}
text = string(fd)
}
return uniast.FileLine{
File: rel,
Line: loc.Range.Start.Line + 1,
StartOffset: PositionOffset(fileURI, text, loc.Range.Start),
EndOffset: PositionOffset(fileURI, text, loc.Range.End),
}
}
func newModule(name string, dir string, lang uniast.Language) *uniast.Module {
ret := uniast.NewModule(name, dir, lang)
return ret
}
func (c *Collector) ExportLocalFunction() map[Location]*DocumentSymbol {
if len(c.localFunc) == 0 {
c.localFunc = make(map[Location]*DocumentSymbol)
for symbol := range c.funcs {
c.localFunc[symbol.Location] = symbol
}
}
return c.localFunc
}
func (c *Collector) Export(ctx context.Context) (*uniast.Repository, error) {
// recursively read all go files in repo
repo := uniast.NewRepository(c.repo)
modules, err := c.spec.WorkSpace(c.repo)
if err != nil {
return nil, err
}
// set modules on repo
for name, path := range modules {
rel, err := filepath.Rel(c.repo, path)
if err != nil {
return nil, err
}
repo.Modules[name] = newModule(name, rel, c.Language)
}
// not allow local symbols inside another symbol
c.filterLocalSymbols()
// export symbols
visited := make(map[*DocumentSymbol]*uniast.Identity)
for _, symbol := range c.syms {
_, _ = c.exportSymbol(&repo, symbol, "", visited)
}
for fp, f := range c.files {
rel, err := filepath.Rel(c.repo, fp)
if err != nil {
continue
}
modpath, pkgpath, err := c.spec.NameSpace(fp, f)
if err != nil {
continue
}
// connect file to package
if modpath == "" || strings.Contains(modpath, "@") {
continue
}
m, ok := repo.Modules[modpath]
if !ok {
continue
}
m.Files[rel] = f
if pkgpath == "" || f.Package != "" {
continue
}
if _, ok := m.Packages[pkgpath]; !ok {
continue
}
f.Package = pkgpath
}
return &repo, nil
}
var (
ErrStdSymbol = errors.New("std symbol")
ErrExternalSymbol = errors.New("external symbol")
)
// NOTICE: for rust and golang, each entity has separate location
// TODO: some language may allow local symbols inside another symbol,
func (c *Collector) filterLocalSymbols() {
// filter symbols
for loc1 := range c.syms {
for loc2 := range c.syms {
if loc1 == loc2 {
continue
}
if loc2.Include(loc1) {
if utils.Contains(c.spec.ProtectedSymbolKinds(), c.syms[loc1].Kind) {
break
}
delete(c.syms, loc1)
break
}
}
}
}
func (c *Collector) exportSymbol(repo *uniast.Repository, symbol *DocumentSymbol, refName string, visited map[*DocumentSymbol]*uniast.Identity) (id *uniast.Identity, e error) {
defer func() {
if e != nil && e != ErrStdSymbol && e != ErrExternalSymbol {
log.Info("export symbol %s failed: %v\n", symbol, e)
}
}()
if symbol == nil {
e = errors.New("symbol is nil")
return
}
// 判断是否为本地符号
// 只有符号是“定义”,或者符号是“本地方法”时,才需要完整导出
// 其他情况(如外部引用、或对本地非顶层符号的引用)都只导出标识符
isDefinition := symbol.Role == DEFINITION
_, isLocalMethod := c.funcs[symbol]
_, isLocalSymbol := c.syms[symbol.Location]
if !isDefinition {
if isLocalSymbol {
//引用类型符号,把引用类型符号替换为local 符号
symbol = c.syms[symbol.Location]
} else {
if symbol.Kind == SKFunction || symbol.Kind == SKMethod {
documentSymbol := c.ExportLocalFunction()[symbol.Location]
if documentSymbol != nil {
symbol = documentSymbol
}
}
}
}
if id, ok := visited[symbol]; ok {
return id, nil
}
// Check NeedStdSymbol
file := symbol.Location.URI.File()
mod, path, err := c.spec.NameSpace(file, c.files[file])
if err != nil {
e = err
return
}
// Java IPC mode: external/JDK/third-party symbols are exported as one-layer stub identities,
// and MUST NOT create module/package entries in repo.
isJavaIPC := c.Language == uniast.Java && c.javaIPC != nil
if isJavaIPC && !c.internal(symbol.Location) {
name := symbol.Name
if name == "" {
if refName == "" {
e = fmt.Errorf("both symbol %v name and refname is empty", symbol)
return
}
name = refName
}
m := "@external"
fp := symbol.Location.URI.File()
if strings.Contains(fp, "abcoder-jdk") {
m = "@jdk"
} else if strings.Contains(fp, "abcoder-third") {
m = "@third"
}
tmp := uniast.NewIdentity(m, "external", name)
id = &tmp
visited[symbol] = id
return id, nil
}
if !c.NeedStdSymbol && mod == "" {
e = ErrStdSymbol
return
}
// Load external symbol on demands
if !c.LoadExternalSymbol && (!c.internal(symbol.Location) || symbol.Kind == SKUnknown) {
e = ErrExternalSymbol
return
}
// Construct Identity and save to visited
name := symbol.Name
if name == "" {
if refName == "" {
e = fmt.Errorf("both symbol %v name and refname is empty", symbol)
return
}
// NOTICE: use refName as id when symbol name is missing
name = refName
}
tmp := uniast.NewIdentity(mod, path, name)
id = &tmp
// Save to visited ONLY WHEN no errors occur
visited[symbol] = id
// Walk down from repo struct
if repo.Modules[mod] == nil {
repo.Modules[mod] = newModule(mod, "", c.Language)
}
module := repo.Modules[mod]
if module.Packages[path] == nil {
module.Packages[path] = uniast.NewPackage(path)
}
pkg := repo.Modules[mod].Packages[path]
if c.spec.IsMainFunction(*symbol) {
pkg.IsMain = true
}
fileLine := c.fileLine(symbol.Location)
content := symbol.Text
public := c.spec.IsPublicSymbol(*symbol)
if !isDefinition && !isLocalMethod && !isLocalSymbol {
// In Java IPC mode we never rely on LSP Definition.
if !isJavaIPC {
if c.cli == nil {
return id, fmt.Errorf("LSP client is nil")
}
defs, err := c.cli.Definition(context.Background(), symbol.Location.URI, symbol.Location.Range.Start)
if err != nil || len(defs) == 0 {
// 意味着引用为外部符号,LSP 无法查询到符号定位
return id, err
}
}
}
// map receiver to methods
receivers := make(map[*DocumentSymbol][]*DocumentSymbol, len(c.funcs)/4)
for method, rec := range c.funcs {
if method.Kind == SKMethod && rec.Method != nil && rec.Method.Receiver.Symbol != nil {
receivers[rec.Method.Receiver.Symbol] = append(receivers[rec.Method.Receiver.Symbol], method)
}
}
// Sort methods within each receiver by source location for deterministic output
for _, methods := range receivers {
sort.Slice(methods, func(i, j int) bool {
if methods[i].Location.Range.Start.Line != methods[j].Location.Range.Start.Line {
return methods[i].Location.Range.Start.Line < methods[j].Location.Range.Start.Line
}
return methods[i].Location.Range.Start.Character < methods[j].Location.Range.Start.Character
})
}
switch k := symbol.Kind; k {
// Function
case SKFunction, SKMethod:
if c.cli != nil {
if p := c.cli.GetParent(symbol); p != nil && p.Kind == SKInterface {
// NOTICE: no need collect interface method
break
}
}
obj := &uniast.Function{
FileLine: fileLine,
Content: content,
Exported: public,
}
info := c.funcs[symbol]
obj.Signature = info.Signature
// NOTICE: type parames collect into types
if info.TypeParams != nil {
for _, input := range info.TypeParamsSorted {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(input.Location)
}
tyid, err := c.exportSymbol(repo, input.Symbol, tok, visited)
if err != nil {
continue
}
dep := uniast.NewDependency(*tyid, c.fileLine(input.Location))
obj.Types = uniast.InsertDependency(obj.Types, dep)
}
}
if info.Inputs != nil {
for _, input := range info.InputsSorted {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(input.Location)
}
tyid, err := c.exportSymbol(repo, input.Symbol, tok, visited)
if err != nil {
continue
}
dep := uniast.NewDependency(*tyid, c.fileLine(input.Location))
obj.Params = uniast.InsertDependency(obj.Params, dep)
}
}
if info.Outputs != nil {
for _, output := range info.OutputsSorted {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(output.Location)
}
tyid, err := c.exportSymbol(repo, output.Symbol, tok, visited)
if err != nil {
continue
}
dep := uniast.NewDependency(*tyid, c.fileLine(output.Location))
obj.Results = uniast.InsertDependency(obj.Results, dep)
}
}
if info.Method != nil && info.Method.Receiver.Symbol != nil {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(info.Method.Receiver.Location)
}
rid, err := c.exportSymbol(repo, info.Method.Receiver.Symbol, tok, visited)
if err == nil {
obj.Receiver = &uniast.Receiver{
Type: *rid,
// Name: rid.Name,
}
obj.IsMethod = true
id.Name = rid.Name
// NOTICE: check if the method is a trait method
// if true, type = trait<receiver>
if info.Method.Interface != nil {
itok := ""
if c.cli != nil {
itok, _ = c.cli.Locate(info.Method.Interface.Location)
}
iid, err := c.exportSymbol(repo, info.Method.Interface.Symbol, itok, visited)
if err == nil {
id.Name = iid.Name + "<" + id.Name + ">"
}
}
if k == SKFunction {
// NOTICE: class static method name is: type::method
id.Name += "::" + name
} else {
// NOTICE: object method name is: type.method
id.Name += "." + name
}
// NOTICE: keep impl codes to the content
if info.Method.ImplHead != "" {
obj.Content = info.Method.ImplHead + obj.Content + "\n}"
}
}
}
// collect deps
if deps := c.deps[symbol]; deps != nil {
for _, dep := range deps {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(dep.Location)
}
depid, err := c.exportSymbol(repo, dep.Symbol, tok, visited)
if err != nil {
continue
}
pdep := uniast.NewDependency(*depid, c.fileLine(dep.Location))
switch dep.Symbol.Kind {
case SKFunction:
obj.FunctionCalls = uniast.InsertDependency(obj.FunctionCalls, pdep)
case SKMethod:
if obj.MethodCalls == nil {
obj.MethodCalls = make([]uniast.Dependency, 0, len(deps))
}
// NOTICE: use loc token as key here, to make it more readable
obj.MethodCalls = uniast.InsertDependency(obj.MethodCalls, pdep)
case SKVariable, SKConstant:
if obj.GlobalVars == nil {
obj.GlobalVars = make([]uniast.Dependency, 0, len(deps))
}
obj.GlobalVars = uniast.InsertDependency(obj.GlobalVars, pdep)
case SKStruct, SKTypeParameter, SKInterface, SKEnum, SKClass:
if obj.Types == nil {
obj.Types = make([]uniast.Dependency, 0, len(deps))
}
obj.Types = uniast.InsertDependency(obj.Types, pdep)
default:
log.Error("dep symbol %s not collected for %v\n", dep.Symbol, id)
}
}
}
obj.Identity = *id
pkg.Functions[id.Name] = obj
// Type
case SKStruct, SKTypeParameter, SKInterface, SKEnum, SKClass:
obj := &uniast.Type{
FileLine: fileLine,
Content: content,
TypeKind: mapKind(k),
Exported: public,
}
// collect deps
if deps := c.deps[symbol]; deps != nil {
for _, dep := range deps {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(dep.Location)
}
depid, err := c.exportSymbol(repo, dep.Symbol, tok, visited)
if err != nil {
continue
}
switch dep.Symbol.Kind {
case SKStruct, SKTypeParameter, SKInterface, SKEnum, SKClass:
obj.SubStruct = uniast.InsertDependency(obj.SubStruct, uniast.NewDependency(*depid, c.fileLine(dep.Location)))
case SKConstant, SKVariable:
default:
log.Error("dep symbol %s not collected for \n", dep.Symbol, id)
}
}
}
// collect methods
if rec := receivers[symbol]; rec != nil {
obj.Methods = make(map[string]uniast.Identity, len(rec))
for _, method := range rec {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(method.Location)
}
mid, err := c.exportSymbol(repo, method, tok, visited)
if err != nil {
continue
}
// NOTICE: use method name as key here
obj.Methods[method.Name] = *mid
}
}
obj.Identity = *id
pkg.Types[id.Name] = obj
// Vars
case SKConstant, SKVariable:
obj := &uniast.Var{
FileLine: fileLine,
Content: content,
IsExported: public,
IsConst: k == SKConstant,
}
if ty, ok := c.vars[symbol]; ok {
tok := ""
if c.cli != nil {
tok, _ = c.cli.Locate(ty.Location)
}
tyid, err := c.exportSymbol(repo, ty.Symbol, tok, visited)
if err == nil {
obj.Type = tyid
}
}
obj.Identity = *id
pkg.Vars[id.Name] = obj
default:
log.Error("symbol %s not collected\n", symbol)
}
return
}
func mapKind(kind SymbolKind) uniast.TypeKind {
switch kind {
case SKStruct:
return "struct"
// XXX: C++ should use class instead of struct
case SKClass:
return "struct"
case SKTypeParameter:
return "type-parameter"
case SKInterface:
return "interface"
case SKEnum:
return "enum"
default:
panic(fmt.Sprintf("unexpected kind %v", kind))
}
}