GitNexus/gitnexus-shared/src
Gergő Magyar 1abcac9c16
fix(scope-resolution): stop platform builtins resolving to unrelated same-file symbols (#2549)
* fix(scope-resolution): stop platform builtins resolving to unrelated same-file symbols (#2545)

An unqualified call to a platform/language builtin (e.g. TypeScript's
global fetch()) could resolve to an unrelated same-file declaration
sharing that name, most visibly a Cloudflare Worker's
`export default { async fetch(req) {...} }` handler. Two contributing
gaps, both fixed:

- Object literals had no scope boundary in the TS/JS grammar queries,
  so a method's/property-arrow's name auto-hoisted past the literal
  into whatever lexically enclosed it (scope-extractor.ts's auto-hoist
  logic had nowhere to stop). Give object literals a Block scope, like
  6 other languages already do for lexical blocks.

- Independently, finalize's per-file bindings bucket
  (materializeBindings in gitnexus-shared) flattens every local
  declaration in a file onto its module scope for cross-file import
  resolution, regardless of true nesting -- so free-call-fallback's
  scope-chain walk could still hit the leaked binding at module scope.
  Guard free-call resolution: when a match for a known builtin name
  (LanguageProvider.isBuiltInName, already populated for TS/JS but
  never consulted by this pass) has no binding reachable via the true
  lexical scope chain, leave the call unresolved instead of emitting a
  false CALLS edge.

Verified against the full TS/JS resolver suites plus every other
language populating builtInNames (Python, Go, C/C++, C#, Dart, Kotlin,
PHP, Ruby, Rust, Swift, Vue) -- 2333 tests, no regressions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(scope-resolution): extend the #2545 scope-leak fix to Kotlin and Java

Anonymous object-expressions (Kotlin `object { ... }`) and anonymous
class bodies (Java `new Runnable() { ... }`) have the same missing
scope-boundary gap that caused #2545 in TypeScript/JavaScript: a method
declared inside has no scope of its own to stop the auto-hoist at, so
its name leaks past the container into the enclosing scope.

- Kotlin: `(object_literal) @scope.class` (distinct from the already-
  scoped named `object_declaration`/`companion_object`). Kotlin already
  populates `builtInNames`, so free-call-fallback's isBuiltInName guard
  (added for #2545) fully closes the equivalent leak here too --
  verified with a `println`-shadowing regression test.

- Java: `(object_creation_expression (class_body) @scope.class)`,
  matching PHP's existing `anonymous_class` handling. Java has no
  `builtInNames` list, so the isBuiltInName guard doesn't engage --
  the scope-tree fix is still correct and necessary (the anonymous
  class's own methods are now owned by the right scope), but an
  unqualified call to an unrelated same-file method sharing the
  anonymous class's method name can still resolve via finalize's
  per-file module-scope bucket (materializeBindings, shared/
  language-agnostic, intentionally not touched by this PR). Documented
  in the test as a known residual gap, same as TS/JS/Kotlin's own
  non-builtin-name collisions.

Audited every other language for the same shape (a value/container
node with no @scope.* capture hosting a would-be-auto-hoisted named
declaration): PHP and Vue already handle it correctly (PHP scopes
anonymous_class; Vue's <script> delegates to the now-fixed TS/JS
query). Ruby, Python, Dart, C#, Swift, Go, Rust, and C/C++ have no
query pattern that treats a literal/container value position as a
named declaration in the first place, so the bug shape can't occur
there.

Verified: full Kotlin + Java resolver suites, 468 tests, no
regressions.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(scope-resolution): dedicated Object scope kind for object literals (#2545, #2551)

Review of the #2545 fix surfaced two defects, both fixed here:

1. The isBuiltInName guard suppressed genuine cross-file imports whose
   name matches a builtin (`import { fetch } from './fetch-polyfill'`
   silently stopped resolving -- verified regression vs. main). The
   leak the guard targets is inherently same-file (finalize's flat
   bucket is per-file), so the guard now also requires
   `fnDef.filePath === parsed.filePath`. New regression test covers
   the polyfill-import shape.

2. The sibling-property case of the reported bug was still broken and
   masked by a tautological assertion (`c.reason` -- a property that
   doesn't exist; the real path is `c.rel.reason` -- so the test
   passed regardless of behavior). In
   `export default { fetch() {...}, handler: () => fetch(...) }`,
   `handler`'s bare `fetch()` still resolved to its sibling. Reusing
   the `Block` scope kind was the root cause: correct for a real
   lexical block (a nested closure legitimately sees a sibling
   `let`/`const` from an enclosing `if`/`for`), wrong for object
   literals, whose members are reachable only via property access --
   never as bare identifiers, not even by sibling property bodies.

   Fix: a dedicated `Object` ScopeKind (gitnexus-shared) -- a hoist
   boundary whose own bindings scope-chain walkers never consult while
   still traversing past it to the parent. TS/JS object literals now
   emit `@scope.object`; the four chain walkers in
   scope-resolution/scope/walkers.ts (walkScopeChain,
   findAllCallableBindingsInScope, findCallableBindingsAndAdlBlocker,
   findExportedDefByName) and free-call-fallback's
   hasGenuineLexicalBinding skip Object scopes' bindings. Kotlin's
   anonymous `object {}` keeps `@scope.class` -- unlike JS object
   literals it has real implicit-this sibling dispatch.

Verified with the full resolver matrix run sequentially (TS 254, JS/
Kotlin/Java/Python/Go + TS variants 960, C/C++/C#/Dart/PHP/Ruby 1049,
Rust/Swift/Vue/Cobol + route/flow/unit suites 828, scope-extractor/
scope-tree units 51). Worker-pool crashes under parallel suite load
reproduced on unrelated files and pass in isolation (known flake, not
caused by this change).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(autofix): apply prettier + eslint fixes via /autofix command

* feat(java): model anonymous class bodies as first-class Class nodes (#2550, step 1)

`new Runnable() { public void run() {} }` now emits a synthesized
javac-style `Class` node (`Worker$1`, `$N` = source order within the
top-level class) and owns its methods: the enclosing-owner walk
attributes `run` to `Worker$1` (re-keyed `Method:...:Worker$1.run#0`,
HAS_METHOD from the anonymous class) instead of the lexically enclosing
named class.

- `synthesizeJavaAnonymousClassName` (ast-helpers): single naming
  authority for every layer that keys the anonymous class; returns
  undefined for `object_creation_expression` without a `class_body`
  child, which also keeps it a no-op for C#'s same-named node type.
- `findEnclosingClassInfo`: anonymous-body branch before the generic
  container walk.
- JAVA_QUERIES: `(object_creation_expression (class_body))
  @definition.class` (no @name); `getLabelFromCaptures` now lets a
  nameless `definition.class` through — the parse-worker's existing
  `!nameNode && !extractedClassSymbol` gate still drops any nameless
  class the extractor cannot name, so other languages are unaffected.
- `javaClassConfig.extractName` synthesizes the name on the extractor
  path (worker node emission).
- Node identities move on unchanged files: INCREMENTAL_SCHEMA_VERSION
  7→8 and parse-cache SCHEMA_BUMP 17→18 (the v5 Route-identity
  precedent) force full re-analyze / cache invalidation.

Verified: new #2550 identity tests + resolve-enclosing-owner and
has-method suites (53 tests) green.

Prep for step 2/3 (scope-side ownership + receiver typeBinding) and the
free-call instance-ownership gate per
docs/plans/2026-07-18-gitnexus-plan-java-instance-scoped-freecalls.md
(plan file is local — docs/ is gitignored by repo policy).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(java): instance-scoped free-call resolution for anonymous-class methods (#2550, steps 2-4)

Completes the #2550 instance model on top of the Worker$N identity
commit:

- Scope-side ownership (java/captures.ts): synthesize
  `@declaration.class` + `@declaration.name` (`Worker$N`) anchored on
  the anonymous `class_body` — same range as its `@scope.class`, so the
  def lands in that Class scope's ownedDefs, `populateClassOwnedMembers`
  stamps `ownerId` on the anonymous class's methods, and the name
  auto-hoists exactly like a named class declaration.

- Receiver typeBinding (java/captures.ts + type-extractors/jvm.ts):
  `Runnable handler = new Runnable() { ... }` binds `handler` to the
  ANONYMOUS class (`Worker$1`), not the declared JDK interface — in both
  the scope-side TypeRef channel (receiver-bound Case 4) and the worker
  typeEnv. `handler.run()` now resolves through the receiver path
  (reason 'global', target `Worker$1.run#0`) instead of depending on
  the free-call finalize-bucket leak — which is why the prior gate
  attempt broke it (the #2550 landmine, now explained and structurally
  removed).

- Instance-ownership gate (free-call-fallback.ts + contract + run.ts +
  java opt-in): with `ScopeResolver.freeCallsRequireInstanceOwnership`,
  a free call may resolve to a `Method` only when the caller's
  enclosing class chain (self + MRO via `scopes.methodDispatch.mroFor`)
  contains the method's owner. Same-file matches only — the
  `materializeBindings` leak is per-file; cross-file Method matches come
  through genuine import channels (suppressing them broke the
  arity-narrowing parity suite, verified). Suppressions recorded as
  `'free-call-instance-ownership'` outcomes. Java opts in; every other
  language is byte-identical (flag off).

Result on the #2545 fixture: `process()`'s bare `run()` emits NO edge
to the unrelated anonymous method (the #2550 bug, closed), while
`handler.run()`, same-class implicit-this dispatch, and bare inherited
calls (MRO arm) all keep resolving.

Verified: full java.test.ts 223/223 twice sequentially (landmine gate);
cross-language matrix (TS/JS/Kotlin/Python/Go/C/C++/C#/Dart/PHP/Ruby/
Rust/Swift/Vue/Cobol + callable-value-flow + java-class-impact + core
units) — zero assertion failures; worker-crash flakes re-verified green
in single-file isolation.

Known deferral (documented): EXTENDS/IMPLEMENTS edges from the
anonymous class to its constructed type are not yet emitted, so a
same-file inherited-but-not-overridden member called ON the anonymous
instance does not resolve through the anon MRO; tracked as the
follow-up in #2550.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(autofix): apply prettier + eslint fixes via /autofix command

* fix(java): anonymous-class inheritance, host coverage, and phantom-node guard (#2550 review)

Self-review of the instance model (gitnexus-review with empirical lens
probes) surfaced three defects, all fixed:

1. HIGH — the ownership gate suppressed TRUE bare calls to inherited
   methods inside an anonymous body extending a same-file class
   (`new Base() { void extra() { work(); } }` lost `extra -> work`):
   the anon class had no inheritance edge, so `mroFor(Worker$N)` was
   empty and the MRO arm could never pass. The synthesis now emits an
   `@reference.inherits` for the constructed type, anchored on the
   `class_body` so the reference's enclosing class resolves to the
   SYNTHESIZED def (anchoring on the type node would sit outside the
   anonymous scope and attribute the edge to the wrong class). Anon
   classes now get real EXTENDS/IMPLEMENTS edges and inherited bare
   calls pass the gate.

2. MEDIUM — hostless anonymous bodies materialized a phantom Class
   node named after the CONSTRUCTED type (`Class:...:Runnable`) via
   extract()'s extractTypeNameFromNode fallback. New
   `shouldSkipClassCapture` in javaClassConfig drops the capture when
   no name can be synthesized.

3. MEDIUM — enum/interface/record-hosted anonymous bodies silently
   fell back to the pre-#2550 model (mis-attribution + open leak).
   The topmost-host walk now accepts all four host type declarations
   (JAVA_ANON_HOST_TYPES), so `EnumHost$1` etc. are modeled; the
   phantom-node shape disappears for those hosts as a side effect.

Also: per-parse-tree WeakMap memo for the `$N` numbering — the helper
is called from four independent layers per anonymous body and each call
re-scanned the host subtree (`descendantsOfType`), quadratic on
anon-heavy files (old-style listener-per-widget Java); and the
scope-capture bench fingerprints rebaselined for java/typescript/
javascript/kotlin (`measure.mjs --check` now passes all 14 languages —
it failed for every scope query this PR touched; drift notes added per
the file's convention).

Verified: full java.test.ts 225/225; all 11 #2550 tests including the
new anon-extends-base and enum-host scenarios; bench --check PASS.

Known remaining (documented, unchanged-old behavior): enum CONSTANT
bodies (`A { ... }`) stay unmodeled; nested-host naming is top-level-
anchored (`EnumWrap$1`, not javac's `EnumWrap$Mode$1`).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(autofix): apply prettier + eslint fixes via /autofix command

* test(storage): update the INCREMENTAL_SCHEMA_VERSION pin to v8 (#2550)

The U-C5 reuse-gate test deliberately pins the exact schema version so
a bump cannot land without consciously extending the gate expectations.
Extend for v8 (Java anonymous-class node identities, #2550): a v7 stamp
now fails the strict-equality reuse gate — a pre-v8 index would strand
old `Worker.run`-keyed Method nodes alongside the re-keyed
`Worker$N.run` ones on unchanged files — and v8 passes.

Caught by CI (tests/ubuntu coverage shard 2/3 on PR #2549); the local
matrix had not included this unit file. All 7 schema-referencing unit
suites verified green (109 tests).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-18 14:30:37 +01:00
..
graph feat: add Spring DI resolver for @Autowired List<T> injection (#2200) 2026-07-02 17:49:46 +01:00
integrations fix(embeddings): make HTTP generation resumable 2026-07-14 02:15:57 +07:00
lbug feat: add Spring DI resolver for @Autowired List<T> injection (#2200) 2026-07-02 17:49:46 +01:00
scope-resolution fix(scope-resolution): stop platform builtins resolving to unrelated same-file symbols (#2549) 2026-07-18 14:30:37 +01:00
index.ts fix(scope-resolution): resolve callable reference flows (#2437) (#2522) 2026-07-17 17:20:02 +01:00
language-detection.ts feat(cpp): parse CUDA source extensions (#2213) 2026-06-16 07:32:53 +01:00
languages.ts feat(vue): Vue SFC support + destructured call result tracking (#604) 2026-04-03 14:18:55 +05:30
mro-strategy.ts feat(ingestion): language-agnostic heritage extractor with config+factory pattern (#890) 2026-04-17 17:51:17 +01:00
pipeline.ts feat(progress): add per-language progress reporting to scope-resolution phase (#1813) 2026-05-25 11:53:54 +01:00
test-helpers.ts feat: shared resilient-fetch (retries + circuit breaker) (#1448) 2026-05-09 15:18:09 +01:00