|
| 1 | +package goextractor |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "go/ast" |
| 6 | + "go/parser" |
| 7 | + "go/token" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + "path/filepath" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/enola-labs/enola/internal/facts" |
| 14 | + "github.com/enola-labs/enola/internal/parallel" |
| 15 | +) |
| 16 | + |
| 17 | +// isGoTestFile reports whether a repo-relative path is a Go test file. The Go |
| 18 | +// toolchain defines the suffix, so this needs no directory scoping — a production |
| 19 | +// file cannot legally be named *_test.go and still compile into the package. |
| 20 | +func isGoTestFile(relFile string) bool { return strings.HasSuffix(relFile, "_test.go") } |
| 21 | + |
| 22 | +// ExtractTestRefs implements plugin.TestRefExtractor. It parses *_test.go files for |
| 23 | +// the SOLE purpose of capturing their outbound references into production code, |
| 24 | +// emitting one facts.KindTestRef fact per file that carries only RelCalls edges — |
| 25 | +// no symbols. Test functions therefore never become dead-code candidates, and no |
| 26 | +// symbol/module/route explainer is affected, while the dead-code detector can see |
| 27 | +// that a production function is exercised by a test and not mis-report it as dead. |
| 28 | +// |
| 29 | +// The engine hands every TestGlob match to every TestRefExtractor whose repo it |
| 30 | +// detected, scoped by plugin.FileOwner when the extractor implements it. |
| 31 | +// GoExtractor deliberately does not: FileOwner is what opts an extractor into the |
| 32 | +// incremental cache (see its doc comment), and implementing it here would both |
| 33 | +// enable Go caching and pull .go files out of computeExtractorKeys' shared |
| 34 | +// partition, changing the shared hash that keys EVERY other extractor. So the |
| 35 | +// filter lives here instead — Ruby's ExtractTestRefs filters internally too. |
| 36 | +func (e *GoExtractor) ExtractTestRefs(ctx context.Context, repoPath string, files []string) ([]facts.Fact, error) { |
| 37 | + var goFiles []string |
| 38 | + for _, relFile := range files { |
| 39 | + if isGoTestFile(relFile) { |
| 40 | + goFiles = append(goFiles, relFile) |
| 41 | + } |
| 42 | + } |
| 43 | + if len(goFiles) == 0 { |
| 44 | + return nil, nil |
| 45 | + } |
| 46 | + |
| 47 | + modulePath := readModulePath(repoPath) |
| 48 | + perFile := parallel.MapFiles(ctx, goFiles, func(relFile string) []facts.Fact { |
| 49 | + src, err := os.ReadFile(filepath.Join(repoPath, relFile)) |
| 50 | + if err != nil { |
| 51 | + log.Printf("[go-extractor] error reading test file %s: %v", relFile, err) |
| 52 | + return nil |
| 53 | + } |
| 54 | + return refsFromGoTest(src, relFile, modulePath) |
| 55 | + }) |
| 56 | + |
| 57 | + var out []facts.Fact |
| 58 | + for _, ff := range perFile { |
| 59 | + out = append(out, ff...) |
| 60 | + } |
| 61 | + return out, nil |
| 62 | +} |
| 63 | + |
| 64 | +// refsFromGoTest parses one Go test file and returns a single reference-only fact |
| 65 | +// carrying the production symbols it calls, or nil when it references nothing. |
| 66 | +// |
| 67 | +// Call targets are resolved with the PRODUCTION resolvers (flattenSelector, |
| 68 | +// collectLocalTypes, resolveChain), so a reference from a test is spelled exactly |
| 69 | +// as the same reference from production code would be, and the dead-code detector |
| 70 | +// needs no special case. That also inherits goBuiltins filtering, so len/make/min |
| 71 | +// never become phantom targets. |
| 72 | +// |
| 73 | +// Only call expressions yield targets — matching analyzeBody, which likewise |
| 74 | +// ignores composite literals. A type constructed only as `Foo{}` from a test is |
| 75 | +// therefore still reported dead, but so is one constructed only that way from |
| 76 | +// production code: that blind spot is pre-existing and not specific to tests. |
| 77 | +func refsFromGoTest(src []byte, relFile, modulePath string) []facts.Fact { |
| 78 | + fset := token.NewFileSet() |
| 79 | + f, err := parser.ParseFile(fset, relFile, src, parser.SkipObjectResolution) |
| 80 | + if err != nil { |
| 81 | + log.Printf("[go-extractor] error parsing test file %s: %v", relFile, err) |
| 82 | + return nil |
| 83 | + } |
| 84 | + |
| 85 | + base := resolveCtx{ |
| 86 | + pkgDir: filepath.Dir(relFile), |
| 87 | + modulePath: modulePath, |
| 88 | + // pkgNames is deliberately nil. It exists to recover a declared package name |
| 89 | + // that differs from its directory base ("go-auth" → package auth), which |
| 90 | + // needs a view of every parsed package — and this pass sees only test files. |
| 91 | + // Worse, a test file's own package name carries a _test suffix |
| 92 | + // (`package svc_test`), so feeding these in would alias the import under |
| 93 | + // test as "svc_test" and break the very idiom this exists to resolve. |
| 94 | + // buildFileImports then falls back to the import path's base, exactly as the |
| 95 | + // production pass does for any package it did not parse. |
| 96 | + imports: buildFileImports(f, modulePath, nil), |
| 97 | + } |
| 98 | + |
| 99 | + seen := make(map[string]bool) |
| 100 | + var rels []facts.Relation |
| 101 | + add := func(target string) { |
| 102 | + if target == "" || seen[target] { |
| 103 | + return |
| 104 | + } |
| 105 | + seen[target] = true |
| 106 | + rels = append(rels, facts.Relation{Kind: facts.RelCalls, Target: target}) |
| 107 | + } |
| 108 | + collectCalls := func(n ast.Node, ctx resolveCtx) { |
| 109 | + ast.Inspect(n, func(node ast.Node) bool { |
| 110 | + if call, ok := node.(*ast.CallExpr); ok { |
| 111 | + if chain := flattenSelector(call.Fun); chain != nil { |
| 112 | + add(resolveChain(chain, ctx)) |
| 113 | + } |
| 114 | + } |
| 115 | + return true |
| 116 | + }) |
| 117 | + } |
| 118 | + |
| 119 | + for _, decl := range f.Decls { |
| 120 | + switch d := decl.(type) { |
| 121 | + case *ast.FuncDecl: |
| 122 | + if d.Body == nil { |
| 123 | + continue |
| 124 | + } |
| 125 | + ctx := base |
| 126 | + if d.Recv != nil && len(d.Recv.List) > 0 { |
| 127 | + field := d.Recv.List[0] |
| 128 | + ctx.recvType = typeExprToString(field.Type) |
| 129 | + if len(field.Names) > 0 { |
| 130 | + ctx.recvVar = field.Names[0].Name |
| 131 | + } |
| 132 | + } |
| 133 | + ctx.localTypes = collectLocalTypes(d.Body, ctx) |
| 134 | + collectCalls(d.Body, ctx) |
| 135 | + case *ast.GenDecl: |
| 136 | + // File-scope initializers (`var _ = Register(handler)`) reference |
| 137 | + // production code with no enclosing function to attribute them to. |
| 138 | + for _, spec := range d.Specs { |
| 139 | + vs, ok := spec.(*ast.ValueSpec) |
| 140 | + if !ok { |
| 141 | + continue |
| 142 | + } |
| 143 | + for _, v := range vs.Values { |
| 144 | + collectCalls(v, base) |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + if len(rels) == 0 { |
| 151 | + return nil |
| 152 | + } |
| 153 | + return []facts.Fact{{ |
| 154 | + Kind: facts.KindTestRef, |
| 155 | + Name: relFile, |
| 156 | + File: relFile, |
| 157 | + Props: map[string]any{"language": "go"}, |
| 158 | + Relations: rels, |
| 159 | + }} |
| 160 | +} |
0 commit comments