-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgo.go
More file actions
935 lines (859 loc) · 29.3 KB
/
Copy pathgo.go
File metadata and controls
935 lines (859 loc) · 29.3 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
package goextractor
import (
"context"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"unicode"
"github.com/enola-labs/enola/internal/facts"
)
// goBuiltins are Go's predeclared functions and type-conversion identifiers.
// Bare calls to these (e.g. len(x), make(...), string(b)) are not calls to a
// symbol, so resolving them would produce dangling phantom call edges.
var goBuiltins = map[string]bool{
// Builtin functions.
"append": true, "cap": true, "clear": true, "close": true, "complex": true,
"copy": true, "delete": true, "imag": true, "len": true, "make": true,
"max": true, "min": true, "new": true, "panic": true, "print": true,
"println": true, "real": true, "recover": true,
// Predeclared types used as conversions.
"string": true, "bool": true, "byte": true, "rune": true, "error": true,
"any": true, "int": true, "int8": true, "int16": true, "int32": true,
"int64": true, "uint": true, "uint8": true, "uint16": true, "uint32": true,
"uint64": true, "uintptr": true, "float32": true, "float64": true,
"complex64": true, "complex128": true,
}
// GoExtractor extracts architectural facts from Go source code using go/ast.
type GoExtractor struct{}
// New creates a new GoExtractor.
func New() *GoExtractor {
return &GoExtractor{}
}
func (e *GoExtractor) Name() string {
return "go"
}
// Detect returns true if the repository contains a go.mod file.
func (e *GoExtractor) Detect(repoPath string) (bool, error) {
_, err := os.Stat(filepath.Join(repoPath, "go.mod"))
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
// parsedPkg holds parsing results for a single Go package directory.
type parsedPkg struct {
pkgName string
relFiles []string
parsedFiles []*ast.File
fileMap map[string]*ast.File // relFile → *ast.File
}
// Extract parses Go files and emits architectural facts.
// It uses three global passes so that struct field types are visible across
// package boundaries within the same module — necessary for resolving
// multi-hop call chains like h.authLib.Service.Register.
func (e *GoExtractor) Extract(ctx context.Context, repoPath string, files []string) ([]facts.Fact, error) {
var allFacts []facts.Fact
fset := token.NewFileSet()
modulePath := readModulePath(repoPath)
// Pass 1: parse all Go files, grouping by package directory.
parsedPkgs := make(map[string]*parsedPkg)
for _, f := range files {
if !strings.HasSuffix(f, ".go") {
continue
}
pkgDir := filepath.Dir(f)
pp := parsedPkgs[pkgDir]
if pp == nil {
pp = &parsedPkg{fileMap: make(map[string]*ast.File)}
parsedPkgs[pkgDir] = pp
}
pp.relFiles = append(pp.relFiles, f)
absFile := filepath.Join(repoPath, f)
src, err := os.ReadFile(absFile)
if err != nil {
log.Printf("[go-extractor] error reading %s: %v", f, err)
continue
}
parsed, err := parser.ParseFile(fset, absFile, src, parser.ParseComments)
if err != nil {
log.Printf("[go-extractor] error parsing %s: %v", f, err)
continue
}
if pp.pkgName == "" {
pp.pkgName = parsed.Name.Name
}
pp.parsedFiles = append(pp.parsedFiles, parsed)
pp.fileMap[f] = parsed
}
// Build declared package-name map so buildFileImports can resolve implicit
// aliases correctly (e.g. "go-auth" path base → "auth" package name).
pkgNames := make(map[string]string)
for pkgDir, pp := range parsedPkgs {
if pp.pkgName != "" {
pkgNames[pkgDir] = pp.pkgName
}
}
// Pass 2: build a global field-type map from ALL packages in the module.
// This allows cross-package field-chain resolution (e.g., a subpackage can
// look up fields of a root-package struct).
globalFieldTypes := make(map[string]string)
for pkgDir, pp := range parsedPkgs {
select {
case <-ctx.Done():
return allFacts, ctx.Err()
default:
}
for k, v := range collectFieldTypes(pp.parsedFiles, pkgDir, modulePath, pkgNames) {
globalFieldTypes[k] = v
}
}
// Pass 2b: build the gRPC client stub index (generated concrete clients →
// method wire paths) so consumer call sites in any package resolve to the
// "/pkg.Service/Method" they invoke.
var allParsed []*ast.File
for _, pp := range parsedPkgs {
allParsed = append(allParsed, pp.parsedFiles...)
}
grpcStubs := buildGoGRPCStubIndex(allParsed)
// Pass 3: extract facts per package using the global field types.
for pkgDir, pp := range parsedPkgs {
select {
case <-ctx.Done():
return allFacts, ctx.Err()
default:
}
if pp.pkgName == "" {
continue
}
pkgFacts := e.extractPackage(fset, pkgDir, pp, modulePath, globalFieldTypes, pkgNames, grpcStubs)
allFacts = append(allFacts, pkgFacts...)
}
return allFacts, nil
}
func (e *GoExtractor) extractPackage(fset *token.FileSet, pkgDir string, pp *parsedPkg, modulePath string, fieldTypes map[string]string, pkgNames map[string]string, grpcStubs *goGRPCStubIndex) []facts.Fact {
var result []facts.Fact
// Package-scoped map of top-level `var x = NewXxxClient(...)` bindings, so a
// gRPC client held in a package var (declared in any file of the package)
// resolves at its call sites.
pkgVarClients := collectPackageVarClients(pp.parsedFiles, grpcStubs)
for _, relFile := range pp.relFiles {
f, ok := pp.fileMap[relFile]
if !ok {
continue
}
result = append(result, e.extractFile(fset, f, relFile, pkgDir, modulePath, fieldTypes, pkgNames, grpcStubs, pkgVarClients)...)
}
moduleFact := facts.Fact{
Kind: facts.KindModule,
Name: pkgDir,
File: pkgDir,
Props: map[string]any{
"package": pp.pkgName,
"language": "go",
},
}
// Store the full Go module path on the root package fact so that the graph
// layer can normalise cross-repo call targets (Bug 2).
if pkgDir == "." && modulePath != "" {
moduleFact.Props["modulePath"] = modulePath
}
result = append(result, moduleFact)
return result
}
func (e *GoExtractor) extractFile(fset *token.FileSet, f *ast.File, relFile, pkgDir, modulePath string, fieldTypes map[string]string, pkgNames map[string]string, grpcStubs *goGRPCStubIndex, pkgVarClients map[string]string) []facts.Fact {
var result []facts.Fact
// Build per-file import alias map for call resolution.
fileImports := buildFileImports(f, modulePath, pkgNames)
// Extract imports
for _, imp := range f.Imports {
importPath := strings.Trim(imp.Path.Value, `"`)
// Normalize internal import targets to short paths (e.g.
// "github.com/foo/bar/internal/pkg" → "internal/pkg") so they
// match the module fact names used elsewhere in the store.
relTarget := importPath
if modulePath != "" {
if importPath == modulePath {
relTarget = "."
} else if strings.HasPrefix(importPath, modulePath+"/") {
relTarget = strings.TrimPrefix(importPath, modulePath+"/")
}
}
result = append(result, facts.Fact{
Kind: facts.KindDependency,
Name: pkgDir + " -> " + importPath,
File: relFile,
Line: fset.Position(imp.Pos()).Line,
Props: map[string]any{
"language": "go",
"source": classifyImport(importPath, modulePath),
},
Relations: []facts.Relation{
{Kind: facts.RelImports, Target: relTarget},
},
})
}
// Walk declarations
for _, decl := range f.Decls {
switch d := decl.(type) {
case *ast.FuncDecl:
result = append(result, e.extractFunc(fset, d, relFile, pkgDir, modulePath, fileImports, fieldTypes)...)
case *ast.GenDecl:
result = append(result, e.extractGenDecl(fset, d, relFile, pkgDir)...)
}
}
// Extract route registrations
result = append(result, extractRoutes(fset, f, relFile, pkgDir)...)
// Extract outbound HTTP-client calls
result = append(result, extractHTTPClientFacts(fset, f, relFile, pkgDir)...)
// Extract outbound gRPC-client calls
result = append(result, extractGRPCClientFacts(fset, f, relFile, pkgDir, modulePath, fileImports, fieldTypes, pkgVarClients, grpcStubs)...)
// Extract storage patterns
result = append(result, extractStorage(fset, f, relFile, pkgDir)...)
return result
}
func (e *GoExtractor) extractFunc(fset *token.FileSet, fn *ast.FuncDecl, relFile, pkgDir, modulePath string, fileImports map[string]string, fieldTypes map[string]string) []facts.Fact {
var result []facts.Fact
name := fn.Name.Name
exported := fn.Name.IsExported()
kind := facts.SymbolFunc
var receiver string
var recvVar string
if fn.Recv != nil && len(fn.Recv.List) > 0 {
kind = facts.SymbolMethod
field := fn.Recv.List[0]
receiver = typeExprToString(field.Type)
name = receiver + "." + name
if len(field.Names) > 0 {
recvVar = field.Names[0].Name
}
}
qualifiedName := pkgDir + "." + name
symbolFact := facts.Fact{
Kind: facts.KindSymbol,
Name: qualifiedName,
File: relFile,
Line: fset.Position(fn.Pos()).Line,
Props: map[string]any{
"symbol_kind": kind,
"exported": exported,
"language": "go",
},
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: pkgDir},
},
}
if receiver != "" {
symbolFact.Props["receiver"] = receiver
}
// Extract function calls and per-function complexity metrics in a single
// body walk. The metrics ride on Props (map[string]any) and feed the
// enterprise performance analyzer; they are parser-derived, never inferred.
if fn.Body != nil {
ctx := resolveCtx{
pkgDir: pkgDir,
modulePath: modulePath,
imports: fileImports,
recvVar: recvVar,
recvType: receiver,
fieldTypes: fieldTypes,
}
ctx.localTypes = collectLocalTypes(fn.Body, ctx)
m := analyzeBody(fn.Body, ctx, qualifiedName)
for _, call := range m.calls {
symbolFact.Relations = append(symbolFact.Relations, facts.Relation{
Kind: facts.RelCalls,
Target: call,
})
}
// Only emit non-trivial metrics so existing snapshots and facts from
// other extractors (which don't compute these) stay clean.
symbolFact.Props["cyclomatic"] = m.cyclomatic
if m.loopDepth > 0 {
symbolFact.Props["loop_depth"] = m.loopDepth
// Emit the scaling depth (bounded loops discounted) alongside — even when 0 —
// so the consumer distinguishes "all loops bounded" from "signal absent".
symbolFact.Props["scaling_loop_depth"] = m.scalingLoopDepth
}
if m.loopCount > 0 {
symbolFact.Props["loop_count"] = m.loopCount
}
if len(m.callsInLoop) > 0 {
symbolFact.Props["calls_in_loop"] = m.callsInLoop
}
if len(m.callsInScalingLoop) > 0 {
symbolFact.Props["calls_in_scaling_loop"] = m.callsInScalingLoop
}
if m.recursiveSelf {
symbolFact.Props["recursive_self"] = true
}
}
result = append(result, symbolFact)
return result
}
func (e *GoExtractor) extractGenDecl(fset *token.FileSet, gd *ast.GenDecl, relFile, pkgDir string) []facts.Fact {
var result []facts.Fact
for _, spec := range gd.Specs {
switch s := spec.(type) {
case *ast.TypeSpec:
result = append(result, e.extractTypeSpec(fset, gd, s, relFile, pkgDir)...)
}
}
return result
}
func (e *GoExtractor) extractTypeSpec(fset *token.FileSet, gd *ast.GenDecl, ts *ast.TypeSpec, relFile, pkgDir string) []facts.Fact {
var result []facts.Fact
name := ts.Name.Name
exported := ts.Name.IsExported()
qualifiedName := pkgDir + "." + name
var kind string
var implements []string
switch t := ts.Type.(type) {
case *ast.StructType:
kind = facts.SymbolStruct
// Extract embedded types (potential interface implementations)
if t.Fields != nil {
for _, field := range t.Fields.List {
if len(field.Names) == 0 {
// Embedded type
embeddedName := typeExprToString(field.Type)
if embeddedName != "" {
implements = append(implements, embeddedName)
}
}
}
}
case *ast.InterfaceType:
kind = facts.SymbolInterface
default:
kind = facts.SymbolType
}
symbolFact := facts.Fact{
Kind: facts.KindSymbol,
Name: qualifiedName,
File: relFile,
Line: fset.Position(ts.Pos()).Line,
Props: map[string]any{
"symbol_kind": kind,
"exported": exported,
"language": "go",
},
Relations: []facts.Relation{
{Kind: facts.RelDeclares, Target: pkgDir},
},
}
for _, impl := range implements {
symbolFact.Relations = append(symbolFact.Relations, facts.Relation{
Kind: facts.RelImplements,
Target: impl,
})
}
result = append(result, symbolFact)
return result
}
// resolveCtx holds the context needed to resolve call targets within a function body.
type resolveCtx struct {
pkgDir string
modulePath string
imports map[string]string // alias → relative package path
recvVar string // receiver variable name, e.g. "h"
recvType string // receiver type (star stripped), e.g. "AuthHandler"
fieldTypes map[string]string // "pkgDir.TypeName.fieldName" → pre-qualified typeString
localTypes map[string]string // local variable name → qualified type, e.g. "svc" → "internal/auth.Service"
}
// bodyMetrics holds the call list and the per-function complexity signals
// derived from a single walk of a function body.
type bodyMetrics struct {
calls []string // resolved call targets, deduped, in source order
callsInLoop []string // subset of calls invoked at loop nesting depth >= 1
callsInScalingLoop []string // subset of calls invoked at scaling (unbounded) nesting depth >= 1
loopDepth int // max nesting depth of for/range loops
scalingLoopDepth int // max nesting counting only unbounded (input-scaling) loops
loopCount int // total number of for/range loops
cyclomatic int // McCabe complexity (1 + decision points)
recursiveSelf bool // body directly calls the enclosing function
}
// analyzeBody walks a function body once and extracts both the call edges
// (identical resolution to the previous extractCalls) and complexity metrics.
//
// Loop nesting depth is tracked without an explicit recursive walker by keeping
// a stack of the end positions of the loops currently enclosing the node being
// visited: ast.Inspect is pre-order, and the AST is properly nested, so a node
// is inside every loop on the stack whose body it lexically falls within. Calls
// inside func literals are attributed by lexical nesting; interface-dispatch
// targets remain unresolved exactly as before.
func analyzeBody(body ast.Node, ctx resolveCtx, selfName string) bodyMetrics {
var m bodyMetrics
decisions := 0
seen := make(map[string]bool)
inLoopSeen := make(map[string]bool)
inScalingSeen := make(map[string]bool)
var loopEnds []token.Pos // end positions of enclosing loops
// scalingEnds tracks only the enclosing loops that scale with input (bounded loops —
// `for {}` event loops and `range` over a composite literal — are excluded), so
// len(scalingEnds) is the current scaling nesting depth used for Big-O.
var scalingEnds []token.Pos
ast.Inspect(body, func(n ast.Node) bool {
if n == nil {
return false
}
// Pop loops whose extent we have now left.
for len(loopEnds) > 0 && n.Pos() >= loopEnds[len(loopEnds)-1] {
loopEnds = loopEnds[:len(loopEnds)-1]
}
for len(scalingEnds) > 0 && n.Pos() >= scalingEnds[len(scalingEnds)-1] {
scalingEnds = scalingEnds[:len(scalingEnds)-1]
}
switch x := n.(type) {
case *ast.ForStmt:
m.loopCount++
decisions++
loopEnds = append(loopEnds, x.End())
if len(loopEnds) > m.loopDepth {
m.loopDepth = len(loopEnds)
}
if !goForBounded(x) {
scalingEnds = append(scalingEnds, x.End())
if len(scalingEnds) > m.scalingLoopDepth {
m.scalingLoopDepth = len(scalingEnds)
}
}
case *ast.RangeStmt:
m.loopCount++
decisions++
loopEnds = append(loopEnds, x.End())
if len(loopEnds) > m.loopDepth {
m.loopDepth = len(loopEnds)
}
if !goRangeBounded(x) {
scalingEnds = append(scalingEnds, x.End())
if len(scalingEnds) > m.scalingLoopDepth {
m.scalingLoopDepth = len(scalingEnds)
}
}
case *ast.IfStmt:
decisions++
case *ast.CaseClause:
if len(x.List) > 0 { // ignore default
decisions++
}
case *ast.CommClause:
if x.Comm != nil { // ignore default in select
decisions++
}
case *ast.BinaryExpr:
if x.Op == token.LAND || x.Op == token.LOR {
decisions++
}
case *ast.CallExpr:
chain := flattenSelector(x.Fun)
if chain == nil {
return true
}
resolved := resolveChain(chain, ctx)
if resolved == "" {
return true
}
if !seen[resolved] {
seen[resolved] = true
m.calls = append(m.calls, resolved)
}
if len(loopEnds) > 0 && !inLoopSeen[resolved] {
inLoopSeen[resolved] = true
m.callsInLoop = append(m.callsInLoop, resolved)
}
// A call inside an input-scaling loop is an N+1 candidate; a call only ever in
// a bounded loop (`for {}` / range over a composite literal) is not.
if len(scalingEnds) > 0 && !inScalingSeen[resolved] {
inScalingSeen[resolved] = true
m.callsInScalingLoop = append(m.callsInScalingLoop, resolved)
}
if resolved == selfName {
m.recursiveSelf = true
}
}
return true
})
m.cyclomatic = 1 + decisions
return m
}
// goForBounded reports whether a for-statement runs a fixed number of times regardless
// of input: a bare `for { }` infinite loop is driven by break/return/events, not data
// size, so it does not add a factor of n to Big-O. (A `for i := 0; i < n; i++` with a
// data-derived bound is treated as unbounded — its static bound is not evident here.)
func goForBounded(x *ast.ForStmt) bool {
return x.Cond == nil && x.Init == nil && x.Post == nil
}
// goRangeBounded reports whether a range loop iterates a fixed-size composite literal
// (`for _, x := range []T{a, b, c}` / a map literal) — a constant count, not input-scaling.
func goRangeBounded(x *ast.RangeStmt) bool {
_, ok := x.X.(*ast.CompositeLit)
return ok
}
// flattenSelector converts a (potentially deep) selector chain to a left-to-right
// slice of name segments. Returns nil for non-identifier/non-selector expressions
// (e.g. function-result calls, type assertions, index expressions).
func flattenSelector(expr ast.Expr) []string {
switch e := expr.(type) {
case *ast.Ident:
return []string{e.Name}
case *ast.SelectorExpr:
prefix := flattenSelector(e.X)
if prefix == nil {
return nil
}
return append(prefix, e.Sel.Name)
}
return nil
}
// buildFileImports returns a map of import alias → relative package path for all
// imports in f. The relative path strips the module prefix to match fact naming.
// Exact-match self-imports (importPath == modulePath) map to "." (the root package).
// Blank ("_") and dot (".") imports are excluded.
// pkgNames maps pkgDir → declared package name (from parsing); it is used to
// resolve the implicit alias for packages whose path base is not a valid identifier
// (e.g. "github.com/x/go-auth" has base "go-auth" but package name "auth").
func buildFileImports(f *ast.File, modulePath string, pkgNames map[string]string) map[string]string {
m := make(map[string]string)
for _, imp := range f.Imports {
importPath := strings.Trim(imp.Path.Value, `"`)
if imp.Name != nil {
if imp.Name.Name == "_" || imp.Name.Name == "." {
continue
}
}
relTarget := importPath
if modulePath != "" {
if importPath == modulePath {
// Subpackage importing the module root — map to "." so that
// call targets resolve to root-package fact names.
relTarget = "."
} else if strings.HasPrefix(importPath, modulePath+"/") {
relTarget = strings.TrimPrefix(importPath, modulePath+"/")
}
}
alias := ""
if imp.Name != nil {
alias = imp.Name.Name
} else if pkgNames != nil {
// Use the declared package name as alias when available — this is
// correct when the last path segment isn't a valid identifier
// (e.g. "go-auth" → package name "auth").
if name, ok := pkgNames[relTarget]; ok {
alias = name
} else {
alias = filepath.Base(importPath)
}
} else {
alias = filepath.Base(importPath)
}
if alias != "" {
m[alias] = relTarget
}
}
return m
}
// collectFieldTypes pre-scans all struct declarations in the given parsed files
// and returns a map of "pkgDir.TypeName.fieldName" → pre-qualified typeString for
// named fields. Types are pre-qualified at collection time using each struct's
// source-package context so they remain correct when looked up from a different
// package (e.g. an adapters package looking up root-package struct fields).
func collectFieldTypes(files []*ast.File, pkgDir, modulePath string, pkgNames map[string]string) map[string]string {
m := make(map[string]string)
for _, f := range files {
fileImports := buildFileImports(f, modulePath, pkgNames)
ctx := resolveCtx{pkgDir: pkgDir, imports: fileImports}
for _, decl := range f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range gd.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
st, ok := ts.Type.(*ast.StructType)
if !ok || st.Fields == nil {
continue
}
typeName := ts.Name.Name
for _, field := range st.Fields.List {
typeStr := typeExprToString(field.Type)
if typeStr == "" {
continue
}
// Pre-qualify so cross-package lookups return the correct
// fact-name prefix rather than the local alias or bare type name.
qualifiedType := resolveTypeName(typeStr, ctx)
for _, fname := range field.Names {
key := pkgDir + "." + typeName + "." + fname.Name
m[key] = qualifiedType
}
}
}
}
}
return m
}
// resolveChain resolves a flattened call chain to a graph fact name.
//
// Resolution rules:
// - 1 element (bare call): same-package function → pkgDir.name
// - 2 elements [alias, func]: import alias → relPath.func; receiver var → pkgDir.ReceiverType.func; fallback → raw join
// - 3+ elements: resolve root to a qualified "pkg.Type", walk intermediate fields via fieldTypes, produce qualifiedType.method
//
// Falls back to the raw joined string when resolution is not possible, so no call is dropped.
//
// Known limitation: calls through an interface value (e.g. iface.Method()) cannot be
// statically bound to a concrete implementation without type-flow analysis, so the
// resolved target may name an interface method that has no backing symbol fact. Such
// edges surface as "unresolved" nodes during traversal rather than concrete callees.
func resolveChain(chain []string, ctx resolveCtx) string {
switch len(chain) {
case 0:
return ""
case 1:
// Builtins and predeclared type conversions (len, make, string(...), etc.)
// are not symbols — emitting them produces dangling phantom nodes.
if goBuiltins[chain[0]] {
return ""
}
return ctx.pkgDir + "." + chain[0]
case 2:
root, sel := chain[0], chain[1]
if importPath, ok := ctx.imports[root]; ok {
return importPath + "." + sel
}
if root == ctx.recvVar && ctx.recvType != "" {
return ctx.pkgDir + "." + ctx.recvType + "." + sel
}
if qualType, ok := ctx.localTypes[root]; ok && qualType != "" {
// root is a local variable of a known type; sel is a method on it.
return qualType + "." + sel
}
return root + "." + sel
default:
// 3+ elements: attempt field-chain resolution.
root := chain[0]
var qualType string // "pkgDir.TypeName" or "importedPkg.TypeName"
var fieldStart int // index of the first intermediate field in chain
if root == ctx.recvVar && ctx.recvType != "" {
qualType = ctx.pkgDir + "." + ctx.recvType
fieldStart = 1
} else if lt, ok := ctx.localTypes[root]; ok && lt != "" {
// root is a local variable; its type is already fully qualified.
qualType = lt
fieldStart = 1
} else if importPath, ok := ctx.imports[root]; ok {
// root is an import alias; chain[1] is a type in that package.
qualType = importPath + "." + chain[1]
fieldStart = 2
} else {
return strings.Join(chain, ".")
}
for _, fieldName := range chain[fieldStart : len(chain)-1] {
key := qualType + "." + fieldName
nextType, ok := ctx.fieldTypes[key]
if !ok {
return strings.Join(chain, ".")
}
qualType = resolveTypeName(nextType, ctx)
}
return qualType + "." + chain[len(chain)-1]
}
}
// collectLocalTypes scans a function body for local variable declarations whose
// type is statically knowable and returns a map of variable name → qualified type
// name (e.g. "svc" → "internal/auth.Service"). It recognises:
// - `var x T` / `var x *T` declarations
// - `x := &Foo{}` / `x := Foo{}` composite literals
// - `x := NewFoo(...)` / `x := pkg.NewFoo(...)` constructor conventions
//
// Variable names are recorded so that calls like `svc.Do()` resolve to the
// canonical method fact name instead of dangling on a raw join.
func collectLocalTypes(body ast.Node, ctx resolveCtx) map[string]string {
locals := make(map[string]string)
ast.Inspect(body, func(n ast.Node) bool {
switch stmt := n.(type) {
case *ast.DeclStmt:
gd, ok := stmt.Decl.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
return true
}
for _, spec := range gd.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
if vs.Type != nil {
if typeStr := typeExprToString(vs.Type); typeStr != "" {
qual := resolveTypeName(typeStr, ctx)
for _, name := range vs.Names {
if name.Name != "_" {
locals[name.Name] = qual
}
}
}
continue
}
// `var x = <rhs>` — infer from the initializer.
if len(vs.Names) == len(vs.Values) {
for i, name := range vs.Names {
if name.Name == "_" {
continue
}
if qual := inferRHSType(vs.Values[i], ctx); qual != "" {
locals[name.Name] = qual
}
}
}
}
case *ast.AssignStmt:
if stmt.Tok != token.DEFINE || len(stmt.Lhs) != len(stmt.Rhs) {
return true
}
for i, lhs := range stmt.Lhs {
ident, ok := lhs.(*ast.Ident)
if !ok || ident.Name == "_" {
continue
}
if qual := inferRHSType(stmt.Rhs[i], ctx); qual != "" {
locals[ident.Name] = qual
}
}
}
return true
})
return locals
}
// inferRHSType attempts to determine the qualified type of an expression used as
// the right-hand side of a variable assignment. Returns "" when the type is not
// statically knowable.
func inferRHSType(expr ast.Expr, ctx resolveCtx) string {
switch e := expr.(type) {
case *ast.UnaryExpr:
// &Foo{}
if cl, ok := e.X.(*ast.CompositeLit); ok {
return compositeLitType(cl, ctx)
}
case *ast.CompositeLit:
// Foo{} or pkg.Foo{}
return compositeLitType(e, ctx)
case *ast.CallExpr:
// NewFoo(...) / pkg.NewFoo(...)
return constructorReturnType(e.Fun, ctx)
}
return ""
}
// compositeLitType returns the qualified type name of a composite literal, or ""
// when the literal has no named type (e.g. slice/map literals).
func compositeLitType(cl *ast.CompositeLit, ctx resolveCtx) string {
if cl.Type == nil {
return ""
}
typeStr := typeExprToString(cl.Type)
if typeStr == "" {
return ""
}
return resolveTypeName(typeStr, ctx)
}
// constructorReturnType infers the qualified return type of a call following the
// `New<Type>` convention (e.g. `NewService()` → "pkgDir.Service",
// `auth.NewClient()` → "internal/auth.Client"). Returns "" otherwise.
func constructorReturnType(fun ast.Expr, ctx resolveCtx) string {
switch f := fun.(type) {
case *ast.Ident:
if t := newConventionType(f.Name); t != "" {
return ctx.pkgDir + "." + t
}
case *ast.SelectorExpr:
if x, ok := f.X.(*ast.Ident); ok {
if t := newConventionType(f.Sel.Name); t != "" {
if importPath, ok := ctx.imports[x.Name]; ok {
return importPath + "." + t
}
}
}
}
return ""
}
// newConventionType returns the type name implied by a constructor following the
// `New<Type>` convention (e.g. "NewService" → "Service"), or "" if the name does
// not follow it (e.g. "New", "Newton").
func newConventionType(name string) string {
rest := strings.TrimPrefix(name, "New")
if rest == name || rest == "" {
return ""
}
if !unicode.IsUpper([]rune(rest)[0]) {
return ""
}
return rest
}
// resolveTypeName converts a raw type string (e.g. "pkg.Type" or "LocalType")
// to a fully qualified "relPath.Type" form using the import alias map.
// Pre-qualified types (e.g. "..AuthService" stored by collectFieldTypes) are
// passed through unchanged when their alias part is not in the import map.
func resolveTypeName(typeStr string, ctx resolveCtx) string {
if !strings.Contains(typeStr, ".") {
return ctx.pkgDir + "." + typeStr
}
parts := strings.SplitN(typeStr, ".", 2)
if resolvedPkg, ok := ctx.imports[parts[0]]; ok {
return resolvedPkg + "." + parts[1]
}
return typeStr
}
// readModulePath reads the module path from go.mod in the given repo.
func readModulePath(repoPath string) string {
data, err := os.ReadFile(filepath.Join(repoPath, "go.mod"))
if err != nil {
return ""
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "module ") {
return strings.TrimSpace(strings.TrimPrefix(line, "module "))
}
}
return ""
}
// classifyImport returns "stdlib", "internal", or "external" for a Go import path.
func classifyImport(importPath, modulePath string) string {
// stdlib: first path segment has no dots
firstSegment := importPath
if i := strings.Index(importPath, "/"); i >= 0 {
firstSegment = importPath[:i]
}
if !strings.Contains(firstSegment, ".") {
return "stdlib"
}
// internal: starts with the module path
if modulePath != "" && (importPath == modulePath || strings.HasPrefix(importPath, modulePath+"/")) {
return "internal"
}
return "external"
}
// typeExprToString converts a type expression to a string representation.
func typeExprToString(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
return t.Name
case *ast.StarExpr:
return typeExprToString(t.X)
case *ast.SelectorExpr:
if x, ok := t.X.(*ast.Ident); ok {
return x.Name + "." + t.Sel.Name
}
case *ast.IndexExpr:
return typeExprToString(t.X)
}
return ""
}