devlensio 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/extractors/runner.js +1 -0
  2. package/dist/extractors/types.d.ts +2 -1
  3. package/dist/graph/buildLookup.d.ts +30 -0
  4. package/dist/graph/buildLookup.js +36 -1
  5. package/dist/graph/edges/aliasChain.d.ts +7 -0
  6. package/dist/graph/edges/aliasChain.js +63 -0
  7. package/dist/graph/edges/aliasResolution.test.d.ts +1 -0
  8. package/dist/graph/edges/aliasResolution.test.js +351 -0
  9. package/dist/graph/edges/callEdges.js +101 -15
  10. package/dist/graph/edges/callEdges.test.js +119 -0
  11. package/dist/graph/edges/importEdges.js +124 -0
  12. package/dist/parser/declarationIds.d.ts +23 -0
  13. package/dist/parser/declarationIds.js +123 -0
  14. package/dist/parser/exportsMap.d.ts +9 -0
  15. package/dist/parser/exportsMap.js +260 -0
  16. package/dist/parser/exportsMap.test.d.ts +1 -0
  17. package/dist/parser/exportsMap.test.js +324 -0
  18. package/dist/parser/extractors/functions.d.ts +11 -0
  19. package/dist/parser/extractors/functions.js +69 -59
  20. package/dist/parser/extractors/moduleScope.d.ts +8 -0
  21. package/dist/parser/extractors/moduleScope.js +80 -0
  22. package/dist/parser/index.d.ts +2 -1
  23. package/dist/parser/index.js +45 -0
  24. package/dist/parser/moduleScope.test.d.ts +1 -0
  25. package/dist/parser/moduleScope.test.js +174 -0
  26. package/dist/pipeline/index.d.ts +2 -1
  27. package/dist/pipeline/index.js +1 -0
  28. package/dist/storage/fileStorage.d.ts +2 -1
  29. package/dist/storage/fileStorage.js +5 -1
  30. package/dist/storage/fileStorage.test.d.ts +1 -0
  31. package/dist/storage/fileStorage.test.js +112 -0
  32. package/dist/types.d.ts +4 -0
  33. package/extractors/go/bin/darwin-amd64/devlens_go_extractor +0 -0
  34. package/extractors/go/bin/darwin-arm64/devlens_go_extractor +0 -0
  35. package/extractors/go/bin/linux-amd64/devlens_go_extractor +0 -0
  36. package/extractors/go/bin/linux-arm64/devlens_go_extractor +0 -0
  37. package/extractors/go/bin/windows-amd64/devlens_go_extractor.exe +0 -0
  38. package/extractors/go/calls.go +45 -3
  39. package/extractors/go/parser.go +81 -36
  40. package/extractors/java/devlens_java_extractor.jar +0 -0
  41. package/extractors/java/src/devlens/extractor/Extractor.java +16 -2
  42. package/extractors/java/src/devlens/extractor/LookupMaps.java +2 -0
  43. package/extractors/java/src/devlens/extractor/Parser.java +33 -1
  44. package/extractors/java/src/devlens/extractor/edges/Calls.java +44 -0
  45. package/extractors/python/devlens_extractors_python/edges/calls.py +173 -33
  46. package/extractors/python/devlens_extractors_python/edges/imports.py +21 -1
  47. package/extractors/python/devlens_extractors_python/lookup.py +9 -0
  48. package/extractors/python/devlens_extractors_python/parser/__init__.py +10 -1
  49. package/extractors/rust/bin/darwin-amd64/devlens_rust_extractor +0 -0
  50. package/extractors/rust/bin/darwin-arm64/devlens_rust_extractor +0 -0
  51. package/extractors/rust/bin/linux-amd64/devlens_rust_extractor +0 -0
  52. package/extractors/rust/bin/linux-arm64/devlens_rust_extractor +0 -0
  53. package/extractors/rust/bin/windows-amd64/devlens_rust_extractor.exe +0 -0
  54. package/extractors/rust/src/calls.rs +32 -0
  55. package/extractors/rust/src/lookup.rs +66 -0
  56. package/package.json +1 -1
@@ -0,0 +1,112 @@
1
+ // Storage round-trip + back-compat tests for the exports map.
2
+ //
3
+ // STORAGE_DIR is computed from os.homedir() at module load, so these tests
4
+ // point it at a temp dir via DEVLENS_STORAGE_DIR and import the module
5
+ // dynamically AFTER setting the env var — nothing here ever touches the
6
+ // real ~/.devlens.
7
+ import { describe, expect, test } from "bun:test";
8
+ import fs from "fs";
9
+ import os from "os";
10
+ import path from "path";
11
+ const FAKE_STORAGE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "devlens-storage-test-"));
12
+ process.env.DEVLENS_STORAGE_DIR = FAKE_STORAGE_ROOT;
13
+ const { saveGraph, getGraph, deleteGraph } = await import("./fileStorage.js");
14
+ function makeNode(id, name) {
15
+ return {
16
+ id,
17
+ name,
18
+ type: "FUNCTION",
19
+ filePath: `src/${name}.ts`,
20
+ startLine: 1,
21
+ endLine: 2,
22
+ parentFile: `file::src/${name}.ts`,
23
+ metadata: {},
24
+ };
25
+ }
26
+ function makeResult(overrides) {
27
+ const nodes = [makeNode("src/alpha.ts::alpha", "alpha"), makeNode("src/alpha.ts::alpha#2", "alpha")];
28
+ const edges = [];
29
+ return {
30
+ repoPath: FAKE_STORAGE_ROOT,
31
+ analyzedAt: "2026-10-07T00:00:00.000Z",
32
+ fingerprint: { language: "typescript" },
33
+ routes: [],
34
+ nodes,
35
+ edges,
36
+ allNodes: nodes,
37
+ allEdges: edges,
38
+ nodeScores: {},
39
+ stats: {
40
+ totalNodesBeforeFilter: nodes.length,
41
+ totalEdgesBeforeFilter: 0,
42
+ totalNodesAfterFilter: nodes.length,
43
+ totalEdgesAfterFilter: 0,
44
+ removedNodeCount: 0,
45
+ removedEdgeCount: 0,
46
+ averageNodeScore: 0,
47
+ topScoringNodes: [],
48
+ topScoringFiles: [],
49
+ },
50
+ isGithubRepo: false,
51
+ gitInfo: { commitHash: "abc12345", branch: "main", message: "test", hasGit: true },
52
+ ...overrides,
53
+ };
54
+ }
55
+ const MAP = {
56
+ exports: {
57
+ ".": {
58
+ alpha: ["src/alpha.ts::alpha", "src/alpha.ts::alpha#2"],
59
+ beta: ["src/beta.ts::beta"],
60
+ },
61
+ "./server": { serve: ["src/server.ts::serve"] },
62
+ },
63
+ ambiguousNames: {},
64
+ };
65
+ describe("exports map persistence (saveGraph -> getGraph)", () => {
66
+ test("round trip: map survives byte-for-byte, including multi-id groups and order", () => {
67
+ const result = makeResult({ graphId: "rt-test-graph", exports: MAP });
68
+ saveGraph(result, { force: true });
69
+ const loaded = getGraph("rt-test-graph", "abc12345");
70
+ expect(loaded).toBeDefined();
71
+ expect(loaded.exports).toBeDefined();
72
+ // deep identity: shape, keys, values, AND array order within groups
73
+ expect(loaded.exports).toEqual(MAP);
74
+ expect(loaded.exports.exports["."].alpha).toEqual(["src/alpha.ts::alpha", "src/alpha.ts::alpha#2"]);
75
+ expect(loaded.exports.ambiguousNames).toEqual({});
76
+ deleteGraph("rt-test-graph");
77
+ });
78
+ test("legacy artifact without the exports field: loads, yields undefined, no fabricated empty map", () => {
79
+ const result = makeResult({ graphId: "legacy-test-graph" });
80
+ delete result.exports;
81
+ saveGraph(result, { force: true });
82
+ const commitFile = path.join(FAKE_STORAGE_ROOT, "graphs", "legacy-test-graph", "commits", "abc12345.json");
83
+ const onDisk = JSON.parse(fs.readFileSync(commitFile, "utf-8"));
84
+ expect("exports" in onDisk).toBe(false);
85
+ const loaded = getGraph("legacy-test-graph", "abc12345");
86
+ expect(loaded).toBeDefined();
87
+ expect(loaded.exports).toBeUndefined();
88
+ deleteGraph("legacy-test-graph");
89
+ });
90
+ test("degraded input: exports present but EMPTY subpaths load without crash", () => {
91
+ const emptyMap = { exports: { ".": {} }, ambiguousNames: {} };
92
+ const result = makeResult({ graphId: "empty-map-graph", exports: emptyMap });
93
+ saveGraph(result, { force: true });
94
+ const loaded = getGraph("empty-map-graph", "abc12345");
95
+ expect(loaded).toBeDefined();
96
+ expect(loaded.exports).toEqual(emptyMap);
97
+ deleteGraph("empty-map-graph");
98
+ });
99
+ test("degraded input: exports referencing node ids ABSENT from the nodes array load without crash", () => {
100
+ const danglingMap = {
101
+ exports: { ".": { ghost: ["src/gone.ts::gone"] } },
102
+ ambiguousNames: {},
103
+ };
104
+ const result = makeResult({ graphId: "dangling-map-graph", exports: danglingMap });
105
+ saveGraph(result, { force: true });
106
+ const loaded = getGraph("dangling-map-graph", "abc12345");
107
+ expect(loaded).toBeDefined();
108
+ expect(loaded.exports).toEqual(danglingMap);
109
+ expect(loaded.exports.exports["."].ghost).toEqual(["src/gone.ts::gone"]);
110
+ deleteGraph("dangling-map-graph");
111
+ });
112
+ });
package/dist/types.d.ts CHANGED
@@ -83,3 +83,7 @@ export interface CodeEdge {
83
83
  type: EdgeType;
84
84
  metadata?: Record<string, unknown>;
85
85
  }
86
+ export interface GraphExports {
87
+ exports: Record<string, Record<string, string[]>>;
88
+ ambiguousNames: Record<string, string[]>;
89
+ }
@@ -60,6 +60,41 @@ func detectCalls(pr *parsedRepo, ti *TypeInfo, l *LookupMaps, opts *Options) []m
60
60
  }
61
61
  }
62
62
  }
63
+ // ── Module scope: package-level VAR initializers ──
64
+ // These run at init time and belong to the FILE node. Resolution uses the
65
+ // exact same ladder + registry (l.tp) as function callers, so the
66
+ // third-party gate applies identically.
67
+ for _, pf := range pr.files {
68
+ if pf.IsTest || len(pf.FileCalls) == 0 {
69
+ continue
70
+ }
71
+ callerID := "file::" + pf.RelPath
72
+ info := ti.Infos[pf.RelPath]
73
+ callStrings := make([]string, 0, len(pf.FileCalls))
74
+ var details []resolvedCall
75
+
76
+ for _, c := range pf.FileCalls {
77
+ callStrings = append(callStrings, c.Str)
78
+ target, method, class, e := resolveCallFor(c, pf.PkgPath, callerID, nil, pf, info, l)
79
+ if e != nil {
80
+ e["metadata"].(map[string]any)["scope"] = "module"
81
+ edges = append(edges, e)
82
+ }
83
+ if target != "" {
84
+ details = append(details, resolvedCall{Target: target, Method: method, Class: class})
85
+ }
86
+ }
87
+
88
+ if n, ok := l.NodeByID[callerID]; ok {
89
+ m := n["metadata"].(map[string]any)
90
+ m["calls"] = sortedUnique(callStrings)
91
+ m["callSites"] = callSitesMeta(pf.FileCalls)
92
+ if len(details) > 0 {
93
+ m["resolvedCalls"] = details
94
+ }
95
+ }
96
+ }
97
+
63
98
  return edges
64
99
  }
65
100
 
@@ -73,11 +108,18 @@ func nodeIDForFunc(rel string, fn *ParsedFunc) string {
73
108
 
74
109
  // resolveCall → (target node id, method, class, edge) — edge nil when
75
110
  // unresolvable (documented: builtins/locals/dynamic stay metadata-only).
111
+ // resolveCall — function/method caller wrapper. Keeps the ParsedFunc-based
112
+ // call sites untouched while the shared ladder works on a caller identity.
76
113
  func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
77
114
  l *LookupMaps) (string, string, string, map[string]any) {
115
+ return resolveCallFor(c, fn.PkgPath, nodeIDForFunc(pf.RelPath, fn), fn, pf, info, l)
116
+ }
78
117
 
79
- pkgPath := fn.PkgPath
80
- callerID := nodeIDForFunc(pf.RelPath, fn)
118
+ // resolveCallFor — the resolution ladder for any caller identity (FUNCTION,
119
+ // METHOD, or FILE for module-scope VAR initializers).
120
+ func resolveCallFor(c CallSite, pkgPath, callerID string, fn *ParsedFunc,
121
+ pf *ParsedFile, info *types.Info,
122
+ l *LookupMaps) (string, string, string, map[string]any) {
81
123
 
82
124
  // ── 1. type-info resolution (exact) ──
83
125
  if info != nil {
@@ -117,7 +159,7 @@ func resolveCall(c CallSite, fn *ParsedFunc, pf *ParsedFile, info *types.Info,
117
159
  // ── 1.5 receiver-type-from-declaration (params / typed vars) ──
118
160
  // Handlers receive framework types by signature: func(c *gin.Context) —
119
161
  // the checker can't resolve external types, but the DECLARED type can.
120
- if c.IsSel {
162
+ if c.IsSel && fn != nil {
121
163
  if impPath, typeName, local := receiverDeclaredType(c, fn, pf, l); typeName != "" {
122
164
  if local {
123
165
  if id, ok := l.MethodNodeByPkgTypeName[impPath+"::"+typeName+"."+c.Sel]; ok {
@@ -81,15 +81,19 @@ type ImportSpec struct {
81
81
  }
82
82
 
83
83
  type ParsedFile struct {
84
- RelPath string
85
- PkgName string
86
- IsTest bool
84
+ RelPath string
85
+ PkgName string
86
+ PkgPath string // import path of the containing package (module + dir)
87
+ IsTest bool
87
88
  Imports []ImportSpec
88
89
  Funcs []*ParsedFunc
89
90
  Structs []*ParsedStruct
90
91
  Interfaces []*ParsedInterface
91
- EndLine int
92
- AST *ast.File // kept for go/types check (typeload.go)
92
+ // FileCalls — calls in package-level VAR initializers (run at init time,
93
+ // owned by the FILE node). Function bodies stay on ParsedFunc.Calls.
94
+ FileCalls []CallSite
95
+ EndLine int
96
+ AST *ast.File // kept for go/types check (typeload.go)
93
97
  // iota const blocks on named numeric types (enum pattern, stretch)
94
98
  numericEnums []numericEnum
95
99
  }
@@ -175,6 +179,7 @@ func parseFile(repoPath, rel string, pkg *ParsedPackage, addError errFn) *Parsed
175
179
  pf := &ParsedFile{
176
180
  RelPath: rel,
177
181
  PkgName: f.Name.Name,
182
+ PkgPath: pkg.ImportPath,
178
183
  IsTest: strings.HasSuffix(rel, "_test.go"),
179
184
  AST: f,
180
185
  }
@@ -258,6 +263,19 @@ func parseFile(repoPath, rel string, pkg *ParsedPackage, addError errFn) *Parsed
258
263
  }
259
264
  }
260
265
  }
266
+ case token.VAR:
267
+ // Package-level initializers execute at init time — attribute
268
+ // their calls to the FILE node (function bodies stay on the
269
+ // ParsedFunc). const blocks are compile-time, no calls.
270
+ for _, spec := range d.Specs {
271
+ vs, ok := spec.(*ast.ValueSpec)
272
+ if !ok {
273
+ continue
274
+ }
275
+ for _, val := range vs.Values {
276
+ pf.FileCalls = append(pf.FileCalls, collectModuleCalls(val)...)
277
+ }
278
+ }
261
279
  case token.CONST:
262
280
  // Go const blocks inherit type + value from the previous spec
263
281
  // (`Red Color = iota; Green; Blue`). Two passes: resolve names
@@ -364,49 +382,76 @@ func receiverTypeName(e ast.Expr) string {
364
382
 
365
383
  // collectCalls — all CallExprs in a body (scope rule: closures inside the
366
384
  // body attribute to the enclosing function — Go has no nested func decls).
367
- // Each call also records its argument shape (count, cheap type tags, spread)
368
- // for arity-aware CALLS resolution.
369
385
  func collectCalls(body ast.Node) []CallSite {
370
386
  var calls []CallSite
371
387
  ast.Inspect(body, func(n ast.Node) bool {
372
- call, ok := n.(*ast.CallExpr)
373
- if !ok {
374
- return true
388
+ if call, ok := n.(*ast.CallExpr); ok {
389
+ if site := callSiteFrom(call); site != nil {
390
+ calls = append(calls, *site)
391
+ }
375
392
  }
376
- argCount := len(call.Args)
377
- hasSpread := call.Ellipsis != token.NoPos
378
- argTypes := make([]string, 0, argCount)
379
- for _, arg := range call.Args {
380
- argTypes = append(argTypes, argTypeTag(arg))
393
+ return true
394
+ })
395
+ return calls
396
+ }
397
+
398
+ // collectModuleCalls — calls in a package-level VAR initializer. Closures are
399
+ // NOT module scope: `var h = func() { svc.Get() }` runs svc.Get when h is
400
+ // invoked, so the walk does not descend into FuncLit.
401
+ func collectModuleCalls(root ast.Node) []CallSite {
402
+ var calls []CallSite
403
+ ast.Inspect(root, func(n ast.Node) bool {
404
+ if n == nil {
405
+ return false
381
406
  }
382
- fun := call.Fun
383
- // unwrap generic calls: f[T](...)
384
- if idx, ok := fun.(*ast.IndexExpr); ok {
385
- fun = idx.X
386
- } else if idx, ok := fun.(*ast.IndexListExpr); ok {
387
- fun = idx.X
407
+ if _, isFunc := n.(*ast.FuncLit); isFunc {
408
+ return false
388
409
  }
389
- switch f := fun.(type) {
390
- case *ast.Ident:
391
- calls = append(calls, CallSite{Str: f.Name, Node: f, Pos: call.Pos(), ArgCount: argCount, ArgTypes: argTypes, HasSpread: hasSpread})
392
- case *ast.SelectorExpr:
393
- calls = append(calls, CallSite{
394
- Str: exprText(f),
395
- Sel: f.Sel.Name,
396
- Receiver: identName(f.X), // root ident survives call chains: DB.Model(...).Updates → "DB"
397
- IsSel: true,
398
- Node: f,
399
- Pos: call.Pos(),
400
- ArgCount: argCount, ArgTypes: argTypes, HasSpread: hasSpread,
401
- })
402
- case *ast.FuncLit:
403
- // inline anonymous invocation — no symbol to resolve
410
+ if call, ok := n.(*ast.CallExpr); ok {
411
+ if site := callSiteFrom(call); site != nil {
412
+ calls = append(calls, *site)
413
+ }
404
414
  }
405
415
  return true
406
416
  })
407
417
  return calls
408
418
  }
409
419
 
420
+ // callSiteFrom — one CallExpr → CallSite (nil for inline func-literal
421
+ // invocation, which has no symbol to resolve). Each call records its argument
422
+ // shape (count, cheap type tags, spread) for arity-aware CALLS resolution.
423
+ func callSiteFrom(call *ast.CallExpr) *CallSite {
424
+ argCount := len(call.Args)
425
+ hasSpread := call.Ellipsis != token.NoPos
426
+ argTypes := make([]string, 0, argCount)
427
+ for _, arg := range call.Args {
428
+ argTypes = append(argTypes, argTypeTag(arg))
429
+ }
430
+ fun := call.Fun
431
+ // unwrap generic calls: f[T](...)
432
+ if idx, ok := fun.(*ast.IndexExpr); ok {
433
+ fun = idx.X
434
+ } else if idx, ok := fun.(*ast.IndexListExpr); ok {
435
+ fun = idx.X
436
+ }
437
+ switch f := fun.(type) {
438
+ case *ast.Ident:
439
+ return &CallSite{Str: f.Name, Node: f, Pos: call.Pos(), ArgCount: argCount, ArgTypes: argTypes, HasSpread: hasSpread}
440
+ case *ast.SelectorExpr:
441
+ return &CallSite{
442
+ Str: exprText(f),
443
+ Sel: f.Sel.Name,
444
+ Receiver: identName(f.X), // root ident survives call chains: DB.Model(...).Updates → "DB"
445
+ IsSel: true,
446
+ Node: f,
447
+ Pos: call.Pos(),
448
+ ArgCount: argCount, ArgTypes: argTypes, HasSpread: hasSpread,
449
+ }
450
+ }
451
+ // inline anonymous invocation — no symbol to resolve
452
+ return nil
453
+ }
454
+
410
455
  // argTypeTag — cheap per-argument type tag in Go's own vocabulary: literals
411
456
  // and composite literals carry their type, everything else (idents, calls,
412
457
  // expressions) degrades to "unknown". No go/types dependency at parse time.
@@ -97,9 +97,18 @@ public final class Extractor {
97
97
 
98
98
  // ── 2. build nodes + call facts ─────────────────────────────────
99
99
  for (Parser.ParsedFile pf : parsedFiles) {
100
- nodes.add(Contract.fileNode(pf.relPath, pf.endLine, pf.isTest ? "TEST" : "FILE", LANGUAGE));
100
+ Map<String, Object> fileNode =
101
+ Contract.fileNode(pf.relPath, pf.endLine, pf.isTest ? "TEST" : "FILE", LANGUAGE);
102
+ if (!pf.isTest && !pf.fileCalls.isEmpty()) {
103
+ // Module-scope facts — same shape as METHOD metadata.
104
+ @SuppressWarnings("unchecked")
105
+ Map<String, Object> fmeta = (Map<String, Object>) fileNode.get("metadata");
106
+ fmeta.put("calls", pf.fileCalls.stream().map(c -> c.name).distinct().sorted().toList());
107
+ fmeta.put("callSites", callSitesOf(pf.fileCalls));
108
+ }
109
+ nodes.add(fileNode);
101
110
  if (pf.isTest) {
102
- continue; // test files are LEAF nodes — children feed metadata only
111
+ continue;
103
112
  }
104
113
  List<String> childIds = new ArrayList<>();
105
114
  for (Parser.TypeInfo t : pf.allTypes()) {
@@ -134,6 +143,11 @@ public final class Extractor {
134
143
  // ── 3. shared lookup (built ONCE, consumed by every detector) ───
135
144
  LookupMaps lookup = LookupMaps.build(parsedFiles, nodes);
136
145
  lookup.methodCallFacts.putAll(methodCallFacts);
146
+ for (Parser.ParsedFile pf : parsedFiles) {
147
+ if (!pf.isTest && !pf.fileCalls.isEmpty()) {
148
+ lookup.fileCallFacts.put("file::" + pf.relPath, pf.fileCalls);
149
+ }
150
+ }
137
151
  lookup.testCases.putAll(testCases);
138
152
  ThirdParty tp = new ThirdParty(fp.rawDependencies, allowedThirdPartyLibs);
139
153
 
@@ -32,6 +32,8 @@ public final class LookupMaps {
32
32
  public final Map<String, List<String>> methodOverloads = new LinkedHashMap<>();
33
33
  /** method node id → parse-time call facts (CallInfo) */
34
34
  public final Map<String, List<Parser.CallInfo>> methodCallFacts = new LinkedHashMap<>();
35
+ /** FILE node id → call facts from field initializers + { } blocks */
36
+ public final Map<String, List<Parser.CallInfo>> fileCallFacts = new LinkedHashMap<>();
35
37
  /** test file relPath → test method names (metadata.testCases) */
36
38
  public final Map<String, List<String>> testCases = new HashMap<>();
37
39
 
@@ -10,6 +10,7 @@ import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
10
10
  import com.github.javaparser.ast.body.ConstructorDeclaration;
11
11
  import com.github.javaparser.ast.body.EnumDeclaration;
12
12
  import com.github.javaparser.ast.body.FieldDeclaration;
13
+ import com.github.javaparser.ast.body.InitializerDeclaration;
13
14
  import com.github.javaparser.ast.body.MethodDeclaration;
14
15
  import com.github.javaparser.ast.body.Parameter;
15
16
  import com.github.javaparser.ast.body.RecordDeclaration;
@@ -20,6 +21,7 @@ import com.github.javaparser.ast.type.ReferenceType;
20
21
  import com.github.javaparser.ast.expr.AnnotationExpr;
21
22
  import com.github.javaparser.ast.expr.Expression;
22
23
  import com.github.javaparser.ast.expr.FieldAccessExpr;
24
+ import com.github.javaparser.ast.expr.LambdaExpr;
23
25
  import com.github.javaparser.ast.expr.MethodCallExpr;
24
26
  import com.github.javaparser.ast.expr.NameExpr;
25
27
  import com.github.javaparser.ast.expr.NormalAnnotationExpr;
@@ -129,6 +131,9 @@ public final class Parser {
129
131
  public List<TypeInfo> types = new ArrayList<>();
130
132
  public Set<String> usedTypeNames = new LinkedHashSet<>();
131
133
  public List<String> errors = new ArrayList<>();
134
+ /** Calls in field initializers + static/instance { } blocks. These run
135
+ * at class-init time and are owned by the FILE node (module scope). */
136
+ public List<CallInfo> fileCalls = new ArrayList<>();
132
137
 
133
138
  /** Top-level + nested types flattened (nested get dotted names). */
134
139
  public List<TypeInfo> allTypes() {
@@ -232,6 +237,9 @@ public final class Parser {
232
237
  f.line = lineOf(fd, true);
233
238
  f.annotations.addAll(annotationNames(fd.getAnnotations()));
234
239
  t.fields.add(f);
240
+ // Field initializers run at class-init time — module scope.
241
+ v.getInitializer().ifPresent(init ->
242
+ pf.fileCalls.addAll(collectCalls(init, null, true)));
235
243
  }
236
244
  }
237
245
  }
@@ -243,6 +251,9 @@ public final class Parser {
243
251
  t.methods.add(extractMethod(md, pf, t.isInterface));
244
252
  } else if (member instanceof ConstructorDeclaration cd) {
245
253
  t.methods.add(extractConstructor(cd, pf));
254
+ } else if (member instanceof InitializerDeclaration id) {
255
+ // static { } / instance { } blocks — module-scope call sites.
256
+ pf.fileCalls.addAll(collectCalls(id.getBody(), null, true));
246
257
  }
247
258
  }
248
259
  }
@@ -297,12 +308,23 @@ public final class Parser {
297
308
  * lambdas attributed to another owner (same guard as Python's
298
309
  * NESTED_SCOPES).
299
310
  */
300
- private static List<CallInfo> collectCalls(BlockStmt body, MethodInfo owner) {
311
+ private static List<CallInfo> collectCalls(Node body, MethodInfo owner) {
312
+ return collectCalls(body, owner, false);
313
+ }
314
+
315
+ /**
316
+ * @param moduleScope when true, skip calls nested in a lambda / anonymous
317
+ * class method inside the node — those execute later, not at init time.
318
+ */
319
+ private static List<CallInfo> collectCalls(Node body, MethodInfo owner, boolean moduleScope) {
301
320
  List<CallInfo> calls = new ArrayList<>();
302
321
  if (body == null) {
303
322
  return calls;
304
323
  }
305
324
  body.walk(MethodCallExpr.class, call -> {
325
+ if (moduleScope && isNestedScope(call)) {
326
+ return;
327
+ }
306
328
  CallInfo ci = new CallInfo();
307
329
  ci.methodName = call.getNameAsString();
308
330
  ci.line = lineOf(call, true);
@@ -330,6 +352,16 @@ public final class Parser {
330
352
  return calls;
331
353
  }
332
354
 
355
+ /**
356
+ * True when the call executes inside a lambda or an anonymous/local class
357
+ * method — i.e. not at the initializer's own init time.
358
+ */
359
+ private static boolean isNestedScope(MethodCallExpr call) {
360
+ return call.findAncestor(LambdaExpr.class).isPresent()
361
+ || call.findAncestor(MethodDeclaration.class).isPresent()
362
+ || call.findAncestor(ConstructorDeclaration.class).isPresent();
363
+ }
364
+
333
365
  /**
334
366
  * Cheap argument type tag in the same vocabulary as declared param types:
335
367
  * literals map directly, anything else goes through the symbol solver
@@ -68,6 +68,50 @@ public final class Calls {
68
68
  metadata.put("resolvedCallDetails", resolvedDetails);
69
69
  }
70
70
  }
71
+
72
+ // ── module scope: field initializers + static/instance blocks ──
73
+ // Owned by the FILE node. Same ladder + symbol maps, so the
74
+ // third-party gate (Imports' allowed prefixes) applies identically.
75
+ for (Map.Entry<String, List<Parser.CallInfo>> entry : lookup.fileCallFacts.entrySet()) {
76
+ String callerId = entry.getKey();
77
+ Map<String, Object> caller = lookup.nodeById.get(callerId);
78
+ if (caller == null) {
79
+ continue;
80
+ }
81
+ String relPath = (String) caller.get("filePath");
82
+ String pkg = packageOf(callerId, relPath);
83
+ List<String> resolvedCalls = new ArrayList<>();
84
+ List<Map<String, String>> resolvedDetails = new ArrayList<>();
85
+
86
+ for (Parser.CallInfo ci : entry.getValue()) {
87
+ // parentClass null is safe: sameClassMethod builds a
88
+ // "file::x::null" key, which has no candidates.
89
+ Overloads.Pick pick = resolveOne(ci, lookup, relPath, null, pkg, callerId);
90
+ if (pick == null) {
91
+ continue;
92
+ }
93
+ Map<String, Object> edgeMeta = new LinkedHashMap<>();
94
+ edgeMeta.put("line", ci.line);
95
+ edgeMeta.put("matchedBy", pick.matchedBy);
96
+ edgeMeta.put("scope", "module");
97
+ edgesOut.add(Contract.edge("CALLS", callerId, pick.id, edgeMeta));
98
+ resolvedCalls.add(pick.id);
99
+
100
+ Map<String, String> detail = new LinkedHashMap<>();
101
+ detail.put("target", pick.id);
102
+ detail.put("method", ci.methodName);
103
+ detail.put("class", classNodeOf(pick.id));
104
+ resolvedDetails.add(detail);
105
+ }
106
+
107
+ if (!resolvedCalls.isEmpty()) {
108
+ java.util.Collections.sort(resolvedCalls);
109
+ @SuppressWarnings("unchecked")
110
+ Map<String, Object> metadata = (Map<String, Object>) caller.get("metadata");
111
+ metadata.put("resolvedCalls", resolvedCalls);
112
+ metadata.put("resolvedCallDetails", resolvedDetails);
113
+ }
114
+ }
71
115
  }
72
116
 
73
117
  private static Overloads.Pick resolveOne(Parser.CallInfo ci, LookupMaps lookup,