gitnexus 1.6.6-rc.98 → 1.6.6

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 (541) hide show
  1. package/README.md +122 -68
  2. package/dist/_shared/graph/types.d.ts +17 -1
  3. package/dist/_shared/graph/types.d.ts.map +1 -1
  4. package/dist/_shared/index.d.ts +3 -5
  5. package/dist/_shared/index.d.ts.map +1 -1
  6. package/dist/_shared/index.js +2 -4
  7. package/dist/_shared/index.js.map +1 -1
  8. package/dist/_shared/scope-resolution/module-scope-index.d.ts +1 -2
  9. package/dist/_shared/scope-resolution/module-scope-index.d.ts.map +1 -1
  10. package/dist/_shared/scope-resolution/module-scope-index.js +1 -2
  11. package/dist/_shared/scope-resolution/module-scope-index.js.map +1 -1
  12. package/dist/_shared/scope-resolution/parsed-file.d.ts +24 -0
  13. package/dist/_shared/scope-resolution/parsed-file.d.ts.map +1 -1
  14. package/dist/_shared/scope-resolution/reference-site.d.ts +13 -1
  15. package/dist/_shared/scope-resolution/reference-site.d.ts.map +1 -1
  16. package/dist/_shared/scope-resolution/registries/context.d.ts +1 -0
  17. package/dist/_shared/scope-resolution/registries/context.d.ts.map +1 -1
  18. package/dist/_shared/scope-resolution/registries/context.js +6 -0
  19. package/dist/_shared/scope-resolution/registries/context.js.map +1 -1
  20. package/dist/_shared/scope-resolution/registries/evidence.d.ts +2 -3
  21. package/dist/_shared/scope-resolution/registries/evidence.d.ts.map +1 -1
  22. package/dist/_shared/scope-resolution/registries/evidence.js +2 -3
  23. package/dist/_shared/scope-resolution/registries/evidence.js.map +1 -1
  24. package/dist/_shared/scope-resolution/registries/macro-registry.d.ts +29 -0
  25. package/dist/_shared/scope-resolution/registries/macro-registry.d.ts.map +1 -0
  26. package/dist/_shared/scope-resolution/registries/macro-registry.js +32 -0
  27. package/dist/_shared/scope-resolution/registries/macro-registry.js.map +1 -0
  28. package/dist/_shared/scope-resolution/symbol-definition.d.ts +9 -0
  29. package/dist/_shared/scope-resolution/symbol-definition.d.ts.map +1 -1
  30. package/dist/_shared/scope-resolution/types.d.ts +1 -1
  31. package/dist/_shared/scope-resolution/types.d.ts.map +1 -1
  32. package/dist/cli/ai-context.d.ts +35 -1
  33. package/dist/cli/ai-context.js +111 -12
  34. package/dist/cli/analyze-config.d.ts +92 -0
  35. package/dist/cli/analyze-config.js +364 -0
  36. package/dist/cli/analyze.d.ts +17 -1
  37. package/dist/cli/analyze.js +224 -71
  38. package/dist/cli/cli-message.d.ts +1 -1
  39. package/dist/cli/doctor.d.ts +18 -0
  40. package/dist/cli/doctor.js +32 -0
  41. package/dist/cli/i18n/en.d.ts +2 -2
  42. package/dist/cli/i18n/en.js +2 -2
  43. package/dist/cli/i18n/resources.d.ts +2 -2
  44. package/dist/cli/i18n/zh-CN.js +2 -2
  45. package/dist/cli/index.js +4 -2
  46. package/dist/cli/resolve-invocation.d.ts +21 -0
  47. package/dist/cli/resolve-invocation.js +68 -0
  48. package/dist/cli/setup.d.ts +33 -0
  49. package/dist/cli/setup.js +96 -35
  50. package/dist/cli/skill-gen.js +2 -2
  51. package/dist/cli/wiki.js +20 -4
  52. package/dist/core/embeddings/embedder.d.ts +1 -1
  53. package/dist/core/embeddings/embedder.js +14 -1
  54. package/dist/core/embeddings/runtime-support.d.ts +41 -0
  55. package/dist/core/embeddings/runtime-support.js +65 -0
  56. package/dist/core/group/extractors/grpc-patterns/proto.js +2 -1
  57. package/dist/core/group/extractors/http-patterns/java.js +15 -1
  58. package/dist/core/ingestion/call-processor.d.ts +57 -227
  59. package/dist/core/ingestion/call-processor.js +172 -2595
  60. package/dist/core/ingestion/call-routing.d.ts +6 -5
  61. package/dist/core/ingestion/call-routing.js +6 -6
  62. package/dist/core/ingestion/call-types.d.ts +0 -75
  63. package/dist/core/ingestion/class-extractors/configs/c-cpp.js +26 -1
  64. package/dist/core/ingestion/class-extractors/configs/ruby.js +3 -0
  65. package/dist/core/ingestion/class-extractors/generic.js +9 -11
  66. package/dist/core/ingestion/class-types.d.ts +23 -0
  67. package/dist/core/ingestion/cobol/cobol-preprocessor.d.ts +11 -0
  68. package/dist/core/ingestion/cobol/cobol-preprocessor.js +227 -73
  69. package/dist/core/ingestion/cobol-processor.d.ts +1 -0
  70. package/dist/core/ingestion/cobol-processor.js +51 -2
  71. package/dist/core/ingestion/emit-references.js +8 -2
  72. package/dist/core/ingestion/export-detection.d.ts +2 -1
  73. package/dist/core/ingestion/export-detection.js +2 -6
  74. package/dist/core/ingestion/field-extractors/configs/dart.d.ts +0 -6
  75. package/dist/core/ingestion/field-extractors/configs/dart.js +62 -44
  76. package/dist/core/ingestion/field-extractors/configs/go.d.ts +0 -9
  77. package/dist/core/ingestion/field-extractors/configs/go.js +40 -1
  78. package/dist/core/ingestion/field-extractors/configs/jvm.js +43 -4
  79. package/dist/core/ingestion/field-extractors/configs/php.js +1 -2
  80. package/dist/core/ingestion/field-extractors/configs/swift.d.ts +12 -1
  81. package/dist/core/ingestion/field-extractors/configs/swift.js +31 -6
  82. package/dist/core/ingestion/field-extractors/generic.d.ts +6 -0
  83. package/dist/core/ingestion/field-extractors/generic.js +5 -4
  84. package/dist/core/ingestion/field-extractors/typescript.js +0 -29
  85. package/dist/core/ingestion/filesystem-walker.d.ts +0 -9
  86. package/dist/core/ingestion/filesystem-walker.js +0 -11
  87. package/dist/core/ingestion/finalize-orchestrator.js +14 -2
  88. package/dist/core/ingestion/import-resolvers/configs/swift.d.ts +21 -0
  89. package/dist/core/ingestion/import-resolvers/configs/swift.js +72 -11
  90. package/dist/core/ingestion/import-resolvers/python.d.ts +1 -1
  91. package/dist/core/ingestion/import-resolvers/standard.d.ts +2 -2
  92. package/dist/core/ingestion/import-resolvers/standard.js +6 -5
  93. package/dist/core/ingestion/import-resolvers/utils.d.ts +2 -5
  94. package/dist/core/ingestion/import-resolvers/utils.js +1 -9
  95. package/dist/core/ingestion/language-provider.d.ts +39 -119
  96. package/dist/core/ingestion/language-provider.js +0 -2
  97. package/dist/core/ingestion/languages/c/capture-side-channel.d.ts +62 -0
  98. package/dist/core/ingestion/languages/c/capture-side-channel.js +65 -0
  99. package/dist/core/ingestion/languages/c/captures.js +41 -23
  100. package/dist/core/ingestion/languages/c/import-decomposer.d.ts +9 -0
  101. package/dist/core/ingestion/languages/c/import-decomposer.js +15 -0
  102. package/dist/core/ingestion/languages/c/import-target.js +52 -9
  103. package/dist/core/ingestion/languages/c/index.d.ts +2 -1
  104. package/dist/core/ingestion/languages/c/index.js +2 -1
  105. package/dist/core/ingestion/languages/c/query.js +15 -0
  106. package/dist/core/ingestion/languages/c/scope-resolver.js +47 -4
  107. package/dist/core/ingestion/languages/c/static-linkage.d.ts +8 -0
  108. package/dist/core/ingestion/languages/c/static-linkage.js +46 -1
  109. package/dist/core/ingestion/languages/c-cpp.js +16 -7
  110. package/dist/core/ingestion/languages/cobol/captures.js +25 -2
  111. package/dist/core/ingestion/languages/cpp/adl.d.ts +88 -4
  112. package/dist/core/ingestion/languages/cpp/adl.js +380 -160
  113. package/dist/core/ingestion/languages/cpp/arity-metadata.js +2 -8
  114. package/dist/core/ingestion/languages/cpp/capture-side-channel.d.ts +65 -0
  115. package/dist/core/ingestion/languages/cpp/capture-side-channel.js +78 -0
  116. package/dist/core/ingestion/languages/cpp/captures.js +162 -54
  117. package/dist/core/ingestion/languages/cpp/file-local-linkage.d.ts +18 -52
  118. package/dist/core/ingestion/languages/cpp/file-local-linkage.js +49 -1
  119. package/dist/core/ingestion/languages/cpp/import-decomposer.d.ts +7 -0
  120. package/dist/core/ingestion/languages/cpp/import-decomposer.js +12 -0
  121. package/dist/core/ingestion/languages/cpp/index.d.ts +1 -0
  122. package/dist/core/ingestion/languages/cpp/index.js +1 -0
  123. package/dist/core/ingestion/languages/cpp/inline-namespaces.d.ts +8 -0
  124. package/dist/core/ingestion/languages/cpp/inline-namespaces.js +21 -0
  125. package/dist/core/ingestion/languages/cpp/query.js +21 -0
  126. package/dist/core/ingestion/languages/cpp/range-bindings.js +20 -5
  127. package/dist/core/ingestion/languages/cpp/scope-resolver.js +52 -5
  128. package/dist/core/ingestion/languages/cpp/two-phase-lookup.d.ts +20 -0
  129. package/dist/core/ingestion/languages/cpp/two-phase-lookup.js +83 -3
  130. package/dist/core/ingestion/languages/csharp/captures.js +205 -41
  131. package/dist/core/ingestion/languages/csharp/index.d.ts +3 -4
  132. package/dist/core/ingestion/languages/csharp/index.js +3 -4
  133. package/dist/core/ingestion/languages/csharp/interpret.js +17 -3
  134. package/dist/core/ingestion/languages/csharp/namespace-siblings.d.ts +17 -7
  135. package/dist/core/ingestion/languages/csharp/namespace-siblings.js +129 -124
  136. package/dist/core/ingestion/languages/csharp/qualified-type-names.d.ts +14 -0
  137. package/dist/core/ingestion/languages/csharp/qualified-type-names.js +59 -0
  138. package/dist/core/ingestion/languages/csharp/query.js +13 -0
  139. package/dist/core/ingestion/languages/csharp/receiver-binding.js +10 -6
  140. package/dist/core/ingestion/languages/csharp/scope-resolver.js +8 -1
  141. package/dist/core/ingestion/languages/csharp.js +0 -5
  142. package/dist/core/ingestion/languages/dart/arity-metadata.d.ts +25 -0
  143. package/dist/core/ingestion/languages/dart/arity-metadata.js +35 -0
  144. package/dist/core/ingestion/languages/dart/arity.d.ts +19 -0
  145. package/dist/core/ingestion/languages/dart/arity.js +31 -0
  146. package/dist/core/ingestion/languages/dart/built-ins.d.ts +11 -0
  147. package/dist/core/ingestion/languages/dart/built-ins.js +34 -0
  148. package/dist/core/ingestion/languages/dart/cache-stats.d.ts +13 -0
  149. package/dist/core/ingestion/languages/dart/cache-stats.js +24 -0
  150. package/dist/core/ingestion/languages/dart/captures.d.ts +29 -0
  151. package/dist/core/ingestion/languages/dart/captures.js +445 -0
  152. package/dist/core/ingestion/languages/dart/expand-wildcards.d.ts +13 -0
  153. package/dist/core/ingestion/languages/dart/expand-wildcards.js +31 -0
  154. package/dist/core/ingestion/languages/dart/import-target.d.ts +15 -0
  155. package/dist/core/ingestion/languages/dart/import-target.js +65 -0
  156. package/dist/core/ingestion/languages/dart/index.d.ts +28 -0
  157. package/dist/core/ingestion/languages/dart/index.js +28 -0
  158. package/dist/core/ingestion/languages/dart/interpret.d.ts +24 -0
  159. package/dist/core/ingestion/languages/dart/interpret.js +95 -0
  160. package/dist/core/ingestion/languages/dart/merge-bindings.d.ts +10 -0
  161. package/dist/core/ingestion/languages/dart/merge-bindings.js +39 -0
  162. package/dist/core/ingestion/languages/dart/query.d.ts +26 -0
  163. package/dist/core/ingestion/languages/dart/query.js +142 -0
  164. package/dist/core/ingestion/languages/dart/receiver-binding.d.ts +24 -0
  165. package/dist/core/ingestion/languages/dart/receiver-binding.js +87 -0
  166. package/dist/core/ingestion/languages/dart/scope-resolver.d.ts +29 -0
  167. package/dist/core/ingestion/languages/dart/scope-resolver.js +194 -0
  168. package/dist/core/ingestion/languages/dart/signature-bindings.d.ts +23 -0
  169. package/dist/core/ingestion/languages/dart/signature-bindings.js +51 -0
  170. package/dist/core/ingestion/languages/dart/simple-hooks.d.ts +20 -0
  171. package/dist/core/ingestion/languages/dart/simple-hooks.js +47 -0
  172. package/dist/core/ingestion/languages/dart.d.ts +0 -1
  173. package/dist/core/ingestion/languages/dart.js +15 -29
  174. package/dist/core/ingestion/languages/go/arity-metadata.d.ts +1 -0
  175. package/dist/core/ingestion/languages/go/arity-metadata.js +31 -1
  176. package/dist/core/ingestion/languages/go/captures.js +247 -26
  177. package/dist/core/ingestion/languages/go/interface-impls.js +476 -50
  178. package/dist/core/ingestion/languages/go/interpret.js +21 -11
  179. package/dist/core/ingestion/languages/go/method-owners.js +20 -8
  180. package/dist/core/ingestion/languages/go/query.js +15 -7
  181. package/dist/core/ingestion/languages/go/range-binding.js +24 -9
  182. package/dist/core/ingestion/languages/go/receiver-binding.js +1 -1
  183. package/dist/core/ingestion/languages/go/scope-resolver.js +2 -2
  184. package/dist/core/ingestion/languages/go/simple-hooks.js +10 -5
  185. package/dist/core/ingestion/languages/go/type-binding.d.ts +1 -0
  186. package/dist/core/ingestion/languages/go/type-binding.js +40 -2
  187. package/dist/core/ingestion/languages/go.d.ts +0 -1
  188. package/dist/core/ingestion/languages/go.js +0 -5
  189. package/dist/core/ingestion/languages/index.d.ts +0 -5
  190. package/dist/core/ingestion/languages/index.js +0 -3
  191. package/dist/core/ingestion/languages/java/captures.js +252 -23
  192. package/dist/core/ingestion/languages/java/interpret.js +12 -6
  193. package/dist/core/ingestion/languages/java/package-siblings.js +18 -5
  194. package/dist/core/ingestion/languages/java/query.js +16 -1
  195. package/dist/core/ingestion/languages/java/scope-resolver.d.ts +2 -8
  196. package/dist/core/ingestion/languages/java/scope-resolver.js +2 -8
  197. package/dist/core/ingestion/languages/java.js +0 -5
  198. package/dist/core/ingestion/languages/javascript/captures.js +185 -11
  199. package/dist/core/ingestion/languages/javascript/query.js +107 -1
  200. package/dist/core/ingestion/languages/kotlin/capture-side-channel.d.ts +57 -0
  201. package/dist/core/ingestion/languages/kotlin/capture-side-channel.js +60 -0
  202. package/dist/core/ingestion/languages/kotlin/captures.js +213 -22
  203. package/dist/core/ingestion/languages/kotlin/companion-scopes.d.ts +7 -0
  204. package/dist/core/ingestion/languages/kotlin/companion-scopes.js +10 -0
  205. package/dist/core/ingestion/languages/kotlin/index.d.ts +1 -0
  206. package/dist/core/ingestion/languages/kotlin/index.js +1 -0
  207. package/dist/core/ingestion/languages/kotlin/query.js +30 -0
  208. package/dist/core/ingestion/languages/kotlin/scope-resolver.d.ts +5 -7
  209. package/dist/core/ingestion/languages/kotlin/scope-resolver.js +22 -7
  210. package/dist/core/ingestion/languages/kotlin.js +8 -5
  211. package/dist/core/ingestion/languages/php/captures.js +135 -19
  212. package/dist/core/ingestion/languages/php/import-decomposer.js +21 -63
  213. package/dist/core/ingestion/languages/php/index.d.ts +3 -4
  214. package/dist/core/ingestion/languages/php/index.js +3 -4
  215. package/dist/core/ingestion/languages/php/query.js +5 -0
  216. package/dist/core/ingestion/languages/php/receiver-binding.js +8 -4
  217. package/dist/core/ingestion/languages/php.js +0 -4
  218. package/dist/core/ingestion/languages/python/captures.js +128 -13
  219. package/dist/core/ingestion/languages/python/depends-references.js +1 -1
  220. package/dist/core/ingestion/languages/python/import-target.d.ts +4 -5
  221. package/dist/core/ingestion/languages/python/import-target.js +108 -16
  222. package/dist/core/ingestion/languages/python/index-stats.d.ts +18 -0
  223. package/dist/core/ingestion/languages/python/index-stats.js +25 -0
  224. package/dist/core/ingestion/languages/python/index.d.ts +3 -4
  225. package/dist/core/ingestion/languages/python/index.js +3 -4
  226. package/dist/core/ingestion/languages/python/query.js +17 -0
  227. package/dist/core/ingestion/languages/python/scope-resolver.js +7 -6
  228. package/dist/core/ingestion/languages/python.d.ts +0 -2
  229. package/dist/core/ingestion/languages/python.js +0 -7
  230. package/dist/core/ingestion/languages/ruby/captures.js +174 -31
  231. package/dist/core/ingestion/languages/ruby/import-target.js +2 -1
  232. package/dist/core/ingestion/languages/ruby/interpret.js +2 -1
  233. package/dist/core/ingestion/languages/ruby/query.js +10 -0
  234. package/dist/core/ingestion/languages/ruby/scope-resolver.js +61 -11
  235. package/dist/core/ingestion/languages/ruby.js +4 -53
  236. package/dist/core/ingestion/languages/rust/captures.js +95 -13
  237. package/dist/core/ingestion/languages/rust/query.js +64 -1
  238. package/dist/core/ingestion/languages/rust/range-binding.js +40 -12
  239. package/dist/core/ingestion/languages/rust/receiver-binding.js +9 -0
  240. package/dist/core/ingestion/languages/rust/scope-resolver.js +75 -1
  241. package/dist/core/ingestion/languages/rust.d.ts +0 -2
  242. package/dist/core/ingestion/languages/rust.js +0 -6
  243. package/dist/core/ingestion/languages/swift/arity-metadata.d.ts +24 -0
  244. package/dist/core/ingestion/languages/swift/arity-metadata.js +41 -0
  245. package/dist/core/ingestion/languages/swift/arity.d.ts +29 -0
  246. package/dist/core/ingestion/languages/swift/arity.js +42 -0
  247. package/dist/core/ingestion/languages/swift/base-type.d.ts +20 -0
  248. package/dist/core/ingestion/languages/swift/base-type.js +27 -0
  249. package/dist/core/ingestion/languages/swift/cache-stats.d.ts +15 -0
  250. package/dist/core/ingestion/languages/swift/cache-stats.js +26 -0
  251. package/dist/core/ingestion/languages/swift/captures.d.ts +35 -0
  252. package/dist/core/ingestion/languages/swift/captures.js +495 -0
  253. package/dist/core/ingestion/languages/swift/implicit-imports.d.ts +34 -0
  254. package/dist/core/ingestion/languages/swift/implicit-imports.js +57 -0
  255. package/dist/core/ingestion/languages/swift/import-decomposer.d.ts +24 -0
  256. package/dist/core/ingestion/languages/swift/import-decomposer.js +84 -0
  257. package/dist/core/ingestion/languages/swift/import-target.d.ts +33 -0
  258. package/dist/core/ingestion/languages/swift/import-target.js +81 -0
  259. package/dist/core/ingestion/languages/swift/index.d.ts +37 -0
  260. package/dist/core/ingestion/languages/swift/index.js +37 -0
  261. package/dist/core/ingestion/languages/swift/interpret.d.ts +15 -0
  262. package/dist/core/ingestion/languages/swift/interpret.js +89 -0
  263. package/dist/core/ingestion/languages/swift/merge-bindings.d.ts +20 -0
  264. package/dist/core/ingestion/languages/swift/merge-bindings.js +48 -0
  265. package/dist/core/ingestion/languages/swift/query.d.ts +46 -0
  266. package/dist/core/ingestion/languages/swift/query.js +194 -0
  267. package/dist/core/ingestion/languages/swift/receiver-binding.d.ts +40 -0
  268. package/dist/core/ingestion/languages/swift/receiver-binding.js +161 -0
  269. package/dist/core/ingestion/languages/swift/scope-resolver.d.ts +50 -0
  270. package/dist/core/ingestion/languages/swift/scope-resolver.js +189 -0
  271. package/dist/core/ingestion/languages/swift/sibling-type-bindings.d.ts +34 -0
  272. package/dist/core/ingestion/languages/swift/sibling-type-bindings.js +65 -0
  273. package/dist/core/ingestion/languages/swift/signature-bindings.d.ts +25 -0
  274. package/dist/core/ingestion/languages/swift/signature-bindings.js +66 -0
  275. package/dist/core/ingestion/languages/swift/simple-hooks.d.ts +37 -0
  276. package/dist/core/ingestion/languages/swift/simple-hooks.js +60 -0
  277. package/dist/core/ingestion/languages/swift/target-grouping.d.ts +51 -0
  278. package/dist/core/ingestion/languages/swift/target-grouping.js +93 -0
  279. package/dist/core/ingestion/languages/swift/target-siblings.d.ts +30 -0
  280. package/dist/core/ingestion/languages/swift/target-siblings.js +71 -0
  281. package/dist/core/ingestion/languages/swift.d.ts +0 -5
  282. package/dist/core/ingestion/languages/swift.js +11 -87
  283. package/dist/core/ingestion/languages/typescript/array-callback.d.ts +3 -29
  284. package/dist/core/ingestion/languages/typescript/array-callback.js +4 -43
  285. package/dist/core/ingestion/languages/typescript/captures.js +147 -17
  286. package/dist/core/ingestion/languages/typescript/index.d.ts +3 -4
  287. package/dist/core/ingestion/languages/typescript/index.js +3 -4
  288. package/dist/core/ingestion/languages/typescript/query.d.ts +2 -3
  289. package/dist/core/ingestion/languages/typescript/query.js +125 -4
  290. package/dist/core/ingestion/languages/typescript/receiver-binding.js +0 -1
  291. package/dist/core/ingestion/languages/typescript.d.ts +2 -3
  292. package/dist/core/ingestion/languages/typescript.js +46 -23
  293. package/dist/core/ingestion/languages/vue/captures.d.ts +46 -0
  294. package/dist/core/ingestion/languages/vue/captures.js +67 -0
  295. package/dist/core/ingestion/languages/vue/import-target.d.ts +27 -0
  296. package/dist/core/ingestion/languages/vue/import-target.js +58 -0
  297. package/dist/core/ingestion/languages/vue/index.d.ts +49 -0
  298. package/dist/core/ingestion/languages/vue/index.js +49 -0
  299. package/dist/core/ingestion/languages/vue/scope-resolver.d.ts +55 -0
  300. package/dist/core/ingestion/languages/vue/scope-resolver.js +292 -0
  301. package/dist/core/ingestion/languages/vue.js +12 -4
  302. package/dist/core/ingestion/local-symbol-pruner.d.ts +11 -0
  303. package/dist/core/ingestion/local-symbol-pruner.js +63 -0
  304. package/dist/core/ingestion/method-extractors/configs/dart.js +14 -1
  305. package/dist/core/ingestion/method-extractors/configs/jvm.js +37 -20
  306. package/dist/core/ingestion/method-extractors/configs/php.js +0 -1
  307. package/dist/core/ingestion/method-extractors/configs/swift.js +11 -4
  308. package/dist/core/ingestion/method-types.d.ts +2 -2
  309. package/dist/core/ingestion/model/index.d.ts +0 -3
  310. package/dist/core/ingestion/model/index.js +0 -8
  311. package/dist/core/ingestion/model/resolve.d.ts +7 -43
  312. package/dist/core/ingestion/model/resolve.js +7 -226
  313. package/dist/core/ingestion/model/scope-resolution-indexes.d.ts +46 -1
  314. package/dist/core/ingestion/model/semantic-model.d.ts +4 -6
  315. package/dist/core/ingestion/model/semantic-model.js +1 -1
  316. package/dist/core/ingestion/model/symbol-table.d.ts +3 -4
  317. package/dist/core/ingestion/model/symbol-table.js +3 -4
  318. package/dist/core/ingestion/parsing-processor.d.ts +30 -24
  319. package/dist/core/ingestion/parsing-processor.js +76 -640
  320. package/dist/core/ingestion/pipeline-phases/communities.d.ts +1 -1
  321. package/dist/core/ingestion/pipeline-phases/communities.js +5 -2
  322. package/dist/core/ingestion/pipeline-phases/cross-file.d.ts +9 -8
  323. package/dist/core/ingestion/pipeline-phases/cross-file.js +16 -12
  324. package/dist/core/ingestion/pipeline-phases/index.d.ts +1 -0
  325. package/dist/core/ingestion/pipeline-phases/index.js +1 -0
  326. package/dist/core/ingestion/pipeline-phases/mro.d.ts +1 -1
  327. package/dist/core/ingestion/pipeline-phases/mro.js +2 -2
  328. package/dist/core/ingestion/pipeline-phases/parse-impl.d.ts +44 -22
  329. package/dist/core/ingestion/pipeline-phases/parse-impl.js +426 -565
  330. package/dist/core/ingestion/pipeline-phases/parse.d.ts +13 -33
  331. package/dist/core/ingestion/pipeline-phases/parse.js +2 -2
  332. package/dist/core/ingestion/pipeline-phases/processes.d.ts +1 -1
  333. package/dist/core/ingestion/pipeline-phases/processes.js +5 -3
  334. package/dist/core/ingestion/pipeline-phases/prune-local-symbols.d.ts +14 -0
  335. package/dist/core/ingestion/pipeline-phases/prune-local-symbols.js +26 -0
  336. package/dist/core/ingestion/pipeline.d.ts +27 -19
  337. package/dist/core/ingestion/pipeline.js +4 -2
  338. package/dist/core/ingestion/resolve-references.js +15 -3
  339. package/dist/core/ingestion/route-extractors/laravel.d.ts +10 -0
  340. package/dist/core/ingestion/route-extractors/laravel.js +88 -9
  341. package/dist/core/ingestion/scope-extractor-bridge.d.ts +2 -1
  342. package/dist/core/ingestion/scope-extractor-bridge.js +2 -2
  343. package/dist/core/ingestion/scope-extractor.js +13 -0
  344. package/dist/core/ingestion/scope-resolution/contract/scope-resolver.d.ts +181 -15
  345. package/dist/core/ingestion/scope-resolution/contract/scope-resolver.js +21 -10
  346. package/dist/core/ingestion/scope-resolution/graph-bridge/edges.js +10 -2
  347. package/dist/core/ingestion/scope-resolution/graph-bridge/ids.d.ts +7 -1
  348. package/dist/core/ingestion/scope-resolution/graph-bridge/ids.js +58 -6
  349. package/dist/core/ingestion/scope-resolution/graph-bridge/node-lookup.js +24 -5
  350. package/dist/core/ingestion/scope-resolution/passes/free-call-fallback.d.ts +68 -1
  351. package/dist/core/ingestion/scope-resolution/passes/free-call-fallback.js +189 -29
  352. package/dist/core/ingestion/scope-resolution/passes/imported-return-types.js +21 -1
  353. package/dist/core/ingestion/scope-resolution/passes/receiver-bound-calls.js +1 -1
  354. package/dist/core/ingestion/scope-resolution/pipeline/phase.d.ts +8 -11
  355. package/dist/core/ingestion/scope-resolution/pipeline/phase.js +171 -50
  356. package/dist/core/ingestion/scope-resolution/pipeline/registry.d.ts +3 -4
  357. package/dist/core/ingestion/scope-resolution/pipeline/registry.js +9 -4
  358. package/dist/core/ingestion/scope-resolution/pipeline/run.d.ts +28 -5
  359. package/dist/core/ingestion/scope-resolution/pipeline/run.js +191 -24
  360. package/dist/core/ingestion/scope-resolution/pipeline/validate-bindings-immutability.js +31 -0
  361. package/dist/core/ingestion/scope-resolution/scope/walkers.d.ts +72 -0
  362. package/dist/core/ingestion/scope-resolution/scope/walkers.js +440 -39
  363. package/dist/core/ingestion/scope-resolution/workspace-index.d.ts +18 -2
  364. package/dist/core/ingestion/scope-resolution/workspace-index.js +94 -7
  365. package/dist/core/ingestion/tree-sitter-queries.d.ts +14 -14
  366. package/dist/core/ingestion/tree-sitter-queries.js +380 -158
  367. package/dist/core/ingestion/ts-js-hoc-utils.d.ts +12 -0
  368. package/dist/core/ingestion/ts-js-hoc-utils.js +105 -0
  369. package/dist/core/ingestion/type-env.d.ts +2 -1
  370. package/dist/core/ingestion/type-env.js +6 -8
  371. package/dist/core/ingestion/type-extractors/c-cpp.js +8 -10
  372. package/dist/core/ingestion/type-extractors/csharp.js +18 -34
  373. package/dist/core/ingestion/type-extractors/go.js +2 -10
  374. package/dist/core/ingestion/type-extractors/jvm.js +6 -5
  375. package/dist/core/ingestion/type-extractors/php.js +1 -1
  376. package/dist/core/ingestion/type-extractors/python.js +1 -1
  377. package/dist/core/ingestion/type-extractors/ruby.js +2 -2
  378. package/dist/core/ingestion/type-extractors/rust.js +0 -16
  379. package/dist/core/ingestion/type-extractors/shared.d.ts +2 -2
  380. package/dist/core/ingestion/type-extractors/shared.js +25 -11
  381. package/dist/core/ingestion/type-extractors/swift.js +5 -5
  382. package/dist/core/ingestion/type-extractors/types.d.ts +1 -1
  383. package/dist/core/ingestion/type-extractors/typescript.js +1 -1
  384. package/dist/core/ingestion/utils/ast-helpers.d.ts +119 -1
  385. package/dist/core/ingestion/utils/ast-helpers.js +260 -13
  386. package/dist/core/ingestion/utils/callable-labels.d.ts +13 -0
  387. package/dist/core/ingestion/utils/callable-labels.js +14 -0
  388. package/dist/core/ingestion/utils/deferred-resolution-profile.d.ts +10 -0
  389. package/dist/core/ingestion/utils/deferred-resolution-profile.js +30 -0
  390. package/dist/core/ingestion/utils/heap-probe.d.ts +20 -0
  391. package/dist/core/ingestion/utils/heap-probe.js +39 -0
  392. package/dist/core/ingestion/utils/heritage-marker.d.ts +33 -0
  393. package/dist/core/ingestion/utils/heritage-marker.js +41 -0
  394. package/dist/core/ingestion/utils/qualified-name.d.ts +37 -0
  395. package/dist/core/ingestion/utils/qualified-name.js +67 -0
  396. package/dist/core/ingestion/variable-extractors/configs/c-cpp.js +49 -0
  397. package/dist/core/ingestion/variable-extractors/configs/dart.js +76 -62
  398. package/dist/core/ingestion/variable-extractors/configs/go.js +74 -7
  399. package/dist/core/ingestion/variable-extractors/configs/jvm.js +35 -8
  400. package/dist/core/ingestion/variable-extractors/generic.js +40 -12
  401. package/dist/core/ingestion/variable-types.d.ts +9 -0
  402. package/dist/core/ingestion/vue-sfc-extractor.d.ts +97 -7
  403. package/dist/core/ingestion/vue-sfc-extractor.js +433 -11
  404. package/dist/core/ingestion/workers/parse-worker.d.ts +0 -11
  405. package/dist/core/ingestion/workers/parse-worker.js +358 -187
  406. package/dist/core/ingestion/workers/worker-pool.d.ts +78 -9
  407. package/dist/core/ingestion/workers/worker-pool.js +346 -49
  408. package/dist/core/lbug/csv-generator.js +20 -2
  409. package/dist/core/lbug/lbug-adapter.js +29 -10
  410. package/dist/core/lbug/native-check.js +17 -5
  411. package/dist/core/lbug/pool-adapter.d.ts +0 -19
  412. package/dist/core/lbug/pool-adapter.js +40 -77
  413. package/dist/core/lbug/query-result-utils.d.ts +19 -0
  414. package/dist/core/lbug/query-result-utils.js +28 -0
  415. package/dist/core/run-analyze.d.ts +9 -2
  416. package/dist/core/run-analyze.js +24 -3
  417. package/dist/core/tree-sitter/parser-loader.d.ts +13 -0
  418. package/dist/core/tree-sitter/parser-loader.js +4 -0
  419. package/dist/core/tree-sitter/safe-parse.d.ts +70 -3
  420. package/dist/core/tree-sitter/safe-parse.js +214 -11
  421. package/dist/core/wiki/generator.js +13 -5
  422. package/dist/core/wiki/graph-queries.d.ts +3 -0
  423. package/dist/core/wiki/graph-queries.js +9 -1
  424. package/dist/core/wiki/llm-client.d.ts +1 -1
  425. package/dist/core/wiki/llm-client.js +7 -2
  426. package/dist/core/wiki/local-cli-client.d.ts +2 -1
  427. package/dist/core/wiki/local-cli-client.js +62 -4
  428. package/dist/mcp/compatible-stdio-transport.d.ts +3 -0
  429. package/dist/mcp/compatible-stdio-transport.js +22 -0
  430. package/dist/mcp/core/embedder.d.ts +1 -1
  431. package/dist/mcp/core/embedder.js +13 -1
  432. package/dist/mcp/local/local-backend.d.ts +37 -5
  433. package/dist/mcp/local/local-backend.js +227 -129
  434. package/dist/mcp/resources.js +3 -3
  435. package/dist/mcp/server.js +9 -1
  436. package/dist/storage/git.d.ts +11 -0
  437. package/dist/storage/git.js +30 -0
  438. package/dist/storage/parse-cache.d.ts +23 -1
  439. package/dist/storage/parse-cache.js +138 -32
  440. package/dist/storage/parsedfile-store.d.ts +142 -0
  441. package/dist/storage/parsedfile-store.js +367 -0
  442. package/dist/storage/repo-manager.d.ts +2 -1
  443. package/dist/storage/scope-index-store.d.ts +114 -0
  444. package/dist/storage/scope-index-store.js +236 -0
  445. package/dist/types/pipeline.d.ts +6 -3
  446. package/hooks/antigravity/gitnexus-antigravity-hook.cjs +2 -1
  447. package/hooks/claude/gitnexus-hook.cjs +2 -1
  448. package/hooks/claude/resolve-analyze-cmd.cjs +323 -0
  449. package/package.json +4 -5
  450. package/scripts/bench-scope-resolution.ts +1 -3
  451. package/scripts/cross-platform-tests.ts +4 -1
  452. package/skills/gitnexus-cli.md +8 -6
  453. package/skills/gitnexus-debugging.md +15 -15
  454. package/skills/gitnexus-exploring.md +11 -11
  455. package/skills/gitnexus-guide.md +1 -1
  456. package/skills/gitnexus-impact-analysis.md +10 -10
  457. package/skills/gitnexus-pr-review.md +19 -19
  458. package/skills/gitnexus-refactoring.md +25 -25
  459. package/web/assets/{agent-BRX-afm3.js → agent-EkX7webX.js} +156 -131
  460. package/web/assets/{architectureDiagram-UL44E2DR-B1oYB8-c.js → architectureDiagram-UL44E2DR-BoczH8cv.js} +1 -1
  461. package/web/assets/{chunk-LCXTWHL2-SPC6pgWI.js → chunk-LCXTWHL2-By5HB3b-.js} +1 -1
  462. package/web/assets/{chunk-RG4AUYOV-DZXr4Yv3.js → chunk-RG4AUYOV-BQE_DkpL.js} +1 -1
  463. package/web/assets/{classDiagram-KGZ6W3CR-BqpOj8L9.js → classDiagram-KGZ6W3CR-Dj_02GUH.js} +1 -1
  464. package/web/assets/{classDiagram-v2-72OJOZXJ-FmElywK2.js → classDiagram-v2-72OJOZXJ-D-NArMpf.js} +1 -1
  465. package/web/assets/{diagram-3NCE3AQN-BWtJXMDq.js → diagram-3NCE3AQN-VXtXDO95.js} +1 -1
  466. package/web/assets/{diagram-GF46GFSD-Hh-fChxU.js → diagram-GF46GFSD-B1qab2Ah.js} +1 -1
  467. package/web/assets/{diagram-QXG6HAR7-DYeQHxGU.js → diagram-QXG6HAR7-BSCHGzzT.js} +1 -1
  468. package/web/assets/{diagram-WEQXMOUZ-DYGU4T0y.js → diagram-WEQXMOUZ-DHtknmNT.js} +1 -1
  469. package/web/assets/{erDiagram-L5TCEMPS-bN3wlP2A.js → erDiagram-L5TCEMPS-Db-IYTmm.js} +1 -1
  470. package/web/assets/{flowDiagram-H6V6AXG4-YACVtF3-.js → flowDiagram-H6V6AXG4-BHDoyVoW.js} +1 -1
  471. package/web/assets/{index-BhnAdWTt.js → index-BR0IhgbR.js} +10 -10
  472. package/web/assets/{infoDiagram-3YFTVSEB-BWBzD28-.js → infoDiagram-3YFTVSEB-6h8wbWEe.js} +1 -1
  473. package/web/assets/{ishikawaDiagram-BNXS4ZKH-B8qYT-j9.js → ishikawaDiagram-BNXS4ZKH-Dx2OkPk1.js} +1 -1
  474. package/web/assets/{kanban-definition-75IXJCU3-BeoPr5Tl.js → kanban-definition-75IXJCU3-CIIEZfqV.js} +1 -1
  475. package/web/assets/{mindmap-definition-2TDM6QVE-CdLLN_so.js → mindmap-definition-2TDM6QVE-DUAqydRq.js} +1 -1
  476. package/web/assets/{pieDiagram-CU6KROY3-DEd2a_k_.js → pieDiagram-CU6KROY3-BntYuYZa.js} +1 -1
  477. package/web/assets/{requirementDiagram-JXO7QTGE-QNeTo5C_.js → requirementDiagram-JXO7QTGE-QCD6I29n.js} +1 -1
  478. package/web/assets/{sequenceDiagram-VS2MUI6T-BHC7q7yJ.js → sequenceDiagram-VS2MUI6T-DScFwLz2.js} +1 -1
  479. package/web/assets/{stateDiagram-7D4R322I-KONnc2Px.js → stateDiagram-7D4R322I-AkRAm6Hl.js} +1 -1
  480. package/web/assets/{stateDiagram-v2-36443NZ5-C2QfuMlu.js → stateDiagram-v2-36443NZ5-BCK1vigR.js} +1 -1
  481. package/web/assets/{timeline-definition-O6YCAMPW-D4t4NJx1.js → timeline-definition-O6YCAMPW-BvpIVXjX.js} +1 -1
  482. package/web/assets/{vennDiagram-MWXL3ELB-6bctC9Yg.js → vennDiagram-MWXL3ELB-BYGWk6dK.js} +1 -1
  483. package/web/assets/{wardleyDiagram-CUQ6CDDI-BPZYNTvC.js → wardleyDiagram-CUQ6CDDI-Dk1z7H2T.js} +1 -1
  484. package/web/assets/{xychartDiagram-N2JHSOCM-lBI9O6DW.js → xychartDiagram-N2JHSOCM-2N6NCSWN.js} +1 -1
  485. package/web/index.html +1 -1
  486. package/dist/_shared/scope-resolution/shadow/aggregate.d.ts +0 -63
  487. package/dist/_shared/scope-resolution/shadow/aggregate.d.ts.map +0 -1
  488. package/dist/_shared/scope-resolution/shadow/aggregate.js +0 -122
  489. package/dist/_shared/scope-resolution/shadow/aggregate.js.map +0 -1
  490. package/dist/_shared/scope-resolution/shadow/diff.d.ts +0 -59
  491. package/dist/_shared/scope-resolution/shadow/diff.d.ts.map +0 -1
  492. package/dist/_shared/scope-resolution/shadow/diff.js +0 -79
  493. package/dist/_shared/scope-resolution/shadow/diff.js.map +0 -1
  494. package/dist/core/ingestion/ast-cache.d.ts +0 -26
  495. package/dist/core/ingestion/ast-cache.js +0 -48
  496. package/dist/core/ingestion/heritage-extractors/configs/go.d.ts +0 -13
  497. package/dist/core/ingestion/heritage-extractors/configs/go.js +0 -20
  498. package/dist/core/ingestion/heritage-extractors/configs/ruby.d.ts +0 -18
  499. package/dist/core/ingestion/heritage-extractors/configs/ruby.js +0 -65
  500. package/dist/core/ingestion/heritage-extractors/generic.d.ts +0 -23
  501. package/dist/core/ingestion/heritage-extractors/generic.js +0 -47
  502. package/dist/core/ingestion/heritage-processor.d.ts +0 -54
  503. package/dist/core/ingestion/heritage-processor.js +0 -367
  504. package/dist/core/ingestion/heritage-types.d.ts +0 -73
  505. package/dist/core/ingestion/heritage-types.js +0 -2
  506. package/dist/core/ingestion/import-processor.d.ts +0 -23
  507. package/dist/core/ingestion/import-processor.js +0 -377
  508. package/dist/core/ingestion/model/heritage-map.d.ts +0 -105
  509. package/dist/core/ingestion/model/heritage-map.js +0 -294
  510. package/dist/core/ingestion/model/resolution-context.d.ts +0 -93
  511. package/dist/core/ingestion/model/resolution-context.js +0 -337
  512. package/dist/core/ingestion/named-bindings/csharp.d.ts +0 -3
  513. package/dist/core/ingestion/named-bindings/csharp.js +0 -37
  514. package/dist/core/ingestion/named-bindings/java.d.ts +0 -3
  515. package/dist/core/ingestion/named-bindings/java.js +0 -29
  516. package/dist/core/ingestion/named-bindings/kotlin.d.ts +0 -3
  517. package/dist/core/ingestion/named-bindings/kotlin.js +0 -36
  518. package/dist/core/ingestion/named-bindings/php.d.ts +0 -3
  519. package/dist/core/ingestion/named-bindings/php.js +0 -61
  520. package/dist/core/ingestion/named-bindings/python.d.ts +0 -3
  521. package/dist/core/ingestion/named-bindings/python.js +0 -49
  522. package/dist/core/ingestion/named-bindings/rust.d.ts +0 -3
  523. package/dist/core/ingestion/named-bindings/rust.js +0 -66
  524. package/dist/core/ingestion/named-bindings/types.d.ts +0 -16
  525. package/dist/core/ingestion/named-bindings/types.js +0 -6
  526. package/dist/core/ingestion/named-bindings/typescript.d.ts +0 -3
  527. package/dist/core/ingestion/named-bindings/typescript.js +0 -58
  528. package/dist/core/ingestion/pipeline-phases/cross-file-impl.d.ts +0 -17
  529. package/dist/core/ingestion/pipeline-phases/cross-file-impl.js +0 -209
  530. package/dist/core/ingestion/pipeline-phases/orm-extraction.d.ts +0 -22
  531. package/dist/core/ingestion/pipeline-phases/orm-extraction.js +0 -92
  532. package/dist/core/ingestion/pipeline-phases/wildcard-synthesis.d.ts +0 -70
  533. package/dist/core/ingestion/pipeline-phases/wildcard-synthesis.js +0 -312
  534. package/dist/core/ingestion/registry-primary-flag.d.ts +0 -89
  535. package/dist/core/ingestion/registry-primary-flag.js +0 -122
  536. package/dist/core/ingestion/shadow-harness.d.ts +0 -113
  537. package/dist/core/ingestion/shadow-harness.js +0 -148
  538. package/dist/core/ingestion/utils/ruby-self-call.d.ts +0 -52
  539. package/dist/core/ingestion/utils/ruby-self-call.js +0 -59
  540. package/scripts/ci-list-migrated-languages.ts +0 -24
  541. package/scripts/run-parity.ts +0 -128
@@ -1,2523 +1,162 @@
1
- import { CLASS_TYPES, CALL_TARGET_TYPES, lookupMethodByOwnerWithMRO } from './model/index.js';
2
1
  /**
3
- * DAG stage 4 fallback: used when `selectDispatch` is absent or returns null.
4
- * Preserves pre-DAG dispatch semantics:
5
- * - 'constructor' → constructor branch
6
- * - 'free' → free branch (admits class-target fast path)
7
- * - 'member' or undefined → owner-scoped branch
2
+ * Route / fetch edge emission + exported-type-map helpers.
8
3
  *
9
- * `undefined` callForm MUST route through owner-scoped (not free) so bare
10
- * identifiers without a classified shape do NOT trigger `resolveFreeCall`'s
11
- * class-target fast path. Without a `receiverTypeName`, the owner-scoped
12
- * branch falls through to `resolveModuleAliasedCall` + `singleCandidate`,
13
- * matching legacy behavior where non-callable symbols (Class, Interface)
14
- * null-route instead of producing spurious Constructor edges.
4
+ * The legacy call-resolution DAG that previously lived here (per-file type
5
+ * inference receiver inference dispatch selection MRO walk over the
6
+ * legacy heritage map) was deleted in RING4-1 (#942): all languages now resolve
7
+ * calls through the scope-resolution registry pipeline. What remains are the
8
+ * language-agnostic edge emitters that are NOT part of call resolution:
9
+ *
10
+ * - `processRoutesFromExtracted` — CALLS edges from framework routes
11
+ * (e.g. Laravel) to their controller methods.
12
+ * - `processNextjsFetchRoutes` / `extractConsumerAccessedKeys` — FETCHES edges
13
+ * from `fetch()` calls to Next.js Route nodes.
14
+ * - `buildExportedTypeMapFromGraph` — exported symbol → return/declared type
15
+ * map, consumed by the cross-file enrichment pass.
15
16
  */
16
- const defaultDispatchDecision = (callForm) => {
17
- if (callForm === 'constructor')
18
- return { primary: 'constructor' };
19
- if (callForm === 'free')
20
- return { primary: 'free' };
21
- return { primary: 'owner-scoped' };
22
- };
23
- import Parser from 'tree-sitter';
24
- import { TIER_CONFIDENCE } from './model/resolution-context.js';
25
- import { isLanguageAvailable, loadParser, loadLanguage } from '../tree-sitter/parser-loader.js';
26
- import { getProvider } from './languages/index.js';
27
17
  import { generateId } from '../../lib/utils.js';
28
- import { getLanguageFromFilename, SupportedLanguages } from '../../_shared/index.js';
29
- import { isRegistryPrimary } from './registry-primary-flag.js';
30
- import { isVerboseIngestionEnabled } from './utils/verbose.js';
31
- import { deferredCallFileSlowMs, deferredCallLogEveryN, getDeferredProfileDroppedCount, isDeferredResolutionProfileEnabled, logDeferredProfile, profileElapsedMs, resetDeferredProfileDroppedCount, startTimer, } from './utils/deferred-resolution-profile.js';
32
18
  import { yieldToEventLoop } from './utils/event-loop.js';
33
- import { parseSourceSafe } from '../tree-sitter/safe-parse.js';
34
- import { CLASS_CONTAINER_TYPES, FUNCTION_NODE_TYPES, findEnclosingClassInfo, genericFuncName, inferFunctionLabel, } from './utils/ast-helpers.js';
35
- import { typeTagForId, constTagForId, buildCollisionGroups } from './utils/method-props.js';
36
- import { countCallArguments, inferCallForm, extractReceiverName, extractReceiverNode, extractMixedChain, extractCallArgTypes, } from './utils/call-analysis.js';
37
- import { buildTypeEnv, isSubclassOf } from './type-env.js';
38
- import { getTreeSitterBufferSize } from './constants.js';
39
19
  import { normalizeFetchURL, routeMatches } from './route-extractors/nextjs.js';
40
- import { extractTemplateComponents } from './vue-sfc-extractor.js';
41
- import { extractReturnTypeName, stripNullable } from './type-extractors/shared.js';
42
- import { logger } from '../logger.js';
43
- // ── Property-prepass helpers (parity with parse-worker.ts) ──
44
- // These mirror the sequential-path equivalents in parse-worker.ts so the main-
45
- // thread `processCalls` pre-pass produces byte-identical Property nodes/symbols
46
- // to the worker pool. Drift between the two paths breaks the
47
- // `incremental ≡ --force` invariant the moment a repo crosses the worker
48
- // threshold between runs.
49
- /** Walk up to the nearest enclosing class/struct/interface AST node. */
50
- const findEnclosingClassNode = (node) => {
51
- let current = node.parent;
52
- while (current) {
53
- if (CLASS_CONTAINER_TYPES.has(current.type))
54
- return current;
55
- current = current.parent;
56
- }
57
- return null;
58
- };
59
- /** No-op SymbolTable stub for FieldExtractorContext — matches parse-worker. */
60
- const NOOP_SYMBOL_TABLE = {
61
- lookupExact: () => undefined,
62
- lookupExactFull: () => undefined,
63
- lookupExactAll: () => [],
64
- lookupCallableByName: () => [],
65
- getFiles: () => [][Symbol.iterator](),
66
- getStats: () => ({ fileCount: 0 }),
67
- };
68
- /**
69
- * Extract (and cache) field info for a class node. Cache is passed in so it
70
- * stays scoped to a single `processCalls` invocation rather than leaking
71
- * across analyze runs (worker uses module-level caching because each worker
72
- * process is short-lived; the main thread is not).
73
- *
74
- * Cache key is `${filePath}:${classNode.startIndex}` — startIndex alone is a
75
- * per-file byte offset, so almost every Ruby/Python file's leading class lands
76
- * at byte 0 and would collide across files in the shared map.
77
- */
78
- const getFieldInfo = (classNode, provider, context, cache) => {
79
- if (!provider.fieldExtractor)
80
- return undefined;
81
- const cacheKey = `${context.filePath}:${classNode.startIndex}`;
82
- const cached = cache.get(cacheKey);
83
- if (cached)
84
- return cached;
85
- const result = provider.fieldExtractor.extract(classNode, context);
86
- if (!result?.fields?.length)
87
- return undefined;
88
- const map = new Map();
89
- for (const field of result.fields)
90
- map.set(field.name, field);
91
- cache.set(cacheKey, map);
92
- return map;
93
- };
94
- /**
95
- * Type labels treated as class-like **method-dispatch receivers** by the call
96
- * resolver — the set walked by the MRO / heritage path for member and static
97
- * method calls.
98
- *
99
- * Derived from `CLASS_TYPES` (the heritage-index set in symbol-table) plus
100
- * `Impl` — Rust `impl` blocks are the definition site of methods for a struct
101
- * and must be walkable as receiver-type candidates even though they are not
102
- * indexed by `lookupClassByName` (which keys off struct/trait names). Keeping
103
- * this set a strict superset of `CLASS_TYPES` guarantees that anything
104
- * reachable via `lookupClassByName` also passes this filter, so the two call
105
- * paths cannot diverge silently.
106
- *
107
- * `Interface` is included even though interfaces cannot be directly
108
- * instantiated in Java/C#/TypeScript: the resolver still needs to reach
109
- * interface nodes for static-method dispatch (`Interface.staticMethod()`) and
110
- * default-method resolution via the MRO walker.
111
- *
112
- * **Do not reuse this set for constructor-fallback filtering.** Constructors
113
- * can only instantiate a narrower subset — see `INSTANTIABLE_CLASS_TYPES`
114
- * below. `resolveStaticCall`'s step-5 class-node fallback uses the narrower
115
- * set to prevent false `CALLS` edges from constructor-shaped calls to
116
- * `Interface`, `Trait`, or `Impl` nodes.
117
- */
118
- const CLASS_LIKE_TYPES = new Set([...CLASS_TYPES, 'Impl']);
119
- /**
120
- * Type labels that can be the target of a constructor-shaped call when no
121
- * explicit `Constructor` symbol is indexed — the "return the type itself as
122
- * the call target" fallback set.
123
- *
124
- * Strict subset of both `CLASS_LIKE_TYPES` and `CONSTRUCTOR_TARGET_TYPES`.
125
- * Excludes:
126
- * - `Interface` / `Trait` — not instantiable by definition in any
127
- * supported language.
128
- * - `Impl` — Rust `impl` blocks are method-definition containers, not
129
- * the type itself; the owning `Struct` is the correct target.
130
- * - `Enum` — excluded pending language-specific support with motivating
131
- * test fixtures (matches `CONSTRUCTOR_TARGET_TYPES`).
132
- *
133
- * Used exclusively by `resolveStaticCall`'s step-5 class-node fallback.
134
- * Keep in sync with `CONSTRUCTOR_TARGET_TYPES` (which additionally contains
135
- * `'Constructor'` for explicit-constructor-node filtering) when extending.
136
- */
137
- const INSTANTIABLE_CLASS_TYPES = new Set(['Class', 'Struct', 'Record']);
20
+ import { extractReturnTypeName } from './type-extractors/shared.js';
138
21
  const MAX_EXPORTS_PER_FILE = 500;
139
22
  const MAX_TYPE_NAME_LENGTH = 256;
140
- /** Build a map of imported callee names return types for cross-file call-result binding.
141
- * Consulted ONLY when SymbolTable has no unambiguous local match (local-first principle).
142
- *
143
- * Overlapping mechanism (1 of 3): this is the SymbolTable-backed path.
144
- * See also:
145
- * 2. collectExportedBindings (~line 168) / enrichExportedTypeMap — TypeEnv + graph isExported
146
- * 3. Phase 9 fallback in verifyConstructorBindings (~line 563) — namedImportMap + BindingAccumulator
147
- * A future cleanup should merge these into a single resolution pass. */
148
- export function buildImportedReturnTypes(filePath, namedImportMap, symbolTable) {
149
- const result = new Map();
150
- const fileImports = namedImportMap.get(filePath);
151
- if (!fileImports)
152
- return result;
153
- for (const [localName, binding] of fileImports) {
154
- const def = symbolTable.lookupExactFull(binding.sourcePath, binding.exportedName);
155
- if (!def?.returnType)
156
- continue;
157
- const simpleReturn = extractReturnTypeName(def.returnType);
158
- if (simpleReturn)
159
- result.set(localName, simpleReturn);
160
- }
161
- return result;
162
- }
163
- /** Build cross-file RAW return types for imported callables.
164
- * Unlike buildImportedReturnTypes (which stores extractReturnTypeName output),
165
- * this stores the raw declared return type string (e.g., 'User[]', 'List<User>').
166
- * Used by lookupRawReturnType for for-loop element extraction via extractElementTypeFromString. */
167
- export function buildImportedRawReturnTypes(filePath, namedImportMap, symbolTable) {
168
- const result = new Map();
169
- const fileImports = namedImportMap.get(filePath);
170
- if (!fileImports)
171
- return result;
172
- for (const [localName, binding] of fileImports) {
173
- const def = symbolTable.lookupExactFull(binding.sourcePath, binding.exportedName);
174
- if (!def?.returnType)
175
- continue;
176
- result.set(localName, def.returnType);
177
- }
178
- return result;
179
- }
180
- /** Collect resolved type bindings for exported file-scope symbols.
181
- * Uses graph node isExported flag — does NOT require isExported on SymbolDefinition.
182
- *
183
- * **Counterpart**: the worker path populates `exportedTypeMap` via the
184
- * accumulator enrichment loop in `pipeline.ts` (search for "Worker path
185
- * quality enrichment"). Both sites populate the same map with subtly
186
- * different export-check semantics — this site uses SymbolTable +
187
- * graph lookup, the worker loop uses three-candidate-ID graph lookup.
188
- * They must stay in sync until unified. If you edit one, check the other.
189
- *
190
- * Overlapping mechanism (2 of 3): this is the TypeEnv + graph isExported path.
191
- * See also:
192
- * 1. buildImportedReturnTypes (~line 109) — namedImportMap + SymbolTable
193
- * 3. Phase 9 fallback in verifyConstructorBindings (~line 563) — namedImportMap + BindingAccumulator
194
- * A future cleanup should merge these into a single resolution pass. */
195
- function collectExportedBindings(typeEnv, filePath, symbolTable, graph) {
196
- const fileScope = typeEnv.fileScope();
197
- if (!fileScope || fileScope.size === 0)
198
- return null;
199
- const exported = new Map();
200
- for (const [varName, typeName] of fileScope) {
201
- if (exported.size >= MAX_EXPORTS_PER_FILE)
202
- break;
203
- if (!typeName || typeName.length > MAX_TYPE_NAME_LENGTH)
204
- continue;
205
- const nodeId = symbolTable.lookupExact(filePath, varName);
206
- if (!nodeId)
207
- continue;
208
- const node = graph.getNode(nodeId);
209
- if (node?.properties?.isExported) {
210
- exported.set(varName, typeName);
211
- }
212
- }
213
- return exported.size > 0 ? exported : null;
214
- }
215
- /** Build ExportedTypeMap from graph nodes — used for worker path where TypeEnv
216
- * is not available in the main thread. Collects returnType/declaredType from
217
- * exported symbols that have callables with known return types. */
23
+ /** Record one exported graph node into the incremental ExportedTypeMap. */
24
+ export const accumulateExportedTypesFromParsedNode = (result, node, symbolTable) => {
25
+ if (!node.properties?.isExported)
26
+ return;
27
+ if (!node.properties?.filePath || !node.properties?.name)
28
+ return;
29
+ const filePath = node.properties.filePath;
30
+ const name = node.properties.name;
31
+ if (!name || name.length > MAX_TYPE_NAME_LENGTH)
32
+ return;
33
+ const defs = symbolTable.lookupExactAll(filePath, name);
34
+ const def = defs.find((d) => d.nodeId === node.id) ?? defs[0];
35
+ if (!def)
36
+ return;
37
+ const typeName = def.returnType ?? def.declaredType;
38
+ if (!typeName || typeName.length > MAX_TYPE_NAME_LENGTH)
39
+ return;
40
+ const simpleType = extractReturnTypeName(typeName) ?? typeName;
41
+ if (!simpleType)
42
+ return;
43
+ let fileExports = result.get(filePath);
44
+ if (!fileExports) {
45
+ fileExports = new Map();
46
+ result.set(filePath, fileExports);
47
+ }
48
+ if (fileExports.size < MAX_EXPORTS_PER_FILE) {
49
+ fileExports.set(name, simpleType);
50
+ }
51
+ };
52
+ /** Build ExportedTypeMap from graph nodes — used for the worker path where the
53
+ * sequential TypeEnv is not available in the main thread. Collects
54
+ * returnType/declaredType from exported symbols with known types. */
218
55
  export function buildExportedTypeMapFromGraph(graph, symbolTable) {
219
56
  const result = new Map();
220
57
  graph.forEachNode((node) => {
221
- if (!node.properties?.isExported)
222
- return;
223
- if (!node.properties?.filePath || !node.properties?.name)
224
- return;
225
- const filePath = node.properties.filePath;
226
- const name = node.properties.name;
227
- if (!name || name.length > MAX_TYPE_NAME_LENGTH)
228
- return;
229
- // For callable symbols, use returnType; for properties/variables, use declaredType.
230
- // Use lookupExactAll + nodeId match to handle same-name methods in different classes.
231
- const defs = symbolTable.lookupExactAll(filePath, name);
232
- const def = defs.find((d) => d.nodeId === node.id) ?? defs[0];
233
- if (!def)
234
- return;
235
- const typeName = def.returnType ?? def.declaredType;
236
- if (!typeName || typeName.length > MAX_TYPE_NAME_LENGTH)
237
- return;
238
- // Extract simple type name (strip Promise<>, etc.) — reuse shared utility
239
- const simpleType = extractReturnTypeName(typeName) ?? typeName;
240
- if (!simpleType)
241
- return;
242
- let fileExports = result.get(filePath);
243
- if (!fileExports) {
244
- fileExports = new Map();
245
- result.set(filePath, fileExports);
246
- }
247
- if (fileExports.size < MAX_EXPORTS_PER_FILE) {
248
- fileExports.set(name, simpleType);
249
- }
58
+ accumulateExportedTypesFromParsedNode(result, node, symbolTable);
250
59
  });
251
60
  return result;
252
61
  }
253
- /** Seed cross-file receiver types into pre-extracted call records.
254
- * Fills missing receiverTypeName for single-hop imported variables
255
- * using ExportedTypeMap + namedImportMap — zero disk I/O, zero AST re-parsing.
256
- * Mutates calls in-place. Runs BEFORE processCallsFromExtracted. */
257
- export function seedCrossFileReceiverTypes(calls, namedImportMap, exportedTypeMap) {
258
- if (namedImportMap.size === 0 || exportedTypeMap.size === 0) {
259
- return { enrichedCount: 0 };
260
- }
261
- let enrichedCount = 0;
262
- for (const call of calls) {
263
- if (call.receiverTypeName || !call.receiverName)
264
- continue;
265
- if (call.callForm !== 'member')
266
- continue;
267
- const fileImports = namedImportMap.get(call.filePath);
268
- if (!fileImports)
269
- continue;
270
- const binding = fileImports.get(call.receiverName);
271
- if (!binding)
272
- continue;
273
- const upstream = exportedTypeMap.get(binding.sourcePath);
274
- if (!upstream)
275
- continue;
276
- const type = upstream.get(binding.exportedName);
277
- if (type) {
278
- call.receiverTypeName = type;
279
- enrichedCount++;
280
- }
281
- }
282
- return { enrichedCount };
283
- }
284
- // Stdlib methods that preserve the receiver's type identity. When TypeEnv already
285
- // strips nullable wrappers (Option<User> → User), these chain steps are no-ops
286
- // for type resolution — the current type passes through unchanged.
287
- const TYPE_PRESERVING_METHODS = new Set([
288
- 'unwrap',
289
- 'expect',
290
- 'unwrap_or',
291
- 'unwrap_or_default',
292
- 'unwrap_or_else', // Rust Option/Result
293
- 'clone',
294
- 'to_owned',
295
- 'as_ref',
296
- 'as_mut',
297
- 'borrow',
298
- 'borrow_mut', // Rust clone/borrow
299
- 'get', // Kotlin/Java Optional.get()
300
- 'orElseThrow', // Java Optional
301
- ]);
302
- /** Cache for method extraction results in findEnclosingFunction fallback path.
303
- * Keyed by classNode.id to avoid re-extracting the same class body per call site.
304
- * Cleared between files at line ~611 in the processCalls file loop. */
305
- const enclosingFnExtractCache = new Map();
306
- /**
307
- * Walk up the AST from a node to find the enclosing function/method.
308
- * Returns null if the call is at module/file level (top-level code).
309
- */
310
- const findEnclosingFunction = (node, filePath, ctx, provider) => {
311
- let current = node.parent;
312
- while (current) {
313
- if (FUNCTION_NODE_TYPES.has(current.type)) {
314
- const efnResult = provider.methodExtractor?.extractFunctionName?.(current);
315
- const funcName = efnResult?.funcName ?? genericFuncName(current);
316
- const label = efnResult?.label ?? inferFunctionLabel(current.type);
317
- if (funcName) {
318
- const resolved = ctx.resolve(funcName, filePath);
319
- if (resolved?.tier === 'same-file' && resolved.candidates.length > 0) {
320
- // Disambiguate by enclosing class when multiple candidates
321
- if (resolved.candidates.length === 1) {
322
- return resolved.candidates[0].nodeId;
323
- }
324
- const classInfo = findEnclosingClassInfo(current, filePath);
325
- if (classInfo) {
326
- const classMatches = resolved.candidates.filter((c) => c.ownerId === classInfo.classId);
327
- // Unique class match — return it (no same-arity ambiguity)
328
- if (classMatches.length === 1)
329
- return classMatches[0].nodeId;
330
- // Multiple same-class candidates (same-arity overloads) — fall through
331
- // to the fallback path which computes the exact ID with type-hash.
332
- if (classMatches.length > 1) {
333
- /* fall through to manual ID construction below */
334
- }
335
- else {
336
- // No class match — return first candidate as before
337
- return resolved.candidates[0].nodeId;
338
- }
339
- }
340
- else {
341
- return resolved.candidates[0].nodeId;
342
- }
343
- }
344
- // Fallback: qualify the generated ID to match definition-phase node IDs
345
- let finalLabel = label;
346
- if (provider.labelOverride) {
347
- const override = provider.labelOverride(current, label);
348
- if (override !== null)
349
- finalLabel = override;
350
- }
351
- const classInfo2 = findEnclosingClassInfo(current, filePath);
352
- const qualifiedName = classInfo2 ? `${classInfo2.className}.${funcName}` : funcName;
353
- // Include #<arity> and ~typeTag suffix to match definition-phase Method/Constructor IDs.
354
- const language = getLanguageFromFilename(filePath);
355
- let arity;
356
- let encTypeTag = '';
357
- if ((finalLabel === 'Method' || finalLabel === 'Constructor') &&
358
- provider.methodExtractor &&
359
- language) {
360
- // Get class method map (cached per classNode.id) and look up current method
361
- // by funcName:line. This avoids per-call-site extractFromNode AST walks.
362
- let classNode = current.parent;
363
- while (classNode && !provider.methodExtractor.isTypeDeclaration(classNode)) {
364
- classNode = classNode.parent;
365
- }
366
- let info;
367
- if (classNode) {
368
- let extracted = enclosingFnExtractCache.get(classNode.id);
369
- if (extracted === undefined) {
370
- extracted =
371
- provider.methodExtractor.extract(classNode, { filePath, language }) ?? null;
372
- enclosingFnExtractCache.set(classNode.id, extracted);
373
- }
374
- if (extracted?.methods?.length) {
375
- const defLine = current.startPosition.row + 1;
376
- info = extracted.methods.find((m) => m.name === funcName && m.line === defLine);
377
- if (info) {
378
- arity = info.parameters.some((p) => p.isVariadic)
379
- ? undefined
380
- : info.parameters.length;
381
- }
382
- if (arity !== undefined && info) {
383
- const methodMap = new Map();
384
- for (const m of extracted.methods)
385
- methodMap.set(`${m.name}:${m.line}`, m);
386
- const groups = buildCollisionGroups(methodMap);
387
- encTypeTag =
388
- typeTagForId(methodMap, funcName, arity, info, language, groups) +
389
- constTagForId(methodMap, funcName, arity, info, groups);
390
- }
391
- }
392
- }
393
- // Fallback: extractFromNode for top-level methods without a class
394
- if (!info && provider.methodExtractor.extractFromNode) {
395
- const nodeInfo = provider.methodExtractor.extractFromNode(current, {
396
- filePath,
397
- language,
398
- });
399
- if (nodeInfo) {
400
- arity = nodeInfo.parameters.some((p) => p.isVariadic)
401
- ? undefined
402
- : nodeInfo.parameters.length;
403
- }
404
- }
405
- }
406
- const arityTag = arity !== undefined ? `#${arity}${encTypeTag}` : '';
407
- return generateId(finalLabel, `${filePath}:${qualifiedName}${arityTag}`);
408
- }
409
- }
410
- // Language-specific enclosing function resolution (e.g., Dart where
411
- // function_body is a sibling of function_signature, not a child).
412
- if (provider.enclosingFunctionFinder) {
413
- const customResult = provider.enclosingFunctionFinder(current);
414
- if (customResult) {
415
- const resolved = ctx.resolve(customResult.funcName, filePath);
416
- if (resolved?.tier === 'same-file' && resolved.candidates.length > 0) {
417
- if (resolved.candidates.length === 1) {
418
- return resolved.candidates[0].nodeId;
419
- }
420
- const classInfo = findEnclosingClassInfo(current.previousSibling ?? current, filePath);
421
- if (classInfo) {
422
- const classMatches = resolved.candidates.filter((c) => c.ownerId === classInfo.classId);
423
- if (classMatches.length === 1)
424
- return classMatches[0].nodeId;
425
- if (classMatches.length > 1) {
426
- /* fall through to manual ID construction below */
427
- }
428
- else {
429
- return resolved.candidates[0].nodeId;
430
- }
431
- }
432
- else {
433
- return resolved.candidates[0].nodeId;
434
- }
435
- }
436
- let finalLabel = customResult.label;
437
- if (provider.labelOverride) {
438
- const override = provider.labelOverride(current.previousSibling, finalLabel);
439
- if (override !== null)
440
- finalLabel = override;
441
- }
442
- const classInfo2 = findEnclosingClassInfo(current.previousSibling ?? current, filePath);
443
- const qualifiedName = classInfo2
444
- ? `${classInfo2.className}.${customResult.funcName}`
445
- : customResult.funcName;
446
- // Include #<arity> and ~typeTag suffix to match definition-phase Method/Constructor IDs.
447
- const sigNode = current.previousSibling ?? current;
448
- const language2 = getLanguageFromFilename(filePath);
449
- let arity2;
450
- let encTypeTag2 = '';
451
- if ((finalLabel === 'Method' || finalLabel === 'Constructor') &&
452
- provider.methodExtractor &&
453
- language2) {
454
- let classNode2 = (current.previousSibling ?? current).parent;
455
- while (classNode2 && !provider.methodExtractor.isTypeDeclaration(classNode2)) {
456
- classNode2 = classNode2.parent;
457
- }
458
- let info2;
459
- if (classNode2) {
460
- let extracted2 = enclosingFnExtractCache.get(classNode2.id);
461
- if (extracted2 === undefined) {
462
- extracted2 =
463
- provider.methodExtractor.extract(classNode2, { filePath, language: language2 }) ??
464
- null;
465
- enclosingFnExtractCache.set(classNode2.id, extracted2);
466
- }
467
- if (extracted2?.methods?.length) {
468
- const defLine2 = sigNode.startPosition.row + 1;
469
- info2 = extracted2.methods.find((m) => m.name === customResult.funcName && m.line === defLine2);
470
- if (info2) {
471
- arity2 = info2.parameters.some((p) => p.isVariadic)
472
- ? undefined
473
- : info2.parameters.length;
474
- }
475
- if (arity2 !== undefined && info2) {
476
- const methodMap = new Map();
477
- for (const m of extracted2.methods)
478
- methodMap.set(`${m.name}:${m.line}`, m);
479
- const groups2 = buildCollisionGroups(methodMap);
480
- encTypeTag2 =
481
- typeTagForId(methodMap, customResult.funcName, arity2, info2, language2, groups2) + constTagForId(methodMap, customResult.funcName, arity2, info2, groups2);
482
- }
483
- }
484
- }
485
- if (!info2 && provider.methodExtractor.extractFromNode) {
486
- const nodeInfo = provider.methodExtractor.extractFromNode(sigNode, {
487
- filePath,
488
- language: language2,
489
- });
490
- if (nodeInfo) {
491
- arity2 = nodeInfo.parameters.some((p) => p.isVariadic)
492
- ? undefined
493
- : nodeInfo.parameters.length;
494
- }
495
- }
496
- }
497
- const arityTag2 = arity2 !== undefined ? `#${arity2}${encTypeTag2}` : '';
498
- return generateId(finalLabel, `${filePath}:${qualifiedName}${arityTag2}`);
499
- }
500
- }
501
- current = current.parent;
502
- }
503
- return null;
504
- };
505
- /**
506
- * Verify constructor bindings against SymbolTable and infer receiver types.
507
- * Shared between sequential (processCalls) and worker (processCallsFromExtracted) paths.
508
- */
509
- const verifyConstructorBindings = (bindings, filePath, ctx, graph, bindingAccumulator) => {
510
- const verified = new Map();
511
- for (const { scope, varName, calleeName, receiverClassName } of bindings) {
512
- const tiered = ctx.resolve(calleeName, filePath);
513
- const isClass = tiered?.candidates.some((def) => def.type === 'Class') ?? false;
514
- if (isClass) {
515
- verified.set(receiverKey(scope, varName), calleeName);
516
- }
517
- else {
518
- let callableDefs = tiered?.candidates.filter((d) => d.type === 'Function' || d.type === 'Method');
519
- // When receiver class is known (e.g. $this->method() in PHP), narrow
520
- // candidates to methods owned by that class to avoid false disambiguation failures.
521
- if (callableDefs && callableDefs.length > 1 && receiverClassName) {
522
- if (graph) {
523
- // Worker path: use graph.getNode (fast, already in-memory)
524
- const narrowed = callableDefs.filter((d) => {
525
- if (!d.ownerId)
526
- return false;
527
- const owner = graph.getNode(d.ownerId);
528
- return owner?.properties.name === receiverClassName;
529
- });
530
- if (narrowed.length > 0)
531
- callableDefs = narrowed;
532
- }
533
- else {
534
- // Sequential path: use ctx.resolve (no graph available)
535
- const classResolved = ctx.resolve(receiverClassName, filePath);
536
- if (classResolved && classResolved.candidates.length > 0) {
537
- const classNodeIds = new Set(classResolved.candidates.map((c) => c.nodeId));
538
- const narrowed = callableDefs.filter((d) => d.ownerId && classNodeIds.has(d.ownerId));
539
- if (narrowed.length > 0)
540
- callableDefs = narrowed;
541
- }
542
- }
543
- }
544
- let typeName;
545
- if (callableDefs && callableDefs.length === 1 && callableDefs[0].returnType) {
546
- typeName = extractReturnTypeName(callableDefs[0].returnType);
547
- }
548
- // Phase 9: BindingAccumulator fallback for cross-file return types.
549
- // Used when the SymbolTable has no return type for a cross-file callee
550
- // (e.g., a return type that TypeEnv resolved via fixpoint in the source
551
- // file but was not stored as a SymbolTable returnType annotation).
552
- // namedImportMap tells us which source file exported the callee so we
553
- // can look up its file-scope binding via the O(1) fileScopeGet method.
554
- //
555
- // Tier gating: only fall back to the accumulator when resolution is
556
- // unambiguously import-scoped or global. When tiered.tier is 'same-file',
557
- // the local definition is authoritative even without a return type
558
- // annotation — using the accumulator here would let an imported callee
559
- // with the same name shadow the local one, producing false CALLS edges.
560
- // When multiple callable candidates exist, the accumulator would pick
561
- // arbitrarily — skip to avoid fabricated edges.
562
- //
563
- // Quality note: worker-path accumulator entries are Tier 0/1 only
564
- // (annotation-declared + same-file constructor inference) — see the
565
- // BindingAccumulator class JSDoc. For large repos where the worker
566
- // path dominates, Phase 9 binding accuracy is structurally lower
567
- // than for sequential-path repos where Tier 2 cross-file propagation
568
- // is available.
569
- //
570
- // Overlapping mechanism note: this is one of three cross-file
571
- // return-type resolution paths in the codebase:
572
- // 1. buildImportedReturnTypes (~line 109) — namedImportMap +
573
- // SymbolTable.lookupExactFull (structure-processor captured)
574
- // 2. collectExportedBindings (~line 168) / enrichExportedTypeMap
575
- // — TypeEnv + graph isExported flag
576
- // 3. This fallback — namedImportMap + BindingAccumulator
577
- // A future cleanup should merge these into a single resolution pass.
578
- const shouldFallback = tiered?.tier !== 'same-file' && (!callableDefs || callableDefs.length <= 1);
579
- if (!typeName && bindingAccumulator && shouldFallback) {
580
- const namedImports = ctx.namedImportMap.get(filePath);
581
- const importBinding = namedImports?.get(calleeName);
582
- if (importBinding) {
583
- const rawType = bindingAccumulator.fileScopeGet(importBinding.sourcePath, importBinding.exportedName);
584
- if (rawType) {
585
- typeName = extractReturnTypeName(rawType);
586
- }
587
- }
588
- }
589
- if (typeName) {
590
- verified.set(receiverKey(scope, varName), typeName);
591
- }
592
- }
593
- }
594
- return verified;
595
- };
596
- /**
597
- * After resolving a call to an interface method, find additional targets
598
- * in classes implementing that interface. Returns implementation method
599
- * results with lower confidence ('interface-dispatch').
600
- */
601
- function findInterfaceDispatchTargets(calledName, receiverTypeName, currentFile, ctx, heritageMap, primaryNodeId) {
602
- const implFiles = heritageMap.getImplementorFiles(receiverTypeName);
603
- if (implFiles.size === 0)
604
- return [];
605
- const typeResolved = ctx.resolve(receiverTypeName, currentFile);
606
- if (!typeResolved)
607
- return [];
608
- if (!typeResolved.candidates.some((c) => c.type === 'Interface'))
609
- return [];
610
- const results = [];
611
- for (const implFile of implFiles) {
612
- const methods = ctx.model.symbols.lookupExactAll(implFile, calledName);
613
- for (const method of methods) {
614
- if (method.nodeId !== primaryNodeId) {
615
- results.push({
616
- nodeId: method.nodeId,
617
- confidence: 0.7,
618
- reason: 'interface-dispatch',
619
- });
620
- }
621
- }
622
- }
623
- return results;
624
- }
625
- export const processCalls = async (graph, files, astCache, ctx, onProgress, exportedTypeMap,
626
- /** Phase 14: pre-resolved cross-file bindings to seed into buildTypeEnv. Keyed by filePath → Map<localName, typeName>. */
627
- importedBindingsMap,
628
- /** Phase 14 E3: cross-file return types for imported callables. Keyed by filePath → Map<calleeName, returnType>.
629
- * Consulted ONLY when SymbolTable has no unambiguous match (local-first principle). */
630
- importedReturnTypesMap,
631
- /** Phase 14 E3: cross-file RAW return types for for-loop element extraction. Keyed by filePath → Map<calleeName, rawReturnType>. */
632
- importedRawReturnTypesMap, heritageMap, bindingAccumulator,
633
62
  /**
634
- * Optional cache for compiled `Parser.Query` objects keyed by language name.
635
- * When provided, compiled queries are reused across calls instead of being
636
- * re-compiled from the query string for every file. Callers that invoke
637
- * `processCalls` many times with single-file batches (e.g. the cross-file
638
- * propagation phase) should pass a long-lived map here to avoid O(N)
639
- * query recompilation overhead.
640
- */
641
- compiledQueryCache) => {
642
- const parser = await loadParser();
643
- const collectedHeritage = [];
644
- const pendingWrites = [];
645
- // Phase P cross-file: accumulate heritage across files for cross-file isSubclassOf.
646
- // Used as a secondary check when per-file parentMap lacks the relationship — helps
647
- // when the heritage-declaring file is processed before the call site file.
648
- // For remaining cases (reverse file order), the SymbolTable class-type fallback applies.
649
- const globalParentMap = new Map();
650
- const globalParentSeen = new Map();
651
- const logSkipped = isVerboseIngestionEnabled();
652
- const skippedByLang = logSkipped ? new Map() : null;
653
- const prepared = [];
654
- for (let i = 0; i < files.length; i++) {
655
- const file = files[i];
656
- if (i % 20 === 0)
657
- await yieldToEventLoop();
658
- const language = getLanguageFromFilename(file.path);
659
- if (!language)
660
- continue;
661
- // Registry-primary gate: scope-based phase owns CALLS for this lang.
662
- if (isRegistryPrimary(language))
663
- continue;
664
- if (!isLanguageAvailable(language)) {
665
- if (skippedByLang) {
666
- skippedByLang.set(language, (skippedByLang.get(language) ?? 0) + 1);
667
- }
668
- continue;
669
- }
670
- const provider = getProvider(language);
671
- const queryStr = provider.treeSitterQueries;
672
- if (!queryStr)
673
- continue;
674
- await loadLanguage(language, file.path);
675
- let tree = astCache.get(file.path);
676
- if (!tree) {
677
- const parseContent = provider.preprocessSource?.(file.content, file.path) ?? file.content;
678
- try {
679
- tree = parseSourceSafe(parser, parseContent, undefined, {
680
- bufferSize: getTreeSitterBufferSize(parseContent),
681
- });
682
- }
683
- catch (parseError) {
684
- continue;
685
- }
686
- astCache.set(file.path, tree);
687
- }
688
- let matches;
689
- try {
690
- const lang = parser.getLanguage();
691
- let query = compiledQueryCache?.get(language);
692
- if (!query) {
693
- query = new Parser.Query(lang, queryStr);
694
- compiledQueryCache?.set(language, query);
695
- }
696
- matches = query.matches(tree.rootNode);
697
- }
698
- catch (queryError) {
699
- logger.warn({ queryError }, `Query error for ${file.path}:`);
700
- continue;
701
- }
702
- // Extract heritage from query matches to build parentMap for buildTypeEnv.
703
- // Heritage-processor runs in PARALLEL, so graph edges don't exist when buildTypeEnv runs.
704
- const fileParentMap = new Map();
705
- if (provider.heritageExtractor) {
706
- for (const match of matches) {
707
- const captureMap = {};
708
- match.captures.forEach((c) => (captureMap[c.name] = c.node));
709
- if (captureMap['heritage.class']) {
710
- const heritageItems = provider.heritageExtractor.extract(captureMap, {
711
- filePath: file.path,
712
- language,
713
- });
714
- for (const item of heritageItems) {
715
- if (item.kind === 'extends') {
716
- let parents = fileParentMap.get(item.className);
717
- if (!parents) {
718
- parents = [];
719
- fileParentMap.set(item.className, parents);
720
- }
721
- if (!parents.includes(item.parentName))
722
- parents.push(item.parentName);
723
- }
724
- }
725
- }
726
- }
727
- }
728
- const parentMap = fileParentMap;
729
- // Merge per-file heritage into globalParentMap for cross-file isSubclassOf lookups.
730
- for (const [cls, parents] of fileParentMap) {
731
- let global = globalParentMap.get(cls);
732
- let seen = globalParentSeen.get(cls);
733
- if (!global) {
734
- global = [];
735
- globalParentMap.set(cls, global);
736
- }
737
- if (!seen) {
738
- seen = new Set();
739
- globalParentSeen.set(cls, seen);
740
- }
741
- for (const p of parents) {
742
- if (!seen.has(p)) {
743
- seen.add(p);
744
- global.push(p);
745
- }
746
- }
747
- }
748
- const importedBindings = importedBindingsMap?.get(file.path);
749
- const importedReturnTypes = importedReturnTypesMap?.get(file.path);
750
- const importedRawReturnTypes = importedRawReturnTypesMap?.get(file.path);
751
- const typeEnv = buildTypeEnv(tree, language, {
752
- model: ctx.model,
753
- parentMap,
754
- importedBindings,
755
- importedReturnTypes,
756
- importedRawReturnTypes,
757
- enclosingFunctionFinder: provider?.enclosingFunctionFinder,
758
- extractFunctionName: provider?.methodExtractor?.extractFunctionName,
759
- });
760
- if (typeEnv && exportedTypeMap) {
761
- const fileExports = collectExportedBindings(typeEnv, file.path, ctx.model.symbols, graph);
762
- if (fileExports)
763
- exportedTypeMap.set(file.path, fileExports);
764
- }
765
- if (bindingAccumulator) {
766
- typeEnv.flush(file.path, bindingAccumulator);
767
- }
768
- prepared.push({ file, language, provider, tree, matches, parentMap, typeEnv });
769
- }
770
- // ── Property-registration pre-pass ──
771
- // Register all routed properties (e.g. Ruby attr_accessor) BEFORE the
772
- // resolution loop so cross-file field-type lookups (e.g.
773
- // `user.address.save → Address#save`) succeed regardless of file
774
- // processing order. This MUST stay in lockstep with the equivalent
775
- // worker-path block in parse-worker.ts (kind === 'properties') — any
776
- // divergence between the two paths breaks the `incremental ≡ --force`
777
- // invariant once a repo crosses the worker threshold between runs.
778
- const fieldInfoCache = new Map();
779
- for (const { file, language, provider, matches, typeEnv } of prepared) {
780
- const callRouter = provider.callRouter;
781
- if (!callRouter)
782
- continue;
783
- matches.forEach((match) => {
784
- const captureMap = {};
785
- match.captures.forEach((c) => (captureMap[c.name] = c.node));
786
- if (!captureMap['call'])
787
- return;
788
- const callNameNode = captureMap['call.name'];
789
- if (!callNameNode)
790
- return;
791
- const routed = callRouter(callNameNode.text, captureMap['call']);
792
- if (!routed || routed.kind !== 'properties')
793
- return;
794
- const propEnclosingInfo = findEnclosingClassInfo(captureMap['call'], file.path, provider.resolveEnclosingOwner);
795
- const propEnclosingClassId = propEnclosingInfo?.classId ?? null;
796
- // Enrich routed properties with FieldExtractor metadata so types
797
- // discovered from constructor assignments (e.g. `@address = Address.new`)
798
- // are propagated even when the routing payload itself lacks declaredType.
799
- let routedFieldMap;
800
- if (provider.fieldExtractor && typeEnv) {
801
- const classNode = findEnclosingClassNode(captureMap['call']);
802
- if (classNode) {
803
- routedFieldMap = getFieldInfo(classNode, provider, {
804
- typeEnv,
805
- symbolTable: NOOP_SYMBOL_TABLE,
806
- filePath: file.path,
807
- language,
808
- }, fieldInfoCache);
809
- }
810
- }
811
- const fileId = generateId('File', file.path);
812
- for (const item of routed.items) {
813
- const routedFieldInfo = routedFieldMap?.get(item.propName);
814
- const propQualifiedName = propEnclosingInfo
815
- ? `${propEnclosingInfo.className}.${item.propName}`
816
- : item.propName;
817
- const nodeId = generateId('Property', `${file.path}:${propQualifiedName}`);
818
- graph.addNode({
819
- id: nodeId,
820
- label: 'Property',
821
- properties: {
822
- name: item.propName,
823
- filePath: file.path,
824
- startLine: item.startLine,
825
- endLine: item.endLine,
826
- language,
827
- isExported: true,
828
- description: item.accessorType,
829
- ...(item.declaredType
830
- ? { declaredType: item.declaredType }
831
- : routedFieldInfo?.type
832
- ? { declaredType: routedFieldInfo.type }
833
- : {}),
834
- ...(routedFieldInfo?.visibility !== undefined
835
- ? { visibility: routedFieldInfo.visibility }
836
- : {}),
837
- ...(routedFieldInfo?.isStatic !== undefined
838
- ? { isStatic: routedFieldInfo.isStatic }
839
- : {}),
840
- ...(routedFieldInfo?.isReadonly !== undefined
841
- ? { isReadonly: routedFieldInfo.isReadonly }
842
- : {}),
843
- },
844
- });
845
- ctx.model.symbols.add(file.path, item.propName, nodeId, 'Property', {
846
- ...(propEnclosingClassId ? { ownerId: propEnclosingClassId } : {}),
847
- ...(item.declaredType
848
- ? { declaredType: item.declaredType }
849
- : routedFieldInfo?.type
850
- ? { declaredType: routedFieldInfo.type }
851
- : {}),
852
- });
853
- const relId = generateId('DEFINES', `${fileId}->${nodeId}`);
854
- graph.addRelationship({
855
- id: relId,
856
- sourceId: fileId,
857
- targetId: nodeId,
858
- type: 'DEFINES',
859
- confidence: 1.0,
860
- reason: '',
861
- });
862
- if (propEnclosingClassId) {
863
- graph.addRelationship({
864
- id: generateId('HAS_PROPERTY', `${propEnclosingClassId}->${nodeId}`),
865
- sourceId: propEnclosingClassId,
866
- targetId: nodeId,
867
- type: 'HAS_PROPERTY',
868
- confidence: 1.0,
869
- reason: '',
870
- });
871
- }
872
- }
873
- });
874
- }
875
- // ── Resolution loop: verify constructor bindings and resolve calls ──
876
- // The accumulator (if present) is now fully populated from the preparation
877
- // loop above, so verifyConstructorBindings sees all provider bindings
878
- // regardless of file processing order.
879
- for (let i = 0; i < prepared.length; i++) {
880
- const { file, language, provider, tree, matches, parentMap, typeEnv } = prepared[i];
881
- enclosingFnExtractCache.clear();
882
- onProgress?.(i + 1, files.length);
883
- if (i % 20 === 0)
884
- await yieldToEventLoop();
885
- const callRouter = provider.callRouter;
886
- const verifiedReceivers = typeEnv.constructorBindings.length > 0
887
- ? verifyConstructorBindings(typeEnv.constructorBindings, file.path, ctx, undefined, // graph not available on the sequential path here
888
- bindingAccumulator)
889
- : new Map();
890
- const receiverIndex = buildReceiverTypeIndex(verifiedReceivers);
891
- ctx.enableCache(file.path);
892
- const widenCache = new Map();
893
- matches.forEach((match) => {
894
- const captureMap = {};
895
- match.captures.forEach((c) => (captureMap[c.name] = c.node));
896
- // ── Write access: emit ACCESSES {reason: 'write'} for assignments to member fields ──
897
- if (captureMap['assignment'] &&
898
- captureMap['assignment.receiver'] &&
899
- captureMap['assignment.property']) {
900
- const receiverNode = captureMap['assignment.receiver'];
901
- const propertyName = captureMap['assignment.property'].text;
902
- // Resolve receiver type: simple identifier → TypeEnv lookup or class resolution
903
- let receiverTypeName;
904
- const receiverText = receiverNode.text;
905
- if (receiverText && typeEnv) {
906
- receiverTypeName = typeEnv.lookup(receiverText, captureMap['assignment']);
907
- }
908
- // Fall back to verified constructor bindings (mirrors CALLS resolution tier 2)
909
- if (!receiverTypeName && receiverText && receiverIndex.size > 0) {
910
- const enclosing = findEnclosingFunction(captureMap['assignment'], file.path, ctx, provider);
911
- const funcName = enclosing ? extractFuncNameFromSourceId(enclosing) : '';
912
- receiverTypeName = lookupReceiverType(receiverIndex, funcName, receiverText);
913
- }
914
- if (!receiverTypeName && receiverText) {
915
- const resolved = ctx.resolve(receiverText, file.path);
916
- if (resolved?.candidates.some((d) => CLASS_LIKE_TYPES.has(d.type))) {
917
- receiverTypeName = receiverText;
918
- }
919
- }
920
- if (receiverTypeName) {
921
- const enclosing = findEnclosingFunction(captureMap['assignment'], file.path, ctx, provider);
922
- const srcId = enclosing || generateId('File', file.path);
923
- // Defer resolution: Ruby attr_accessor properties are registered during
924
- // this same loop, so cross-file lookups fail if the declaring file hasn't
925
- // been processed yet. Collect now, resolve after all files are done.
926
- pendingWrites.push({
927
- receiverTypeName,
928
- propertyName,
929
- filePath: file.path,
930
- srcId,
931
- line: captureMap['assignment'].startPosition.row + 1,
932
- });
933
- }
934
- // Assignment-only capture (no @call sibling): skip the rest of this
935
- // forEach iteration — this acts as a `continue` in the match loop.
936
- if (!captureMap['call'])
937
- return;
938
- }
939
- if (!captureMap['call'])
940
- return;
941
- const callNode = captureMap['call'];
942
- const callExtractor = provider.callExtractor;
943
- // ── Language-specific call site (e.g. Java :: method references) ──
944
- if (callExtractor) {
945
- const langCallSite = callExtractor.extract(callNode, undefined);
946
- if (langCallSite) {
947
- if (provider.isBuiltInName(langCallSite.calledName))
948
- return;
949
- const sourceId = findEnclosingFunction(callNode, file.path, ctx, provider) ||
950
- generateId('File', file.path);
951
- const receiverName = langCallSite.callForm === 'member' ? langCallSite.receiverName : undefined;
952
- let receiverTypeName = receiverName && typeEnv ? typeEnv.lookup(receiverName, callNode) : undefined;
953
- if (langCallSite.typeAsReceiverHeuristic &&
954
- receiverName !== undefined &&
955
- receiverTypeName === undefined &&
956
- langCallSite.callForm === 'member') {
957
- const c0 = receiverName.charCodeAt(0);
958
- if (c0 >= 65 && c0 <= 90)
959
- receiverTypeName = receiverName;
960
- }
961
- const resolved = resolveCallTarget({
962
- calledName: langCallSite.calledName,
963
- callForm: langCallSite.callForm,
964
- ...(receiverTypeName !== undefined ? { receiverTypeName } : {}),
965
- ...(receiverName !== undefined ? { receiverName } : {}),
966
- }, file.path, ctx, undefined, widenCache, undefined, heritageMap);
967
- if (!resolved)
968
- return;
969
- graph.addRelationship({
970
- id: generateId('CALLS', `${sourceId}:${langCallSite.calledName}->${resolved.nodeId}`),
971
- sourceId,
972
- targetId: resolved.nodeId,
973
- type: 'CALLS',
974
- confidence: resolved.confidence,
975
- reason: resolved.reason,
976
- });
977
- if (heritageMap && langCallSite.callForm === 'member' && receiverTypeName) {
978
- const implTargets = findInterfaceDispatchTargets(langCallSite.calledName, receiverTypeName, file.path, ctx, heritageMap, resolved.nodeId);
979
- for (const impl of implTargets) {
980
- graph.addRelationship({
981
- id: generateId('CALLS', `${sourceId}:${langCallSite.calledName}->${impl.nodeId}`),
982
- sourceId,
983
- targetId: impl.nodeId,
984
- type: 'CALLS',
985
- confidence: impl.confidence,
986
- reason: impl.reason,
987
- });
988
- }
989
- }
990
- return;
991
- }
992
- }
993
- const nameNode = captureMap['call.name'];
994
- if (!nameNode)
995
- return;
996
- const calledName = nameNode.text;
997
- // Check heritage extractor for call-based heritage (e.g., Ruby include/extend/prepend)
998
- if (provider.heritageExtractor?.extractFromCall) {
999
- const heritageItems = provider.heritageExtractor.extractFromCall(calledName, captureMap['call'], { filePath: file.path, language });
1000
- if (heritageItems !== null) {
1001
- for (const item of heritageItems) {
1002
- collectedHeritage.push({
1003
- filePath: file.path,
1004
- className: item.className,
1005
- parentName: item.parentName,
1006
- kind: item.kind,
1007
- });
1008
- }
1009
- return;
1010
- }
1011
- }
1012
- // Dispatch: route language-specific calls (properties, imports)
1013
- // Heritage routing is handled by heritageExtractor.extractFromCall above.
1014
- const routed = callRouter?.(calledName, captureMap['call']);
1015
- if (routed) {
1016
- switch (routed.kind) {
1017
- case 'skip':
1018
- case 'import':
1019
- return;
1020
- case 'properties': {
1021
- // Properties already registered in the pre-pass above.
1022
- // Skip to avoid duplicate nodes/edges.
1023
- return;
1024
- }
1025
- case 'call':
1026
- break;
1027
- }
1028
- }
1029
- if (provider.isBuiltInName(calledName))
1030
- return;
1031
- // --- DAG stage 2-3: classify-form + infer-receiver (shared defaults) ---
1032
- // These stages run the shared inference chain. Language providers can
1033
- // customize infer-receiver (stage 3) via the inferImplicitReceiver hook
1034
- // which runs AFTER this default chain (typed-binding → constructor-map →
1035
- // module-alias → class-as-receiver → mixed-chain), and selectDispatch
1036
- // (stage 4) which picks the resolver branch.
1037
- let callForm = inferCallForm(callNode, nameNode);
1038
- let receiverName = callForm === 'member' ? extractReceiverName(nameNode) : undefined;
1039
- let receiverTypeName = receiverName && typeEnv ? typeEnv.lookup(receiverName, callNode) : undefined;
1040
- let receiverSource = receiverTypeName ? 'typed-binding' : 'none';
1041
- // Phase P: virtual dispatch override — when the declared type is a base class but
1042
- // the constructor created a known subclass, prefer the more specific type.
1043
- // Checks per-file parentMap first, then falls back to globalParentMap for
1044
- // cross-file heritage (e.g. Dog extends Animal declared in a different file).
1045
- // Reconstructs the exact scope key (funcName@startIndex\0varName) from the
1046
- // enclosing function AST node for a correct, O(1) map lookup.
1047
- if (receiverTypeName && receiverName && typeEnv && typeEnv.constructorTypeMap.size > 0) {
1048
- // Reconstruct scope key to match constructorTypeMap's scope\0varName format
1049
- let scope = '';
1050
- let p = callNode.parent;
1051
- while (p) {
1052
- if (FUNCTION_NODE_TYPES.has(p.type)) {
1053
- const funcName = provider.methodExtractor?.extractFunctionName?.(p)?.funcName ?? genericFuncName(p);
1054
- if (funcName) {
1055
- scope = `${funcName}@${p.startIndex}`;
1056
- break;
1057
- }
1058
- }
1059
- p = p.parent;
1060
- }
1061
- const ctorType = typeEnv.constructorTypeMap.get(`${scope}\0${receiverName}`);
1062
- if (ctorType && ctorType !== receiverTypeName) {
1063
- // Verify subclass relationship: per-file parentMap first, then cross-file
1064
- // globalParentMap, then fall back to SymbolTable class verification.
1065
- // The SymbolTable fallback handles cross-file cases where heritage is declared
1066
- // in a file not yet processed (e.g. Dog extends Animal in models/Dog.kt when
1067
- // processing services/App.kt). Since constructorTypeMap only records entries
1068
- // when a type annotation AND constructor are both present (val x: Base = Sub()),
1069
- // confirming both are class-like types is sufficient — the original code would
1070
- // not compile if Sub didn't extend Base.
1071
- if (isSubclassOf(ctorType, receiverTypeName, parentMap) ||
1072
- isSubclassOf(ctorType, receiverTypeName, globalParentMap) ||
1073
- (ctx.model.types.lookupClassByName(ctorType).length > 0 &&
1074
- ctx.model.types.lookupClassByName(receiverTypeName).length > 0)) {
1075
- receiverTypeName = ctorType;
1076
- receiverSource = 'constructor-map';
1077
- }
1078
- }
1079
- }
1080
- // Fall back to verified constructor bindings for return type inference
1081
- if (!receiverTypeName && receiverName && receiverIndex.size > 0) {
1082
- const enclosingFunc = findEnclosingFunction(callNode, file.path, ctx, provider);
1083
- const funcName = enclosingFunc ? extractFuncNameFromSourceId(enclosingFunc) : '';
1084
- receiverTypeName = lookupReceiverType(receiverIndex, funcName, receiverName);
1085
- if (receiverTypeName)
1086
- receiverSource = 'constructor-map';
1087
- }
1088
- // Fall back to class-as-receiver for static method calls (e.g. UserService.find_user(),
1089
- // Greetable.format()). When the receiver name is not a variable in TypeEnv but
1090
- // resolves to a class-like symbol (Class / Interface / Struct / Enum / Trait) via
1091
- // tiered resolution, use it directly as the receiver type. `Trait` is included so
1092
- // Ruby module class-method calls flow through the class-as-receiver path and reach
1093
- // the `selectDispatch` hook's singleton branch.
1094
- if (!receiverTypeName && receiverName && callForm === 'member') {
1095
- const typeResolved = ctx.resolve(receiverName, file.path);
1096
- if (typeResolved &&
1097
- typeResolved.candidates.some((d) => d.type === 'Class' ||
1098
- d.type === 'Interface' ||
1099
- d.type === 'Struct' ||
1100
- d.type === 'Enum' ||
1101
- d.type === 'Trait')) {
1102
- receiverTypeName = receiverName;
1103
- receiverSource = 'class-as-receiver';
1104
- }
1105
- }
1106
- // Hoist sourceId so it's available for ACCESSES edge emission during chain walk.
1107
- const enclosingFuncId = findEnclosingFunction(callNode, file.path, ctx, provider);
1108
- const sourceId = enclosingFuncId || generateId('File', file.path);
1109
- // Fall back to mixed chain resolution when the receiver is a complex expression
1110
- // (field chain, call chain, or interleaved — e.g. user.address.city.save() or
1111
- // svc.getUser().address.save()). Handles all cases with a single unified walk.
1112
- if (callForm === 'member' && !receiverTypeName && !receiverName) {
1113
- const receiverNode = extractReceiverNode(nameNode);
1114
- if (receiverNode) {
1115
- const extracted = extractMixedChain(receiverNode);
1116
- if (extracted && extracted.chain.length > 0) {
1117
- let currentType = extracted.baseReceiverName && typeEnv
1118
- ? typeEnv.lookup(extracted.baseReceiverName, callNode)
1119
- : undefined;
1120
- if (!currentType && extracted.baseReceiverName && receiverIndex.size > 0) {
1121
- const funcName = enclosingFuncId ? extractFuncNameFromSourceId(enclosingFuncId) : '';
1122
- currentType = lookupReceiverType(receiverIndex, funcName, extracted.baseReceiverName);
1123
- }
1124
- if (!currentType && extracted.baseReceiverName) {
1125
- const cr = ctx.resolve(extracted.baseReceiverName, file.path);
1126
- if (cr?.candidates.some((d) => d.type === 'Class' ||
1127
- d.type === 'Interface' ||
1128
- d.type === 'Struct' ||
1129
- d.type === 'Enum')) {
1130
- currentType = extracted.baseReceiverName;
1131
- }
1132
- }
1133
- if (currentType) {
1134
- receiverTypeName = walkMixedChain(extracted.chain, currentType, file.path, ctx, makeAccessEmitter(graph, sourceId), heritageMap);
1135
- if (receiverTypeName)
1136
- receiverSource = 'mixed-chain';
1137
- }
1138
- }
1139
- }
1140
- }
1141
- // --- DAG stage 3: infer-receiver (provider hook) ---
1142
- // Synthesize implicit receivers for languages that omit them (e.g., Ruby bare-call).
1143
- // This hook runs AFTER the shared inference chain so explicit receivers /
1144
- // typed bindings always take precedence. Output (if non-null) overlays onto
1145
- // the ReceiverEnriched for the next stage.
1146
- let dispatchHint;
1147
- if (provider.inferImplicitReceiver) {
1148
- const override = provider.inferImplicitReceiver({
1149
- calledName,
1150
- callForm,
1151
- receiverName,
1152
- receiverTypeName,
1153
- callNode,
1154
- filePath: file.path,
1155
- });
1156
- if (override) {
1157
- callForm = override.callForm;
1158
- receiverName = override.receiverName;
1159
- receiverTypeName = override.receiverTypeName;
1160
- receiverSource = override.receiverSource;
1161
- dispatchHint = override.hint;
1162
- }
1163
- }
1164
- // --- DAG stage 4: select-dispatch (provider hook + default fallback) ---
1165
- // Decide which resolver path to try first (primary) and fallback strategy.
1166
- // Language providers can customize dispatch via selectDispatch hook; all
1167
- // others use the shared defaultDispatchDecision. Always non-null after this
1168
- // block so downstream resolvers are table-driven.
1169
- const dispatchDecision = provider.selectDispatch?.({
1170
- calledName,
1171
- callForm,
1172
- receiverName,
1173
- receiverTypeName,
1174
- receiverSource,
1175
- hint: dispatchHint,
1176
- }) ?? defaultDispatchDecision(callForm);
1177
- // Build overload hints for languages with inferLiteralType (Java/Kotlin/C#/C++).
1178
- // Only used when multiple candidates survive arity filtering — ~1-3% of calls.
1179
- const langConfig = provider.typeConfig;
1180
- const hints = langConfig?.inferLiteralType
1181
- ? { callNode, inferLiteralType: langConfig.inferLiteralType, typeEnv }
1182
- : undefined;
1183
- const resolved = resolveCallTarget({
1184
- calledName,
1185
- argCount: countCallArguments(callNode),
1186
- callForm,
1187
- receiverTypeName,
1188
- receiverName,
1189
- }, file.path, ctx, hints, widenCache, undefined, heritageMap, dispatchDecision);
1190
- if (!resolved)
1191
- return;
1192
- const relId = generateId('CALLS', `${sourceId}:${calledName}->${resolved.nodeId}`);
1193
- graph.addRelationship({
1194
- id: relId,
1195
- sourceId,
1196
- targetId: resolved.nodeId,
1197
- type: 'CALLS',
1198
- confidence: resolved.confidence,
1199
- reason: resolved.reason,
1200
- });
1201
- if (heritageMap && callForm === 'member' && receiverTypeName) {
1202
- const implTargets = findInterfaceDispatchTargets(calledName, receiverTypeName, file.path, ctx, heritageMap, resolved.nodeId);
1203
- for (const impl of implTargets) {
1204
- graph.addRelationship({
1205
- id: generateId('CALLS', `${sourceId}:${calledName}->${impl.nodeId}`),
1206
- sourceId,
1207
- targetId: impl.nodeId,
1208
- type: 'CALLS',
1209
- confidence: impl.confidence,
1210
- reason: impl.reason,
1211
- });
1212
- }
1213
- }
1214
- });
1215
- // Vue: emit CALLS edges for PascalCase components used in <template>.
1216
- // Template components are default-imported (not named), so we match the
1217
- // component name against imported .vue file basenames via the import map.
1218
- if (language === SupportedLanguages.Vue) {
1219
- const templateComponents = extractTemplateComponents(file.content);
1220
- if (templateComponents.length > 0) {
1221
- const fileId = generateId('File', file.path);
1222
- const importedFiles = ctx.importMap.get(file.path);
1223
- if (importedFiles) {
1224
- for (const componentName of templateComponents) {
1225
- for (const importedPath of importedFiles) {
1226
- if (!importedPath.endsWith('.vue'))
1227
- continue;
1228
- const basename = importedPath.slice(importedPath.lastIndexOf('/') + 1, importedPath.lastIndexOf('.'));
1229
- if (basename !== componentName)
1230
- continue;
1231
- const targetFileId = generateId('File', importedPath);
1232
- if (graph.getNode(targetFileId)) {
1233
- graph.addRelationship({
1234
- id: generateId('CALLS', `${fileId}:${componentName}->${targetFileId}`),
1235
- sourceId: fileId,
1236
- targetId: targetFileId,
1237
- type: 'CALLS',
1238
- confidence: 0.9,
1239
- reason: 'vue-template-component',
1240
- });
1241
- }
1242
- break;
1243
- }
1244
- }
1245
- }
1246
- }
1247
- }
1248
- ctx.clearCache();
1249
- }
1250
- // ── Resolve deferred write-access edges ──
1251
- // All properties (including Ruby attr_accessor) are now registered.
1252
- for (const pw of pendingWrites) {
1253
- const fieldOwner = resolveFieldOwnership(pw.receiverTypeName, pw.propertyName, pw.filePath, ctx);
1254
- if (fieldOwner) {
1255
- graph.addRelationship({
1256
- id: generateId('ACCESSES', `${pw.srcId}:${fieldOwner.nodeId}:write${pw.line !== undefined ? `:${pw.line}` : ''}`),
1257
- sourceId: pw.srcId,
1258
- targetId: fieldOwner.nodeId,
1259
- type: 'ACCESSES',
1260
- confidence: 1.0,
1261
- reason: 'write',
1262
- });
1263
- }
1264
- }
1265
- if (skippedByLang && skippedByLang.size > 0) {
1266
- for (const [lang, count] of skippedByLang.entries()) {
1267
- logger.warn(`[ingestion] Skipped ${count} ${lang} file(s) in call processing — ${lang} parser not available.`);
1268
- }
1269
- }
1270
- return collectedHeritage;
1271
- };
1272
- // FREE_CALLABLE_TYPES imported from symbol-table.ts — single source of truth.
1273
- const CONSTRUCTOR_TARGET_TYPES = new Set(['Constructor', 'Class', 'Struct', 'Record']);
1274
- const filterCallableCandidates = (candidates, argCount, callForm) => {
1275
- let kindFiltered;
1276
- if (callForm === 'constructor') {
1277
- const constructors = candidates.filter((c) => c.type === 'Constructor');
1278
- if (constructors.length > 0) {
1279
- kindFiltered = constructors;
1280
- }
1281
- else {
1282
- const types = candidates.filter((c) => CONSTRUCTOR_TARGET_TYPES.has(c.type));
1283
- kindFiltered =
1284
- types.length > 0 ? types : candidates.filter((c) => CALL_TARGET_TYPES.has(c.type));
1285
- }
1286
- }
1287
- else {
1288
- // CALL_TARGET_TYPES (not FREE_CALLABLE_TYPES) — the post-A4 filter must
1289
- // also admit Method and Constructor candidates, which are now unioned
1290
- // into the pool from `model.methods.lookupMethodByName` rather than
1291
- // `symbols.lookupCallableByName`.
1292
- kindFiltered = candidates.filter((c) => CALL_TARGET_TYPES.has(c.type));
1293
- }
1294
- if (kindFiltered.length === 0)
1295
- return [];
1296
- if (argCount === undefined)
1297
- return kindFiltered;
1298
- const hasParameterMetadata = kindFiltered.some((candidate) => candidate.parameterCount !== undefined);
1299
- if (!hasParameterMetadata)
1300
- return kindFiltered;
1301
- return kindFiltered.filter((candidate) => candidate.parameterCount === undefined ||
1302
- (argCount >= (candidate.requiredParameterCount ?? candidate.parameterCount) &&
1303
- argCount <= candidate.parameterCount));
1304
- };
1305
- /**
1306
- * Count callable candidates matching the kind + arity filter without
1307
- * allocating an intermediate array. Short-circuits once count exceeds
1308
- * `threshold` (default 1) — used by the dispatcher's `skipMember` check
1309
- * where we only need to know "more than one survivor".
1310
- */
1311
- const countCallableCandidates = (candidates, argCount, callForm, threshold = 1) => {
1312
- let count = 0;
1313
- for (const c of candidates) {
1314
- // Kind filter (mirrors filterCallableCandidates)
1315
- const typeOk = callForm === 'constructor'
1316
- ? CONSTRUCTOR_TARGET_TYPES.has(c.type)
1317
- : CALL_TARGET_TYPES.has(c.type);
1318
- if (!typeOk)
1319
- continue;
1320
- // Arity filter
1321
- if (argCount !== undefined &&
1322
- c.parameterCount !== undefined &&
1323
- (argCount < (c.requiredParameterCount ?? c.parameterCount) || argCount > c.parameterCount)) {
1324
- continue;
1325
- }
1326
- count++;
1327
- if (count > threshold)
1328
- return count; // early exit
1329
- }
1330
- return count;
1331
- };
1332
- const toResolveResult = (definition, tier) => ({
1333
- nodeId: definition.nodeId,
1334
- confidence: TIER_CONFIDENCE[tier],
1335
- reason: tier === 'same-file' ? 'same-file' : tier === 'import-scoped' ? 'import-resolved' : 'global',
1336
- returnType: definition.returnType,
1337
- });
1338
- /**
1339
- * Kotlin often declares parameters with boxed names (`Int`, `Boolean`, …) while
1340
- * literal inference yields JVM primitives (`int`, `boolean`). This map aligns
1341
- * those for overload matching. Java parameter text is usually already primitive
1342
- * spellings, so lookups here are typically unchanged.
1343
- */
1344
- const KOTLIN_BOXED_TO_PRIMITIVE = {
1345
- Int: 'int',
1346
- Long: 'long',
1347
- Short: 'short',
1348
- Byte: 'byte',
1349
- Float: 'float',
1350
- Double: 'double',
1351
- Boolean: 'boolean',
1352
- Char: 'char',
1353
- };
1354
- const normalizeJvmTypeName = (name) => KOTLIN_BOXED_TO_PRIMITIVE[name] ?? name;
1355
- const matchCandidatesByArgTypes = (candidates, argTypes) => {
1356
- if (!candidates.some((c) => c.parameterTypes))
1357
- return null;
1358
- const matched = candidates.filter((c) => {
1359
- // Keep candidates without type info — conservative: partially-annotated codebases
1360
- // (e.g. C++ with some missing declarations) may have mixed typed/untyped overloads.
1361
- // If one typed and one untyped both survive, matched.length > 1 → returns null (no edge).
1362
- if (!c.parameterTypes)
1363
- return true;
1364
- return c.parameterTypes.every((pType, i) => {
1365
- if (i >= argTypes.length || !argTypes[i])
1366
- return true;
1367
- // Normalise Kotlin boxed type names (Int→int, Boolean→boolean, etc.) so
1368
- // that the stored declaration type matches the inferred literal type.
1369
- return normalizeJvmTypeName(pType) === argTypes[i];
1370
- });
1371
- });
1372
- if (matched.length === 1)
1373
- return matched[0];
1374
- // Multiple survivors may share the same nodeId (e.g. TypeScript overload signatures +
1375
- // implementation body all collide via generateId). Deduplicate by nodeId — if all
1376
- // matched candidates resolve to the same graph node, disambiguation succeeded.
1377
- if (matched.length > 1) {
1378
- const uniqueIds = new Set(matched.map((c) => c.nodeId));
1379
- if (uniqueIds.size === 1)
1380
- return matched[0];
1381
- }
1382
- return null;
1383
- };
1384
- /**
1385
- * Try to disambiguate overloaded candidates using argument literal types.
1386
- * Only invoked when filteredCandidates.length > 1 and at least one has parameterTypes.
1387
- * Returns the single matching candidate, or null if ambiguous/inconclusive.
1388
- */
1389
- const tryOverloadDisambiguation = (candidates, hints) => {
1390
- const argTypes = extractCallArgTypes(hints.callNode, hints.inferLiteralType, hints.typeEnv ? (varName, cn) => hints.typeEnv.lookup(varName, cn) : undefined);
1391
- if (!argTypes)
1392
- return null;
1393
- return matchCandidatesByArgTypes(candidates, argTypes);
1394
- };
1395
- /**
1396
- * Apply overload-hint or arg-type disambiguation to a pre-filtered candidate
1397
- * pool. Returns the unique survivor, or null when neither signal is present,
1398
- * neither can disambiguate, or the pool remains ambiguous.
1399
- *
1400
- * Precedence rule: `overloadHints` wins over `preComputedArgTypes` when both
1401
- * are supplied. The AST-based disambiguator has access to live type inference
1402
- * hooks, whereas `preComputedArgTypes` is a worker-path pre-computation that
1403
- * may be coarser-grained.
1404
- *
1405
- * Single source of truth for the narrowing-signal precedence used by member
1406
- * and constructor resolution paths. Add a new narrowing signal here once, not
1407
- * at each call site.
1408
- */
1409
- const disambiguateByOverloadOrArgTypes = (pool, overloadHints, preComputedArgTypes) => {
1410
- if (!overloadHints && !preComputedArgTypes)
1411
- return null;
1412
- if (overloadHints)
1413
- return tryOverloadDisambiguation(pool, overloadHints);
1414
- if (preComputedArgTypes)
1415
- return matchCandidatesByArgTypes(pool, preComputedArgTypes);
1416
- return null;
1417
- };
1418
- const orderProviderSameNameTypeCandidates = (candidates, typeName, filePath) => {
1419
- const language = getLanguageFromFilename(filePath);
1420
- if (language == null)
1421
- return null;
1422
- return (getProvider(language).orderSameNameTypeCandidates?.({
1423
- typeName,
1424
- callSiteFilePath: filePath,
1425
- candidates,
1426
- }) ?? null);
1427
- };
1428
- const resolveProviderPrimaryTypeCandidate = (candidates, tier, typeName, filePath) => {
1429
- const ordered = orderProviderSameNameTypeCandidates(candidates, typeName, filePath);
1430
- return ordered && ordered.length > 0 ? toResolveResult(ordered[0], tier) : null;
1431
- };
1432
- /**
1433
- * Thin dispatcher that routes a call to the appropriate specialized resolver.
1434
- *
1435
- * - `free` → {@link resolveFreeCall}
1436
- * - `constructor` → {@link resolveStaticCall} (with pre-resolved tiered pool)
1437
- * - `member` with a known receiver type → {@link resolveMemberCall}, with
1438
- * file-based fallback for traits/interfaces
1439
- * - `member` without receiver type → module-alias check, then tiered lookup
1440
- *
1441
- * Replaces the former 200+ line function (SM-19: fuzzy-free call resolution).
1442
- */
1443
- /**
1444
- * Module-alias resolution for member calls without a receiver type.
1445
- *
1446
- * Handles Python/Ruby `import mod; mod.Symbol()` patterns where the receiver
1447
- * is a module name, not a typed variable. Uses `moduleAliasMap` to scope
1448
- * candidates to the correct module file.
1449
- */
1450
- const resolveModuleAliasedCall = (call, currentFile, ctx, widenCache, tieredOverride) => {
1451
- if (!call.receiverName)
1452
- return null;
1453
- const aliasMap = ctx.moduleAliasMap?.get(currentFile);
1454
- if (!aliasMap)
1455
- return null;
1456
- const moduleFile = aliasMap.get(call.receiverName);
1457
- if (!moduleFile)
1458
- return null;
1459
- // Reuse the caller's pre-computed tiered result when available —
1460
- // the dispatcher already called ctx.resolve(call.calledName, currentFile).
1461
- const tiered = tieredOverride ?? ctx.resolve(call.calledName, currentFile);
1462
- if (!tiered)
1463
- return null;
1464
- // Try member-form, then constructor-form (for `module.ClassName()` patterns)
1465
- let filtered = filterCallableCandidates(tiered.candidates, call.argCount, call.callForm).filter((c) => c.filePath === moduleFile);
1466
- if (filtered.length === 0) {
1467
- filtered = filterCallableCandidates(tiered.candidates, call.argCount, 'constructor').filter((c) => c.filePath === moduleFile);
1468
- }
1469
- if (filtered.length === 0) {
1470
- // Widen to global callable+method indexes scoped to the aliased module
1471
- // file. Function+ownerId (Python/Rust/Kotlin) is still routed to both
1472
- // indexes until Unit 5 unblocks, so dedup by nodeId.
1473
- const cacheKey = `${call.calledName}\0${moduleFile}`;
1474
- let defs = widenCache?.get(cacheKey);
1475
- if (!defs) {
1476
- const rawCallable = ctx.model.symbols.lookupCallableByName(call.calledName);
1477
- const rawMethods = ctx.model.methods.lookupMethodByName(call.calledName);
1478
- const widenCombined = [];
1479
- const widenSeen = new Set();
1480
- for (const d of rawCallable) {
1481
- if (widenSeen.has(d.nodeId))
1482
- continue;
1483
- widenSeen.add(d.nodeId);
1484
- widenCombined.push(d);
1485
- }
1486
- for (const d of rawMethods) {
1487
- if (widenSeen.has(d.nodeId))
1488
- continue;
1489
- widenSeen.add(d.nodeId);
1490
- widenCombined.push(d);
1491
- }
1492
- defs = widenCombined;
1493
- widenCache?.set(cacheKey, defs);
1494
- }
1495
- filtered = filterCallableCandidates(defs, call.argCount, call.callForm).filter((c) => c.filePath === moduleFile);
1496
- if (filtered.length === 0) {
1497
- filtered = filterCallableCandidates(defs, call.argCount, 'constructor').filter((c) => c.filePath === moduleFile);
1498
- }
1499
- }
1500
- return filtered.length === 1 ? toResolveResult(filtered[0], tiered.tier) : null;
1501
- };
1502
- /**
1503
- * File-based fallback for member calls where owner-scoped resolution fails.
1504
- *
1505
- * Resolves the receiver type via `ctx.resolve()` and narrows all callable
1506
- * symbols with the method name to the receiver type's defining file(s),
1507
- * then applies ownerId filtering and overload disambiguation.
1508
- *
1509
- * Handles Rust trait dispatch (`repo.find()` where `find` is on a trait impl),
1510
- * cross-file overloaded methods, and similar patterns where ownerId
1511
- * relationships may not be established on all candidates.
1512
- */
1513
- const resolveMemberCallByFile = (calledName, receiverTypeName, currentFile, ctx, argCount, callForm, overloadHints, preComputedArgTypes) => {
1514
- const typeResolved = ctx.resolve(receiverTypeName, currentFile);
1515
- if (!typeResolved || typeResolved.candidates.length === 0)
1516
- return null;
1517
- const typeNodeIds = new Set(typeResolved.candidates.map((d) => d.nodeId));
1518
- const typeFiles = new Set(typeResolved.candidates.map((d) => d.filePath));
1519
- // A4 (plan 006, Unit 4): consult both indexes. Strictly-labeled
1520
- // Method/Constructor are disjoint, but Function+ownerId (Python/Rust/
1521
- // Kotlin) is routed into BOTH indexes by `wrappedAdd` until Unit 5
1522
- // unblocks — dedup by nodeId so overload disambiguation doesn't see
1523
- // phantom duplicates.
1524
- const rawCallablePool = ctx.model.symbols.lookupCallableByName(calledName);
1525
- const rawMethodPool = ctx.model.methods.lookupMethodByName(calledName);
1526
- const combinedPool = [];
1527
- const combinedSeen = new Set();
1528
- for (const def of rawCallablePool) {
1529
- if (combinedSeen.has(def.nodeId))
1530
- continue;
1531
- combinedSeen.add(def.nodeId);
1532
- combinedPool.push(def);
1533
- }
1534
- for (const def of rawMethodPool) {
1535
- if (combinedSeen.has(def.nodeId))
1536
- continue;
1537
- combinedSeen.add(def.nodeId);
1538
- combinedPool.push(def);
1539
- }
1540
- const methodPool = filterCallableCandidates(combinedPool, argCount, callForm);
1541
- const fileFiltered = methodPool.filter((c) => typeFiles.has(c.filePath));
1542
- if (fileFiltered.length === 1) {
1543
- return toResolveResult(fileFiltered[0], typeResolved.tier);
1544
- }
1545
- // ownerId fallback: narrow by ownerId matching the type's nodeId
1546
- const pool = fileFiltered.length > 0 ? fileFiltered : methodPool;
1547
- const ownerFiltered = pool.filter((c) => c.ownerId && typeNodeIds.has(c.ownerId));
1548
- if (ownerFiltered.length === 1)
1549
- return toResolveResult(ownerFiltered[0], typeResolved.tier);
1550
- // Overload disambiguation on the narrowed pool
1551
- if (fileFiltered.length > 1 || ownerFiltered.length > 1) {
1552
- const overloadPool = ownerFiltered.length > 1 ? ownerFiltered : fileFiltered;
1553
- const disambiguated = disambiguateByOverloadOrArgTypes(overloadPool, overloadHints, preComputedArgTypes);
1554
- if (disambiguated)
1555
- return toResolveResult(disambiguated, typeResolved.tier);
1556
- }
1557
- // Zero-match null-route: receiver type resolved but no candidate matched
1558
- // after file-based and owner-based narrowing. Refuse to emit a CALLS edge
1559
- // rather than guess — matches the SM-10 R3 null-route contract.
1560
- return null;
1561
- };
1562
- /** Return the sole survivor from a tiered pool after callable + arity filtering, or null. */
1563
- const singleCandidate = (tiered, argCount, callForm) => {
1564
- const filtered = filterCallableCandidates(tiered.candidates, argCount, callForm);
1565
- return filtered.length === 1 ? toResolveResult(filtered[0], tiered.tier) : null;
1566
- };
1567
- /** @internal Exported for unit tests. Do not use outside tests. */
1568
- export const _resolveCallTargetForTesting = (call, currentFile, ctx, opts) => resolveCallTarget(call, currentFile, ctx, opts?.overloadHints, opts?.widenCache, opts?.preComputedArgTypes, opts?.heritageMap);
1569
- const resolveCallTarget = (call, currentFile, ctx, overloadHints, widenCache, preComputedArgTypes, heritageMap, dispatchDecision) => {
1570
- const tiered = ctx.resolve(call.calledName, currentFile);
1571
- if (!tiered)
1572
- return null;
1573
- // DAG dispatch: use decision.primary to pick the resolver branch.
1574
- // Callers that own the DAG (processCalls + crossFile deferred paths)
1575
- // pass a decision; other callers use the shared default ladder.
1576
- // Language-specific primary / fallback / ancestryView overrides come from
1577
- // the provider's `selectDispatch` hook.
1578
- const decision = dispatchDecision ?? defaultDispatchDecision(call.callForm);
1579
- const primary = decision.primary;
1580
- if (primary === 'free') {
1581
- return resolveFreeCall(call.calledName, currentFile, ctx, call.argCount, tiered, overloadHints, preComputedArgTypes);
1582
- }
1583
- if (primary === 'constructor') {
1584
- return (resolveStaticCall(call.calledName, currentFile, ctx, call.argCount, tiered, overloadHints, preComputedArgTypes) ?? singleCandidate(tiered, call.argCount, 'constructor'));
1585
- }
1586
- // primary === 'owner-scoped'
1587
- if (call.receiverTypeName) {
1588
- // Skip the owner-scoped MRO path when the tiered pool has genuine
1589
- // overload ambiguity that needs D1-D4+E handling, not D0.
1590
- const skipMember = (!!overloadHints || !!preComputedArgTypes) &&
1591
- countCallableCandidates(tiered.candidates, call.argCount, call.callForm) > 1;
1592
- // Try owner-scoped (resolveMemberCall) then file-scoped (resolveMemberCallByFile).
1593
- // DAG: dispatchDecision.ancestryView selects instance vs singleton ancestry
1594
- // for kind-aware MRO strategies. Ruby `Account.log` flows via 'singleton'.
1595
- //
1596
- // Singleton-ancestry miss MUST NOT degrade to the file-scoped fallback:
1597
- // resolveMemberCallByFile matches by ownerId and would happily pick an
1598
- // instance method defined on the same class, leaking instance dispatch
1599
- // onto what was declared a class-method call. For singleton dispatch,
1600
- // a miss either null-routes or falls through to `decision.fallback`.
1601
- const singletonDispatch = decision.ancestryView === 'singleton';
1602
- const memberResult = (!skipMember
1603
- ? resolveMemberCall(call.receiverTypeName, call.calledName, currentFile, ctx, heritageMap, call.argCount, decision.ancestryView)
1604
- : null) ??
1605
- (singletonDispatch
1606
- ? null
1607
- : resolveMemberCallByFile(call.calledName, call.receiverTypeName, currentFile, ctx, call.argCount, call.callForm, overloadHints, preComputedArgTypes));
1608
- if (memberResult)
1609
- return memberResult;
1610
- // Module-alias narrowing runs as a FALLBACK, after owner/file-scoped
1611
- // resolvers have returned null. This ordering is load-bearing: placing
1612
- // alias narrowing first would short-circuit unique owner-scoped answers
1613
- // when a local variable coincidentally matches an alias name, leaking
1614
- // unrelated homonyms from the aliased file onto the wrong receiver type.
1615
- //
1616
- // The type-file verification guard is load-bearing for SM-10 R3: an
1617
- // alias is only a VALID narrowing signal when the alias target file is
1618
- // among the receiver type's defining files. If the alias points at a
1619
- // file that does not hold `receiverTypeName`, any candidate we would
1620
- // pick from there would belong to an unrelated class — a cross-type
1621
- // false positive. ctx.resolve is cached per (name, file), so resolving
1622
- // the receiver type a second time here is free.
1623
- const typeResolves = ctx.resolve(call.receiverTypeName, currentFile);
1624
- const aliasMap = ctx.moduleAliasMap?.get(currentFile);
1625
- const aliasTargetFile = call.receiverName && aliasMap ? aliasMap.get(call.receiverName) : undefined;
1626
- if (aliasTargetFile &&
1627
- typeResolves &&
1628
- typeResolves.candidates.some((c) => c.filePath === aliasTargetFile)) {
1629
- const aliasResult = resolveModuleAliasedCall(call, currentFile, ctx, widenCache, tiered);
1630
- if (aliasResult)
1631
- return aliasResult;
1632
- }
1633
- // SM-10 R3 null-route: when the receiver type resolves to indexed types
1634
- // but no scoped resolver (nor the guarded alias fallback) produced a
1635
- // match, that's a genuine miss — refuse to emit a CALLS edge rather
1636
- // than guess via an unscoped singleCandidate that ignores the class
1637
- // hierarchy. When the type is NOT in the index (PHP `mixed`, dynamic
1638
- // types, unresolvable aliases), the scoped resolvers had nothing to
1639
- // work with and singleCandidate is the correct last resort.
1640
- //
1641
- // DAG fallback override: when `select-dispatch` returned
1642
- // `fallback: 'free-arity-narrowed'` (today: Ruby implicit-self bare
1643
- // calls whose enclosing class doesn't define the method), fall through
1644
- // to free-call resolution instead of null-routing. This preserves
1645
- // existing free-call arity-narrowing heuristics for bare calls that
1646
- // happen to target methods on unrelated classes.
1647
- if (typeResolves && typeResolves.candidates.length > 0) {
1648
- if (decision.fallback === 'free-arity-narrowed') {
1649
- const free = resolveFreeCall(call.calledName, currentFile, ctx, call.argCount, tiered, overloadHints, preComputedArgTypes);
1650
- if (free)
1651
- return free;
1652
- }
1653
- return null; // null-route: type resolved, no candidate matched
1654
- }
1655
- return singleCandidate(tiered, call.argCount, call.callForm);
1656
- }
1657
- // Member call with no inferred receiver type — e.g. Python `mod.fn()`
1658
- // where `mod` is a module alias. Module-alias narrowing is the primary
1659
- // disambiguation signal here. Also consulted from the typed-member
1660
- // branch above as a guarded fallback after owner/file-scoped resolvers.
1661
- return (resolveModuleAliasedCall(call, currentFile, ctx, widenCache, tiered) ??
1662
- singleCandidate(tiered, call.argCount, call.callForm));
1663
- };
1664
- // ── Scope key helpers ────────────────────────────────────────────────────
1665
- // Scope keys use the format "funcName@startIndex" (produced by type-env.ts).
1666
- // Source IDs use "Label:filepath:funcName" (produced by parse-worker.ts).
1667
- // NUL (\0) is used as a composite-key separator because it cannot appear
1668
- // in source-code identifiers, preventing ambiguous concatenation.
1669
- //
1670
- // receiverKey stores the FULL scope (funcName@startIndex) to prevent
1671
- // collisions between overloaded methods with the same name in different
1672
- // classes (e.g. User.save@100 and Repo.save@200 are distinct keys).
1673
- // Lookup uses a secondary funcName-only index built in lookupReceiverType.
1674
- /** Extract the bare function name from a sourceId.
1675
- * Handles both unqualified ("Function:filepath:funcName" → "funcName")
1676
- * and qualified ("Function:filepath:ClassName.funcName" → "funcName").
1677
- * Strips any trailing #<arity> suffix from Method/Constructor IDs. */
1678
- const extractFuncNameFromSourceId = (sourceId) => {
1679
- const lastColon = sourceId.lastIndexOf(':');
1680
- const segment = lastColon >= 0 ? sourceId.slice(lastColon + 1) : '';
1681
- const dotIdx = segment.lastIndexOf('.');
1682
- const raw = dotIdx >= 0 ? segment.slice(dotIdx + 1) : segment;
1683
- // Strip #<arity> suffix (e.g. "save#2" → "save")
1684
- const hashIdx = raw.indexOf('#');
1685
- return hashIdx >= 0 ? raw.slice(0, hashIdx) : raw;
1686
- };
1687
- /**
1688
- * Build a composite key for receiver type storage.
1689
- * Uses the full scope string (e.g. "save@100") to distinguish overloaded
1690
- * methods with the same name in different classes.
1691
- */
1692
- const receiverKey = (scope, varName) => `${scope}\0${varName}`;
1693
- /**
1694
- * Build a two-level secondary index from the verified receiver map.
1695
- * The verified map is keyed by `scope\0varName` where scope is either
1696
- * "funcName@startIndex" (inside a function) or "" (file level).
1697
- * Index structure: Map<funcName, Map<varName, ReceiverTypeEntry>>
1698
- *
1699
- * Known limitation: the index collapses scope keys to bare funcName,
1700
- * so two same-arity overloads with the same local variable name but
1701
- * different types will mark that variable as ambiguous. A future
1702
- * enhancement should key by full scope (funcName@startIndex) and carry
1703
- * scope keys through findEnclosingFunction's return type.
1704
- */
1705
- const buildReceiverTypeIndex = (map) => {
1706
- const index = new Map();
1707
- for (const [key, typeName] of map) {
1708
- const nul = key.indexOf('\0');
1709
- if (nul < 0)
1710
- continue;
1711
- const scope = key.slice(0, nul);
1712
- const varName = key.slice(nul + 1);
1713
- if (!varName)
1714
- continue;
1715
- if (scope !== '' && !scope.includes('@'))
1716
- continue;
1717
- const funcName = scope === '' ? '' : scope.slice(0, scope.indexOf('@'));
1718
- let varMap = index.get(funcName);
1719
- if (!varMap) {
1720
- varMap = new Map();
1721
- index.set(funcName, varMap);
1722
- }
1723
- const existing = varMap.get(varName);
1724
- if (existing === undefined) {
1725
- varMap.set(varName, { kind: 'resolved', value: typeName });
1726
- }
1727
- else if (existing.kind === 'resolved' && existing.value !== typeName) {
1728
- varMap.set(varName, { kind: 'ambiguous' });
1729
- }
1730
- }
1731
- return index;
1732
- };
1733
- /**
1734
- * O(1) receiver type lookup using the pre-built secondary index.
1735
- * Returns the unique type name if unambiguous. Falls back to file-level scope.
1736
- */
1737
- const lookupReceiverType = (index, funcName, varName) => {
1738
- const funcBucket = index.get(funcName);
1739
- if (funcBucket) {
1740
- const entry = funcBucket.get(varName);
1741
- if (entry?.kind === 'resolved')
1742
- return entry.value;
1743
- if (entry?.kind === 'ambiguous') {
1744
- // Ambiguous in this function scope — try file-level fallback
1745
- const fileEntry = index.get('')?.get(varName);
1746
- return fileEntry?.kind === 'resolved' ? fileEntry.value : undefined;
1747
- }
1748
- }
1749
- // Fallback: file-level scope (funcName "")
1750
- if (funcName !== '') {
1751
- const fileEntry = index.get('')?.get(varName);
1752
- if (fileEntry?.kind === 'resolved')
1753
- return fileEntry.value;
1754
- }
1755
- return undefined;
1756
- };
1757
- /**
1758
- * Resolve the type that results from accessing `receiverName.fieldName`.
1759
- * Requires declaredType on the Property node (needed for chain walking continuation).
1760
- */
1761
- const resolveFieldAccessType = (receiverName, fieldName, filePath, ctx) => {
1762
- const fieldDef = resolveFieldOwnership(receiverName, fieldName, filePath, ctx);
1763
- if (!fieldDef?.declaredType)
63
+ * Confidence for route controller-method CALLS edges. Framework-route
64
+ * controller references (e.g. `OrderController::class` in `routes/web.php`)
65
+ * resolve by global class name, so this matches the legacy `global`-tier
66
+ * confidence the tiered resolver previously assigned these edges.
67
+ */
68
+ const ROUTE_EDGE_CONFIDENCE = 0.5;
69
+ /**
70
+ * Resolve a route's controller class from its normalized dot-joined
71
+ * fully-qualified name (threaded by the Laravel extractor from a `use`/`::class`
72
+ * reference). Two strategies, in order:
73
+ *
74
+ * 1. Direct qualified lookup works when the type registry keys the class by
75
+ * its FQN (block-form namespaces, non-PHP frameworks, seeded test models).
76
+ * 2. PSR-4 file-path disambiguation PHP's common statement-form namespace
77
+ * (`namespace App\Http\Controllers;`) leaves the structure-phase
78
+ * `qualifiedName` as the *short* class name, so the registry has no FQN
79
+ * key. Instead, take the FQN's last segment as the class name, fetch the
80
+ * same-short-name candidates, and pick the one whose file path's tail
81
+ * matches the FQN's namespace tail (e.g. `App.Admin.OrderController`
82
+ * `app/Admin/OrderController.php`). Requires ≥2 trailing segments (class +
83
+ * ≥1 namespace segment) and a unique winner conservative, so a
84
+ * non-PSR-4 layout falls through to short-name resolution rather than
85
+ * guessing.
86
+ *
87
+ * Returns the resolved class, or `undefined` when the FQN cannot be uniquely
88
+ * resolved (the caller then falls back to bare short-name resolution).
89
+ */
90
+ function resolveControllerByQualifiedName(model, fqn) {
91
+ const direct = model.types.lookupClassByQualifiedName(fqn);
92
+ if (direct.length === 1)
93
+ return direct[0];
94
+ const fqnSegments = fqn.split('.');
95
+ const shortName = fqnSegments[fqnSegments.length - 1];
96
+ if (!shortName)
1764
97
  return undefined;
1765
- // Use stripNullable (not extractReturnTypeName) — field types like List<User>
1766
- // should be preserved as-is, not unwrapped to User. Only strip nullable wrappers.
1767
- return {
1768
- typeName: stripNullable(fieldDef.declaredType),
1769
- fieldNodeId: fieldDef.nodeId,
1770
- };
1771
- };
1772
- /**
1773
- * Resolve a field's Property node given a receiver type name and field name.
1774
- * Does NOT require declaredType — used by write-access tracking where only the
1775
- * fieldNodeId is needed (no chain continuation).
1776
- */
1777
- const resolveFieldOwnership = (receiverName, fieldName, filePath, ctx) => {
1778
- const typeResolved = ctx.resolve(receiverName, filePath);
1779
- if (!typeResolved)
1780
- return undefined;
1781
- const classDef = typeResolved.candidates.find((d) => CLASS_LIKE_TYPES.has(d.type));
1782
- if (!classDef)
98
+ const candidates = model.types.lookupClassByName(shortName);
99
+ if (candidates.length === 1)
100
+ return candidates[0];
101
+ if (candidates.length === 0)
1783
102
  return undefined;
1784
- return ctx.model.fields.lookupFieldByOwner(classDef.nodeId, fieldName) ?? undefined;
1785
- };
1786
- /**
1787
- * Resolve a method by owner type name using the eagerly-populated methodByOwner index.
1788
- * Returns `{ def, tier }` when an unambiguous method is found, `undefined` otherwise.
1789
- *
1790
- * **Multi-candidate iteration (homonym disambiguation):** when `ctx.resolve(ownerType)`
1791
- * returns multiple class-like candidates (e.g. two classes named `User` in different
1792
- * files reachable from the call site), each is probed with `lookupMethodByOwnerWithMRO`.
1793
- * Results are deduplicated by `nodeId` so that:
1794
- *
1795
- * - homonym classes that both walk up to the SAME ancestor's method collapse to 1 hit
1796
- * - aliased re-exports that produce two candidates pointing at the same def collapse too
1797
- *
1798
- * After deduplication:
1799
- *
1800
- * - 0 unique matches → `undefined` (owner-scoped path has no answer)
1801
- * - 1 unique match → return it
1802
- * - ≥2 unique matches → `undefined` (genuine homonym ambiguity; don't silently pick one)
1803
- *
1804
- * The returned `tier` reflects how the owner TYPE was resolved (not the method name).
1805
- * Threaded out here so callers don't need a second `ctx.resolve(ownerType, ...)` call —
1806
- * this decouples callers from `ctx.resolve`'s per-file caching contract.
1807
- */
1808
- const resolveMethodByOwner = (receiverTypeName, methodName, filePath, ctx, heritageMap, argCount,
1809
- /**
1810
- * DAG-sourced ancestry selector. `'singleton'` routes through
1811
- * `heritageMap.getSingletonAncestry(owner)` for class-method dispatch
1812
- * (Ruby `Account.log` via `extend LoggerMixin`). Default / undefined
1813
- * uses the walker's instance-dispatch behavior.
1814
- */
1815
- ancestryView) => {
1816
- const typeResolved = ctx.resolve(receiverTypeName, filePath);
1817
- if (!typeResolved)
1818
- return undefined;
1819
- // MRO walking needs a language hint so we can derive the per-language
1820
- // strategy; compute it once and reuse for every candidate. Unknown
1821
- // extension → fall back to plain direct lookup (D1-D4 still runs on miss).
1822
- const language = heritageMap ? getLanguageFromFilename(filePath) : null;
1823
- const mroStrategy = language != null ? getProvider(language).mroStrategy : null;
1824
- const canWalkMRO = heritageMap != null && mroStrategy != null;
1825
- // Iterate all class-like candidates tracking the first unambiguous hit.
1826
- // Zero-allocation fast path: the common case is exactly one class candidate,
1827
- // so we avoid building a Map. A second hit with a different `nodeId` flips
1828
- // `ambiguous` and short-circuits the loop. Diamond MRO convergence on the
1829
- // same inherited method collapses to one hit because `nodeId` matches.
1830
- //
1831
- // firstDef === undefined → owner-scoped resolution found nothing
1832
- // firstDef && !ambiguous → unambiguous answer
1833
- // ambiguous → genuine homonym ambiguity — refuse to pick
1834
- //
1835
- // argCount is threaded through so arity-differing overloads
1836
- // (e.g. C++ `greet()` vs `greet(string)`) are disambiguated inside the
1837
- // owner-scoped lookup rather than collapsing to an arbitrary first pick.
1838
- let firstDef;
1839
- let ambiguous = false;
1840
- for (const candidate of typeResolved.candidates) {
1841
- if (!CLASS_LIKE_TYPES.has(candidate.type))
1842
- continue;
1843
- // Singleton dispatch: when the DAG decision requested the singleton
1844
- // ancestry view, pass `heritageMap.getSingletonAncestry` as the walker's
1845
- // ancestry override. Kind-aware strategies (e.g. MroStrategy 'ruby-mixin')
1846
- // honor the override by scanning it linearly in place of their default walk.
1847
- const singletonOverride = ancestryView === 'singleton' && canWalkMRO && heritageMap
1848
- ? heritageMap.getSingletonAncestry(candidate.nodeId).map((e) => e.parentId)
1849
- : undefined;
1850
- const def = canWalkMRO
1851
- ? lookupMethodByOwnerWithMRO(candidate.nodeId, methodName, heritageMap, ctx.model, mroStrategy, argCount, singletonOverride)
1852
- : ctx.model.methods.lookupMethodByOwner(candidate.nodeId, methodName, argCount);
1853
- if (!def)
1854
- continue;
1855
- if (!firstDef) {
1856
- firstDef = def;
1857
- }
1858
- else if (def.nodeId !== firstDef.nodeId) {
1859
- ambiguous = true;
1860
- break;
1861
- }
1862
- }
1863
- if (!firstDef && !ambiguous) {
1864
- const orderedTypeCandidates = orderProviderSameNameTypeCandidates(ctx.model.types.lookupClassByName(receiverTypeName), receiverTypeName, filePath);
1865
- if (orderedTypeCandidates) {
1866
- for (const candidate of orderedTypeCandidates) {
1867
- const def = canWalkMRO
1868
- ? lookupMethodByOwnerWithMRO(candidate.nodeId, methodName, heritageMap, ctx.model, mroStrategy, argCount)
1869
- : ctx.model.methods.lookupMethodByOwner(candidate.nodeId, methodName, argCount);
1870
- if (!def)
1871
- continue;
1872
- if (!firstDef) {
1873
- firstDef = def;
1874
- }
1875
- else if (def.nodeId !== firstDef.nodeId) {
1876
- ambiguous = true;
1877
- break;
1878
- }
1879
- }
1880
- }
1881
- }
1882
- if (!firstDef || ambiguous)
1883
- return undefined;
1884
- return { def: firstDef, tier: typeResolved.tier };
1885
- };
1886
- // ---------------------------------------------------------------------------
1887
- // SM-11: Owner-scoped + MRO member-call resolution (no fuzzy lookup)
1888
- // ---------------------------------------------------------------------------
1889
- /**
1890
- * Resolve a member call using owner-scoped + MRO resolution only (no fuzzy lookup).
1891
- * Used for `obj.method()` calls where the receiver type is known.
1892
- *
1893
- * Delegates to {@link resolveMethodByOwner} which performs an O(1) owner-scoped
1894
- * method lookup and, when a {@link HeritageMap} is provided, walks the MRO chain
1895
- * via {@link lookupMethodByOwnerWithMRO}.
1896
- *
1897
- * {@link resolveCallTarget} delegates here for member calls.
1898
- *
1899
- * **SEMANTIC CHANGE (2026-04-09):** The confidence tier reflects how the
1900
- * owner TYPE was resolved, not how the method NAME was resolved globally.
1901
- * more accurate for owner-scoped resolution (the discriminant IS the class,
1902
- * not the method name). Downstream consumers that filter CALLS edges by
1903
- * confidence threshold may see shifted values on otherwise-unchanged code.
1904
- * See the "returns result with correct confidence tier" tests below for the
1905
- * locked-in behavior.
1906
- *
1907
- * **Performance:** Callers that only need the return type (e.g. `walkMixedChain`)
1908
- * should call {@link resolveMethodByOwner} directly and use the `.def.returnType`
1909
- * field instead, to avoid building a throwaway `ResolveResult`.
1910
- *
1911
- * @param ownerType - The receiver's type name (e.g. 'User')
1912
- * @param methodName - The method being called (e.g. 'save')
1913
- * @param currentFile - File path of the call site
1914
- * @param ctx - Resolution context
1915
- * @param heritageMap - Optional heritage map for MRO-aware ancestor walking
1916
- */
1917
- export const resolveMemberCall = (ownerType, methodName, currentFile, ctx, heritageMap, argCount, ancestryView) => {
1918
- const resolved = resolveMethodByOwner(ownerType, methodName, currentFile, ctx, heritageMap, argCount, ancestryView);
1919
- if (!resolved)
1920
- return null;
1921
- return toResolveResult(resolved.def, resolved.tier);
1922
- };
1923
- // ---------------------------------------------------------------------------
1924
- // SM-13: Free-function call resolution
1925
- // ---------------------------------------------------------------------------
1926
- /**
1927
- * Resolve a free-function call using `lookupExact` (same-file) + import-scoped
1928
- * resolution via `ctx.resolve()`.
1929
- *
1930
- * Used for `foo()`, `doStuff()` — unqualified calls with no receiver.
1931
- * Also handles implicit constructors (`User()` without `new`) by delegating
1932
- * to {@link resolveStaticCall} when the tiered pool contains class-like
1933
- * targets.
1934
- *
1935
- * {@link resolveCallTarget} delegates here for `callForm === 'free'`.
1936
- *
1937
- * `resolveFreeCall` does not take a `widenCache` parameter. Free calls
1938
- * have no receiver type and rely exclusively on the tiered pool
1939
- * from `ctx.resolve()`.
1940
- *
1941
- * @param calledName - The called function name (e.g. 'doStuff')
1942
- * @param filePath - File path of the call site
1943
- * @param ctx - Resolution context
1944
- * @param argCount - Optional argument count for arity filtering
1945
- * @param tieredOverride - Pre-computed tiered candidates from an upstream
1946
- * `ctx.resolve` call. When provided, skips the redundant
1947
- * lookup inside this function.
1948
- * @param overloadHints - Optional AST-based overload disambiguation hints
1949
- * @param preComputedArgTypes - Optional pre-computed argument types (worker path)
1950
- */
1951
- export const resolveFreeCall = (calledName, filePath, ctx, argCount, tieredOverride, overloadHints, preComputedArgTypes) => {
1952
- const tiered = tieredOverride ?? ctx.resolve(calledName, filePath);
1953
- if (!tiered)
1954
- return null;
1955
- let filteredCandidates = filterCallableCandidates(tiered.candidates, argCount, 'free');
1956
- // Class-target fast path: free-form call targeting a class. Delegates to
1957
- // resolveStaticCall for O(1) class + constructor lookup.
1958
- // The `.some()` trigger must stay aligned with `INSTANTIABLE_CLASS_TYPES` —
1959
- // any type admitted here that is not in that set will cause resolveStaticCall
1960
- // to return null, wasting two lookup passes per call. `Enum` is deliberately
1961
- // excluded; `Record` is included so record-like class targets reach the fast
1962
- // path.
1963
- // Align with INSTANTIABLE_CLASS_TYPES by reusing the set directly rather
1964
- // than enumerating literal strings. This converts an invariant that was
1965
- // previously enforced by a comment ("keep this list aligned with
1966
- // INSTANTIABLE_CLASS_TYPES") into one enforced structurally — any future
1967
- // extension of the set propagates here automatically.
1968
- // Language providers can still choose a primary same-name type candidate in
1969
- // the tail of this function when their grammars index one logical type
1970
- // multiple times.
1971
- const hasClassTarget = filteredCandidates.length === 0 &&
1972
- tiered.candidates.some((c) => INSTANTIABLE_CLASS_TYPES.has(c.type));
1973
- if (hasClassTarget) {
1974
- const staticResult = resolveStaticCall(calledName, filePath, ctx, argCount, tiered);
1975
- if (staticResult)
1976
- return staticResult;
1977
- // Retry with constructor form for languages whose constructor calls look
1978
- // like free function calls. If resolveStaticCall didn't match, re-filter
1979
- // with constructor form so CONSTRUCTOR_TARGET_TYPES applies.
1980
- //
1981
- // The retry fires for every null return from `resolveStaticCall`, which
1982
- // can happen for three distinct reasons — all three are handled below:
1983
- //
1984
- // (a) No explicit `Constructor` node found and zero instantiable
1985
- // class candidates (e.g. Interface/Trait/Impl only — the SM-12
1986
- // null-route contract). `filterCallableCandidates` with
1987
- // `'constructor'` form will also return nothing → we fall
1988
- // through to the final null return. Correct.
1989
- //
1990
- // (b) Homonym ambiguity — two or more instantiable class candidates
1991
- // share the name (e.g. `User` in two files, same tier). The
1992
- // retry repopulates `filteredCandidates` with both Classes and
1993
- // they flow into the provider same-name candidate hook below, which
1994
- // can pick a primary definition or null-route.
1995
- //
1996
- // (c) `resolveStaticCall` step 4 bailed because the tiered pool
1997
- // contains ownerless `Constructor` nodes (some extractors emit
1998
- // constructors without `ownerId`). Those `Constructor` nodes
1999
- // survive the constructor-form filter below and reach overload
2000
- // disambiguation, giving the existing filter path a chance to
2001
- // pick the right one. Correct but currently uncovered by a
2002
- // dedicated test — the R5 `preComputedArgTypes` path exercises
2003
- // overload disambiguation for Functions, which is structurally
2004
- // the same code.
2005
- filteredCandidates = filterCallableCandidates(tiered.candidates, argCount, 'constructor');
2006
- }
2007
- // E. Overload disambiguation
2008
- if (filteredCandidates.length > 1) {
2009
- const disambiguated = overloadHints
2010
- ? tryOverloadDisambiguation(filteredCandidates, overloadHints)
2011
- : preComputedArgTypes
2012
- ? matchCandidatesByArgTypes(filteredCandidates, preComputedArgTypes)
2013
- : null;
2014
- if (disambiguated)
2015
- return toResolveResult(disambiguated, tiered.tier);
2016
- }
2017
- if (filteredCandidates.length !== 1) {
2018
- const primary = resolveProviderPrimaryTypeCandidate(filteredCandidates, tiered.tier, calledName, filePath);
2019
- if (primary)
2020
- return primary;
2021
- return null;
2022
- }
2023
- return toResolveResult(filteredCandidates[0], tiered.tier);
2024
- };
2025
- // ---------------------------------------------------------------------------
2026
- // SM-12: Constructor/static call resolution (no fuzzy lookup)
2027
- // ---------------------------------------------------------------------------
2028
- /**
2029
- * Resolve a constructor or static call using class-scoped lookup (no fuzzy lookup).
2030
- * Used for `new User()` / `User()` calls where the calledName targets a class.
2031
- *
2032
- * Uses {@link TypeRegistry.lookupClassByName} for O(1) class lookup and
2033
- * {@link MethodRegistry.lookupMethodByOwner} for constructor resolution.
2034
- * {@link resolveCallTarget} delegates here for constructor and free-form calls
2035
- * that target a class.
2036
- *
2037
- * Resolution strategy:
2038
- * 1. `lookupClassByName(className)` — O(1) pre-check; bail early if no class exists.
2039
- * 2. `ctx.resolve(className, currentFile)` — import-scoped tier for confidence.
2040
- * 3. Filter to class-like candidates via `CLASS_LIKE_TYPES` and walk each
2041
- * with `lookupMethodByOwner(classNodeId, className, argCount)` — O(1)
2042
- * constructor lookup. Only accept results with `type === 'Constructor'`.
2043
- * 4. If step 3 found nothing and the tiered pool contains ownerless
2044
- * `Constructor` nodes (common in some extractors), bail out so
2045
- * `filterCallableCandidates` downstream handles Constructor-vs-Class
2046
- * preference correctly.
2047
- * 5. Class-node fallback: filter `classCandidates` through
2048
- * `INSTANTIABLE_CLASS_TYPES` and return the sole survivor when there is
2049
- * exactly one. Null-route on zero survivors (Interface / Trait / Impl
2050
- * stripped) or multiple (homonym ambiguity).
2051
- *
2052
- * @param className - The class name (e.g. 'User'). Also used as the method
2053
- * name for the `lookupMethodByOwner` scan, because the
2054
- * only constructor-shaped call we handle today is
2055
- * `ClassName(...)` / `new ClassName(...)`. Named
2056
- * constructors like Dart `User.fromJson()` arrive as
2057
- * member calls and route through `resolveMemberCall`,
2058
- * so this function does not yet need a separate
2059
- * `methodName` parameter. Revisit if a language surfaces
2060
- * a static-method-shaped call with a distinct member
2061
- * name.
2062
- * @param currentFile - File path of the call site
2063
- * @param ctx - Resolution context
2064
- * @param argCount - Optional argument count for arity filtering
2065
- * @param tieredOverride - Pre-computed tiered candidates for `className` from
2066
- * an upstream `ctx.resolve` call. When provided, skips
2067
- * the redundant lookup inside this function. Leave
2068
- * unset for direct callers without a prior resolution.
2069
- */
2070
- export const resolveStaticCall = (className, currentFile, ctx, argCount, tieredOverride, overloadHints, preComputedArgTypes) => {
2071
- // 1. Pre-check: does a class with this name exist at all? (O(1))
2072
- // This guards against the expensive `ctx.resolve` walk when the name
2073
- // is clearly not class-like (e.g. plain functions). When `tieredOverride`
2074
- // is supplied, the caller has already paid for the tiered lookup, so this
2075
- // pre-check still prevents the class-candidate filter + lookupMethodByOwner
2076
- // loop from running on obviously non-class targets.
2077
- const allClasses = ctx.model.types.lookupClassByName(className);
2078
- if (allClasses.length === 0)
2079
- return null;
2080
- // 2. Scope via ctx.resolve for import-tier information. Reuse the caller's
2081
- // tiered result when provided — it is computed from the same name and
2082
- // file context, so re-running the walk would be a pure waste.
2083
- const typeResolved = tieredOverride ?? ctx.resolve(className, currentFile);
2084
- if (!typeResolved)
2085
- return null;
2086
- const classCandidates = typeResolved.candidates.filter((c) => CLASS_LIKE_TYPES.has(c.type));
2087
- if (classCandidates.length === 0)
2088
- return null;
2089
- // 3. Try lookupMethodByOwner for explicit Constructor nodes.
2090
- // Only accept results with type === 'Constructor' — a Method or Function
2091
- // that happens to share the class name (e.g. C++ methods named after
2092
- // their class) is not a constructor for resolution purposes.
2093
- // Same dedup logic as resolveMethodByOwner: diamond inheritance converging
2094
- // on the same constructor collapses to one hit.
2095
- //
2096
- // Same-name assumption: the lookup key is `${candidate.nodeId}\0${className}`,
2097
- // so this finds Constructor nodes whose symbol name equals the class name
2098
- // (`class User` with a `Constructor` named `User`). Constructors indexed
2099
- // under a different name (e.g. Python `__init__`) will not be found here —
2100
- // but they also won't appear in the tiered pool for `ctx.resolve(className)`
2101
- // for the same reason, so step 4's Constructor-presence check will not
2102
- // see them either. The two miss cases are symmetric. If a future extractor
2103
- // indexes Constructor nodes under an alternative name while still setting
2104
- // `ownerId`, this assumption will need revisiting.
2105
- let firstDef;
2106
- let ambiguous = false;
2107
- for (const candidate of classCandidates) {
2108
- const def = ctx.model.methods.lookupMethodByOwner(candidate.nodeId, className, argCount);
2109
- if (!def || def.type !== 'Constructor')
2110
- continue;
2111
- if (!firstDef) {
2112
- firstDef = def;
2113
- }
2114
- else if (def.nodeId !== firstDef.nodeId) {
2115
- ambiguous = true;
2116
- break;
2117
- }
2118
- }
2119
- if (firstDef && !ambiguous) {
2120
- return toResolveResult(firstDef, typeResolved.tier);
2121
- }
2122
- // 4. lookupMethodByOwner found nothing — check whether the tiered pool
2123
- // contains Constructor nodes that lack ownerId (common in some extractors).
2124
- // If so, bail out so the existing filterCallableCandidates path handles
2125
- // Constructor-vs-Class preference correctly.
2126
- //
2127
- // This branch also catches the step-3 ambiguous case (`ambiguous = true`
2128
- // with two distinct Constructor nodes across multiple class candidates):
2129
- // the same Constructor nodes are indexed under the class name in the
2130
- // tiered pool, so `.some(Constructor)` is true here and we defer to
2131
- // step 4.5 (overload/arg-type disambiguation) or the caller's fallback.
2132
- // Do not remove this check without also handling the ambiguous step-3
2133
- // path explicitly.
2134
- if (typeResolved.candidates.some((c) => c.type === 'Constructor')) {
2135
- // 4.5. Overload / arg-type disambiguation for ambiguous or ownerless
2136
- // Constructor pools. When the caller supplied a narrowing signal
2137
- // (AST-based overload hints from the sequential path, or pre-
2138
- // computed arg types from the worker path), give disambiguation a
2139
- // chance before null-routing. Symmetric with resolveMemberCallByFile's
2140
- // disambiguation pass — both resolvers now share the same signal
2141
- // precedence via disambiguateByOverloadOrArgTypes. Only fires when
2142
- // at least one narrowing signal is present; preserves SM-10 R3 for
2143
- // genuinely ambiguous cases with no disambiguating input.
2144
- if (overloadHints || preComputedArgTypes) {
2145
- const ctorPool = filterCallableCandidates(typeResolved.candidates, argCount, 'constructor');
2146
- if (ctorPool.length > 1) {
2147
- const disambiguated = disambiguateByOverloadOrArgTypes(ctorPool, overloadHints, preComputedArgTypes);
2148
- if (disambiguated)
2149
- return toResolveResult(disambiguated, typeResolved.tier);
2150
- }
2151
- }
2152
- return null;
2153
- }
2154
- // 5. No constructor nodes at all — fall back to the class node itself, but
2155
- // ONLY when it is actually instantiable. Interface / Trait / Impl / Enum
2156
- // are deliberately excluded via `INSTANTIABLE_CLASS_TYPES` to prevent
2157
- // false `CALLS` edges from constructor-shaped calls to non-instantiable
2158
- // nodes. This also disambiguates the Rust same-file shadowing case
2159
- // (`struct User` + `impl User` both present at same-file tier): the
2160
- // Impl is stripped, leaving the Struct as the sole instantiable target.
2161
- // Addresses Codex review finding on PR #754.
2162
- const instantiableCandidates = classCandidates.filter((c) => INSTANTIABLE_CLASS_TYPES.has(c.type));
2163
- // Three outcomes below, in order of likelihood after the fix:
2164
- // length === 0 → all candidates were stripped as non-instantiable (e.g.
2165
- // Interface / Trait / Impl). Null-route via the fall-through `return
2166
- // null` — this is the dominant Codex-fix case.
2167
- // length === 1 → a single instantiable candidate remains, return it.
2168
- // length > 1 → let the call-site provider choose a primary when it can
2169
- // prove the candidates are one logical type; otherwise null-route.
2170
- const primary = resolveProviderPrimaryTypeCandidate(instantiableCandidates, typeResolved.tier, className, currentFile);
2171
- if (primary)
2172
- return primary;
2173
- if (instantiableCandidates.length === 1) {
2174
- return toResolveResult(instantiableCandidates[0], typeResolved.tier);
2175
- }
2176
- return null;
2177
- };
2178
- /**
2179
- * Create a deduplicated ACCESSES edge emitter for a single source node.
2180
- * Each (sourceId, fieldNodeId) pair is emitted at most once per source.
2181
- */
2182
- const makeAccessEmitter = (graph, sourceId) => {
2183
- const emitted = new Set();
2184
- return (fieldNodeId) => {
2185
- const key = `${sourceId}\0${fieldNodeId}`;
2186
- if (emitted.has(key))
2187
- return;
2188
- emitted.add(key);
2189
- graph.addRelationship({
2190
- id: generateId('ACCESSES', `${sourceId}:${fieldNodeId}:read`),
2191
- sourceId,
2192
- targetId: fieldNodeId,
2193
- type: 'ACCESSES',
2194
- confidence: 1.0,
2195
- reason: 'read',
2196
- });
2197
- };
2198
- };
2199
- const walkMixedChain = (chain, startType, filePath, ctx, onFieldResolved, heritageMap) => {
2200
- let currentType = startType;
2201
- for (const step of chain) {
2202
- if (!currentType)
2203
- break;
2204
- if (step.kind === 'field') {
2205
- const resolved = resolveFieldAccessType(currentType, step.name, filePath, ctx);
2206
- if (!resolved) {
2207
- currentType = undefined;
2208
- break;
2209
- }
2210
- onFieldResolved?.(resolved.fieldNodeId);
2211
- currentType = resolved.typeName;
2212
- }
2213
- else {
2214
- // Ruby/Python: property access is syntactically identical to method calls.
2215
- // Try field resolution first — if the name is a known property with declaredType,
2216
- // use that type directly. Otherwise fall back to method call resolution.
2217
- const fieldResolved = resolveFieldAccessType(currentType, step.name, filePath, ctx);
2218
- if (fieldResolved) {
2219
- onFieldResolved?.(fieldResolved.fieldNodeId);
2220
- currentType = fieldResolved.typeName;
2221
- continue;
2222
- }
2223
- // Fast path: O(1) owner-scoped method lookup via methodByOwner index.
2224
- // Note: CALLS edges for intermediate chain steps are NOT emitted here — walkMixedChain
2225
- // only threads types. CALLS edges come from the outer per-call-expression loop in processCalls.
2226
- //
2227
- // We call `resolveMethodByOwner` directly (NOT `resolveMemberCall`) because this is
2228
- // a hot path — called per chain step per call expression — and we only need the
2229
- // return type string. Going through `resolveMemberCall` would allocate a throwaway
2230
- // `ResolveResult` with confidence/reason that we immediately discard.
2231
- const owned = resolveMethodByOwner(currentType, step.name, filePath, ctx, heritageMap);
2232
- if (owned?.def.returnType) {
2233
- const fastRetType = extractReturnTypeName(owned.def.returnType);
2234
- if (fastRetType) {
2235
- currentType = fastRetType;
2236
- continue;
2237
- }
2238
- }
2239
- // Fallback: resolve via resolveCallTarget dispatcher (delegates to resolveMemberCall)
2240
- const resolved = resolveCallTarget({ calledName: step.name, callForm: 'member', receiverTypeName: currentType }, filePath, ctx, undefined, undefined, undefined, heritageMap);
2241
- if (!resolved) {
2242
- // Stdlib passthrough: unwrap(), clone(), etc. preserve the receiver type
2243
- if (TYPE_PRESERVING_METHODS.has(step.name))
2244
- continue;
2245
- currentType = undefined;
2246
- break;
2247
- }
2248
- if (!resolved.returnType) {
2249
- currentType = undefined;
2250
- break;
2251
- }
2252
- const retType = extractReturnTypeName(resolved.returnType);
2253
- if (!retType) {
2254
- currentType = undefined;
2255
- break;
2256
- }
2257
- currentType = retType;
2258
- }
2259
- }
2260
- return currentType;
2261
- };
2262
- /**
2263
- * Fast path: resolve pre-extracted call sites from workers.
2264
- * No AST parsing — workers already extracted calledName + sourceId.
2265
- *
2266
- * @param bindingAccumulator Phase 9: optional accumulator carrying file-scope
2267
- * TypeEnv bindings from all worker-processed files. When the SymbolTable has
2268
- * no return type for a cross-file callee, `verifyConstructorBindings` falls
2269
- * back to the accumulator via `namedImportMap` to bind the variable to the
2270
- * callee's resolved type (e.g. `var x = getUser()` → `x: User`).
2271
- */
2272
- export const processCallsFromExtracted = async (graph, extractedCalls, ctx, onProgress, constructorBindings, heritageMap, bindingAccumulator) => {
2273
- // Scope-aware receiver types: keyed by filePath → "funcName\0varName" → typeName.
2274
- // The scope dimension prevents collisions when two functions in the same file
2275
- // have same-named locals pointing to different constructor types.
2276
- const fileReceiverTypes = new Map();
2277
- if (constructorBindings) {
2278
- for (const { filePath, bindings } of constructorBindings) {
2279
- const verified = verifyConstructorBindings(bindings, filePath, ctx, graph, bindingAccumulator);
2280
- if (verified.size > 0) {
2281
- fileReceiverTypes.set(filePath, buildReceiverTypeIndex(verified));
2282
- }
2283
- }
2284
- }
2285
- const byFile = new Map();
2286
- for (const call of extractedCalls) {
2287
- let list = byFile.get(call.filePath);
2288
- if (!list) {
2289
- list = [];
2290
- byFile.set(call.filePath, list);
2291
- }
2292
- list.push(call);
2293
- }
2294
- const totalFiles = byFile.size;
2295
- let filesProcessed = 0;
2296
- // Counts only files that survived the registry-primary skip — what the user
2297
- // is actually waiting on. Keyed by this counter, the first per-file progress
2298
- // log fires on the first *resolved* file rather than file #1 of byFile,
2299
- // which would silently land inside the skip block on mixed Python+JVM repos
2300
- // where the skipped language sorts first.
2301
- let resolvedFiles = 0;
2302
- const profileCalls = isDeferredResolutionProfileEnabled();
2303
- const slowFileMs = profileCalls ? deferredCallFileSlowMs() : 0;
2304
- const logEveryN = profileCalls ? deferredCallLogEveryN() : 0;
2305
- let skippedRegistryPrimaryFiles = 0;
2306
- // Fresh dropped-log counter per analyze run — the module-private counter
2307
- // in deferred-resolution-profile.ts is process-lived, so without a reset
2308
- // here it would accumulate across consecutive analyze invocations in the
2309
- // same Node process (e.g., the MCP server, eval harness, integration
2310
- // tests).
2311
- if (profileCalls)
2312
- resetDeferredProfileDroppedCount();
2313
- // One-pass pre-count of the eventual non-skipped total so the live progress
2314
- // denominator stays stable as the loop iterates. Otherwise `${totalFiles -
2315
- // skippedRegistryPrimaryFiles}` drifts upward — files iterated before later
2316
- // registry-primary skips have been seen carry an inflated denominator, and
2317
- // the ratio only self-corrects after every file has been classified. Pre-
2318
- // count runs only on the enabled path so the disabled path stays free of
2319
- // the extra Map iteration. Defaults to 0 on the disabled path; the live log
2320
- // gate is also disabled there, so the value is never read.
2321
- let resolvedTotal = 0;
2322
- if (profileCalls) {
2323
- for (const filePath of byFile.keys()) {
2324
- const lang = getLanguageFromFilename(filePath);
2325
- if (!lang || !isRegistryPrimary(lang))
2326
- resolvedTotal++;
2327
- }
2328
- }
2329
- for (const [filePath, calls] of byFile) {
2330
- filesProcessed++;
2331
- if (filesProcessed % 100 === 0) {
2332
- onProgress?.(filesProcessed, totalFiles);
2333
- await yieldToEventLoop();
2334
- }
2335
- // Registry-primary gate: skip Python (etc.) entirely when the
2336
- // scope-based phase owns CALLS for this language.
2337
- const fileLanguage = getLanguageFromFilename(filePath);
2338
- if (fileLanguage && isRegistryPrimary(fileLanguage)) {
2339
- skippedRegistryPrimaryFiles++;
2340
- continue;
2341
- }
2342
- resolvedFiles++;
2343
- const tFile = startTimer(profileCalls);
2344
- if (profileCalls && (resolvedFiles === 1 || resolvedFiles % logEveryN === 0)) {
2345
- logDeferredProfile(`calls ${resolvedFiles}/${resolvedTotal} file=${filePath} sites=${calls.length}`);
2346
- }
2347
- ctx.enableCache(filePath);
2348
- const widenCache = new Map();
2349
- const receiverMap = fileReceiverTypes.get(filePath);
2350
- for (const call of calls) {
2351
- let effectiveCall = call;
2352
- // Step 1: resolve receiver type from constructor bindings
2353
- if (!call.receiverTypeName && call.receiverName && receiverMap) {
2354
- const callFuncName = extractFuncNameFromSourceId(call.sourceId);
2355
- const resolvedType = lookupReceiverType(receiverMap, callFuncName, call.receiverName);
2356
- if (resolvedType) {
2357
- effectiveCall = { ...call, receiverTypeName: resolvedType };
2358
- }
2359
- }
2360
- // Step 1b: class-as-receiver for static method calls (e.g. UserService.find_user())
2361
- if (!effectiveCall.receiverTypeName &&
2362
- effectiveCall.receiverName &&
2363
- effectiveCall.callForm === 'member') {
2364
- const typeResolved = ctx.resolve(effectiveCall.receiverName, effectiveCall.filePath);
2365
- if (typeResolved &&
2366
- typeResolved.candidates.some((d) => d.type === 'Class' ||
2367
- d.type === 'Interface' ||
2368
- d.type === 'Struct' ||
2369
- d.type === 'Enum')) {
2370
- effectiveCall = { ...effectiveCall, receiverTypeName: effectiveCall.receiverName };
2371
- }
2372
- }
2373
- // Step 1c: mixed chain resolution (field, call, or interleaved — e.g. svc.getUser().address.save()).
2374
- // Runs whenever receiverMixedChain is present. Steps 1/1b may have resolved the base receiver
2375
- // type already; that type is used as the chain's starting point.
2376
- if (effectiveCall.receiverMixedChain?.length) {
2377
- // Use the already-resolved base type (from Steps 1/1b) or look it up now.
2378
- let currentType = effectiveCall.receiverTypeName;
2379
- if (!currentType && effectiveCall.receiverName && receiverMap) {
2380
- const callFuncName = extractFuncNameFromSourceId(effectiveCall.sourceId);
2381
- currentType = lookupReceiverType(receiverMap, callFuncName, effectiveCall.receiverName);
2382
- }
2383
- if (!currentType && effectiveCall.receiverName) {
2384
- const typeResolved = ctx.resolve(effectiveCall.receiverName, effectiveCall.filePath);
2385
- if (typeResolved?.candidates.some((d) => d.type === 'Class' ||
2386
- d.type === 'Interface' ||
2387
- d.type === 'Struct' ||
2388
- d.type === 'Enum')) {
2389
- currentType = effectiveCall.receiverName;
2390
- }
2391
- }
2392
- if (currentType) {
2393
- const walkedType = walkMixedChain(effectiveCall.receiverMixedChain, currentType, effectiveCall.filePath, ctx, makeAccessEmitter(graph, effectiveCall.sourceId), heritageMap);
2394
- if (walkedType) {
2395
- effectiveCall = { ...effectiveCall, receiverTypeName: walkedType };
2396
- }
2397
- }
2398
- }
2399
- const resolved = resolveCallTarget(effectiveCall, effectiveCall.filePath, ctx, undefined, widenCache, effectiveCall.argTypes, heritageMap);
2400
- if (!resolved) {
2401
- // Vue template component fallback: match calledName against imported .vue basenames
2402
- if (effectiveCall.filePath.endsWith('.vue') && effectiveCall.sourceId.startsWith('File:')) {
2403
- const importedFiles = ctx.importMap.get(effectiveCall.filePath);
2404
- if (importedFiles) {
2405
- for (const importedPath of importedFiles) {
2406
- if (!importedPath.endsWith('.vue'))
2407
- continue;
2408
- const basename = importedPath.slice(importedPath.lastIndexOf('/') + 1, importedPath.lastIndexOf('.'));
2409
- if (basename !== effectiveCall.calledName)
2410
- continue;
2411
- const targetFileId = generateId('File', importedPath);
2412
- if (graph.getNode(targetFileId)) {
2413
- graph.addRelationship({
2414
- id: generateId('CALLS', `${effectiveCall.sourceId}:${effectiveCall.calledName}->${targetFileId}`),
2415
- sourceId: effectiveCall.sourceId,
2416
- targetId: targetFileId,
2417
- type: 'CALLS',
2418
- confidence: 0.9,
2419
- reason: 'vue-template-component',
2420
- });
2421
- }
2422
- break;
2423
- }
2424
- }
2425
- }
2426
- continue;
2427
- }
2428
- const relId = generateId('CALLS', `${effectiveCall.sourceId}:${effectiveCall.calledName}->${resolved.nodeId}`);
2429
- graph.addRelationship({
2430
- id: relId,
2431
- sourceId: effectiveCall.sourceId,
2432
- targetId: resolved.nodeId,
2433
- type: 'CALLS',
2434
- confidence: resolved.confidence,
2435
- reason: resolved.reason,
2436
- });
2437
- if (heritageMap && effectiveCall.callForm === 'member' && effectiveCall.receiverTypeName) {
2438
- const implTargets = findInterfaceDispatchTargets(effectiveCall.calledName, effectiveCall.receiverTypeName, effectiveCall.filePath, ctx, heritageMap, resolved.nodeId);
2439
- for (const impl of implTargets) {
2440
- graph.addRelationship({
2441
- id: generateId('CALLS', `${effectiveCall.sourceId}:${effectiveCall.calledName}->${impl.nodeId}`),
2442
- sourceId: effectiveCall.sourceId,
2443
- targetId: impl.nodeId,
2444
- type: 'CALLS',
2445
- confidence: impl.confidence,
2446
- reason: impl.reason,
2447
- });
2448
- }
2449
- }
2450
- }
2451
- ctx.clearCache();
2452
- if (tFile !== null) {
2453
- const elapsed = profileElapsedMs(tFile);
2454
- if (elapsed >= slowFileMs) {
2455
- logDeferredProfile(`slow file ${elapsed.toFixed(0)}ms path=${filePath} calls=${calls.length} lang=${fileLanguage ?? 'unknown'}`);
2456
- }
2457
- }
2458
- }
2459
- if (profileCalls) {
2460
- logDeferredProfile(`processCallsFromExtracted done: ${totalFiles} files, ${extractedCalls.length} call sites, skipped registry-primary files=${skippedRegistryPrimaryFiles}`);
2461
- const droppedCount = getDeferredProfileDroppedCount();
2462
- if (droppedCount > 0) {
2463
- logDeferredProfile(`note: ${droppedCount} profile log lines dropped (logger errors)`);
2464
- }
2465
- }
2466
- onProgress?.(totalFiles, totalFiles);
2467
- };
2468
- /**
2469
- * Resolve pre-extracted field write assignments to ACCESSES {reason: 'write'} edges.
2470
- * Accepts optional constructorBindings for return-type-aware receiver inference,
2471
- * mirroring processCallsFromExtracted's verified binding lookup.
2472
- */
2473
- export const processAssignmentsFromExtracted = (graph, assignments, ctx, constructorBindings, bindingAccumulator) => {
2474
- // Build per-file receiver type indexes from verified constructor bindings
2475
- const fileReceiverTypes = new Map();
2476
- if (constructorBindings) {
2477
- for (const { filePath, bindings } of constructorBindings) {
2478
- const verified = verifyConstructorBindings(bindings, filePath, ctx, graph, bindingAccumulator);
2479
- if (verified.size > 0) {
2480
- fileReceiverTypes.set(filePath, buildReceiverTypeIndex(verified));
2481
- }
2482
- }
2483
- }
2484
- for (const asn of assignments) {
2485
- // Resolve the receiver type
2486
- let receiverTypeName = asn.receiverTypeName;
2487
- // Tier 2: verified constructor bindings (return-type inference)
2488
- if (!receiverTypeName && fileReceiverTypes.size > 0) {
2489
- const receiverMap = fileReceiverTypes.get(asn.filePath);
2490
- if (receiverMap) {
2491
- const funcName = extractFuncNameFromSourceId(asn.sourceId);
2492
- receiverTypeName = lookupReceiverType(receiverMap, funcName, asn.receiverText);
2493
- }
2494
- }
2495
- // Tier 3: static class-as-receiver fallback
2496
- if (!receiverTypeName) {
2497
- const resolved = ctx.resolve(asn.receiverText, asn.filePath);
2498
- if (resolved?.candidates.some((d) => CLASS_LIKE_TYPES.has(d.type))) {
2499
- receiverTypeName = asn.receiverText;
2500
- }
2501
- }
2502
- if (!receiverTypeName)
2503
- continue;
2504
- const fieldOwner = resolveFieldOwnership(receiverTypeName, asn.propertyName, asn.filePath, ctx);
2505
- if (!fieldOwner)
2506
- continue;
2507
- graph.addRelationship({
2508
- id: generateId('ACCESSES', `${asn.sourceId}:${fieldOwner.nodeId}:write${asn.line !== undefined ? `:${asn.line}` : ''}`),
2509
- sourceId: asn.sourceId,
2510
- targetId: fieldOwner.nodeId,
2511
- type: 'ACCESSES',
2512
- confidence: 1.0,
2513
- reason: 'write',
2514
- });
2515
- }
2516
- };
103
+ let best;
104
+ let bestScore = 0;
105
+ let tie = false;
106
+ for (const candidate of candidates) {
107
+ // Compare the FQN's namespace tail against the file path's directory tail
108
+ // (PSR-4: `App\Admin\OrderController` ↔ `app/Admin/OrderController.php`).
109
+ // Split on `/` (a path separator normalizeQualifiedName does not touch).
110
+ const fileBase = candidate.filePath.replace(/\.[^./]+$/, '');
111
+ const fileSegments = fileBase.split('/').filter((s) => s.length > 0);
112
+ let score = 0;
113
+ while (score < fqnSegments.length &&
114
+ score < fileSegments.length &&
115
+ fqnSegments[fqnSegments.length - 1 - score].toLowerCase() ===
116
+ fileSegments[fileSegments.length - 1 - score].toLowerCase()) {
117
+ score++;
118
+ }
119
+ if (score > bestScore) {
120
+ bestScore = score;
121
+ best = candidate;
122
+ tie = false;
123
+ }
124
+ else if (score === bestScore) {
125
+ tie = true;
126
+ }
127
+ }
128
+ // Need the class name + at least one namespace segment to disambiguate, and a
129
+ // single unambiguous winner.
130
+ return bestScore >= 2 && !tie ? best : undefined;
131
+ }
2517
132
  /**
2518
- * Resolve pre-extracted Laravel routes to CALLS edges from route files to controller methods.
2519
- */
2520
- export const processRoutesFromExtracted = async (graph, extractedRoutes, ctx, onProgress) => {
133
+ * Create CALLS edges from extracted framework routes (e.g. Laravel) to their
134
+ * controller methods. Runs for all languages — independent of call resolution.
135
+ *
136
+ * Resolution is registry-based (RING4-2 #943 retired the tiered resolver):
137
+ * - Controller: **qualified-first** (see {@link resolveControllerByQualifiedName}).
138
+ * When the routes file disambiguated the controller, the Laravel extractor
139
+ * threads `route.controllerQualifiedName` (a `use` import — incl. aliased
140
+ * `use … as X;` — or an inline qualified `::class`, normalized to the dot-
141
+ * joined key shape). The emitter resolves it by direct qualified lookup, or
142
+ * by PSR-4 file-path disambiguation when PHP's statement-form namespace left
143
+ * the registry keyed only by the short name — either way picking the
144
+ * specific class even when the short name is globally duplicated (the common
145
+ * admin/public `OrderController` split) or aliased. It falls back to the
146
+ * global short-name lookup (`lookupClassByName`), which still skips on
147
+ * ambiguity (`length !== 1`) — so a bare, genuinely ambiguous short name
148
+ * with no `use`/FQN correctly produces no (wrong) edge.
149
+ * - Method: resolved within the controller's own file via the symbol table
150
+ * (the legacy emitter only accepted same-file method resolutions).
151
+ *
152
+ * Edge confidence is a flat {@link ROUTE_EDGE_CONFIDENCE}. Route CALLS edges
153
+ * are gated downstream by the process-trace (`MIN_TRACE_CONFIDENCE`) and
154
+ * large-graph community (`MIN_CONFIDENCE_LARGE`) thresholds (both 0.5); a
155
+ * resolved edge lands at exactly 0.5 and passes (`>= 0.5`). The guessed-method
156
+ * fallback edge (`× 0.8` = 0.4) sits below the gate and is excluded from those
157
+ * passes — acceptable for an edge whose target method could not be resolved.
158
+ */
159
+ export const processRoutesFromExtracted = async (graph, extractedRoutes, model, onProgress) => {
2521
160
  for (let i = 0; i < extractedRoutes.length; i++) {
2522
161
  const route = extractedRoutes[i];
2523
162
  if (i % 50 === 0) {
@@ -2526,15 +165,28 @@ export const processRoutesFromExtracted = async (graph, extractedRoutes, ctx, on
2526
165
  }
2527
166
  if (!route.controllerName || !route.methodName)
2528
167
  continue;
2529
- const controllerResolved = ctx.resolve(route.controllerName, route.filePath);
2530
- if (!controllerResolved || controllerResolved.candidates.length === 0)
2531
- continue;
2532
- if (controllerResolved.tier === 'global' && controllerResolved.candidates.length > 1)
2533
- continue;
2534
- const controllerDef = controllerResolved.candidates[0];
2535
- const confidence = TIER_CONFIDENCE[controllerResolved.tier];
2536
- const methodResolved = ctx.resolve(route.methodName, controllerDef.filePath);
2537
- const methodId = methodResolved?.tier === 'same-file' ? methodResolved.candidates[0]?.nodeId : undefined;
168
+ // Resolve the controller class. Qualified-first: when the routes file
169
+ // disambiguated the controller (a `use` import or inline `::class` FQN, both
170
+ // normalized to the registry's dot-joined key shape by the extractor), look
171
+ // it up by qualified name this resolves aliased imports and same-short-name
172
+ // controllers in different namespaces. Fall back to the global short-name
173
+ // lookup, which still refuses ambiguous matches (`length !== 1 → skip`),
174
+ // mirroring the legacy global tier.
175
+ let controllerDef;
176
+ if (route.controllerQualifiedName) {
177
+ controllerDef = resolveControllerByQualifiedName(model, route.controllerQualifiedName);
178
+ }
179
+ if (!controllerDef) {
180
+ const controllerDefs = model.types.lookupClassByName(route.controllerName);
181
+ if (controllerDefs.length !== 1)
182
+ continue;
183
+ controllerDef = controllerDefs[0];
184
+ }
185
+ const confidence = ROUTE_EDGE_CONFIDENCE;
186
+ // Method must live in the controller's own file (the legacy emitter only
187
+ // accepted same-file method resolutions).
188
+ const methodDefs = model.symbols.lookupExactAll(controllerDef.filePath, route.methodName);
189
+ const methodId = methodDefs[0]?.nodeId;
2538
190
  const sourceId = generateId('File', route.filePath);
2539
191
  if (!methodId) {
2540
192
  const guessedId = generateId('Method', `${controllerDef.filePath}:${route.methodName}`);
@@ -2561,20 +213,6 @@ export const processRoutesFromExtracted = async (graph, extractedRoutes, ctx, on
2561
213
  }
2562
214
  onProgress?.(extractedRoutes.length, extractedRoutes.length);
2563
215
  };
2564
- /**
2565
- * Extract property access keys from a consumer file's source code near fetch calls.
2566
- *
2567
- * Looks for three patterns after a fetch/response variable assignment:
2568
- * 1. Destructuring: `const { data, pagination } = await res.json()`
2569
- * 2. Property access: `response.data`, `result.items`
2570
- * 3. Optional chaining: `data?.key1?.key2`
2571
- *
2572
- * Returns deduplicated top-level property names accessed on the response.
2573
- *
2574
- * NOTE: This scans the entire file content, not just code near a specific fetch call.
2575
- * If a file has multiple fetch calls to different routes, all accessed keys are
2576
- * attributed to each fetch. This is an acceptable tradeoff for regex-based extraction.
2577
- */
2578
216
  /** Common method names on response/data objects that are NOT property accesses */
2579
217
  // Properties/methods to ignore when extracting consumer accessed keys from `data.X` patterns.
2580
218
  // Avoids false positives from Fetch API, Array, Object, Promise, and DOM access on variables
@@ -2658,6 +296,15 @@ const RESPONSE_ACCESS_BLOCKLIST = new Set([
2658
296
  'textContent',
2659
297
  'innerText',
2660
298
  ]);
299
+ /**
300
+ * Extract property access keys from a consumer file's source code near fetch calls.
301
+ *
302
+ * Looks for destructuring (`const { data } = await res.json()`), property access
303
+ * (`response.data`), and optional chaining (`data?.key`). Returns deduplicated
304
+ * top-level property names accessed on the response. Scans the whole file, so
305
+ * all accessed keys are attributed to each fetch — acceptable for regex-based
306
+ * extraction.
307
+ */
2661
308
  export const extractConsumerAccessedKeys = (content) => {
2662
309
  const keys = new Set();
2663
310
  // Pattern 1: Destructuring from .json() — const { key1, key2 } = await res.json()
@@ -2754,73 +401,3 @@ consumerContents) => {
2754
401
  }
2755
402
  }
2756
403
  };
2757
- /**
2758
- * Extract fetch() calls from source files (sequential path).
2759
- * Workers handle this via tree-sitter captures in parse-worker; this function
2760
- * provides the same extraction for the sequential fallback path.
2761
- */
2762
- export const extractFetchCallsFromFiles = async (files, astCache) => {
2763
- const parser = await loadParser();
2764
- const result = [];
2765
- for (const file of files) {
2766
- const language = getLanguageFromFilename(file.path);
2767
- if (!language)
2768
- continue;
2769
- if (!isLanguageAvailable(language))
2770
- continue;
2771
- const provider = getProvider(language);
2772
- const queryStr = provider.treeSitterQueries;
2773
- if (!queryStr)
2774
- continue;
2775
- await loadLanguage(language, file.path);
2776
- let tree = astCache.get(file.path);
2777
- if (!tree) {
2778
- const parseContent = provider.preprocessSource?.(file.content, file.path) ?? file.content;
2779
- try {
2780
- tree = parseSourceSafe(parser, parseContent, undefined, {
2781
- bufferSize: getTreeSitterBufferSize(parseContent),
2782
- });
2783
- }
2784
- catch {
2785
- continue;
2786
- }
2787
- astCache.set(file.path, tree);
2788
- }
2789
- let matches;
2790
- try {
2791
- const lang = parser.getLanguage();
2792
- const query = new Parser.Query(lang, queryStr);
2793
- matches = query.matches(tree.rootNode);
2794
- }
2795
- catch {
2796
- continue;
2797
- }
2798
- for (const match of matches) {
2799
- const captureMap = {};
2800
- match.captures.forEach((c) => (captureMap[c.name] = c.node));
2801
- if (captureMap['route.fetch']) {
2802
- const urlNode = captureMap['route.url'] ?? captureMap['route.template_url'];
2803
- if (urlNode) {
2804
- result.push({
2805
- filePath: file.path,
2806
- fetchURL: urlNode.text,
2807
- lineNumber: captureMap['route.fetch'].startPosition.row,
2808
- });
2809
- }
2810
- }
2811
- else if (captureMap['http_client'] && captureMap['http_client.url']) {
2812
- const method = captureMap['http_client.method']?.text;
2813
- const url = captureMap['http_client.url'].text;
2814
- const HTTP_CLIENT_ONLY = new Set(['head', 'options', 'request', 'ajax']);
2815
- if (method && HTTP_CLIENT_ONLY.has(method) && url.startsWith('/')) {
2816
- result.push({
2817
- filePath: file.path,
2818
- fetchURL: url,
2819
- lineNumber: captureMap['http_client'].startPosition.row,
2820
- });
2821
- }
2822
- }
2823
- }
2824
- }
2825
- return result;
2826
- };