diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml index 83fbe37349..96146dbb40 100644 --- a/.github/workflows/ci-tests.yml +++ b/.github/workflows/ci-tests.yml @@ -833,7 +833,7 @@ jobs: if: ${{ !cancelled() }} # Build-free: same baseline approach as parse-dispatch-rounds — # exact declared/SDK/undeclared floors plus a fingerprint, then - # ratio timing only (resolveSwiftImportTarget, swiftPackageStrategy, + # ratio timing only (resolveSwiftImportTarget, # parseSwiftPackageManifest 4n/n). Pins declaration-only resolve, # https:// factory survival, and #2931 segment-boundary membership. # See bench/swift-package-imports/measure.mjs. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3a6ec294e2..26991fc412 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,7 +69,7 @@ Group-mode `trace` (`gitnexus/src/core/group/cross-trace.ts`) stitches a path th | Embeddings | `src/core/embeddings/` + `src/core/run-analyze.ts` | | Wiki generation | `src/core/wiki/` | | Language support | `src/core/ingestion/languages/` + `tree-sitter-queries.ts` + `gitnexus-shared/src/languages.ts` | -| Import resolution | `src/core/ingestion/import-processor.ts` + `import-resolvers/configs/` + `model/resolution-context.ts` | +| Import resolution | `src/core/ingestion/scope-resolution/pipeline/run.ts` + per-language `ScopeResolver.resolveImportTarget` hooks | | Call resolution/inheritance/MRO | `src/core/ingestion/scope-resolution/` (pipeline, passes, graph-bridge) | | Type extraction | `src/core/ingestion/type-extractors/` | | Worker pool | `src/core/ingestion/workers/` | @@ -389,13 +389,16 @@ Single interface a language implements to plug into the pipeline. Contract fully | `fieldFallbackOnMethodLookup?` | Statically-typed languages turn this OFF — the heuristic over-connects (default on) | | `elementTypeOf?` | `(containerType, via: {kind:'index'} \| {kind:'accessor',name}) → elementType \| undefined` — element type of a container, reached by subscript (`repos[0]`) or by a property-style collection view (`data.Values`). ONE hook for both routes (it replaced the split `unwrapCollectionAccessor` / `unwrapCollectionElement`, where implementing one silently answered nothing for the other). Consulted only where the source actually performed the access — never as a general type-name normalizer | | `stripTypePreservingDecoration?` | `(typeName) → strippedName \| undefined` — strip ONE layer of TYPE-PRESERVING decoration (pointer, reference, `const`, nullable, borrow, sigil) so a receiver declared `*Host` still finds the `Host` binding (#2766). Never a container: unwrapping `Repo[]` here would fold `repos.find(x)` to `Repo.find` — that is `elementTypeOf`'s job, and only after a real subscript. Consulted only after every undecorated lookup fails, and only by receiver-chain base/step resolution — default off | -| `qualifiedTypeLookupSpelling?` | `(typeRef) → 'pkg.Type' \| undefined` — the namespace-qualified spelling of a declared type whose qualifier capture cut from `rawName` (`*models.User` stored as `User`), recovered from `declaredSpelling`. Receiver typing tries it first, grounded on the qualifier's import (no unique-name guess), and falls back to the bare `rawName` lookup on any miss, so two packages' same-named types stop colliding. The binding is not rewritten — default off | +| `qualifiedTypeLookupSpelling?` | `(typeRef, scopes?) → 'pkg.Type' \| null \| undefined` — the namespace-qualified spelling of a declared type whose qualifier capture cut from `rawName` (`*models.User` stored as `User`), recovered from `declaredSpelling`. Receiver typing tries it first, grounded on the qualifier's import (no unique-name guess). A failed written-qualified lookup stops instead of falling back to a bare type name. The optional scope indexes also let a provider expand a visible namespace alias; `null` refuses the written lookup and its fallback. The binding is not rewritten — default off | | `collapseMemberCallsByCallerTarget?` | One CALLS edge per (caller, target) instead of per-site — default off | | `populateNamespaceSiblings?` | Cross-file implicit visibility (compiler-implicit namespace sharing) — default off; ctx carries `treeCache` | | `hoistTypeBindingsToModule?` | Walk up to Module scope when looking up a method's return-type typeBinding — default off; enable only when bindings are stored at module level | | `hasFileLocalCallableLinkage?` | Precise internal-linkage predicate used only when joining callable declarations/prototypes to cross-file definitions; C/C++ use it for `static` free functions | | `constructorCallTargetsClass?` | A constructor-form call `Type(...)` links to the Class def rather than its explicit Constructor def — default off; Swift and Dart opt in | | `constructionSyntax?` | How the language spells construction, so an INLINE constructor receiver (`Service(db).m()`, `new Service(db).m()`, `Service.new.m()`) can be typed — `bare` / `keyword` / `selector`; default off, opt in per language only where measured to be needed (#2708) | +| `resolveQualifiedCallee?` | `(calleeText, inScope, …) → callable \| undefined` — resolve a qualified callee only the language can read (`rp::make` in `x = rp::make()` / `rp::make().m()`) so chain-follow types the call from its return annotation; default off | +| `resolveQualifiedTypeSpellings?` | A receiver's declared or return type written QUALIFIED (`rp::C x`, `f(a::Config c)`) that binds nothing through the scope chain resolves through `resolveQualifiedInheritanceBase` — qualifier matched against the candidate's namespace, refuse on a tie — instead of by its tail, which binds the nearer same-named class. Runs after every existing lookup and after the template-argument match; default off, C++ opts in | +| `splitQualifiedCallee?` | `(callee, callerScope?, scopes?, position?) → { receiver, member } \| undefined` — map a qualified callee spelling (`rp::make`) onto a receiver/member pair that retains the full written namespace qualifier, so a factory result (`auto x = rp::make(); x.m()`, `rp::make().m()`) is typed from the definition `resolveQualifiedReceiverMember` returns and that definition's own declared return type. Caller scope, indexes and source position let a provider reject shadowed or aliased namespace qualifiers only when visible at the factory expression. Shared code never splits on a separator; default off, C++ implements it | ### Per-language registration @@ -455,7 +458,6 @@ Each language implements `LanguageProvider` (`language-provider.ts`). Key fields | `id`, `extensions` | Language identity and file matching | | `treeSitterQueries` | S-expression queries for AST extraction | | `importSemantics` | `named` / `wildcard-leaf` / `wildcard-transitive` / `namespace` | -| `importResolver` | Language-specific path → file resolution | | `exportChecker` | Public/exported symbol detection | | `typeConfig` | Type annotation extraction rules | | `mroStrategy` | `first-wins` / `c3` / `none` | @@ -472,22 +474,9 @@ Per-language tree-sitter queries use different AST node names but produce the ** ### Import resolution -Per-language import resolution uses the **configs + factory** pattern (like call/method/class extractors). Each language declares an `ImportResolutionConfig` in `import-resolvers/configs/`, listing an ordered chain of `ImportResolverStrategy` functions. `createImportResolver()` (in `resolver-factory.ts`) composes them: first non-null result wins. Low-level helpers shared across strategies live alongside the configs in `import-resolvers/` (e.g. `go.ts`, `rust.ts`, `python.ts`). +Per-language import resolution runs through `ScopeResolver.resolveImportTarget`, registered in `SCOPE_RESOLVERS`. The shared orchestrator (`scope-resolution/pipeline/run.ts`) passes each language's workspace configuration to the resolver hook. The hook maps a parsed import to its target file or files; finalization links imports and materializes bindings for scope lookup. -Unified 3-tier algorithm (`model/resolution-context.ts`), per-language `importSemantics` controls which tier activates: - -| Tier | Confidence | Mechanism | -| ----------------- | ---------- | ---------------------------------------------------------------------- | -| 1 — same-file | 0.95 | Symbol table for caller's file | -| 2 — import-scoped | 0.9 | `NamedImportMap` chains (named) or all files in `importMap` (wildcard) | -| 3 — global | 0.5 | O(1) index lookups: class, impl, callable. Fallback only | - -| Import strategy | Languages | Behavior | -| --------------------- | ----------------------------------- | ---------------------------------------------- | -| `named` | TS, JS, Java, C#, Rust, PHP, Kotlin | Only explicitly imported names visible | -| `wildcard-leaf` | Go, Ruby, Swift, Dart | Whole-package import, no transitive re-exports | -| `wildcard-transitive` | C, C++ | `#include` closure chains through re-exports | -| `namespace` | Python | Module aliases resolved at call site | +Language-specific import helpers and namespace rules live beside each resolver in `languages//`. Language-neutral package-directory and suffix indexes, workspace indexes, and per-file-set caches live in `ingestion/utils/`; suffix lookups receive their ordered extension candidates from callers. The dormant `LanguageProvider.importResolver` field, adapter, and strategy factory have been removed; new languages implement the `ScopeResolver` hook. ### Chunked parse-and-resolve diff --git a/gitnexus/bench/import-target/baselines.json b/gitnexus/bench/import-target/baselines.json index cb3ad42187..6701144f60 100644 --- a/gitnexus/bench/import-target/baselines.json +++ b/gitnexus/bench/import-target/baselines.json @@ -8,7 +8,7 @@ "_php_composer_gate_2962": "The canonical PHP arm supplies an authoritative App PSR-4 mapping. A deterministic Vendor0 suffix decoy makes deletion of the external gate change every timing fingerprint, while the heap arm separately pins a mapped miss, the rendered mapping, and the external null result. Three serial samples measured depth ratios 1.058, 1.114, and 1.158; the 1.8 budget is 1.55x the observed maximum. The mapped-miss heap reading peaked at 39607216 retained bytes at 32000 files.", "_fingerprint_note": "Per-language sha256 over every distinct fromFile|target -> resolved target. A change here is a BEHAVIOUR change: the resolver returned a different target set, and IMPORTS/CALLS edges moved. Explain it, never re-baseline to make CI green. For the languages these PRs changed, the pre-change implementations produce these same values on this corpus at both 400 and 1600 files \u2014 that is what makes the index hoist a performance change. The tie-break-level proof lives in test/unit/scope-resolution/import-target-index-parity.test.ts (verbatim copies of the pre-change code, diffed) for Kotlin's current declared-package behavior in test/unit/kotlin-module-resolution.test.ts, and for the four resolvers added there in test/unit/scope-resolution/{php,java,cobol}-import-target-parity.test.ts and test/unit/import-resolvers/csharp-csproj-parity.test.ts, and for JavaScript in test/unit/scope-resolution/javascript-import-target-parity.test.ts (a differential over 211200 old-vs-new pairs, PR #2911). The eight languages added last have no per-language parity harness against a pre-change implementation and do NOT need one: nothing about their resolution changed, so there is no before to diff against. Their fingerprints are pure forward guards, minted from the current implementations, and their adapter-boundary index reuse is covered for every registered language at once by test/unit/scope-resolution/import-target-index-reuse.contract.test.ts. NOTE for csharp_csproj: on this corpus the #2902 indexed leg (step 3 of resolveCSharpImportInternal) is reached by 2221 of the 3200 small-arm imports but answers null for every one of them \u2014 the 979 that resolve do so at step 2 \u2014 so this fingerprint pins that legs cost and its null answers, while its positive tie-breaks (unanchored substring, iteration order) are pinned by csharp-csproj-parity.test.ts. NOTE for kotlin, go, csharp and java: twenty fingerprints across these four languages were re-baselined in #2881, the one deliberate behaviour change any language in this file has had. It landed in two steps and the second is the reason the first is not a special case: Kotlin first, then the shared package-dir-index (go, java, csharp) and the csproj namespace index once the same rule was found live there. `getKotlinFileIndex` no longer requires a file's package directory to be the FIRST occurrence of that name in its own path, so the unique arm's `d % 7` nested slice (`mod{d}/src/main/kotlin/com/example/pkg{d}/inner/pkg{d}`) now belongs to package `pkg{d}` and its wildcard imports resolve: resolved 1100 -> 1153 small and deep, 4456 -> 4681 large. The collide arm needed a CORPUS edit alongside it, not just a new number \u2014 its `d % 7` slice deliberately imported `com.example.vendor{d}`, a package that exists nowhere, purely to mirror the unique arm's nested-slice MISS, so leaving it would have left collide at 1100 against small's 1153 and broken the same-workload invariant the arm is built on (that assertion is what caught it). It now uses the same `com.example.models.*` spelling as the rest of the arm, which is why its distinct_outcomes fell (2775 -> 2744, 11087 -> 10961): one shared target instead of one per d. The record-level evidence for the resolver change \u2014 235 of 19968 records moved, 54 null -> resolved, 0 buckets losing a member \u2014 is in bench/kotlin-import-target/baselines.json `_provenance`. The kotlin heap_reading_bytes and heap_ceiling_bytes moved with it, together as `_heap_reading_note` requires: 48073096 -> 48200224 bytes_large (+127128, +0.264%), ceiling still exactly 1.5x. Small, and it is worth saying WHY it is small rather than reading the number as evidence that the change is cheap. `dirChildren` grows by one entry per component-suffix the old rule used to skip, and this arm can only see part of that: the heap corpus is built with HEAP_PAD 8, which prefixes every path with `d0/\u2026/d7/`, so no path can begin with a suffix of its own directory and the leading-segment half of the old rule is structurally invisible here. What moves the reading is the `d % 7` nested slice alone. Read +0.264% as this arm's ceiling on the effect, not as the effect. GO NEEDED A CORPUS EDIT TO BE GATED AT ALL. Its nested slice was `src/pkg{d}/internal/pkg{d}`, repeating only the LAST segment, while a Go query addresses the whole package path `src/pkg{d}` \u2014 so the directory never even ended with the query and the first-occurrence rule was never reached. Every go arm sat unchanged through the resolver fix. `uniqueDir`/`collideDir` now repeat the shape at the granularity Go actually queries (`src/pkg{d}/internal/src/pkg{d}`, `svc{d}/internal/sub/svc{d}/internal`), which is what moved go from 979 to 1153 resolved and bumped `languages.go.heap.path_segments` 13 -> 14. The general lesson: a corpus that carries a shape the QUERY cannot express does not gate that shape. CSHARP AND JAVA HIT THE SAME COLLIDE-ARM TRAP AS KOTLIN. Both collide arms sent their `d % 7` slice to a namespace that exists nowhere (`App.Src{d}.Vendor`, `com.svc{d}.vendor`) purely to MIRROR the unique arm's nested-slice miss; once that miss became a hit, collide sat at 979/1100 against small's 1153 and the same-workload assertion failed. Both now use the same spelling as the rest of their arm. HEAP: no reading here moved for the resolver change. An earlier revision of this branch re-recorded `csharp_csproj` 73703384 -> 73116520 as a -0.79% effect of the step-2 filter; review measured base and branch three times each and got the same 73.10e6 on BOTH sides \u2014 the recorded 73703384 was simply not reproducible on this box, and re-recording it would have dropped that language's derived floor by 0.8% for no reason belonging to this change. Reverted. Everything else sat within +/-0.03%. Note that `_heap_reading_note`'s claim that these readings 'reproduce to the byte across processes on one box' did NOT hold on the box this was measured on: go, dart, ruby, python, php and cpp all wandered by a few hundred to a few thousand bytes between processes with no code change touching them. Treat sub-0.05% movement as jitter, not signal. HEAP, kotlin, second movement: 48200224 -> 42802456 (-11.20%), re-recorded with its ceiling. `getKotlinFileIndex` now compacts each `dirChildren` bucket as it freezes it. `addChild` mints a bucket as `[raw]` and pushes the rest, and V8 grows a backing store by `old + old/2 + 16`, so the second child takes a 1-slot store to 17: 61144 buckets, 52.9% of their slots empty, 88 B each. Same fix and same accounting as the python `byBasename` sentence above. Note what this means for the gate: a memory WIN of this size passes every arm \u2014 it is under the ceiling and over the 0.5x floor \u2014 so it is recorded because the convention says a reading and its ceiling move together, not because anything went red. kotlin now reads 40.82 MiB. The prose in measure.mjs calling it '45.85 MiB, the second-largest reading in this file' is corrected with it \u2014 and was already wrong on the ranking before this change, since csharp_csproj (69.73) and php (47.28) both read higher; kotlin was third. A measurement written into prose is not re-taken, which is the finding `_heap_bound_note` records about this very file. One further corpus edit, made in review and MEASURED rather than assumed: kotlin's collide layout repeated only the `models` leaf (`\u2026/com/example/models/inner/models`) while a Kotlin query addresses the whole dotted path, so a full revert of the Kotlin guards left both collide fingerprints UNMOVED \u2014 the arm was blind to the rule it was re-baselined for. Deepening it to `\u2026/models/inner/com/example/models` makes the revert move both, and those two fingerprints are the only ones that changed for it. The same deepening was applied to the java and kotlin UNIQUE arms and REVERTED: it moved ten more fingerprints, grew java's heap reading 43%, and bought nothing \u2014 progressive stripping lands those queries on the same file with or without the rule, so the control still failed only on go.", "_shape_note": "files/imports/resolved/distinct_outcomes AND the fingerprint are asserted exactly, per scale. A fingerprint alone cannot tell a legitimate resolution change from a corpus quietly shrunk below the size at which the timing arms can see anything; conversely the counts alone cannot see a defect confined to one arm, because the arms differ only in path padding and directory layout and both of those are count-neutral by design. Two cross-arm assertions close the remaining hole: the deep and collide arms must resolve exactly what small resolves (they are the same workload), and each of their fingerprints must DIFFER from small's (they are not the same corpus). Without the second, setting DEEP_PAD to 0 \u2014 which deletes the entire depth arm \u2014 moves no asserted number and prints PASS; the same is true of a collideDir that forwards to uniqueDir. THE HEAP ARM IS ASSERTED THE SAME WAY, by the same loop, and was not before: files_small, files_large, path_segments and probe decide WHAT it measures, and every one of them was reported and compared to nothing. Swapping HEAP_PROBE_TARGET.csharp_csproj for a target matching no CSPROJ_CONFIGS rootNamespace skips the whole config loop, so the getFilesInDir and getInsensitive legs never run and the arm the header calls the witness that the read pattern IS the footprint quietly becomes a two-map arm \u2014 73703384 -> 59921216 B, ratio 1.017 -> 1.011, ceiling and floor both still passing and --check still exiting 0. Setting HEAP_SMALL equal to HEAP_LARGE is the same hole from the other side: ratio goes to ~1.0 by construction and bytes_large never moves. bytes_small and bytes_large are deliberately NOT asserted for equality \u2014 heap_ceiling_bytes and the heap_reading_bytes floor bound them with ~50% either way, because heapUsed accounting moves across platforms and Node majors and an exact byte assertion would be a re-baseline per runner. THE CONTEXT ARM IS ASSERTED THE SAME WAY, by the same loop, and more strictly than either: target, with_context and without_context are exact strings with no tolerance at all, because the arm resolves one import over a three-file corpus and has no measurement noise to tolerate. A separate check requires the last two to DIFFER, for the same reason deep.fingerprint must differ from small.fingerprint \u2014 a probe on which both call shapes agree asserts one number twice. Both halves run through resolveOne, so what the arm gates is this bench threading run.ts's fifth argument, not the resolvers' behaviour.", - "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT \u2014 the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) emits one entry per component, while Kotlin's declared-package index is depth-free while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x \u2014 and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION \u2014 this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number \u2014 measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 \u2014 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 \u2014 no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all \u2014 harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it \u2014 same corpus, same getWorkspaceFileIndex, three maps instead of one \u2014 it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release \u2014 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths \u2014 37% of what this arm used to read was empty array slots \u2014 the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE \u2014 do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% \u2014 identical to the byte \u2014 on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way \u2014 true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs \u2014 tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost \u2014 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in import-resolvers/python.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` \u2014 the package probe's recursion re-ran the whole tail on identical inputs \u2014 and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 \u2014 its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 \u2014 python 1.097, javascript 1.083, typescript 1.053, vue 1.079 \u2014 and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) \u2014 the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 \u2014 a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter \u2014 if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK \u2014 ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s \u2014 see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another \u2014 i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) \u2014 its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms \u2014 which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL \u2014 the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP now runs its sole timing, depth, collision and heap workloads with Composer's PSR-4 config. The canonical recording is small_ms 12.515, collide_ms 13.684, scaling_ratio 1.077, collide_scaling_ratio 0.994, depth_ratio 1.536 and 13407592 retained bytes. Its ceilings are 55/60 ms, 2.4 depth and 20200000 bytes, preserving normal cross-run headroom without splitting PHP into benchmark identities. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later \u2014 which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch \u2014 the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x \u2014 far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 \u2014 both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles \u2014 see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", + "_arms_note": "Five timing arms, one memory arm and one deterministic arm elsewhere, because none of them gates alone. scaling_ratio (t_large/t_small)/(1600/400) catches cost growing with FILE COUNT \u2014 the #2877-#2880, #2901, #2902 and #2908 regressions themselves; every one of those legs was Theta(files) per import, so a revert scores ~4 here by construction. depth_ratio (t_deep/t_small at a FIXED file count, ~6x the path components) catches cost growing with path DEPTH, which scaling_ratio divides out and structurally cannot see; buildSuffixIndex (C#, Ruby, PHP, Java) emits one entry per component, while Kotlin's declared-package index is depth-free while Go, Dart and COBOL, whose indexes are depth-free, sit at ~1.0. csharp's depth_budget has now been retightened twice for the same reason, and the second time it did lock the win in. It was 5 against a then-measured 3.318; #2903 made buildSuffixIndex's dirMap lazy and it became 3.5 against 2.31, with the file stating plainly that 3.5 did NOT lock that win in because a revert to an eager dirMap scores 3.318 and passes. Extending the laziness to the two SUFFIX maps drops it again, to 1.438 (java likewise 2.214 -> 1.402), because the deep arm has ~6x the path components and an O(files x depth) build of a map the no-csproj leg never reads is exactly the cost that scales with depth. Both are now 2.2, which is this file's 1.5x convention against measurements whose own peak-to-peak over 4 runs is 1.04x and 1.07x \u2014 and 2.2 DOES lock it in: an eager rebuild scores 2.3+ and fails. The other fifteen depth budgets sit at 1.37-1.75x measured and are unchanged. collide_scaling_ratio is the same measurement on a SHARED-LEAF layout (svcN/internal, SrcN/Models, com/example/model in every service, a repeated mod0.dart/mod0.rb/Mod0.cpy basename) carrying an identical file, import and resolved count: the small/large/deep arms mint one directory name per index, so every index bucket in them holds exactly ONE entry (measured: max last-segment bucket 1 and max matching directories 1 for go and csharp at 400 and 1600 files; max basename bucket 1 for dart and ruby), and bucket cardinality is the only non-constant term the new indexes have. On the shared-leaf shape go, csharp, dart and java legitimately score 2.1-3.9 because the bucket grows with the file count BY CONSTRUCTION \u2014 this is a limit on the SCOPE of the \"independent of corpus size\" claim, not a regression (the indexed code is still faster there than the pre-change full scan); their collide budgets say so honestly instead of pretending 1.8. Ruby, Kotlin, PHP and COBOL answer from keyed maps and are collision-immune, so they keep the linear 1.8 budget and that immunity is the assertion. csharp_csproj is the one arm that runs the other way: its shared leaf collapses dirsByLastSegment to the single key Models, so the slash-free sweep (see CSPROJ_CONFIGS) is CHEAPER on the collide layout than on the unique one and its expensive scale arm is large, not collide_large. Its 1.8 collide budget is therefore the linear one, and the arm that carries its real cost is the unique one. The collide arm is also the only arm that reaches filesDirectlyInPkgDir's dirCount > 1 merge (go: 388 multi-directory calls at 400 files, up to 9 directories; 1517 at 1600 files, up to 34) and the only one that reaches COBOL's copybook-over-source tier tie-break, which needs one bookname to name two files. small_ms_ceiling and collide_ms_ceiling are ABSOLUTE (~4x the measured arm), because a constant-factor regression that grows both scale arms equally passes every ratio. The five arms added here use 4.2x, the middle of the 3.7-4.6x the original five already carry; the two COBOL arms use ~5x, the multiplier dart's sub-1 ms arm has always carried, because a fixed scheduler hiccup is a larger fraction of a smaller number \u2014 measured over 8 runs they sat at 0.25-0.37 ms and 0.18-0.30 ms, and the pre-#2908 two-scans-per-COPY implementation costs ~300 ms on the same arm, so 2.0 and 1.5 still separate fixed from broken by two orders of magnitude. NOISE, measured rather than assumed: depth_ratio divides two sub-3 ms numbers (Dart's are sub-1 ms) and is by far the noisiest arm here, so it set N for the whole file. fastest() is a min-of-N estimator, so N is the knob. Over 22 --check runs on an idle box, peak-to-peak: at N=5 go ran 0.757-1.748 (2.31x) and tripped its own 1.6 budget about 1 run in 20; at N=7 (the kotlin-import-target setting) Dart still ran 0.678-2.043 (3.01x) and tripped once; at N=15 (bench/cfg, bench/schema-pairs, bench/callable-value-flow) every language collapsed to a 1.13-1.26x swing with 22/22 passing. The budgets were NOT widened; the estimator was fixed instead, which is why the headroom above is real rather than granted. N IS NOW PER LANGUAGE, and that is a refinement of the same finding rather than a retreat from it. The overshoot of min-of-K against min-of-15 is a function of the CELL's absolute duration, not of the language: replayed against two independent runs' full sample sets, the worst overshoots at K=7 land on swift.small (0.43 ms, 31.8%) and dart.collide (1.5 ms, 37.6%), while every cell at or above 10 ms overshoots by at most 6.3%. So repsFor() keeps 15 while a language's cheapest arm is under 5 ms and otherwise spends ~150 ms per cell, floored at 7 \u2014 15 for go, csharp, dart, kotlin, java, cobol, swift, rust, python, c and cpp (every language the flakiness above was ever about, cheapest arm 0.19-3.2 ms) and 7-8 for csharp_csproj, ruby, php, javascript, typescript and vue (cheapest arm 20-28 ms). Per LANGUAGE, not per cell, so all five arms of a language share one estimator and the four ratios stay comparisons of like with like. The replay passed all 85 cells on all five gates at 0.4-0.7 of budget and saved 12.8 s and 12.4 s of a 46 s run; min-of-7 also reads slightly HIGHER than min-of-15, so the ceilings get marginally more sensitive rather than less. Confirmed on 4 fresh runs with the adaptive estimator live: every small arm inside 1.12x peak-to-peak and every collide arm inside 1.07x, with the six 7-8 rep languages at 1.008-1.071 \u2014 no worse than the 11 that kept 15. The chosen N is reported per language as `reps`. heap_ceiling_bytes bounds the retained per-pass import index, the only arm here that can see memory: buildSuffixIndex emits maps at O(files x depth), the profile package-dir-index.ts cites #2649 to avoid for itself, and csharp, ruby, php and java all retained NOTHING across imports at BASE (C#'s no-csproj leg and PHP's and Java's every leg re-scanned the raw Set; Ruby rebuilt and discarded a suffix index per require). It is measured at 8000 and 32000 files at HEAP_PAD depth rather than at the timing arms' sizes, because the finding is an ABSOLUTE footprint at repository scale. THE ARM NOW READS WHAT THE LANGUAGE READS, and that change is the whole reason this file was re-baselined. Four of these arms used to call getWorkspaceFileIndex(set) directly and then read index.all.length, which asks no suffix question at all \u2014 harmless only while buildSuffixIndex built both maps eagerly. The moment they went lazy the direct call built NO map, csharp, ruby, php and java each reported 0 B at 32000 files, and 0 B is under every ceiling: --check printed PASS over four gates that had silently become ceilings over nothing, which is precisely the failure this file's own header warns about for rust and cobol. Every arm now resolves a real MISSING import through the real resolver (HEAP_PROBE_TARGET, asserted to miss), so the maps it forces are the maps production forces, and a resolver that starts asking a new question moves the number without anyone editing the bench. That makes the READ PATTERN the dominant term, and the eight numbers say so: java 34958600 B and csharp 29862200 B ask index.get and never getInsensitive; php 37579888 B asks getInsensitive and never get, plus its own first-proper-suffix map; ruby 41025360 B and javascript 26745296 B read get(s) || getInsensitive(s) and pay for both, the second DERIVED from the first; and csharp_csproj 73705944 B additionally asks getFilesInDir. csharp_csproj IS NOW GATED, reversing the earlier decision that it would be 'a ceiling on a duplicate': at +20.8% of the C# index it was one, and at 2.47x of it \u2014 same corpus, same getWorkspaceFileIndex, three maps instead of one \u2014 it is the witness that the read pattern is the footprint. The old RESIDUAL note is superseded by that number: a dirMap-sized addition is no longer +18%, and a consumer that asks all three questions blows csharp's ceiling by 1.64x rather than sliding under it. A SECOND MEASUREMENT BIAS was removed at the same time and it moved every figure here, so do not read these against the old ones as if only the read pattern changed. buildFiles mints paths with template literals, which V8 keeps as ropes; the first traversal that slices one flattens it, allocating the flat string and dropping the rope's pieces, so a build measured over an unflattened corpus reports the index MINUS that net release \u2014 11% low, uniformly. bytes_small was read over a corpus a discarded warm-up pass had already flattened and bytes_large over a fresh one, so every ratio read ~0.85-0.89 for structures that are exactly linear in the file count. measureHeap now flattens each corpus before measuring it; all eight ratios read 0.998-1.017, and the warm-up pass is gone because with the corpus flat a language's first and second reads agree to within 0.3%. python's figure rises from 7624992 to 10362976 for this reason and not because anything regressed, and then to 10543152 (+1.7%) because #2913's nestedDirNames set is retained for the pass, and then FALLS to 6360936 (-39.7%) for a reason worth knowing: byBasename holds roughly one bucket per file, and building each with `[]` followed by `push` made V8 grow the backing store to its 16-slot minimum, so every single-file bucket retained 15 empty pointer slots. Constructing the one-element buckets directly (`set(base, [entry])`) is byte-identical in contents and 3.9 MiB smaller at 32000 paths \u2014 37% of what this arm used to read was empty array slots \u2014 the ancestorsByDir memo itself is NOT in this reading, because python's probe target misses at the nested-name rejection and never reaches the walk, so this arm does not bound that memo; measured separately with a probe that does reach it, a 32000-file corpus with every file in its own 10-deep directory retains ~19 MB, which would clear this ceiling, so repointing python's heap probe at a walking spelling means re-recording the ceiling in the same change, and c is unchanged at 10018816 because its basename map does not slice paths. Its ceiling is 1.5x the measured arm, and the DIFFERENCE FROM THE 4x TIMING CONVENTION IS DELIBERATE \u2014 do not harmonise it back. 4x exists because runner contention dominates a wall-clock number; this one has essentially no measurement noise (across 4 runs the widest spread was 0.11% on python, 0.03% on csharp_csproj and 0.00% \u2014 identical to the byte \u2014 on ruby, php, java, javascript and c, and the same holds across separate processes), so 4x would throw away almost all of the gate's power and sail straight past the regression this arm exists to catch. 1.5x still tolerates ~50% of cross-platform and Node-version drift, far more than a Node major bump plausibly moves heapUsed accounting; it catches a duplicated index (+100%) or a second exactMap-sized suffix map (+~85%). heap_floor_fraction is the arm the 0 B incident proved was missing. A ceiling can only say 'not too big'; nothing said 'still measuring something', which is why four dead arms passed. The floor is 0.5 x each language's RECORDED READING (heap_reading_bytes), which is half the measured size and says so. It used to be 0.33 x the CEILING, described the same way \u2014 true only while every ceiling stayed at exactly 1.5x its reading, a convention this file states and nothing enforces, so re-tuning one ceiling upward would have loosened that language's floor by the same factor in the one direction a floor exists to watch. The two forms agree to within 0.8% for all eight today, so this is a correction of derivation, not of strength. It sits ~400x above the readings' own reproducibility and far below any collapse. A genuine 2x memory WIN trips it too, and that is intended: like a fingerprint move, it must be explained and re-baselined rather than absorbed. COBOL is left out for the opposite reason: its index is two Map, O(files) with no depth term, and at 32000 files its retained delta does not clear the noise of the measurement itself. heap_ratio_budget, the linear-growth check across the 4x file-count gap, is the orthogonal arm: it sees per-file and per-depth growth but not a constant factor. ---- THE EIGHT LANGUAGES ADDED LAST (swift, rust, python, javascript, typescript, vue, c, cpp) ---- They carry the SAME five arms and the same gates; what differs is which arm can actually fail for each, because each resolver has a different cost axis, and the budgets below say so instead of copying a number across. Every figure quoted is the MAXIMUM over 5 full runs on an idle box, and the peak-to-peak of every one of these arms stayed inside 1.10x over those runs \u2014 tighter than the 1.13-1.26x the original nine record, because none of these arms divides two sub-1 ms numbers the way dart depth_ratio does. depth_budget is ~1.5x measured throughout: swift 2.3 (1.487), rust 2.1 (1.377), javascript 2.1 (1.376), typescript 2.1 (1.381), vue 2.3 (1.563), c 3.0 (1.990), cpp 3.0 (1.999). PYTHON WAS 11 AGAINST 7.389 AND IS NOW 2.6 AGAINST 1.872, because #2913 fixed the resolver rather than the budget. Its INDEX was always depth-free; hasRepoCandidate and resolveAbsoluteFromFiles each rebuilt one ancestor prefix per directory component of the importer on EVERY import, and the index's own dirPrefixes build inserted one entry per component per file, so the resolver was quadratic in path depth where every other language here is linear or flat. The prefixes are a pure function of the importer's DIRECTORY, so they are now memoized per directory inside getPythonFileIndex (ancestorsByDir), the leading segment is rejected up front against a set of nested directory names, the module and package buckets are consulted before the walk rather than inside it, and the dirPrefixes build stops at the first ancestor already stored. All five fingerprints are byte-identical, so it is a hoist. The budget is 2.2, and BOTH numbers behind it were re-measured on a quiet box AFTER the context leg below started being measured, because that change moved the arm: the work it adds is depth-FLAT, so python's absolute cost more than doubled while depth_ratio FELL to 1.405-1.563 over 5 serial runs (peak-to-peak 1.11x). A budget carried over from before that change would have been slack against a smaller ratio. 2.2 is 1.41x the measured maximum, inside the 1.37-1.75x band the other fifteen sit in, and it LOCKS THE WIN IN: reverting the per-directory ancestor memo alone scores 2.524 and reverting the nested-name rejection alone scores 2.553, both measured under the current call shape, so each fails at 2.2 with 13% to spare. Do not read those two figures as the pre-#2913 cost \u2014 7.239 was that, and the gap closed because the bare-import tier stopped walking at all (see below). The other two parts of the fix are not gated by this arm and are not meant to be: reverting the bucket prune or the dirPrefixes early break lands under any budget this arm's noise supports, so they are gated deterministically instead, by the prefix-parity and package-probe arms of test/unit/scope-resolution/python/python-importer-ancestors.test.ts and python-import-target-parity.test.ts, which go red on exactly those two mutations. A timing budget catches what it can measure; the counts catch the rest. THE BARE-IMPORT TIER (`import os`, single segment, no dot) was a separate O(depth) walk in languages/python/import-helpers.ts that this bench cannot see at all, because every python arm here spells its imports with a dot and returns at the `pathLike.includes('/')` guard before reaching it. It ran TWICE per `from x import y` \u2014 the package probe's recursion re-ran the whole tail on identical inputs \u2014 and is now one memoized chain plus an O(1) proof-of-absence against the index's basename buckets: 12/24/72 Set probes at depth 1/4/16 became a flat 2, and 11.615 us/import at 18 path components became 0.740. Gated by probe COUNT in test/unit/scope-resolution/python/python-import-probe-count.test.ts, not here. collide_scaling_budget splits three ways. Three languages scan a bucket that grows with the corpus and get their measured value x1.5: swift 4.9 (3.279 \u2014 its bucket is the module file list it RETURNS, and its collide arm is four modules instead of dirs of them so that bucket is fileCount/4, i.e. 100 files at 400 and 400 at 1600), c 3.8 (2.535) and cpp 4.0 (2.639, the same basename bucket its suffix fallback walks). Four answer from keyed maps and keep the linear 1.8 \u2014 python 1.097, javascript 1.083, typescript 1.053, vue 1.079 \u2014 and that immunity IS the assertion, exactly as for ruby, kotlin, php and cobol. RUST IS THE ONE ARM THAT WAS REDESIGNED RATHER THAN BUDGETED. It resolves by probing candidate paths with allFilePaths.has(...) and never searches, so its cost is O(path segments) and provably flat in the file count (1.095 scaling, 1.061 collide scaling): a shared-leaf collide arm for rust would have asserted nothing, which is worse than no arm. Its collide corpus is instead a deep module tree (src/l0/l1/l2/l3/l4/mod{d}) whose targets carry ~2x the :: segments, so the arm exercises the axis that CAN grow, its 1.8 budget asserts the flatness across file counts, and collide_ms_ceiling 19 bounds the absolute cost of the long-path probe. small_ms_ceiling and collide_ms_ceiling are ~4x measured as everywhere else: rust 10/19 (2.609/4.704), python 7/8 (1.76/1.929, retightened from 12/15 against 3.044/3.771 by #2913), javascript 85/89 (21.254/22.145), typescript 85/86 (21.250/21.464), vue 81/93 (20.164/23.227), c 7/11 (1.620/2.850), cpp 7/12 (1.581/3.009). Swift takes ~5x (2 against 0.421 and 4 against 0.821) \u2014 the multiplier dart and cobol already carry, because a fixed scheduler hiccup is a larger fraction of a sub-1 ms number. ONE CAVEAT ON THE THREE ts-FAMILY MS NUMBERS, stated because nothing else in this file would reveal it: resolveTsTarget carries a per-pass resolveCache keyed currentFile::importPath, which no other resolver here has, and ~10% of this corpus is repeat pairs. Their us/import is therefore a slight underestimate of a cold resolve. It is left in rather than defeated because it is what the real pipeline does, and it is identical across all three so the arms stay comparable. HEAP for the eight: rust, swift, typescript, vue, cpp and cobol are still NOT gated, all of them measured before being left out. rust builds no index on this hook (16 B at 8000 files, 0 B at 32000); swift holds one pointer per file-times-segment and mints no strings, reading 0.98 MB at 8000 files against 0.29 MB at 32000 \u2014 a 4x larger corpus reading 3x SMALLER, which is what a measurement below its own noise floor looks like, and the same reading cobol gives (0.54 MB then 0 B); typescript and vue duplicate javascript through the same builder over the same-shaped corpus, and cpp duplicates c (10021320 against 10016960, 0.04% apart). Those four duplications are the ONLY exclusions that still rest on 'it would be a duplicate', and they are duplicates of a builder AND of a read pattern, which is the pairing csharp_csproj failed once the read pattern started to matter \u2014 if any of the four ever diverges in what it ASKS the index, it earns an arm the same way csharp_csproj just did. All eight gated arms are read the same way now (retainedPassBytes, one real import), so unlike before they are directly comparable to one another. WALL CLOCK \u2014 ~33-35 s in report mode, down from ~46 s, and ~44-45 s for --check, which is essentially UNCHANGED from ~46 s. Only report mode got faster; do not read the pair as 46 -> 42. The breakdown is worth having before anyone trims it. Timing arms: go 2.02, csharp 1.09, csharp_csproj 3.22, dart 0.41, ruby 2.90, kotlin 0.85, php 3.46, java 1.57, cobol 0.09, swift 0.46, rust 0.85, python 1.22, javascript 3.23, typescript 2.72, vue 2.89, c 0.86, cpp 0.91 (28.7 s, from 39.8 s: repsFor() accounts for all of it, and every second of it comes from the six languages whose cheapest cell is 20-28 ms); heap arms 3.43 s for SEVENTEEN languages, from 2.06 s for eight (every registered language is measured now; the nine added cost 1.37 s, of which kotlin alone is 0.57 s \u2014 see _heap_bound_note), and 2.1 s came from 3.0 s for seven when flattening retired the warm-up pass; module load 3.9 s. --check pays one import that report mode does not: the inventory arm loads pipeline/registry.ts, which drags in every registered scope resolver and its providers. Measured in isolation with the bench's own static imports already resident, that import costs 6.3-6.5 s on one box and 9.3-10.0 s on another \u2014 i.e. it consumes almost the whole repsFor win, which is why --check did not get faster. It is loaded dynamically at the point of use rather than at the top of the file, so report mode does not pay it and both modes take their measurements in the same module state. IT WAS WEIGHED AND KEPT, on the number that decides it: the benchmarks job is not CI's critical path. On the last green run of main it took 9 m 23 s against 12 m 58 s for the sharded coverage job that gates the merge, so ~4 m 40 s of slack sits above this bench and those seconds buy zero merge latency. Moving the arm to a vitest file would move the registry load ONTO the critical path, and would weaken it as well: this reconciles LANG_REGISTRY's SupportedLanguages values, which are what the five dispatcher branches key off, whereas a test that cannot import measure.mjs can only reconcile this file's arm NAMES plus a hand-written rule for de-aliasing csharp_csproj. The contract test import-target-index-reuse.contract.test.ts already covers the ADAPTER-boundary contract for every registered resolver; this arm covers a different claim, that the BENCH covers the pipeline. The ts family is still the largest single block of the timing phase (8.8 s) \u2014 its cost is suffixResolve probing ~39 extensions per path part on a miss, which is the real resolver and cannot be tuned away from the bench side. IF IT HAS TO SHRINK, drop collide and collide_large for typescript and vue and nothing else: -3.9 s, and it is the only cut that removes near-duplicate work rather than coverage, because all three run the same resolveTsTarget over the same buildSuffixIndex and javascript keeps the collide arm that covers their shared collision axis. Do NOT reach for REPS_MAX: it is 15 because depth_ratio tripped its own budget about 1 run in 20 at 5 and once at 7, and lowering it would re-open that for the eleven languages whose cheapest cell is sub-5 ms \u2014 which is where every recorded trip happened. The six languages it was safe to lower have already been lowered, per language and from a measurement, by repsFor(). ---- THE FIFTH ARGUMENT (context) AND THE TWO ARMS IT MOVED ---- resolveOne now makes run.ts's five-argument call for the two hooks that declare a fifth parameter, so php and python time the legs behind it. Nothing else moved: the other fifteen arms are handed no context and build no ParsedFile[] at all, and over five runs their five ms numbers and four ratios sit exactly where they did. Both languages' ten fingerprints, resolved counts and distinct_outcomes are IDENTICAL \u2014 the leg AGREES with the cascade on this corpus, which is the whole reason the context arm had to be added rather than leaving the fingerprint to notice. PHP now runs its sole timing, depth, collision and heap workloads with Composer's PSR-4 config. The canonical recording is small_ms 12.515, collide_ms 13.684, scaling_ratio 1.077, collide_scaling_ratio 0.994, depth_ratio 1.536 and 13407592 retained bytes. Its ceilings are 55/60 ms, 2.4 depth and 20200000 bytes, preserving normal cross-run headroom without splitting PHP into benchmark identities. PYTHON, WHOSE FIGURES ARE THE LEAST SETTLED THING IN THIS FILE AND ARE RECORDED IN TWO SNAPSHOTS BECAUSE OF IT. A named import is the only spelling that reads context.parsedFiles, and it costs up to three entries into the resolver per import (package probe, exports check, submodule probe) where the synthetic namespace spelling this arm used to pass costs one. Against the resolver as it stood when the call shape changed that read small_ms 1.76 -> 5.751 and collide_ms 1.929 -> 5.894, ~3.1x. Against the resolver a few commits later \u2014 which stopped re-running the whole tail after a null package probe, a double-probe this bench could not previously see because the namespace spelling never entered that branch \u2014 the same arms read 4.404 and 4.505. The ceilings are 18 and 19, chosen to clear BOTH: 4.09x and 4.22x of the current numbers, 3.13x and 3.22x of the higher ones, so neither state is red. Retighten toward 4x once that resolver settles. ITS DEPTH ARM WAS DILUTED AND THE BUDGET IS RETIGHTENED TO MATCH, which is the one thing here worth arguing about: the added work is depth-FLAT, so depth_ratio FALLS 1.872 -> 1.478 while the absolute cost more than doubles, and 2.6 against 1.478 would be 1.76x \u2014 far looser than the 1.39x #2913 chose deliberately to lock its own fix in. 2.1 restores that multiplier (1.42x). THE TWO MUTATION SCORES #2913 RECORDED (3.123 for reverting the per-directory memo, 2.734 for reverting the nested-name rejection) WERE TAKEN AGAINST THE OLD CALL SHAPE AND HAVE NOT BEEN RE-TAKEN. Modelled forward, with the depth-quadratic term reappearing in every resolver entry so its absolute contribution scales with the entry count, they land near 2.8 and 2.4 \u2014 both above 2.1, and the second BELOW 2.6, which is the arithmetic that decided the budget. Re-run the two mutations before trusting the lock-in claim above. python's heap reading is unchanged (10543152 recorded; 10529848-10544616 across eight runs) because its probe misses before the branch that reads parsedFiles \u2014 see _blind_spot for why no probe can reach that memo. Every figure in this section is the MAXIMUM over its snapshot's runs (five, then three), with peak-to-peak 1.031-1.058 on php and 1.019-1.081 on python, taken on a box that was NOT idle and with another change landing in python's resolver mid-measurement. Re-take them serially before merging.", "_triage": "Every ratio and ms ceiling here is a TIMING signal \u2014 re-run on an idle machine before investigating; runner contention dominates. depth_ratio is the noisiest of them by a wide margin (it divides two sub-3 ms numbers, and Dart's are sub-1 ms): if exactly one arm fails and it is that one, suspect the machine first. N is 15 for every language whose cheapest arm is under 5 ms, rather than this bench's original 5, specifically to hold that arm's peak-to-peak swing under 1.26x \u2014 see _arms_note for the measured distributions and for why the six languages that drop to 7-8 are the ones where cell size makes it safe \u2014 so a depth_ratio failure that REPRODUCES is a real signal, not noise. Each language's chosen N is printed as `reps`; read it before blaming the estimator. The fingerprint, shape and heap arms are the opposite: deterministic (over 4 runs the heap arm's widest spread was 0.11% on python and 0.00% on java, javascript and c), a re-run never changes them, and they must never be wished away. TWO heap failures mean the arm STOPPED MEASURING rather than that memory grew, and both are deterministic: a heap floor failure says the probe no longer forces the index it used to (this is how four arms read 0 B when buildSuffixIndex went lazy, and 0 B passes every ceiling), and a `heap probe ... resolved` throw says a probe target that must MISS now hits, so the reading is a materialized answer and the legs past it were never reached. A heap BOUND failure is deterministic in the same way and means one specific thing: a language excluded from the budgeted tier has grown a structure, or started asking its index a question it did not ask when the exclusion was recorded \u2014 never a timing signal, never a re-run, and never fixed by raising the bound without saying what grew. The context arm is deterministic too, and a failure there means one specific thing rather than a range of them: run.ts's fifth argument is not reaching that resolver from this bench, or the leg behind it stopped running. Never a timing signal, never a re-run. TIGHTENED IN #2881, because the measurements they bound got faster and a budget left alone while its reading falls is a gate loosening without anyone deciding to. Each new value holds the headroom the old one expressed over the old reading, computed from `_measured` on both sides: kotlin depth 3.4 -> 2.8 (reading 2.219 -> 1.813), go depth 1.6 -> 1.4 (1.169 -> 0.999), csharp depth 2.2 -> 2.0 (1.438 -> 1.279), java depth 2.2 -> 2.1 (1.402 -> 1.354), kotlin collide_scaling 1.8 -> 1.65 (1.179 -> 1.081), go collide_scaling 5.5 -> 5.1 (3.763 -> 3.465). The ABSOLUTE ms ceilings were deliberately NOT tightened by the same reasoning: they carry runner-contention headroom rather than measurement headroom, and a ratio is runner-speed-invariant where a millisecond is not.", "_floor": "Measured against the pre-change implementations on THIS corpus at 150/600 files: go 3.36, csharp 4.10, dart 3.32, ruby 3.87. The issues report 4.00 / 3.43 / 4.05 on their own corpora; those are DIFFERENT numbers from different repositories and are not reproduced here \u2014 what they and these share is that both independently land in the quadratic band, well clear of the ~1.0 a linear result gives. Note also that this floor was taken at 150/600 while the gate runs at 400/1600, so it is a lower bound on what the pre-change code would score today. Kotlin's own bench measured its pre-index floor at 3.737. The four resolvers added later were NOT re-floored on this corpus, and the reason is that they do not need to be: every one of their pre-change legs walked the whole file set per import (PHP one findIndex per path part per extension, Java one scan per stripped prefix, COBOL two full scans per COPY, C# csproj one normalizedFileList pass per import per matching config), so their scaling_ratio is ~4 by construction rather than by measurement. Their per-import costs were measured on their own issue corpora instead: PHP 96.40 ms -> 0.036 ms, Java 8.05 ms -> 0.62 ms, COBOL 3879 us -> 10.5 us, C# csproj 1103 us -> 7.6 us. The 1.8 budget sits well above the linear result and well below every one of those. The eight languages added last were NOT floored either, and for a different reason again: they are not fixes, so there is no pre-change implementation to floor against. Their scaling budgets are the global linear 1.8 and the point of the arms is to hold the current numbers (measured 1.01-1.13) rather than to separate a fix from a break. The one exception is javascript, which IS a fix and does have a floor: 6448.9 us per import at 2000 files and 25972.6 us at 8000 \u2014 4.12x the per-import cost for 4x the files, i.e. O(imports x files) \u2014 against 28.5 / 27.4 us with the index PR #2911 gave it, and 25.0 / 27.0 us for TypeScript over the identical corpus.", "_rebaselined_2910_java_declared_packages": "#2910 replaces Java path-suffix fallback with declared-package resolution. The benchmark now restores package capture side channels, threads parsedFiles through javaScopeResolver, proves the context leg with a positive path/package-mismatch probe, and models the collide arm as one package declared across service paths. External imports now remain unresolved; local exact and wildcard imports preserve the 1153/4681 workload. Java's index is package/type maps rather than suffix maps: bytes_large 34958600 -> 3676984, with its floor and ceiling re-recorded together. Depth and collision scaling budgets tighten to the shared linear 1.8 gate.", diff --git a/gitnexus/bench/import-target/measure.mjs b/gitnexus/bench/import-target/measure.mjs index 5a1773c10d..f3f180a6e6 100644 --- a/gitnexus/bench/import-target/measure.mjs +++ b/gitnexus/bench/import-target/measure.mjs @@ -378,7 +378,7 @@ * toward the noise floor would only buy flaky CI; see `_blind_spot` in * baselines.json. PR #2911 is the proof that this blind spot is real rather * than theoretical: JavaScript's missing index was a scan of - * `ImportPassCache.normalizedFileList` on EVERY import, which the Set counter + * a cached normalized file array on EVERY import, which the Set counter * could not see, and it took a differential parity test over 211 200 pairs plus * this bench's arrival to pin it. * @@ -498,7 +498,7 @@ import { javaScopeResolver } from '../../src/core/ingestion/languages/java/scope import { cobolScopeResolver } from '../../src/core/ingestion/languages/cobol/scope-resolver.ts'; import { resolveSwiftImportTarget } from '../../src/core/ingestion/languages/swift/import-target.ts'; import { resolveRustImportTarget } from '../../src/core/ingestion/languages/rust/import-target.ts'; -import { resolveZigImportInternal } from '../../src/core/ingestion/import-resolvers/zig.ts'; +import { resolveZigImportInternal } from '../../src/core/ingestion/languages/zig/import-helpers.ts'; import { resolvePythonImportTarget } from '../../src/core/ingestion/languages/python/import-target.ts'; import { makeJsResolveImportTarget } from '../../src/core/ingestion/languages/javascript/import-target.ts'; import { makeVueResolveImportTarget } from '../../src/core/ingestion/languages/vue/import-target.ts'; @@ -1877,7 +1877,7 @@ function buildRepo(lang, fileCount, pad = 0, shape = 'unique') { * `resolutionConfig` the orchestrator threads beside it. * * `allFilePaths` is a FRESH Set per pass on purpose — every per-file-set memo - * in `import-resolvers/per-file-set.ts` is keyed on that object's identity, so + * in `utils/per-file-set.ts` is keyed on that object's identity, so * reusing one Set across passes would hide the index build after the first and * let a rebuilt-per-import index look free from rep 2 onward. * @@ -2070,8 +2070,8 @@ function resolveOne(lang, from, target, pass) { contextFor(pass, { kind: 'named', localName: 'X', importedName: 'X', targetRaw: target }), ); } - // Quotes already stripped — `configs/zig.ts` strips them before this call in - // production too. `null` build config: this arm pins the path walk alone + // Quotes are already stripped from the parsed import target. + // `null` build config: this arm pins the path walk alone // (see the header); the config legs are gated by their own unit tests. if (lang === 'zig') return resolveZigImportInternal(from, target, allFilePaths, null); if (lang === 'python') { diff --git a/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt b/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt index 6eb8287381..e172a35acc 100644 --- a/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt +++ b/gitnexus/bench/python-scope/baseline-import-target-fingerprint.txt @@ -1 +1 @@ -d51ea9edd1902fc20dd888f3fc51907c8119a4692b92c32a427801ac7f41d451 +99ec4434eb21b3212425eb92f5652e4955380ab27b705727b422b86e7e0be368 diff --git a/gitnexus/bench/receiver-resolution/BASELINE.md b/gitnexus/bench/receiver-resolution/BASELINE.md index 09bd31166b..0eb05b3302 100644 --- a/gitnexus/bench/receiver-resolution/BASELINE.md +++ b/gitnexus/bench/receiver-resolution/BASELINE.md @@ -1,5 +1,107 @@ # Receiver-resolution baseline +## Rust module-qualified factory results (#3498) + +The provider resolves module-qualified factory callees such as `rp::make`, +`modx::make` and `crate::modx::make` before reading their own return annotations. +Bound and inline receivers share that lookup. Untyped factory results retain +an unresolved-receiver drop. Type-qualified construction remains separate. + +The merged corpus contains 5,351 resolution records, compared with main +`f6e42092`'s 5,319: 32 records added, none removed, all in Rust. The additions include the +new factory fixture and `rust-ambiguous`'s `models::Handler.handle` receiver. +Shape states are unchanged. The fixture's two untyped receivers add two call +drops and two callee-read drops: calls 135 → 137, reads 27 → 29, all kinds +182 → 186; writes remain 20. The final benchmark check verifies this baseline. + +Qualified candidates retain Unicode names and accept uppercase module names. +Lexical type claims distinguish type-qualified construction from module calls, +including lowercase types and derived `Default`. A resolved type import or local +type claim cannot fall back to a same-named module. Const generic values remain +in Rust's value namespace. Local type aliases are not expanded by this change. + +The merge retains main's Zig capture behavior. Filename casing cannot establish +whether an imported file is a namespace; restoring main preserves the lowercase +`config.zig` file-struct edge. Python root-package imports and method-return +ownership use main's declaration checks. A cold Rust disk-scope regression and +a repeated-member call regression cover the shared producer and drop paths. +## Zig receiver gaps from the #3498 drop triage + +Measured against main `2b6542737`, the four Zig fixes clear 18 +`receiver-unresolved` sites: all-kind drops move from 200 to 182, reads from +42 to 27 and calls from 138 to 135. Writes and every shape-arm state are +unchanged. + +- 9 reads of `const X = @import("f.zig").X;` (zig-hub `stdx.zig:2-4`, + zig-receivers `stdx.zig:2`, zig-idioms `holder.zig:6`, `main.zig:6`, + `Element.zig:35`, `hub.zig:9-10`): the `@import(…)` receiver is now bound as a + namespace, so the read resolves through the written module (`import-resolved`). +- 3 reads off an anonymous container (`Sorter.zig:16`, `:23`, `:28`): + the receiver names the container's minted identity. The site is now anchored + on the member, so it moves off the reported `struct` position and resolves + from the scope that evaluates it. +- 1 call and its callee-position read at zig-idioms `main.zig:42` + (`Stack(u8).init()`): the new `isTypeApplicationCall` hook types the receiver + as `Stack`. +- 2 calls and their callee-position reads at zig-filestruct `aliases.zig:86` + and `:88` (`JsApi.Meta.prototype_chain` and `JsApi.value`): the + `bridge = generic.Bridge(Local)` alias reaches `Builder` through the + forwarding return type. These were lines 77 and 79 on the measured main. + +Forwarding type constructors (`Bridge ↦ Builder`) also work through the +namespace-factory lookup already merged in #3648. The combined result clears +more sites than the original standalone branch, which cleared 14. The `b12` +alias control resolves. Zig call drops fall from 13 to 10; `no-chain` call +drops move from 34 to 31 and `in-program` calls from 60 to 57. + +## C# namespace precedence after main integration + +Types resolve through the enclosing namespace declaration's lookup tiers. +Its own namespace and scoped using targets precede enclosing and global +namespaces; compilation-unit usings follow. Registry candidate collection stops +at the winning tier, retaining ambiguity within that tier. Bare class receivers +exclude known nonzero generic arity outside the class itself. Positioned using +ownership uses binary search over namespace starts. + +Before the Zig merge, against main `2b6542737`, call drops move from 138 to 135, reads from 42 to 41, +writes stay at 20, and all-kind drops move from 200 to 196. The four cleared +sites are the two Address.Save calls in csharp-field-types and +csharp-deep-field-chain, plus the City read and GetName call in the latter. +All shape-arm states are unchanged. The resolution corpus has 5,313 rows versus +5,309 on main: 40 removed records and 44 added records, all in C#. +Process traversal is capped; these counts do not prove whole-flow coverage. + +After merging main `f6e42092`, the baseline is 132 call drops, 26 reads, +20 writes and 178 across all kinds. Initializing the fixture's `Voucher.Payee` +keeps those counts and all shape states unchanged. The current corpus has +5,324 records versus main's 5,319: 45 additions and 40 removals, all in C#. +The initializer adds a constructor capture; only the C# capture fingerprint +changes, and all 16 scaling ratios remain below their unchanged budgets. + +## JS/TS literal-key writes and class-level field receivers (#3498) + +Measured on top of #3654 (`a3db31923`, tree-identical to its squash merge +`2b6542737`). Call drops move from 138 to 136, all-kind drops from 200 to +178, and writes from 20 to zero. Read drops remain 42 and every shape-arm +state is unchanged. + +The 20 cleared writes are 19 object-literal keys answered by later resolution +passes and the CommonJS `module.exports.arrowRequest` declaration. Answered +sites withdraw only a matching kind/name/site drop; unanswered sites retain +theirs. A return-shape key's own write requires its exact declaration position +and file, so unrelated input reads and writes retain ordinary candidate ranking. + +The two call-drop changes are `Config.DEFAULT.validate()` resolving through +its `new Config()` initializer and the owned `this.route.go()` site in +`ts-dynamic-this-no-seed` being classified as `receiver-owned-but-unbound`, +which is outside this gate. The latter does not gain a call edge, and its call +remains in the persisted unresolved-receiver summary used by impact/context. +Static field inference stops at an untyped override and resolves constructor names through +the value namespace; annotations retain type-namespace lookup. + +Answered-site identity includes the full range, so an answered inner read in +`res.data.data` cannot withdraw the unresolved outer read with the same name. + ## Go module visibility and qualified receiver refusal Local imports now select the importer's own module or a module selected by its @@ -892,3 +994,38 @@ Two incidental corrections from that check, both to KTD6: drop is recorded. An untyped fixture parameter had been reporting a language gap that was really a fixture defect — the same error class as the untyped `$repo` control caught earlier. + + +### Merged main `f6e42092` + +Re-measured both benchmark arms after merging the Zig receiver fix from main. +Shape states remain unchanged; counts are 132 call drops and +178 drops of all kinds (26 reads, +20 writes). The counts include both main and this branch's fixes. + +Shape states remain unchanged; counts are 133 call drops and +160 drops of all kinds (27 reads, +0 writes). The counts include both main and this branch's fixes. + +### Rust qualified factories after #3653 + +Main `2b4456553` is merged normally. The receiver-drop guard preserves both qualified-factory evidence and the module-export exclusion. Fresh build, both TypeScript configurations and all 28 Rust boundary, capture-golden and CommonJS checks pass. The measured baseline has 135 call drops, 164 total drops, 29 reads and 0 writes. +### C++ qualified receivers after #3653 + +Main `2b4456553` is merged normally. The field lookup retains both the declared namespace purpose and provider-qualified type handling. Build and both TypeScript configurations pass, and all 59 focused C++ and CommonJS merge checks pass. The measured receiver baseline has 133 call drops, 160 total drops, 27 reads and 0 writes. +### After merging #3653 into the C# namespace branch + +Main `2b4456553` is merged normally. The measured baseline has 130 call drops and 156 across all kinds, with 26 reads and zero writes. Main has 133 calls, 27 reads and zero writes (160 total). Every shape state matches main. The fresh build and both TypeScript configurations pass, as do all 68 namespace-boundary, capture, hook and CommonJS merge checks. + +### Rust qualified factories after #3655 + +Main `caacc3bac` is merged normally. The C# capture baseline retains main's fixture additions, and receiver counts are regenerated on the combined source: 132 call drops, 160 total, 28 reads and zero writes. All shape states match the preceding Rust baseline. Fresh build, both TypeScript configurations and 23 Rust factory, capture and CommonJS checks pass. Final hosted CI remains required. +### C++ qualified receivers after #3655 + +Main `caacc3bac` is merged normally. The regenerated combined baseline has 130 call drops,156 total,26 reads and zero writes; all shape states match. These counts include the C# namespace fix from main. The broad C++ resolver run was interrupted for the prioritized focused merge checks and is not reported as a pass. Fresh exact-head CI remains required. + +The prioritized merge validation passes a fresh package build, both TypeScript configurations and 56 tests across six C++, CommonJS and C# namespace-boundary files. + +### Rust qualified factories after #3656 + +Main `a09f76be3` is merged normally. The shared receiver pass keeps Rust's provider-qualified callee hook and C++'s position-aware qualified-member lookup. Fresh package build, both TypeScript configurations and 302 tests across 20 Rust, C++, Go, CommonJS and sealed-disk-scope files pass. All 16 capture scaling checks pass without changing their budgets. The regenerated receiver check passes with 132 call drops, 160 across all kinds, 28 reads and zero writes; shape states are unchanged. The corpus adds 32 Rust resolution records to main's 5,392, removes none, and totals 5,424. Exact-head hosted CI remains required. diff --git a/gitnexus/bench/receiver-resolution/baseline.json b/gitnexus/bench/receiver-resolution/baseline.json index 9deb7c6c94..a70499aa11 100644 --- a/gitnexus/bench/receiver-resolution/baseline.json +++ b/gitnexus/bench/receiver-resolution/baseline.json @@ -199,39 +199,38 @@ } }, "countArm": { - "callDrops": 138, - "totalDropsAllKinds": 200, + "callDrops": 132, + "totalDropsAllKinds": 160, "bySiteKind": { - "call": 138, - "read": 42, - "write": 20 + "call": 132, + "read": 28 }, "callDropsByExtension": { ".java": 49, ".py": 24, - ".ts": 17, - ".zig": 13, - ".cs": 8, + ".ts": 16, + ".zig": 10, ".tsx": 6, + ".rs": 6, + ".cs": 5, ".go": 4, ".php": 4, - ".rs": 4, ".kt": 4, - ".js": 2, ".dart": 2, + ".js": 1, ".swift": 1 }, "callDropsByShape": { - "chain-field": 59, - "no-chain": 34, + "chain-field": 54, + "no-chain": 33, "chain-call": 31, "<>": 13, "chain-unwrap": 1 }, "callDropsByOrigin": { - "in-program": 60, + "in-program": 55, "external": 44, - "unknown": 32, + "unknown": 31, "<>": 2 } } diff --git a/gitnexus/bench/scope-capture/baselines.json b/gitnexus/bench/scope-capture/baselines.json index 8d3ab71990..8e0892c671 100644 --- a/gitnexus/bench/scope-capture/baselines.json +++ b/gitnexus/bench/scope-capture/baselines.json @@ -11,11 +11,11 @@ "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior 3d4e32e7490c830516126e28931827949baa3594cb521f7a3d8dcfed95b6018a -> 57b3c55135af8d2af33b9a7c4bf89796a7bee5b5822b402a2dea91af7232cf4a; scaling 1.058 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: provider-owned callable assignment/copy/formal/argument/invoke facts with invocation/constructor-result suppression. Prior 09ecd94911b830f52fa8807560abcbd79f163d02a2072870c1a59297e9a326e1 -> 3d4e32e7490c830516126e28931827949baa3594cb521f7a3d8dcfed95b6018a; scaling 1.039 < 1.5.", "_rebaselined": "#1976: F33 generic composite literal constructor inference adds generic_type captures in composite_literal patterns; fingerprint drift expected.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 57b3c55135af8d2af33b9a7c4bf89796a7bee5b5822b402a2dea91af7232cf4a -> 5d6c59c2f2c0dd937c53bf5d736e0f8376b2899a381e488a33aec23524823efb.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 57b3c55135af8d2af33b9a7c4bf89796a7bee5b5822b402a2dea91af7232cf4a -> 5d6c59c2f2c0dd937c53bf5d736e0f8376b2899a381e488a33aec23524823efb.", "_rebaselined_2766_go_pointer_receiver_fixture": "#2766: added test/fixtures/lang-resolution/go-pointer-receiver-field-chain/ (2 Go files) as the committed regression fixture for pointer-receiver base resolution. Go fixture_count 100 -> 102. Prior 5d6c59c2f2c0dd937c53bf5d736e0f8376b2899a381e488a33aec23524823efb -> 8cba537ff211fab3bac5fb4456cd1ffba14d6a2db75c40acae28ab8bf29f3d2e. FIXTURE-CORPUS GROWTH, NOT A CAPTURE CHANGE: the accompanying fix is a resolution-time lookup fallback (stripTypePreservingDecoration) and cannot move capture output; go was the ONLY language whose fingerprint drifted, and every other language matched its baseline on the same run.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 8cba537ff211fab3bac5fb4456cd1ffba14d6a2db75c40acae28ab8bf29f3d2e -> 8162272bb897b0b89472c406321cf8d88a5ae4ea83ea9e3c45f8e817041bff9f.", - "_rebaselined_2766_await_subscript_emission": "#2766: extractMixedChain now walks THROUGH await and subscript nodes and peels transparent wrappers at loop entry, so sites whose receiver is `repos[0]` or `(await f())` mint a receiver chain where they previously minted none. EMISSION CHANGE: more sites carry `@reference.receiver-chain`; no existing chain changed shape. Only go and kotlin drifted of 15 \u2014 the two whose fixture corpora contain such receivers. Prior 8162272bb897b0b89472c406321cf8d88a5ae4ea83ea9e3c45f8e817041bff9f -> c9c908f441e3be12fad2448120ed3ea35dc235a12b3f63b0ec532ffdae11d9e9.", - "_rebaselined_2766_phantom_callee_read_site": "#2766: Go's `@reference.read` pattern matches EVERY selector_expression, so a member call `h.dep.Work()` minted THREE sites \u2014 the call, the genuine `h.dep` field read, and a PHANTOM read on the callee `h.dep.Work`. The phantom resolved through findOwnedMember (which prefers methods over fields) and emitted an ACCESSES edge to the METHOD duplicating the CALLS edge at the same position; visible today on any receiver the text cascade can type (`RunFromValueReceiver -> DoWork`). The emitter now drops a read match whose selector is in FUNCTION position. FEWER capture matches for Go, no other language affected \u2014 go was the only fingerprint of 15 that moved. A method VALUE (`f := h.dep.Work`) is not in function position and is untouched. Prior c9c908f441e3be12fad2448120ed3ea35dc235a12b3f63b0ec532ffdae11d9e9 -> 7bb524a32a2eed57a15b454e3a33480e92a496c683e6856ef02179693c0e02e3.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 8cba537ff211fab3bac5fb4456cd1ffba14d6a2db75c40acae28ab8bf29f3d2e -> 8162272bb897b0b89472c406321cf8d88a5ae4ea83ea9e3c45f8e817041bff9f.", + "_rebaselined_2766_await_subscript_emission": "#2766: extractMixedChain now walks THROUGH await and subscript nodes and peels transparent wrappers at loop entry, so sites whose receiver is `repos[0]` or `(await f())` mint a receiver chain where they previously minted none. EMISSION CHANGE: more sites carry `@reference.receiver-chain`; no existing chain changed shape. Only go and kotlin drifted of 15 — the two whose fixture corpora contain such receivers. Prior 8162272bb897b0b89472c406321cf8d88a5ae4ea83ea9e3c45f8e817041bff9f -> c9c908f441e3be12fad2448120ed3ea35dc235a12b3f63b0ec532ffdae11d9e9.", + "_rebaselined_2766_phantom_callee_read_site": "#2766: Go's `@reference.read` pattern matches EVERY selector_expression, so a member call `h.dep.Work()` minted THREE sites — the call, the genuine `h.dep` field read, and a PHANTOM read on the callee `h.dep.Work`. The phantom resolved through findOwnedMember (which prefers methods over fields) and emitted an ACCESSES edge to the METHOD duplicating the CALLS edge at the same position; visible today on any receiver the text cascade can type (`RunFromValueReceiver -> DoWork`). The emitter now drops a read match whose selector is in FUNCTION position. FEWER capture matches for Go, no other language affected — go was the only fingerprint of 15 that moved. A method VALUE (`f := h.dep.Work`) is not in function position and is untouched. Prior c9c908f441e3be12fad2448120ed3ea35dc235a12b3f63b0ec532ffdae11d9e9 -> 7bb524a32a2eed57a15b454e3a33480e92a496c683e6856ef02179693c0e02e3.", "_rebaselined_2766_callee_position_marker": "#2766 review fix: a call's callee selector is no longer DROPPED at capture. An earlier commit on this branch dropped it outright, which also deleted the genuine field read on a func-typed struct field (`h.dep.Work()` where `Work func() error`) - callback/hook/mock structs lost their only ACCESSES evidence. The match is now emitted carrying `@reference.callee-position`, and the phantom is suppressed at EMIT by the resolved target's kind instead. Go only: the other 14 languages' fingerprints are byte-identical, which is the check that this is not a cross-language capture change. Prior 7bb524a32a2eed57a15b454e3a33480e92a496c683e6856ef02179693c0e02e3 -> e47302079e17a5e73711bbed5416557b49327cb67e4932008700ec6b8fb468b3; scaling 1.001 < 1.5; fixtures 102 (unchanged), capture_groups_fp 2103.", "_rebaselined_2813_interface_field_dispatch_fixture": "#2813: added test/fixtures/lang-resolution/go-interface-field-dispatch/ (8 Go files) as the committed regression fixture for calls through an interface-typed struct field. Go fixture_count 102 -> 110. FIXTURE-CORPUS GROWTH, NOT A CAPTURE CHANGE: the accompanying fixes are a detection-time method-set change (interface-impls.ts) and a resolution-time fan-out in the shared receiver pass, neither of which emits captures; go/query.ts and go/captures.ts are untouched. Go was the ONLY language whose fingerprint drifted, and every other language matched its baseline on the same run - the same check used for the #2766 fixture growth above. Prior e47302079e17a5e73711bbed5416557b49327cb67e4932008700ec6b8fb468b3 -> cffee41cadbf350855d99bd5aee7c015b1e8b31d1c343d02f113540abe86c765; scaling 1.074 < 1.5, capture_groups_fp 2303.", "_rebaselined_2837": "#2837: Go struct/interface captures re-anchored from the type_declaration onto the type_spec (@scope.class/@declaration.struct/@declaration.interface in languages/go/query.ts, @definition.struct/@definition.interface in GO_QUERIES). A grouped `type (...)` block used to yield ONE scope and ONE node for every type in it, so each type after the first lost its field typeBindings and every field-receiver call in the file emitted nothing. Capture COUNT is unchanged; only ranges moved, plus the new go-grouped-type-decl fixture. Prior c27fb803598581fa4eb7ddf5ef6f8369b9e3a150082d11362e7aa3ec8faaa832 -> e386598526e502d131e52a17d219635b3a4196d94f1ebdd25922a2582c985d18; scaling 1.054 < 1.5.", @@ -24,11 +24,11 @@ }, "cobol": { "fingerprint": "d77fe8c2e08894d40bfdfeb6df8f5eceefa9f870bdfce9d4b620e6ef298870c9", - "_rebaselined_2813_exact_method_sets": "#2813: Go embedded fields now emit `@reference.embedded-pointer` when spelled `*T` rather than `T`. A CAPTURE-EMISSION CHANGE, not fixture growth: fixture_count is unchanged at 110 and capture_groups_fp moves 2303 -> 2339 (+36), which is the new marker plus the WrongSigRepo/Recount rows added to two existing fixture files. The marker is required for exactness \u2014 Go gives `struct{ Base }` and `struct{ *Base }` different method sets, so structural interface satisfaction cannot be correct without knowing which was written (go.dev/ref/spec#Struct_types). Go was the ONLY language of 15 whose fingerprint moved, which is the check that this is a Go capture change and not a cross-language regression. Accompanied by SCHEMA_BUMP 39 -> 43 (skipping 40/41/42, taken by origin/main during review) so a warm cache cannot replay the pre-marker capture set. Prior cffee41cadbf350855d99bd5aee7c015b1e8b31d1c343d02f113540abe86c765 -> c27fb803598581fa4eb7ddf5ef6f8369b9e3a150082d11362e7aa3ec8faaa832; scaling 0.987 < 1.5.", + "_rebaselined_2813_exact_method_sets": "#2813: Go embedded fields now emit `@reference.embedded-pointer` when spelled `*T` rather than `T`. A CAPTURE-EMISSION CHANGE, not fixture growth: fixture_count is unchanged at 110 and capture_groups_fp moves 2303 -> 2339 (+36), which is the new marker plus the WrongSigRepo/Recount rows added to two existing fixture files. The marker is required for exactness — Go gives `struct{ Base }` and `struct{ *Base }` different method sets, so structural interface satisfaction cannot be correct without knowing which was written (go.dev/ref/spec#Struct_types). Go was the ONLY language of 15 whose fingerprint moved, which is the check that this is a Go capture change and not a cross-language regression. Accompanied by SCHEMA_BUMP 39 -> 43 (skipping 40/41/42, taken by origin/main during review) so a warm cache cannot replay the pre-marker capture set. Prior cffee41cadbf350855d99bd5aee7c015b1e8b31d1c343d02f113540abe86c765 -> c27fb803598581fa4eb7ddf5ef6f8369b9e3a150082d11362e7aa3ec8faaa832; scaling 0.987 < 1.5.", "scaling_budget": 1.5, "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: COBOL procedure-pointer callable flow facts; multi-topic extraction now consumes each grouped scope/declaration match once instead of requiring a duplicate declaration-only match. Prior 68ee0e95eb9f86f2d92ca35f730f4c2d4d83abc1b5241ae767ff3437780ec8d1 -> d45bb091b0893d0de4fae2486b31ba21719c9377bf35a0908fd3a36fa1c3bf4e; scaling 0.853 < 1.5.", "_note": "Updated for F17-F23 fixes (P2: TIMES guard, ADD GIVING, SQL AS alias). See PR #1959.", - "_rebaselined_2793_declaratives": "PR #2793: corpus-only re-baseline. `cobol-declaratives` was added to test/fixtures/lang-resolution to reproduce the `Namespace\u2192Record` analyze abort (DECLARATIVES / USE AFTER STANDARD ERROR ON ), and this bench globs `lang-resolution/cobol-*`, so the corpus grew 14 -> 15 files. Verified capture-neutral: with that one fixture moved aside the fingerprint is byte-identical to the prior d45bb091b0893d0de4fae2486b31ba21719c9377bf35a0908fd3a36fa1c3bf4e. No COBOL capture code changed in that PR. Scaling 0.677 < 1.5.", + "_rebaselined_2793_declaratives": "PR #2793: corpus-only re-baseline. `cobol-declaratives` was added to test/fixtures/lang-resolution to reproduce the `Namespace→Record` analyze abort (DECLARATIVES / USE AFTER STANDARD ERROR ON ), and this bench globs `lang-resolution/cobol-*`, so the corpus grew 14 -> 15 files. Verified capture-neutral: with that one fixture moved aside the fingerprint is byte-identical to the prior d45bb091b0893d0de4fae2486b31ba21719c9377bf35a0908fd3a36fa1c3bf4e. No COBOL capture code changed in that PR. Scaling 0.677 < 1.5.", "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. Provider semantic facts replace line-only declarations: exact name spans and qualified/binding identities, full executable ownership scopes, section namespaces, data-item properties and identifier reads/calls. The 13 changed fixture entries gain 49 property declarations, 150 reads and 11 call-reference groups; sections become 5 namespaces instead of callable functions. The fixture corpus is unchanged. Fixture entries 15; changed entries 13; capture groups 110 -> 320. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." }, "c": { @@ -37,17 +37,22 @@ "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior 57fee292147ae6d2db7062da1e07d17122cf355207c8967fa85fd2ec9ca398a4 -> 3418cded9f7072152f68992f0a426f43ae7d9d553579a47075fc0cab185848a5; scaling 1.073 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: C function-pointer signatures plus direct-callee argument metadata and invocation-result suppression. Prior 75bcdbbf006bf9bd263c0f5857461b118f39b164e9f821cb0651ad0ec46ef6ae -> 57fee292147ae6d2db7062da1e07d17122cf355207c8967fa85fd2ec9ca398a4; scaling 1.035 < 1.5.", "_rebaselined_callable_flow": "Callable-value-flow facts for C function pointers, copies, pointer-to-pointer cells, arguments, and indirect invokes. Prior 12a196b2d6249c8d86a931b12ecebc2a0cdf8d6f47683acdd0d8e9d8bc7657f5 -> 75bcdbbf006bf9bd263c0f5857461b118f39b164e9f821cb0651ad0ec46ef6ae; measured scaling ratio 0.980 < 1.5.", - "_added": "#1956: c added to the scope-capture bench (was UNBENCHED). C has no inheritance \u2014 flat scale source. Adding it exposed + fixed a pre-existing O(n^2) findNodeAtRange root-walk in c/captures.ts (threaded c.node, byte-identical over c-* fixtures); scaling 3.475 -> 0.96.", - "_note": "#1983: + c-static-linkage-worker fixture (caller.c/lib.c/lib.h/local.c \u2014 worker-path static-linkage side-channel test). Pure fixture-corpus drift: no c/captures.ts or query change branch-vs-main, existing fixtures' captures byte-identical (c-captures.test.ts 45/45), scaling stays linear (~0.97). The baseline was missed when the fixture landed; regenerated here. fingerprint 0de009b->39f3a83.", + "_added": "#1956: c added to the scope-capture bench (was UNBENCHED). C has no inheritance — flat scale source. Adding it exposed + fixed a pre-existing O(n^2) findNodeAtRange root-walk in c/captures.ts (threaded c.node, byte-identical over c-* fixtures); scaling 3.475 -> 0.96.", + "_note": "#1983: + c-static-linkage-worker fixture (caller.c/lib.c/lib.h/local.c — worker-path static-linkage side-channel test). Pure fixture-corpus drift: no c/captures.ts or query change branch-vs-main, existing fixtures' captures byte-identical (c-captures.test.ts 45/45), scaling stays linear (~0.97). The baseline was missed when the fixture landed; regenerated here. fingerprint 0de009b->39f3a83.", "_rebaselined": "#1919 open-language coverage: new lang-resolution fixtures + intended capture additions (F5/F9 c-cpp, F26/F28/F29 dart, F47/F48/F49/F51/F52 kotlin, F75/F79 swift). Fingerprint-only drift; scaling_ratio ~1.0 (linear, no perf regression).", "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 72 pointer-parameter and 43 field type bindings are added; 19 reference-only struct/union specifiers stop introducing class scopes; 53 callable groups gain C/C++-compatible parameter type classes and normalized type spelling. The existing fixture corpus is unchanged. Fixture entries 15; changed entries 9; capture groups 545 -> 641. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." }, "cpp": { "_lexical_ownership_3532": "#3532: lexical ownership captures and fixture updates; fixture identities are relative to lang-resolution so serialized scope IDs are independent of checkout location. Full capture content remains hashed; scaling_budget is unchanged.", - "fingerprint": "dfd1de80f55d8e1bacde91a99951e7eee4e76ccdc8a7477c5a8ac98d804ce05a", + "fingerprint": "14dcc4038c95a874f8f7bd72cbd8797f2deb030ba080b0d124ebcb3117617d00", + "_rebaselined_qualified_receiver_typing_factory_callee": "Qualified factory callee: captures.ts now promotes `auto x = ns::f()` / `auto x = ns::T()` (a qualified_identifier callee whose innermost name is a plain identifier) from the `type: (_)` @type-binding.assignment match, which bound x to the literal type `auto`, to @type-binding.constructor with the whole qualified callee as @type-binding.type - the qualified twin of the bare `auto x = f()` rule. Template callees (`std::make_shared()`) keep their dedicated rule. Compared canonicalized captures of the pre-change and post-change emitters over the same corpus: exactly ONE match changed outside the new fixture - cpp-method-enrichment/app.cpp `auto category = Animal::classify(\"dog\");`, @type-binding.assignment/type `auto` -> @type-binding.constructor/type `Animal::classify` - and none was added or removed; synthetic DAO-20 unchanged. interpret.ts additionally drops any leftover `auto` / `decltype(auto)` binding (no capture effect; over the corpus no such leftover remained). The fixture gains its qualified-factory callers (+33 groups). capture_groups_fp 4793 -> 4826, fixture_count 285 unchanged. Corpus A/B: no edge or drop outside the fixture moved (the changed binding names a class's static method, which the qualified-namespace lookup does not answer, so category stays untyped as before). Prior 2242a6b8085b27478cc8bf6f37da3f7b9b07df85fd863a3f633d7b0887ab7ac8 -> 13bfad4a8197dd9e3d252e28c6b591e08bb51e799d1c1a839f8a485d11e549eb; scaling 1.198 < 1.5.", + "_rebaselined_qualified_receiver_typing_inline_fixture": "cpp-qualified-receiver-typing/using.cpp gains two inline-receiver callers (`make().m()` and `makeWidget().m()` under a using-directive) for the compound resolver's definition-identity return-type fallback. CORPUS GROWTH ONLY: the accompanying fix is resolution-time (compound-receiver.ts) and no emitter changed; the new fixture is the only file whose captures moved (+14 groups). capture_groups_fp 4779 -> 4793, fixture_count 285 unchanged. Prior b21abc71298d184dd484647e6d36237bb56e66c82597ef7a47452a74526856cd -> 2242a6b8085b27478cc8bf6f37da3f7b9b07df85fd863a3f633d7b0887ab7ac8; scaling 1.167 < 1.5.", + "_rebaselined_qualified_receiver_typing_prototype_returns": "Header prototype return types: two @type-binding.return rules on a free-function PROTOTYPE (`D makeD();`, `D* makeDp();`), anchored on the `declaration` node; captures.ts drops a match whose declaration is not at namespace scope (translation unit or declaration_list, through preprocessor conditionals, extern \"C\" and template prefixes), so a block-scope `D x();` (most vexing parse) binds nothing. Compared canonicalized captures of the pre-change and post-change emitters over the same corpus: exactly ONE match added outside the new fixture - cpp-return-type/user.h `User getUser(const char* name);` (the header prototype whose same-file definition already bound the identical type) - and nothing removed or changed; synthetic DAO-20 unchanged (no free prototypes). Over the whole cpp corpus the gate drops exactly one candidate, the fixture's deliberate `E y();` in a function body. The fixture gains its prototype shapes and using.cpp (140 -> 242 groups, fixture_count 284 -> 285). capture_groups_fp 4676 -> 4779. Corpus A/B: no edge or drop outside the fixture moved. Prior a50c2b2313f34e03f8da44d34007250830b66af7c62690d55b1716219eae481e -> b21abc71298d184dd484647e6d36237bb56e66c82597ef7a47452a74526856cd; scaling 1.226 < 1.5.", + "_rebaselined_qualified_receiver_typing_declared_ns": "Qualified declarations without an initializer: two @type-binding.annotation rules matching the OUTER qualified_identifier (`rp::C x;` and `rp::C* x = nullptr;`), the qualified twins of the bare `T x;` / `T* x = ...` rules, so the local binds `rp::C` as written for the qualifier-aware resolver. Compared canonicalized captures of the pre-change and post-change emitters over the same corpus: 29 matches ADDED outside the new fixture, every one a @type-binding.annotation on a qualified local (21 x `ns::T v;` - audit::Event, data::Pair, lib::T, alpha::Token, lib::Foo - across 16 cpp-adl-* / cpp-inline-namespace-adl-participation / cpp-phase5-u2-u3-adl-from-derived files, plus 8 std::vector / std::array / std::map locals in cpp-adl-template-args, cpp-template-cross-file and cpp-template-overload); zero matches removed or changed, no other tag moved, synthetic DAO-20 unchanged (it declares no qualified local). The new fixture gains 2 callers (127 -> 140 groups). capture_groups_fp 4634 -> 4676. Corpus A/B: no CALLS/ACCESSES edge or receiver drop outside the fixture moved (ADL arguments are typed from the capture-time AST, not typeBindings). Prior 83c1009cd6c88f6997a0b7aa8c188bc7c44c03e9126a2ed684bfb5a21bb9f5f3 -> a50c2b2313f34e03f8da44d34007250830b66af7c62690d55b1716219eae481e; scaling 1.255 < 1.5.", + "_rebaselined_qualified_receiver_typing_brace_init": "Qualified receiver typing (resolveQualifiedTypeSpellings): the `auto x = ns::T{}` brace-init @type-binding.constructor rule now captures the WHOLE qualified_identifier instead of its type_identifier tail, so the resolver can match the qualifier (the tail bound a nearer same-named class: a global C through another include, or the enclosing namespace's own Config). Compared canonicalized captures of the pre-change and post-change emitters over the same corpus: exactly ONE existing match changed - cpp-scoped-brace-init/main.cpp `client = ns::HttpClient{}`, @type-binding.type text HttpClient -> ns::HttpClient (range 4:22-4:32 -> 4:18-4:32); no tag was added or removed anywhere. The rest is CORPUS growth: the new cpp-qualified-receiver-typing fixture (5 files, 127 capture groups). capture_groups_fp 4507 -> 4634, fixture_count 279 -> 284. The member field change (non-generic qualified members keep their qualifier) is in interpret.ts and does not touch captures. Prior dfd1de80f55d8e1bacde91a99951e7eee4e76ccdc8a7477c5a8ac98d804ce05a -> 83c1009cd6c88f6997a0b7aa8c188bc7c44c03e9126a2ed684bfb5a21bb9f5f3; scaling 1.479 < 1.5 on a host at load ~14.", "scaling_budget": 1.5, - "_rebaselined_2833_qualified_member_fields": "#2833 follow-up: the six per-qualifier-depth `field_declaration` type-binding rules for a QUALIFIED generic member are replaced by three depth-agnostic ones that match the outer `qualified_identifier` itself, with the qualifier reduced to its top-level tail in `interpret.ts` (`cppQualifiedTail`). This is a CAPTURE-LOGIC change and it moves the fingerprint in two places at once. (1) A qualified NON-generic member (`ns::Address addr;`, `std::string name;`) was captured by nothing at all and now binds \u2014 that is the whole +24 on the fixture corpus, every one of them a `std::string` member. (2) Qualifier depth is no longer enumerated, so `a::b::c::Repo` (depth 3+) is captured where the old rules stopped at 2. Capture-name histogram, cpp-* corpus (278 files): `@type-binding.field` 8 -> 32, `@type-binding.name` and `@type-binding.type` 401 -> 425; synthetic DAO-20: `@type-binding.field` 40 -> 60, `@type-binding.name` and `@type-binding.type` 61 -> 81 (= 20 entities x the one `std::string name;` member the DAO unit already declared). NO OTHER TAG MOVED in either set \u2014 not one `@declaration.*`, `@scope.*` or `@reference.*` count \u2014 which is the property that says three rules replaced six without widening what a field_declaration matches. Measured over the 13 cpp-* fixture repos whose sources gained a binding, the distinct CALLS edge set is byte-identical before and after (32 edges): a reduced tail that names no workspace class binds nothing. Prior bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a -> db1156d81b3e3341faf5e938a4a34417f4fd246588b6150b4686481823262529; scaling 1.04 < 1.5.", - "_rebaselined_2833_generic_member_fields": "#2833 review follow-up: the cpp DAO generator's unit gains two GENERIC member fields \u2014 `Repo repo;` (bare template_type) and `std::vector items;` (qualified_identifier wrapping a template_type) \u2014 plus the header declaring `template class Repo`. CORPUS CHANGE, NOT A CAPTURE-LOGIC CHANGE: no extractor edit accompanies it. It exists because the corpus had ZERO template-typed member fields and, across 279 cpp-* fixtures, not one qualified generic member either, so BOTH rounds of new `field_declaration` type-binding rules landed with a byte-identical cpp fingerprint \u2014 the gate was structurally blind to the exact thing being changed. Measured under the new corpus, the three states now differ: pre-#2833 query 0e7cbda71360b7ff35dd76091c77f288d6af6a5cfa9185ad85a372aae8c85191 (4521 groups) -> the three template_type field rules de07d8b5300ed867b460918e16b4d80259c7eb6efc1034d32bebe9ff7cab126d (4541) -> the six qualified rules bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a (4561); under the OLD corpus all three were 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc. Capture-name histogram over the synthetic DAO-20: `@type-binding.field` 0 -> 40, `@declaration.field` 40 -> 80, `@type-binding.type`/`@type-binding.name` 20 -> 61, `@declaration.name` 104 -> 147 \u2014 40 = 20 entities x 2 fields, with the residual +1/+2/+3 attributable to the one-off header declaration; every `@reference.*` count is unchanged. Prior 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc -> bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a; scaling 1.058 < 1.5. `c` is unaffected (3418cded..., unchanged).", + "_rebaselined_2833_qualified_member_fields": "#2833 follow-up: the six per-qualifier-depth `field_declaration` type-binding rules for a QUALIFIED generic member are replaced by three depth-agnostic ones that match the outer `qualified_identifier` itself, with the qualifier reduced to its top-level tail in `interpret.ts` (`cppQualifiedTail`). This is a CAPTURE-LOGIC change and it moves the fingerprint in two places at once. (1) A qualified NON-generic member (`ns::Address addr;`, `std::string name;`) was captured by nothing at all and now binds — that is the whole +24 on the fixture corpus, every one of them a `std::string` member. (2) Qualifier depth is no longer enumerated, so `a::b::c::Repo` (depth 3+) is captured where the old rules stopped at 2. Capture-name histogram, cpp-* corpus (278 files): `@type-binding.field` 8 -> 32, `@type-binding.name` and `@type-binding.type` 401 -> 425; synthetic DAO-20: `@type-binding.field` 40 -> 60, `@type-binding.name` and `@type-binding.type` 61 -> 81 (= 20 entities x the one `std::string name;` member the DAO unit already declared). NO OTHER TAG MOVED in either set — not one `@declaration.*`, `@scope.*` or `@reference.*` count — which is the property that says three rules replaced six without widening what a field_declaration matches. Measured over the 13 cpp-* fixture repos whose sources gained a binding, the distinct CALLS edge set is byte-identical before and after (32 edges): a reduced tail that names no workspace class binds nothing. Prior bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a -> db1156d81b3e3341faf5e938a4a34417f4fd246588b6150b4686481823262529; scaling 1.04 < 1.5.", + "_rebaselined_2833_generic_member_fields": "#2833 review follow-up: the cpp DAO generator's unit gains two GENERIC member fields — `Repo repo;` (bare template_type) and `std::vector items;` (qualified_identifier wrapping a template_type) — plus the header declaring `template class Repo`. CORPUS CHANGE, NOT A CAPTURE-LOGIC CHANGE: no extractor edit accompanies it. It exists because the corpus had ZERO template-typed member fields and, across 279 cpp-* fixtures, not one qualified generic member either, so BOTH rounds of new `field_declaration` type-binding rules landed with a byte-identical cpp fingerprint — the gate was structurally blind to the exact thing being changed. Measured under the new corpus, the three states now differ: pre-#2833 query 0e7cbda71360b7ff35dd76091c77f288d6af6a5cfa9185ad85a372aae8c85191 (4521 groups) -> the three template_type field rules de07d8b5300ed867b460918e16b4d80259c7eb6efc1034d32bebe9ff7cab126d (4541) -> the six qualified rules bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a (4561); under the OLD corpus all three were 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc. Capture-name histogram over the synthetic DAO-20: `@type-binding.field` 0 -> 40, `@declaration.field` 40 -> 80, `@type-binding.type`/`@type-binding.name` 20 -> 61, `@declaration.name` 104 -> 147 — 40 = 20 entities x 2 fields, with the residual +1/+2/+3 attributable to the one-off header declaration; every `@reference.*` count is unchanged. Prior 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc -> bd47c82d09a83cbf0ac857f41876fa31d22304043735582e913bccde06cf2c1a; scaling 1.058 < 1.5. `c` is unaffected (3418cded..., unchanged).", "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature/cv metadata. Prior dde874d2c30bda9f634f9799281a66de800cad9f76cf65e7c31839e2ae9da9ff -> 57860dd2a8d4b06c6d2dd0d854c08b781faee3da8f2b6c42ba0c68a9f70e5ccb; scaling 1.090 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: C++ overload-aware function/reference/member-pointer flow facts with invocation/constructor-result suppression. Prior 3a503a1513e7eede3f7a223dcce0896c06d15bdfa920445224c9025848c0d710 -> dde874d2c30bda9f634f9799281a66de800cad9f76cf65e7c31839e2ae9da9ff; scaling 1.034 < 1.5.", "_rebaselined_callable_flow": "Callable-value-flow facts for C++ function pointers/references, reference aliases, contextual arity, arguments, and member-pointer syntax. Prior 6ab657c8f9bfe988a3759098c2cffdcc0443def75ff263f1282b82c21d96e931 -> 3a503a1513e7eede3f7a223dcce0896c06d15bdfa920445224c9025848c0d710; measured scaling ratio 1.069 < 1.5.", @@ -55,56 +60,61 @@ "_note_1899_followup": "#1899 follow-up: braced-init metadata now carries element count, intentionally changing C++ capture output; CI benchmark scaling remains linear (1.129 < 1.5).", "_added": "#1956: cpp added to the scope-capture bench (was UNBENCHED). Heritage-bearing scale source (: public Base, public Mixin) drives emitCppInheritanceCaptures at scale. Adding it exposed + fixed a pre-existing O(n^2) findNodeAtRange root-walk in cpp/captures.ts (~12 sites, threaded c.node, byte-identical over 263 cpp-* fixtures); scaling 2.30 -> 1.12.", "_rebaselined": "#1919 open-language coverage: new lang-resolution fixtures + intended capture additions (F5/F9 c-cpp, F26/F28/F29 dart, F47/F48/F49/F51/F52 kotlin, F75/F79 swift). Fingerprint-only drift; scaling_ratio ~1.0 (linear, no perf regression). #2094: deleted C++ declarations retain @declaration.is-deleted metadata; deleted operator and pointer-return shapes plus the expanded deleted-overload fixture are included. Intended capture drift; scaling remains linear (1.139 < 1.5).", - "_note": "#1975: + cpp-out-of-line-class fixture, fixture_count 263->265. #1990: + cpp-adl-ns-plus-hidden-friend-same-name fixture (ADL hidden-friend + namespace-callable merge parity test). Pure fixture-corpus drift \u2014 no scope-extractor change; existing fixtures' captures byte-identical. fixture_count 265->267. #1995: + cpp-union-nested-tail-collision and cpp-anon-ns-tail-collision fixtures \u2014 pure fixture-corpus drift; fixture_count 270->272, fingerprint 538e8be->d63ded6. #1993: + cpp-cross-namespace-same-tail fixture \u2014 pure fixture-corpus drift; fixture_count 272->273, fingerprint d63ded6->6d6207ae. #2077 review follow-up: cpp-member-lattice adds cross-file, qualified-base, nested-template, inherited-using, this-receiver, and non-virtual-override regressions; fixture_count 274->275. Capture scaling remains linear (1.134 < 1.5). #1899: braced-init call arguments emit a conservative parameter-type capture; fixture_count 277, scaling remains linear (1.141 < 1.5).", + "_note": "#1975: + cpp-out-of-line-class fixture, fixture_count 263->265. #1990: + cpp-adl-ns-plus-hidden-friend-same-name fixture (ADL hidden-friend + namespace-callable merge parity test). Pure fixture-corpus drift — no scope-extractor change; existing fixtures' captures byte-identical. fixture_count 265->267. #1995: + cpp-union-nested-tail-collision and cpp-anon-ns-tail-collision fixtures — pure fixture-corpus drift; fixture_count 270->272, fingerprint 538e8be->d63ded6. #1993: + cpp-cross-namespace-same-tail fixture — pure fixture-corpus drift; fixture_count 272->273, fingerprint d63ded6->6d6207ae. #2077 review follow-up: cpp-member-lattice adds cross-file, qualified-base, nested-template, inherited-using, this-receiver, and non-virtual-override regressions; fixture_count 274->275. Capture scaling remains linear (1.134 < 1.5). #1899: braced-init call arguments emit a conservative parameter-type capture; fixture_count 277, scaling remains linear (1.141 < 1.5).", "_rebaselined_2522_review_fixes": "PR #2522 review fixes: outermost-chain passing modes; ->* ERROR-recovery role order; member-store visibility. Prior 57860dd2a8d4b06c6d2dd0d854c08b781faee3da8f2b6c42ba0c68a9f70e5ccb -> f29bc3f7b1622954d6f6b7647bc9cf6c7a2629ffcc0fe00ac7918e4925876b65; scaling ratio re-verified within budget.", - "_rebaselined_2522_prototype_value_cells": "Plain function/method prototypes no longer index as callable value cells (only pointer/parenthesized variable declarators do) \u2014 removes the spurious indirect-invoke facts that leaked phantom CALLS past two-phase suppression. Prior f29bc3f7b1622954d6f6b7647bc9cf6c7a2629ffcc0fe00ac7918e4925876b65 -> a70625bb0a9ef74e760d9d79cc5557485d0f0d3fb935e8a22a0c9556c65b5bb1; scaling re-verified within budget.", + "_rebaselined_2522_prototype_value_cells": "Plain function/method prototypes no longer index as callable value cells (only pointer/parenthesized variable declarators do) — removes the spurious indirect-invoke facts that leaked phantom CALLS past two-phase suppression. Prior f29bc3f7b1622954d6f6b7647bc9cf6c7a2629ffcc0fe00ac7918e4925876b65 -> a70625bb0a9ef74e760d9d79cc5557485d0f0d3fb935e8a22a0c9556c65b5bb1; scaling re-verified within budget.", "_rebaselined_receiver_chain_2747": "#2747: additionally adds the `cpp-receiver-chain-arrow` fixture, the behavioural proof for a `->` BASE receiver (`svc->getUser()->save()`) that the rollout fixed and that `cpp-chain-call/` could never catch because it uses the value `.` form. Prior a70625bb0a9ef74e760d9d79cc5557485d0f0d3fb935e8a22a0c9556c65b5bb1 -> 7e27aea46f3e17f33c41babbe0ddd982d1ab5920f143864763e0a1c6aef882a5.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 7e27aea46f3e17f33c41babbe0ddd982d1ab5920f143864763e0a1c6aef882a5 -> 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 7e27aea46f3e17f33c41babbe0ddd982d1ab5920f143864763e0a1c6aef882a5 -> 856d02f3f9d22cb973877211100aee8e052d4bc545922f78704b1a21ce49ddcc.", "capture_groups_small": 5021, "capture_groups_large": 16021, - "capture_groups_fp": 4601, - "fixture_count": 279, + "capture_groups_fp": 4826, + "fixture_count": 285, "_rebaselined_1432_member_call_callee_name": "#1432 (Zig): the shared callable-flow reader no longer names a callee by simple name for a MEMBER call (`@callable-flow.direct-callee-name` requires a direct designator: `f(x)`, `ns.f(x)`), and a member call is a field-stored-callable invoke only when a MEMBER store (`o.f = handler`) or a declared callable-typed field is visible - a same-named plain binding no longer gates it. CAPTURE-EMISSION CHANGE, not fixture growth (fixture_count unchanged). Only drift: `choice.select(1)` / `choice.select(1.5)` (cpp-deleted-overload/main.cpp) no longer mint an INDIRECT `@callable-flow.invoke` (callee-kind binding) plus its synthetic `@reference.call.free` - that invoke was gated only by the same-named free `select` binding while the site is a genuine method call already captured as `@reference.call.member`, so the free-call duplicate is gone. capture_groups_fp 4605 -> 4601 (-4: 2 invokes + 2 synthetic call.free). Prior bf3587674267be1759e7c45abef143c3b81fe8629cfd17da5f8af40e83cc39ec -> 3aaee42523f02718795ba348782d78ec1418f35eff2e1b602422b192544fed96.", - "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 9 existing read matches gain receiver chains; 9 synthetic operator names now use their written operator-token range rather than the translation-unit range. Group counts are unchanged. Fixture entries 279; changed entries 10; capture groups 4507 -> 4507. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." + "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 9 existing read matches gain receiver chains; 9 synthetic operator names now use their written operator-token range rather than the translation-unit range. Group counts are unchanged. Fixture entries 279; changed entries 10; capture groups 4507 -> 4507. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged.", + "_rebaselined_3498_review": "Qualified callable returns retain namespace spelling. Function-template definitions publish their own parameter list, including pointer-returning declarators. Only C++ capture fingerprint changes; all sixteen unchanged scaling budgets pass. Native boundaries cover alias chains, namespace/class collisions, overloaded prototypes and independent callable return owners." }, "csharp": { "_rebaselined": "#1956 synth-widening: + csharp-qualified-base fixture; the synth now walks record_declaration + struct_declaration base_lists and handles alias_qualified_name (matching the #1940 legacy leg), so record/struct heritage now emits. csharp-record-base gains a record inherits capture. (record->record SAME-namespace EXTENDS is a separate registry resolution gap, tracked as follow-up.) Linear (~1.00). (Earlier #1956: heritage-bearing scale source.) | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged. | #1924 F16: record primary-constructor base bindings now exclude constructor arguments; capture fingerprint changes, scaling remains linear. | #2036 review follow-up: csharp-record-base now exercises primary-constructor base dispatch end to end; +2 capture groups, scaling remains linear.", - "fingerprint": "af724813b5183ad9c98408a9c6944a44897b97d02e7f474ffa4ae637ca9ac1e3", + "fingerprint": "28a51b97c32bf95d85e5a322e443ab00cd490a1178269c2f6f9cfc4fb9776686", "scaling_budget": 1.5, "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior f31544530924748f9aa37d11cec570bc10c3ddf9d9b237e6df7a17623fd2bb3a -> 75cf380209fa7d1a8a3ec873be1a9424b4e5173be0b08234c2291e8521a9b3c1; scaling 1.061 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: C# method-group/delegate callable flow facts with invocation-result suppression. Prior 2bb5bc8c19cb8eb08c9590545ad8a1968a7152951f7e12746e2d7901d542fed9 -> f31544530924748f9aa37d11cec570bc10c3ddf9d9b237e6df7a17623fd2bb3a; scaling 1.115 < 1.5.", "_note": "#2046: F35 qualified-constructor captures now emit @reference.qualified-name + a simple-name @reference.name on `new Ns.Foo()`/`new A.B.Foo()`; namespace_declaration/file_scoped_namespace_declaration now emit @declaration.namespace name captures (feeding the non-destructive namespacePrefix sidecar for `new B.Foo()` same-tail disambiguation). + csharp-interface-only-base and csharp-namespace-qualified-ctor fixtures. Pure capture-additive + fixture-corpus drift; scaling stays linear (~1.11).", "_rebaselined_2563_instance_ownership": "#2563: csharp-using-static adds same-file ownership, local-function, overload, partial-class, and cross-namespace same-name coverage. Prior 75cf380209fa7d1a8a3ec873be1a9424b4e5173be0b08234c2291e8521a9b3c1 -> e05dc27456bde8175948586c9e7689033a378fa40e9ca4ce78cce41fbea0f2f8; scaling 1.058 < 1.5.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 05a85bae70cf9c94f42459c843cfc36e3e81c872e5dcc7d77bc42fbc390f4bfe -> 8a282254b93b3ef2ff34c2fdba819ebc95c53c4fcb09942cbad99f96d3687855.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 8a282254b93b3ef2ff34c2fdba819ebc95c53c4fcb09942cbad99f96d3687855 -> 476d98a7cc659951c315d63319c8077bbcf0e5f3ec12d32ed773992a1f3a2adc.", - "capture_groups_small": 4259, - "capture_groups_large": 13609, - "capture_groups_fp": 2657, - "fixture_count": 178, + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 05a85bae70cf9c94f42459c843cfc36e3e81c872e5dcc7d77bc42fbc390f4bfe -> 8a282254b93b3ef2ff34c2fdba819ebc95c53c4fcb09942cbad99f96d3687855.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 8a282254b93b3ef2ff34c2fdba819ebc95c53c4fcb09942cbad99f96d3687855 -> 476d98a7cc659951c315d63319c8077bbcf0e5f3ec12d32ed773992a1f3a2adc.", + "capture_groups_small": 4509, + "capture_groups_large": 14409, + "capture_groups_fp": 2841, + "fixture_count": 186, "_rebaselined_1432_member_call_callee_name": "#1432 (Zig): the shared callable-flow reader no longer names a callee by simple name for a MEMBER call (`@callable-flow.direct-callee-name` requires a direct designator: `f(x)`, `ns.f(x)`), and a member call is a field-stored-callable invoke only when a MEMBER store (`o.f = handler`) or a declared callable-typed field is visible - a same-named plain binding no longer gates it. CAPTURE-EMISSION CHANGE, not fixture growth (fixture_count unchanged). Only drift: `string.Join(\", \", args)` (csharp-variadic-resolution/Utils/Logger.cs) loses `direct-callee-name|Join`; the argument fact itself is unchanged, capture_groups_fp 2657 (unchanged). Prior 2930ef49fdce984a4c051409880bddfe8445e30e1c6bf802bd90a0a0f8f6b094 -> 9c4d2ca55707a03185ea45e554462e81e6d83c9f8d0ea3cd63db5c362ad1bfec.", - "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 89 constructor-parameter type bindings are added, 46 field declarations become addressable properties, and 3 existing member reads gain receiver-chain tags. Reversing exactly these three changes restores the complete main capture set. Fixture entries 178; changed entries 47; capture groups 2657 -> 2746. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." + "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 89 constructor-parameter type bindings are added, 46 field declarations become addressable properties, and 3 existing member reads gain receiver-chain tags. Reversing exactly these three changes restores the complete main capture set. Fixture entries 178; changed entries 47; capture groups 2657 -> 2746. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged.", + "_rebaselined_global_namespace_precedence": "C# global-namespace precedence: fixture growth only. The new csharp-global-namespace-precedence fixture adds 8 files and 94 capture groups; no existing entry changes (the C# capture golden gains only those 8 entries). Capture emission is unchanged. Fixture entries 178 -> 186; capture groups 2746 -> 2840. Prior af724813b5183ad9c98408a9c6944a44897b97d02e7f474ffa4ae637ca9ac1e3 -> 98b066eb5a5d6b5ece83e9fb61cff19cc7bc4b2538f7bddfcd1dc416d1ce4cb4; scaling 1.108 < 1.5.", + "_rebaselined_3498_payee_initializer": "Review follow-up initializes Voucher.Payee in the namespace-precedence fixture. Only this fixture input changes: one constructor capture is added (2840 -> 2841 groups), fixture_count stays186; only the C# fingerprint changes. Current measured synthetic counts4509/14409, scaling1.109 below unchanged1.5; all16 languages remain within budget." }, "rust": { "_lexical_ownership_3532": "#3532: lexical ownership captures and fixture updates; fixture identities are relative to lang-resolution so serialized scope IDs are independent of checkout location. Full capture content remains hashed; scaling_budget is unchanged.", - "fingerprint": "7d314a184cba1e5c47260d0a5018107146437f56a2bd183ae0670f0d77a3fbd2", + "fingerprint": "19045ed3d4ee9fcea36e949284b385f8d0a24e471cb05f77d8b35d8a1a8dd7fa", "scaling_budget": 1.5, - "_rebaselined_generic_instantiation_2912": "#2912: RUST_SCOPE_QUERY tags trait-impl heritage with the instantiation the impl was written with (`impl Validator for V`), so interface dispatch can prune implementors of an instantiation the receiver cannot hold. Additive capture text on existing impl matches \u2014 the same matches are minted, carrying one more field \u2014 so this is digest drift, not a capture-set change: capture_groups_fp (3556) and fixture_count (202) are both unchanged, which is the check that no match appeared or vanished. Prior 116a971fee0004f340477aff69fa110a1d92bd8ba882d7c926483c6b1e8ca2b9 -> e61653008ff2de506cfd47f905fa9eb22d82fbbfe94d2a1d8190c358211b57b7; scaling 1.018 < 1.5. Only rust and dart move; the other 13 languages are byte-identical.", - "_rebaselined_mod_node_identity_2745_review": "#2745 review: added rust-2742-mod-members, rust-2742-nested-mods and rust-2742-type-vs-module under lang-resolution for the container/owner-edge fix, nested inline modules, and the imported-type-vs-module precedence. emitRustScopeCaptures is unchanged \u2014 verified by removing ONLY those three fixture dirs and re-running, which reproduces the prior fingerprint exactly, so the shift is purely corpus growth (fixture_count 196 -> 202, capture_groups_fp 3432 -> 3556). Prior 90fda086a4e13aa069a5981f63ed58ab1c71f1ed3da5e1480a080e1992b0d3e5 -> 05acbaca48427e0d9e0793bcd0ce4057712d3716b5e7868189c12e05ef8dd300; scaling 1.022 local / 1.057 CI < 1.5. NOTE for the next fixture author: a new rust-* fixture drifts BOTH this bench baseline and the rust-captures-golden snapshot. Updating only the golden is how this reached CI red.", + "_rebaselined_generic_instantiation_2912": "#2912: RUST_SCOPE_QUERY tags trait-impl heritage with the instantiation the impl was written with (`impl Validator for V`), so interface dispatch can prune implementors of an instantiation the receiver cannot hold. Additive capture text on existing impl matches — the same matches are minted, carrying one more field — so this is digest drift, not a capture-set change: capture_groups_fp (3556) and fixture_count (202) are both unchanged, which is the check that no match appeared or vanished. Prior 116a971fee0004f340477aff69fa110a1d92bd8ba882d7c926483c6b1e8ca2b9 -> e61653008ff2de506cfd47f905fa9eb22d82fbbfe94d2a1d8190c358211b57b7; scaling 1.018 < 1.5. Only rust and dart move; the other 13 languages are byte-identical.", + "_rebaselined_mod_node_identity_2745_review": "#2745 review: added rust-2742-mod-members, rust-2742-nested-mods and rust-2742-type-vs-module under lang-resolution for the container/owner-edge fix, nested inline modules, and the imported-type-vs-module precedence. emitRustScopeCaptures is unchanged — verified by removing ONLY those three fixture dirs and re-running, which reproduces the prior fingerprint exactly, so the shift is purely corpus growth (fixture_count 196 -> 202, capture_groups_fp 3432 -> 3556). Prior 90fda086a4e13aa069a5981f63ed58ab1c71f1ed3da5e1480a080e1992b0d3e5 -> 05acbaca48427e0d9e0793bcd0ce4057712d3716b5e7868189c12e05ef8dd300; scaling 1.022 local / 1.057 CI < 1.5. NOTE for the next fixture author: a new rust-* fixture drifts BOTH this bench baseline and the rust-captures-golden snapshot. Updating only the golden is how this reached CI red.", "_rebaselined_dyn_trait_object_2604": "#2604: RUST_SCOPE_QUERY now captures function_signature_item (abstract trait methods, no body) as a scope + declaration, so a &dyn Trait receiver can dispatch a CALLS edge to the trait's own method. Additive capture shift across every bench fixture with a required trait method. Prior df369c5a5f8de7753fc8bab8b4108ef5081750974ea5085ba9a867675ac9eb29 -> f7742f65f14d7d6590df7f16303fc3cc9dc0c233cd80bf90c98b084933cd3846; scaling 1.033 < 1.5.", "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior 65e5bca66bb1ca117949409e8fb5c80ee69d6f1b5318908eaaecf08da0482e5c -> df369c5a5f8de7753fc8bab8b4108ef5081750974ea5085ba9a867675ac9eb29; scaling 1.065 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: Rust fn-value callable flow facts with invocation/constructor-result suppression. Prior ac610bbe97666bf285923479dd7b43a2fe4c5354aae8df1bcbafdc04fb220f82 -> 65e5bca66bb1ca117949409e8fb5c80ee69d6f1b5318908eaaecf08da0482e5c; scaling 1.024 < 1.5.", - "_rebaselined": "#1956 tri-review U1: rust-qualified-trait fixture (scoped + generic-of-scoped impl trait paths); bareTypeIdentifier now resolves scoped_type_identifier bases by their name: tail (additive, no existing-fixture drift); linear (~1.04). #1975: + rust-scoped-impl fixture (impl a::Inner / b::Inner inherent scoped impls) \u2014 legacy @definition.impl scoped arm + findEnclosingClassInfo inherent-impl scoped target; rust scope-extractor captures byte-identical. | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", - "_note": "PR #1934: F66/F68 let-binding pattern narrowing; F71 union (Struct-labeled, now materialized via legacy @definition.struct + resolvable); F72 macro FULLY WIRED \u2014 @declaration.macro/@reference.macro + MacroRegistry \u2192 USES edges to Macro nodes (never a same-named fn). + rust-macro / rust-union fixtures and merged with origin/main #1975 rust-scoped-impl; fingerprint re-baselined (scaling ~0.99, fixture_count 126). #1992: + rust-nested-tail-collision-generic and rust-generic-impl-same-method-name (F3) fixtures \u2014 pure fixture-corpus drift, no scope-extractor change; fixture_count 127->129, fingerprint 56ffc1c0->b00aea0f.", + "_rebaselined": "#1956 tri-review U1: rust-qualified-trait fixture (scoped + generic-of-scoped impl trait paths); bareTypeIdentifier now resolves scoped_type_identifier bases by their name: tail (additive, no existing-fixture drift); linear (~1.04). #1975: + rust-scoped-impl fixture (impl a::Inner / b::Inner inherent scoped impls) — legacy @definition.impl scoped arm + findEnclosingClassInfo inherent-impl scoped target; rust scope-extractor captures byte-identical. | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", + "_note": "PR #1934: F66/F68 let-binding pattern narrowing; F71 union (Struct-labeled, now materialized via legacy @definition.struct + resolvable); F72 macro FULLY WIRED — @declaration.macro/@reference.macro + MacroRegistry → USES edges to Macro nodes (never a same-named fn). + rust-macro / rust-union fixtures and merged with origin/main #1975 rust-scoped-impl; fingerprint re-baselined (scaling ~0.99, fixture_count 126). #1992: + rust-nested-tail-collision-generic and rust-generic-impl-same-method-name (F3) fixtures — pure fixture-corpus drift, no scope-extractor change; fixture_count 127->129, fingerprint 56ffc1c0->b00aea0f.", "_rebaselined_import_disambiguation_2514": "#2514: added rust-import-* and rust-dup-* fixtures under lang-resolution for the range-binding ambiguity latch + import-disambiguated resolution (for-loops / struct destructuring across explicit/aliased/glob use imports). emitRustScopeCaptures is unchanged; the corpus fingerprint shifts purely because the fixture set grew (130 -> 174). Prior f7742f65f14d7d6590df7f16303fc3cc9dc0c233cd80bf90c98b084933cd3846 -> 655aed01cf1b6b84fa0c64d48dfb2526ecb67f47d90f0a91edabacd269a212db; scaling 1.06 < 1.5.", - "_rebaselined_self_type_binding_2714": "#2714: a Rust `Self` type binding now records the enclosing impl's type instead of the literal 'Self'. `let fresh = Self { .. }` inside `impl User` binds `fresh: User`; recorded verbatim it bound `fresh: Self`, which resolves to nothing. The type-env channel already substituted this (type-extractors/rust.ts findEnclosingImplType); the scope-resolution channel did not, so the two disagreed. The gap was invisible while lookupCore Step 1 still walked the lexical chain for NAMED receivers \u2014 the impl scope binds the method by name, so fresh.validate() resolved by accident \u2014 and became a lost CALLS edge when #2714 stopped that walk. Only the rust fingerprint moves; the other 14 languages are byte-identical.", + "_rebaselined_self_type_binding_2714": "#2714: a Rust `Self` type binding now records the enclosing impl's type instead of the literal 'Self'. `let fresh = Self { .. }` inside `impl User` binds `fresh: User`; recorded verbatim it bound `fresh: Self`, which resolves to nothing. The type-env channel already substituted this (type-extractors/rust.ts findEnclosingImplType); the scope-resolution channel did not, so the two disagreed. The gap was invisible while lookupCore Step 1 still walked the lexical chain for NAMED receivers — the impl scope binds the method by name, so fresh.validate() resolved by accident — and became a lost CALLS edge when #2714 stopped that walk. Only the rust fingerprint moves; the other 14 languages are byte-identical.", "_rebaselined_module_tree_2730": "#2730 + #2741 review: RUST_SCOPE_QUERY captures mod_item as @declaration.namespace (a Rust module is an item, mirroring the C++ namespace_definition capture) and tags scoped call sites with @reference.qualified-name so the written path survives to resolution. Both are additive captures: every bench fixture holding a mod block or a Foo::bar() call gains groups, and the corpus also grew by the rust-2730-* fixtures added for the fix and its review (workspace-crates, type-qualified, gaps, samename-wrapper, crate-layout). Prior 7f1240b38457468f06b7931e0c2c578f218f922774d0dc7e2ee6ef3b08d4d689 -> 90fda086a4e13aa069a5981f63ed58ab1c71f1ed3da5e1480a080e1992b0d3e5; scaling 1.061 < 1.5; fixture_count 196. Only the rust fingerprint moves; the other 14 languages are byte-identical. The earlier revision of this note cited 655aed01... as the prior value, which was two rebaselines stale (it predates #2604 and #2714); the CI gate compares live fingerprints, not this prose, so nothing caught it.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 05acbaca48427e0d9e0793bcd0ce4057712d3716b5e7868189c12e05ef8dd300 -> 83812d82f0e2c3eb552f3246381ca3dd5ccd6783d63aba3325f1343e7772280c.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 83812d82f0e2c3eb552f3246381ca3dd5ccd6783d63aba3325f1343e7772280c -> 6174889b8c98e0af430fa54c268dc781989ca9a8172d690eebae37a95f77e809.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 05acbaca48427e0d9e0793bcd0ce4057712d3716b5e7868189c12e05ef8dd300 -> 83812d82f0e2c3eb552f3246381ca3dd5ccd6783d63aba3325f1343e7772280c.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 83812d82f0e2c3eb552f3246381ca3dd5ccd6783d63aba3325f1343e7772280c -> 6174889b8c98e0af430fa54c268dc781989ca9a8172d690eebae37a95f77e809.", "capture_groups_small": 5507, "capture_groups_large": 17607, - "capture_groups_fp": 3556, - "fixture_count": 202, - "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 28 existing field-read matches gain receiver-chain tags; removing only these added tags restores the complete main capture set. No group is added or removed. Fixture entries 204; changed entries 6; capture groups 3568 -> 3568. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." + "capture_groups_fp": 3699, + "fixture_count": 207, + "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 28 existing field-read matches gain receiver-chain tags; removing only these added tags restores the complete main capture set. No group is added or removed. Fixture entries 204; changed entries 6; capture groups 3568 -> 3568. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged.", + "_rebaselined_3498_qualified_factory": "Rust module-qualified factory fixture adds four files. Provider-qualified callee and return bindings retain the complete module path. All other language fingerprints equal merged main. Measured on the combined main merge; native boundary tests cover untyped and disk-sealed calls.", + "_rebaselined_3498_qualified_factory_review": "Review follow-up: fixture comment distinguishes module factories from type-qualified/untyped controls. Current measured Rust corpus: 207 files, 3699 capture groups, synthetic 5507/17607; fingerprint 19045ed3d4ee9fcea36e949284b385f8d0a24e471cb05f77d8b35d8a1a8dd7fa. Constructor inference retains Unicode/uppercase qualified candidates until lexical type ownership is available. Other 15 fingerprints unchanged; all 16 scaling ratios below unchanged 1.5 budgets (Rust 1.092)." }, "php": { "fingerprint": "310d2c1cddf3b36264f988a78486f5c287a1094f8539dd165e8b58a5258febd5", @@ -115,9 +125,9 @@ "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior df7b1565f9115d66b1ae32e4a408d651afb2521b14e5ca615f3be426c29af618 -> 4a688fa5a7016546f7f3c6d44de023608ae80c5b0e3670c16f6e61b3632608fd; scaling 1.078 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: PHP first-class callable and variable-invocation flow facts with invocation-result suppression. Prior 31c9e3f3cb7094a2bf9021cf9db859036e002f8b44605cd993b470fc600e97cb -> df7b1565f9115d66b1ae32e4a408d651afb2521b14e5ca615f3be426c29af618; scaling 1.074 < 1.5.", "_rebaselined": "#1956: heritage-bearing scale source (class extends Base + use trait); both forms gated at scale; linear (~1.04). | #2481/#2482: PHP imports carry a symbol-kind capture so function/constant imports resolve by declaring file; capture shape changes, scaling remains linear (~1.04).", - "_note": "PR #1931: F53 import multi-clause, F54 enum_case, F55 anonymous_class \u2014 fixture count 138\u2192140, fingerprint drift expected.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 4a688fa5a7016546f7f3c6d44de023608ae80c5b0e3670c16f6e61b3632608fd -> 3745662053c76b6ae0a84a29aad319626ed5ccb88f7b9376c2680d3dc6502e28.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 3745662053c76b6ae0a84a29aad319626ed5ccb88f7b9376c2680d3dc6502e28 -> b213a872342da2d866b04681dede988770e4d3dfdc0d6e9f62212ec5b59cdc2c.", + "_note": "PR #1931: F53 import multi-clause, F54 enum_case, F55 anonymous_class — fixture count 138→140, fingerprint drift expected.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 4a688fa5a7016546f7f3c6d44de023608ae80c5b0e3670c16f6e61b3632608fd -> 3745662053c76b6ae0a84a29aad319626ed5ccb88f7b9376c2680d3dc6502e28.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 3745662053c76b6ae0a84a29aad319626ed5ccb88f7b9376c2680d3dc6502e28 -> b213a872342da2d866b04681dede988770e4d3dfdc0d6e9f62212ec5b59cdc2c.", "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. The existing php-use-function-const/app/Config/constants.php fixture now captures its MAX_RETRIES declaration. Its one new declaration group is the entire delta. Fixture entries 143; changed entries 1; capture groups 2241 -> 2242. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." }, "ruby": { @@ -128,10 +138,10 @@ "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior cff273ae6cb7232c977d9241581834a2a2fa8bcf6369f7bd8f2471cd4419a6ef -> bf50ec6a53c8c91680dc6feac63a8956e78b1059249232dc25a0cfed25f31236; scaling 1.103 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: Ruby Method/Proc callable flow facts with invocation/constructor-result suppression. Prior b5ea93bb3d0469c3821a8c70f5d5991c6f326e41097c119ad691154301dcc753 -> cff273ae6cb7232c977d9241581834a2a2fa8bcf6369f7bd8f2471cd4419a6ef; scaling 1.086 < 1.5.", "_rebaselined": "#1956 synth-widening: + ruby-qualified-base fixture; synth now reduces a scope_resolution superclass (class C < Mod::Super) to its trailing constant (matching the #1940 legacy leg), at parity. Linear (~1.03). (Earlier #1956: heritage-bearing scale source.) | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", - "_note": "F62: + scope_resolution class/module declaration captures \u2014 fixture count 78\u219281, fingerprint drift expected. #1975: + ruby-tail-collision fixture (Foo::Bar vs Baz::Bar stay distinct nodes) \u2014 pure fixture-corpus drift, scope-extractor captures unchanged; 81\u219282. #1991: + ruby-nested-mixin-tail-collision fixture (85\u219286). Recomputed on the #942 merge (fixture-comment rewording shifts capture byte-positions, capture LOGIC unchanged): bf6b13a -> b5ea93bb.", + "_note": "F62: + scope_resolution class/module declaration captures — fixture count 78→81, fingerprint drift expected. #1975: + ruby-tail-collision fixture (Foo::Bar vs Baz::Bar stay distinct nodes) — pure fixture-corpus drift, scope-extractor captures unchanged; 81→82. #1991: + ruby-nested-mixin-tail-collision fixture (85→86). Recomputed on the #942 merge (fixture-comment rewording shifts capture byte-positions, capture LOGIC unchanged): bf6b13a -> b5ea93bb.", "_rebaselined_2522_review_fixes": "PR #2522 review fixes: bare identifiers are calls, not callable references (bareNamesAreCalls). Prior bf50ec6a53c8c91680dc6feac63a8956e78b1059249232dc25a0cfed25f31236 -> 070e4e11502442998ddf4048c2981cf1b2b735a87362ff854c5d14d71f98f4e2; scaling ratio re-verified within budget.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior fea3edf82f521995147874b7f6c5f9e2eb88efdebf6365668f3260e913f0b558 -> fc81941b0a921074fa80dc448284de9a23bd07358ddc84d4894797cc08c3fe83.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior fc81941b0a921074fa80dc448284de9a23bd07358ddc84d4894797cc08c3fe83 -> 1c8c9c4b54036fa24c2a81e39ea530e938645c856d369075e5f437da78218c57.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior fea3edf82f521995147874b7f6c5f9e2eb88efdebf6365668f3260e913f0b558 -> fc81941b0a921074fa80dc448284de9a23bd07358ddc84d4894797cc08c3fe83.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior fc81941b0a921074fa80dc448284de9a23bd07358ddc84d4894797cc08c3fe83 -> 1c8c9c4b54036fa24c2a81e39ea530e938645c856d369075e5f437da78218c57.", "_rebaselined_3354_callable_alternatives": "#3354 callable alternatives: a callable chosen by a value-selecting source now flows every branch it can yield (`a ?? b`, `a || b`, `a or b`, `c ? a : b`, statement `if`, elvis), and an operator branch (`x == f || g`) stays opaque instead of seeding a qualified name. Verified by running the BASE (merge-base 233ca2849) and HEAD emitters over the SAME HEAD fixture corpus: every added or removed match is an `@callable-flow.*` match on one of those sources, and the pre-existing corpus is byte-identical (all other languages: zero delta). The rest of the drift is corpus growth from this PR's regression fixture, which this bench globs. Corpus growth: ruby-callable-alternatives/app.rb (+1 file, +58 groups). Emitter delta: +5 / -0: seeds for single-statement `if` / `elsif` branches (run_then, run_else, run_sweep, run_a, run_b); the multi-statement branch contributes nothing. capture_groups_fp 1358 -> 1416, fixture_count 91 -> 92; synthetic counts unchanged; scaling 1.04 < 1.5. Prior 1c8c9c4b54036fa24c2a81e39ea530e938645c856d369075e5f437da78218c57 -> 45e65d9fa8a9e5e905ddb596b179b77c86ed13ab5139c6b17ccaaf7315dfe46a.", "capture_groups_small": 3011, "capture_groups_large": 9611, @@ -151,8 +161,8 @@ "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: Swift function-value callable flow facts with invocation-result suppression. Prior 180ac68e780bdf6f9089d53f51cbb9a66aed3e7774631cc3fcbaae5020213998 -> 5f923c6604d825d12b249f31c155b0f4d13a8379d532e5dde64a0f9b15cf4725; scaling 1.043 < 1.5.", "_rebaselined": "#1919 open-language coverage: new lang-resolution fixtures + intended capture additions (F5/F9 c-cpp, F26/F28/F29 dart, F47/F48/F49/F51/F52 kotlin, F75/F79 swift). Fingerprint-only drift; scaling_ratio ~1.0 (linear, no perf regression).", "_rebaselined_2522_review_fixes": "PR #2522 review fixes: assignment target:/result: fields join the shared fallback. Prior 7687ee2466e16020a12440a03fbda53e63aa05f94b4481f6133c09867a0d560d -> 115c5da807e36bb12fdeba28e44f2b6484ef322ff26c19fa0f191febaf774248; scaling ratio re-verified within budget.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 115c5da807e36bb12fdeba28e44f2b6484ef322ff26c19fa0f191febaf774248 -> a6fca5f052ae5ec635b56051e28a168c864a988b2221a3279ddd69807378ba0b.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior a6fca5f052ae5ec635b56051e28a168c864a988b2221a3279ddd69807378ba0b -> 2f04ae960123cf50138a49fabdc5a146c2963170cecf5755c552b23c9055a9e7.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 115c5da807e36bb12fdeba28e44f2b6484ef322ff26c19fa0f191febaf774248 -> a6fca5f052ae5ec635b56051e28a168c864a988b2221a3279ddd69807378ba0b.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior a6fca5f052ae5ec635b56051e28a168c864a988b2221a3279ddd69807378ba0b -> 2f04ae960123cf50138a49fabdc5a146c2963170cecf5755c552b23c9055a9e7.", "_rebaselined_inferred_field_receiver_2807": "#2807: optional property annotations (`var a: Outer?`) now emit a type binding. The prior pattern required the `user_type` to be a DIRECT child of the annotation, so an `optional_type` wrapper meant an optional field was never typed at all and its receiver could not resolve. ADDS @type-binding.annotation captures on the optional form only; no capture is removed. Prior 2f04ae960123cf50138a49fabdc5a146c2963170cecf5755c552b23c9055a9e7 -> adef9284feaecd39cb490aebce83876e15b9150c7a04b00a396feb78b7e1e0a9; scaling 1.023 < 1.5.", "_rebaselined_nested_constructor_3262": "#3262: the existing nested-constructor fixture now uses the qualified legal form `extension Outer.Container`, covering full extension-owner recovery. Fixture-only capture drift; no capture logic changed. Prior adef9284feaecd39cb490aebce83876e15b9150c7a04b00a396feb78b7e1e0a9 -> 3ac80b64776969effb75c8d32aa0bc38fc6a41c6c115a33829c502559fa404f9; scaling 1.025 < 1.5.", "_rebaselined_3309_call_result_assignment": "#3309: the Swift protocol-extension regression fixture adds one file with an untyped local initialized from a helper call, plus a compound-field receiver call. The capture query is unchanged; this is fixture-corpus growth only. capture_groups_fp 1235 -> 1272 and fixture_count 62 -> 64; synthetic scale counts remain 5012/16012. Prior adef9284feaecd39cb490aebce83876e15b9150c7a04b00a396feb78b7e1e0a9 -> 4d32535d454cd79086f0fcaec3b75de855c1314e73630321460e569f19aa484f; measured scaling 1.020 < 1.5.", @@ -166,7 +176,7 @@ "fingerprint": "1c5b892a136318eddee3435225284896c2effb52dd51ca5717c92887ae4a39a3", "scaling_budget": 1.5, "_rebaselined_2963_package_imports": "#3369 package-import fixtures: dart-package-imports adds six .dart files. CORPUS GROWTH ONLY, NOT A CAPTURE CHANGE: parking that directory restores 795290a9524ee0dc38af635536e9744c401ec13828ec77822d39e59e1cd6e649 byte-for-byte. The six files contribute 33 capture groups (862 -> 895) and fixture_count 37 -> 43. Synthetic scale counts stay 5011/16011. Local scaling 1.091 < 1.5. Prior 795290a9524ee0dc38af635536e9744c401ec13828ec77822d39e59e1cd6e649 -> f4edcfedb6e97def5ffbb9d3227fce2549e5c6c6cc876a05bc3b68a46ed30c24.", - "_rebaselined_generic_instantiation_2912": "#2912: the Dart heritage marker carries a fourth field \u2014 the type arguments the clause was written with (`implements Validator`) \u2014 so interface dispatch can prune implementors of a mismatched instantiation. Additive marker text on existing heritage matches rather than a new match, so this is digest drift only; a marker from a pre-#2912 cache simply has no fourth field and reads as unknown. Prior ba93c90dcd341259e8e088816bc8c76ad27882419f665e35c056dc22fa54cf73 -> 3a8ddabbeb1cba47a4757451d4f79d726ca230fd15e860772b11526fbb1c6687; scaling 1.027 < 1.5.", + "_rebaselined_generic_instantiation_2912": "#2912: the Dart heritage marker carries a fourth field — the type arguments the clause was written with (`implements Validator`) — so interface dispatch can prune implementors of a mismatched instantiation. Additive marker text on existing heritage matches rather than a new match, so this is digest drift only; a marker from a pre-#2912 cache simply has no fourth field and reads as unknown. Prior ba93c90dcd341259e8e088816bc8c76ad27882419f665e35c056dc22fa54cf73 -> 3a8ddabbeb1cba47a4757451d4f79d726ca230fd15e860772b11526fbb1c6687; scaling 1.027 < 1.5.", "_rebaselined_2538": "#2538: Dart extension type headers are preprocessed into normal extension declarations before scope capture, so extension type symbols and their methods are now emitted. Intentional Dart-only capture fingerprint drift; CI measured scaling 1.042 < 1.5.", "_rebaselined_2538_implements": "#2538 tri-review follow-up: Dart extension type implements clauses now emit heritage markers and fixture coverage asserts IMPLEMENTS edges, including multi-arg generic interfaces. Prior committed baseline 66a46d5ff09f3d11b2771db0f48596fe7057e95c5bc8f56241fdb911137298c3 -> ba93c90dcd341259e8e088816bc8c76ad27882419f665e35c056dc22fa54cf73; scaling 0.945 < 1.5.", "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior 29ce2bfe70b246b1c9d5e99c0ec11e850c22e9672737592207242b7f4cc824b8 -> 66a46d5ff09f3d11b2771db0f48596fe7057e95c5bc8f56241fdb911137298c3; scaling 1.054 < 1.5.", @@ -187,7 +197,7 @@ "_rebaselined_2900_record_heritage": "#2900 review follow-up: the Java scale unit now includes a record implementing Marker, so the record-declaration @reference.inherits path is fingerprinted and exercised at scale. Prior b29e263524f55151dcb7cfc4c929d3d1d7bb360355cee4e832158f927857f663 -> 36d689c58526c4482fbd701d1d9ca156623a3970734ead145717858712271ab5; scaling 1.042 < 1.5.", "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata; same-name lexical regions use an O(ancestor-depth) ID-set lookup. Prior d5c59d7dc9e206637515d5aea1163f7c1cdd76410c38c5fe6143d13d19677d6a -> 004a3592998dca1193bd1429a8284513725de7764f2a3eceedaaa984cfd763b4; scaling 0.992 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: Java method-reference/SAM callable flow facts with invocation-result suppression. Prior 062d754764aaa8a6772fb90875c710502a63e3e7a300e633942381ed914faada -> d5c59d7dc9e206637515d5aea1163f7c1cdd76410c38c5fe6143d13d19677d6a; scaling 1.074 < 1.5.", - "_rebaselined": "#2357 (supersedes #2353): + java-cast-receiver, java-this-field-chain, java-this-dispatch fixtures (cast-wrapped receivers, this.field chains incl. initializer contexts, bare-this dispatch pinning). Drift is purely fixture-additive: with the three new dirs parked, the fingerprint reproduces the prior baseline byte-identically \u2014 no emit/capture change. #1956 synth-widening: + java-iface-extends fixture; synthesizeJavaInheritanceReferences now ALSO walks interface_declaration extends_interfaces (interface IA extends IB, IC), matching the #1940 legacy leg. (Earlier U2+review: java-qualified-base fixture covers 2- AND 3-segment qualified bases guarding the legacy end-anchor; synth tail-resolves scoped bases.) Linear (~1.03). (Earliest: java added to bench, exposed+fixed the O(n^2) findNodeAtRange root-walk; 3.09 -> ~0.99.) | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", + "_rebaselined": "#2357 (supersedes #2353): + java-cast-receiver, java-this-field-chain, java-this-dispatch fixtures (cast-wrapped receivers, this.field chains incl. initializer contexts, bare-this dispatch pinning). Drift is purely fixture-additive: with the three new dirs parked, the fingerprint reproduces the prior baseline byte-identically — no emit/capture change. #1956 synth-widening: + java-iface-extends fixture; synthesizeJavaInheritanceReferences now ALSO walks interface_declaration extends_interfaces (interface IA extends IB, IC), matching the #1940 legacy leg. (Earlier U2+review: java-qualified-base fixture covers 2- AND 3-segment qualified bases guarding the legacy end-anchor; synth tail-resolves scoped bases.) Linear (~1.03). (Earliest: java added to bench, exposed+fixed the O(n^2) findNodeAtRange root-walk; 3.09 -> ~0.99.) | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", "_note": "#1928 / #2045: F35 adds qualified + qualified-generic constructor query captures (`new pkg.Foo()`, `new a.b.Foo()`, `new pkg.Box()`); F38 synthesizes `@reference.call.constructor` on `super(...)`/`this(...)` explicit_constructor_invocation nodes; F41 generic-aware stripQualifier in interpret (type-binding normalization). + java-qualified-constructor and java-explicit-constructor fixtures. Pure capture-additive + fixture-corpus drift; scaling stays linear (~1.06).", "_rebaselined_2522_review_fixes": "PR #2522 review fixes: get/test dropped from callableProtocolMethods. Prior 004a3592998dca1193bd1429a8284513725de7764f2a3eceedaaa984cfd763b4 -> f3b4f4b6610e07c3ac90deb1c53d3572b6ad55a36e5d7134984876d30031ff67; scaling ratio re-verified within budget.", "_rebaselined_2550_instance_model": "PR #2549 (#2550): anonymous class bodies emit synthesized @declaration.class/@declaration.name (Worker$N), an @reference.inherits to the constructed type, and receiver @type-binding.* captures; six new java-* fixtures joined the corpus. Prior f3b4f4b6610e07c3ac90deb1c53d3572b6ad55a36e5d7134984876d30031ff67 -> d79c3b92acfc866094981499b977388ca14f90839bca0c040342ab1cec00aa90; scaling 1.058 < 1.5.", @@ -195,8 +205,8 @@ "_rebaselined_2564_record_capture": "PR for #2564: JAVA_QUERIES gained a (record_declaration name: (identifier) @name) @definition.record capture, previously entirely missing (record_declaration had no structure-phase capture at all, unlike class/interface/enum) - a record's methods existed as ownerless Method nodes with no HAS_METHOD edge. Two new java-* fixtures (java-record-methods, java-new-expr-chain-call) joined the corpus. Prior 975b68aaac6d06094260fb0c67f9b1bc03692ba7220669d192aca9dccd5fc0ca -> 85fc7af9c3c1bceac76cb4f27214410b04967682a2eaa7e468e26efd1f4e2537; scaling 1.059 < 1.5.", "_rebaselined_2561_enum_constant_receiver": "PR for #2561: synthesizeJavaAnonymousClassDeclarations now emits a class-scope @type-binding.annotation/name/type per enum constant (constant simple name -> its E$N synthesized class when bodied, else the host enum) so E.CONST.method() resolves through the existing compound-receiver chain walk. Two drivers of the drift, both in the java-enum-constant-body fixture (this bench's corpus IS test/fixtures/lang-resolution): (1) one extra type-binding match per enum_constant from the capture change; (2) review follow-up added a body-less Plain.java enum + EnumConst.dispatchToConstant/dispatchInherited methods (bodied-override, inherited-via-MRO, and body-less dispatch call sites). The review's fail-safe hardening (bodied constant binds ONLY to E$N, never the host enum, when name synthesis fails on a malformed tree) is output-neutral on this well-formed corpus (verified: fingerprint identical with and without it). Prior 85fc7af9c3c1bceac76cb4f27214410b04967682a2eaa7e468e26efd1f4e2537 -> d04298a91beec76d0fa7099b3d71265723be60c1df688969aa954f135dd49686; scaling < 1.5.", "_rebaselined_2562_local_classes": "#2562: Java block-local classes, enums, records, and interfaces use source-type-relative JLS 13.1 Host$NLocal identities with javac-compatible per-(host, simple-name) numbering; anonymous numbering remains separate. Lexical aliases begin at each declaration and end with its immediate block. Expanded java-local-class-naming fixtures cover declaration order, disjoint blocks, initializers, lambdas, local type kinds, and recursive local/member/anonymous host chains. Prior d04298a91beec76d0fa7099b3d71265723be60c1df688969aa954f135dd49686 -> 6dd5913a58400a191ff54abf9b852b03d5add657d16c11e60a7c4608ba186197; scaling 1.204 < 1.5.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 6dd5913a58400a191ff54abf9b852b03d5add657d16c11e60a7c4608ba186197 -> 310adbc2e0827b5ac749acaa981cd12d256fc5b7cbc5592c5bee219e92abf9ee.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 310adbc2e0827b5ac749acaa981cd12d256fc5b7cbc5592c5bee219e92abf9ee -> a9943355e945e03ddb87c800f4cc1f62b3d04feefb3ec64c258d8e0bb3b3fcd9.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 6dd5913a58400a191ff54abf9b852b03d5add657d16c11e60a7c4608ba186197 -> 310adbc2e0827b5ac749acaa981cd12d256fc5b7cbc5592c5bee219e92abf9ee.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 310adbc2e0827b5ac749acaa981cd12d256fc5b7cbc5592c5bee219e92abf9ee -> a9943355e945e03ddb87c800f4cc1f62b3d04feefb3ec64c258d8e0bb3b3fcd9.", "capture_groups_small": 6255, "capture_groups_large": 20005, "capture_groups_fp": 3586, @@ -210,8 +220,8 @@ "_rebaselined_2935_synthetic_declarations": "PR #2935 review follow-up: the local-type stress corpus includes synthesized anonymous declarations, which now carry the presence-only @declaration.is-synthetic sidecar. DIGEST DRIFT ONLY, NOT A CAPTURE-SET CHANGE. Prior 8c50bbc83dff4f7f5abd06078aa6abc6b64af05fddb17ee826b5f3df3d346633 -> 560734cd053fb4f4b23aa04bc7870c22089a8deedb0217fa9c1b4db689e02a97; CI scaling 1.002 < 1.5.", "_rebaselined_2917_record_component_accessors": "#2917: the focused local-type fixture corpus contains local records, so their implicit component accessors add the same bounded scope/declaration captures as the general Java corpus. No local-type naming logic changed. Prior 8c50bbc83dff4f7f5abd06078aa6abc6b64af05fddb17ee826b5f3df3d346633 -> 3e22f368a4ee139be7cb91ff4fb77ddadf60c55efe8d66955ec81f366a46e460; scaling 1.032 < 1.5, capture_groups_fp 680. Re-measured on top of #2935's is-synthetic sidecar after merging origin/main: 560734cd053fb4f4b23aa04bc7870c22089a8deedb0217fa9c1b4db689e02a97 -> bdde823fa725e636e257940efb4c8655aa23124c1727cbaa8856d1ad8f71729e; scaling 0.997 < 1.5, capture_groups_fp 680.", "_added": "#2562 performance follow-up: co-scales same-host, same-name local classes and anonymous classes to gate JLS binary-name ordinal allocation. Precomputed per-sequence ordinals reduce the focused 100->800 workload from 176->6655ms to 141->752ms; normalized 250->800 scaling is 1.054.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior a9ad88de21ca6747a923260dbdf677fb74a004abbf9d57781f745e3a9027530b -> 3ca67847ea2b9a71b0a41e09f943767e5a2d3a113d3e203499ee364e37f40236.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 3ca67847ea2b9a71b0a41e09f943767e5a2d3a113d3e203499ee364e37f40236 -> 8c50bbc83dff4f7f5abd06078aa6abc6b64af05fddb17ee826b5f3df3d346633.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior a9ad88de21ca6747a923260dbdf677fb74a004abbf9d57781f745e3a9027530b -> 3ca67847ea2b9a71b0a41e09f943767e5a2d3a113d3e203499ee364e37f40236.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 3ca67847ea2b9a71b0a41e09f943767e5a2d3a113d3e203499ee364e37f40236 -> 8c50bbc83dff4f7f5abd06078aa6abc6b64af05fddb17ee826b5f3df3d346633.", "capture_groups_fp": 680, "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 2 constructor-parameter type bindings are added and 38 duplicate qualified free-call matches are removed. Every removed free-call match retains a member-call match with the identical call anchor and name capture. Fixture entries 6; changed entries 6; capture groups 680 -> 644. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." }, @@ -222,26 +232,26 @@ "_rebaselined_3446_mcp_tools_fixture": "#3446 adds typescript-mcp-tools/src/{handlers,server,tools}.ts: corpus growth only, with fixture_count 171 -> 174 and capture_groups_fp 2753 -> 2894. Excluding only that fixture directory restores the prior fingerprint 77c9b4ea654123a64972db8348190ec250b669472b150db65ea8c7f20b355467 exactly. The scope emitter, synthetic capture counts (4503/14403), scaling budget, and other language baselines are unchanged.", "_rebaselined_3190": "Capture matches now retain explicit ESM export/private evidence, including synthesized default HOCs; CommonJS surfaces remain undecided. Capture group counts unchanged. Scaling budget unchanged.", "scaling_budget": 1.5, - "_rebaselined_2934_import_type_only": "#2934: `import-decomposer.ts` attaches a presence-only `@import.type-only` synthetic capture to specifiers `tsc` erases, so `check --cycles` can stop counting type-only edges as initialization cycles. DIGEST DRIFT ONLY, NOT A CAPTURE-SET CHANGE \u2014 the tag is added to import matches that already existed, never a new match, the same shape as the #2747 receiver-chain rebaseline. Every count is unchanged: capture_groups_fp 2414, fixture_count 155, capture_groups_small/large 4503/14403 (those measure the SYNTHETIC scaling source, which has no imports at all). The fingerprint moves because `canonicalizeMatch` in measure.mjs hashes every TAG on every match, synthetics included, so one extra presence-only tag on an existing match rewrites that match's canonical string. Attribution is exact, not inferred: neutralizing ONLY the `m['@import.type-only'] = \u2026` assignment in import-decomposer.ts and re-running returns the fingerprint to c2fbf8a89e5686dd\u2026 byte-for-byte, so nothing else in the TypeScript capture stream moved. All 14 other languages report ok. Scaling 0.997 < 1.5. NOTE ON THE CONTROL: javascript did not move (2026993b\u2026, 43 fixtures), but it is a WEAK control here \u2014 `import type` is TypeScript-only syntax, so a JS corpus cannot express the construct and could not have drifted either way. It evidences no collateral damage, not the correctness of the TS change; the exact-attribution check above is what does that. Prior c2fbf8a89e5686dd1ff3659b20d41d8b05ebcc9790356e3653ee0c8ca5d365c8 -> f719163eb03a447c9e40ca316a905dd76cee82192a75a403df478ebbdc13e98f.", + "_rebaselined_2934_import_type_only": "#2934: `import-decomposer.ts` attaches a presence-only `@import.type-only` synthetic capture to specifiers `tsc` erases, so `check --cycles` can stop counting type-only edges as initialization cycles. DIGEST DRIFT ONLY, NOT A CAPTURE-SET CHANGE — the tag is added to import matches that already existed, never a new match, the same shape as the #2747 receiver-chain rebaseline. Every count is unchanged: capture_groups_fp 2414, fixture_count 155, capture_groups_small/large 4503/14403 (those measure the SYNTHETIC scaling source, which has no imports at all). The fingerprint moves because `canonicalizeMatch` in measure.mjs hashes every TAG on every match, synthetics included, so one extra presence-only tag on an existing match rewrites that match's canonical string. Attribution is exact, not inferred: neutralizing ONLY the `m['@import.type-only'] = …` assignment in import-decomposer.ts and re-running returns the fingerprint to c2fbf8a89e5686dd… byte-for-byte, so nothing else in the TypeScript capture stream moved. All 14 other languages report ok. Scaling 0.997 < 1.5. NOTE ON THE CONTROL: javascript did not move (2026993b…, 43 fixtures), but it is a WEAK control here — `import type` is TypeScript-only syntax, so a JS corpus cannot express the construct and could not have drifted either way. It evidences no collateral damage, not the correctness of the TS change; the exact-attribution check above is what does that. Prior c2fbf8a89e5686dd1ff3659b20d41d8b05ebcc9790356e3653ee0c8ca5d365c8 -> f719163eb03a447c9e40ca316a905dd76cee82192a75a403df478ebbdc13e98f.", "_rebaselined_callable_flow_2522_review": "PR #2522 review hardening: callable operands retain expression/qualified identity and formals retain signature metadata. Prior 27f937bfb47d4bded316ea3c785ff659c8cd88a5761d928f113477a08c802c78 -> e05446620c5b80b7aae291cfdf32f693580fada2ae687124769b04a0c03bfe63; scaling 0.983 < 1.5.", "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: lexical callable bindings, direct-callee argument metadata, and invocation-result suppression. Prior db5933cc6760234ed7d495123410feba6de243646d583f20d43032b9459f81fd -> 27f937bfb47d4bded316ea3c785ff659c8cd88a5761d928f113477a08c802c78; scaling 0.975 < 1.5.", "_rebaselined_callable_flow": "Callable assignment/copy/formal/argument/invoke facts (also consumed by Vue script blocks). Prior 25de86fd3377132c4e35d3d98f4f94a58e0cfeb7c22948a8ea3be4e793be74fd -> db5933cc6760234ed7d495123410feba6de243646d583f20d43032b9459f81fd; measured scaling ratio 0.951 < 1.5.", - "_rebaselined": "#1962: F44 (class scope@), F85 (enum member declarations), F87 (optional_parameter type annotations) add new captures \u2014 fingerprint drift expected.", - "_note": "#1968: F44, F85, F87 \u2014 fingerprint drift expected.", + "_rebaselined": "#1962: F44 (class scope@), F85 (enum member declarations), F87 (optional_parameter type annotations) add new captures — fingerprint drift expected.", + "_note": "#1968: F44, F85, F87 — fingerprint drift expected.", "_rebaselined_2522": "#2522 intentional @reference.value-ref/property-key capture additions. GitHub Actions run 29553361660 job 87800394279: prior 3f44a4a6892698df2d145c8ff2812c3b318807648983c88aca28fbd694f172f9 -> 25de86fd3377132c4e35d3d98f4f94a58e0cfeb7c22948a8ea3be4e793be74fd; scaling ratio 0.987 < 1.5.", "_rebaselined_2550_instance_model": "PR #2549 (#2545/#2551): object literals emit @scope.object (was unscoped, then @scope.block during development). Prior e05446620c5b80b7aae291cfdf32f693580fada2ae687124769b04a0c03bfe63 -> 3280b13d3f9378ab23eee31c2edc779b5a9ae1e7bb510c23a24855b44406d2f4; scaling 0.981 < 1.5.", - "_rebaselined_receiver_owner_2701": "#2701: every non-arrow function form now carries a `@receiver-owner.this` marker on the same node as `@scope.function`, so a scope that BINDS its own `this` can stop the receiver walk (`Scope.ownsReceivers`). Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus against 1d3088173f6f93827641b476d614d5d15cd4f3ea: the ONLY delta is @receiver-owner.this (typescript +143, javascript +32) \u2014 every other capture count is byte-identical, so no existing capture moved. Prior 3280b13d3f9378ab23eee31c2edc779b5a9ae1e7bb510c23a24855b44406d2f4 -> 281e95484203b481094729ca249ef0423c41273eac35e424cdfd032a0dac7699.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior cad25be9f81d6e021ebae8dcb166bc0af3a1ba8021f1506f6ca93fd4c2649000 -> 9e112415f1169f08576826c12ea1d137d1994e34b44c45986c9ffee83b8b4edc.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 9e112415f1169f08576826c12ea1d137d1994e34b44c45986c9ffee83b8b4edc -> cdefe88d3c275f31953216c676ef32c7bf5727d56b9c3840b81ee6bf85749dff.", - "_rebaselined_inferred_field_receiver_2807": "#2807: inference-typed class fields now emit a type binding \u2014 `public_field_definition` with a `new_expression` value, and `this. = new ...` carrying a @type-binding.this-field marker. ADDS @type-binding.constructor captures only; no capture is removed, and the annotated form is unchanged because annotation outranks constructor-inferred in typeBindingStrength. Prior cdefe88d3c275f31953216c676ef32c7bf5727d56b9c3840b81ee6bf85749dff -> 248b56f0d7a0a6fc7a949dc7afb8611e135ed642bccc2631b96ebb9d686bb965; scaling 0.994 < 1.5.", - "_rebaselined_ts_heritage_2842": "#2842 review: TypeScript heritage capture now emits `@reference.inherits` for `interface_declaration` (bases on `extends_type_clause`) and `abstract_class_declaration` (bases on `class_heritage`), which were both silently skipped \u2014 so `interface B extends A` and `abstract class X implements I` produced no edge and every interface-dispatch walk dead-ended on a bodiless declaration. Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus (145 files) with and without the change: the ONLY deltas are @reference.inherits 17 -> 20 (+3) and its paired @reference.name 245 -> 248 (+3), emitted together by emitTsInheritanceBase. Every other capture count is byte-identical, so no existing capture moved. The +3 is the three `interface X extends BasePayload` declarations in typescript-generic-calls/src/{auth,admin,guest}.ts. javascript is unchanged (no interfaces in the language). Prior 248b56f0d7a0a6fc7a949dc7afb8611e135ed642bccc2631b96ebb9d686bb965 -> 7a960908031331360ce582f5b55b7681e1cd7f8a2eabfd73c00982cb17f2a949.", + "_rebaselined_receiver_owner_2701": "#2701: every non-arrow function form now carries a `@receiver-owner.this` marker on the same node as `@scope.function`, so a scope that BINDS its own `this` can stop the receiver walk (`Scope.ownsReceivers`). Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus against 1d3088173f6f93827641b476d614d5d15cd4f3ea: the ONLY delta is @receiver-owner.this (typescript +143, javascript +32) — every other capture count is byte-identical, so no existing capture moved. Prior 3280b13d3f9378ab23eee31c2edc779b5a9ae1e7bb510c23a24855b44406d2f4 -> 281e95484203b481094729ca249ef0423c41273eac35e424cdfd032a0dac7699.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior cad25be9f81d6e021ebae8dcb166bc0af3a1ba8021f1506f6ca93fd4c2649000 -> 9e112415f1169f08576826c12ea1d137d1994e34b44c45986c9ffee83b8b4edc.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 9e112415f1169f08576826c12ea1d137d1994e34b44c45986c9ffee83b8b4edc -> cdefe88d3c275f31953216c676ef32c7bf5727d56b9c3840b81ee6bf85749dff.", + "_rebaselined_inferred_field_receiver_2807": "#2807: inference-typed class fields now emit a type binding — `public_field_definition` with a `new_expression` value, and `this. = new ...` carrying a @type-binding.this-field marker. ADDS @type-binding.constructor captures only; no capture is removed, and the annotated form is unchanged because annotation outranks constructor-inferred in typeBindingStrength. Prior cdefe88d3c275f31953216c676ef32c7bf5727d56b9c3840b81ee6bf85749dff -> 248b56f0d7a0a6fc7a949dc7afb8611e135ed642bccc2631b96ebb9d686bb965; scaling 0.994 < 1.5.", + "_rebaselined_ts_heritage_2842": "#2842 review: TypeScript heritage capture now emits `@reference.inherits` for `interface_declaration` (bases on `extends_type_clause`) and `abstract_class_declaration` (bases on `class_heritage`), which were both silently skipped — so `interface B extends A` and `abstract class X implements I` produced no edge and every interface-dispatch walk dead-ended on a bodiless declaration. Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus (145 files) with and without the change: the ONLY deltas are @reference.inherits 17 -> 20 (+3) and its paired @reference.name 245 -> 248 (+3), emitted together by emitTsInheritanceBase. Every other capture count is byte-identical, so no existing capture moved. The +3 is the three `interface X extends BasePayload` declarations in typescript-generic-calls/src/{auth,admin,guest}.ts. javascript is unchanged (no interfaces in the language). Prior 248b56f0d7a0a6fc7a949dc7afb8611e135ed642bccc2631b96ebb9d686bb965 -> 7a960908031331360ce582f5b55b7681e1cd7f8a2eabfd73c00982cb17f2a949.", "capture_groups_small": 4503, "capture_groups_large": 14403, "capture_groups_fp": 2465, "fixture_count": 167, - "_rebaselined_blind_spots_2856": "#2856 blind-spots series: the JS/TS SCOPE queries gained capture rules, so fingerprint drift is expected and additive. Verified before re-baselining by diffing the capture-name sets in both scope queries against origin/main: TypeScript gained exactly @reference.read.identifier (A2 bare-identifier reads in value positions) and @reference.type (R2-2 type references, so a declared contract stops reporting incoming:{}); JavaScript gained exactly @reference.read.identifier, @reference.read.destructured (R2-1c) and @reference.write.property-key (R2-1b record-construction writes). NOTHING was removed on either side \u2014 the delta is a pure superset, which is the check that no existing capture moved. capture_groups_small/large are unchanged (4503/14403) because those measure the SYNTHETIC scaling source, which this branch does not touch; only the fixture-corpus count moves. capture_groups_fp 2097 -> 2338 and fixture_count 146 -> 151 from 21 new lang-resolution fixtures. Scaling stayed linear and inside budget: typescript 1.116 < 1.5, javascript 1.010 < 1.5. Prior typescript ed92588e0fc7b28b3a0174339ac378b4dd85965fe007db1208dea97a65ce0571 -> f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7; prior javascript 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594 -> 2026993b81b873839dd2ef8797d9c14d9c48516b2b57b05ac17d8d43f2f4eba3.", - "_rebaselined_type_parameter_shadowing_w2_8": "W2-8: `@declaration.type-parameters` is now captured on generic FUNCTIONS, generator functions and type ALIASES, not only on class/interface declarations. NO NEW CAPTURE NAME \u2014 verified by diffing the capture-name sets against the wave-1 branch, which returns empty; the tag already existed and simply fires on more declarations. That is the whole delta: capture_groups_fp 2338 -> 2371 (+33 occurrences of an existing tag) and fixture_count 151 -> 152 (one new fixture, typescript-type-parameters). capture_groups_small/large unchanged at 4503/14403, since those measure the synthetic scaling source this does not touch. Scaling 1.06 < 1.5. JavaScript is untouched \u2014 it has no type parameters \u2014 and its fingerprint does not move, which is the check that this is the TS declaration rules and not something broader. Prior f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7 -> 62c7f1bfbe568eed927fb78f00061ed5e49d12511fd8260648b876df386f3b4c.", - "_rebaselined_2899_review_type_parameter_scope_fixtures": "PR #2899 review follow-up: FIXTURE-CORPUS GROWTH ONLY \u2014 no query rule changed and no capture name was added or removed. `typescript/query.ts` is byte-identical to the previous baseline; the type-parameter shadowing defect was fixed on the RESOLUTION side (`walkers.ts` gains a `declarationOpenedScope` gate so a declaration's `typeParameters` bind only inside the scope that declaration opened, and the `USES` guard moved from `graph-bridge/references-to-edges.ts` to `resolve-references.ts` where the spelled `site.name` is in hand). The fingerprint moves because measure.mjs fingerprints the whole `lang-resolution/typescript-*` fixture corpus and the regression tests add three files to `typescript-type-parameters/src/` (values.ts, aliased.ts, namespaced.ts) plus two scope-less generic aliases in shapes.ts. Per-file accounting sums exactly to the delta: shapes.ts 33->35 (+2), values.ts +11, aliased.ts +10, namespaced.ts +20 = +43. capture_groups_fp 2371 -> 2414; fixture_count 152 -> 155. capture_groups_small/large unchanged at 4503/14403 (they measure the SYNTHETIC scaling source, untouched). JAVASCRIPT IS THE CONTROL AND DID NOT MOVE (fingerprint 2026993b..., 43 fixtures) \u2014 which is the check that this is corpus growth and not a capture regression; all 14 other languages report `ok`. Scaling 0.976 < 1.5. Prior 62c7f1bfbe568eed927fb78f00061ed5e49d12511fd8260648b876df386f3b4c -> c2fbf8a89e5686dd1ff3659b20d41d8b05ebcc9790356e3653ee0c8ca5d365c8.", + "_rebaselined_blind_spots_2856": "#2856 blind-spots series: the JS/TS SCOPE queries gained capture rules, so fingerprint drift is expected and additive. Verified before re-baselining by diffing the capture-name sets in both scope queries against origin/main: TypeScript gained exactly @reference.read.identifier (A2 bare-identifier reads in value positions) and @reference.type (R2-2 type references, so a declared contract stops reporting incoming:{}); JavaScript gained exactly @reference.read.identifier, @reference.read.destructured (R2-1c) and @reference.write.property-key (R2-1b record-construction writes). NOTHING was removed on either side — the delta is a pure superset, which is the check that no existing capture moved. capture_groups_small/large are unchanged (4503/14403) because those measure the SYNTHETIC scaling source, which this branch does not touch; only the fixture-corpus count moves. capture_groups_fp 2097 -> 2338 and fixture_count 146 -> 151 from 21 new lang-resolution fixtures. Scaling stayed linear and inside budget: typescript 1.116 < 1.5, javascript 1.010 < 1.5. Prior typescript ed92588e0fc7b28b3a0174339ac378b4dd85965fe007db1208dea97a65ce0571 -> f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7; prior javascript 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594 -> 2026993b81b873839dd2ef8797d9c14d9c48516b2b57b05ac17d8d43f2f4eba3.", + "_rebaselined_type_parameter_shadowing_w2_8": "W2-8: `@declaration.type-parameters` is now captured on generic FUNCTIONS, generator functions and type ALIASES, not only on class/interface declarations. NO NEW CAPTURE NAME — verified by diffing the capture-name sets against the wave-1 branch, which returns empty; the tag already existed and simply fires on more declarations. That is the whole delta: capture_groups_fp 2338 -> 2371 (+33 occurrences of an existing tag) and fixture_count 151 -> 152 (one new fixture, typescript-type-parameters). capture_groups_small/large unchanged at 4503/14403, since those measure the synthetic scaling source this does not touch. Scaling 1.06 < 1.5. JavaScript is untouched — it has no type parameters — and its fingerprint does not move, which is the check that this is the TS declaration rules and not something broader. Prior f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7 -> 62c7f1bfbe568eed927fb78f00061ed5e49d12511fd8260648b876df386f3b4c.", + "_rebaselined_2899_review_type_parameter_scope_fixtures": "PR #2899 review follow-up: FIXTURE-CORPUS GROWTH ONLY — no query rule changed and no capture name was added or removed. `typescript/query.ts` is byte-identical to the previous baseline; the type-parameter shadowing defect was fixed on the RESOLUTION side (`walkers.ts` gains a `declarationOpenedScope` gate so a declaration's `typeParameters` bind only inside the scope that declaration opened, and the `USES` guard moved from `graph-bridge/references-to-edges.ts` to `resolve-references.ts` where the spelled `site.name` is in hand). The fingerprint moves because measure.mjs fingerprints the whole `lang-resolution/typescript-*` fixture corpus and the regression tests add three files to `typescript-type-parameters/src/` (values.ts, aliased.ts, namespaced.ts) plus two scope-less generic aliases in shapes.ts. Per-file accounting sums exactly to the delta: shapes.ts 33->35 (+2), values.ts +11, aliased.ts +10, namespaced.ts +20 = +43. capture_groups_fp 2371 -> 2414; fixture_count 152 -> 155. capture_groups_small/large unchanged at 4503/14403 (they measure the SYNTHETIC scaling source, untouched). JAVASCRIPT IS THE CONTROL AND DID NOT MOVE (fingerprint 2026993b..., 43 fixtures) — which is the check that this is corpus growth and not a capture regression; all 14 other languages report `ok`. Scaling 0.976 < 1.5. Prior 62c7f1bfbe568eed927fb78f00061ed5e49d12511fd8260648b876df386f3b4c -> c2fbf8a89e5686dd1ff3659b20d41d8b05ebcc9790356e3653ee0c8ca5d365c8.", "_rebaselined_2953_workspace_fixture": "#2953 adds test/fixtures/lang-resolution/typescript-pnpm-workspace-imports, a pnpm monorepo of 12 .ts files, and the TypeScript capture corpus is collected from test/fixtures. CORPUS GROWTH ONLY, NOT A CAPTURE CHANGE: fixture_count 155 -> 167 and capture_groups_fp 2414 -> 2465 are the 12 new files' own matches; capture_groups_small/large are unchanged at 4503/14403 because those measure the SYNTHETIC scaling source, which the fixture corpus does not feed. Attribution is exact rather than inferred: moving that one fixture directory aside and re-running returns typescript to f719163eb03a447c9e40ca316a905dd76cee82192a75a403df478ebbdc13e98f byte-for-byte with fixture_count back at 155, and [scope-capture --check] PASSES for all 15 languages - so nothing in the TypeScript capture stream moved. #2953 changes import RESOLUTION, which runs after capture and feeds no capture tag. Prior f719163eb03a447c9e40ca316a905dd76cee82192a75a403df478ebbdc13e98f -> 05d1dadd6c9ef35c74079fa50f341b1b36e4fb02c9a89dd1b59f32b7cfd5e633.", "_rebaselined_1432_member_call_callee_name": "#1432 (Zig): the shared callable-flow reader no longer names a callee by simple name for a MEMBER call (`@callable-flow.direct-callee-name` requires a direct designator: `f(x)`, `ns.f(x)`), and a member call is a field-stored-callable invoke only when a MEMBER store (`o.f = handler`) or a declared callable-typed field is visible - a same-named plain binding no longer gates it. CAPTURE-EMISSION CHANGE, not fixture growth (fixture_count unchanged). Drift: `await svc.verify(token, ...)` (typescript-generic-calls/src/guest.ts, member call) and `initializer()(() => {...})` (typescript-hof-callbacks/src/store.ts, call-of-call) lose `direct-callee-name`. `await verifyToken(token, ...)` (admin.ts/auth.ts) KEEPS `direct-callee-name|verifyToken`: tree-sitter-typescript parses `await f(x)` as call_expression(function: await_expression(f), type_arguments, ...), and wrappedExpression now unwraps `await_expression` so the direct designator survives as it does for the un-awaited spelling. capture_groups_fp 2465 (unchanged). Prior 05d1dadd6c9ef35c74079fa50f341b1b36e4fb02c9a89dd1b59f32b7cfd5e633 -> fed04ed1d5db112387781e405da208ae6b3ab803889773b0455be96f01b893ff.", "_rebaselined_3354_callable_alternatives": "#3354 callable alternatives: a callable chosen by a value-selecting source now flows every branch it can yield (`a ?? b`, `a || b`, `a or b`, `c ? a : b`, statement `if`, elvis), and an operator branch (`x == f || g`) stays opaque instead of seeding a qualified name. Verified by running the BASE (merge-base 233ca2849) and HEAD emitters over the SAME HEAD fixture corpus: every added or removed match is an `@callable-flow.*` match on one of those sources, and the pre-existing corpus is byte-identical (all other languages: zero delta). The rest of the drift is corpus growth from this PR's regression fixture, which this bench globs. Corpus growth: typescript-callable-alternatives/{index,compare,worker,sweep/index}.ts (+4 files, +288 groups). Emitter delta: +18 / -14: `??` / `||` / `&&` / ternary seeds and copies now name each operand (`&&` its right operand only); the 14 removed matches are the whole-expression seeds and copies carrying a qualified name of the compound source, including the comparison branches in compare.ts that now stay opaque. capture_groups_fp 2465 -> 2753, fixture_count 167 -> 171; synthetic counts unchanged; scaling 0.963 < 1.5. Prior 60e75bbe846f7200005f12c4d95c32e82d9d3feae9f2fd594e484670762b82b0 -> 77c9b4ea654123a64972db8348190ec250b669472b150db65ea8c7f20b355467.", @@ -259,10 +269,10 @@ "_rebaselined": "#1956 synth-widening: + javascript-qualified-base fixture; synthesizeJsInheritanceReferences now handles a member_expression base (class S extends ns.Base -> Base), matching the #1940 legacy leg + the TS terminalTsTypeNameNode property_identifier case, at parity. Linear (~1.05). | #942: scope-resolution-only cleanup reworded fixture comments; capture byte-positions shift, capture LOGIC unchanged.", "_rebaselined_2522": "#2522 intentional @reference.value-ref/property-key capture additions. GitHub Actions run 29553361660 job 87800394279: prior d72f03c6c502235d2d4b74d66baa5c7d361f040d7a1b72e84acad61210d05ae8 -> 5567dd47e7ba29821a518c4a9852adc3b774e25ef3e7a6e2b3ecb7b59ddab73c; scaling ratio 1.031 < 1.5.", "_rebaselined_2550_instance_model": "PR #2549 (#2545/#2551): object literals emit @scope.object. Prior 479927409bbdd9852a36172c8260aa56df260e99129a7a9c20a0d1903dd5538b -> f1ccf42a36895c8e34dcb724286f247d469835f2dcbb23ad3347190adc7fde1c; scaling 1.096 < 1.5.", - "_rebaselined_receiver_owner_2701": "#2701: every non-arrow function form now carries a `@receiver-owner.this` marker on the same node as `@scope.function`, so a scope that BINDS its own `this` can stop the receiver walk (`Scope.ownsReceivers`). Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus against 1d3088173f6f93827641b476d614d5d15cd4f3ea: the ONLY delta is @receiver-owner.this (typescript +143, javascript +32) \u2014 every other capture count is byte-identical, so no existing capture moved. Prior f1ccf42a36895c8e34dcb724286f247d469835f2dcbb23ad3347190adc7fde1c -> 90601494695b834d3a9af7ac4844eac603f4f432809a05554cc59de0674a4354.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 1c71ef628eb75a3b111afa8c2a7c351c16a7f5aab9fac2f098f82b2866312aa8 -> 83344b7cba093702f4528eeee44e438809c229d43b12e69ed288812ce7ffc7bc.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 83344b7cba093702f4528eeee44e438809c229d43b12e69ed288812ce7ffc7bc -> 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594.", - "_rebaselined_blind_spots_2856": "#2856 blind-spots series: the JS/TS SCOPE queries gained capture rules, so fingerprint drift is expected and additive. Verified before re-baselining by diffing the capture-name sets in both scope queries against origin/main: TypeScript gained exactly @reference.read.identifier (A2 bare-identifier reads in value positions) and @reference.type (R2-2 type references, so a declared contract stops reporting incoming:{}); JavaScript gained exactly @reference.read.identifier, @reference.read.destructured (R2-1c) and @reference.write.property-key (R2-1b record-construction writes). NOTHING was removed on either side \u2014 the delta is a pure superset, which is the check that no existing capture moved. capture_groups_small/large are unchanged (4503/14403) because those measure the SYNTHETIC scaling source, which this branch does not touch; only the fixture-corpus count moves. capture_groups_fp 2097 -> 2338 and fixture_count 146 -> 151 from 21 new lang-resolution fixtures. Scaling stayed linear and inside budget: typescript 1.116 < 1.5, javascript 1.010 < 1.5. Prior typescript ed92588e0fc7b28b3a0174339ac378b4dd85965fe007db1208dea97a65ce0571 -> f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7; prior javascript 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594 -> 2026993b81b873839dd2ef8797d9c14d9c48516b2b57b05ac17d8d43f2f4eba3." + "_rebaselined_receiver_owner_2701": "#2701: every non-arrow function form now carries a `@receiver-owner.this` marker on the same node as `@scope.function`, so a scope that BINDS its own `this` can stop the receiver walk (`Scope.ownsReceivers`). Verified before re-baselining by diffing the capture-name histogram over this same fixture corpus against 1d3088173f6f93827641b476d614d5d15cd4f3ea: the ONLY delta is @receiver-owner.this (typescript +143, javascript +32) — every other capture count is byte-identical, so no existing capture moved. Prior f1ccf42a36895c8e34dcb724286f247d469835f2dcbb23ad3347190adc7fde1c -> 90601494695b834d3a9af7ac4844eac603f4f432809a05554cc59de0674a4354.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 1c71ef628eb75a3b111afa8c2a7c351c16a7f5aab9fac2f098f82b2866312aa8 -> 83344b7cba093702f4528eeee44e438809c229d43b12e69ed288812ce7ffc7bc.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior 83344b7cba093702f4528eeee44e438809c229d43b12e69ed288812ce7ffc7bc -> 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594.", + "_rebaselined_blind_spots_2856": "#2856 blind-spots series: the JS/TS SCOPE queries gained capture rules, so fingerprint drift is expected and additive. Verified before re-baselining by diffing the capture-name sets in both scope queries against origin/main: TypeScript gained exactly @reference.read.identifier (A2 bare-identifier reads in value positions) and @reference.type (R2-2 type references, so a declared contract stops reporting incoming:{}); JavaScript gained exactly @reference.read.identifier, @reference.read.destructured (R2-1c) and @reference.write.property-key (R2-1b record-construction writes). NOTHING was removed on either side — the delta is a pure superset, which is the check that no existing capture moved. capture_groups_small/large are unchanged (4503/14403) because those measure the SYNTHETIC scaling source, which this branch does not touch; only the fixture-corpus count moves. capture_groups_fp 2097 -> 2338 and fixture_count 146 -> 151 from 21 new lang-resolution fixtures. Scaling stayed linear and inside budget: typescript 1.116 < 1.5, javascript 1.010 < 1.5. Prior typescript ed92588e0fc7b28b3a0174339ac378b4dd85965fe007db1208dea97a65ce0571 -> f66a3e6f1e096431e7046505129a627deaa00ca0de5bc846b080591b397248f7; prior javascript 806f70ad3cce5fc849f6d06a08ace8a95f92a1ea84a2418fddabb1eef5846594 -> 2026993b81b873839dd2ef8797d9c14d9c48516b2b57b05ac17d8d43f2f4eba3." }, "kotlin": { "fingerprint": "026392f9a60d9808dd993fa6d26f3a2ca6240ed6ac63981d614058ae7acd29e2", @@ -274,13 +284,13 @@ "_rebaselined_callable_flow_2522_followup": "PR #2522 follow-up: Kotlin callable-reference flow facts with invocation-result suppression. Prior 4900431791f2b9280009deb2b82659c26ead8aa6fb8731190a7c505dec5a9041 -> bddba25d5a88152bbbee8d70e82c944b5302accb4b625df782adb1d4f7a7ac12; scaling 0.880 < 1.5.", "_added": "#1951: bench coverage added (was ungated); scale source heritage-bearing (: Base()); js/kotlin O(n^2) findNodeAtRange-per-match fixed to threaded captured node, now linear.", "_rebaselined": "#1919 review CF3 fix: extended kotlin-local-property-owner (init/accessor destructuring) + new dart-accessor-owner fixture (getter/setter ownership). Fingerprint-only corpus drift; scaling ~1.0.", - "_rebaselined_2271": "PR #2271: re-vendored tree-sitter-kotlin 0.3.8 -> unreleased fwcd main c8ac3d26 for `fun interface` support + new kotlin-fun-interface fixture in the corpus. Drift is both corpus-additive (the fixture) and grammar-driven (the new grammar parses `fun interface` as a class_declaration, not an ERROR node). Baselined to the NEW grammar's fingerprint, so this --check passes only once the regenerated prebuilds land \u2014 until then CI loads the committed 0.3.8 binary and the bench is red, same as the kotlin fun-interface integration tests. scaling ~0.83 (linear).", + "_rebaselined_2271": "PR #2271: re-vendored tree-sitter-kotlin 0.3.8 -> unreleased fwcd main c8ac3d26 for `fun interface` support + new kotlin-fun-interface fixture in the corpus. Drift is both corpus-additive (the fixture) and grammar-driven (the new grammar parses `fun interface` as a class_declaration, not an ERROR node). Baselined to the NEW grammar's fingerprint, so this --check passes only once the regenerated prebuilds land — until then CI loads the committed 0.3.8 binary and the bench is red, same as the kotlin fun-interface integration tests. scaling ~0.83 (linear).", "_rebaselined_2522_review_fixes": "PR #2522 review fixes: fieldless assignment nodes decomposed positionally. Prior e856951c2a779163d555dadc8e1bf59304a86caed78ac1f450d9caa2b50f63d1 -> 4b31f46cfb004ba769a96feeb06ae4ef109c77410f54e7aaab4a688df599b112; scaling ratio re-verified within budget.", "_rebaselined_2550_instance_model": "PR #2549 (#2545): anonymous object expressions (object_literal) emit @scope.class, and the kotlin-object-literal-scope fixture joined the corpus. Prior 4b31f46cfb004ba769a96feeb06ae4ef109c77410f54e7aaab4a688df599b112 -> a6fce0dff00e88d41d85023eaf3f35016b5217c7e5225f24a598e4c70bb63091; scaling 0.951 < 1.5.", "_rebaselined_2563_instance_ownership": "#2563: kotlin-instance-ownership adds unrelated, inherited, outer-instance, and anonymous-object coverage. Prior a6fce0dff00e88d41d85023eaf3f35016b5217c7e5225f24a598e4c70bb63091 -> 9f159f8810d342ef1c821f466efd6920dad9a190f06000056e6cd2815861b195; scaling 1.257 < 1.5.", - "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged \u2014 the tag is added to existing call matches, never a new match \u2014 so this is digest drift only. Prior 9f159f8810d342ef1c821f466efd6920dad9a190f06000056e6cd2815861b195 -> d3c4d2fa0d82d248a2299cfc888b067187ad1faf2c87a97f93c6ed835eefc3f1.", - "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|\u2026` instead of `1|\u2026`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior d3c4d2fa0d82d248a2299cfc888b067187ad1faf2c87a97f93c6ed835eefc3f1 -> c1f0cc9058ab11b7cd6fc8b440deb6db2b2f530f2eb21178923e68a3d0796c4b.", - "_rebaselined_2766_await_subscript_emission": "#2766: extractMixedChain now walks THROUGH await and subscript nodes and peels transparent wrappers at loop entry, so sites whose receiver is `repos[0]` or `(await f())` mint a receiver chain where they previously minted none. EMISSION CHANGE: more sites carry `@reference.receiver-chain`; no existing chain changed shape. Only go and kotlin drifted of 15 \u2014 the two whose fixture corpora contain such receivers. Prior c1f0cc9058ab11b7cd6fc8b440deb6db2b2f530f2eb21178923e68a3d0796c4b -> efd5dbf80ffcd3bab2834d1010f6fe2b239dcc5d58229938dea9cff8d0f380f2.", + "_rebaselined_receiver_chain_2747": "#2747 receiver-chain rollout: call matches whose receiver is itself an expression now carry `@reference.receiver-chain`, a compact encoding of the receiver's structure, so resolution types it by folding instead of re-parsing receiver source text. Capture GROUP counts are unchanged — the tag is added to existing call matches, never a new match — so this is digest drift only. Prior 9f159f8810d342ef1c821f466efd6920dad9a190f06000056e6cd2815861b195 -> d3c4d2fa0d82d248a2299cfc888b067187ad1faf2c87a97f93c6ed835eefc3f1.", + "_rebaselined_2766_receiver_chain_wire_v2": "#2766: receiver-chain wire format v1 -> v2 (name-free `await` / `index` step kinds). The VERSION prefix is part of every emitted `@reference.receiver-chain` capture, so every chain-minting language's capture text changed. WIRE-FORMAT CHANGE, NOT A CAPTURE-SET CHANGE: the same chains are minted for the same sites, spelled `2|…` instead of `1|…`. Exactly the 12 chain-minting languages drifted; c, cobol and dart did not, which is the check that this is the prefix and not a capture regression. Accompanied by SCHEMA_BUMP 34 -> 37 and INCREMENTAL_SCHEMA_VERSION 28 -> 31 so a stale index is rejected rather than replaying chains a v2 decoder refuses. Prior d3c4d2fa0d82d248a2299cfc888b067187ad1faf2c87a97f93c6ed835eefc3f1 -> c1f0cc9058ab11b7cd6fc8b440deb6db2b2f530f2eb21178923e68a3d0796c4b.", + "_rebaselined_2766_await_subscript_emission": "#2766: extractMixedChain now walks THROUGH await and subscript nodes and peels transparent wrappers at loop entry, so sites whose receiver is `repos[0]` or `(await f())` mint a receiver chain where they previously minted none. EMISSION CHANGE: more sites carry `@reference.receiver-chain`; no existing chain changed shape. Only go and kotlin drifted of 15 — the two whose fixture corpora contain such receivers. Prior c1f0cc9058ab11b7cd6fc8b440deb6db2b2f530f2eb21178923e68a3d0796c4b -> efd5dbf80ffcd3bab2834d1010f6fe2b239dcc5d58229938dea9cff8d0f380f2.", "_rebaselined_2960_declared_package_fixture": "#2960 adds four Kotlin declared-package import-resolution fixture files. This is fixture-corpus growth only: fixture_count 137 -> 141 and capture_groups_fp 2334 -> 2367; the synthetic capture counts remain 4753/15203, no Kotlin scope-capture query or implementation changed, and package resolution runs after capture. Other language fingerprints matched their baselines in the same CI run. Prior a184f8ff0ae40d246db855b63f7ff26bda3afac03e5f4c76e4593c7e2cefce54 -> f98e7e936afbce0e99588285cfc603bf945fd58c5de45271860509a5d90eb832.", "capture_groups_small": 5253, "capture_groups_large": 16803, @@ -288,7 +298,7 @@ "fixture_count": 142, "_rebaselined_1432_member_call_callee_name": "#1432 (Zig): the shared callable-flow reader no longer names a callee by simple name for a MEMBER call (`@callable-flow.direct-callee-name` requires a direct designator: `f(x)`, `ns.f(x)`), and a member call is a field-stored-callable invoke only when a MEMBER store (`o.f = handler`) or a declared callable-typed field is visible - a same-named plain binding no longer gates it. CAPTURE-EMISSION CHANGE, not fixture growth (fixture_count unchanged). Only drift: `users.map { it.name }.forEach { name -> println(name) }` (kotlin-lambda-scopes/App.kt) loses `direct-callee-name|forEach` (member call). capture_groups_fp 2334 (unchanged). Prior a184f8ff0ae40d246db855b63f7ff26bda3afac03e5f4c76e4593c7e2cefce54 -> 5a181af0dbc9451937da0964c40d3f3f9820914ca429d873bb5c812b5e2b9284.", "_rebaselined_1432_rebase_onto_2960": "#1432 rebase onto main @ aac7515d: the kotlin fingerprint is a COMBINATION of two independent changes, so neither side of the merge conflict was correct on its own and resolving it by picking a side would have committed a fingerprint no run can reproduce. main's #2960 added four declared-package fixture files (fixture_count 137 -> 141, capture_groups_fp 2334 -> 2367); this branch's `_rebaselined_1432_member_call_callee_name` drops `direct-callee-name|forEach` from one member call. Recomputed under both: capture_groups_fp 2367 and fixture_count 141 match main's committed counts EXACTLY (this branch's change is emission-only and moves no count), capture_groups_small/large stay 4753/15203 (the SYNTHETIC scaling source, which neither change touches), scaling 1.003 < 1.5, and the other 14 languages report ok against their committed baselines in the same run - which is the check that the rebase replayed nothing else into the capture stream. Attribution is exact rather than inferred: moving test/fixtures/lang-resolution/kotlin-import-package-evidence aside and re-running returns kotlin to 5a181af0dbc9451937da0964c40d3f3f9820914ca429d873bb5c812b5e2b9284 byte-for-byte with fixture_count back at 137 and capture_groups_fp back at 2334 - this branch's pre-rebase value - so the whole delta is #2960's corpus growth layered on top, with nothing else moving. Prior (this branch, pre-rebase) 5a181af0dbc9451937da0964c40d3f3f9820914ca429d873bb5c812b5e2b9284 and (main) f98e7e936afbce0e99588285cfc603bf945fd58c5de45271860509a5d90eb832 -> 973d702510002dda76166e017c5eca90cae37a139f5a512877b7a1b04ad19dc5.", - "_rebaselined_1432_merge_main_2885": "#1432 merge of main @ 212e007a: the kotlin fingerprint is again a COMBINATION of two independent changes \u2014 main's #2885 JVM property accessors / interface-abstract (4753/15203 -> 5753/18403, capture_groups_fp 2367 -> 2563) and this branch's `_rebaselined_1432_member_call_callee_name` (drops `direct-callee-name|forEach` from one member call). Neither side's value reproduces under the merged tree. Recomputed under both: counts 5753/18403/2563 and fixture_count 141 match main's committed counts EXACTLY (this branch's change is emission-only), scaling 1.061 < 1.5, and csharp / cpp / typescript measure byte-for-byte at this branch's committed values (main did not touch them since the merge-base) while the other 11 languages report ok \u2014 the check that the merge replayed nothing else into the capture stream. Prior (main) aeafc7a87402c933786ef582b7c98683b1822b78fa909e605cb97552867fa0d5 and (this branch) 973d702510002dda76166e017c5eca90cae37a139f5a512877b7a1b04ad19dc5 -> a9d3f0db7547ff47856159debf15d2a6f427efca97a6af27b4004174ed432132.", + "_rebaselined_1432_merge_main_2885": "#1432 merge of main @ 212e007a: the kotlin fingerprint is again a COMBINATION of two independent changes — main's #2885 JVM property accessors / interface-abstract (4753/15203 -> 5753/18403, capture_groups_fp 2367 -> 2563) and this branch's `_rebaselined_1432_member_call_callee_name` (drops `direct-callee-name|forEach` from one member call). Neither side's value reproduces under the merged tree. Recomputed under both: counts 5753/18403/2563 and fixture_count 141 match main's committed counts EXACTLY (this branch's change is emission-only), scaling 1.061 < 1.5, and csharp / cpp / typescript measure byte-for-byte at this branch's committed values (main did not touch them since the merge-base) while the other 11 languages report ok — the check that the merge replayed nothing else into the capture stream. Prior (main) aeafc7a87402c933786ef582b7c98683b1822b78fa909e605cb97552867fa0d5 and (this branch) 973d702510002dda76166e017c5eca90cae37a139f5a512877b7a1b04ad19dc5 -> a9d3f0db7547ff47856159debf15d2a6f427efca97a6af27b4004174ed432132.", "_rebaselined_3354_callable_alternatives": "#3354 callable alternatives: a callable chosen by a value-selecting source now flows every branch it can yield (`a ?? b`, `a || b`, `a or b`, `c ? a : b`, statement `if`, elvis), and an operator branch (`x == f || g`) stays opaque instead of seeding a qualified name. Verified by running the BASE (merge-base 233ca2849) and HEAD emitters over the SAME HEAD fixture corpus: every added or removed match is an `@callable-flow.*` match on one of those sources, and the pre-existing corpus is byte-identical (all other languages: zero delta). The rest of the drift is corpus growth from this PR's regression fixture, which this bench globs. Corpus growth: kotlin-callable-alternatives/App.kt (+1 file, +71 groups). Emitter delta: +8 / -2: elvis and `if` expression (bare and braced) seeds and copies now name each operand; the 2 removed matches are the whole-expression seed and copy carrying a qualified name of the compound source; the multi-statement `if` stays opaque. capture_groups_fp 2563 -> 2634, fixture_count 141 -> 142; synthetic counts unchanged; scaling 1.17 < 1.5. Prior a9d3f0db7547ff47856159debf15d2a6f427efca97a6af27b4004174ed432132 -> f3fefe058484823761b52df5715f41d65fa4ff0223843bcc86893d7b0a6b3de2.", "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 1 existing member-read match gains a receiver-chain tag; removing only that added tag restores the complete main capture set. No group is added or removed. Fixture entries 142; changed entries 1; capture groups 2634 -> 2634. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged." }, @@ -296,6 +306,6 @@ "_lexical_ownership_3532": "#3532: lexical ownership captures and fixture updates; fixture identities are relative to lang-resolution so serialized scope IDs are independent of checkout location. Full capture content remains hashed; scaling_budget is unchanged.", "fingerprint": "3f41a3c6d9161f95c0c906cc979e6ef853c25b39052c5cab274dba2aabf270ba", "scaling_budget": 1.5, - "_added": "#3354 review: one TS `handler || w === \"k0\" || \u2026` chain, operand count = entity count (250 -> 800). Guards callable-flow value-alternative expansion (valueAlternatives + per-leaf visibility walks) against per-leaf cost that grows with chain depth: before the fix this measured 7.5-8.0 (super-linear; 8000 operands overflowed the stack), after it 1.11-1.22. Synthetic-only fingerprint (no fixture corpus); identical before and after the fix." + "_added": "#3354 review: one TS `handler || w === \"k0\" || …` chain, operand count = entity count (250 -> 800). Guards callable-flow value-alternative expansion (valueAlternatives + per-leaf visibility walks) against per-leaf cost that grows with chain depth: before the fix this measured 7.5-8.0 (super-linear; 8000 operands overflowed the stack), after it 1.11-1.22. Synthetic-only fingerprint (no fixture corpus); identical before and after the fix." } } diff --git a/gitnexus/bench/swift-package-imports/baselines.json b/gitnexus/bench/swift-package-imports/baselines.json index d52e9da11e..850d842d31 100644 --- a/gitnexus/bench/swift-package-imports/baselines.json +++ b/gitnexus/bench/swift-package-imports/baselines.json @@ -1,7 +1,7 @@ { "_what": "Baselines for bench/swift-package-imports/measure.mjs --check. Guards Swift Package.swift declaration resolve after #2964 / #2931: declared-target hits, SDK and undeclared-folder misses, empty declaredTargets fail-closed, @_exported union, #2931 nested-prefix membership, first-wins grouping, and https:// factory survival. Same approach as bench/parse-dispatch-rounds/baselines.json — exact floors and a fingerprint first; the only timing arms are ratios.", - "_triage": "READ THIS BEFORE RE-RUNNING. targets, files, imports, declared_resolved, sdk_external, undeclared_external, empty_declared_external, reexport_extra, nested_repeat_resolved, first_wins, parse_targets, parse_binary_skipped, url_comment_targets, parse_complete and layout_fingerprint are DETERMINISTIC: a re-run never changes them, and none may be re-baselined to make CI green. resolve_scaling_ratio, strategy_scaling_ratio and parse_scaling_ratio are the only timing arms; runner contention dominates them, so re-run on an idle machine before investigating and read the reported `reps` first. If exactly one arm fails and it is a timing arm, suspect the machine.", + "_triage": "READ THIS BEFORE RE-RUNNING. targets, files, imports, declared_resolved, sdk_external, undeclared_external, empty_declared_external, reexport_extra, nested_repeat_resolved, first_wins, parse_targets, parse_binary_skipped, url_comment_targets, parse_complete and layout_fingerprint are DETERMINISTIC: a re-run never changes them, and none may be re-baselined to make CI green. resolve_scaling_ratio and parse_scaling_ratio are the only timing arms; runner contention dominates them, so re-run on an idle machine before investigating and read the reported `reps` first. If exactly one arm fails and it is a timing arm, suspect the machine.", "targets": 16, "files": 260, @@ -27,23 +27,17 @@ "_layout_fingerprint_note": "sha256 over sorted from|target->files rows on the unique query set. A change here is a BEHAVIOUR change — the resolver returned a different target set. Explain it, never re-baseline it alone.", "resolve_scaling_budget": 1.9, - "strategy_scaling_budget": 1.6, "parse_scaling_budget": 1.9, "_resolve_scaling_note": "(t_4n / t_n) / 4 for resolveSwiftImportTarget over the declared corpus; ~1.0 is linear. A RATIO rather than a millisecond ceiling, deliberately: wall-clock is runner-speed-dependent, and this repo has already been bitten by a fixed ms budget. A per-import allFilePaths scan scores ~4. Budget is 1.9, i.e. 1.51x the measured maximum 1.261 — this file's siblings use ~1.5x on ratios. min-of-15 estimator.", - "_strategy_scaling_note": "(t_4n / t_n) / 4 for swiftPackageStrategy (the import-config WeakMap index). Measured maximum 1.030; budget 1.6 is 1.55x, matching parse-dispatch-rounds' pack_scaling_budget.", - "_parse_scaling_note": "(t_4n / t_n) / 4 for parseSwiftPackageManifest over 256 vs 1024 factories. Measured maximum 1.276; budget 1.9 is 1.49x. The small cell is still sub-millisecond, so this budget is looser than strategy on purpose.", + "_parse_scaling_note": "(t_4n / t_n) / 4 for parseSwiftPackageManifest over 256 vs 1024 factories. Measured maximum 1.276; budget 1.9 is 1.49x. The small cell is still sub-millisecond, so the budget allows timing variance.", "_measured": { "resolve_scaling_ratio": 1.261, "resolve_scaling_ratio_samples": [1.261, 1.201, 1.182, 1.241, 1.212], - "strategy_scaling_ratio": 1.03, - "strategy_scaling_ratio_samples": [1.019, 0.994, 0.97, 1.015, 1.03], "parse_scaling_ratio": 1.276, "parse_scaling_ratio_samples": [1.25, 1.276, 1.215, 1.224, 1.227], "resolve_ms": 3.5, "resolve_ms_4x": 17.16, - "strategy_ms": 0.67, - "strategy_ms_4x": 2.65, "parse_ms": 0.41, "parse_ms_4x": 2.01, "reps": 15 diff --git a/gitnexus/bench/swift-package-imports/measure.mjs b/gitnexus/bench/swift-package-imports/measure.mjs index efaed2ddd6..e20c7dd767 100644 --- a/gitnexus/bench/swift-package-imports/measure.mjs +++ b/gitnexus/bench/swift-package-imports/measure.mjs @@ -37,7 +37,7 @@ * rows on the unique query set. Catches a target-set change that leaves * the counts intact. * - * - `resolve_scaling_ratio` / `strategy_scaling_ratio` / `parse_scaling_ratio` + * - `resolve_scaling_ratio` / `parse_scaling_ratio` * — the only timing arms, RATIOS not millisecond ceilings. * `(t_4n / t_n) / 4` divides the machine out; ~1.0 is linear. * Files-per-target is FIXED while target count (and therefore files and @@ -54,7 +54,6 @@ import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { performance } from 'node:perf_hooks'; import { parseSwiftPackageManifest } from '../../src/core/ingestion/language-config.ts'; -import { swiftPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/swift.ts'; import { resolveSwiftImportTarget } from '../../src/core/ingestion/languages/swift/import-target.ts'; import { groupSwiftFilesByModule } from '../../src/core/ingestion/languages/swift/target-grouping.ts'; @@ -173,23 +172,6 @@ function resolveOne(query, allFilePaths, config, parsedFiles) { }); } -function strategyCtx(files, config) { - return { - allFilePaths: new Set(files), - allFileList: files, - normalizedFileList: files.map((p) => p.replace(/\\/g, '/')), - index: {}, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: config, - csharpConfigs: [], - }, - }; -} - function resolvePass(corpus) { const allFilePaths = new Set(corpus.files); let resolved = 0; @@ -199,15 +181,6 @@ function resolvePass(corpus) { return resolved; } -function strategyPass(corpus) { - const ctx = strategyCtx(corpus.files, corpus.config); - let resolved = 0; - for (const query of corpus.queries) { - if (swiftPackageStrategy(query.raw, query.from, ctx) != null) resolved++; - } - return resolved; -} - function manifestFor(targetCount) { const rows = []; for (let i = 0; i < targetCount; i++) { @@ -327,10 +300,6 @@ const smallResolveMs = fastest(() => resolvePass(small), REPS); const largeResolveMs = fastest(() => resolvePass(large), REPS); const resolveScaling = largeResolveMs / smallResolveMs / SCALE; -const smallStrategyMs = fastest(() => strategyPass(small), REPS); -const largeStrategyMs = fastest(() => strategyPass(large), REPS); -const strategyScaling = largeStrategyMs / smallStrategyMs / SCALE; - const parseSmallSrc = manifestFor(PARSE_TARGETS); const parseLargeSrc = manifestFor(PARSE_TARGETS * SCALE); const parseSmall = parseSwiftPackageManifest(parseSmallSrc); @@ -376,14 +345,11 @@ console.log(`layout_fingerprint : ${shape.fingerprint}`); console.log( `resolve_scaling_ratio : ${resolveScaling.toFixed(3)} (budget <= ${baselines.resolve_scaling_budget}; ~1.0 is linear)`, ); -console.log( - `strategy_scaling_ratio : ${strategyScaling.toFixed(3)} (budget <= ${baselines.strategy_scaling_budget}; ~1.0 is linear)`, -); console.log( `parse_scaling_ratio : ${parseScaling.toFixed(3)} (budget <= ${baselines.parse_scaling_budget}; ~1.0 is linear)`, ); console.log( - `reps : ${REPS} resolve ${smallResolveMs.toFixed(2)}ms / 4x ${largeResolveMs.toFixed(2)}ms strategy ${smallStrategyMs.toFixed(2)}ms / 4x ${largeStrategyMs.toFixed(2)}ms parse ${smallParseMs.toFixed(2)}ms / 4x ${largeParseMs.toFixed(2)}ms`, + `reps : ${REPS} resolve ${smallResolveMs.toFixed(2)}ms / 4x ${largeResolveMs.toFixed(2)}ms parse ${smallParseMs.toFixed(2)}ms / 4x ${largeParseMs.toFixed(2)}ms`, ); console.log( `parse_scale_shape : ${parseSmall.targets.size} -> ${parseLarge.targets.size} targets (expect ${PARSE_TARGETS} -> ${PARSE_TARGETS * SCALE})`, @@ -457,16 +423,6 @@ if (process.argv.includes('--check')) { ); } - if (strategyScaling > baselines.strategy_scaling_budget) { - failed = true; - console.error( - `\nFAIL strategy_scaling_ratio: ${strategyScaling.toFixed(3)} exceeds ` + - `${baselines.strategy_scaling_budget} (~1.0 is linear).\n` + - ` swiftPackageStrategy grew superlinearly — usually the WeakMap target\n` + - ` index falling back to O(imports × files). Re-run idle; check \`reps\`.`, - ); - } - if (parseScaling > baselines.parse_scaling_budget) { failed = true; console.error( diff --git a/gitnexus/src/core/group/extractors/http-patterns/php.ts b/gitnexus/src/core/group/extractors/http-patterns/php.ts index 65a1896c9a..8a72052f00 100644 --- a/gitnexus/src/core/group/extractors/http-patterns/php.ts +++ b/gitnexus/src/core/group/extractors/http-patterns/php.ts @@ -42,7 +42,7 @@ import type { HttpDetection, HttpLanguagePlugin } from './types.js'; * `python-const-resolver.ts` / `js-const-resolver.ts`). PHP has no such * binding yet — adding one is a real, separate project (this repo's PHP * import resolution for `use`-statements is its own multi-file subsystem - * under `ingestion/import-resolvers/php.ts`, built for symbol/scope + * under `ingestion/languages/php/import-helpers.ts`, built for symbol/scope * resolution, not constant extraction) and is intentionally out of scope * here. Tracked as a follow-up, not silently punted. */ diff --git a/gitnexus/src/core/group/extractors/include-extractor.ts b/gitnexus/src/core/group/extractors/include-extractor.ts index d7993c0f4d..bd11a388d5 100644 --- a/gitnexus/src/core/group/extractors/include-extractor.ts +++ b/gitnexus/src/core/group/extractors/include-extractor.ts @@ -21,7 +21,7 @@ try { import type { ContractExtractor, CypherExecutor } from '../contract-extractor.js'; import type { ExtractedContract, RepoHandle } from '../types.js'; import { readSafe } from './fs-utils.js'; -import { buildSuffixIndex, type SuffixIndex } from '../../ingestion/import-resolvers/utils.js'; +import { buildSuffixIndex, type SuffixIndex } from '../../ingestion/utils/suffix-index.js'; import { createIgnoreFilter } from '../../../config/ignore-service.js'; import { getMaxFileSizeBytes } from '../../ingestion/utils/max-file-size.js'; import { parseSourceSafe } from '../../tree-sitter/safe-parse.js'; diff --git a/gitnexus/src/core/ingestion/asyncapi/document.ts b/gitnexus/src/core/ingestion/asyncapi/document.ts index 282e579175..5932db5a10 100644 --- a/gitnexus/src/core/ingestion/asyncapi/document.ts +++ b/gitnexus/src/core/ingestion/asyncapi/document.ts @@ -60,7 +60,7 @@ import path from 'node:path'; import { brokerForBindingKey, brokerForProtocol, isNonDestinationBroker } from './protocol.js'; // `js-yaml` is CJS; the rest of this repository reaches it the same way -// (`pipeline-phases/spring-config.ts`, `import-resolvers/node-workspace-packages.ts`). +// (`pipeline-phases/spring-config.ts`, `languages/typescript/workspace-packages.ts`). const _require = createRequire(import.meta.url); const yaml = _require('js-yaml') as typeof import('js-yaml'); diff --git a/gitnexus/src/core/ingestion/di-extractors/types.ts b/gitnexus/src/core/ingestion/di-extractors/types.ts index 5a06212639..ea91dc5500 100644 --- a/gitnexus/src/core/ingestion/di-extractors/types.ts +++ b/gitnexus/src/core/ingestion/di-extractors/types.ts @@ -9,8 +9,6 @@ * consumers of the registry read them off its results; `DiResolver` is not * re-exported, since only implementations need it and they import it from here * directly. - * - * Mirrors the `import-resolvers/types.ts` split of contract from registry. */ import type { GraphNode } from 'gitnexus-shared'; diff --git a/gitnexus/src/core/ingestion/field-extractors/configs/typescript-javascript.ts b/gitnexus/src/core/ingestion/field-extractors/configs/typescript-javascript.ts index 1f7786973f..1ae3e40cbd 100644 --- a/gitnexus/src/core/ingestion/field-extractors/configs/typescript-javascript.ts +++ b/gitnexus/src/core/ingestion/field-extractors/configs/typescript-javascript.ts @@ -2,11 +2,36 @@ import { SupportedLanguages } from 'gitnexus-shared'; import type { FieldExtractionConfig } from '../generic.js'; +import type { SyntaxNode } from '../../utils/ast-helpers.js'; import { hasKeyword, findVisibility, typeFromAnnotation } from './helpers.js'; import type { FieldVisibility } from '../../field-types.js'; const VISIBILITY_KEYWORDS = new Set(['public', 'private', 'protected']); +/** + * The class a field's initializer constructs: `static DEFAULT = new Config()` + * -> `Config`, `repo = new models.Repo()` -> `models.Repo`. `undefined` for any + * other initializer — a literal, a call, a missing one. + * + * The same two constructor shapes (identifier, member expression) the JS and TS + * scope queries bind a class field from (`@type-binding.constructor`). Those + * bindings live in the CLASS scope, which has one map for static and instance + * members, so a static field's binding is dropped there to keep it from + * retyping an instance field of the same name (`isStaticClassFieldBinding`). + * Recorded on the field instead, the static field keeps its type on its own + * Property node, where nothing else can collide with it. + */ +export function constructedTypeOfFieldInitializer(node: SyntaxNode): string | undefined { + const value = node.childForFieldName('value'); + if (value === null || value.type !== 'new_expression') return undefined; + const constructorNode = value.childForFieldName('constructor'); + if (constructorNode === null) return undefined; + if (constructorNode.type !== 'identifier' && constructorNode.type !== 'member_expression') { + return undefined; + } + return constructorNode.text; +} + const shared: Omit = { typeDeclarationNodes: [ 'class_declaration', @@ -35,6 +60,8 @@ const shared: Omit = { return typeFromAnnotation(node); }, + extractInitializerType: constructedTypeOfFieldInitializer, + extractVisibility(node) { // TypeScript accessibility_modifier for (let i = 0; i < node.namedChildCount; i++) { diff --git a/gitnexus/src/core/ingestion/field-extractors/generic.ts b/gitnexus/src/core/ingestion/field-extractors/generic.ts index 7e22053eef..960566c7d2 100644 --- a/gitnexus/src/core/ingestion/field-extractors/generic.ts +++ b/gitnexus/src/core/ingestion/field-extractors/generic.ts @@ -58,6 +58,13 @@ export interface FieldExtractionConfig { * `normalizeType`/`resolveType` entirely — it is the untouched source text. */ extractRawType?: (node: SyntaxNode) => string | undefined; + /** + * Extract the type a field's initializer constructs (`= new Config()` -> + * `Config`). Consulted only when `extractType` found no declared type, so it + * can never stand in for one. Optional — only languages whose fields can be + * typed by their initializer alone implement it. + */ + extractInitializerType?: (node: SyntaxNode) => string | undefined; /** * Extract `'@Name'`-prefixed annotation names from a field declaration * node (e.g. `['@Autowired']`). Optional — only languages with @@ -232,16 +239,27 @@ export function createFieldExtractor(config: FieldExtractionConfig): FieldExtrac annotations = undefined; } + let initializerType: string | undefined; + try { + initializerType = type === null ? config.extractInitializerType?.(node) : undefined; + } catch { + // Same group-drop rationale as the extractRawType guard above — + // degrade to a field without an initializer type. + initializerType = undefined; + } + return { name, type, ...(rawDeclaredType !== undefined ? { rawDeclaredType } : {}), + ...(initializerType !== undefined ? { initializerType } : {}), ...(annotations !== undefined && annotations.length > 0 ? { annotations } : {}), visibility: config.extractVisibilityForName?.(node, name) ?? config.extractVisibility(node), isStatic: config.isStatic(node), isReadonly: config.isReadonly(node), sourceFile: context.filePath, line: node.startPosition.row + 1, + column: node.startPosition.column, }; } } diff --git a/gitnexus/src/core/ingestion/field-extractors/typescript.ts b/gitnexus/src/core/ingestion/field-extractors/typescript.ts index 974148a8d1..6a3d7c3076 100644 --- a/gitnexus/src/core/ingestion/field-extractors/typescript.ts +++ b/gitnexus/src/core/ingestion/field-extractors/typescript.ts @@ -3,6 +3,7 @@ import type { SyntaxNode } from '../utils/ast-helpers.js'; import { SupportedLanguages } from 'gitnexus-shared'; import { BaseFieldExtractor } from '../field-extractor.js'; +import { constructedTypeOfFieldInitializer } from './configs/typescript-javascript.js'; import type { FieldExtractorContext, ExtractedFields, @@ -177,14 +178,18 @@ export class TypeScriptFieldExtractor extends BaseFieldExtractor { type = resolvedType ?? type; } + const initializerType = type === null ? constructedTypeOfFieldInitializer(node) : undefined; + return { name, type, + ...(initializerType !== undefined ? { initializerType } : {}), visibility: this.extractVisibility(node), isStatic: this.isStatic(node), isReadonly: this.isReadonly(node), sourceFile: context.filePath, line: node.startPosition.row + 1, + column: node.startPosition.column, }; } diff --git a/gitnexus/src/core/ingestion/field-types.ts b/gitnexus/src/core/ingestion/field-types.ts index 6c243f8ba3..d334460a6c 100644 --- a/gitnexus/src/core/ingestion/field-types.ts +++ b/gitnexus/src/core/ingestion/field-types.ts @@ -39,6 +39,13 @@ export interface FieldInfo { * Never passes through simple-name extraction or type resolution. */ rawDeclaredType?: string; + /** + * The type the field's INITIALIZER constructs, recorded only for a field that + * declares no type (`static DEFAULT = new Config()` -> `Config`). Omitted when + * `type` is set, when the initializer constructs nothing nameable, and for + * every language whose config does not read initializers. + */ + initializerType?: string; /** * Annotation names found on the field declaration, `'@Name'`-prefixed * (e.g. `['@Autowired']`), matching the method-extractor convention. @@ -56,6 +63,8 @@ export interface FieldInfo { sourceFile: string; /** Line number */ line: number; + /** Zero-based declaration column, when the extractor has an AST position. */ + column?: number; } /** diff --git a/gitnexus/src/core/ingestion/finalize-orchestrator.ts b/gitnexus/src/core/ingestion/finalize-orchestrator.ts index 0c17017780..e72182acd7 100644 --- a/gitnexus/src/core/ingestion/finalize-orchestrator.ts +++ b/gitnexus/src/core/ingestion/finalize-orchestrator.ts @@ -159,6 +159,7 @@ export function finalizeScopeModel( namespaceFqnBindings: new Map(), namespaceTypeBindings: new Map(), accessibleNamespacesByScope: new Map(), + namespaceLookupTiersByScope: new Map(), referenceSites: Object.freeze([...allReferenceSites]), sccs: finalizeOut.sccs, stats: finalizeOut.stats, diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts deleted file mode 100644 index bcfddee0ba..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/c-cpp.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * C / C++ import resolution configs. - * Both use standard resolution for #include directives. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; - -export const cImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.C, - strategies: [createStandardStrategy(SupportedLanguages.C)], -}; - -export const cppImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.CPlusPlus, - strategies: [createStandardStrategy(SupportedLanguages.CPlusPlus)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts deleted file mode 100644 index 24e9e6cfa0..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/csharp.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * C# import resolution config. - * Namespace-based strategy via .csproj configs, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveCSharpImportInternal, resolveCSharpNamespaceDir } from '../csharp.js'; -import { csharpSuffixFallbackAllowed } from '../../csharp-namespace-gate.js'; - -/** C# namespace-based resolution strategy via .csproj configs. */ -export const csharpNamespaceStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const csharpConfigs = ctx.configs.csharpConfigs; - const evidence = ctx.configs.csharpNamespaces; - if (csharpConfigs.length === 0) { - // No csproj → there's no namespace→directory mapping to apply, so the - // generic strategy would normally take over. But that generic suffix match - // is UNGATED: it re-introduces the BCL→local spurious match the #1881 gate - // exists to stop. Mirror the registry leg's no-csproj path — defer to the - // generic strategy ONLY for imports that align with an in-repo declared - // namespace; for everything else (BCL usings) return an authoritative empty - // result that STOPS the chain (#2 parity). With no evidence threaded the - // gate fails open, so behavior is unchanged when the scan didn't run. - if (!csharpSuffixFallbackAllowed(rawImportPath, evidence)) { - return { kind: 'files', files: [] }; - } - return null; - } - - const resolvedFiles = resolveCSharpImportInternal( - rawImportPath, - csharpConfigs, - // The Set, not `ctx.normalizedFileList`/`ctx.allFileList`: the resolver - // derives both from it through the same per-pass memo the ctx's own arrays - // come from, so this is the identical pair by a shorter route. - ctx.allFilePaths, - ctx.index, - evidence, - ); - if (resolvedFiles.length > 1) { - const dirSuffix = resolveCSharpNamespaceDir(rawImportPath, csharpConfigs); - if (dirSuffix) { - return { kind: 'package', files: resolvedFiles, dirSuffix }; - } - } - // Authoritative once csproj configs exist: return even an empty result to - // STOP the chain, so the generic suffix fallback can't re-introduce the - // gated BCL→local match this resolver just suppressed (#1881). - return { kind: 'files', files: resolvedFiles }; -}; - -export const csharpImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.CSharp, - strategies: [csharpNamespaceStrategy, createStandardStrategy(SupportedLanguages.CSharp)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts deleted file mode 100644 index 06dcea98a3..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/dart.ts +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Dart import resolution config. - * SDK/package strategy first, then relative import strategy (with ./ prepending). - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolveStandard } from '../standard.js'; - -/** - * Dart SDK and package: import strategy. - * Absorbs dart: SDK imports and external packages (returns empty result to stop chain). - * Returns null for relative imports to let the next strategy handle them. - */ -export const dartPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - // Strip surrounding quotes from configurable_uri capture - const stripped = rawImportPath.replace(/^['"]|['"]$/g, ''); - - // Skip dart: SDK imports (dart:async, dart:io, etc.) - if (stripped.startsWith('dart:')) return { kind: 'files', files: [] }; - - // Local package: imports → resolve to lib/ - if (stripped.startsWith('package:')) { - const slashIdx = stripped.indexOf('/'); - if (slashIdx === -1) return { kind: 'files', files: [] }; - const relPath = stripped.slice(slashIdx + 1); - const candidates = [`lib/${relPath}`, relPath]; - const files: string[] = []; - for (const candidate of candidates) { - for (const fp of ctx.allFileList) { - if (fp.endsWith('/' + candidate) || fp === candidate) { - files.push(fp); - break; - } - } - if (files.length > 0) break; - } - if (files.length > 0) return { kind: 'files', files }; - return { kind: 'files', files: [] }; // external package - } - - return null; -}; - -/** - * Dart relative import strategy — prepends "./" for bare relative paths, - * then delegates to standard resolution. - */ -export const dartRelativeStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - const stripped = rawImportPath.replace(/^['"]|['"]$/g, ''); - const relPath = stripped.startsWith('.') ? stripped : './' + stripped; - return resolveStandard(relPath, filePath, ctx, SupportedLanguages.Dart); -}; - -export const dartImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Dart, - strategies: [dartPackageStrategy, dartRelativeStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts deleted file mode 100644 index 7eee179884..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/go.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Go import resolution config. - * Go-specific package strategy (go.mod), then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveGoPackageDir, resolveGoPackage } from '../go.js'; - -/** Go-specific package resolution strategy — resolves go.mod-based package imports. */ -export const goPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const goModule = ctx.configs.goModule; - if (goModule && rawImportPath.startsWith(goModule.modulePath)) { - const pkgSuffix = resolveGoPackageDir(rawImportPath, goModule); - if (pkgSuffix) { - const pkgFiles = resolveGoPackage( - rawImportPath, - goModule, - ctx.normalizedFileList, - ctx.allFileList, - ); - if (pkgFiles.length > 0) { - return { kind: 'package', files: pkgFiles, dirSuffix: pkgSuffix }; - } - } - // Fall through if no files found (package might be external) - } - return null; -}; - -export const goImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Go, - strategies: [goPackageStrategy, createStandardStrategy(SupportedLanguages.Go)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts deleted file mode 100644 index 47e590fe87..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/jvm.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Java / Kotlin import resolution configs. - * JVM-specific wildcard/member strategy, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveJvmWildcard, resolveJvmMemberImport, KOTLIN_EXTENSIONS } from '../jvm.js'; - -/** Java JVM resolution strategy — wildcard and member import resolution. */ -export const javaJvmStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - if (rawImportPath.endsWith('.*')) { - const matchedFiles = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (matchedFiles.length > 0) return { kind: 'files', files: matchedFiles }; - } else { - const memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (memberResolved) return { kind: 'files', files: [memberResolved] }; - } - return null; -}; - -/** - * Kotlin JVM resolution strategy — wildcard/member with Java-interop + top-level function imports. - */ -export const kotlinJvmStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - if (rawImportPath.endsWith('.*')) { - const matchedFiles = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (matchedFiles.length === 0) { - const javaMatches = resolveJvmWildcard( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - if (javaMatches.length > 0) return { kind: 'files', files: javaMatches }; - } - if (matchedFiles.length > 0) return { kind: 'files', files: matchedFiles }; - } else { - let memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (!memberResolved) { - memberResolved = resolveJvmMemberImport( - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - } - if (memberResolved) return { kind: 'files', files: [memberResolved] }; - - // Kotlin: top-level function imports (e.g. import models.getUser) have only 2 segments, - // which resolveJvmMemberImport skips (requires >=3). Fall back to package-directory scan - // for lowercase last segments (function/property imports). Uppercase last segments - // (class imports like models.User) fall through to standard suffix resolution. - const segments = rawImportPath.split('.'); - const lastSeg = segments[segments.length - 1]; - if (segments.length >= 2 && lastSeg[0] && lastSeg[0] === lastSeg[0].toLowerCase()) { - const pkgWildcard = segments.slice(0, -1).join('.') + '.*'; - let dirFiles = resolveJvmWildcard( - pkgWildcard, - ctx.normalizedFileList, - ctx.allFileList, - KOTLIN_EXTENSIONS, - ctx.index, - ); - if (dirFiles.length === 0) { - dirFiles = resolveJvmWildcard( - pkgWildcard, - ctx.normalizedFileList, - ctx.allFileList, - ['.java'], - ctx.index, - ); - } - if (dirFiles.length > 0) return { kind: 'files', files: dirFiles }; - } - } - return null; -}; - -export const javaImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Java, - strategies: [javaJvmStrategy, createStandardStrategy(SupportedLanguages.Java)], -}; - -export const kotlinImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Kotlin, - strategies: [kotlinJvmStrategy, createStandardStrategy(SupportedLanguages.Kotlin)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts deleted file mode 100644 index 5a8446f25c..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/php.ts +++ /dev/null @@ -1,26 +0,0 @@ -/** - * PHP import resolution config. - * PSR-4 strategy via composer.json — no standard fallback (PSR-4 includes its own suffix matching). - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolvePhpImportInternal } from '../php.js'; - -/** PHP PSR-4 resolution strategy via composer.json autoload mappings. */ -export const phpPsr4Strategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const resolved = resolvePhpImportInternal( - rawImportPath, - ctx.configs.composerConfig, - ctx.allFilePaths, - ctx.normalizedFileList, - ctx.allFileList, - ctx.index, - ); - return resolved ? { kind: 'files', files: [resolved] } : null; -}; - -export const phpImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.PHP, - strategies: [phpPsr4Strategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts deleted file mode 100644 index d983045611..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/python.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Python import resolution config. - * PEP 328 relative + proximity-based strategy, then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolvePythonImportInternal } from '../python.js'; - -/** - * Python import resolution strategy — PEP 328 relative + proximity-based bare imports. - * Returns null to continue chain for non-relative imports. - * Absorbs unresolved relative imports (returns empty result to stop the chain). - */ -export const pythonImportStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - const resolved = resolvePythonImportInternal(filePath, rawImportPath, ctx.allFilePaths); - if (resolved) { - ctx.resolveCache.set(`${filePath}::${rawImportPath}`, resolved); - return { kind: 'files', files: [resolved] }; - } - // PEP 328: unresolved relative imports should not fall through to suffix matching - if (rawImportPath.startsWith('.')) return { kind: 'files', files: [] }; - - // External dotted imports like `django.apps` should not fall through to generic - // suffix matching when the repo has unrelated local files such as `accounts/apps.py`. - // Keep suffix fallback only when the leading segment appears somewhere in-repo, - // which preserves existing internal absolute-import behavior like `accounts.models`. - const pathLike = rawImportPath.replace(/\./g, '/'); - if (pathLike.includes('/')) { - const [leadingSegment] = pathLike.split('/').filter(Boolean); - const hasRepoCandidate = - !!leadingSegment && - (ctx.index.get(`${leadingSegment}.py`) !== undefined || - ctx.index.get(`${leadingSegment}/__init__.py`) !== undefined || - ctx.index.getFilesInDir(leadingSegment, '.py').length > 0); - - if (!hasRepoCandidate) return { kind: 'files', files: [] }; - } - - return null; -}; - -export const pythonImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Python, - strategies: [pythonImportStrategy, createStandardStrategy(SupportedLanguages.Python)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts deleted file mode 100644 index bf2507f705..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/ruby.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Ruby import resolution config. - * Require/require_relative suffix matching — no standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { suffixResolve } from '../utils.js'; - -/** Ruby require/require_relative resolution strategy. */ -export const rubyRequireStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const pathParts = rawImportPath.replace(/^\.\//, '').split('/').filter(Boolean); - const resolved = suffixResolve(pathParts, ctx.normalizedFileList, ctx.allFileList, ctx.index); - return resolved ? { kind: 'files', files: [resolved] } : null; -}; - -export const rubyImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Ruby, - strategies: [rubyRequireStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts deleted file mode 100644 index daa2173e71..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/rust.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Rust import resolution config. - * Rust module strategy (grouped imports, crate/super/self paths), then standard fallback. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; -import { resolveRustImportInternal } from '../rust.js'; - -/** Rust module resolution strategy — handles grouped imports and crate/super/self paths. */ -export const rustModuleStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - // Top-level grouped: use {crate::a, crate::b} - if (rawImportPath.startsWith('{') && rawImportPath.endsWith('}')) { - const inner = rawImportPath.slice(1, -1); - const parts = inner - .split(',') - .map((p) => p.trim()) - .filter(Boolean); - const resolved: string[] = []; - for (const part of parts) { - const r = resolveRustImportInternal(filePath, part, ctx.allFilePaths); - if (r) resolved.push(r); - } - return resolved.length > 0 ? { kind: 'files', files: resolved } : null; - } - - // Scoped grouped: use crate::models::{User, Repo} - const braceIdx = rawImportPath.indexOf('::{'); - if (braceIdx !== -1 && rawImportPath.endsWith('}')) { - const pathPrefix = rawImportPath.substring(0, braceIdx); - const braceContent = rawImportPath.substring(braceIdx + 3, rawImportPath.length - 1); - const items = braceContent - .split(',') - .map((s) => s.trim()) - .filter(Boolean); - const resolved: string[] = []; - for (const item of items) { - // Handle `use crate::models::{User, Repo as R}` — strip alias for resolution - const itemName = item.includes(' as ') ? item.split(' as ')[0].trim() : item; - const r = resolveRustImportInternal(filePath, `${pathPrefix}::${itemName}`, ctx.allFilePaths); - if (r) resolved.push(r); - } - if (resolved.length > 0) return { kind: 'files', files: resolved }; - // Fallback: resolve the prefix path itself (e.g. crate::models -> models.rs) - const prefixResult = resolveRustImportInternal(filePath, pathPrefix, ctx.allFilePaths); - if (prefixResult) return { kind: 'files', files: [prefixResult] }; - } - - return null; -}; - -export const rustImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Rust, - strategies: [rustModuleStrategy, createStandardStrategy(SupportedLanguages.Rust)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts deleted file mode 100644 index 1081a5aabe..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/swift.ts +++ /dev/null @@ -1,123 +0,0 @@ -/** - * Swift import resolution config. - * Package.swift target map strategy — no standard fallback (unresolved = external framework). - * - * ## Performance (anti-O(imports × files)) - * - * The previous implementation rescanned the whole `normalizedFileList` - * on every import to collect the `.swift` files under the requested - * target's directory — O(imports × files) per run, the exact hot path - * fixed for Python in PR #1918. We now build a `target → files` index - * ONCE per run, memoized on the stable `allFileList` array reference - * (the same `ResolveCtx` — and therefore the same array — is passed to - * every strategy invocation, per `import-processor`'s build-once - * context). Lookup per import is then O(1). - * - * A file is attributed to a target iff its **forward-slash - * (backslash-normalized), case-sensitive** path matches at a - * **segment boundary**: it starts with `/` or contains - * `//`. `normalizedFileList` is - * only backslash→forward-slash normalized — NOT lowercased — so the - * match is case-sensitive. The returned paths are the original-case - * `allFileList` entries, and the per-target file ORDER follows - * `allFileList`. - * - * Import-config fans a file to every matching declared target. Module - * grouping (`groupSwiftFilesByModule`) anchors target paths at the repo root - * and picks the deepest. That divergence is intentional: this legacy - * strategy only sees the root declaration map. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import { coerceDeclaredSwiftTargets, swiftDeclaredTargetPrefix } from '../../language-config.js'; -import type { ImportResolutionConfig, ImportResolverStrategy, ResolveCtx } from '../types.js'; - -interface SwiftTargetIndex { - /** Target name → original-case `.swift` file paths under that target dir. */ - readonly byTarget: ReadonlyMap; -} - -/** - * Memoized on the `allFileList` array identity. `import-processor` builds - * the `ResolveCtx` once per run and threads the same object (and the same - * `allFileList`) through every strategy call, so the WeakMap is keyed on a - * stable reference and the index is built once — not once per import. A - * fresh run produces a fresh array → a fresh index, so cross-run staleness - * is impossible. - * - * DELIBERATELY NOT ON `import-resolvers/per-file-set.ts` (#2909 sweep): this is - * a TWO-input memo keyed on ONE of them. The index is a function of both - * `ctx` (`allFileList` + the index-aligned `normalizedFileList`) and `targets`, - * but the key is only `ctx.allFileList`, and `perFileSet`'s `build: (key) => T` - * hands the builder nothing but the key. It is sound here only because of an - * invariant OUTSIDE the memo — `targets` is `ctx.configs.swiftPackageConfig - * .targets`, so it shares `ctx`'s lifetime and cannot vary while - * `ctx.allFileList` is fixed — and `perFileSet` has no way to express "and this - * other input is pinned by the same lifetime". Re-keying on `ctx` to make - * `targets` derivable from the key would change what the cache is keyed on and - * force an unreachable null-config arm into the builder, so it is a behaviour - * change rather than a consolidation. Leave it hand-rolled. - */ -const SWIFT_TARGET_INDEX_CACHE = new WeakMap(); - -function getSwiftTargetIndex( - ctx: ResolveCtx, - targets: ReadonlyMap, -): SwiftTargetIndex { - const key = ctx.allFileList as object; - const cached = SWIFT_TARGET_INDEX_CACHE.get(key); - if (cached !== undefined) return cached; - - // Pre-compute each target's directory prefix once (original case, to - // match the legacy comparison against the forward-slash-normalized, - // case-sensitive file list — see module docstring). - const targetDirs: { name: string; prefix: string }[] = []; - const byTarget = new Map(); - for (const [name, dir] of targets) { - targetDirs.push({ name, prefix: swiftDeclaredTargetPrefix(dir) }); - byTarget.set(name, []); - } - - // Single pass over the file list. `normalizedFileList` is forward-slash - // (backslash-normalized), case-sensitive, and index-aligned with - // `allFileList`; attribute the original-case path to every target whose - // prefix the normalized path starts with (a file under a nested target - // dir can legitimately belong to multiple configured targets — the - // legacy per-import scan would have returned it for each). - for (let i = 0; i < ctx.allFileList.length; i++) { - const norm = ctx.normalizedFileList[i]; - if (!norm.endsWith('.swift')) continue; - for (const { name, prefix } of targetDirs) { - if (!norm.startsWith(prefix) && !norm.includes(`/${prefix}`)) continue; - const bucket = byTarget.get(name); - if (bucket !== undefined) bucket.push(ctx.allFileList[i]); - } - } - - const index: SwiftTargetIndex = { byTarget }; - SWIFT_TARGET_INDEX_CACHE.set(key, index); - return index; -} - -/** Swift Package.swift target map resolution strategy. */ -export const swiftPackageStrategy: ImportResolverStrategy = (rawImportPath, _filePath, ctx) => { - const swiftPackageConfig = ctx.configs.swiftPackageConfig; - if (swiftPackageConfig == null) return null; - const declared = coerceDeclaredSwiftTargets(swiftPackageConfig); - if (declared == null) return null; - const moduleName = rawImportPath.split('.')[0]; - if (moduleName === '' || !declared.has(moduleName)) { - return null; - } - const index = getSwiftTargetIndex(ctx, declared); - const files = index.byTarget.get(moduleName); - if (files !== undefined && files.length > 0) { - return { kind: 'files', files: [...files] }; - } - return null; -}; - -export const swiftImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Swift, - strategies: [swiftPackageStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts deleted file mode 100644 index b86b365fd2..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/typescript-javascript.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * TypeScript / JavaScript / Vue import resolution configs. - * All use standard resolution — TS/JS with tsconfig path aliases, - * Vue delegates to TypeScript's resolver. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig } from '../types.js'; -import { createStandardStrategy } from '../standard.js'; - -export const typescriptImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.TypeScript, - strategies: [createStandardStrategy(SupportedLanguages.TypeScript)], -}; - -export const javascriptImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.JavaScript, - strategies: [createStandardStrategy(SupportedLanguages.JavaScript)], -}; - -// Vue SFCs are preprocessed into TypeScript upstream of import resolution, -// so the resolver intentionally runs as TypeScript. `language: Vue` here is -// documentation-only metadata (see `ImportResolutionConfig.language` JSDoc -// and ARCHITECTURE.md §Vue); it is not consumed by `createImportResolver`. -export const vueImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Vue, - strategies: [createStandardStrategy(SupportedLanguages.TypeScript)], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts b/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts deleted file mode 100644 index a191df9b6b..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/configs/zig.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Zig import resolution. - * - * Local-file imports (`@import("./foo.zig")`, `@import("foo.zig")`) resolve - * relative to the importer. Bare names (`@import("bar")`) resolve through - * build.zig.zon `.path` deps when a parsed ZigBuildZonConfig is available - * (see language-config.ts `loadZigBuildConfig`). Everything unresolvable — - * `std`, `builtin`, `root`, `.url`-based deps — returns an empty result so - * it doesn't produce ghost import edges. - */ - -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResolutionConfig, ImportResolverStrategy } from '../types.js'; -import { resolveZigImportInternal } from '../zig.js'; - -const stripQuotes = (s: string): string => s.replace(/^['"]|['"]$/g, ''); - -export const zigImportStrategy: ImportResolverStrategy = (rawImportPath, filePath, ctx) => { - // tree-sitter-zig captures the string with surrounding quotes. - const stripped = stripQuotes(rawImportPath); - const resolved = resolveZigImportInternal( - filePath, - stripped, - ctx.allFilePaths, - ctx.configs.zigBuildZon ?? null, - ); - // Unresolvable (stdlib / builtin / .url dep / missing file): stop the - // chain with an empty result rather than falling through to suffix - // matching, which could ghost-match an unrelated same-named file. - return { kind: 'files', files: resolved ? [resolved] : [] }; -}; - -export const zigImportConfig: ImportResolutionConfig = { - language: SupportedLanguages.Zig, - strategies: [zigImportStrategy], -}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/go.ts b/gitnexus/src/core/ingestion/import-resolvers/go.ts deleted file mode 100644 index eb87b09973..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/go.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Go package import resolution — internal helpers. - * - * Strategy lives in configs/go.ts. - * This file contains the shared helpers used by the strategy. - * - * **Reachability, as of #2929:** nothing in production calls either export - * today. The only path in is `configs/go.ts` → `createImportResolver` → - * the `importResolver` field on Go's `LanguageProvider`, and that field is - * read at exactly two lines — `import-target-adapter.ts:74-75` — whose two - * exports (`buildImportTargetWorkspace`, - * `resolveImportTargetAcrossLanguages`) have no importer anywhere but their - * own unit test. So this is a live-looking but currently unwired leg; the - * tests in `test/unit/import-resolvers/go-package-resolve.test.ts` are the - * only thing watching it. - */ - -import type { GoModuleConfig } from '../language-config.js'; - -/** `'/'`, for the parent-directory boundary check in `resolveGoPackage`. */ -const SLASH_CODE = 47; - -/** - * Extract the package directory suffix from a Go import path. - * Returns the suffix string (e.g., "/internal/auth/") or null if invalid. - */ -export function resolveGoPackageDir(importPath: string, goModule: GoModuleConfig): string | null { - if (!importPath.startsWith(goModule.modulePath)) return null; - const relativePkg = importPath.slice(goModule.modulePath.length + 1); - if (!relativePkg) return null; - return '/' + relativePkg + '/'; -} - -/** - * Resolve a Go internal package import to all .go files in the package directory. - * Returns an array of file paths. - */ -export function resolveGoPackage( - importPath: string, - goModule: GoModuleConfig, - normalizedFileList: readonly string[], - allFileList: readonly string[], -): string[] { - // Identical to the six lines this used to re-derive; `resolveGoPackageDir` - // returns the '/'-wrapped form and the scan wants the bare path, so unwrap. - const pkgDir = resolveGoPackageDir(importPath, goModule); - if (pkgDir === null) return []; - const relativePkg = pkgDir.slice(1, -1); // "/internal/auth/" → "internal/auth" - - const pkgLen = relativePkg.length; // >= 1: `resolveGoPackageDir` rejects empty - const matches: string[] = []; - - for (let i = 0; i < normalizedFileList.length; i++) { - const normalized = normalizedFileList[i]; - if (!normalized.endsWith('.go') || normalized.endsWith('_test.go')) continue; - // The file's PARENT directory ends with the package path — the same - // predicate `package-dir-index.ts` states. This used to ask `indexOf` for - // the FIRST `//` and then check that nothing after it held a slash, - // which made `a/pkg/b/pkg/x.go` not a member of `pkg` (#2881). - // - // Expressed as "`relativePkg` sits immediately before the last slash, on a - // segment boundary". The boundary is either the start of the path (an - // import matching from index 0, `internal/auth/x.go`) or a `/` — which is - // what the old `'/' + path` cons bought, at the price of a per-file - // concatenation the first `endsWith` forced V8 to flatten (#2929). - // - // Rewriting this as `endsWith(relativePkg, lastSlash)` buys nothing: the - // two-argument overload measured a wash against `startsWith(needle, pos)` - // here (10.28 ns vs 9.82 ns), so it trades the clarity of an explicit start - // index for no gain. A "the 2-arg overload leaves V8's fast path, 20x" - // claim from review did not reproduce on Node 22.18 — its baseline was a - // one-argument call that early-exited on the length precheck. - const start = normalized.lastIndexOf('/') - pkgLen; // < 0 when there is no parent dir - if (start < 0 || !normalized.startsWith(relativePkg, start)) continue; - if (start > 0 && normalized.charCodeAt(start - 1) !== SLASH_CODE) continue; - matches.push(allFileList[i]); - } - - return matches; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/jvm.ts b/gitnexus/src/core/ingestion/import-resolvers/jvm.ts deleted file mode 100644 index b6723b8e24..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/jvm.ts +++ /dev/null @@ -1,127 +0,0 @@ -/** - * JVM import resolution — internal helpers (Java + Kotlin). - * - * Strategies live in configs/jvm.ts. - * This file contains shared helpers for wildcard/member resolution - * and the Kotlin wildcard preprocessor. - */ - -import type { SuffixIndex } from './utils.js'; -import type { SyntaxNode } from '../utils/ast-helpers.js'; - -/** Kotlin file extensions for JVM resolver reuse */ -export const KOTLIN_EXTENSIONS: readonly string[] = ['.kt', '.kts']; - -/** - * Append .* to a Kotlin import path if the AST has a wildcard_import sibling node. - * Pure function — returns a new string without mutating the input. - */ -export const appendKotlinWildcard = (importPath: string, importNode: SyntaxNode): string => { - for (let i = 0; i < importNode.childCount; i++) { - if (importNode.child(i)?.type === 'wildcard_import') { - return importPath.endsWith('.*') ? importPath : `${importPath}.*`; - } - } - return importPath; -}; - -/** - * Resolve a JVM wildcard import (com.example.*) to all matching files. - * Works for both Java (.java) and Kotlin (.kt, .kts). - */ -export function resolveJvmWildcard( - importPath: string, - normalizedFileList: readonly string[], - allFileList: readonly string[], - extensions: readonly string[], - index?: SuffixIndex, -): string[] { - // "com.example.util.*" -> "com/example/util" - const packagePath = importPath.slice(0, -2).replace(/\./g, '/'); - - if (index) { - const candidates = extensions.flatMap((ext) => index.getFilesInDir(packagePath, ext)); - // Filter to only direct children (no subdirectories) - const packageSuffix = '/' + packagePath + '/'; - const packagePrefix = packagePath + '/'; - return candidates.filter((f) => { - const normalized = f.replace(/\\/g, '/'); - // Match both nested (src/models/User.kt) and root-level (models/User.kt) packages - let afterPkg: string; - const idx = normalized.lastIndexOf(packageSuffix); - if (idx >= 0) { - afterPkg = normalized.substring(idx + packageSuffix.length); - } else if (normalized.startsWith(packagePrefix)) { - afterPkg = normalized.substring(packagePrefix.length); - } else { - return false; - } - return !afterPkg.includes('/'); - }); - } - - // Fallback: linear scan - const packageSuffix = '/' + packagePath + '/'; - const packagePrefix = packagePath + '/'; - const matches: string[] = []; - for (let i = 0; i < normalizedFileList.length; i++) { - const normalized = normalizedFileList[i]; - if (!extensions.some((ext) => normalized.endsWith(ext))) continue; - // Match both nested (src/models/User.kt) and root-level (models/User.kt) packages - let afterPackage: string | null = null; - if (normalized.includes(packageSuffix)) { - afterPackage = normalized.substring( - normalized.lastIndexOf(packageSuffix) + packageSuffix.length, - ); - } else if (normalized.startsWith(packagePrefix)) { - afterPackage = normalized.substring(packagePrefix.length); - } - if (afterPackage !== null && !afterPackage.includes('/')) { - matches.push(allFileList[i]); - } - } - return matches; -} - -/** - * Try to resolve a JVM member/static import by stripping the member name. - * Java: "com.example.Constants.VALUE" -> resolve "com.example.Constants" - * Kotlin: "com.example.Constants.VALUE" -> resolve "com.example.Constants" - */ -export function resolveJvmMemberImport( - importPath: string, - normalizedFileList: readonly string[], - allFileList: readonly string[], - extensions: readonly string[], - index?: SuffixIndex, -): string | null { - // Member imports: com.example.Constants.VALUE or com.example.Constants.* - // The last segment is a member name if it starts with lowercase, is ALL_CAPS, or is a wildcard - const segments = importPath.split('.'); - if (segments.length < 3) return null; - - const lastSeg = segments[segments.length - 1]; - if (lastSeg === '*' || /^[a-z]/.test(lastSeg) || /^[A-Z_]+$/.test(lastSeg)) { - const classPath = segments.slice(0, -1).join('/'); - - for (const ext of extensions) { - const classSuffix = classPath + ext; - if (index) { - const result = index.get(classSuffix) || index.getInsensitive(classSuffix); - if (result) return result; - } else { - const fullSuffix = '/' + classSuffix; - for (let i = 0; i < normalizedFileList.length; i++) { - if ( - normalizedFileList[i].endsWith(fullSuffix) || - normalizedFileList[i].toLowerCase().endsWith(fullSuffix.toLowerCase()) - ) { - return allFileList[i]; - } - } - } - } - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts b/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts deleted file mode 100644 index 4c307cfd04..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/pass-cache.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { buildSuffixIndex, type SuffixIndex } from './utils.js'; - -/** - * Everything the standard `resolveTsTarget` path derives from one workspace - * file set: the file list, the lower-cased file list, the suffix index and the - * per-pass `resolveCache`. - * - * Without this memoization the resolver re-derived `allFileList` and - * `normalizedFileList` (both O(N_files)), rebuilt the index and threw away the - * `resolveCache` on every import — O(N_files × N_imports) total work for what - * should be O(N_files + N_imports). - */ -export interface ImportPassCache { - readonly allFilePaths: Set; - readonly allFileList: readonly string[]; - readonly normalizedFileList: readonly string[]; - readonly index: SuffixIndex; - readonly resolveCache: Map; -} - -/** - * Build that state. Shared by every adapter whose resolution runs through - * `resolveTsTarget`. - * - * Not a dedup of identical copies, and the difference is the point. At - * 49c5b7d81 each of those adapters carried this record inline and they did NOT - * agree: `languages/typescript/scope-resolver.ts` and - * `languages/vue/import-target.ts` held six byte-identical fields built around - * `index: buildSuffixIndex(normalizedFileList, allFileList)`, while - * `languages/javascript/import-target.ts` held five and never called - * `buildSuffixIndex` at all. That one missing field IS the O(imports × files) - * defect PR #2911 fixed — `resolveTsTarget` fell back to `suffixResolve`'s - * linear scan for every JavaScript import — and the header of - * `languages/javascript/import-target.ts` carries the measurements. Hoisting - * the builder is what makes a fourth adapter unable to omit it again: `index` - * is not optional on `ImportPassCache`. - * - * The BUILDER is shared; the MEMO deliberately is not. Each adapter wraps this - * in its own `perFileSet(...)`, so each gets its own `WeakMap`, its own index - * instance and — the one that would be a behaviour change — its own - * `resolveCache`. The languages disagree about what a specifier resolves to - * (`tsconfigPaths` is read from config for TypeScript and Vue, pinned to `null` - * for JavaScript, and the tried extension list differs), so one shared resolve - * cache across them would hand a language another language's answers. - * - * Sharing the builder is a code dedup and nothing more: it buys no runtime - * reuse, because there is none to buy. Each provider pass builds its own - * `allFilePaths` Set (`scope-resolution/pipeline/run.ts`, per provider), so - * TypeScript's set and JavaScript's set are different objects and therefore - * different `WeakMap` keys even where the two memos are the same code. - */ -export function buildImportPassCache(allFilePaths: ReadonlySet): ImportPassCache { - const allFileList = Array.from(allFilePaths); - // LOWERCASED, not slash-normalized — unlike every other caller of - // `buildSuffixIndex`. That is what `alreadyLowercased` below records. - const normalizedFileList = allFileList.map((f) => f.toLowerCase()); - return { - // Copied ONCE per file set, not once per import: `TsResolveContext` wants a - // mutable `Set` and the orchestrator hands us a `ReadonlySet`. The copy is - // not the #1918 hazard because the cache KEY is the caller's original Set. - allFilePaths: new Set(allFilePaths), - allFileList, - normalizedFileList, - // Every suffix of an all-lowercase path is itself lowercase, so the index's - // case-folded map came out a byte-for-byte copy of its exact map — same - // keys, same values, same insertion order — one per `ImportPassCache`, so - // once per adapter per pass. Measured 14.00 MiB at 32 000 paths, 29.8% of - // the retained `ImportPassCache`. The flag drops the copy; it does not change - // what `getInsensitive` answers, because the copy was the identity (see - // `SuffixIndexOptions`). Checked, not assumed: over 474 524 probes on four - // mixed-case corpora — Vue PascalCase plus alias specifiers, case-colliding - // twins, a 600-file deep monorepo, and Unicode paths carrying final sigma, - // dotted-I and sharp-S — the two maps came out byte-identical, the exact - // map was the sole answerer 0 times, and `get(s) || getInsensitive(s)` - // returned the same file 474 524 times out of 474 524. - index: buildSuffixIndex(normalizedFileList, allFileList, { alreadyLowercased: true }), - resolveCache: new Map(), - }; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts b/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts deleted file mode 100644 index 4caf748a78..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/resolver-factory.ts +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Import resolver factory — creates a composable import resolver from - * an ordered list of strategies. - * - * Mirrors the method-extractors/generic.ts and call-extractors/generic.ts - * pattern: declare a config per language, produce a runtime resolver via factory. - * - * Each strategy is tried in order. The first non-null result wins. - * A result with an empty `files` array is treated as "handled but unresolved" - * (stops the chain without producing import edges). - */ - -import type { ImportResolverFn, ImportResolutionConfig } from './types.js'; - -/** - * Create an ImportResolverFn from a declarative config. - * - * Chains strategies in declaration order — first non-null result wins. - * Returns null only if every strategy returns null. - * - * Error behaviour: if a strategy throws, the error propagates immediately - * and remaining strategies are not tried. Strategies are expected to be - * pure data transforms that never throw; any unexpected exception indicates - * a bug in the strategy implementation. - */ -export function createImportResolver(config: ImportResolutionConfig): ImportResolverFn { - const { strategies } = config; - return (rawImportPath, filePath, ctx) => { - for (const strategy of strategies) { - const result = strategy(rawImportPath, filePath, ctx); - if (result) return result; - } - return null; - }; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/rust.ts b/gitnexus/src/core/ingestion/import-resolvers/rust.ts deleted file mode 100644 index 41ac608cf6..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/rust.ts +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Rust module import resolution — internal helpers. - * - * Strategy lives in configs/rust.ts. - * This file contains shared helpers used by the strategy and standard.ts. - */ - -/** - * Resolve Rust use-path to a file (low-level helper). - * Handles crate::, super::, self:: prefixes and :: path separators. - */ -export function resolveRustImportInternal( - currentFile: string, - importPath: string, - allFiles: ReadonlySet, -): string | null { - let rustPath: string; - - if (importPath.startsWith('crate::')) { - // crate:: resolves from src/ directory (standard Rust layout) - rustPath = importPath.slice(7).replace(/::/g, '/'); - - // Try from src/ (standard layout) - const fromSrc = tryRustModulePath('src/' + rustPath, allFiles); - if (fromSrc) return fromSrc; - - // Try from repo root (non-standard) - const fromRoot = tryRustModulePath(rustPath, allFiles); - if (fromRoot) return fromRoot; - - return null; - } - - if (importPath.startsWith('super::')) { - // super:: = parent directory of current file's module - const currentDir = currentFile.split('/').slice(0, -1); - currentDir.pop(); // Go up one level for super:: - rustPath = importPath.slice(7).replace(/::/g, '/'); - const fullPath = [...currentDir, rustPath].join('/'); - return tryRustModulePath(fullPath, allFiles); - } - - if (importPath.startsWith('self::')) { - // self:: = current module's directory - const currentDir = currentFile.split('/').slice(0, -1); - rustPath = importPath.slice(6).replace(/::/g, '/'); - const fullPath = [...currentDir, rustPath].join('/'); - return tryRustModulePath(fullPath, allFiles); - } - - // Bare path without prefix (e.g., from a use in a nested module) - // Convert :: to / and try suffix matching - if (importPath.includes('::')) { - rustPath = importPath.replace(/::/g, '/'); - return tryRustModulePath(rustPath, allFiles); - } - - return null; -} - -/** - * Try to resolve a Rust module path to a file. - * Tries: path.rs, path/mod.rs, and with the last segment stripped - * (last segment might be a symbol name, not a module). - */ -export function tryRustModulePath( - modulePath: string, - allFiles: ReadonlySet, -): string | null { - // Try direct: path.rs - if (allFiles.has(modulePath + '.rs')) return modulePath + '.rs'; - // Try directory: path/mod.rs - if (allFiles.has(modulePath + '/mod.rs')) return modulePath + '/mod.rs'; - // Try path/lib.rs (for crate root) - if (allFiles.has(modulePath + '/lib.rs')) return modulePath + '/lib.rs'; - - // The last segment might be a symbol (function, struct, etc.), not a module. - // Strip it and try again. - const lastSlash = modulePath.lastIndexOf('/'); - if (lastSlash > 0) { - const parentPath = modulePath.substring(0, lastSlash); - if (allFiles.has(parentPath + '.rs')) return parentPath + '.rs'; - if (allFiles.has(parentPath + '/mod.rs')) return parentPath + '/mod.rs'; - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/standard.ts b/gitnexus/src/core/ingestion/import-resolvers/standard.ts deleted file mode 100644 index 4cc4c1c603..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/standard.ts +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Standard import path resolution. - * Handles relative imports, path alias rewriting, and generic suffix matching. - * Used as the fallback when language-specific resolvers don't match. - */ - -import type { SuffixIndex } from './utils.js'; -import { tryResolveWithExtensions, suffixResolve } from './utils.js'; -import { resolveRustImportInternal } from './rust.js'; -import { SupportedLanguages } from 'gitnexus-shared'; -import type { ImportResult, ImportResolverStrategy, ResolveCtx } from './types.js'; -import type { TsconfigPaths } from '../language-config.js'; - -/** Max entries in the resolve cache. Beyond this, entries are evicted. - * 100K entries ≈ 15MB — covers the most common import patterns. */ -export const RESOLVE_CACHE_CAP = 100_000; - -/** - * Resolve an import path to a file path in the repository. - * - * Language-specific preprocessing is applied before the generic resolution: - * - TypeScript/JavaScript: rewrites tsconfig path aliases - * - Rust: converts crate::/super::/self:: to relative paths - * - * Java wildcards and Go package imports are handled by the scope-resolution - * phase because they resolve to multiple files. - */ -export const resolveImportPath = ( - currentFile: string, - importPath: string, - allFiles: Set, - allFileList: readonly string[], - normalizedFileList: readonly string[], - resolveCache: Map, - language: SupportedLanguages, - tsconfigPaths: TsconfigPaths | null, - index?: SuffixIndex, -): string | null => { - const cacheKey = `${currentFile}::${importPath}`; - if (resolveCache.has(cacheKey)) return resolveCache.get(cacheKey) ?? null; - - const cache = (result: string | null): string | null => { - // Evict oldest 20% when cap is reached instead of clearing all - if (resolveCache.size >= RESOLVE_CACHE_CAP) { - const evictCount = Math.floor(RESOLVE_CACHE_CAP * 0.2); - const iter = resolveCache.keys(); - for (let i = 0; i < evictCount; i++) { - const key = iter.next().value; - if (key !== undefined) resolveCache.delete(key); - } - } - resolveCache.set(cacheKey, result); - return result; - }; - - // ---- TypeScript/JavaScript: rewrite path aliases ---- - if ( - (language === SupportedLanguages.TypeScript || language === SupportedLanguages.JavaScript) && - tsconfigPaths && - !importPath.startsWith('.') - ) { - for (const [aliasPrefix, targetPrefix] of tsconfigPaths.aliases) { - if (importPath.startsWith(aliasPrefix)) { - const remainder = importPath.slice(aliasPrefix.length); - // Build the rewritten path relative to baseUrl - const rewritten = - tsconfigPaths.baseUrl === '.' - ? targetPrefix + remainder - : tsconfigPaths.baseUrl + '/' + targetPrefix + remainder; - - // Try direct resolution from repo root - const resolved = tryResolveWithExtensions(rewritten, allFiles); - if (resolved) return cache(resolved); - - // ESM fallback: strip .js/.jsx/.mjs/.cjs and retry with TS equivalents - const strippedAlias = stripJsExtension(rewritten); - if (strippedAlias !== null) { - const esmResolved = tryResolveWithExtensions(strippedAlias, allFiles); - if (esmResolved) return cache(esmResolved); - } - - // Try suffix matching as fallback - const parts = rewritten.split('/').filter(Boolean); - const suffixResult = suffixResolve(parts, normalizedFileList, allFileList, index); - if (suffixResult) return cache(suffixResult); - } - } - } - - // ---- Rust: convert module path syntax to file paths ---- - if (language === SupportedLanguages.Rust) { - // Handle grouped imports: use crate::module::{Foo, Bar, Baz} - // Extract the prefix path before ::{...} and resolve the module, not the symbols - let rustImportPath = importPath; - const braceIdx = importPath.indexOf('::{'); - if (braceIdx !== -1) { - rustImportPath = importPath.substring(0, braceIdx); - } else if (importPath.startsWith('{') && importPath.endsWith('}')) { - // Top-level grouped imports: use {crate::a, crate::b} - // Iterate each part and return the first that resolves. This function returns a single - // string, so callers that need ALL edges must intercept before reaching here (the - // scope-resolution phase handles Rust grouped-import blocks). This fallback - // handles any path that reaches resolveImportPath directly. - const inner = importPath.slice(1, -1); - const parts = inner - .split(',') - .map((p) => p.trim()) - .filter(Boolean); - for (const part of parts) { - const partResult = resolveRustImportInternal(currentFile, part, allFiles); - if (partResult) return cache(partResult); - } - return cache(null); - } - - const rustResult = resolveRustImportInternal(currentFile, rustImportPath, allFiles); - if (rustResult) return cache(rustResult); - // Fall through to generic resolution if Rust-specific didn't match - } - - // ---- Generic relative import resolution (./ and ../) ---- - const currentDir = currentFile.split('/').slice(0, -1); - const parts = importPath.split('/'); - - for (const part of parts) { - if (part === '.') continue; - if (part === '..') { - currentDir.pop(); - } else { - currentDir.push(part); - } - } - - const basePath = currentDir.join('/'); - - if (importPath.startsWith('.')) { - const resolved = tryResolveWithExtensions(basePath, allFiles); - if (resolved) return cache(resolved); - - // TypeScript ESM: imports use .js/.jsx/.mjs/.cjs but source files are - // .ts/.tsx/.mts/.cts. Strip the JS-family extension and re-resolve. - if (language === SupportedLanguages.TypeScript || language === SupportedLanguages.JavaScript) { - const stripped = stripJsExtension(basePath); - if (stripped !== null) { - return cache(tryResolveWithExtensions(stripped, allFiles)); - } - } - - return cache(null); - } - - // ---- Generic package/absolute import resolution (suffix matching) ---- - // Java wildcards are handled by the scope-resolution phase, not here; this - // resolver returns null for `.*` so it never produces a single-file match. - if (importPath.endsWith('.*')) { - return cache(null); - } - - // C/C++ includes use actual file paths (e.g. "animal.h") — don't convert dots to slashes - const isCpp = language === SupportedLanguages.C || language === SupportedLanguages.CPlusPlus; - const pathLike = importPath.includes('/') || isCpp ? importPath : importPath.replace(/\./g, '/'); - const pathParts = pathLike.split('/').filter(Boolean); - - const resolved = suffixResolve(pathParts, normalizedFileList, allFileList, index); - return cache(resolved); -}; - -// ============================================================================ -// Per-language dispatch functions (moved from import-resolution.ts) -// ============================================================================ - -/** - * Standard single-file resolution (TS/JS/C/C++ and fallback for other languages). - * Handles relative imports, tsconfig path aliases, and suffix matching. - */ -export function resolveStandard( - rawImportPath: string, - filePath: string, - ctx: ResolveCtx, - language: SupportedLanguages, -): ImportResult { - const resolvedPath = resolveImportPath( - filePath, - rawImportPath, - ctx.allFilePaths, - ctx.allFileList, - ctx.normalizedFileList, - ctx.resolveCache, - language, - ctx.configs.tsconfigPaths, - ctx.index, - ); - return resolvedPath ? { kind: 'files', files: [resolvedPath] } : null; -} - -// ============================================================================ -// Strategy factory — composable hook for ImportResolutionConfig -// ============================================================================ - -/** Create a reusable standard-resolution strategy for a given language. */ -export function createStandardStrategy(language: SupportedLanguages): ImportResolverStrategy { - return (raw, fp, ctx) => resolveStandard(raw, fp, ctx, language); -} - -// ============================================================================ -// ESM extension helpers -// ============================================================================ - -/** JS-family extensions that TypeScript ESM maps to TS equivalents. */ -const JS_EXTENSION_PATTERN = /\.(js|jsx|mjs|cjs)$/; - -/** - * Strip a JS-family extension from a path, returning the stem. - * Returns `null` if the path does not end with a JS-family extension. - */ -export function stripJsExtension(path: string): string | null { - const match = JS_EXTENSION_PATTERN.exec(path); - return match ? path.slice(0, -match[0].length) : null; -} diff --git a/gitnexus/src/core/ingestion/import-resolvers/types.ts b/gitnexus/src/core/ingestion/import-resolvers/types.ts deleted file mode 100644 index 081972b77d..0000000000 --- a/gitnexus/src/core/ingestion/import-resolvers/types.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Import resolution types — shared across all per-language resolvers. - * - * Extracted from import-resolution.ts to co-locate types with their consumers. - */ - -import type { ImportConfigs } from '../language-config.js'; -import type { SuffixIndex } from './utils.js'; -import type { SupportedLanguages } from 'gitnexus-shared'; - -/** - * Result of resolving an import via language-specific dispatch. - * - 'files': resolved to one or more files -> add to ImportMap - * - 'package': resolved to a directory -> add graph edges + store dirSuffix in PackageMap - * - null: no resolution (external dependency, etc.) - */ -export type ImportResult = - | { kind: 'files'; files: string[] } - | { kind: 'package'; files: string[]; dirSuffix: string } - | null; - -/** Pre-built lookup structures for import resolution. Build once, reuse across chunks. */ -export interface ImportResolutionContext { - allFilePaths: Set; - allFileList: string[]; - normalizedFileList: string[]; - index: SuffixIndex; - resolveCache: Map; -} - -/** Full context for import resolution: file lookups + language configs. */ -export interface ResolveCtx extends ImportResolutionContext { - configs: ImportConfigs; -} - -/** Per-language import resolver -- function alias matching ExportChecker/CallRouter pattern. */ -export type ImportResolverFn = ( - rawImportPath: string, - filePath: string, - resolveCtx: ResolveCtx, -) => ImportResult; - -/** - * A single import resolution strategy — one step in a composable chain. - * Same signature as ImportResolverFn. Returns null to let the next strategy - * in the chain try; returns a result (even with empty files) to stop the chain. - */ -export type ImportResolverStrategy = ImportResolverFn; - -/** - * Declarative config for composable import resolution — mirrors the - * MethodExtractionConfig / CallExtractionConfig pattern. - * - * Each language declares an ordered list of strategies to try. - * The factory (`createImportResolver`) chains them: first non-null result wins. - */ -export interface ImportResolutionConfig { - /** - * Documentation-only metadata identifying which language this config serves. - * **Not used by `createImportResolver`** — the factory only iterates `strategies`. - * Useful for logging, debugging, and compile-time exhaustiveness checks when - * mapping `SupportedLanguages → ImportResolutionConfig` in language providers. - */ - readonly language: SupportedLanguages; - readonly strategies: readonly ImportResolverStrategy[]; -} diff --git a/gitnexus/src/core/ingestion/import-target-adapter.ts b/gitnexus/src/core/ingestion/import-target-adapter.ts deleted file mode 100644 index 80a5a265e5..0000000000 --- a/gitnexus/src/core/ingestion/import-target-adapter.ts +++ /dev/null @@ -1,124 +0,0 @@ -/** - * Bridge between CLI-package per-language `ImportResolverFn`s and the - * shared `FinalizeHooks.resolveImportTarget` contract - * (RFC §5.2; Ring 2 PKG #922). - * - * The shared finalize algorithm (#915) asks one question: - * - * resolveImportTarget(targetRaw, fromFile, workspaceIndex): string | null - * - * The CLI already has 16 language-specific resolvers satisfying a - * richer signature: - * - * ImportResolverFn(rawImportPath, filePath, resolveCtx): ImportResult - * - * This module builds a dispatch adapter — one FinalizeHook implementation - * that looks up the file's language from its path and delegates to the - * right per-language resolver. Callers package per-language resolvers + - * a shared `ResolveCtx` into an opaque `ImportTargetWorkspace` and pass - * it as `workspaceIndex` to `finalizeScopeModel`. - * - * ## What's deliberately NOT here - * - * - **Re-implementation of any per-language resolver.** We wrap the - * existing `importResolver` field on each `LanguageProvider` — the - * same code path the legacy DAG uses today. - * - **Dynamic-import handling.** The shared finalize algorithm short- - * circuits `ParsedImport { kind: 'dynamic-unresolved' }` before - * calling `resolveImportTarget`, so the adapter never sees those. - * - **`importPathPreprocessor`.** Preprocessing belongs inside the - * provider's `interpretImport` hook (which writes the final - * `ParsedImport.targetRaw`). By the time finalize passes a - * `targetRaw` to this adapter, it is the string the provider wants - * resolved verbatim. - */ - -import { - getLanguageFromFilename, - type SupportedLanguages, - type WorkspaceIndex, -} from 'gitnexus-shared'; -import type { ImportResolverFn, ImportResult, ResolveCtx } from './import-resolvers/types.js'; -import type { LanguageProvider } from './language-provider.js'; - -/** A single language's resolver bundled with the context it needs. */ -export interface LanguageResolverEntry { - readonly resolver: ImportResolverFn; - readonly ctx: ResolveCtx; -} - -/** - * The opaque `workspaceIndex` shape recognized by - * `resolveImportTargetAcrossLanguages`. Built once per ingestion run via - * `buildImportTargetWorkspace`, threaded through `finalizeScopeModel`. - */ -export interface ImportTargetWorkspace { - readonly perLanguage: ReadonlyMap; -} - -/** - * Build the workspace index from a map of language → provider. Providers - * whose `importResolver` is absent are silently skipped (no language will - * ever hit that branch at dispatch time). - * - * The `resolveCtx` is shared across all languages. Callers assemble it - * once per run (the existing pipeline already does this for the legacy - * DAG) and hand it to both the legacy resolution path and this factory. - */ -export function buildImportTargetWorkspace( - providers: ReadonlyMap, - resolveCtx: ResolveCtx, -): ImportTargetWorkspace { - const perLanguage = new Map(); - for (const [lang, provider] of providers) { - if (provider.importResolver === undefined) continue; - perLanguage.set(lang, { resolver: provider.importResolver, ctx: resolveCtx }); - } - return { perLanguage }; -} - -/** - * The FinalizeHooks-compatible implementation. Dispatches on `fromFile`'s - * extension → per-language resolver. Returns the first resolved file, - * or `null` if the resolver returns `null` or doesn't know about the - * language. - * - * Picks the first entry of `files[]` for both `'files'` and `'package'` - * result kinds — the legacy pipeline uses the whole array, but the - * shared `finalize()` hook contract is single-file. If the workspace - * later needs richer semantics (split-target packages), this is the - * single site to extend. - */ -export function resolveImportTargetAcrossLanguages( - targetRaw: string, - fromFile: string, - workspaceIndex: WorkspaceIndex, -): string | null { - const workspace = workspaceIndex as ImportTargetWorkspace | undefined; - if (workspace === undefined || workspace.perLanguage === undefined) return null; - - const lang = getLanguageFromFilename(fromFile); - if (lang === null) return null; - - const entry = workspace.perLanguage.get(lang); - if (entry === undefined) return null; - - let result: ImportResult; - try { - result = entry.resolver(targetRaw, fromFile, entry.ctx); - } catch { - // Existing resolvers can throw on malformed inputs (e.g., Python - // relative paths above the workspace root). Swallow — the shared - // algorithm treats a null here as `linkStatus: 'unresolved'`, which - // is the right fallback. - return null; - } - if (result === null) return null; - - // Both `files` and `package` variants expose a `files` array; the - // package variant also carries `dirSuffix` which we ignore at the - // FinalizeHook boundary (single-file contract). Legacy consumers - // continue to see the full result via `importResolver` directly. - const first = result.files[0]; - return first ?? null; -} diff --git a/gitnexus/src/core/ingestion/language-config.ts b/gitnexus/src/core/ingestion/language-config.ts index 1c8bafa03a..fdc3ea7bc5 100644 --- a/gitnexus/src/core/ingestion/language-config.ts +++ b/gitnexus/src/core/ingestion/language-config.ts @@ -21,12 +21,6 @@ export interface TsconfigPaths { baseUrl: string; } -/** Go module config parsed from go.mod */ -export interface GoModuleConfig { - /** Module path (e.g., "github.com/user/repo") */ - modulePath: string; -} - /** PHP Composer PSR-4 autoload config */ export interface ComposerConfig { /** Map of namespace prefix -> directory (e.g., "App\\" -> "app/") */ @@ -161,11 +155,7 @@ export interface CSharpProjectScan { readonly truncated: boolean; } -/** Project the one-pass {@link CSharpProjectScan} into the - * {@link CSharpNamespaceEvidence} both import-resolution legs thread to the - * #1881 gate — one shape, two carriers (`ImportConfigs.csharpNamespaces` for - * the legacy DAG, `CsharpResolutionConfig.namespaces` for the scope resolver). - * Keeps the field mapping in one place so the two carriers can't drift. */ +/** Project a workspace scan into the namespace evidence used by import resolution. */ export function csharpScanToEvidence(scan: CSharpProjectScan): CSharpNamespaceEvidence { return { declaredNamespaces: scan.declaredNamespaces, @@ -410,26 +400,6 @@ export async function loadTsconfigPaths(repoRoot: string): Promise { - try { - const goModPath = path.join(repoRoot, 'go.mod'); - const content = await fs.readFile(goModPath, 'utf-8'); - const match = content.match(/^module\s+(\S+)/m); - if (match) { - if (isDev) { - logger.info(`📦 Loaded Go module path: ${match[1]}`); - } - return { modulePath: match[1] }; - } - } catch { - // No go.mod - } - return null; -} - /** Parse composer.json to extract PSR-4 autoload mappings (including autoload-dev). */ export async function loadComposerConfig(repoRoot: string): Promise { try { @@ -466,9 +436,8 @@ const CSHARP_ROOT_NAMESPACE_RE = /\s*([^<]+)\s*<\/RootNamespace>/ // scanner shared with the scope-resolution namespace-siblings pass // (`extractCsharpStructureViaScanner`), not a bare regex: a regex matches // `namespace` inside comments and string literals, seeding the #1881 gate -// with phantom namespaces. Imported lazily (and memoized) so the always-on -// `loadImportConfigs` path — every repo, every language — doesn't eagerly -// pull tree-sitter-c-sharp in via `namespace-siblings.ts` → `query.ts`. +// with phantom namespaces. Imported lazily (and memoized) so loading unrelated +// configs does not pull tree-sitter-c-sharp in via namespace-siblings.ts. let csharpScannerFactoryPromise: Promise<() => CsharpStructureLineScanner> | undefined; function getCsharpStructureScannerFactory(): Promise<() => CsharpStructureLineScanner> { if (csharpScannerFactoryPromise === undefined) { @@ -1925,10 +1894,7 @@ export function zigPackageFor( * * Called from `ScopeResolver.loadResolutionConfig`, which the orchestrator runs * once per LANGUAGE workspace pass — so the walk happens only for repos that - * actually contain Zig. `loadImportConfigs`, which runs unconditionally for - * every repo, keeps calling `loadZigBuildConfig` for the root package alone; - * that is the same split TypeScript already has between the cheap - * `loadTsconfigPaths` and the repo-walking `loadTsconfigIndex`. + * actually contain Zig. */ export async function loadZigWorkspaceIndex(repoRoot: string): Promise { const dirs = await findZigPackageDirs(repoRoot); @@ -2611,45 +2577,3 @@ export function parseZigBuildZon(raw: string): ZigBuildZonConfig | null { } return { pathDeps }; } - -// ============================================================================ -// BUNDLED CONFIG LOADER -// ============================================================================ - -/** - * Bundled language-specific configs loaded once per ingestion run — the - * result of {@link loadImportConfigs}, and every field's type is declared - * above in this module. - * - * It lives here rather than in `import-resolvers/types.ts` (its consumer, via - * `ResolveCtx`) so the dependency runs one way: the import-resolver types - * import this bundle, and this module imports nothing from them. Homing the - * producer's result type with the producer also keeps `import-resolvers/ - * types.ts` free of per-language names. - */ -export interface ImportConfigs { - tsconfigPaths: TsconfigPaths | null; - goModule: GoModuleConfig | null; - composerConfig: ComposerConfig | null; - swiftPackageConfig: SwiftPackageConfig | null; - csharpConfigs: CSharpProjectConfig[]; - /** In-repo namespace evidence gating C# suffix-fallback resolution (#1881). */ - csharpNamespaces?: CSharpNamespaceEvidence; - /** Zig `.path` deps from build.zig.zon. Optional so call sites that - * hand-build ImportConfigs (tests) don't have to supply it. */ - zigBuildZon?: ZigBuildZonConfig | null; -} - -/** Load all language-specific configs once for an ingestion run. */ -export async function loadImportConfigs(repoRoot: string): Promise { - const csharpScan = await scanCSharpProject(repoRoot); - return { - tsconfigPaths: await loadTsconfigPaths(repoRoot), - goModule: await loadGoModulePath(repoRoot), - composerConfig: await loadComposerConfig(repoRoot), - swiftPackageConfig: await loadSwiftPackageConfig(repoRoot), - csharpConfigs: csharpScan.configs, - csharpNamespaces: csharpScanToEvidence(csharpScan), - zigBuildZon: await loadZigBuildConfig(repoRoot), - }; -} diff --git a/gitnexus/src/core/ingestion/language-provider.ts b/gitnexus/src/core/ingestion/language-provider.ts index c395dade73..e128174ded 100644 --- a/gitnexus/src/core/ingestion/language-provider.ts +++ b/gitnexus/src/core/ingestion/language-provider.ts @@ -35,7 +35,6 @@ import type { ExportChecker } from './export-detection.js'; import type { FieldExtractor } from './field-extractor.js'; import type { MethodExtractor } from './method-types.js'; import type { VariableExtractor } from './variable-types.js'; -import type { ImportResolverFn } from './import-resolvers/types.js'; import type { SyntaxNode } from './utils/ast-helpers.js'; import type { CfgVisitor } from './cfg/types.js'; import type { CollectedCfgs } from './cfg/collect.js'; @@ -366,8 +365,6 @@ interface LanguageProviderConfig { readonly typeConfig: LanguageTypeConfig; /** Export detection: is this AST node a public/exported symbol? */ readonly exportChecker: ExportChecker; - /** Import resolution: resolves raw import path to file system path */ - readonly importResolver: ImportResolverFn; // ── Calls & Imports (optional) ──────────────────────────────────── /** Call routing for languages that express imports/heritage as calls (e.g., Ruby). diff --git a/gitnexus/src/core/ingestion/languages/c-cpp.ts b/gitnexus/src/core/ingestion/languages/c-cpp.ts index c6e01ac6ef..d436fa4fde 100644 --- a/gitnexus/src/core/ingestion/languages/c-cpp.ts +++ b/gitnexus/src/core/ingestion/languages/c-cpp.ts @@ -17,8 +17,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as cCppConfig } from '../type-extractors/c-cpp.js'; import { cCppExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { cImportConfig, cppImportConfig } from '../import-resolvers/configs/c-cpp.js'; import { C_QUERIES, CPP_QUERIES } from '../tree-sitter-queries.js'; /** @@ -397,7 +395,6 @@ export const cProvider = defineLanguage({ `, typeConfig: cCppConfig, exportChecker: cCppExportChecker, - importResolver: createImportResolver(cImportConfig), callExtractor: createCallExtractor(cCallConfig), fieldExtractor: createFieldExtractor(cFieldConfig), methodExtractor: createMethodExtractor({ @@ -492,7 +489,6 @@ export const cppProvider = defineLanguage({ preprocessSource: stripUeMacros, typeConfig: cCppConfig, exportChecker: cCppExportChecker, - importResolver: createImportResolver(cppImportConfig), mroStrategy: 'leftmost-base', callExtractor: createCallExtractor(cppCallConfig), fieldExtractor: createFieldExtractor(cppFieldConfig), diff --git a/gitnexus/src/core/ingestion/languages/c/import-target.ts b/gitnexus/src/core/ingestion/languages/c/import-target.ts index 07f79df3c1..068041440f 100644 --- a/gitnexus/src/core/ingestion/languages/c/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/c/import-target.ts @@ -1,5 +1,5 @@ import { dirname, join } from 'path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { collapseRepoPath, nearestScope, diff --git a/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts index 60fbb085db..d74a4dc00e 100644 --- a/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/c/scope-resolver.ts @@ -13,7 +13,7 @@ import { } from './resolution-config.js'; import { expandCWildcardNames, isStaticName, clearStaticNames } from './static-linkage.js'; import { applyCStaticLinkageSideChannel } from './capture-side-channel.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * Per-pass memo of the augmented `#include`-resolution file set @@ -35,8 +35,7 @@ import { perFileSet } from '../../import-resolvers/per-file-set.js'; * byte-identical. The augmented set's IDENTITY is load-bearing downstream — * C++ delegates to `resolveCImportTarget`, whose `suffixIndex` memo is keyed on * exactly this set — so one memo shared across the two languages would hand - * each the other's index. Same builder-shared/memo-separate rule as - * `import-resolvers/pass-cache.ts`. + * each the other's index. Sharing a builder must not share its memo. */ const augmentedFilePathsFor = perFileSet((allFilePaths: ReadonlySet) => perFileSet((headerPaths: ReadonlySet): ReadonlySet => { diff --git a/gitnexus/src/core/ingestion/languages/c/static-linkage.ts b/gitnexus/src/core/ingestion/languages/c/static-linkage.ts index a81398354d..ebc461d39d 100644 --- a/gitnexus/src/core/ingestion/languages/c/static-linkage.ts +++ b/gitnexus/src/core/ingestion/languages/c/static-linkage.ts @@ -1,5 +1,5 @@ import type { ParsedFile, ScopeId, SymbolDefinition } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * Per-file set of function names declared with `static` storage class. diff --git a/gitnexus/src/core/ingestion/languages/cobol.ts b/gitnexus/src/core/ingestion/languages/cobol.ts index ea754f1e9a..08b5b66e5c 100644 --- a/gitnexus/src/core/ingestion/languages/cobol.ts +++ b/gitnexus/src/core/ingestion/languages/cobol.ts @@ -34,7 +34,6 @@ export const cobolProvider = defineLanguage({ extractParameter: () => null, }, exportChecker: () => false, - importResolver: () => null, rename: cobolRenameProvider, // Standalone source provider: program regions preserve paragraph fallthrough diff --git a/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts b/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts index 7b0bde4c41..d7901e7be4 100644 --- a/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts +++ b/gitnexus/src/core/ingestion/languages/cobol/copy-target.ts @@ -24,7 +24,7 @@ * per-name arrays, so a pass still scans the set once. */ import path from 'node:path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; const COPYBOOK_EXTENSIONS = new Set(['.cpy', '.copybook']); const COBOL_SOURCE_EXTENSIONS = new Set(['.cbl', '.cob', '.cobol']); diff --git a/gitnexus/src/core/ingestion/languages/cpp/captures.ts b/gitnexus/src/core/ingestion/languages/cpp/captures.ts index c8dd4075d8..7e69f9fb8f 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/captures.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/captures.ts @@ -224,6 +224,11 @@ export function emitCppScopeCaptures( } if (Object.keys(grouped).length === 0) continue; + if (grouped['@import.namespace-alias'] !== undefined) { + recordCppUsingDeclaration(filePath, grouped); + continue; + } + // ── Handle #include statements ────────────────────────────────── // `@import.statement` is captured directly on the `preproc_include` node. if (grouped['@import.statement'] !== undefined) { @@ -237,6 +242,19 @@ export function emitCppScopeCaptures( } } + const callable = nodeIfType( + nodeMap['@declaration.function'] ?? nodeMap['@declaration.method'], + 'function_definition', + ); + if (callable?.parent?.type === 'template_declaration') { + const parameters = callable.parent.childForFieldName('parameters'); + if (parameters !== null) + grouped['@declaration.type-parameters'] = nodeToCapture( + '@declaration.type-parameters', + parameters, + ); + } + // ── Handle using declarations (using namespace / using name) ──── // `@import.using-decl` is captured directly on the `using_declaration` node. if (grouped['@import.using-decl'] !== undefined) { @@ -606,6 +624,17 @@ export function emitCppScopeCaptures( grouped['@type-binding.type'] = nodeToCapture('@type-binding.type', fieldNode); delete grouped['@type-binding.assignment']; } + } else if (fnNode !== null && isCppQualifiedCallee(fnNode)) { + // auto x = rp::make() / auto x = rp::C() → bind the QUALIFIED + // callee, as `auto x = make()` binds `make` (the constructor rule + // in query.ts matches only a bare identifier callee). Left alone, + // the match bound `x` to the literal type `auto`. The resolver + // types `x` from the class the spelling names, or from the + // return type the callee's definition declares + // (ScopeResolver.splitQualifiedCallee). + grouped['@type-binding.constructor'] = anchor; + grouped['@type-binding.type'] = nodeToCapture('@type-binding.type', fnNode); + delete grouped['@type-binding.assignment']; } } } @@ -613,6 +642,17 @@ export function emitCppScopeCaptures( } } + // A prototype's return type (`D makeD();`) is a module-level fact only at + // namespace scope. In a function body the same syntax declares a + // block-scope function — the most vexing parse, `D x();` — and its binding + // would be hoisted to the module and type every undeclared `x` in the file. + // Only the prototype rules anchor `@type-binding.return` on a `declaration` + // (definitions anchor on `function_definition`, in-class prototypes on + // `field_declaration`), and the match carries nothing else, so it is dropped + // whole. + const prototypeReturn = nodeIfType(nodeMap['@type-binding.return'], 'declaration'); + if (prototypeReturn !== null && !isCppNamespaceScopeDeclaration(prototypeReturn)) continue; + const parameterNode = nodeMap['@type-binding.parameter']; const parameterCapture = grouped['@type-binding.parameter']; if (parameterNode !== undefined && parameterCapture !== undefined) { @@ -655,6 +695,48 @@ export function emitCppScopeCaptures( return out; } +/** + * A `qualified_identifier` callee naming a plain function or class — `rp::make`, + * `a::b::make`, `rp::C` — as opposed to a template call (`std::make_shared`, + * typed by its own rule in query.ts), an operator or a destructor. + */ +function isCppQualifiedCallee(node: SyntaxNode): boolean { + if (node.type !== 'qualified_identifier') return false; + let name = node.childForFieldName('name'); + while (name !== null && name.type === 'qualified_identifier') { + name = name.childForFieldName('name'); + } + return name !== null && name.type === 'identifier'; +} + +/** Nodes a namespace-scope declaration may sit inside without leaving namespace + * scope: preprocessor conditionals (include guards nest every declaration of a + * guarded header in one), single-declaration `extern "C"`, and a `template` + * prefix. */ +const CPP_NAMESPACE_SCOPE_WRAPPERS: ReadonlySet = new Set([ + 'preproc_if', + 'preproc_ifdef', + 'preproc_else', + 'preproc_elif', + 'preproc_elifdef', + 'linkage_specification', + 'template_declaration', +]); + +/** + * Is `node` declared at namespace scope — directly in the translation unit or in + * a namespace / `extern "C" {}` body (`declaration_list`), through any number of + * {@link CPP_NAMESPACE_SCOPE_WRAPPERS}? A function body, class body, friend + * declaration or anything else on the way up answers no. + */ +function isCppNamespaceScopeDeclaration(node: SyntaxNode): boolean { + for (let parent = node.parent; parent !== null; parent = parent.parent) { + if (parent.type === 'translation_unit' || parent.type === 'declaration_list') return true; + if (!CPP_NAMESPACE_SCOPE_WRAPPERS.has(parent.type)) return false; + } + return false; +} + /** Prototype and nested function-pointer parameter names do not bind the body. */ function isCppLexicalParameter(node: SyntaxNode): boolean { for (let parent = node.parent; parent !== null; parent = parent.parent) { diff --git a/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts b/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts index e11f32b8d4..cfa83a9f0c 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/file-local-linkage.ts @@ -1,5 +1,5 @@ import type { ParsedFile, Scope, ScopeId, SymbolDefinition } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { isCppInlineNamespaceScope } from './inline-namespaces.js'; /** diff --git a/gitnexus/src/core/ingestion/languages/cpp/inline-namespaces.ts b/gitnexus/src/core/ingestion/languages/cpp/inline-namespaces.ts index 47f76d845e..5c02d84fa6 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/inline-namespaces.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/inline-namespaces.ts @@ -29,7 +29,8 @@ * declaration transparently. */ -import type { Callsite, ParsedFile, ScopeId, SymbolDefinition } from 'gitnexus-shared'; +import type { Callsite, ParsedFile, ScopeId, SymbolDefinition, TypeRef } from 'gitnexus-shared'; +import { isCppNamespaceQualifierShadowed } from './qualified-name-claims.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import { isOverloadAmbiguousAfterNormalization, @@ -182,6 +183,7 @@ interface QualifiedNsMemberIndex { * for are ever materialized, which is what keeps the deep-chain case linear. */ readonly membersByReceiver: Map>; + readonly ownerScopeByDefId: ReadonlyMap; } /** One `Namespace` scope as the qualified-lookup walk sees it. */ @@ -271,6 +273,7 @@ interface MemoizedIndex { * pairs it already found. */ function buildQualifiedNsMemberIndex(parsedFiles: readonly ParsedFile[]): QualifiedNsMemberIndex { const rootsByReceiver = new Map(); + const ownerScopeByDefId = new Map(); for (const parsed of parsedFiles) { const nodesByScope = new Map(); @@ -278,6 +281,8 @@ function buildQualifiedNsMemberIndex(parsedFiles: readonly ParsedFile[]): Qualif for (const sc of parsed.scopes) { if (sc.kind !== 'Namespace') continue; const node: MutableNsNode = { ownMembers: bucketOwnMembers(sc), inlineChildren: [] }; + for (const definitions of node.ownMembers.values()) + for (const definition of definitions) ownerScopeByDefId.set(definition.nodeId, sc.id); nodesByScope.set(sc.id, node); namespaces.push([sc, node]); } @@ -299,7 +304,7 @@ function buildQualifiedNsMemberIndex(parsedFiles: readonly ParsedFile[]): Qualif roots.push(node); } } - return { rootsByReceiver, membersByReceiver: new Map() }; + return { rootsByReceiver, membersByReceiver: new Map(), ownerScopeByDefId }; } /** Bucket a namespace scope's own callable `ownedDefs` by member simple name. @@ -450,10 +455,50 @@ export function resolveCppQualifiedNamespaceMember( receiverName: string, memberName: string, parsedFiles: readonly ParsedFile[], - _scopes: ScopeResolutionIndexes, + scopes: ScopeResolutionIndexes, callsite?: Callsite, + callerScope?: ScopeId, ): SymbolDefinition | 'ambiguous' | undefined { - const allHits = qualifiedNsMembers(qualifiedNsMemberIndex(parsedFiles), receiverName, memberName); + const index = qualifiedNsMemberIndex(parsedFiles); + const qualifier = receiverName.replace(/^::/, '').replace(/::/g, '.'); + const qualified = receiverName.includes('::'); + const receiver = qualifier.slice(qualifier.lastIndexOf('.') + 1); + let allHits = qualifiedNsMembers(index, receiver, memberName); + if (qualified) { + const prefixes: string[] = []; + let cursor = callerScope === undefined ? undefined : scopes.scopeTree.getScope(callerScope); + const visited = new Set(); + while (cursor !== undefined && !visited.has(cursor.id)) { + visited.add(cursor.id); + if (cursor.kind === 'Namespace') { + const definition = findNamespaceDefInScope(cursor); + if (definition !== undefined) prefixes.unshift(simpleNameOf(definition)); + } + cursor = cursor.parent === null ? undefined : scopes.scopeTree.getScope(cursor.parent); + } + const keys = new Set([qualifier]); + if (!receiverName.startsWith('::')) + for (let length = prefixes.length; length > 0; length--) + keys.add([...prefixes.slice(0, length), qualifier].join('.')); + allHits = allHits.filter((definition) => { + if (definition.namespacePrefix !== undefined && keys.has(definition.namespacePrefix)) + return true; + const transparent: string[] = []; + let id = index.ownerScopeByDefId.get(definition.nodeId); + const seen = new Set(); + while (id !== undefined && !seen.has(id)) { + seen.add(id); + const scope = scopes.scopeTree.getScope(id); + if (scope === undefined) break; + if (scope.kind === 'Namespace' && !isCppInlineNamespaceScope(id)) { + const namespace = findNamespaceDefInScope(scope); + if (namespace !== undefined) transparent.unshift(simpleNameOf(namespace)); + } + id = scope.parent ?? undefined; + } + return keys.has(transparent.join('.')); + }); + } if (allHits.length === 0) return undefined; if (allHits.length === 1) return allHits[0]; @@ -476,6 +521,47 @@ export function resolveCppQualifiedNamespaceMember( return 'ambiguous'; } +/** + * `ScopeResolver.splitQualifiedCallee` for C++: the receiver/member pair the + * qualified-call captures produce for a callee spelling, so + * {@link resolveCppQualifiedNamespaceMember} answers it exactly as it answers + * the call. The full written qualifier is retained + * (`a::b::make()` → `a::b` / `make`) so another outer namespace cannot supply + * the result type. Separators inside template + * arguments are not split points (`ns::Box::make` → `ns::Box` / `make`, + * which names no namespace and resolves nothing). Unqualified → `undefined`. + */ +export function splitCppQualifiedCallee( + callee: string, + callerScope?: ScopeId, + scopes?: ScopeResolutionIndexes, + position?: TypeRef['lookupPosition'], +): { readonly receiver: string; readonly member: string } | undefined { + if (callerScope !== undefined && scopes !== undefined && !/^\s*::/.test(callee)) { + const root = callee.trim().split('::')[0]?.trim(); + if (root !== undefined) { + if (isCppNamespaceQualifierShadowed(root, callerScope, scopes, position)) return undefined; + } + } + const separators: number[] = []; + let angleDepth = 0; + for (let i = 0; i < callee.length; i++) { + const ch = callee[i]; + if (ch === '<') angleDepth++; + else if (ch === '>') { + if (angleDepth > 0) angleDepth--; + } else if (angleDepth === 0 && ch === ':' && callee[i + 1] === ':') { + separators.push(i); + i++; + } + } + const last = separators[separators.length - 1]; + if (last === undefined) return undefined; + const receiver = callee.slice(0, last).trim(); + const member = callee.slice(last + 2).trim(); + return receiver.length > 0 && member.length > 0 ? { receiver, member } : undefined; +} + function findNamespaceDefInScope(scope: { readonly ownedDefs: readonly SymbolDefinition[]; }): SymbolDefinition | undefined { diff --git a/gitnexus/src/core/ingestion/languages/cpp/interpret.ts b/gitnexus/src/core/ingestion/languages/cpp/interpret.ts index 774080965f..7e68f16d80 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/interpret.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/interpret.ts @@ -35,6 +35,9 @@ export function interpretCppImport(captures: CaptureMatch): ParsedImport | null return { kind: 'wildcard', targetRaw: source, isSystem }; } +/** Placeholder type specifiers: the declared type is deduced, never named. */ +const CPP_PLACEHOLDER_TYPES: ReadonlySet = new Set(['auto', 'decltype(auto)']); + /** * Interpret a C++ type-binding capture into a ParsedTypeBinding. * @@ -51,6 +54,12 @@ export function interpretCppTypeBinding(captures: CaptureMatch): ParsedTypeBindi const name = captures['@type-binding.name']?.text; const type = captures['@type-binding.type']?.text; if (name === undefined || type === undefined) return null; + // `auto` names no type: the deduced type is whatever the initializer yields, + // which the specific rules (constructor, alias, member access, qualified + // callee) capture directly. What reaches here as `auto` is a leftover — + // `auto n = 5;`, `[](auto v)` — and binding it records the literal type name + // `auto`, which types nothing and hides the variable from every other route. + if (CPP_PLACEHOLDER_TYPES.has(type.trim())) return null; let source: TypeRef['source'] = 'annotation'; @@ -85,17 +94,24 @@ export function interpretCppTypeBinding(captures: CaptureMatch): ParsedTypeBindi // A member field's type is captured AS WRITTEN, qualifier and all // (`ns::Repo`), because the query matches the outer // `qualified_identifier` — one depth-agnostic pattern per declarator shape - // instead of one per qualifier depth. The qualifier is dropped HERE; see the - // "Field type, QUALIFIED" block in query.ts for why the qualified spelling - // resolves to nothing and the tail resolves like the bare one. + // instead of one per qualifier depth. // - // FIELDS ONLY. `@type-binding.parameter` and `@type-binding.assignment` also - // capture qualified spellings (their patterns use `type: (_)`), and reducing - // THOSE would newly bind every qualified local and parameter in the workspace - // — a far wider change than the member-field miss this closes, and not one - // anything here has measured. + // A NON-GENERIC qualified member (`a::Config cfg;`) keeps its qualifier, like + // a qualified local or parameter: the resolver matches the qualifier against + // the candidate's namespace (`ScopeResolver.resolveQualifiedTypeSpellings`). + // Its tail bound the NEAREST `Config` — inside a `namespace b` that declares + // one, `cfg.m()` reached `b::Config::m`, a confident wrong edge. + // + // A GENERIC qualified member is still reduced to its tail, here, because the + // template-argument match that picks a specialization (`Repo` over the + // primary `Repo`) keys on the bare base name; the qualified route is + // argument-blind and would refuse wherever a specialization exists. See the + // "Field type, QUALIFIED" block in query.ts. That keeps the tail hazard for + // generic members, and only for them. const effectiveType = - captures['@type-binding.field'] === undefined ? type : cppQualifiedTail(type); + captures['@type-binding.field'] !== undefined && type.includes('<') + ? cppQualifiedTail(type) + : type; // The reduced spelling is also the AS-WRITTEN one, and saying so is load // bearing. `collectTypeBindings` derives `TypeRef.declaredSpelling` from // `@type-binding.type` whenever that text differs from `rawTypeName`, and it diff --git a/gitnexus/src/core/ingestion/languages/cpp/qualified-name-claims.ts b/gitnexus/src/core/ingestion/languages/cpp/qualified-name-claims.ts new file mode 100644 index 0000000000..77d2f3312b --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/cpp/qualified-name-claims.ts @@ -0,0 +1,42 @@ +import type { Range, ScopeId } from 'gitnexus-shared'; +import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; +import { bindsTypeParameter, isClassLike } from '../../scope-resolution/scope/walkers.js'; + +/** Check lexical owners, excluding the finalize channel's hoisted declarations. */ +export function isCppNamespaceQualifierShadowed( + name: string, + inScope: ScopeId, + indexes: ScopeResolutionIndexes, + position?: Pick, +): boolean { + if (bindsTypeParameter(inScope, name, indexes)) return true; + const seen = new Set(); + let id: ScopeId | null = inScope; + while (id !== null && !seen.has(id)) { + seen.add(id); + const scope = indexes.scopeTree.getScope(id); + if (scope === undefined) break; + if ( + scope.bindings.get(name)?.some((binding) => { + if ( + !isClassLike(binding.def.type) && + binding.def.type !== 'Typedef' && + binding.def.type !== 'TypeAlias' + ) + return false; + const at = + binding.availableFrom ?? binding.declarationRange ?? binding.def.declarationRange; + return ( + position === undefined || + at === undefined || + scope.kind === 'Class' || + at.startLine < position.startLine || + (at.startLine === position.startLine && at.startCol <= position.startCol) + ); + }) + ) + return true; + id = scope.parent; + } + return false; +} diff --git a/gitnexus/src/core/ingestion/languages/cpp/query.ts b/gitnexus/src/core/ingestion/languages/cpp/query.ts index 7b708b60b8..2f124a195f 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/query.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/query.ts @@ -264,6 +264,10 @@ const CPP_SCOPE_QUERY = ` (type_definition declarator: (type_identifier) @declaration.name) @declaration.typedef +(namespace_alias_definition + name: (namespace_identifier) @import.name + . (_) @import.source) @import.namespace-alias @import.statement + ;; ─── Declarations — type alias (using Name = Type) ────────────────── (alias_declaration name: (type_identifier) @declaration.name) @declaration.typedef @@ -383,6 +387,17 @@ const CPP_SCOPE_QUERY = ` type: (template_type) @type-binding.type declarator: (identifier) @type-binding.name) @type-binding.annotation +;; Covers: rp::C x; std::vector users; +;; A QUALIFIED type is a qualified_identifier wrapping the type_identifier or +;; template_type, so the two rules above never matched it and rp::C x; bound +;; nothing — the receiver of x.m() was untyped. Matched on the OUTER node, one +;; pattern per declarator shape like the qualified field rules below (depth- and +;; genericity-agnostic, no alternation). The spelling is kept as written and +;; resolved by the qualifier-aware route (resolveQualifiedTypeSpellings). +(declaration + type: (qualified_identifier) @type-binding.type + declarator: (identifier) @type-binding.name) @type-binding.annotation + ;; ─── Type bindings — pointer variable declaration ─────────────────── ;; Covers: User* ptr = new User() (declaration @@ -391,6 +406,13 @@ const CPP_SCOPE_QUERY = ` declarator: (pointer_declarator declarator: (identifier) @type-binding.name))) @type-binding.annotation +;; Covers: rp::C* ptr = nullptr; (the qualified twin of the rule above) +(declaration + type: (qualified_identifier) @type-binding.type + declarator: (init_declarator + declarator: (pointer_declarator + declarator: (identifier) @type-binding.name))) @type-binding.annotation + ;; ─── Type bindings — auto + constructor call ──────────────────────── ;; Covers: auto user = User("alice") ;; AST: declaration > placeholder_type_specifier/auto > init_declarator > identifier + call_expression > identifier @@ -414,13 +436,18 @@ const CPP_SCOPE_QUERY = ` ;; ─── Type bindings — auto + scoped brace-init (qualified) ─────────── ;; Covers: auto client = ns::HttpClient{} ;; AST: compound_literal_expression > qualified_identifier > type_identifier +;; The WHOLE qualified spelling is captured, not its tail: \`ns::HttpClient\` is +;; resolved by the qualifier-aware route (\`resolveQualifiedTypeSpellings\`), +;; while the tail \`HttpClient\` bound whichever same-named class was nearer — a +;; global one through another include, or the enclosing namespace's own +;; (\`auto x = a::Config{}\` inside a \`namespace b\` declaring Config). Matching +;; the outer node is also depth-agnostic (\`a::b::T{}\`). (declaration type: (placeholder_type_specifier) declarator: (init_declarator declarator: (identifier) @type-binding.name value: (compound_literal_expression - type: (qualified_identifier - name: (type_identifier) @type-binding.type)))) @type-binding.constructor + type: (qualified_identifier) @type-binding.type))) @type-binding.constructor ;; ─── Type bindings — auto + new expression ────────────────────────── ;; Covers: auto user = new User(name) @@ -488,20 +515,43 @@ const CPP_SCOPE_QUERY = ` ;; Covers: User getUser() { ... } ;; AST: function_definition > type_identifier + function_declarator > identifier (function_definition - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (function_declarator declarator: (identifier) @type-binding.name)) @type-binding.return ;; Return type — out-of-class method: User Class::getUser() { ... } (function_definition - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (function_declarator declarator: (qualified_identifier name: (identifier) @type-binding.name))) @type-binding.return ;; Return type — pointer return: User* getUser() { ... } (function_definition - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type + declarator: (pointer_declarator + declarator: (function_declarator + declarator: (identifier) @type-binding.name))) @type-binding.return + +;; ─── Type bindings — free-function PROTOTYPE return type ───────────── +;; Covers: D makeD(); D* makeDp(); namespace rp { C make(); } +;; The usual layout is "header declares, .cpp defines", and a .cpp is never +;; included — so the header prototype is the only return-type fact an includer +;; can see. Only definitions carried one, which left \`auto x = makeD(); x.m()\` +;; and \`makeD().m()\` untyped in every file that merely includes the header. +;; Inside a function body the same syntax declares a BLOCK-scope function (the +;; most vexing parse, \`D x();\`), whose binding would be hoisted to the module +;; like any return type; captures.ts keeps only the matches at namespace scope +;; (isCppNamespaceScopeDeclaration). A reference return (\`D& f();\`) has no +;; rule here because such a function is not declared as a Function at all. +(declaration + type: [(type_identifier) (qualified_identifier)] @type-binding.type + declarator: (function_declarator + declarator: (identifier) @type-binding.name)) @type-binding.return + +;; Prototype pointer return: D* makeDp(); +(declaration + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @type-binding.name))) @type-binding.return @@ -509,13 +559,13 @@ const CPP_SCOPE_QUERY = ` ;; ─── Type bindings — inline method return type ────────────────────── ;; Covers: class Foo { User getUser() { ... } }; (function_definition - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (function_declarator declarator: (field_identifier) @type-binding.name)) @type-binding.return ;; Inline method pointer return type: class Foo { User* lookup(int) { ... } }; (function_definition - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (pointer_declarator declarator: (function_declarator declarator: (field_identifier) @type-binding.name))) @type-binding.return @@ -524,13 +574,13 @@ const CPP_SCOPE_QUERY = ` ;; Covers: class User { User* lookup(int); std::string getName(); }; ;; AST: field_declaration > function_declarator > field_identifier (field_declaration - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (function_declarator declarator: (field_identifier) @type-binding.name)) @type-binding.return ;; Method prototype pointer return type: User* lookup(int id); (field_declaration - type: (type_identifier) @type-binding.type + type: [(type_identifier) (qualified_identifier)] @type-binding.type declarator: (pointer_declarator declarator: (function_declarator declarator: (field_identifier) @type-binding.name))) @type-binding.return @@ -599,18 +649,16 @@ const CPP_SCOPE_QUERY = ` ;; a single node type in the field position, not an alternation — the ;; tree-sitter 0.21 hazard this repo has been bitten by before. ;; -;; The QUALIFIER IS THEN DROPPED, by cppQualifiedTail in interpret.ts, not -;; here — and dropping it was measured rather than assumed. Recording -;; ns::Repo resolves to NOTHING: findClassBindingInScope's dotted-tail -;; fallback splits on "." and C++ writes "::", and resolveClassBindingForName's -;; generic branch then looks up the base ns::Repo, which is not a key either -;; because C++ emits no @declaration.qualified_name and indexes ns::Repo under -;; Repo. Reducing to the tail lands on exactly the path the BARE spelling -;; already takes — one class-like match or decline — so a qualified member field -;; behaves like the bare one instead of like nothing. A tail that names no -;; workspace class (std::string with no "class string" in the repo) binds -;; nothing and emits nothing, which is why this is a miss-closing change rather -;; than an edge-fabricating one. +;; For a GENERIC member the QUALIFIER IS THEN DROPPED, by cppQualifiedTail in +;; interpret.ts, not here. resolveClassBindingForName's template-argument match +;; (the one that prefers a Repo specialization over the primary Repo) +;; looks up the BASE name, and C++ indexes ns::Repo under Repo, so only the tail +;; reaches it. A NON-GENERIC member keeps its qualifier and resolves through the +;; qualifier-aware route (ScopeResolver.resolveQualifiedTypeSpellings): its tail +;; bound the NEAREST same-named class, which inside a namespace declaring its +;; own Config made a::Config cfg; type cfg as that one. A qualified spelling +;; that names no workspace class (std::string with no namespace std in the +;; repo) binds nothing and emits nothing. ;; ;; Like the six above, each requires the declarator to reach the field_identifier ;; DIRECTLY, so a method whose return type is qualified (ns::Thing method();) diff --git a/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts index 8dc8752d80..5af2985662 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/scope-resolver.ts @@ -1,4 +1,4 @@ -import type { ParsedFile, SymbolDefinition } from 'gitnexus-shared'; +import type { ParsedFile, SymbolDefinition, TypeRef } from 'gitnexus-shared'; import { findClassBindingInScope, findEnclosingClassDef, @@ -44,6 +44,7 @@ import { clearCppInlineNamespaces, populateCppInlineNamespaceScopes, resolveCppQualifiedNamespaceMember, + splitCppQualifiedCallee, } from './inline-namespaces.js'; import { populateCppRangeBindings } from './range-bindings.js'; import { cppConstraintCompatibility } from './constraint-filter.js'; @@ -57,11 +58,12 @@ import { resolveCppReceiverMember, } from './member-lookup.js'; import { stripCppSpecifiers } from './interpret.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { clearCppUsingDeclarations, populateCppIncludedUsingClaims, populateCppUsingBindings, + cppQualifiedTypeLookupSpelling, } from './using-bindings.js'; /** A pointee worth binding: a bare identifier, not `T**`, `T[]`, `A::B` or a @@ -85,8 +87,8 @@ const CPP_SIMPLE_POINTEE_RE = /^[A-Za-z_]\w*$/; * (Twin of the C resolver's `augmentedFilePathsFor`.) The two memos stay * SEPARATE deliberately. C++ delegates to `resolveCImportTarget`, whose * `suffixIndex` memo is keyed on the augmented set, so a single memo shared - * with C would hand each language the other's index — same - * builder-shared/memo-separate rule as `import-resolvers/pass-cache.ts`. + * with C would hand each language the other's index. Sharing a builder must + * not share its memo. */ const augmentedFilePathsFor = perFileSet((allFilePaths: ReadonlySet) => perFileSet((headerPaths: ReadonlySet): ReadonlySet => { @@ -231,6 +233,26 @@ export const cppScopeResolver: ScopeResolver = { }, populateNamespaceSiblings: (parsedFiles, indexes) => { + // Name-keyed return facts cannot choose between free overloads whose + // return types differ. Keep their declaration identities, drop the guess. + for (const parsed of parsedFiles) { + for (const scope of parsed.scopes) { + if (scope.kind !== 'Module' && scope.kind !== 'Namespace') continue; + const returns = new Map>(); + for (const definition of scope.ownedDefs) { + if (definition.type !== 'Function' || definition.qualifiedName === undefined) continue; + const name = definition.qualifiedName.slice( + definition.qualifiedName.lastIndexOf('.') + 1, + ); + const types = returns.get(name) ?? new Set(); + types.add(definition.returnType); + returns.set(name, types); + } + for (const [name, types] of returns) + if (types.size > 1 && scope.typeBindings.get(name)?.source === 'return-annotation') + (scope.typeBindings as Map).delete(name); + } + } populateCppUsingBindings(parsedFiles, indexes); populateCppIncludedOverloads(indexes); }, @@ -321,12 +343,18 @@ export const cppScopeResolver: ScopeResolver = { conversionOnlyArgTypePrefixes: CPP_CONVERSION_ONLY_ARG_TYPE_PREFIXES, // Range-for element type inference: for (auto& user : users) → bind user to User populateRangeBindings: populateCppRangeBindings, - // C++ method return-type bindings need to be visible from module scope - // for cross-file propagation and compound-receiver chain resolution. - // cppBindingScopeFor hoists @type-binding.return to Module scope. - hoistTypeBindingsToModule: true, + // Return bindings stay with their declaring class or namespace. An absent + // method fact must not borrow a same-name free function's return type. // Enable receiver-bound explicit-`this` fallback only for C++. resolveThisViaEnclosingClass: true, + // `rp::C x`, `void f(a::Config c)`: the capture keeps the qualifier, and + // neither `#include` (no namespace handle) nor the index (`rp::C` keyed as + // `C`) lets the shared receiver lookups read it. Resolve it the way a + // qualified base class already resolves — qualifier matched against the + // candidate's namespace, refuse on a tie — rather than by its tail, which + // binds the nearer same-named class the qualifier was written to exclude. + resolveQualifiedTypeSpellings: true, + qualifiedTypeLookupSpelling: cppQualifiedTypeLookupSpelling, resolveReceiverMember: resolveCppReceiverMember, // The `isFileLocalDef` hook on the global free-call fallback names // file-local linkage historically, but semantically gates "logically @@ -396,9 +424,38 @@ export const cppScopeResolver: ScopeResolver = { resolveQualifiedReceiverMember: ( receiverName, memberName, - _callerScope, + callerScope, scopes, parsedFiles, callsite, - ) => resolveCppQualifiedNamespaceMember(receiverName, memberName, parsedFiles, scopes, callsite), + ) => + resolveCppQualifiedNamespaceMember( + receiverName, + memberName, + parsedFiles, + scopes, + callsite, + callerScope, + ), + // `auto x = rp::make(); x.m()` / `rp::make().m()`: map the callee text back + // onto the receiver/member pair the call capture used, so the hook above + // answers the factory's definition the way it answered the call. + splitQualifiedCallee: (callee, callerScope, scopes, position) => { + // The namespace-member resolver does not bind aliases. Decline instead + // of treating an alias as an unrelated namespace with the same name. + if ( + callerScope !== undefined && + cppQualifiedTypeLookupSpelling( + { + rawName: callee, + declaredAtScope: callerScope, + source: 'assignment-inferred', + lookupPosition: position, + }, + scopes, + ) !== undefined + ) + return undefined; + return splitCppQualifiedCallee(callee, callerScope, scopes, position); + }, }; diff --git a/gitnexus/src/core/ingestion/languages/cpp/simple-hooks.ts b/gitnexus/src/core/ingestion/languages/cpp/simple-hooks.ts index 63500abd53..3dfb3e62dd 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/simple-hooks.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/simple-hooks.ts @@ -21,17 +21,15 @@ export function cppBindingScopeFor( innermost: Scope, tree: ScopeTree, ): ScopeId | null { - // Hoist return-type bindings to Module scope so: - // 1. propagateImportedReturnTypes can mirror them across files - // 2. compound-receiver can find method return types via hoistTypeBindingsToModule + // Keep each callable's return fact with its declaring owner. In particular, + // a free prototype must not overwrite a same-name method's return type. if (decl['@type-binding.return'] !== undefined) { - let cur: Scope | undefined = innermost; - while (cur !== undefined && cur.kind !== 'Module') { - const parentId: ScopeId | null = cur.parent ?? null; - if (parentId === null) break; - cur = tree.getScope(parentId); + let current: Scope | undefined = innermost; + while (current !== undefined) { + if (current.kind === 'Class' || current.kind === 'Namespace' || current.kind === 'Module') + return current.id; + current = current.parent === null ? undefined : tree.getScope(current.parent); } - if (cur !== undefined && cur.kind === 'Module') return cur.id; } return null; // default auto-hoist for other bindings } diff --git a/gitnexus/src/core/ingestion/languages/cpp/using-bindings.ts b/gitnexus/src/core/ingestion/languages/cpp/using-bindings.ts index 5874c116f4..c1414ed1d4 100644 --- a/gitnexus/src/core/ingestion/languages/cpp/using-bindings.ts +++ b/gitnexus/src/core/ingestion/languages/cpp/using-bindings.ts @@ -8,14 +8,18 @@ import type { Range, Scope, ScopeId, + TypeRef, } from 'gitnexus-shared'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; +import { findClassBindingInScope, isClassLike } from '../../scope-resolution/scope/walkers.js'; import { isCppInlineNamespaceScope } from './inline-namespaces.js'; +import { isCppNamespaceQualifierShadowed } from './qualified-name-claims.js'; /** Namespace lookup facts, deliberately distinct from preprocessor file imports. */ export interface CppUsingDeclaration { readonly namespace: string; readonly name?: string; + readonly alias?: string; readonly range: Range; } @@ -35,7 +39,12 @@ export function recordCppUsingDeclaration(filePath: string, capture: CaptureMatc if (namespace === undefined || range === undefined) return; const name = capture['@import.name']?.text; const declarations = declarationsByFile.get(filePath) ?? []; - declarations.push({ namespace, range, ...(name === undefined ? {} : { name }) }); + const alias = capture['@import.namespace-alias'] === undefined ? undefined : name; + declarations.push({ + namespace, + range, + ...(alias === undefined ? (name === undefined ? {} : { name }) : { alias }), + }); declarationsByFile.set(filePath, declarations); } @@ -92,7 +101,7 @@ export function attachCppUsingClaims(captures: CaptureMatch[], filePath: string) byOwner.set(owner.match, claims); }; for (const declaration of collectCppUsingDeclarations(filePath)) { - if (declaration.name === undefined) continue; + if (declaration.alias !== undefined || declaration.name === undefined) continue; add({ name: declaration.name, range: declaration.range, @@ -276,6 +285,7 @@ export function populateCppIncludedUsingClaims( for (const parsed of parsedFiles) { const declarations = usingDeclarations(parsed).filter( (declaration) => + declaration.alias === undefined && declaration.name !== undefined && owningScope(parsed, declaration.range)?.id === parsed.moduleScope, ); @@ -371,16 +381,166 @@ export function populateCppIncludedUsingClaims( } } +interface NamespaceAliasTarget { + readonly target: string; + readonly availableFrom?: Pick; +} +const namespaceAliases = new WeakMap< + ScopeResolutionIndexes, + Map> +>(); +const classScopeIds = new WeakMap>(); + +function visibleNamespaceAlias( + name: string, + inScope: ScopeId, + indexes: ScopeResolutionIndexes, + position?: Pick, +): string | undefined { + let id: ScopeId | null = inScope; + const seen = new Set(); + while (id !== null && !seen.has(id)) { + seen.add(id); + const alias = namespaceAliases.get(indexes)?.get(id)?.get(name); + if ( + alias !== undefined && + (position === undefined || + alias.availableFrom === undefined || + compare(alias.availableFrom, position) <= 0) + ) + return alias.target; + const scope = indexes.scopeTree.getScope(id); + if ( + scope?.bindings + .get(name) + ?.some( + (binding) => + binding.def.type === 'Namespace' && + (position === undefined || + binding.declarationRange === undefined || + compare(binding.declarationRange, position) <= 0), + ) + ) + break; + id = scope?.parent ?? null; + } + return undefined; +} + +/** Expand only aliases visible from the binding's declaration scope. */ +export function cppQualifiedTypeLookupSpelling( + ref: TypeRef, + indexes?: ScopeResolutionIndexes, +): string | null | undefined { + if (indexes === undefined) return undefined; + const separator = ref.rawName.indexOf('::'); + if (separator <= 0) return undefined; + const head = ref.rawName.slice(0, separator).trim(); + if ( + isCppNamespaceQualifierShadowed( + head, + ref.declaredAtScope, + indexes, + ref.lookupPosition ?? ref.bindingRange, + ) + ) { + // A concrete class can still own the written nested type. A type alias or + // dependent qualifier with no class identity cannot borrow a namespace. + return findClassBindingInScope(ref.declaredAtScope, head, indexes, undefined, { + uniqueQualifiedNameFallback: false, + position: ref.lookupPosition ?? ref.bindingRange, + purpose: 'type', + }) === undefined + ? null + : undefined; + } + const alias = visibleNamespaceAlias( + head, + ref.declaredAtScope, + indexes, + ref.lookupPosition ?? ref.bindingRange, + ); + const expanded = + alias === undefined ? undefined : `${alias}::${ref.rawName.slice(separator + 2)}`; + const spelling = expanded ?? ref.rawName; + const last = spelling.lastIndexOf('::'); + const qualifier = spelling.slice(0, last).replace(/::/g, '.'); + const tail = spelling.slice(last + 2); + const qualifiers = new Set([qualifier]); + if (alias === undefined && !spelling.startsWith('::')) { + const enclosing: string[] = []; + let scope = indexes.scopeTree.getScope(ref.declaredAtScope); + const seen = new Set(); + while (scope !== undefined && !seen.has(scope.id)) { + seen.add(scope.id); + if (scope.kind === 'Namespace') { + const name = scope.ownedDefs.find((def) => def.type === 'Namespace')?.qualifiedName; + if (name !== undefined) enclosing.unshift(name.slice(name.lastIndexOf('.') + 1)); + } + scope = scope.parent === null ? undefined : indexes.scopeTree.getScope(scope.parent); + } + for (let length = enclosing.length; length > 0; length--) + qualifiers.add([...enclosing.slice(0, length), qualifier].join('.')); + } + const matches = new Map(); + for (const candidateId of indexes.qualifiedNames.get(tail)) { + const classScopeId = classScopeIds.get(indexes)?.get(candidateId); + if (classScopeId === undefined) continue; + let parent = indexes.scopeTree.getScope(classScopeId)?.parent ?? null; + const visited = new Set(); + const full: string[] = []; + const transparent: string[] = []; + let hasInline = false; + while (parent !== null && !visited.has(parent)) { + visited.add(parent); + const scope = indexes.scopeTree.getScope(parent); + if (scope === undefined) break; + if (scope.kind === 'Namespace') { + const name = scope.ownedDefs.find((def) => def.type === 'Namespace')?.qualifiedName; + if (name !== undefined) { + const segment = name.slice(name.lastIndexOf('.') + 1); + full.unshift(segment); + if (isCppInlineNamespaceScope(scope.id)) hasInline = true; + else transparent.unshift(segment); + } + } + parent = scope.parent; + } + if (hasInline && qualifiers.has(transparent.join('.'))) + matches.set(candidateId, [...full, tail].join('::')); + } + return matches.size === 1 ? matches.values().next().value : expanded; +} + /** Materialize namespace identities once, then augment only the using's owner. */ export function populateCppUsingBindings( parsedFiles: readonly ParsedFile[], indexes: ScopeResolutionIndexes, ): void { + const classes = new Map(); + for (const parsed of parsedFiles) { + for (const scope of parsed.scopes) { + if (scope.kind !== 'Class') continue; + const definition = scope.ownedDefs.find((def) => isClassLike(def.type)); + if (definition !== undefined) classes.set(definition.nodeId, scope.id); + } + } + classScopeIds.set(indexes, classes); if (!parsedFiles.some((parsed) => usingDeclarations(parsed).length > 0)) return; const namespaceLookup = createNamespaceLookup(parsedFiles, (id) => indexes.scopeTree.getScope(id), ); const { namespacePath } = namespaceLookup; + const aliases = new Map>(); + namespaceAliases.set(indexes, aliases); + const installAlias = (scope: ScopeId, name: string, value: NamespaceAliasTarget): void => { + let bucket = aliases.get(scope); + if (bucket === undefined) { + bucket = new Map(); + aliases.set(scope, bucket); + } + bucket.set(name, value); + }; const byFile = new Map(parsedFiles.map((parsed) => [parsed.filePath, parsed])); const visibleFiles = createIncludeClosure((filePath) => { const parsed = byFile.get(filePath); @@ -389,6 +549,38 @@ export function populateCppUsingBindings( edge.targetFile !== null && edge.linkStatus !== 'unresolved' ? [edge.targetFile] : [], ); }); + const consumersByHeader = new Map< + string, + Map | undefined> + >(); + const aliasFiles = new Set( + parsedFiles + .filter((parsed) => + usingDeclarations(parsed).some((declaration) => declaration.alias !== undefined), + ) + .map((parsed) => parsed.filePath), + ); + if (aliasFiles.size > 0) { + for (const consumer of parsedFiles) { + for (const edge of indexes.imports.get(consumer.moduleScope) ?? []) { + if (edge.targetFile === null || edge.linkStatus === 'unresolved') continue; + for (const header of visibleFiles(edge.targetFile)) { + if (header === consumer.filePath || !aliasFiles.has(header)) continue; + const consumers = consumersByHeader.get(header) ?? new Map(); + const previous = consumers.get(consumer.moduleScope); + const availableFrom = edge.atRange === undefined ? undefined : end(edge.atRange); + if ( + !consumers.has(consumer.moduleScope) || + availableFrom === undefined || + (previous !== undefined && compare(availableFrom, previous) < 0) + ) { + consumers.set(consumer.moduleScope, availableFrom); + } + consumersByHeader.set(header, consumers); + } + } + } + } const augmentations = indexes.bindingAugmentations as Map>; const append = ( scope: Scope, @@ -412,22 +604,72 @@ export function populateCppUsingBindings( } bindings.set(name, bucket); }; + const resolveDeclaration = (parsed: ParsedFile, declaration: CppUsingDeclaration) => { + const owner = owningScope(parsed, declaration.range); + if (owner === undefined) return undefined; + const parts = declaration.namespace.split('::').map((part) => part.trim()); + const head = parts[0]; + const alias = + head === undefined || head.length === 0 + ? undefined + : visibleNamespaceAlias(head, owner.id, indexes, declaration.range); + const resolved = resolveUsingMembers( + alias === undefined + ? declaration + : { ...declaration, namespace: `::${[alias, ...parts.slice(1)].join('::')}` }, + owner, + parsed.filePath, + visibleFiles(parsed.filePath), + namespaceLookup, + ); + return resolved === undefined ? undefined : { owner, ...resolved }; + }; + // Includes are leaves-first. Retry only unresolved aliases inside cycles; + // successful aliases have canonical targets and never need expanding again. + const ordered = new Map(); + for (const scc of indexes.sccs) + for (const file of scc.files) { + const parsed = byFile.get(file); + if (parsed !== undefined) ordered.set(file, parsed); + } + for (const parsed of parsedFiles) + if (!ordered.has(parsed.filePath)) ordered.set(parsed.filePath, parsed); + let pending = [...ordered.values()].flatMap((parsed) => + usingDeclarations(parsed) + .filter((declaration) => declaration.alias !== undefined) + .map((declaration) => ({ parsed, declaration })), + ); + while (pending.length > 0) { + const retry: typeof pending = []; + for (const item of pending) { + const resolved = resolveDeclaration(item.parsed, item.declaration); + const name = item.declaration.alias; + if (resolved === undefined || name === undefined) { + retry.push(item); + continue; + } + installAlias(resolved.owner.id, name, { + target: resolved.target, + availableFrom: item.declaration.range, + }); + if (resolved.owner.id === item.parsed.moduleScope) + for (const [consumer, availableFrom] of consumersByHeader.get(item.parsed.filePath) ?? []) + installAlias(consumer, name, { + target: resolved.target, + availableFrom, + }); + } + if (retry.length === pending.length) break; + pending = retry; + } for (const parsed of parsedFiles) { const facts = usingDeclarations(parsed); if (facts.length === 0) continue; - const visible = visibleFiles(parsed.filePath); for (const declaration of facts) { - const owner = owningScope(parsed, declaration.range); - if (owner === undefined) continue; - const resolved = resolveUsingMembers( - declaration, - owner, - parsed.filePath, - visible, - namespaceLookup, - ); + if (declaration.alias !== undefined) continue; + const resolved = resolveDeclaration(parsed, declaration); if (resolved === undefined) continue; - const { target, members } = resolved; + const { owner, target, members } = resolved; for (const [name, refs] of members) { if (declaration.name !== undefined) { append(owner, name, refs, declaration); diff --git a/gitnexus/src/core/ingestion/languages/csharp.ts b/gitnexus/src/core/ingestion/languages/csharp.ts index 90fbc7c287..6fccd810f9 100644 --- a/gitnexus/src/core/ingestion/languages/csharp.ts +++ b/gitnexus/src/core/ingestion/languages/csharp.ts @@ -13,8 +13,6 @@ import { csharpClassConfig } from '../class-extractors/configs/csharp.js'; import { defineLanguage } from '../language-provider.js'; import { typeConfig as csharpConfig } from '../type-extractors/csharp.js'; import { csharpExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { csharpImportConfig } from '../import-resolvers/configs/csharp.js'; import { CSHARP_QUERIES } from '../tree-sitter-queries.js'; import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; @@ -195,7 +193,6 @@ export const csharpProvider = defineLanguage({ `, typeConfig: csharpConfig, exportChecker: csharpExportChecker, - importResolver: createImportResolver(csharpImportConfig), mroStrategy: 'implements-split', callExtractor: createCallExtractor(csharpCallConfig), fieldExtractor: createFieldExtractor(csharpFieldConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts b/gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts similarity index 93% rename from gitnexus/src/core/ingestion/import-resolvers/csharp.ts rename to gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts index e8d6fdf7ab..fd7d7f2e47 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/csharp.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/import-helpers.ts @@ -1,16 +1,17 @@ /** * C# namespace import resolution — internal helpers. * - * Strategy lives in configs/csharp.ts. + * Used by the C# ScopeResolver.resolveImportTarget hook. * This file contains shared helpers for namespace-based resolution. */ -import { perFileSet } from './per-file-set.js'; -import { getWorkspaceFileIndex } from './workspace-file-index.js'; -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; -import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../language-config.js'; -import { csharpSuffixFallbackAllowed } from '../csharp-namespace-gate.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../../language-config.js'; +import { csharpSuffixFallbackAllowed } from './namespace-gate.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** * Directory index backing the namespace-directory fallback below (step 3). @@ -397,40 +398,6 @@ export function resolveCSharpImportInternal( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } - -/** - * Compute the directory suffix for a C# namespace import (for PackageMap). - * Returns a suffix like "/ProjectDir/Models/" or null if no config matches. - */ -export function resolveCSharpNamespaceDir( - importPath: string, - csharpConfigs: CSharpProjectConfig[], -): string | null { - const namespacePath = importPath.replace(/\./g, '/'); - - for (const config of csharpConfigs) { - const nsPath = config.rootNamespace.replace(/\./g, '/'); - let relative: string; - if (namespacePath.startsWith(nsPath + '/')) { - relative = namespacePath.slice(nsPath.length + 1); - } else if (namespacePath === nsPath) { - relative = ''; - } else { - continue; - } - - const dirPrefix = config.projectDir - ? relative - ? config.projectDir + '/' + relative - : config.projectDir - : relative; - - if (!dirPrefix) continue; - return '/' + dirPrefix + '/'; - } - - return null; -} diff --git a/gitnexus/src/core/ingestion/languages/csharp/import-target.ts b/gitnexus/src/core/ingestion/languages/csharp/import-target.ts index 68f1e484d5..424b3d6cb7 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/import-target.ts @@ -21,18 +21,18 @@ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; import type { CSharpProjectConfig, CSharpNamespaceEvidence } from '../../language-config.js'; -import { resolveCSharpImportInternal } from '../../import-resolvers/csharp.js'; +import { resolveCSharpImportInternal } from './import-helpers.js'; import { getWorkspaceFileIndex, type WorkspaceFileIndex, -} from '../../import-resolvers/workspace-file-index.js'; +} from '../../utils/workspace-file-index.js'; import { buildPackageDirIndex, firstFileDirectlyInPkgDir, type PackageDirIndex, -} from '../../import-resolvers/package-dir-index.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { csharpSuffixFallbackAllowed } from '../../csharp-namespace-gate.js'; +} from '../../utils/package-dir-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { csharpSuffixFallbackAllowed } from './namespace-gate.js'; export interface CsharpResolveContext { readonly fromFile: string; @@ -44,7 +44,7 @@ export interface CsharpResolveContext { /** * Namespace-directory index over the `.cs` files, memoized on the Set's * identity. Feeds `firstFileDirectlyInPkgDir` (in - * `import-resolvers/package-dir-index.ts`), which the no-csproj path calls once + * `utils/package-dir-index.ts`), which the no-csproj path calls once * for the direct match and then up to once per stripped namespace prefix. */ const getCsharpDirIndex = perFileSet( @@ -74,8 +74,7 @@ export function resolveCsharpImportTarget( evidence, ); if (fromCsproj.length > 0) return fromCsproj[0]!; - // csproj configs are authoritative: mirror legacy `configs/csharp.ts`, - // which returns an empty result to STOP the chain. Falling through to the + // csproj configs are authoritative. Falling through to the // ungated `resolveDirectMatch` would re-introduce the BCL→local match the // internal resolver's gate just suppressed (#1881 parity, #2). return null; @@ -87,10 +86,8 @@ export function resolveCsharpImportTarget( // Gate the WHOLE no-csproj path on declared in-repo namespaces — the direct // path/suffix match INCLUDED — so a BCL using can't resolve to a // coincidentally path-aligned local file (e.g. `Legacy/System/Threading/ - // Tasks.cs` satisfying `using System.Threading.Tasks;`). Running the gate - // before `resolveDirectMatch` mirrors the legacy leg's gate-first ordering - // (`import-resolvers/configs/csharp.ts`), so the two legs are equivalent - // (#1881 parity, Codex F2). The gate keeps its fail-open for + // Tasks.cs` satisfying `using System.Threading.Tasks;`). The gate runs + // before `resolveDirectMatch` and keeps its fail-open for // undefined/truncated evidence, so legitimate edges in unscanned repos are // unaffected. if (!csharpSuffixFallbackAllowed(targetRaw, evidence)) { diff --git a/gitnexus/src/core/ingestion/csharp-namespace-gate.ts b/gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts similarity index 93% rename from gitnexus/src/core/ingestion/csharp-namespace-gate.ts rename to gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts index df806bf2b7..ca8913aad2 100644 --- a/gitnexus/src/core/ingestion/csharp-namespace-gate.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/namespace-gate.ts @@ -3,13 +3,11 @@ * (e.g. `System.Threading.Tasks`) can't match a coincidentally-named local * file (#1881). * - * Lives in the shared `ingestion/` layer — NOT under `languages/csharp/` — so - * BOTH the registry-primary scope resolver (`languages/csharp/import-target.ts`) - * and the legacy DAG resolver (`import-resolvers/csharp.ts`) can import it - * without an `import-resolvers/ -> languages/` dependency inversion (#5). + * Shared by this provider's import-target adapter and namespace-directory + * helpers. The legacy DAG resolver has been removed. */ -import type { CSharpNamespaceEvidence } from './language-config.js'; +import type { CSharpNamespaceEvidence } from '../../language-config.js'; /** * Top-level namespace segments that clearly belong to the BCL / runtime / a diff --git a/gitnexus/src/core/ingestion/languages/csharp/namespace-siblings.ts b/gitnexus/src/core/ingestion/languages/csharp/namespace-siblings.ts index 10aefb45ed..3ac1f00f77 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/namespace-siblings.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/namespace-siblings.ts @@ -26,8 +26,9 @@ * / `Scope.typeBindings`. That per-file copy was O(files²) for a * concentrated namespace and OOM'd large solutions (#1871; the global * twin was fixed in #1905/#1954). The walkers consult these channels - * gated by `accessibleNamespacesByScope` (a file's own namespace + - * `using` targets), so visibility is unchanged — only the storage is + * gated by `accessibleNamespacesByScope` (a file's own and enclosing + * namespaces, the global namespace, and `using` targets, in C# lookup + * order), so visibility is unchanged — only the storage is * shared. Finalized bindings remain first in `lookupBindingsAt`, and * local lexical `Scope.bindings` remains the first-tier shadowing * channel. (`using static` member exposure still uses the per-scope @@ -478,9 +479,9 @@ export function populateCsharpNamespaceSiblings( // both time and memory and OOM'd large no-namespace solutions (tens of // thousands of files in the global bucket → billions of Map entries). This // mirrors how Roslyn resolves against a single `Compilation.GlobalNamespace` - // symbol instead of per-file copies, and is the typeBindings analogue of the - // `workspaceFqnBindings` fast-path (#1905). `findReceiverTypeBinding` / - // `followChainPostFinalize` consult this channel as a final fallback. + // symbol instead of per-file copies (#1905). `findReceiverTypeBinding` / + // `followChainPostFinalize` consult this channel as a final fallback. Global + // class bindings go through the per-namespace channel instead (see below). const workspaceTypeBindings = indexes.workspaceTypeBindings as Map; const globalBucket = buckets.get(''); if (globalBucket !== undefined) { @@ -523,38 +524,94 @@ export function populateCsharpNamespaceSiblings( } } - // Materialize each file's accessible namespaces (its own declared namespaces + - // every `using namespace X;` target, plus dotted-path prefixes), keyed by the - // file's Module scope id. This is the SAME accessibility set the per-file copy - // above used to derive — now stored so the language-neutral walkers can gate - // their `namespaceFqnBindings` / `namespaceTypeBindings` lookups to exactly the - // namespaces a file can see. The global ('') namespace is excluded: it is - // type-visible everywhere and handled by the flat workspace channels. + // Namespace lookup follows declaration scopes. Types from one precedence + // group compete together; a nearer group hides later groups. const accessibleNamespacesByScope = indexes.accessibleNamespacesByScope as Map; + const namespaceTiers = indexes.namespaceLookupTiersByScope as + | Map + | undefined; for (const parsed of parsedFiles) { - const moduleScope = parsed.scopes.find((s) => s.kind === 'Module'); + const moduleScope = parsed.scopes.find((scope) => scope.kind === 'Module'); if (moduleScope === undefined) continue; - const accessibleNamespaces = new Set(); - const struct = structureByFile.get(parsed.filePath); - if (struct !== undefined) { - for (const n of struct.namespaces) accessibleNamespaces.add(n); + const declared = structureByFile.get(parsed.filePath)?.namespaces ?? []; + const usings = usingTargetsByDeclaration(parsed, declared); + const namespaceScopes = parsed.scopes + .filter((scope) => scope.kind === 'Namespace') + .sort((a, b) => comparePositions(a.range.startLine, a.range.startCol, b.range)); + const namesByScope = new Map(); + for (let i = 0; i < namespaceScopes.length; i++) { + const scope = namespaceScopes[i]!; + const name = declaredNameAt(declared, namespaceScopes.length, i); + const parentName = scope.parent === null ? undefined : namesByScope.get(scope.parent); + if (name !== undefined) + namesByScope.set(scope.id, parentName === undefined ? name : `${parentName}.${name}`); } - for (const imp of parsed.parsedImports) { - if (imp.kind === 'namespace' && imp.targetRaw !== null) { - accessibleNamespaces.add(imp.targetRaw); + const scopesById = new Map(namespaceScopes.map((scope) => [scope.id, scope])); + const sourceLines = (inputs.fileContents.get(parsed.filePath) ?? '').split('\n'); + const fileScoped = namespaceScopes.find((scope) => { + let inComment = false; + for (let line = scope.range.startLine - 1; line < scope.range.endLine; line++) { + const text = sourceLines[line] ?? ''; + const start = line === scope.range.startLine - 1 ? scope.range.startCol : 0; + for (let column = start; column < text.length; column++) { + if (inComment) { + if (text[column] === '*' && text[column + 1] === '/') { + inComment = false; + column++; + } + continue; + } + if (text[column] === '/' && text[column + 1] === '/') break; + if (text[column] === '/' && text[column + 1] === '*') { + inComment = true; + column++; + continue; + } + if (text[column] === '{') return false; + if (text[column] === ';') return true; + } } - } - const expandedNamespaces = new Set(accessibleNamespaces); - for (const ns of accessibleNamespaces) { - const segments = ns.split('.'); - for (let i = segments.length - 1; i > 0; i--) { - expandedNamespaces.add(segments.slice(0, i).join('.')); + return false; + }); + const install = (scopeId: ScopeId, owner?: Scope): void => { + const tiers: string[][] = []; + const seen = new Set(); + const imported: string[] = []; + const addNamespace = (name: string): void => { + if (!seen.has(name)) { + seen.add(name); + tiers.push([name]); + } + }; + const visited = new Set(); + let current = owner; + while (current !== undefined && !visited.has(current.id)) { + visited.add(current.id); + const name = namesByScope.get(current.id); + if (name !== undefined) { + addNamespace(name); + const targets = usings.byDeclaration.get(current.id) ?? []; + if (targets.length > 0) { + tiers.push([...targets]); + imported.push(...targets); + } + for (const enclosing of enclosingNamespaces(name)) addNamespace(enclosing); + } + current = current.parent === null ? undefined : scopesById.get(current.parent); } - } - expandedNamespaces.delete(''); // global handled by the flat workspace channels - if (expandedNamespaces.size > 0) { - accessibleNamespacesByScope.set(moduleScope.id, [...expandedNamespaces]); - } + addNamespace(''); + if (usings.compilationUnit.length > 0) { + tiers.push([...usings.compilationUnit]); + imported.push(...usings.compilationUnit); + } + for (const target of imported) { + for (const prefix of enclosingNamespaces(target)) addNamespace(prefix); + } + accessibleNamespacesByScope.set(scopeId, [...new Set(tiers.flat())]); + namespaceTiers?.set(scopeId, tiers); + }; + install(moduleScope.id, fileScoped); + for (const scope of namespaceScopes) install(scope.id, scope); } // `using static X.Y.Z;` — expose every public static method of @@ -633,20 +690,14 @@ export function populateCsharpNamespaceSiblings( // augmentation removes an O(importers × bucket-size) fanout on popular // namespaces — the cross-namespace twin of the same-namespace blow-up. - // Workspace-level binding channel for global-namespace types (see the - // global fast-path below). `lookupBindingsAt` consults this as a third - // source after finalized + per-scope augmented bindings. Its inner arrays - // are mutable by contract (append-only, like `bindingAugmentations` — see - // the ScopeResolutionIndexes doc + validateBindingsImmutability), so the - // ReadonlyMap→Map cast is localized to this one line and all writes go - // through `getWorkspaceBucket`. - const workspace = indexes.workspaceFqnBindings as Map; - // Per-namespace binding channel for NAMED-namespace class visibility — the - // namespace-scoped analogue of `workspace`, populated once per named bucket - // (#1871). Replaces the per-scope `bindingAugmentations` fanout (O(scopes × - // defs)) for same-namespace siblings AND the per-file cross-namespace-`using` - // injection above. `lookupBindingsAt` consults it gated by - // `accessibleNamespacesByScope`. + // Per-namespace binding channel for class visibility, populated once per + // bucket (#1871), the global ('') bucket included. Replaces the per-scope + // `bindingAugmentations` fanout (O(scopes × defs)) for same-namespace + // siblings AND the per-file cross-namespace-`using` injection above. + // `lookupBindingsAt` consults it gated by `accessibleNamespacesByScope`. + // Its inner arrays are mutable by contract (append-only, like + // `bindingAugmentations`; see the ScopeResolutionIndexes doc and + // validateBindingsImmutability). const namespaceFqn = indexes.namespaceFqnBindings as Map>; for (const [nsName, bucket] of buckets) { @@ -670,42 +721,20 @@ export function populateCsharpNamespaceSiblings( arr.push(def); } - // Global-namespace fast path (Unity OOM guard). Types declared in the - // default (global) namespace are visible from EVERY file in C# — the - // global namespace is always implicitly in scope — so one workspace- - // level entry per simple name is both semantically correct and O(D) - // instead of the O(S·D) per-scope augmentation that materialized - // billions of BindingRefs on large Unity solutions (tens of thousands - // of global types × tens of thousands of scopes). `walkScopeChain` - // checks local `scope.bindings` first, so local declarations still - // shadow these workspace entries; a file resolving its own global type - // hits the local binding before this map. Dedup by `def.nodeId` keeps - // partial-class / duplicate declarations from double-emitting. - if (nsName === '') { - for (const [name, defs] of defsByName) { - const bucket = getWorkspaceBucket(workspace, name); - const seen = new Set(); - for (const b of bucket) seen.add(b.def.nodeId); - for (const def of defs) { - if (seen.has(def.nodeId)) continue; // dedup by nodeId (keeps partials, drops re-emits) - seen.add(def.nodeId); - bucket.push({ def, origin: 'namespace' }); - } - } - continue; - } - - // Named-namespace fast path (#1871) — the namespace-scoped mirror of the - // global path above. One `namespaceFqnBindings[nsName]` entry per simple - // name, O(D) per bucket, instead of the prior O(scopes × defs) per-scope - // augmentation that materialized O(files²) BindingRefs for a concentrated - // named namespace. `lookupBindingsAt` consults this gated by - // `accessibleNamespacesByScope` and ranks finalized `scope.bindings` - // (local declarations) ABOVE it, so local types still shadow — exactly as - // `walkScopeChain` shadows the global workspace entries. Dedup by + // One `namespaceFqnBindings[nsName]` entry per simple name, O(D) per + // bucket, instead of the prior O(scopes × defs) per-scope augmentation + // that materialized O(files²) BindingRefs for a concentrated namespace + // (#1871), and billions for the global bucket of a large Unity solution + // (tens of thousands of global types × tens of thousands of scopes). + // Global types share this channel rather than a scope-independent one: + // the walkers consult it at the provider's owning scopes through their + // ordered accessibility list, so a global type no longer answers from a + // method scope before the walk reaches the file's own namespace. + // `lookupBindingsAt` ranks finalized `scope.bindings` (local declarations) + // ABOVE this channel, so local types still shadow it. Dedup by // `def.nodeId` keeps partial-class / duplicate declarations from - // double-emitting. (The prior local-shadow and self-reference skips are now - // handled by lookup precedence, identical to the global path.) + // double-emitting. (The prior local-shadow and self-reference skips are + // handled by lookup precedence.) let nsMap = namespaceFqn.get(nsName); for (const [name, defs] of defsByName) { let bucketArr = nsMap?.get(name); @@ -755,20 +784,89 @@ function getAugmentationBucket( return bucketArr; } -/** Get-or-create a mutable inner bucket inside the `workspaceFqnBindings` - * channel (the scope-independent third channel; see - * `ScopeResolutionIndexes.workspaceFqnBindings`). Like - * `getAugmentationBucket`, the inner arrays are mutable by contract — - * callers `push` directly. Keeping the get-or-create here means the one - * ReadonlyMap→Map cast at the call site is the only place the mutable - * view is taken. */ -function getWorkspaceBucket(workspace: Map, name: string): BindingRef[] { - let bucketArr = workspace.get(name); - if (bucketArr === undefined) { - bucketArr = []; - workspace.set(name, bucketArr); +/** `using` targets of one file, grouped by the declaration that owns them. */ +interface UsingTargetsByDeclaration { + readonly byDeclaration: ReadonlyMap; + /** Directives at compilation-unit level. */ + readonly compilationUnit: readonly string[]; +} + +/** + * Group a file's `using` targets by the declaration that owns them, which is + * the level C# name lookup consults them at. + * + * A directive belongs to the last namespace declaration that starts before it. + * For a block namespace, that declaration contains it. A file-scoped + * `namespace X;` scope covers only its own line, and the directives after it + * still belong to `X`. Directives cannot follow a closed block namespace + * (CS1529), so the rule needs no other case. Namespace scopes pair with + * `declared` by source order. When the counts disagree, as with an incomplete + * line scan, every namespace-level directive goes to the first declared + * namespace, matching how top-level classes are attributed above. + */ +function usingTargetsByDeclaration( + parsed: ParsedFile, + declared: readonly string[], +): UsingTargetsByDeclaration { + const namespaceScopes = parsed.scopes + .filter((s) => s.kind === 'Namespace') + .sort((a, b) => comparePositions(a.range.startLine, a.range.startCol, b.range)); + const byDeclaration = new Map(); + const compilationUnit: string[] = []; + for (const imp of parsed.parsedImports) { + if (imp.kind !== 'namespace' || imp.targetRaw === null) continue; + const at = imp.atRange; + let owner = -1; + if (at !== undefined) { + let lo = 0; + let hi = namespaceScopes.length; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + if (comparePositions(at.startLine, at.startCol, namespaceScopes[mid]!.range) > 0) { + lo = mid + 1; + } else { + hi = mid; + } + } + owner = lo - 1; + } + const name = owner === -1 ? undefined : declaredNameAt(declared, namespaceScopes.length, owner); + if (name === undefined) { + compilationUnit.push(imp.targetRaw); + continue; + } + const ownerScope = namespaceScopes[owner]; + if (ownerScope !== undefined) { + const ownTargets = byDeclaration.get(ownerScope.id) ?? []; + ownTargets.push(imp.targetRaw); + byDeclaration.set(ownerScope.id, ownTargets); + } } - return bucketArr; + return { byDeclaration, compilationUnit }; +} + +/** The declared namespace name for the `index`-th Namespace scope, or the first + * declared name when scopes and declarations do not pair one-to-one. */ +function declaredNameAt( + declared: readonly string[], + scopeCount: number, + index: number, +): string | undefined { + return declared.length === scopeCount ? declared[index] : declared[0]; +} + +/** Sign of position (`line`, `col`) relative to the start of `range`. */ +function comparePositions(line: number, col: number, range: Scope['range']): number { + return line !== range.startLine ? line - range.startLine : col - range.startCol; +} + +/** The namespaces enclosing a dotted namespace name, innermost first: + * `A.B.C` → `A.B`, `A`. The global namespace is not included. */ +function enclosingNamespaces(ns: string): string[] { + const segments = ns.split('.'); + const out: string[] = []; + for (let i = segments.length - 1; i > 0; i--) out.push(segments.slice(0, i).join('.')); + return out; } function isTypeDef(def: SymbolDefinition): boolean { diff --git a/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts b/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts index 714be8c1fc..63dbb3a7a2 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/resolution-config.ts @@ -3,7 +3,7 @@ * * Loaded once per analyze pass via `csharpScopeResolver.loadResolutionConfig` * and threaded into `resolveCsharpImportTarget`. The pure gate predicates live - * in `../../csharp-namespace-gate.ts` (shared with the legacy DAG resolver). + * in `./namespace-gate.ts`. */ import { diff --git a/gitnexus/src/core/ingestion/languages/csharp/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/csharp/scope-resolver.ts index b767e8c3ff..8a6a49dd17 100644 --- a/gitnexus/src/core/ingestion/languages/csharp/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/csharp/scope-resolver.ts @@ -6,10 +6,13 @@ * canonical shape. */ -import type { ParsedFile } from 'gitnexus-shared'; +import type { ParsedFile, ScopeId } from 'gitnexus-shared'; import { CLASS_KINDS, SupportedLanguages } from 'gitnexus-shared'; import { buildMro, defaultLinearize } from '../../scope-resolution/passes/mro.js'; -import { populateClassOwnedMembers } from '../../scope-resolution/scope/walkers.js'; +import { + populateClassOwnedMembers, + lookupNameClaim, +} from '../../scope-resolution/scope/walkers.js'; import { populateCsharpNamespacePrefixes } from './qualified-type-names.js'; import type { ScopeResolver } from '../../scope-resolution/contract/scope-resolver.js'; import { @@ -119,6 +122,26 @@ const csharpScopeResolver: ScopeResolver = { // `namespace-siblings.ts` for the implementation. populateNamespaceSiblings: populateCsharpNamespaceSiblings, + isBareClassReceiverCandidate: ({ candidate, spelling, inScope, scopes }) => { + if (candidate.typeParameters === undefined || candidate.typeParameters.length === 0) + return true; + if (spelling.includes('.') || spelling.includes('<') || spelling.includes('::')) return true; + if (candidate.qualifiedName?.split('.').at(-1) !== spelling) return true; + const claim = lookupNameClaim(inScope, spelling, scopes, { purpose: 'value' }); + if (claim.imports.some((edge) => edge.kind === 'alias')) return true; + const visited = new Set(); + let current: ScopeId | null = inScope; + while (current !== null && !visited.has(current)) { + visited.add(current); + const scope = scopes.scopeTree.getScope(current); + if (scope === undefined) break; + if (scope.kind === 'Class' && scope.ownedDefs.some((def) => def.nodeId === candidate.nodeId)) + return true; + current = scope.parent; + } + return false; + }, + // C# is statically typed — type information is reliable. Field- // fallback heuristic stays off (the type-binding layer already // produces precise owner types); return-type propagation on is fine diff --git a/gitnexus/src/core/ingestion/languages/dart.ts b/gitnexus/src/core/ingestion/languages/dart.ts index d6eafd701e..16f15307d9 100644 --- a/gitnexus/src/core/ingestion/languages/dart.ts +++ b/gitnexus/src/core/ingestion/languages/dart.ts @@ -23,8 +23,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as dartConfig } from '../type-extractors/dart.js'; import { dartExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { dartImportConfig } from '../import-resolvers/configs/dart.js'; import { DART_QUERIES } from '../tree-sitter-queries.js'; import { createDartCfgVisitor } from '../cfg/visitors/dart.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -124,7 +122,6 @@ export const dartProvider = defineLanguage({ treeSitterQueries: DART_QUERIES, typeConfig: dartConfig, exportChecker: dartExportChecker, - importResolver: createImportResolver(dartImportConfig), callExtractor: createCallExtractor(dartCallConfig), fieldExtractor: createFieldExtractor(dartFieldConfig), methodExtractor: createMethodExtractor(dartMethodConfig), diff --git a/gitnexus/src/core/ingestion/languages/dart/import-target.ts b/gitnexus/src/core/ingestion/languages/dart/import-target.ts index 602ea5ce49..e4c7f80b44 100644 --- a/gitnexus/src/core/ingestion/languages/dart/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/dart/import-target.ts @@ -12,7 +12,7 @@ * `targetRaw` arrives already quote-stripped from `interpretDartImport`. */ -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { DART_HERITAGE_PREFIX } from './interpret.js'; import type { DartPackageConfig } from './package-config.js'; import { DART_PACKAGE_SCHEME, dartPackageImportName } from './package-uri.js'; diff --git a/gitnexus/src/core/ingestion/languages/go.ts b/gitnexus/src/core/ingestion/languages/go.ts index 3f2502a320..dd6ea6895f 100644 --- a/gitnexus/src/core/ingestion/languages/go.ts +++ b/gitnexus/src/core/ingestion/languages/go.ts @@ -17,8 +17,6 @@ import { createGoCfgVisitor } from '../cfg/visitors/go.js'; import { defineLanguage } from '../language-provider.js'; import { typeConfig as goConfig } from '../type-extractors/go.js'; import { goExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { goImportConfig } from '../import-resolvers/configs/go.js'; import { GO_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -141,7 +139,6 @@ export const goProvider = defineLanguage({ treeSitterQueries: GO_QUERIES, typeConfig: goConfig, exportChecker: goExportChecker, - importResolver: createImportResolver(goImportConfig), callExtractor: createCallExtractor(goCallConfig), fieldExtractor: createFieldExtractor(goFieldConfig), methodExtractor: createMethodExtractor(goMethodConfig), diff --git a/gitnexus/src/core/ingestion/languages/go/import-target.ts b/gitnexus/src/core/ingestion/languages/go/import-target.ts index c41c7d18aa..1d2c133714 100644 --- a/gitnexus/src/core/ingestion/languages/go/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/go/import-target.ts @@ -4,8 +4,8 @@ import { filesInDir, sortedRootFiles, type PackageDirIndex, -} from '../../import-resolvers/package-dir-index.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +} from '../../utils/package-dir-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { isGoWorkspaceConfig, locateGoImport } from './workspace-config.js'; /** @@ -80,7 +80,7 @@ function isGoPackageFile(normalized: string): boolean { * * The orchestrator hands the same Set to every import in a pass, so the index * is built once per run. `resolveGoImportTarget` must therefore never copy the - * Set before this point — see `import-resolvers/workspace-file-index.ts`. + * Set before this point — see `utils/workspace-file-index.ts`. */ const getGoPackageIndex = perFileSet( (allFilePaths: ReadonlySet): PackageDirIndex => diff --git a/gitnexus/src/core/ingestion/languages/go/workspace-config.ts b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts index 9c3dfa6ecb..a9dc25c6e3 100644 --- a/gitnexus/src/core/ingestion/languages/go/workspace-config.ts +++ b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts @@ -1,14 +1,9 @@ /** * Go module discovery: every `go.mod` and `go.work` in the repository. * - * `loadGoModulePath` reads only the ROOT `go.mod`. A monorepo with one module - * per service (`services/orders/go.mod`), a root module with nested modules - * (`tools/go.mod`, k8s-style `staging/`), or a repo with no root module at all - * then answers every import from the wrong place: with no root `go.mod` the - * GOPATH suffix match runs, so two modules' `internal/repository` both answer - * `…/internal/repository`; with one, imports of a nested module are "not ours" - * and drop, while the root module's own imports match any directory ENDING in - * the package path — the nested modules' included. + * Every module needs its own root: services may have separate `go.mod` files, + * and nested modules own subtrees that an enclosing module cannot import as + * its own packages. * * Go itself resolves an import against modules, not directory names: * diff --git a/gitnexus/src/core/ingestion/languages/import-candidates.ts b/gitnexus/src/core/ingestion/languages/import-candidates.ts new file mode 100644 index 0000000000..61b35c2cad --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/import-candidates.ts @@ -0,0 +1,51 @@ +/** Ordered fallback candidates supplied by import-resolution providers. */ +export const EXTENSIONS = [ + '', + // TypeScript/JavaScript + '.tsx', + '.ts', + '.mts', + '.cts', + '.jsx', + '.js', + '.mjs', + '.cjs', + '.vue', + '/index.tsx', + '/index.ts', + '/index.jsx', + '/index.js', + // Python + '.py', + '/__init__.py', + // Java + '.java', + // Kotlin + '.kt', + '.kts', + // C/C++ + '.c', + '.h', + '.cpp', + '.hpp', + '.cc', + '.cxx', + '.hxx', + '.hh', + '.cu', + '.cuh', + // C# + '.cs', + // Go + '.go', + // Rust + '.rs', + '/mod.rs', + // PHP + '.php', + '.phtml', + // Swift + '.swift', + // Ruby + '.rb', +]; diff --git a/gitnexus/src/core/ingestion/languages/java.ts b/gitnexus/src/core/ingestion/languages/java.ts index 80851ee4ea..9a308edaae 100644 --- a/gitnexus/src/core/ingestion/languages/java.ts +++ b/gitnexus/src/core/ingestion/languages/java.ts @@ -23,8 +23,6 @@ import { prepareJavaRouteConstants, } from '../route-extractors/java-const-resolver.js'; import { javaExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { javaImportConfig } from '../import-resolvers/configs/jvm.js'; import { JAVA_QUERIES } from '../tree-sitter-queries.js'; import { createCallExtractor } from '../call-extractors/generic.js'; import { javaCallConfig } from '../call-extractors/configs/jvm.js'; @@ -198,7 +196,6 @@ export const javaProvider = defineLanguage({ treeSitterQueries: JAVA_QUERIES, typeConfig: javaTypeConfig, exportChecker: javaExportChecker, - importResolver: createImportResolver(javaImportConfig), mroStrategy: 'implements-split', callExtractor: createCallExtractor(javaCallConfig), fieldExtractor: createFieldExtractor(javaConfig), diff --git a/gitnexus/src/core/ingestion/languages/java/import-target.ts b/gitnexus/src/core/ingestion/languages/java/import-target.ts index 4843e854dd..ec1fd0a360 100644 --- a/gitnexus/src/core/ingestion/languages/java/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/java/import-target.ts @@ -40,7 +40,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { getJavaPackageFact } from './package-facts.js'; import { buildJavaPackageIndex, diff --git a/gitnexus/src/core/ingestion/languages/javascript/captures.ts b/gitnexus/src/core/ingestion/languages/javascript/captures.ts index a7764f5547..e2890c50b4 100644 --- a/gitnexus/src/core/ingestion/languages/javascript/captures.ts +++ b/gitnexus/src/core/ingestion/languages/javascript/captures.ts @@ -26,9 +26,11 @@ * instanceof narrowing passes are duplicated from `typescript/captures.ts` * (they are pure AST operations with no grammar-specific logic). * - * Pure given the input source text. No I/O, no globals consulted. + * Derives captures from its inputs and records CommonJS classification for + * immediate side-channel collection. Performs no I/O. */ +import { recordCommonJsModuleKind } from '../typescript/module-kind.js'; import type { Capture, CaptureMatch } from 'gitnexus-shared'; import { findNodeAtRange, @@ -890,6 +892,8 @@ export function emitJsScopeCaptures( }); } + recordCommonJsModuleKind(tree.rootNode, filePath); + const rawMatches = getJsScopeQuery(grammarPath).matches(tree.rootNode); // Export evidence, read once per file (see `ts-js-export-marker.ts`). const exportEvidence = collectEsmExportEvidence(tree.rootNode, filePath); diff --git a/gitnexus/src/core/ingestion/languages/javascript/import-target.ts b/gitnexus/src/core/ingestion/languages/javascript/import-target.ts index 47b8e9fa89..0342e70d95 100644 --- a/gitnexus/src/core/ingestion/languages/javascript/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/javascript/import-target.ts @@ -22,7 +22,7 @@ * mapping or a package manifest, and otherwise not at all. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { resolveTsTarget } from '../typescript/import-target.js'; import type { TsconfigIndex } from '../typescript/tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts index 65bc834eb1..7927222d6f 100644 --- a/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/javascript/scope-resolver.ts @@ -46,7 +46,8 @@ import { jsArityCompatibility } from './arity.js'; import { makeJsResolveImportTarget } from './import-target.js'; import { loadTsconfigIndex } from '../typescript/tsconfig.js'; import { typescriptModuleExports } from '../typescript/module-exports.js'; -import { loadNodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import { isCommonJsExportAssignment } from '../typescript/cjs-export-receiver.js'; +import { loadNodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { isJsSelfBoundCallableFallbackPlausible } from './callable-visibility.js'; async function loadResolutionConfig(repoPath: string, fresh = false) { @@ -93,6 +94,8 @@ const javascriptScopeResolver: ScopeResolver = { // JavaScript `super` keyword: same pattern as TypeScript. isSuperReceiver: (text) => /^super(\s*\(|\s*\.|\s*\[|\s*$)/.test(text.trim()), + isModuleExportAssignment: isCommonJsExportAssignment, + // JavaScript is dynamically typed — enable the field-fallback heuristic // so member-call receivers without type annotations can still resolve // through declared class fields (e.g. JSDoc-typed fields). diff --git a/gitnexus/src/core/ingestion/languages/kotlin.ts b/gitnexus/src/core/ingestion/languages/kotlin.ts index 4ffda436dc..bf4b4daf30 100644 --- a/gitnexus/src/core/ingestion/languages/kotlin.ts +++ b/gitnexus/src/core/ingestion/languages/kotlin.ts @@ -16,9 +16,7 @@ import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; import { assertCloneable } from '../workers/clone-safety.js'; import { kotlinTypeConfig } from '../type-extractors/jvm.js'; import { kotlinExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { kotlinImportConfig } from '../import-resolvers/configs/jvm.js'; -import { appendKotlinWildcard } from '../import-resolvers/jvm.js'; +import { appendKotlinWildcard } from './kotlin/import-wildcard.js'; import { KOTLIN_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import type { SyntaxNode } from '../utils/ast-helpers.js'; @@ -178,7 +176,6 @@ export const kotlinProvider = defineLanguage({ treeSitterQueries: KOTLIN_QUERIES, typeConfig: kotlinTypeConfig, exportChecker: kotlinExportChecker, - importResolver: createImportResolver(kotlinImportConfig), importPathPreprocessor: appendKotlinWildcard, mroStrategy: 'implements-split', callExtractor: createCallExtractor(kotlinCallConfig), diff --git a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts index 7fb8b74100..695c104889 100644 --- a/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/kotlin/import-target.ts @@ -5,7 +5,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { getKotlinPackageFact } from './package-facts.js'; import { buildKotlinPackageIndex, diff --git a/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts b/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts new file mode 100644 index 0000000000..8121da87ae --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/kotlin/import-wildcard.ts @@ -0,0 +1,14 @@ +import type { SyntaxNode } from '../../utils/ast-helpers.js'; + +/** + * Append .* to a Kotlin import path if the AST has a wildcard_import sibling node. + * Pure function — returns a new string without mutating the input. + */ +export const appendKotlinWildcard = (importPath: string, importNode: SyntaxNode): string => { + for (let i = 0; i < importNode.childCount; i++) { + if (importNode.child(i)?.type === 'wildcard_import') { + return importPath.endsWith('.*') ? importPath : `${importPath}.*`; + } + } + return importPath; +}; diff --git a/gitnexus/src/core/ingestion/languages/objective-c.ts b/gitnexus/src/core/ingestion/languages/objective-c.ts index 6a86e9dd72..c1daac9933 100644 --- a/gitnexus/src/core/ingestion/languages/objective-c.ts +++ b/gitnexus/src/core/ingestion/languages/objective-c.ts @@ -8,7 +8,6 @@ import { import Parser from 'tree-sitter'; import { defineLanguage } from '../language-provider.js'; import { createObjectiveCCfgVisitor } from '../cfg/visitors/objective-c.js'; -import type { ImportResolverFn } from '../import-resolvers/types.js'; import { getLanguageGrammar } from '../../tree-sitter/parser-loader.js'; import { parseSourceSafe } from '../../tree-sitter/safe-parse.js'; import { assertCloneable } from '../workers/clone-safety.js'; @@ -31,8 +30,6 @@ const EMPTY_TYPE_CONFIG = { extractParameter: () => null, }; -const noImportResolution: ImportResolverFn = () => null; - function normalizedExt(filePath: string): string { return path.extname(filePath).toLowerCase(); } @@ -318,7 +315,6 @@ export const objectiveCProvider = defineLanguage({ treeSitterQueries: OBJECTIVE_C_SCOPE_QUERY, typeConfig: EMPTY_TYPE_CONFIG, exportChecker: () => true, - importResolver: noImportResolution, classifyFileContent: classifyObjectiveCFileContent, shouldClassifyFileContent: isHeaderPath, preprocessSource: preprocessObjectiveCMacroMarkers, diff --git a/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts b/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts index fb493e466d..20fefe37f9 100644 --- a/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/objective-c/import-target.ts @@ -10,7 +10,7 @@ */ import path from 'path'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { coerceObjectiveCResolutionConfig, normalizeRepoPath, diff --git a/gitnexus/src/core/ingestion/languages/php.ts b/gitnexus/src/core/ingestion/languages/php.ts index 644b6d3522..4fd5a84825 100644 --- a/gitnexus/src/core/ingestion/languages/php.ts +++ b/gitnexus/src/core/ingestion/languages/php.ts @@ -29,8 +29,6 @@ import { } from '../language-provider.js'; import { typeConfig as phpConfig } from '../type-extractors/php.js'; import { phpExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { phpImportConfig } from '../import-resolvers/configs/php.js'; import { PHP_QUERIES } from '../tree-sitter-queries.js'; import { findDescendant, @@ -308,7 +306,6 @@ export const phpProvider = defineLanguage({ treeSitterQueries: PHP_QUERIES, typeConfig: phpConfig, exportChecker: phpExportChecker, - importResolver: createImportResolver(phpImportConfig), callExtractor: createCallExtractor(phpCallConfig), fieldExtractor: createFieldExtractor(phpFieldConfig), methodExtractor: createMethodExtractor(phpMethodConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/php.ts b/gitnexus/src/core/ingestion/languages/php/import-helpers.ts similarity index 95% rename from gitnexus/src/core/ingestion/import-resolvers/php.ts rename to gitnexus/src/core/ingestion/languages/php/import-helpers.ts index 72acba2f09..f112a1031e 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/php.ts +++ b/gitnexus/src/core/ingestion/languages/php/import-helpers.ts @@ -1,13 +1,14 @@ /** * PHP PSR-4 import resolution — internal helpers. * - * Strategy lives in configs/php.ts. + * Used by the PHP ScopeResolver.resolveImportTarget hook. * This file contains the shared helper for PSR-4 resolution via composer.json. */ -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; -import type { ComposerConfig } from '../language-config.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import type { ComposerConfig } from '../../language-config.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** Get or compute the sorted PSR-4 entries (cached after first call). */ function getSortedPsr4(config: ComposerConfig): readonly [string, string][] { @@ -142,5 +143,5 @@ export function resolvePhpImportInternal( // Fallback: suffix matching (works without composer.json) const pathParts = normalized.split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } diff --git a/gitnexus/src/core/ingestion/languages/php/import-target.ts b/gitnexus/src/core/ingestion/languages/php/import-target.ts index ae7783b674..2a9513a744 100644 --- a/gitnexus/src/core/ingestion/languages/php/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/php/import-target.ts @@ -17,10 +17,10 @@ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; import type { ImportResolutionContext } from '../../scope-resolution/contract/scope-resolver.js'; -import { resolvePhpImportInternal } from '../../import-resolvers/php.js'; -import type { SuffixIndex } from '../../import-resolvers/utils.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { getWorkspaceFileIndex } from '../../import-resolvers/workspace-file-index.js'; +import { resolvePhpImportInternal } from './import-helpers.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; import { mergeComposerConfigs, parseComposerConfig, @@ -305,7 +305,7 @@ const getPhpWorkspaceIndex = perFileSet((allFilePaths: ReadonlySet): Php * * DEFERRED for the same reason as the shared `dirMap` (#2903), and here the * case is stronger: `getFilesInDir` has exactly one caller, - * `import-resolvers/php.ts`'s PSR-4 function/constant fallback, and that + * `import-helpers.ts`'s PSR-4 function/constant fallback, and that * caller sits inside `if (composerConfig) { … }`. `resolvePhpImportTarget` * hard-codes `composerConfig: null`, so on the LanguageProvider path the map * is statically unreachable; on the ScopeResolver path it is reachable only diff --git a/gitnexus/src/core/ingestion/languages/python.ts b/gitnexus/src/core/ingestion/languages/python.ts index cd7230abb5..23afcf0052 100644 --- a/gitnexus/src/core/ingestion/languages/python.ts +++ b/gitnexus/src/core/ingestion/languages/python.ts @@ -16,8 +16,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as pythonConfig } from '../type-extractors/python.js'; import { pythonExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { pythonImportConfig } from '../import-resolvers/configs/python.js'; import { PYTHON_QUERIES } from '../tree-sitter-queries.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; import { pythonConfig as pythonFieldConfig } from '../field-extractors/configs/python.js'; @@ -130,7 +128,6 @@ export const pythonProvider = defineLanguage({ treeSitterQueries: PYTHON_QUERIES, typeConfig: pythonConfig, exportChecker: pythonExportChecker, - importResolver: createImportResolver(pythonImportConfig), mroStrategy: 'c3', callExtractor: createCallExtractor(pythonCallConfig), fieldExtractor: createFieldExtractor(pythonFieldConfig), diff --git a/gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts b/gitnexus/src/core/ingestion/languages/python/import-file-index.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts rename to gitnexus/src/core/ingestion/languages/python/import-file-index.ts index d624bb45a6..751a28d149 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/python-file-index.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-file-index.ts @@ -6,7 +6,7 @@ * * Everything here is derived from `allFilePaths` and nothing here is specific * to either CALLER, and there are two of them on opposite sides of a layer - * boundary: `import-resolvers/python.ts` resolves the single-segment bare tier + * boundary: `languages/python/import-helpers.ts` resolves the single-segment bare tier * and `languages/python/import-target.ts` resolves the dotted tiers. The second * imports the first, so the index could not live in either without the other * reaching back through a cycle — it used to live in `import-target.ts`, which @@ -18,7 +18,7 @@ * query functions taking the index. */ -import { perFileSet } from './per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; /** * The importer's ancestor directories, CLOSEST FIRST and excluding the diff --git a/gitnexus/src/core/ingestion/import-resolvers/python.ts b/gitnexus/src/core/ingestion/languages/python/import-helpers.ts similarity index 93% rename from gitnexus/src/core/ingestion/import-resolvers/python.ts rename to gitnexus/src/core/ingestion/languages/python/import-helpers.ts index 9914a76133..e61574d9bb 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/python.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-helpers.ts @@ -2,8 +2,7 @@ * Python import resolution — PEP 328 relative imports and proximity-based bare imports. * Import system spec: PEP 302 (original), PEP 451 (current). * - * Strategy lives in configs/python.ts. - * This file contains the shared internal helper used by the strategy and tests. + * Used by the Python ScopeResolver.resolveImportTarget hook and tests. */ import { @@ -11,8 +10,10 @@ import { importerBarePrefixes, importerDirOf, pythonSegmentAbsent, -} from './python-file-index.js'; -import { tryResolveWithExtensions } from './utils.js'; +} from './import-file-index.js'; +import { tryResolveWithExtensions } from '../../utils/suffix-index.js'; + +const RELATIVE_IMPORT_EXTENSIONS = ['/__init__.py', '.py'] as const; /** * Resolve a Python import to a file path (low-level helper). @@ -22,8 +23,6 @@ import { tryResolveWithExtensions } from './utils.js'; * Approximates the common case where co-located files find each other without an installed package. * Single-segment only — multi-segment (e.g. `os.path`) falls through to suffixResolve. * Checks package (__init__.py) before module (.py), matching CPython's finder order (PEP 451 §4). - * Coexistence of both is physically impossible (same name = file vs directory), so the order - * only matters for spec compliance. * Note: implicit namespace packages (Python 3.3+, directory without __init__.py) are not handled. * * Returns null to let the caller fall through to suffixResolve. @@ -50,7 +49,7 @@ export function resolvePythonImportInternal( dirParts.push(...modulePart.replace(/\./g, '/').split('/')); } - return tryResolveWithExtensions(dirParts.join('/'), allFiles); + return tryResolveWithExtensions(dirParts.join('/'), allFiles, RELATIVE_IMPORT_EXTENSIONS); } // Proximity bare import — single-segment only; package before module (PEP 451 §4) diff --git a/gitnexus/src/core/ingestion/languages/python/import-target.ts b/gitnexus/src/core/ingestion/languages/python/import-target.ts index f48359c1b2..9158094b25 100644 --- a/gitnexus/src/core/ingestion/languages/python/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/python/import-target.ts @@ -11,13 +11,9 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; -import { - getPythonFileIndex, - importerAncestors, - importerDirOf, -} from '../../import-resolvers/python-file-index.js'; -import { resolvePythonImportInternal } from '../../import-resolvers/python.js'; +import { perFileSet } from '../../utils/per-file-set.js'; +import { getPythonFileIndex, importerAncestors, importerDirOf } from './import-file-index.js'; +import { resolvePythonImportInternal } from './import-helpers.js'; export interface PythonResolveContext { readonly fromFile: string; diff --git a/gitnexus/src/core/ingestion/languages/r.ts b/gitnexus/src/core/ingestion/languages/r.ts index 2c29954727..61c2835475 100644 --- a/gitnexus/src/core/ingestion/languages/r.ts +++ b/gitnexus/src/core/ingestion/languages/r.ts @@ -12,7 +12,6 @@ import { SupportedLanguages } from 'gitnexus-shared'; import { defineLanguage } from '../language-provider.js'; import { typeConfig as rTypeConfig } from '../type-extractors/r.js'; -import { resolveRImport } from './r/import-target.js'; import { R_QUERIES } from '../tree-sitter-queries.js'; import { RFieldExtractor } from '../field-extractors/r.js'; import { rMethodExtractor } from '../method-extractors/r.js'; @@ -189,7 +188,6 @@ export const rProvider = defineLanguage({ // Every definition is exported by default. NAMESPACE-driven export refinement lives in // `rPostParse`: an `ExportChecker` has no file-path context, and NAMESPACE detection needs it. exportChecker: () => true, - importResolver: resolveRImport, fieldExtractor: new RFieldExtractor(), methodExtractor: rMethodExtractor, builtInNames: R_BUILT_INS, diff --git a/gitnexus/src/core/ingestion/languages/r/import-target.ts b/gitnexus/src/core/ingestion/languages/r/import-target.ts index 56df8caa8a..dd9895324b 100644 --- a/gitnexus/src/core/ingestion/languages/r/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/r/import-target.ts @@ -4,15 +4,15 @@ */ import path from 'path'; -import type { SuffixIndex } from '../../import-resolvers/utils.js'; -import { suffixResolve } from '../../import-resolvers/utils.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import { EXTENSIONS } from '../import-candidates.js'; import type { ParsedFile } from 'gitnexus-shared'; import { rExportPatternMatches, type RPackageConfig } from './package-config.js'; import { rBareName } from './bare-name.js'; import { rFileTopLevel, rPackageDirForFile, type RFileTopLevel } from './namespace-imports.js'; -import type { ImportResult, ResolveCtx } from '../../import-resolvers/types.js'; import type { ImportResolutionContext } from '../../scope-resolution/contract/scope-resolver.js'; -import { getWorkspaceFileIndex } from '../../import-resolvers/workspace-file-index.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; /** * Low-level R import resolver (internal helper). @@ -51,7 +51,7 @@ export function resolveRImportInternal( if (direct !== undefined) return direct; const pathParts = cleaned.split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } // library("pkg") / require("pkg") — resolve to ALL files in the local package @@ -75,28 +75,7 @@ export function resolveRImportInternal( // Fallback: suffix-based resolution const pathParts = cleaned.split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); -} - -/** R: library/require/source resolution via R package config. */ -export function resolveRImport( - rawImportPath: string, - filePath: string, - ctx: ResolveCtx, -): ImportResult { - const resolved = resolveRImportInternal( - filePath, - rawImportPath, - ctx.normalizedFileList, - ctx.allFileList, - // The legacy `ResolveCtx` bundle never carried R's config; the live path is - // `resolveRImportTarget` + `loadResolutionConfig`. - null, - ctx.index, - ); - if (!resolved) return null; - const files = Array.isArray(resolved) ? resolved : [resolved]; - return { kind: 'files', files }; + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } /** Per-package index of top-level definitions, built once per `parsedFiles` array. */ @@ -247,7 +226,7 @@ export function resolveRNamedImport( * - Cross-language false-positive guard: a `library()`/`require()` package * name not found in `rConfig.packages` would otherwise fall through to * `resolveRImportInternal`'s generic suffix fallback — and `EXTENSIONS` - * (`../../import-resolvers/utils.ts`) has no `.R`/`.r` entry, so a bare R package reference can + * (`languages/import-candidates.ts`) has no `.R`/`.r` entry, so a bare R package reference can * suffix-match an unrelated same-named file in another language. * `context.parsedImport.kind === 'wildcard'` is exactly the * `library()`/`require()` shape (see `interpretRImport`), so the guard is diff --git a/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts index bd7f70f72b..fe089b0e90 100644 --- a/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/r/scope-resolver.ts @@ -35,7 +35,7 @@ import type { KnowledgeGraph } from '../../../graph/types.js'; import { generateId } from '../../../../lib/utils.js'; import { loadRPackageConfig, recordRPackageConfig } from './package-config.js'; import { rBareName } from './bare-name.js'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { resolveRImportTarget } from './import-target.js'; import { isRGlobalNameFallbackPlausible, diff --git a/gitnexus/src/core/ingestion/languages/ruby.ts b/gitnexus/src/core/ingestion/languages/ruby.ts index 7daebcf0c9..ac3ae9d4c1 100644 --- a/gitnexus/src/core/ingestion/languages/ruby.ts +++ b/gitnexus/src/core/ingestion/languages/ruby.ts @@ -23,11 +23,8 @@ import { createLeadingDocDescriptionExtractor, type SyntaxNode } from '../utils/ import { typeConfig as rubyConfig } from '../type-extractors/ruby.js'; import { routeRubyCall } from '../call-routing.js'; import { rubyExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { rubyImportConfig } from '../import-resolvers/configs/ruby.js'; import { RUBY_QUERIES } from '../tree-sitter-queries.js'; -import { createFieldExtractor } from '../field-extractors/generic.js'; -import { rubyConfig as rubyFieldConfig } from '../field-extractors/configs/ruby.js'; +import { rubyFieldExtractor } from './ruby/field-extractor.js'; import { createMethodExtractor } from '../method-extractors/generic.js'; import { rubyMethodConfig } from '../method-extractors/configs/ruby.js'; import { createVariableExtractor } from '../variable-extractors/generic.js'; @@ -214,12 +211,11 @@ export const rubyProvider = defineLanguage({ `, typeConfig: rubyConfig, exportChecker: rubyExportChecker, - importResolver: createImportResolver(rubyImportConfig), callRouter: routeRubyCall, callExtractor: createCallExtractor(rubyCallConfig), resolveEnclosingOwner: rubyResolveEnclosingOwner, resolveContainerTypeOwner: rubyResolveContainerTypeOwner, - fieldExtractor: createFieldExtractor(rubyFieldConfig), + fieldExtractor: rubyFieldExtractor, methodExtractor: createMethodExtractor({ ...rubyMethodConfig, extractFunctionName: rubyExtractFunctionName, diff --git a/gitnexus/src/core/ingestion/languages/ruby/field-extractor.ts b/gitnexus/src/core/ingestion/languages/ruby/field-extractor.ts new file mode 100644 index 0000000000..87f30f0ada --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/ruby/field-extractor.ts @@ -0,0 +1,24 @@ +import type { FieldExtractor } from '../../field-extractor.js'; +import { createFieldExtractor } from '../../field-extractors/generic.js'; +import { rubyConfig } from '../../field-extractors/configs/ruby.js'; + +const declarationExtractor = createFieldExtractor(rubyConfig); + +export const rubyFieldExtractor: FieldExtractor = { + language: declarationExtractor.language, + isTypeDeclaration: (node) => declarationExtractor.isTypeDeclaration(node), + extract(node, context) { + const extracted = declarationExtractor.extract(node, context); + if (extracted === null) return null; + + // Accessors describe one property: any setter makes that property writable. + const writable = new Set(); + for (const field of extracted.fields) { + if (!field.isReadonly) writable.add(field.name); + } + for (const field of extracted.fields) { + if (writable.has(field.name)) field.isReadonly = false; + } + return extracted; + }, +}; diff --git a/gitnexus/src/core/ingestion/import-resolvers/ruby.ts b/gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts similarity index 71% rename from gitnexus/src/core/ingestion/import-resolvers/ruby.ts rename to gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts index b19a6b3c31..141cf7a5fd 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/ruby.ts +++ b/gitnexus/src/core/ingestion/languages/ruby/import-helpers.ts @@ -1,12 +1,12 @@ /** * Ruby require/require_relative import resolution — internal helpers. * - * Strategy lives in configs/ruby.ts. - * This file only contains the low-level helper used by the strategy. + * Used by the Ruby ScopeResolver.resolveImportTarget hook. */ -import type { SuffixIndex } from './utils.js'; -import { suffixResolve } from './utils.js'; +import type { SuffixIndex } from '../../utils/suffix-index.js'; +import { suffixResolve } from '../../utils/suffix-index.js'; +import { EXTENSIONS } from '../import-candidates.js'; /** * Resolve a Ruby require/require_relative path to a matching .rb file (low-level helper). @@ -21,5 +21,5 @@ export function resolveRubyImportInternal( index?: SuffixIndex, ): string | null { const pathParts = importPath.replace(/^\.\//, '').split('/').filter(Boolean); - return suffixResolve(pathParts, normalizedFileList, allFileList, index); + return suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); } diff --git a/gitnexus/src/core/ingestion/languages/ruby/import-target.ts b/gitnexus/src/core/ingestion/languages/ruby/import-target.ts index eae1f56e3b..402f60fdf6 100644 --- a/gitnexus/src/core/ingestion/languages/ruby/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/ruby/import-target.ts @@ -8,8 +8,8 @@ * - Known external gems → null, even if an unrelated repo file suffix matches */ -import { resolveRubyImportInternal } from '../../import-resolvers/ruby.js'; -import { getWorkspaceFileIndex } from '../../import-resolvers/workspace-file-index.js'; +import { resolveRubyImportInternal } from './import-helpers.js'; +import { getWorkspaceFileIndex } from '../../utils/workspace-file-index.js'; import { isHeritageMarker } from '../../utils/heritage-marker.js'; import { findRubyResolutionScope, diff --git a/gitnexus/src/core/ingestion/languages/rust.ts b/gitnexus/src/core/ingestion/languages/rust.ts index 85a4ad1a06..cc01ade725 100644 --- a/gitnexus/src/core/ingestion/languages/rust.ts +++ b/gitnexus/src/core/ingestion/languages/rust.ts @@ -17,8 +17,6 @@ import { defineLanguage } from '../language-provider.js'; import { createLeadingDocDescriptionExtractor, type SyntaxNode } from '../utils/ast-helpers.js'; import { typeConfig as rustConfig } from '../type-extractors/rust.js'; import { rustExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { rustImportConfig } from '../import-resolvers/configs/rust.js'; import { RUST_QUERIES } from '../tree-sitter-queries.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -168,7 +166,6 @@ export const rustProvider = defineLanguage({ treeSitterQueries: RUST_QUERIES, typeConfig: rustConfig, exportChecker: rustExportChecker, - importResolver: createImportResolver(rustImportConfig), mroStrategy: 'qualified-syntax', callExtractor: createCallExtractor(rustCallConfig), fieldExtractor: createFieldExtractor(rustFieldConfig), diff --git a/gitnexus/src/core/ingestion/languages/rust/interpret.ts b/gitnexus/src/core/ingestion/languages/rust/interpret.ts index 547114eaca..4fdcd5f01c 100644 --- a/gitnexus/src/core/ingestion/languages/rust/interpret.ts +++ b/gitnexus/src/core/ingestion/languages/rust/interpret.ts @@ -158,8 +158,16 @@ function findTopLevelComma(text: string): number { return -1; } +// Preserve possible module-function paths until finalized type bindings can +// distinguish module factories from associated functions. Casing is a lint. +const RUST_MODULE_FN_PATH_RE = + /^(?:(?:r#)?[_\p{XID_Start}][\p{XID_Continue}]*::)+(?:r#)?[_\p{XID_Start}][\p{XID_Continue}]*$/u; + function normalizeRustCallReturnType(text: string): string { - let t = text.trim(); + let t = text.trim().replace(/\s*::\s*/g, '::'); + // Kept whole so `resolveQualifiedCallee` can read the function's return + // annotation; the head alone would name the module, not a type (#3498). + if (!t.startsWith('Self::') && RUST_MODULE_FN_PATH_RE.test(t)) return t; // For scoped calls like `Foo::new()`, extract the type part before `::` const scopeIdx = t.indexOf('::'); if (scopeIdx !== -1) { diff --git a/gitnexus/src/core/ingestion/languages/rust/lexical-bindings.ts b/gitnexus/src/core/ingestion/languages/rust/lexical-bindings.ts index 5fada0b77e..6c741921e1 100644 --- a/gitnexus/src/core/ingestion/languages/rust/lexical-bindings.ts +++ b/gitnexus/src/core/ingestion/languages/rust/lexical-bindings.ts @@ -20,6 +20,7 @@ const SCOPE_TYPES = new Set([ 'impl_item', 'enum_item', 'union_item', + 'type_item', ]); /** Pattern identifiers own values even when no useful target/type was indexed. */ @@ -89,6 +90,10 @@ export function collectRustNameClaims(root: SyntaxNode): ReadonlyMap): RustModuleIndex => buildRustModuleIndex(allFilePaths), ); +/** What path resolution reads off the calling file. */ +type RustCaller = Pick; + +/** The callee name ending a `::` path (`make` in `crate::modx::make`). */ +const RUST_PATH_TAIL_RE = /::\s*((?:r#)?[_\p{XID_Start}][\p{XID_Continue}]*)\s*$/u; + +/** + * `ScopeResolver.resolveQualifiedCallee`: the function a callee path names + * (`rp::make` in `let x = rp::make()` or `rp::make().m()`), resolved over the + * module tree exactly like the free call itself, so the call's type and its + * CALLS edge cannot disagree (#3498). A type-qualified path (`Foo::new`) + * names no module and is refused. + */ +export function resolveRustQualifiedCallee( + calleeText: string, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + workspaceIndex: WorkspaceResolutionIndex, + allFilePaths: ReadonlySet, +): SymbolDefinition | undefined { + const name = RUST_PATH_TAIL_RE.exec(calleeText)?.[1]; + if (name === undefined) return undefined; + const filePath = scopes.scopeTree.getScope(inScope)?.filePath; + if (filePath === undefined) return undefined; + const moduleScope = workspaceIndex.moduleScopeByFile.get(filePath); + if (moduleScope === undefined) return undefined; + return resolveRustQualifiedFreeCall( + { name, rawQualifiedName: calleeText, inScope }, + { filePath, moduleScope: moduleScope.id }, + scopes, + workspaceIndex, + allFilePaths, + ); +} + export function resolveRustQualifiedFreeCall( site: { readonly name: string; readonly rawQualifiedName?: string; readonly inScope: ScopeId }, - callerParsed: ParsedFile, + callerParsed: RustCaller, scopes: ScopeResolutionIndexes, workspaceIndex: WorkspaceResolutionIndex, allFilePaths: ReadonlySet, @@ -99,7 +138,13 @@ export function resolveRustQualifiedFreeCall( // which is the part that scales with the workspace. const index = moduleIndexFor(allFilePaths); const pass = passIndexFor(workspaceIndex, index, scopes); - if (!couldNameAModule(qualifier, pass.knownModuleNames)) { + // A `use crate::modx as rp;` alias is a module name only in this file, so the + // workspace-wide filter cannot know it; candidate 2 resolves it. + if ( + !couldNameAModule(qualifier, pass.knownModuleNames) && + importedModulesNamed(qualifier[0], scopes, workspaceIndex, index, site.inScope).next().done === + true + ) { return undefined; } @@ -117,6 +162,7 @@ export function resolveRustQualifiedFreeCall( scopes, workspaceIndex, index, + site.inScope, )) { const hit = findMemberInModule(targetModule, site.name, scopes, workspaceIndex, index) ?? @@ -132,7 +178,7 @@ export function resolveRustQualifiedFreeCall( * makes `super::` correct from inside an inline module. */ function callerModuleOf( - callerParsed: ParsedFile, + callerParsed: RustCaller, inScope: ScopeId, scopes: ScopeResolutionIndexes, index: RustModuleIndex, @@ -166,10 +212,11 @@ function* candidateModules( anchored: { readonly module: RustModule; readonly anchored: boolean }, qualifier: readonly string[], callerModule: RustModule, - callerParsed: ParsedFile, + callerParsed: RustCaller, scopes: ScopeResolutionIndexes, workspaceIndex: WorkspaceResolutionIndex, index: RustModuleIndex, + inScope: ScopeId, ): Generator { if (anchored.anchored) { yield anchored.module; @@ -188,35 +235,59 @@ function* candidateModules( // A `mod` declaration — inline or file-backed — emits a `Namespace` def // bound in the declaring scope, so the check is a binding lookup. const head = qualifier[0]; + if (head === undefined) return; + const claim = lookupNameClaim(inScope, head, scopes, { purpose: 'type' }); + if (claim.status !== 'absent' && claim.bindings.length === 0 && claim.imports.length === 0) + return; if ( - head !== undefined && - declaresSubmodule(callerParsed, callerModule, head, workspaceIndex, index, scopes) - ) { - yield { crateRoot: callerModule.crateRoot, segments: [...callerModule.segments, ...qualifier] }; + claim.bindings.some( + (binding) => + isClassLike(binding.def.type) || + binding.def.type === 'Typedef' || + binding.def.type === 'TypeAlias', + ) + ) + return; + if (claim.imports.length > 0) { + for (const importedModule of importedModulesNamed( + head, + scopes, + workspaceIndex, + index, + inScope, + )) { + yield { + crateRoot: importedModule.crateRoot, + segments: [...importedModule.segments, ...qualifier.slice(1)], + }; + } + return; } - - // 2. A `use` binding for the first segment. Finalize already resolved the - // import to a file, so the module path comes back through the same - // file → module mapping as everything else. Covers `use crate::tools;`, - // `use crate::tools::{self}` and `use crate::a::b as tools`. - // - // The binding must name a MODULE, not a symbol inside one. Import - // resolution deliberately strips a trailing symbol segment when probing for - // a file ("the last segment might be a symbol, not a module" — - // import-resolvers/rust.ts), so `use crate::client::ClientBuilder;` also - // lands on `client/mod.rs`. Taking that at face value made the imported - // TYPE look like the module `client`, and `ClientBuilder::new()` then - // resolved against `client`'s module members — binding an associated - // function to an unrelated module-level `new` (#2741 review H2). - for (const edge of scopes.imports.get(callerParsed.moduleScope) ?? []) { - if (edge.localName !== head || edge.targetFile === null) continue; - const importedModule = moduleOfFile(edge.targetFile, index); - if (importedModule === undefined) continue; - if (!importNamesModule(edge.targetExportedName, importedModule)) continue; - yield { - crateRoot: importedModule.crateRoot, - segments: [...importedModule.segments, ...qualifier.slice(1)], - }; + const namespaces = claim.bindings.filter((binding) => binding.def.type === 'Namespace'); + if (namespaces.length > 0) { + const modules = new Map(); + for (const { def } of namespaces) { + const target = moduleOfImport( + { targetFile: def.filePath, targetExportedName: head, targetDefId: def.nodeId }, + scopes, + workspaceIndex, + index, + ); + if (target !== undefined) + modules.set(`${target.crateRoot}\0${target.segments.join('::')}`, target); + } + if (modules.size === 1) { + const selected = modules.values().next().value!; + yield { + crateRoot: selected.crateRoot, + segments: [...selected.segments, ...qualifier.slice(1)], + }; + } + if (modules.size > 0) return; + } + if (declaresSubmodule(callerParsed, callerModule, head, workspaceIndex, index, scopes)) { + yield { crateRoot: callerModule.crateRoot, segments: [...callerModule.segments, ...qualifier] }; + return; } // 3. Crate-root-relative (`a::b::f()` written from a nested module — 2015 @@ -239,11 +310,69 @@ function* candidateModules( // callee the source never names. The base emitted no edge at all, and per the // doctrine quoted in `ids.ts` that is the correct failure direction: a missing // edge is recoverable, a fabricated caller silently misleads `impact`. - if (callerModule.segments.length > 0 && !headBoundLocally(callerParsed, head, scopes)) { + if ( + claim.status === 'absent' && + callerModule.segments.length > 0 && + !headBoundLocally(callerParsed, head, scopes) + ) { yield { crateRoot: callerModule.crateRoot, segments: [...qualifier] }; } } +/** Modules selected by the nearest lexical type-namespace import. */ +function* importedModulesNamed( + name: string | undefined, + scopes: ScopeResolutionIndexes, + workspaceIndex: WorkspaceResolutionIndex, + index: RustModuleIndex, + inScope: ScopeId, +): Generator { + if (name === undefined) return; + for (const edge of lookupNameClaim(inScope, name, scopes, { purpose: 'type' }).imports) { + if (edge.localName !== name) continue; + const importedModule = moduleOfImport(edge, scopes, workspaceIndex, index); + if (importedModule !== undefined) yield importedModule; + } +} + +/** + * The module a `use` binding names, or `undefined` when it names a symbol. + * + * Path-based import resolution lands on the module's own file + * (`use crate::tools;` → `tools.rs`). Cargo-aware resolution instead binds the + * module's DECLARATION — the `Namespace` def `mod tools;` leaves in its parent's + * file — so the module is the parent's path plus the def's name. Only a + * declaration bound at its file's top level (or carrying its enclosing path in + * `namespacePrefix`) is read this way; a nested inline `mod` def records no + * enclosing path, and guessing one could name the wrong module. + */ +function moduleOfImport( + edge: { + readonly targetFile: string | null; + readonly targetExportedName: string; + readonly targetDefId?: string; + }, + scopes: ScopeResolutionIndexes, + workspaceIndex: WorkspaceResolutionIndex, + index: RustModuleIndex, +): RustModule | undefined { + const declaration = + edge.targetDefId === undefined ? undefined : scopes.defs.get(edge.targetDefId); + if (declaration !== undefined && declaration.type !== 'Namespace') return undefined; + if (declaration?.type === 'Namespace' && declaration.qualifiedName !== undefined) { + const name = tailSegment(declaration.qualifiedName); + if (!isModuleLevelMember(declaration, name, workspaceIndex)) return undefined; + const parent = moduleOfDef(declaration.filePath, declaration.namespacePrefix, index); + return parent === undefined + ? undefined + : { crateRoot: parent.crateRoot, segments: [...parent.segments, name] }; + } + if (edge.targetFile === null) return undefined; + const importedModule = moduleOfFile(edge.targetFile, index); + if (importedModule === undefined) return undefined; + return importNamesModule(edge.targetExportedName, importedModule) ? importedModule : undefined; +} + /** * Is `name` bound in the caller's own module to anything that is NOT a module? * @@ -253,7 +382,7 @@ function* candidateModules( * case, which candidate 2 already handles, is not double-counted here. */ function headBoundLocally( - callerParsed: ParsedFile, + callerParsed: RustCaller, name: string | undefined, scopes: ScopeResolutionIndexes, ): boolean { @@ -290,7 +419,7 @@ function tailSegment(qualifiedName: string): string { * contributes nothing and cannot outrank a real `use` binding (#2741 review). */ function declaresSubmodule( - callerParsed: ParsedFile, + callerParsed: RustCaller, callerModule: RustModule, name: string, workspaceIndex: WorkspaceResolutionIndex, @@ -483,7 +612,7 @@ interface PassModuleIndex { } /** - * DELIBERATELY NOT ON `import-resolvers/per-file-set.ts` (#2909 sweep), unlike + * DELIBERATELY NOT ON `utils/per-file-set.ts` (#2909 sweep), unlike * {@link moduleIndexFor} above. {@link passIndexFor} takes THREE inputs — * `workspaceIndex`, `index` and `scopes` — and keys on the first alone; the * builder reads `scopes.defs.byId` and `index`, neither of which is derivable diff --git a/gitnexus/src/core/ingestion/languages/rust/query.ts b/gitnexus/src/core/ingestion/languages/rust/query.ts index 02b9dde2a3..d57fe0208f 100644 --- a/gitnexus/src/core/ingestion/languages/rust/query.ts +++ b/gitnexus/src/core/ingestion/languages/rust/query.ts @@ -13,6 +13,7 @@ const RUST_SCOPE_QUERY = ` (function_signature_item) @scope.function (closure_expression) @scope.function (block) @scope.block +(type_item) @scope.block (if_expression) @scope.block (match_expression) @scope.block (match_arm) @scope.block diff --git a/gitnexus/src/core/ingestion/languages/rust/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/rust/scope-resolver.ts index f1cab711eb..d90cce9d5c 100644 --- a/gitnexus/src/core/ingestion/languages/rust/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/rust/scope-resolver.ts @@ -1,4 +1,4 @@ -import type { ParsedFile } from 'gitnexus-shared'; +import type { ParsedFile, TypeRef } from 'gitnexus-shared'; import { SupportedLanguages } from 'gitnexus-shared'; import { buildMro, defaultLinearize } from '../../scope-resolution/passes/mro.js'; import type { ScopeResolver } from '../../scope-resolution/contract/scope-resolver.js'; @@ -6,7 +6,7 @@ import { indexOnlyElementType } from '../../type-extractors/shared.js'; import { rustProvider } from '../rust.js'; import { rustArityCompatibility, rustMergeBindings, resolveRustImportTarget } from './index.js'; import { populateRustOwners } from './method-owners.js'; -import { resolveRustQualifiedFreeCall } from './qualified-call.js'; +import { resolveRustQualifiedCallee, resolveRustQualifiedFreeCall } from './qualified-call.js'; import { populateRustRangeBindings } from './range-binding.js'; import { isClassLike, @@ -170,6 +170,33 @@ export const rustScopeResolver: ScopeResolver = { resolveQualifiedFreeCall: (site, callerParsed, scopes, workspaceIndex, allFilePaths) => resolveRustQualifiedFreeCall(site, callerParsed, scopes, workspaceIndex, allFilePaths), + resolveQualifiedCallee: resolveRustQualifiedCallee, + + // A qualified initializer may name either a module factory or an associated + // function. Restore the constructor's type only after lexical type ownership + // is known, before imported-return propagation follows the remaining paths. + populateNamespaceSiblings: (parsedFiles, scopes) => { + for (const parsed of parsedFiles) { + for (const scope of parsed.scopes) { + for (const [name, ref] of scope.typeBindings) { + if (ref.source !== 'constructor-inferred') continue; + const separator = ref.rawName.lastIndexOf('::'); + if (separator < 1) continue; + const owner = ref.rawName.slice(0, separator); + if ( + findClassBindingInScope(ref.declaredAtScope, owner, scopes, undefined, { + uniqueQualifiedNameFallback: false, + purpose: 'type', + position: ref.lookupPosition ?? ref.bindingRange, + }) !== undefined + ) { + (scope.typeBindings as Map).set(name, { ...ref, rawName: owner }); + } + } + } + } + }, + buildMro: (graph, parsedFiles, nodeLookup) => buildRustMro(graph, parsedFiles, nodeLookup), emitHeritageEdges: (graph, parsedFiles, nodeLookup, scopes, recordTypeArguments) => diff --git a/gitnexus/src/core/ingestion/languages/swift.ts b/gitnexus/src/core/ingestion/languages/swift.ts index d0092c47b3..57d06ee674 100644 --- a/gitnexus/src/core/ingestion/languages/swift.ts +++ b/gitnexus/src/core/ingestion/languages/swift.ts @@ -14,8 +14,6 @@ import { defineLanguage } from '../language-provider.js'; import type { AstFrameworkPatternConfig } from '../language-provider.js'; import { typeConfig as swiftConfig } from '../type-extractors/swift.js'; import { swiftExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { swiftImportConfig } from '../import-resolvers/configs/swift.js'; import { SWIFT_QUERIES } from '../tree-sitter-queries.js'; import type { SyntaxNode } from '../utils/ast-helpers.js'; import { createLeadingDocDescriptionExtractor } from '../utils/ast-helpers.js'; @@ -239,7 +237,6 @@ export const swiftProvider = defineLanguage({ treeSitterQueries: SWIFT_QUERIES, typeConfig: swiftConfig, exportChecker: swiftExportChecker, - importResolver: createImportResolver(swiftImportConfig), callExtractor: createCallExtractor(swiftCallConfig), fieldExtractor: createFieldExtractor(swiftFieldConfig), methodExtractor: createMethodExtractor({ diff --git a/gitnexus/src/core/ingestion/languages/swift/import-target.ts b/gitnexus/src/core/ingestion/languages/swift/import-target.ts index 85add32095..a2e8479fcb 100644 --- a/gitnexus/src/core/ingestion/languages/swift/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/swift/import-target.ts @@ -19,7 +19,7 @@ */ import type { ParsedFile, ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { perFileSet } from '../../utils/per-file-set.js'; import { coerceDeclaredSwiftTargets, swiftDeclaredTargetPrefix, diff --git a/gitnexus/src/core/ingestion/languages/typescript.ts b/gitnexus/src/core/ingestion/languages/typescript.ts index 56aae341fd..32f2e95cb4 100644 --- a/gitnexus/src/core/ingestion/languages/typescript.ts +++ b/gitnexus/src/core/ingestion/languages/typescript.ts @@ -29,6 +29,7 @@ import { isModuleLevelThisExport, isShadowedCjsExportAssignmentNode, } from './typescript/cjs-export-assignment.js'; +import { collectCommonJsModuleKind, withCommonJsModuleKind } from './typescript/module-kind.js'; const rootOf = (node: SyntaxNode): SyntaxNode | undefined => (node as { tree?: { rootNode?: SyntaxNode } }).tree?.rootNode; @@ -76,11 +77,6 @@ const memberAssignmentLabel = (node: SyntaxNode): NodeLabel | null => { import { createTypeScriptCfgVisitor } from '../cfg/visitors/typescript.js'; import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js'; import { tsExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { - typescriptImportConfig, - javascriptImportConfig, -} from '../import-resolvers/configs/typescript-javascript.js'; import { TYPESCRIPT_QUERIES, JAVASCRIPT_QUERIES } from '../tree-sitter-queries.js'; import { typescriptFieldExtractor } from '../field-extractors/typescript.js'; import { createFieldExtractor } from '../field-extractors/generic.js'; @@ -491,7 +487,6 @@ export const typescriptProvider = defineLanguage({ typeConfig: typescriptConfig, scopeOwnsReceivers: tsScopeOwnsReceivers, exportChecker: tsExportChecker, - importResolver: createImportResolver(typescriptImportConfig), callExtractor: createCallExtractor(typescriptCallConfig), fieldExtractor: typescriptFieldExtractor, methodExtractor: createMethodExtractor({ @@ -528,7 +523,8 @@ export const typescriptProvider = defineLanguage({ // ./typescript/index.ts for the full per-hook rationale and the // canonical capture vocabulary in ./typescript/query.ts // (TYPESCRIPT_SCOPE_QUERY constant). - emitScopeCaptures: emitTsScopeCaptures, + emitScopeCaptures: withCommonJsModuleKind(emitTsScopeCaptures), + collectCaptureSideChannel: collectCommonJsModuleKind, // CFG/PDG substrate (#2081 M1) — runs in the worker on a --pdg run. cfgVisitor: createTypeScriptCfgVisitor(), interpretImport: interpretTsImport, @@ -592,7 +588,6 @@ export const javascriptProvider = defineLanguage({ typeConfig: typescriptConfig, scopeOwnsReceivers: tsScopeOwnsReceivers, exportChecker: tsExportChecker, - importResolver: createImportResolver(javascriptImportConfig), callExtractor: createCallExtractor(javascriptCallConfig), fieldExtractor: createFieldExtractor(javascriptConfig), methodExtractor: createMethodExtractor({ @@ -623,7 +618,8 @@ export const javascriptProvider = defineLanguage({ // semantics are identical; JS-specific additions (CJS require(), // JSDoc type bindings) live in ./javascript/captures.ts. // See ./javascript/index.ts for the full per-module rationale. - emitScopeCaptures: emitJsScopeCaptures, + emitScopeCaptures: withCommonJsModuleKind(emitJsScopeCaptures), + collectCaptureSideChannel: collectCommonJsModuleKind, // CFG/PDG substrate (#2081 M1) — TS and JS share the same grammar family. cfgVisitor: createTypeScriptCfgVisitor(), interpretImport: interpretJsImport, diff --git a/gitnexus/src/core/ingestion/languages/typescript/captures.ts b/gitnexus/src/core/ingestion/languages/typescript/captures.ts index 59879a6f1a..3ba0f2a945 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/captures.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/captures.ts @@ -22,9 +22,11 @@ * 5. **Receiver-binding synthesis** (Unit 3) — `this` type anchors on * instance methods, with arrow-function lexical-this walk-up. * - * Pure given the input source text. No I/O, no globals consulted. + * Derives captures from its inputs and records CommonJS classification for + * immediate side-channel collection. Performs no I/O. */ +import { recordCommonJsModuleKind } from './module-kind.js'; import type { Capture, CaptureMatch } from 'gitnexus-shared'; import { findNodeAtRange, @@ -284,7 +286,12 @@ export const TS_CLASS_FIELD_DEFINITION_TYPES: ReadonlySet = new Set([ * For a class declaring BOTH twins the wrong edge does not disappear, it MOVES: * `Host.p` now reads the INSTANCE twin's binding, because that is what is left * in the map under that name. Only the no-twin case — the common static shape — - * is a true missed edge. + * is a true missed edge, and its first hop no longer is: the field extractor + * records the type the initializer constructs on the static Property NODE + * (`initializerType`), and the class-level receiver route in + * `receiver-bound-calls.ts` reads it there, so `Host.q.m()` resolves `Wrong.m` + * without the binding ever entering the shared map. A longer chain off it + * (`Host.q.m().n()`) still goes through the fold and is still missed. * * The trade is still the right one, since `this.p` is overwhelmingly the more * common access and a `Host.p` static chain is the cheaper place to be wrong. @@ -297,7 +304,8 @@ export const TS_CLASS_FIELD_DEFINITION_TYPES: ReadonlySet = new Set([ * with automatic parser-cache invalidation. Both shapes are pinned by rows in * `test/integration/resolvers/inferred-field-receiver-matrix.test.ts` * (`static-read-of-a-same-name-twin-picks-up-the-instance-type`, - * `static-read-without-a-twin-loses-its-type`), so the cost moves visibly. + * `static-read-without-a-twin-types-from-its-initializer`), so the cost moves + * visibly. * * Sibling of {@link isStaticMethodThis}, which drops the ASSIGNMENT form * (`this.x = new Y()` inside a static method). Together they cover both ways a @@ -393,6 +401,8 @@ export function emitTsScopeCaptures( recordCacheHit(); } + recordCommonJsModuleKind(tree.rootNode, filePath); + const rawMatches = getTsScopeQuery(grammarPath).matches(tree.rootNode); // Export evidence, read once per file (see `ts-js-export-marker.ts`). const exportEvidence = collectEsmExportEvidence(tree.rootNode, filePath); diff --git a/gitnexus/src/core/ingestion/languages/typescript/cjs-export-assignment.ts b/gitnexus/src/core/ingestion/languages/typescript/cjs-export-assignment.ts index a82557ac0c..4647c3c6cb 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/cjs-export-assignment.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/cjs-export-assignment.ts @@ -192,7 +192,7 @@ const THIS_BINDING_NODE_TYPES = new Set([ * `exports`/`module` reference marks it CommonJS. A file with neither signal * is left alone — silence is not evidence of CommonJS. */ -function isCommonJsModule(root: SyntaxNode, filePath?: string): boolean { +export function isCommonJsModule(root: SyntaxNode, filePath?: string): boolean { // The extension settles it outright where Node itself does: `.cjs`/`.cts` are // CommonJS whatever the body contains, `.mjs`/`.mts` are ESM. Without this a // `.cjs` file whose only content is `this.x = fn` carries no AST signal and @@ -206,19 +206,29 @@ function isCommonJsModule(root: SyntaxNode, filePath?: string): boolean { if (cached !== undefined) return cached; let sawCjsSignal = false; - const visit = (node: SyntaxNode): boolean => { + let sawEsmSignal = false; + const pending = [root]; + while (pending.length > 0) { + const node = pending.pop(); + if (node === undefined) break; // An ESM statement settles it immediately: top-level `this` is undefined. - if (node.type === 'import_statement' || node.type === 'export_statement') return false; + if (node.type === 'import_statement' || node.type === 'export_statement') { + sawEsmSignal = true; + break; + } if (node.type === 'identifier' && (node.text === 'exports' || node.text === 'module')) sawCjsSignal = true; if (node.type === 'call_expression' && node.childForFieldName('function')?.text === 'require') sawCjsSignal = true; - for (const child of node.namedChildren) if (!visit(child)) return false; - return true; - }; + const children = node.namedChildren; + for (let i = children.length - 1; i >= 0; i--) { + const child = children[i]; + if (child !== undefined) pending.push(child); + } + } - const result = visit(root) && sawCjsSignal; + const result = !sawEsmSignal && sawCjsSignal; isCommonJsByRoot.set(root, result); return result; } diff --git a/gitnexus/src/core/ingestion/languages/typescript/cjs-export-receiver.ts b/gitnexus/src/core/ingestion/languages/typescript/cjs-export-receiver.ts new file mode 100644 index 0000000000..c7fe642f0b --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/typescript/cjs-export-receiver.ts @@ -0,0 +1,42 @@ +import type { ParsedFile, ReferenceSite } from 'gitnexus-shared'; +import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; +import { lookupNameClaim } from '../../scope-resolution/scope/walkers.js'; +import { decodeReceiverChain } from '../../utils/receiver-chain-codec.js'; + +/** + * True when `site` writes a member of `module.exports` and `module` is the + * CommonJS module object. + * + * `module` must resolve to NOTHING in scope. The canonical UMD wrapper and any + * `function wrap(module) { … }` take it as a parameter, and a write through that + * local is a write to a value the resolver cannot type — a real drop, not a + * declaration. Same rule `cjs-export-assignment.ts` applies to `exports` on the + * capture side, asked here of the resolved scope chain instead of the AST. + */ +export function isCommonJsExportAssignment( + site: ReferenceSite, + scopes: ScopeResolutionIndexes, + parsed: ParsedFile, +): boolean { + if (parsed.captureSideChannel !== true) return false; + if (site.kind !== 'write') return false; + if (!isModuleExportsReceiver(site)) return false; + const claim = lookupNameClaim(site.inScope, 'module', scopes, { + position: site.atRange, + purpose: 'value', + }); + return claim.status === 'absent'; +} + +function isModuleExportsReceiver(site: ReferenceSite): boolean { + const chain = decodeReceiverChain(site.receiverChain); + if (chain === undefined) return site.explicitReceiver?.name === 'module.exports'; + const [step] = chain.steps; + return ( + chain.baseReceiverName === 'module' && + !chain.truncated && + chain.steps.length === 1 && + step?.kind === 'field' && + step.name === 'exports' + ); +} diff --git a/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts b/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts index 421959788f..963814be74 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/file-candidates.ts @@ -4,7 +4,7 @@ * Shared by `module-resolution.ts` and the package-manifest resolver so both * try the same three shapes — exact path, extension, directory index — and, as * importantly, the same NARROW extension list. The repo-wide `EXTENSIONS` in - * `import-resolvers/utils.ts` carries ~39 entries spanning every language the + * `languages/import-candidates.ts` carries ~39 entries spanning every language the * indexer supports; a TypeScript import cannot resolve to a `.py` or `.rb` * file, and letting it try was part of how the old suffix matcher found files * that had nothing to do with the import. diff --git a/gitnexus/src/core/ingestion/languages/typescript/import-target.ts b/gitnexus/src/core/ingestion/languages/typescript/import-target.ts index 2100a77176..9f1ad105f9 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/import-target.ts @@ -18,7 +18,7 @@ */ import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from './workspace-packages.js'; import { resolveTsModule } from './module-resolution.js'; import type { TsconfigIndex } from './tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/typescript/module-kind.ts b/gitnexus/src/core/ingestion/languages/typescript/module-kind.ts new file mode 100644 index 0000000000..5f945108ba --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/typescript/module-kind.ts @@ -0,0 +1,27 @@ +import type { LanguageProvider } from '../../language-provider.js'; +import type { SyntaxNode } from '../../utils/ast-helpers.js'; +import { assertCloneable } from '../../workers/clone-safety.js'; +import { isCommonJsModule } from './cjs-export-assignment.js'; + +type CaptureEmitter = NonNullable; + +// Collected immediately after extraction. Keep only the file's scalar fact; +// standalone capture calls cannot retain ASTs or maps. +let pending: { readonly filePath: string; readonly commonJs: boolean } | undefined; + +export function withCommonJsModuleKind(emit: CaptureEmitter): CaptureEmitter { + return (...args) => { + pending = undefined; + return emit(...args); + }; +} + +export function recordCommonJsModuleKind(root: SyntaxNode, filePath: string): void { + pending = { filePath, commonJs: isCommonJsModule(root, filePath) }; +} + +export function collectCommonJsModuleKind(filePath: string): boolean | undefined { + const captured = pending; + pending = undefined; + return captured?.filePath === filePath ? assertCloneable(captured.commonJs) : undefined; +} diff --git a/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts b/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts index ea8d2d637e..88c986324f 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/module-resolution.ts @@ -2,7 +2,7 @@ * TypeScript / JavaScript module resolution (#2953). * * This is the algorithm `tsc` and Node actually run, in the order they run it. - * It replaces `import-resolvers/utils.ts:suffixResolve` on the TS/JS/Vue path, + * It replaces `utils/suffix-index.ts:suffixResolve` on the TS/JS/Vue path, * which answered a different question — "does any file in this repo have a path * ending in this specifier?" — and answered it by dropping leading segments * until something matched. That is why `@acme/telemetry/nest`, a registry @@ -31,14 +31,14 @@ * 6. anything else — external. `null`. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from './workspace-packages.js'; import { matchSubpathMap, nodePackageNameOf, owningPackage, resolveNodeWorkspaceImport, substituteStar, -} from '../../import-resolvers/node-workspace-packages.js'; +} from './workspace-packages.js'; import { resolveFile } from './file-candidates.js'; import { tsconfigFor, type TsconfigIndex, type TsPathMapping } from './tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts index 9d75676b9d..0d150511aa 100644 --- a/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/scope-resolver.ts @@ -24,11 +24,9 @@ import { simpleKey } from '../../scope-resolution/graph-bridge/node-lookup.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import { typescriptProvider } from '../typescript.js'; import { typescriptModuleExports } from './module-exports.js'; +import { isCommonJsExportAssignment } from './cjs-export-receiver.js'; import { loadTsconfigIndex, type TsconfigIndex } from './tsconfig.js'; -import { - loadNodeWorkspacePackages, - type NodeWorkspacePackages, -} from '../../import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages, type NodeWorkspacePackages } from './workspace-packages.js'; import { indexOnlyElementType } from '../../type-extractors/shared.js'; import { typescriptArityCompatibility, typescriptMergeBindings, resolveTsTarget } from './index.js'; import { @@ -137,6 +135,8 @@ const typescriptScopeResolver: ScopeResolver = { // contain the substring `super` (e.g. `superman`). isSuperReceiver: (text) => /^super(\s*\(|\s*\.|\s*\[|\s*$)/.test(text.trim()), + isModuleExportAssignment: isCommonJsExportAssignment, + // TypeScript is statically typed — field-fallback heuristic off // (the type-binding layer produces precise owner types). Return- // type propagation across imports on (matches the legacy DAG's diff --git a/gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts b/gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts rename to gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts index 2f36e35e27..c3c4392c98 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/node-workspace-packages.ts +++ b/gitnexus/src/core/ingestion/languages/typescript/workspace-packages.ts @@ -20,9 +20,9 @@ import path from 'path'; import { createRequire } from 'node:module'; import type Parser from 'tree-sitter'; -import { isHardcodedIgnoredDirectoryAtPath } from '../../../config/ignore-service.js'; -import { logger } from '../../logger.js'; -import { resolveFile } from '../languages/typescript/file-candidates.js'; +import { isHardcodedIgnoredDirectoryAtPath } from '../../../../config/ignore-service.js'; +import { logger } from '../../../logger.js'; +import { resolveFile } from './file-candidates.js'; // `js-yaml` is CJS; the rest of this repository reaches it the same way // (`core/group/config-parser.ts`, `cli/group.ts`). @@ -830,7 +830,7 @@ async function staticViteEntry(text: string): Promise { const [{ default: TreeSitter }, { default: grammar }, { parseSourceSafe }] = await Promise.all([ import('tree-sitter'), import('tree-sitter-typescript'), - import('../../tree-sitter/safe-parse.js'), + import('../../../tree-sitter/safe-parse.js'), ]); const parser = new TreeSitter(); parser.setLanguage(grammar.typescript); diff --git a/gitnexus/src/core/ingestion/languages/vue.ts b/gitnexus/src/core/ingestion/languages/vue.ts index 9475d8a7be..ca8d49c041 100644 --- a/gitnexus/src/core/ingestion/languages/vue.ts +++ b/gitnexus/src/core/ingestion/languages/vue.ts @@ -17,8 +17,6 @@ import { vueClassConfig } from '../class-extractors/configs/typescript-javascrip import { defineLanguage } from '../language-provider.js'; import { typeConfig as typescriptConfig } from '../type-extractors/typescript.js'; import { tsExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { vueImportConfig } from '../import-resolvers/configs/typescript-javascript.js'; import { TYPESCRIPT_QUERIES } from '../tree-sitter-queries.js'; import { typescriptFieldExtractor } from '../field-extractors/typescript.js'; import { BUILT_INS as TS_BUILT_INS } from './typescript.js'; @@ -86,7 +84,6 @@ export const vueProvider = defineLanguage({ treeSitterQueries: TYPESCRIPT_QUERIES, typeConfig: typescriptConfig, exportChecker: tsExportChecker, - importResolver: createImportResolver(vueImportConfig), callExtractor: createCallExtractor(typescriptCallConfig), fieldExtractor: typescriptFieldExtractor, variableExtractor: createVariableExtractor(typescriptVariableConfig), diff --git a/gitnexus/src/core/ingestion/languages/vue/import-target.ts b/gitnexus/src/core/ingestion/languages/vue/import-target.ts index 886580b0ef..2e7d363a15 100644 --- a/gitnexus/src/core/ingestion/languages/vue/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/vue/import-target.ts @@ -8,7 +8,7 @@ * Vue-specific guessing is required — the exact-path branch finds them first. */ -import type { NodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import type { NodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { resolveTsTarget } from '../typescript/import-target.js'; import type { TsconfigIndex } from '../typescript/tsconfig.js'; diff --git a/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts index f9021631d9..4d64953352 100644 --- a/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/vue/scope-resolver.ts @@ -63,7 +63,7 @@ import { simpleKey } from '../../scope-resolution/graph-bridge/node-lookup.js'; import { vueProvider } from '../vue.js'; import { loadTsconfigIndex } from '../typescript/tsconfig.js'; import { typescriptModuleExports } from '../typescript/module-exports.js'; -import { loadNodeWorkspacePackages } from '../../import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../typescript/workspace-packages.js'; import { typescriptArityCompatibility, typescriptMergeBindings } from '../typescript/index.js'; import { makeVueResolveImportTarget } from './import-target.js'; import { extractVueTemplateEdgeData } from '../../vue-sfc-extractor.js'; diff --git a/gitnexus/src/core/ingestion/languages/zig.ts b/gitnexus/src/core/ingestion/languages/zig.ts index 9b5c9eff9e..da28085a37 100644 --- a/gitnexus/src/core/ingestion/languages/zig.ts +++ b/gitnexus/src/core/ingestion/languages/zig.ts @@ -8,7 +8,7 @@ import { zigRenameProvider } from './zig/rename.js'; * `@heritage.*` captures). * - exportChecker: walks to the enclosing variable_declaration / * function_declaration and looks for a `pub` or `export` keyword child. - * - importResolver: resolves local `@import("./foo.zig")` paths and + * - ScopeResolver.resolveImportTarget: resolves local `@import("./foo.zig")` paths and * build.zig.zon `.path` deps (root the dep's build.zig declares, then * src/root.zig, src/.zig, src/main.zig); `@import("std")` and * `.url` packages are deliberately external. @@ -35,8 +35,6 @@ import { SupportedLanguages } from 'gitnexus-shared'; import { defineLanguage } from '../language-provider.js'; import { ZIG_QUERIES } from '../tree-sitter-queries.js'; import { zigExportChecker } from '../export-detection.js'; -import { createImportResolver } from '../import-resolvers/resolver-factory.js'; -import { zigImportConfig } from '../import-resolvers/configs/zig.js'; import { createCallExtractor } from '../call-extractors/generic.js'; import { zigCallConfig } from '../call-extractors/configs/zig.js'; import { createClassExtractor } from '../class-extractors/generic.js'; @@ -79,7 +77,6 @@ export const zigProvider = defineLanguage({ typeConfig: zigTypeConfig, cfgVisitor: createZigCfgVisitor(), exportChecker: zigExportChecker, - importResolver: createImportResolver(zigImportConfig), callExtractor: createCallExtractor(zigCallConfig), classExtractor: createClassExtractor(zigClassConfig), fieldExtractor: createFieldExtractor(zigFieldConfig), diff --git a/gitnexus/src/core/ingestion/languages/zig/captures.ts b/gitnexus/src/core/ingestion/languages/zig/captures.ts index 1e6b1c03de..721f4a2547 100644 --- a/gitnexus/src/core/ingestion/languages/zig/captures.ts +++ b/gitnexus/src/core/ingestion/languages/zig/captures.ts @@ -28,6 +28,13 @@ const STATIC_GATED_MARKER: Capture = Object.freeze({ text: '', }); const NO_IMPORT_ALIASES: ZigImportAliasMap = new Map(); +/** The site anchors of the query's receiver-bearing reference rules. */ +const ZIG_RECEIVER_SITE_ANCHORS = [ + '@reference.read', + '@reference.value-ref', + '@reference.call.member', + '@reference.call.constructor', +] as const; /** Stamp `@reference.static-gated` onto every call capture whose anchor sits * in a statically dead range. File-local constants only for now (v1): the @@ -83,15 +90,30 @@ export function zigImportRootOf(value: SyntaxNode | null): SyntaxNode | null { * `@import("dump.zig").root(...)` — or of a qualified construction — * `@import("a.zig").Thing{…}` — i.e. the `object` of a `field_expression` * that is the `function` of a `call_expression` or the type of a - * `struct_initializer`? A deeper chain (`@import("x.zig").Foo.init()`) is - * not: its receiver is `….Foo`, and the builtin is only the module the chain - * starts from (the namespace chain walk resolves it from there). */ + * `struct_initializer`? Or of the member READ a one-member import + * declaration makes — `const X = @import("f.zig").X;` — which the deep form + * (`@import("lib.zig").B.work`, `collectZigDeepAliases`) already binds: the + * named import records `X`, but the `.X` read beside it had a receiver + * nothing was bound to, so it was a receiver drop, and a renaming alias + * (`const Gauge = @import("u.zig").DEFAULT_NS;`) reached nothing at all + * (#3498 triage, F-A). Any other deeper chain (`@import("x.zig").Foo.init()`) + * is not: its receiver is `….Foo`, and the builtin is only the module the + * chain starts from (the namespace chain walk resolves it from there). */ export function isZigInlineImportReceiver(importNode: SyntaxNode): boolean { const field = importNode.parent; if (field?.type !== 'field_expression') return false; if (field.childForFieldName('object')?.id !== importNode.id) return false; const use = field.parent; if (use === null || use === undefined) return false; + if (use.type === 'variable_declaration') { + // The VALUE only: `var x: @import("m.zig").T = undefined;` types a + // variable and imports nothing (`isZigTypePositionImport`). + return ( + isZigKeywordDeclaration(use) && + use.childForFieldName('type')?.id !== field.id && + use.namedChildren.filter((child) => child !== null).at(-1)?.id === field.id + ); + } if (use.type === 'call_expression') return use.childForFieldName('function')?.id === field.id; // `@import("a.zig").Thing{…}` — the module is the receiver of a qualified // CONSTRUCTION (the `@reference.call.constructor` rule with a receiver, see @@ -601,6 +623,37 @@ export function zigTypeConstructorOf(containerNode: SyntaxNode): SyntaxNode | nu return fn.childForFieldName('type')?.text === 'type' ? fn : null; } +/** For a type constructor that FORWARDS to another — `fn Bridge(comptime T: + * type) type { return Builder(T); }`, Lightpanda's `js.Bridge(T)` — the + * callee as written (`Builder`, `other.Builder`); undefined for any other + * fn. `Bridge(X)` IS `Builder(X)`, but neither `zigReturnTypeIsNominal` (a + * `type` return) nor `zigTypeConstructorOf` (no container in the body) gives + * `Bridge` a type, so a receiver typed `Bridge(X)` reached a Function that + * owns no members (#3498 triage, F-B). Only the literal shape counts: a body + * that is ONE `return ` (comments aside), whose callee is not + * a parameter of the fn (`return F(u8)` applies the caller's choice). */ +export function zigForwardedTypeConstructor(fn: SyntaxNode): string | undefined { + if (fn.type !== 'function_declaration' || fn.childForFieldName('type')?.text !== 'type') { + return undefined; + } + const statements = (fn.childForFieldName('body')?.namedChildren ?? []).filter( + (c): c is SyntaxNode => c !== null && c.type !== 'comment', + ); + const [only] = statements; + if (statements.length !== 1 || only?.type !== 'expression_statement') return undefined; + const ret = only.namedChild(0); + const value = ret?.type === 'return_expression' ? ret.namedChild(0) : null; + if (value === null || value === undefined || !isZigTypeConstructorCall(value)) return undefined; + const callee = value.childForFieldName('function'); + const head = callee === null ? null : zigChainHead(callee); + if (callee === null || head === null) return undefined; + const params = fn.namedChildren.find((c): c is SyntaxNode => c?.type === 'parameters'); + const appliesParameter = (params?.namedChildren ?? []).some( + (p) => p?.type === 'parameter' && p.childForFieldName('name')?.text === head.text, + ); + return appliesParameter ? undefined : callee.text; +} + /** F7 — is `call` an instantiation of a generic type constructor — * `List(u8)`, `util.List(u8)`, `js.Bridge(T)`, `std.AutoHashMapUnmanaged(K, V)`? * Zig spells a generic type as a CALL, and the grammar cannot separate it @@ -615,6 +668,14 @@ export function isZigTypeConstructorCall(call: SyntaxNode): boolean { return /^[A-Z]/.test(callee.text); } +/** The text twin of `isZigTypeConstructorCall`, for the resolver's + * `isTypeApplicationCall` hook, which sees a receiver call's callee as + * written (`Stack`, `util.List`) rather than as a node: its last + * identifier is TitleCase. Same heuristic, same caveat. */ +export function isZigTypeConstructorCallee(callee: string): boolean { + return /^[A-Z]\w*$/.test(callee.slice(callee.lastIndexOf('.') + 1)); +} + /** A `fn` nested in a struct/enum/union/opaque container is a method. Single * predicate shared between the provider's `labelOverride` (worker * structure phase) and the scope-capture relabel below, so the graph @@ -1328,13 +1389,18 @@ export function emitZigScopeCaptures( // `root` in dump.zig exactly as it would for `const dump = // @import("dump.zig"); dump.root(...)`. Anything else is a side-effect // import (file edge only), emitted once per distinct source per file. + // A one-member import declaration's builtin is claimed by its binding + // rule (the named import owns the file edge) and is still a receiver: it + // gets the namespace binding and nothing else. const inlineImport = nodeMap['@import.inline']; if (inlineImport !== undefined) { const source = nodeMap['@import.source']!; - if (claimedImportSourceIds.has(source.id)) continue; + const isReceiver = + isZigInlineImportReceiver(inlineImport) || deepAliases.inlineRoots.has(inlineImport.id); + if (claimedImportSourceIds.has(source.id) && !isReceiver) continue; const sourceCapture = grouped['@import.source']!; - if (isZigInlineImportReceiver(inlineImport) || deepAliases.inlineRoots.has(inlineImport.id)) { - const key = `receiver:${zigLexicalHost(inlineImport)?.id}:${source.text}`; + if (isReceiver) { + const key = `receiver:${zigLexicalHost(inlineImport)?.id}:${inlineImport.text}`; if (importedSourceTexts.has(key)) continue; importedSourceTexts.add(key); out.push({ @@ -1369,7 +1435,7 @@ export function emitZigScopeCaptures( ); const source = nodeMap['@import.source']; if (importRoot !== null && source !== undefined) { - const key = `receiver:${zigLexicalHost(importRoot)?.id}:${source.text}`; + const key = `receiver:${zigLexicalHost(importRoot)?.id}:${importRoot.text}`; if (!importedSourceTexts.has(key)) { importedSourceTexts.add(key); out.push({ @@ -1521,8 +1587,20 @@ export function emitZigScopeCaptures( // Only nominal returns bind (see `zigReturnTypeIsNominal`); a bare // `@This()` return names the enclosing container by name (the alias // rewrite below handles the `Self` spelling of the same thing). + // A forwarding type constructor (`fn Bridge(…) type { return Builder(T); + // }`) binds `Bridge ↦ Builder` instead of its `type` return — declared in + // Bridge's own scope, so a chain followed from another file still looks + // `Builder` up where it is visible (see `zigForwardedTypeConstructor`). const returnAnchor = nodeMap['@type-binding.return']; - if (returnAnchor !== undefined) { + const forwardedType = + returnAnchor === undefined ? undefined : zigForwardedTypeConstructor(returnAnchor); + if (returnAnchor !== undefined && forwardedType !== undefined) { + grouped['@type-binding.type'] = syntheticCapture( + '@type-binding.type', + nodeMap['@type-binding.type'] ?? returnAnchor, + forwardedType, + ); + } else if (returnAnchor !== undefined) { const retType = nodeMap['@type-binding.type']; if (retType === undefined || !zigReturnTypeIsNominal(retType)) continue; if (retType.text.includes('@This()')) { @@ -1638,6 +1716,37 @@ export function emitZigScopeCaptures( ) { Object.assign(grouped, republishMarker(nodeMap['@import.statement'])); } + + // F8 — a member of an ANONYMOUS container used in place: `std.sort.pdq(…, + // struct { fn lessThan … }.lessThan)`, `const byteSize = struct { fn it … + // }.it;`. The receiver text is the container's whole body, which names + // nothing, so every such site was a receiver drop (#3498 triage, F-C). + // Name the receiver by the identity the container is minted under + // (`Sorter.sortBoth$1`, see `zigContainerName`), and anchor the site on the + // member: from `struct` on it lies inside the container's own Class scope, + // which made the container the "caller" of its own fn, while the member is + // evaluated in the enclosing scope (the fn that hands the comparator on). + const receiverNode = nodeMap['@reference.receiver']; + const memberNode = nodeMap['@reference.name']; + if ( + receiverNode !== undefined && + memberNode !== undefined && + ZIG_CONTAINER_TYPES.has(receiverNode.type) + ) { + const identity = zigContainerName(receiverNode, _filePath); + if (identity !== undefined) { + grouped['@reference.receiver'] = syntheticCapture( + '@reference.receiver', + receiverNode, + identity, + ); + const memberRange = zigNodeRange(memberNode); + for (const tag of ZIG_RECEIVER_SITE_ANCHORS) { + const anchor = grouped[tag]; + if (anchor !== undefined) grouped[tag] = { ...anchor, range: memberRange }; + } + } + } out.push(grouped); // F5 — field types. `session: *Session,` declares the TYPE of the member @@ -1872,12 +1981,22 @@ function zigRangeKey(range: ZigRange): string { function addZigLexicalFacts(out: CaptureMatch[], root: SyntaxNode): void { const nodes = new Map(); const declarations: SyntaxNode[] = []; + const typeConstructors = new Set(); const visit = (node: SyntaxNode): void => { const key = zigRangeKey(zigNodeRange(node)); const peers = nodes.get(key); if (peers === undefined) nodes.set(key, [node]); else peers.push(node); - if (node.type === 'variable_declaration' || node.type === 'parameter') declarations.push(node); + if ( + node.type === 'variable_declaration' || + node.type === 'parameter' || + node.type === 'function_declaration' + ) + declarations.push(node); + if (ZIG_CONTAINER_TYPES.has(node.type)) { + const constructor = zigTypeConstructorOf(node); + if (constructor !== null) typeConstructors.add(constructor.id); + } for (const child of node.namedChildren) if (child !== null) visit(child); }; visit(root); @@ -1937,8 +2056,16 @@ function addZigLexicalFacts(out: CaptureMatch[], root: SyntaxNode): void { } for (const node of declarations) { if (importedDeclarations.has(zigRangeKey(zigNodeRange(node)))) continue; + if (node.type === 'function_declaration' && node.childForFieldName('type')?.text !== 'type') + continue; + // A modeled constructor also binds its returned container under this name, + // with a different declaration range. Preserve that dual binding. + if (node.type === 'function_declaration' && typeConstructors.has(node.id)) continue; if (node.type === 'variable_declaration' && !isZigKeywordDeclaration(node)) continue; - const name = node.type === 'parameter' ? node.childForFieldName('name') : node.namedChild(0); + const name = + node.type === 'parameter' || node.type === 'function_declaration' + ? node.childForFieldName('name') + : node.namedChild(0); const owner = zigLexicalHost(node); if (owner !== null && name?.type === 'identifier') { // A file's @This() alias names the synthetic Struct declaration, whose diff --git a/gitnexus/src/core/ingestion/import-resolvers/zig.ts b/gitnexus/src/core/ingestion/languages/zig/import-helpers.ts similarity index 99% rename from gitnexus/src/core/ingestion/import-resolvers/zig.ts rename to gitnexus/src/core/ingestion/languages/zig/import-helpers.ts index 8b66a26265..cb999c1800 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/zig.ts +++ b/gitnexus/src/core/ingestion/languages/zig/import-helpers.ts @@ -29,7 +29,7 @@ import { normalizeZigDepPath, type ZigBuildModule, type ZigBuildZonConfig, -} from '../language-config.js'; +} from '../../language-config.js'; const ZIG_STDLIB_NAMES = new Set(['std', 'builtin', 'root']); diff --git a/gitnexus/src/core/ingestion/languages/zig/index.ts b/gitnexus/src/core/ingestion/languages/zig/index.ts index 10d47336bb..86db140215 100644 --- a/gitnexus/src/core/ingestion/languages/zig/index.ts +++ b/gitnexus/src/core/ingestion/languages/zig/index.ts @@ -6,6 +6,7 @@ export { isZigFileThisAlias, isZigKeywordDeclaration, isZigRedundantContainerCapture, + isZigTypeConstructorCallee, isZigTypeShadowingBinding, zigCallableQualifiedName, zigContainerAnchor, diff --git a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts index 675f6e1a89..9e0665747e 100644 --- a/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/zig/scope-resolver.ts @@ -20,9 +20,14 @@ import { zigPackageFor, type ZigWorkspaceIndex, } from '../../language-config.js'; -import { resolveZigImportInternal } from '../../import-resolvers/zig.js'; +import { resolveZigImportInternal } from './import-helpers.js'; import { zigProvider } from '../zig.js'; -import { expandZigWildcardNames, zigArityCompatibility, zigMergeBindings } from './index.js'; +import { + expandZigWildcardNames, + isZigTypeConstructorCallee, + zigArityCompatibility, + zigMergeBindings, +} from './index.js'; import { populateZigRangeBindings } from './range-binding.js'; import { populateZigWorkspaceStaticGating } from './workspace-static-gating.js'; @@ -51,6 +56,13 @@ export const zigScopeResolver: ScopeResolver = { // import; a one-hop split at the last dot resolved none of them. resolveNamespaceChains: true, + // Zig spells a generic type as a call: `Stack(u8).init()` calls `init` on + // the TYPE `Stack(u8)`. `Stack` returns `type`, which binds nothing, so the + // inline receiver typed nothing while `var t = Stack(u8).init()` resolved. + // A TitleCase callee is a type constructor by Zig's naming convention — the + // same heuristic as `isZigTypeConstructorCall`. + isTypeApplicationCall: isZigTypeConstructorCallee, + // The whole workspace, not just the root package. A Zig module's import table // is declared by the `build.zig` of the package the file belongs to, so a repo // laying its packages out as `packages//build.zig` has as many import diff --git a/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts b/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts index 11c13b2596..9b5a6f633e 100644 --- a/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts +++ b/gitnexus/src/core/ingestion/languages/zig/workspace-static-gating.ts @@ -1,7 +1,7 @@ import type { ParsedFile, ReferenceSite } from 'gitnexus-shared'; import { getTreeSitterBufferSize } from '../../constants.js'; import { zigPackageFor, type ZigWorkspaceIndex } from '../../language-config.js'; -import { resolveZigImportInternal } from '../../import-resolvers/zig.js'; +import { resolveZigImportInternal } from './import-helpers.js'; import { buildZigBoolConstMap, collectZigStaticGatedRanges, diff --git a/gitnexus/src/core/ingestion/model/scope-resolution-indexes.ts b/gitnexus/src/core/ingestion/model/scope-resolution-indexes.ts index 4f8ed0ee62..129befbf1f 100644 --- a/gitnexus/src/core/ingestion/model/scope-resolution-indexes.ts +++ b/gitnexus/src/core/ingestion/model/scope-resolution-indexes.ts @@ -81,12 +81,14 @@ export interface ScopeResolutionIndexes { /** Workspace-level binding lookup, shared instead of per-scope * duplication. Consulted by `lookupBindingsAt` as a third source after * finalized and per-scope augmented bindings. Language-specific - * namespace-sibling hooks populate it with disjoint key formats that - * never collide — e.g. backslash-separated FQNs (`App\Models\User`) for - * backslash-namespace languages, and bare simple names (`User`) for - * global-/default-namespace types that are visible from every file. The - * shared map gives those workspace-wide names one entry each instead of - * O(scopes × defs) per-scope augmentation. */ + * namespace-sibling hooks populate it with keys that mean the same thing + * from every scope — e.g. backslash-separated FQNs (`App\Models\User`) for + * backslash-namespace languages. The shared map gives those workspace-wide + * names one entry each instead of O(scopes × defs) per-scope augmentation. + * It answers at EVERY scope, ahead of anything an enclosing scope binds, so + * a bare simple name belongs here only if no nearer declaration can hide + * it. A default namespace whose simple names rank below the file's own + * namespaces goes through `namespaceFqnBindings` under its own key instead. */ readonly workspaceFqnBindings: ReadonlyMap; /** Workspace-level *type* binding lookup — the typeBindings analogue of * `workspaceFqnBindings`. Holds names that are type-visible from every file @@ -123,16 +125,17 @@ export interface ScopeResolutionIndexes { * after the per-scope chain and the flat `workspaceTypeBindings` miss. * Populated post-finalize; most languages leave it empty. */ readonly namespaceTypeBindings: ReadonlyMap>; - /** Accessibility gate for the per-namespace channels: maps a module ScopeId to - * the namespace names type-visible from that file — its own declared - * namespace(s) plus every imported/`using`d namespace (and dotted prefixes). - * This is the same per-file accessible-namespace set the C# hook already - * derives (`expandedNamespaces`), materialized so the language-neutral walkers - * can consult `namespaceFqnBindings` / `namespaceTypeBindings` for exactly the - * namespaces a file can see — preserving namespace visibility semantics - * without the per-file binding copy. Empty when no language populates the - * namespace channels. */ + /** Accessibility gate for the per-namespace channels. A declaration or module + * scope maps to the namespace names visible there, including enclosing and + * global namespaces where the provider permits them. Provider ordering + * preserves lookup precedence without copying definitions into every scope. + * Empty for bundles that do not populate the namespace channels. */ readonly accessibleNamespacesByScope: ReadonlyMap; + /** Optional precedence groups for namespace lookup. Candidates in one group + * compete together; the first group containing a name hides later groups. + * Keys may be declaration scopes as well as module scopes. Bundles that + * omit this channel retain their existing flat accessibility semantics. */ + readonly namespaceLookupTiersByScope?: ReadonlyMap; /** Pre-resolution usage facts; consumed by the resolution phase. */ readonly referenceSites: readonly ReferenceSite[]; /** SCC condensation of the file-level import graph — callers that want diff --git a/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts b/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts index 131055deb9..a948250acf 100644 --- a/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts +++ b/gitnexus/src/core/ingestion/route-extractors/js-const-resolver.ts @@ -131,7 +131,7 @@ export interface JsRepoFacts { * * A tail lookup only ever matches keys whose last segment equals the * candidate's last segment, so the bucket is the entire search space — turning - * an O(files) sweep per candidate into one map hit. `import-resolvers/utils.ts` + * an O(files) sweep per candidate into one map hit. `utils/suffix-index.ts` * already ships `buildSuffixIndex` for the same job, but it keeps only a first * winner per suffix; this index has to SEE a collision to refuse it (below), so * it keeps the whole bucket. diff --git a/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts b/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts index 6224a16c96..39734fa886 100644 --- a/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts +++ b/gitnexus/src/core/ingestion/route-extractors/spring-shared.ts @@ -12,7 +12,7 @@ * This module lives in `ingestion/` (the lower layer); the group layer imports * from it, matching the existing `group → ingestion` dependency direction * (e.g. `group/extractors/include-extractor.ts` already imports - * `ingestion/import-resolvers/utils.ts`). It MUST NOT import anything from + * `ingestion/utils/suffix-index.ts`). It MUST NOT import anything from * `group/` to avoid a dependency cycle. */ diff --git a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts index 3925355558..22d447a555 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/contract/scope-resolver.ts @@ -167,7 +167,7 @@ * unconditionally), and `indexes.namespaceFqnBindings` + * `indexes.namespaceTypeBindings` (per-namespace, consulted only for the * namespaces in `indexes.accessibleNamespacesByScope` for the caller's - * module). All but `indexes.bindings` are mutable post-finalize and + * owning scope). All but `indexes.bindings` are mutable post-finalize and * populated by hooks; only `indexes.bindings` is frozen. * * `indexes.bindings` is the **finalize-output channel**. After @@ -1117,6 +1117,17 @@ export interface ScopeResolver { */ readonly isNamespaceMemberVisible?: (ctx: { readonly member: SymbolDefinition }) => boolean; + /** Optional compatibility rule for bare class-name receivers. Runs before + * namespace precedence selection, so an incompatible declaration cannot + * hide a compatible declaration in an enclosing namespace. Value receivers + * and declared-type lookups keep their existing rules. */ + readonly isBareClassReceiverCandidate?: (ctx: { + readonly candidate: SymbolDefinition; + readonly spelling: string; + readonly inScope: ScopeId; + readonly scopes: ScopeResolutionIndexes; + }) => boolean; + /** * When true, a qualified receiver is walked SEGMENT BY SEGMENT from its * verified namespace root instead of being split once at the last dot: @@ -1135,6 +1146,30 @@ export interface ScopeResolver { */ readonly resolveNamespaceChains?: boolean; + /** + * When true, a receiver's declared type written as a QUALIFIED name + * (`rp::C x`, `void f(a::Config c)`, a factory returning `rp::C`) that binds + * nothing through the scope chain is resolved through the same precise route + * a qualified inheritance base and a qualified type reference take + * (`resolveQualifiedInheritanceBase`): the qualifier must match the + * candidate's namespace, and a tie resolves nothing. + * + * The shared receiver lookups read a qualifier only as a `.` namespace-import + * handle, so a language whose qualifier is a namespace PATH with no import + * handle behind it typed none of these receivers. File includes + * binds no handle and its index keys `rp::C` under `C`. The alternative — + * reducing the spelling to its tail at capture — binds the nearest + * same-named class, which is the class the qualifier was written to exclude. + * + * Per-language rather than universal because PHP also keeps qualified + * (`\`-separated) declared types and resolves them through its own import + * channel; it was not measured under this route. Off ⇒ every receiver + * lookup is unchanged. It runs only after every existing lookup missed, and + * after the template-argument match, so it can add an edge but never + * retarget one. + */ + readonly resolveQualifiedTypeSpellings?: boolean; + /** * How this language spells a construction expression, so the compound * receiver resolver can type an INLINE constructor receiver — the @@ -1187,6 +1222,29 @@ export interface ScopeResolver { readonly selector?: string; }; + /** + * Optional: does a CALL written as a receiver apply a type constructor — + * yield a TYPE — rather than invoke a function? `callee` is the call's + * function expression as written (`Stack`, `util.List`). + * + * A language that spells a generic type as a call (`Stack(u8).init()` + * calls `init` on the type `Stack(u8)`) has no return-type binding for the + * callee — it returns `type` — and no construction syntax, so the inline + * receiver typed nothing even though the bound form (`var t = + * Stack(u8).init()`, whose binding drops the type arguments) resolved. When + * this answers true, the compound resolver types the receiver as the class + * the callee names through a lexical or import binding, including a + * namespace-qualified callee. A unique workspace name is insufficient. The + * callee's return-type binding is consulted first and still wins. + * + * A predicate rather than a flag so the language decides WHICH calls are + * type applications, for example by its naming convention for types. + * + * Only affects receiver TYPING, like `constructionSyntax`. + * Default: undefined (no call is a type application). + */ + readonly isTypeApplicationCall?: (callee: string) => boolean; + /** * Optional per-slot conversion-rank function for overload resolution. * When provided, `narrowOverloadCandidates` uses ranked scoring as a @@ -1411,6 +1469,39 @@ export interface ScopeResolver { allFilePaths: ReadonlySet, ) => SymbolDefinition | undefined; + /** + * Optional resolver for a qualified CALLEE TEXT whose path syntax only the + * language can read — Rust `rp::make` in `let x = rp::make(); x.m()` and in + * the inline receiver `rp::make().m()`, where `rp` names a module rather than + * a value or a type (#3498). + * + * The shared walkers never split this text. They hand it over verbatim, with + * the scope the call sits in, and only after their own lookups found nothing: + * - `followChainPostFinalize`, for a typeBinding rawName no scope binds (so + * the provider's call-return binding must keep the whole callee path); + * - the compound-receiver call branch, for an undotted callee no scope binds; + * - the receiver-bound drop recorder, so a receiver bound to an in-program + * callable with no return annotation records a `receiver-unresolved` drop + * instead of passing as an exact miss. + * + * Return the callable the path names, or `undefined` when the text is not a + * qualified path in this language, names nothing in the workspace, or is + * ambiguous. The shared side reads that callable's `return-annotation` type + * fact by definition identity, so a callable without one types nothing. + * Refusal must be cheap: the hook is asked about every name these sites fail + * to resolve. + * + * Languages whose qualified callees are dotted member expressions covered by + * namespace imports (`ns.make()`) leave this undefined. + */ + readonly resolveQualifiedCallee?: ( + calleeText: string, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + workspaceIndex: WorkspaceResolutionIndex, + allFilePaths: ReadonlySet, + ) => SymbolDefinition | undefined; + /** * Optional resolver for qualified-receiver member calls where the * receiver is a namespace (not a class) and ordinary scope-chain / @@ -1437,6 +1528,36 @@ export interface ScopeResolver { callsite?: Callsite, ) => SymbolDefinition | 'ambiguous' | undefined; + /** + * Split a qualified CALLEE as written (`rp::make`, `a::b::make`) into the + * receiver/member pair this language's qualified call captures produce for + * the same spelling, or `undefined` when the callee is not qualified. + * + * A factory call types a receiver in two shapes — bound + * (`auto x = rp::make(); x.m()`, whose binding records the callee text) and + * inline (`rp::make().m()`) — and both reach the compound receiver resolver + * as callee TEXT, while the call itself was resolved from its captured + * receiver and member. This hook maps the text back onto that pair so the + * resolver can ask `resolveQualifiedReceiverMember` for the callee's + * definition and read the return type that definition declares (by + * definition identity, never by name). Splitting is the language's job: the + * separator and which segment counts as the receiver are grammar facts; a + * provider may capture `a::b::make` as `b` / `make`. The caller scope and + * indexes let it reject dependent or shadowed qualifiers before splitting. + * The optional position keeps later local declarations from hiding the + * factory expression; bound receivers pass their producer lookup position. + * + * Consulted only for a free-call head whose name binds no callable, and only + * when `resolveQualifiedReceiverMember` is implemented too. It is asked + * without call-site arity, so an `'ambiguous'` answer types nothing. + */ + readonly splitQualifiedCallee?: ( + callee: string, + callerScope?: ScopeId, + scopes?: ScopeResolutionIndexes, + position?: TypeRef['lookupPosition'], + ) => { readonly receiver: string; readonly member: string } | undefined; + /** * Every receiver spelling under which a namespace import's target is * reachable, and the file each spelling names (#2826). Returning @@ -1534,6 +1655,24 @@ export interface ScopeResolver { * caller records a receiver-unresolved outcome. */ readonly suppressReceiverLookup?: (typeRef: TypeRef) => boolean; + /** + * True when a WRITE site is the language's module-export DECLARATION written + * through a qualified receiver — CommonJS `module.exports.name = …` — rather + * than a write to a member of some value. + * + * Instrumentation only. Consulted after the receiver-bound cases have all + * failed to type the receiver, to keep the declaration out of the + * `receiver-unresolved` drops: the receiver is the module's own export + * object, not a value whose type was lost. It neither emits an edge nor marks + * the site handled, so whatever the later passes do with the site is + * unchanged. Omit to record every such site as a drop. + */ + readonly isModuleExportAssignment?: ( + site: ReferenceSite, + scopes: ScopeResolutionIndexes, + parsed: ParsedFile, + ) => boolean; + /** * Enable the receiver-bound Case 0.5 fallback for explicit `this` * receivers (`this->m()` / `this.m()`) that resolves against the @@ -1600,8 +1739,8 @@ export interface ScopeResolver { ) => ArityVerdict; /** - * Optional post-finalize hook to inject cross-file bindings that - * aren't modeled via explicit imports. Runs after + * Optional post-finalize hook to complete provider-owned namespace and type + * facts that need finalized lexical ownership. Runs after * `buildWorkspaceResolutionIndex` and before * `propagateImportedReturnTypes`. * @@ -1609,8 +1748,10 @@ export interface ScopeResolver { * makes names visible across files without a syntactic import — * for example a shared-namespace convention where types declared * in the same namespace see each other without a `using` / `import` - * statement. Languages that require explicit imports for cross-file - * visibility leave this undefined. + * statement. The hook may also refine existing scope type bindings before + * return propagation, such as distinguishing a qualified constructor from a + * namespace factory. Add visible bindings through bindingAugmentations; + * finalized indexes.bindings remains immutable. */ readonly populateNamespaceSiblings?: ( parsedFiles: readonly ParsedFile[], @@ -1718,10 +1859,15 @@ export interface ScopeResolver { * `rawName` has many readers, and the compound resolver reads a dotted one as * a `value.member` alias path. Only receiver typing needs the distinction. * - * Return a lookup-ready class name (no decoration, no type arguments). Leave - * undefined for languages whose `rawName` keeps its qualifier. + * Return a module-visible class spelling (no decoration or type arguments). + * Providers may also expand a namespace alias using the binding's declaration + * scope and the supplied indexes. Leave undefined when no expansion is needed. + * Return null to refuse the written qualified lookup and its fallback. */ - readonly qualifiedTypeLookupSpelling?: (typeRef: TypeRef) => string | undefined; + readonly qualifiedTypeLookupSpelling?: ( + typeRef: TypeRef, + scopes?: ScopeResolutionIndexes, + ) => string | null | undefined; /** * Whether the compound-receiver resolver should strip C-style cast diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts index 4bc6465a6d..ac54ba5492 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts @@ -31,13 +31,14 @@ import { } from '../../utils/template-arguments.js'; import type { DecodedReceiverChain } from '../../utils/receiver-chain-codec.js'; import { decodeReceiverChain } from '../../utils/receiver-chain-codec.js'; -import { namespaceCallReturnType } from './imported-return-types.js'; +import { namespaceCallReturnType, producerTypeRef } from './imported-return-types.js'; import type { ClassBindingLookup, DecorationStripper } from '../scope/walkers.js'; import { findClassBindingInScope, lookupNameClaim, hasExplicitNameClaim, resolveClassBindingForName, + resolveQualifiedClassSpelling, findEnclosingClassDef, findExportedDef, findExportedDefByName, @@ -137,6 +138,9 @@ interface ResolveCompoundReceiverOptions { * rather than re-declared, so a future sub-field cannot be added there * and silently ignored here (#2708). */ readonly constructionSyntax?: ScopeResolver['constructionSyntax']; + /** `ScopeResolver.isTypeApplicationCall`: a call whose callee names a type + * constructor yields that TYPE, typed like a bare construction. */ + readonly isTypeApplicationCall?: ScopeResolver['isTypeApplicationCall']; /** Verified namespace handles visible in the current file. */ readonly namespaceTargets?: ReadonlyMap; /** A namespace member may be a name the target module imported and @@ -183,12 +187,36 @@ interface ResolveCompoundReceiverOptions { * by the shared lookup's other callers — see the contract's own note on why * this is opt-in rather than global. */ readonly stripTypePreservingDecoration?: DecorationStripper; + /** `ScopeResolver.resolveQualifiedTypeSpellings`: a qualified declared or + * return type (`rp::C`) that binds nothing is resolved through the precise + * qualified route. Absent ⇒ both lookups are exactly as before. */ + readonly qualifiedTypeSpellings?: boolean; + /** The definition a QUALIFIED callee (`rp::make`) names, through + * `ScopeResolver.splitQualifiedCallee` + `resolveQualifiedReceiverMember` + * — the same answer the qualified call itself got. Consulted for a + * free-call head whose name binds no callable; absent ⇒ such a head types + * nothing, exactly as before. */ + readonly resolveQualifiedCallee?: ( + callee: string, + inScope: ScopeId, + position?: TypeRef['lookupPosition'], + ) => SymbolDefinition | undefined; /** `ScopeResolver.qualifiedTypeLookupSpelling`, tried before `rawName` by * every {@link classOfDeclaredType} caller (member, head and fold lookups). * Absent ⇒ `rawName` alone, exactly as before. */ readonly qualifiedTypeLookupSpelling?: ScopeResolver['qualifiedTypeLookupSpelling']; } +/** The options the two declared-type lookups below read. */ +type TypeLookupOptions = Pick< + ResolveCompoundReceiverOptions, + | 'recordReceiverType' + | 'onNameFallback' + | 'qualifiedTypeSpellings' + | 'qualifiedTypeLookupSpelling' + | 'namespaceMemberVisible' +>; + /** Is this hop the language's construction selector applied to the class * itself — `Factory.new` — rather than an ordinary member named `new` on a * value? Both call sites ask the identical question, so it is asked in one @@ -224,10 +252,14 @@ function escapeForRegExp(literal: string): string { * `isConstructionSelectorHop` (the `Class.new` spelling), this is where the * rule "constructing a class yields an instance of it" lives; the * per-language surface syntax arrives via `constructionSyntax` (#2708). + * A type application (`Stack(u8)`, `isTypeApplicationCall`) names + * its class the same way a bare construction does: the expression is the + * TYPE rather than an instance, which receiver typing does not distinguish. * - * Returns undefined when the language declares no construction syntax, - * when the callee names no class-like symbol reachable from `inScope`, - * or when the keyword is required but absent — never a guess. + * Returns undefined when the language declares no construction syntax and + * the call is no type application, when the callee names no class-like + * symbol reachable from `inScope`, or when the keyword is required but + * absent — never a guess. */ function resolveConstructionExpressionClass( fnExpr: string, @@ -237,7 +269,8 @@ function resolveConstructionExpressionClass( options: ResolveCompoundReceiverOptions, ): SymbolDefinition | undefined { const syntax = options.constructionSyntax; - if (syntax === undefined) return undefined; + const typeApplication = options.isTypeApplicationCall?.(fnExpr) === true; + if (syntax === undefined && !typeApplication) return undefined; let calleeName: string | undefined; // The keyword is separated from the type by whatever trivia the source @@ -246,12 +279,12 @@ function resolveConstructionExpressionClass( // rather than by exactly one space (#2708). `newService()` keeps failing // the match, which is the point: it is an ordinary call. const keywordMatch = - syntax.keyword === undefined + syntax?.keyword === undefined ? null : new RegExp(`^${escapeForRegExp(syntax.keyword)}\\s+`).exec(fnExpr); if (keywordMatch !== null) { calleeName = fnExpr.slice(keywordMatch[0].length).trim(); - } else if (syntax.bare === true) { + } else if (syntax?.bare === true || typeApplication) { calleeName = fnExpr; } // A `new`-keyword language reaching here without the keyword is an @@ -304,6 +337,7 @@ function resolveConstructionExpressionClass( onNameFallback: options.onNameFallback, position: options.lookupPosition, purpose: 'value', + uniqueQualifiedNameFallback: typeApplication ? false : undefined, }); if (direct !== undefined && isClassLike(direct.type)) return direct; @@ -312,6 +346,7 @@ function resolveConstructionExpressionClass( onNameFallback: options.onNameFallback, position: options.lookupPosition, purpose: 'value', + uniqueQualifiedNameFallback: typeApplication ? false : undefined, }); if (viaBaseName !== undefined && isClassLike(viaBaseName.type)) return viaBaseName; } @@ -319,7 +354,8 @@ function resolveConstructionExpressionClass( // Qualified callee — `new ns.Service()` / `new Outer.Inner()`. Prefer an // unambiguous qualified-name match, then fall back to the trailing simple // name the way receiver resolution does elsewhere (#2708). - if (lastDot === -1) return undefined; + // Type-application syntax alone cannot justify a workspace-name guess. + if (lastDot === -1 || typeApplication) return undefined; const root = baseName.slice(0, baseName.indexOf('.')); const claim = lookupNameClaim(inScope, root, scopes, { position: options.lookupPosition, @@ -453,6 +489,7 @@ function classOfDeclaredType( position: typeRef.lookupPosition, purpose: typeRef.lookupPurpose ?? 'type', onNameFallback: options.onNameFallback, + qualifiedTypeSpellings: options.qualifiedTypeSpellings, }; // The report keeps the spelling it always had, whichever lookup answers: it // is read only for type ARGUMENTS (#2912), and the qualified spelling has none. @@ -508,11 +545,12 @@ export function classOfQualifiedTypeSpelling( ): SymbolDefinition | null | undefined { // Runs for every declared-type lookup in every language, so nothing is // allocated until the provider has actually returned a qualified spelling. - const qualified = qualifiedTypeLookupSpelling?.(typeRef); + const qualified = qualifiedTypeLookupSpelling?.(typeRef, scopes); + if (qualified === null) return null; if (qualified === undefined || qualified === typeRef.rawName) return undefined; const importScope = moduleScopeIdOf(typeRef.declaredAtScope, scopes) ?? typeRef.declaredAtScope; return ( - findClassBindingInScope(importScope, qualified, scopes, undefined, { + resolveClassBindingForName(importScope, qualified, scopes, undefined, { ...lookup, namespaceMemberVisible, uniqueQualifiedNameFallback: false, @@ -554,22 +592,72 @@ function noteReceiverType( * arguments intact. The spelling is built only once the lookup has actually * found a class, because it is discarded otherwise — and every fold hop * through a call reaches this, generic or not. + * + * A qualified return type (`rp::C make();`) binds nothing through the bare + * lookup for the same reason a qualified declared type does not, so it takes + * the same opt-in qualified route as a last resort (see + * `ScopeResolver.resolveQualifiedTypeSpellings`). */ function classOfReturnType( retType: TypeRef, scopes: ScopeResolutionIndexes, - record: ReceiverTypeRecorder | undefined, - onNameFallback?: () => void, + options: TypeLookupOptions, ): SymbolDefinition | undefined { - const def = findClassBindingInScope(retType.declaredAtScope, retType.rawName, scopes, undefined, { - position: retType.lookupPosition, - purpose: retType.lookupPurpose ?? 'type', - onNameFallback, - }); + const qualified = classOfQualifiedTypeSpelling( + retType, + scopes, + options.qualifiedTypeLookupSpelling, + { + position: retType.lookupPosition, + purpose: retType.lookupPurpose ?? 'type', + onNameFallback: options.onNameFallback, + qualifiedTypeSpellings: options.qualifiedTypeSpellings, + }, + options.namespaceMemberVisible, + ); + const def = + qualified === undefined + ? (findClassBindingInScope(retType.declaredAtScope, retType.rawName, scopes, undefined, { + position: retType.lookupPosition, + purpose: retType.lookupPurpose ?? 'type', + onNameFallback: options.onNameFallback, + }) ?? + (options.qualifiedTypeSpellings === true + ? resolveQualifiedClassSpelling(retType.declaredAtScope, retType.rawName, scopes) + : undefined)) + : (qualified ?? undefined); + const record = options.recordReceiverType; if (def === undefined || record === undefined) return def; return noteReceiverType(record, erasedTypeApplication(retType) ?? retType.rawName, def); } +/** + * The return type a free-call callee declares for ITSELF — read by definition + * identity (`producerTypeRef`), the way the chain follow types the bound form + * `auto x = make(); x.m()` — for when the name read finds no return binding + * under the callee's name. That happens whenever the callee arrived by a + * channel nothing mirrors a return binding through (a namespace directive), so + * `make().m()` dropped while the bound form beside it resolved. + * + * Only for a callee the name actually BINDS at the call. `findExportedDefByName` + * falls back to the first workspace callable of that name, and reading a + * return type off that guess typed a receiver from an unrelated module's + * same-named factory — a confident wrong edge where the name read declined. + */ +function boundCalleeReturnType( + fnDef: SymbolDefinition, + name: string, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + position: TypeRef['lookupPosition'], +): TypeRef | undefined { + const claim = lookupNameClaim(inScope, name, scopes, { position, purpose: 'value' }); + const identities = new Set(claim.bindings.map((binding) => binding.def.nodeId)); + return identities.size === 1 && identities.has(fnDef.nodeId) + ? producerTypeRef(fnDef.nodeId, scopes) + : undefined; +} + function typeOfMemberOnClass( owner: SymbolDefinition, memberName: string, @@ -1084,25 +1172,36 @@ export function resolveCompoundReceiverClass( purpose: 'value', }); if (fnDef !== undefined) { - const retType = findReceiverTypeBinding(inScope, fnExpr, scopes, { - position: options.lookupPosition, - }); + const retType = + findReceiverTypeBinding(inScope, fnExpr, scopes, { + position: options.lookupPosition, + }) ?? boundCalleeReturnType(fnDef, fnExpr, inScope, scopes, options.lookupPosition); const viaReturn = - retType === undefined - ? undefined - : classOfReturnType( - retType, - scopes, - options.recordReceiverType, - options.onNameFallback, - ); + retType === undefined ? undefined : classOfReturnType(retType, scopes, options); + if (viaReturn !== undefined) return viaReturn; + } else { + // A qualified callee (`rp::make`, from `rp::make().m()` or the binding + // `auto x = rp::make()`) binds no name; its definition comes from the + // language's qualified-member lookup — the qualifier is the evidence — + // and its return type from that definition's own declaration. + const qualifiedDef = options.resolveQualifiedCallee?.( + fnExpr, + inScope, + options.lookupPosition, + ); + const retType = + qualifiedDef === undefined ? undefined : producerTypeRef(qualifiedDef.nodeId, scopes); + const viaReturn = + retType === undefined ? undefined : classOfReturnType(retType, scopes, options); if (viaReturn !== undefined) return viaReturn; } // Inline construction — `Service(db).m()` / `new Service(db).m()`. // The constructed value IS the receiver, so there is no binding to // read a type off; the return-type path above cannot help either, // because a class has no return-type binding. Type it from the - // class the callee names (#2708). + // class the callee names (#2708). A type application (`Stack(u8) + // .init()`) reaches here too: its callee returns `type`, which binds + // nothing. return resolveConstructionExpressionClass(fnExpr, inScope, scopes, index, options); } @@ -1127,14 +1226,7 @@ export function resolveCompoundReceiverClass( // named import of that function (#3498). const returned = namespaceCallReturnType(fnExpr, inScope, scopes, options.lookupPosition); const viaReturn = - returned === undefined - ? undefined - : classOfReturnType( - returned, - scopes, - options.recordReceiverType, - options.onNameFallback, - ); + returned === undefined ? undefined : classOfReturnType(returned, scopes, options); if (viaReturn !== undefined) return viaReturn; return resolveConstructionExpressionClass(fnExpr, inScope, scopes, index, options); } @@ -1236,7 +1328,7 @@ export function resolveCompoundReceiverClass( } if (retType === undefined) return undefined; - return classOfReturnType(retType, scopes, options.recordReceiverType, options.onNameFallback); + return classOfReturnType(retType, scopes, options); } // Mixed dotted + call chain: `obj.field.method().field.method()…`. diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/imported-return-types.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/imported-return-types.ts index fd0b246571..7d36f7c379 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/imported-return-types.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/imported-return-types.ts @@ -49,6 +49,7 @@ import type { } from 'gitnexus-shared'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import type { WorkspaceResolutionIndex } from '../workspace-index.js'; +import type { ScopeResolver } from '../contract/scope-resolver.js'; import { definitionIdPosition } from '../utils/definition-id.js'; import { followedStep } from '../../utils/type-ref-chain.js'; import { @@ -56,23 +57,35 @@ import { lookupNameClaim, findReceiverTypeBinding, namesAtScope, - moduleScopeIdOf, namespaceTypeBindingFor, } from '../scope/walkers.js'; /** Definition identity → its own type fact; built once, facts read lazily after propagation. */ interface TypeFactOwner { - readonly scope: Scope; + readonly scope: ScopeId; readonly name: string; } const typeFactOwners = new WeakMap>(); -function producerTypeRef(defId: string, scopes: ScopeResolutionIndexes): TypeRef | undefined { +/** The type fact a definition declares for itself (a callable's return type), + * joined by definition identity rather than by name. */ +export function producerTypeRef( + defId: string, + scopes: ScopeResolutionIndexes, +): TypeRef | undefined { let owners = typeFactOwners.get(scopes); if (owners === undefined) { owners = new Map(); const returnsByDeclaration = new Map(); const definitions = new Map(); - for (const scope of scopes.scopeTree.byId?.values() ?? []) { + const pending = [...scopes.moduleScopes.byFilePath.values()]; + const visited = new Set(); + while (pending.length > 0) { + const id = pending.pop(); + if (id === undefined || visited.has(id)) continue; + visited.add(id); + const scope = scopes.scopeTree.getScope(id); + if (scope === undefined) continue; + for (const child of scopes.scopeTree.getChildren(id)) pending.push(child); for (const def of scope.ownedDefs ?? []) definitions.set(def.nodeId, def); for (const [name, ref] of scope.typeBindings) { // Some providers hoist method return annotations to the module. Join @@ -84,7 +97,10 @@ function producerTypeRef(defId: string, scopes: ScopeResolutionIndexes): TypeRef ) continue; const key = `${scope.filePath}\0${ref.bindingRange.startLine}:${ref.bindingRange.startCol}`; - returnsByDeclaration.set(key, returnsByDeclaration.has(key) ? null : { scope, name }); + returnsByDeclaration.set( + key, + returnsByDeclaration.has(key) ? null : { scope: scope.id, name }, + ); } for (const [name, bindings] of scope.bindings) { for (const binding of bindings) { @@ -95,7 +111,7 @@ function producerTypeRef(defId: string, scopes: ScopeResolutionIndexes): TypeRef ref !== undefined && !(ref.source === 'return-annotation' && ref.bindingRange !== undefined) ) - owners.set(binding.def.nodeId, { scope, name }); + owners.set(binding.def.nodeId, { scope: scope.id, name }); } } } @@ -110,7 +126,9 @@ function producerTypeRef(defId: string, scopes: ScopeResolutionIndexes): TypeRef typeFactOwners.set(scopes, owners); } const owner = owners.get(defId); - return owner?.scope.typeBindings.get(owner.name); + return owner === undefined + ? undefined + : scopes.scopeTree.getScope(owner.scope)?.typeBindings.get(owner.name); } /** @@ -224,6 +242,48 @@ export function namespaceCallReturnType( : undefined; } +/** `ScopeResolver.resolveQualifiedCallee` bound to one resolution pass. */ +export type QualifiedCalleeResolver = ( + calleeText: string, + inScope: ScopeId, +) => SymbolDefinition | undefined; + +/** Bind the provider's qualified-callee hook to this pass's indexes, or + * `undefined` when the language has none. Reuse the pipeline's file-path set + * when supplied; standalone callers build one lazily. */ +export function bindQualifiedCalleeResolver( + hook: ScopeResolver['resolveQualifiedCallee'], + scopes: ScopeResolutionIndexes, + workspaceIndex: WorkspaceResolutionIndex, + parsedFiles: readonly ParsedFile[], + filePaths?: ReadonlySet, +): QualifiedCalleeResolver | undefined { + if (hook === undefined) return undefined; + let allFilePaths = filePaths; + return (calleeText, inScope) => { + allFilePaths ??= new Set(parsedFiles.map((parsed) => parsed.filePath)); + return hook(calleeText, inScope, scopes, workspaceIndex, allFilePaths); + }; +} + +/** + * A callee only the provider can read (`rp::make`, #3498): the return + * annotation of the callable it resolves to, read by definition identity like + * the producer lookup in {@link followChainPostFinalize}. `undefined` when the + * provider resolves nothing or the callable declares no return type. + */ +export function qualifiedCalleeReturnType( + calleeText: string, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + resolveCallee: QualifiedCalleeResolver | undefined, +): TypeRef | undefined { + const callee = resolveCallee?.(calleeText, inScope); + if (callee === undefined) return undefined; + const returned = producerTypeRef(callee.nodeId, scopes); + return returned?.source === 'return-annotation' ? returned : undefined; +} + /** Walk `ref.rawName` through the scope chain's typeBindings looking * for a terminal class-like rawName. Mirrors the in-extractor * `followChainedRef` but operates on post-finalize Scope objects so @@ -233,12 +293,10 @@ export function followChainPostFinalize( start: TypeRef, fromScopeId: ScopeId, scopes: ScopeResolutionIndexes, + resolveCallee?: QualifiedCalleeResolver, ): TypeRef { let current = start; const visited = new Set(); - // The caller's module scope is fixed across the walk; resolve it once so the - // accessibility-gated per-namespace fallback below can be consulted cheaply. - const moduleScopeId = moduleScopeIdOf(fromScopeId, scopes); for (let depth = 0; depth < RECHAIN_MAX_DEPTH; depth++) { const lookupScope = current.declaredAtScope ?? fromScopeId; if (current.rawName.includes('.')) { @@ -270,6 +328,12 @@ export function followChainPostFinalize( if (next === undefined || claim.bindings.some((binding) => binding.origin !== 'local')) { const candidates = new Map(); for (const binding of claim.bindings) { + // A member exposed through an import bucket must not replace a + // return fact anchored on the module's own free function. + if (binding.def.type === 'Method' && next?.source === 'return-annotation') { + const owner = scopes.scopeTree.getScope(next.declaredAtScope); + if (owner?.kind === 'Module' && isModuleOwnReturn(next, owner, current.rawName)) continue; + } const producer = producerTypeRef(binding.def.nodeId, scopes); if (producer !== undefined) candidates.set(binding.def.nodeId, producer); } @@ -291,13 +355,17 @@ export function followChainPostFinalize( // Both live in shared channels rather than each Scope.typeBindings to avoid // the O(files × names) blow-up. if (next === undefined && claim.status === 'absent') { - const nsHit = namespaceTypeBindingFor(moduleScopeId, current.rawName, scopes); + const nsHit = namespaceTypeBindingFor(lookupScope, current.rawName, scopes); if (nsHit !== undefined && nsHit !== current) next = nsHit; } if (next === undefined && claim.status === 'absent') { const ws = scopes.workspaceTypeBindings?.get(current.rawName); if (ws !== undefined && ws !== current) next = ws; } + // Last, a callee path no scope binds (`rp::make`): the provider names the + // callable, and its return annotation continues the chain (#3498). + if (next === undefined && claim.status === 'absent') + next = qualifiedCalleeReturnType(current.rawName, lookupScope, scopes, resolveCallee); if (next === undefined) return current; if (visited.has(next.rawName)) return current; visited.add(next.rawName); @@ -326,8 +394,17 @@ export function propagateImportedReturnTypes( parsedFiles: readonly ParsedFile[], indexes: ScopeResolutionIndexes, index: WorkspaceResolutionIndex, + resolveQualifiedCallee?: ScopeResolver['resolveQualifiedCallee'], + allFilePaths?: ReadonlySet, ): void { const moduleScopeByFile = index.moduleScopeByFile; + const resolveCallee = bindQualifiedCalleeResolver( + resolveQualifiedCallee, + indexes, + index, + parsedFiles, + allFilePaths, + ); const scopesByFile = new Map(parsedFiles.map((file) => [file.filePath, file.scopes])); // Walk SCCs in reverse-topological order (`indexes.sccs` is leaves- @@ -381,7 +458,12 @@ export function propagateImportedReturnTypes( // Chain-follow inside the source module so we mirror the // terminal type, not an intermediate intra-source reference. - const terminal = followChainPostFinalize(sourceTypeRef, sourceModule.id, indexes); + const terminal = followChainPostFinalize( + sourceTypeRef, + sourceModule.id, + indexes, + resolveCallee, + ); // Mutating typeBindings is safe because draftToScope // produced a non-frozen Map (Contract Invariant I3/I8). @@ -403,7 +485,7 @@ export function propagateImportedReturnTypes( // later (closer-to-root) SCC will see x's terminal type rather // than an intra-module call ref. for (const [name, ref] of importerModule.typeBindings) { - const resolved = followChainPostFinalize(ref, importerModule.id, indexes); + const resolved = followChainPostFinalize(ref, importerModule.id, indexes, resolveCallee); if (resolved !== ref) { (importerModule.typeBindings as Map).set(name, resolved); } @@ -419,7 +501,7 @@ export function propagateImportedReturnTypes( for (const scope of parsed.scopes) { if (scope.id === moduleScopeId) continue; for (const [name, ref] of scope.typeBindings) { - const resolved = followChainPostFinalize(ref, scope.id, indexes); + const resolved = followChainPostFinalize(ref, scope.id, indexes, resolveCallee); if (resolved !== ref) { (scope.typeBindings as Map).set(name, resolved); } diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts index 79d43545b9..a8c9ce2fef 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/receiver-bound-calls.ts @@ -98,6 +98,7 @@ import { type CalleeIdCaptureCtx, } from '../graph-bridge/edges.js'; import { constructionSiteReason } from './free-call-fallback.js'; +import { bindQualifiedCalleeResolver } from './imported-return-types.js'; import type { CalleeIdSink } from '../graph-bridge/callee-id-sink.js'; import { classOfQualifiedTypeSpelling, @@ -189,6 +190,7 @@ type ReceiverBoundProviderSubset = Pick< | 'hoistTypeBindingsToModule' | 'stripReceiverCastExpressions' | 'constructionSyntax' + | 'isTypeApplicationCall' | 'stripTypePreservingDecoration' | 'qualifiedTypeLookupSpelling' | 'resolveQualifiedReceiverMember' @@ -198,6 +200,7 @@ type ReceiverBoundProviderSubset = Pick< | 'createReceiverNamespaceResolver' | 'resolveReceiverMember' | 'suppressReceiverLookup' + | 'isModuleExportAssignment' | 'resolveThisViaEnclosingClass' | 'resolveMissingReceiverMembersFromSubtypes' | 'missingReceiverSubtypeCandidateCompatibility' @@ -210,8 +213,12 @@ type ReceiverBoundProviderSubset = Pick< | 'markConstructionSites' | 'namespaceExportsIncludeImportedNames' | 'isNamespaceMemberVisible' + | 'isBareClassReceiverCandidate' | 'importsBindAtLexicalScope' | 'resolveNamespaceChains' + | 'resolveQualifiedCallee' + | 'resolveQualifiedTypeSpellings' + | 'splitQualifiedCallee' >; /** A bare, undecorated identifier and nothing else — see {@link isBareTypeName}. */ @@ -276,6 +283,10 @@ export function classifyReceiverOrigin( * external. Same hook the three receiver-chain lookups in * `compound-receiver.ts` already receive. */ readonly stripTypePreservingDecoration?: DecorationStripper; + /** `ScopeResolver.resolveQualifiedTypeSpellings`, so a base declared with a + * qualified type (`rp::C x`) is classified by the same lookup that typed + * (or failed to type) it. */ + readonly qualifiedTypeSpellings?: boolean; /** `LanguageProvider.isBuiltInName`, threaded through the pass options the * same way `emitFreeCallFallback` receives it. THE only source of positive * external evidence available here; languages that declare no built-in set @@ -299,8 +310,9 @@ export function classifyReceiverOrigin( // arguments, so an in-program generic base (`Box b; b.open()`) // resolves instead of being mislabelled and dropped from the hedge. if ( - resolveClassBindingForName(binding.declaredAtScope, binding.rawName, scopes, strip) !== - undefined + resolveClassBindingForName(binding.declaredAtScope, binding.rawName, scopes, strip, { + qualifiedTypeSpellings: options.qualifiedTypeSpellings, + }) !== undefined ) { return 'in-program'; } @@ -407,6 +419,8 @@ export function emitReceiverBoundCalls( index: WorkspaceResolutionIndex, model: SemanticModel, options: { + /** Stable pass identity for provider indexes shared with return propagation. */ + readonly allFilePaths?: ReadonlySet; readonly recordResolutionOutcome?: ResolutionOutcomeRecorder; readonly recordSourceBinding?: SourceBindingRecorder; /** Resolved-callee-id capture sink (#2227 U2). Threaded in under `--pdg` @@ -500,6 +514,17 @@ export function emitReceiverBoundCalls( return def !== undefined && CALLABLE_TYPES.has(def.type); }); }; + const resolveProviderQualifiedCallee = bindQualifiedCalleeResolver( + provider.resolveQualifiedCallee, + scopes, + index, + parsedFiles, + options.allFilePaths, + ); + const bindsQualifiedCallable = (typeRef: TypeRef): boolean => { + const definition = resolveProviderQualifiedCallee?.(typeRef.rawName, typeRef.declaredAtScope); + return definition !== undefined && CALLABLE_TYPES.has(definition.type); + }; // A class-like def NESTED in `owner` (`A.Item` inside `A`): its qualified // name is the owner's plus the segment — the identity the structure phase // and `populateClassOwnedMembers` agree on — so the qualified-name index @@ -636,6 +661,32 @@ export function emitReceiverBoundCalls( return undefined; return uniqueClassAcross(files, tail); }; + // A qualified callee as the free-call head of a compound receiver + // (`rp::make().m()`, or `x` bound to `rp::make`): the definition the + // qualified CALL resolves to, so its declared return type can type the + // receiver. Asked without call-site arity, so an ambiguous answer is none. + const splitQualifiedCallee = provider.splitQualifiedCallee; + const resolveQualifiedReceiverMember = provider.resolveQualifiedReceiverMember; + const resolveQualifiedCallee = + resolveProviderQualifiedCallee ?? + (splitQualifiedCallee === undefined || resolveQualifiedReceiverMember === undefined + ? undefined + : ( + callee: string, + inScope: ScopeId, + position?: TypeRef['lookupPosition'], + ): SymbolDefinition | undefined => { + const parts = splitQualifiedCallee(callee, inScope, scopes, position); + if (parts === undefined) return undefined; + const def = resolveQualifiedReceiverMember( + parts.receiver, + parts.member, + inScope, + scopes, + parsedFiles, + ); + return def === 'ambiguous' ? undefined : def; + }); const compoundOpts = { fieldFallback, elementTypeOf: provider.elementTypeOf, @@ -645,15 +696,19 @@ export function emitReceiverBoundCalls( hoistTypeBindingsToModule, stripReceiverCastExpressions: provider.stripReceiverCastExpressions === true, constructionSyntax: provider.constructionSyntax, + isTypeApplicationCall: provider.isTypeApplicationCall, stripTypePreservingDecoration: provider.stripTypePreservingDecoration, qualifiedTypeLookupSpelling: provider.qualifiedTypeLookupSpelling, resolveThisViaEnclosingClass: provider.resolveThisViaEnclosingClass, + qualifiedTypeSpellings: provider.resolveQualifiedTypeSpellings === true, + resolveQualifiedCallee, }; // Loop-invariant: both hooks come off the pass arguments, so the options bag // for `classifyReceiverOrigin` is built once here rather than per dropped site. const receiverOriginOpts = { stripTypePreservingDecoration: provider.stripTypePreservingDecoration, isBuiltInName: options.isBuiltInName, + qualifiedTypeSpellings: provider.resolveQualifiedTypeSpellings === true, }; // Maps class-like graph ids back to ALL scope definitions that resolved to @@ -1079,40 +1134,29 @@ export function emitReceiverBoundCalls( return n; }; - /** - * Declared type of the CLASS-LEVEL field named `fieldName` on `ownerId`, or - * `undefined` when the owner declares no such field, declares only an - * instance one, or declares one whose type was never captured. - * - * Both facts live on the graph NODE rather than on `SymbolDefinition` — - * `isStatic` is set by the structure phase and `declaredType` by the field - * extractor — which is the same place {@link isUnreachableByInstanceDispatch} - * reads `isStatic` from, so this introduces no new dependency. - * - * `isStatic === true` is required, not merely preferred. The receiver that - * asks this question resolved its head to the CLASS, so an instance field of - * that name is not reachable through it and answering with the instance - * field's type would type the receiver as something the source cannot - * denote. A def that resolves to no node, or a node with no captured type, - * answers `undefined` — the declining direction, matching how the rest of - * this pass treats an unresolvable lookup. - */ + // Undefined means absent; null means an untyped static declaration that + // shadows ancestors. An annotation names a type; a constructor names a value. const declaredTypeOfClassLevelField = ( ownerId: string, fieldName: string, - ): string | undefined => { + ): { readonly name: string; readonly purpose: 'type' | 'value' } | null | undefined => { + let declaresStatic = false; for (const candidate of model.fields.lookupAllByOwner(ownerId, fieldName)) { const graphId = resolveDefGraphId(candidate.filePath, candidate, nodeLookup); if (graphId === undefined) continue; const properties = graph.getNode(graphId)?.properties; if (properties?.isStatic !== true) continue; - const declaredType = properties.declaredType; - if (typeof declaredType !== 'string') continue; - const trimmed = declaredType.trim(); - if (trimmed.length === 0) continue; - return trimmed; + declaresStatic = true; + for (const [fieldType, purpose] of [ + [properties.declaredType, 'type'], + [properties.initializerType, 'value'], + ] as const) { + if (typeof fieldType !== 'string') continue; + const trimmed = fieldType.trim(); + if (trimmed.length > 0) return { name: trimmed, purpose }; + } } - return undefined; + return declaresStatic ? null : undefined; }; const resolveReceiverNamespace = provider.createReceiverNamespaceResolver?.(scopes, index); @@ -1222,10 +1266,11 @@ export function emitReceiverBoundCalls( `${receiverName}.${memberName}`, ); + const baseName = + decodeReceiverChain(site.receiverChain)?.baseReceiverName ?? + receiverName.split(/[.([\s]/, 1)[0]; + if (provider.suppressReceiverLookup !== undefined) { - const baseName = - decodeReceiverChain(site.receiverChain)?.baseReceiverName ?? - receiverName.split(/[.([\s]/, 1)[0]; const baseTypeRef = baseName === undefined ? undefined @@ -1254,7 +1299,7 @@ export function emitReceiverBoundCalls( // instead of letting the receiver-blind lexical fallback in // `lookupCore` match the enclosing class's member by name. // No-op for every language that leaves `Scope.ownsReceivers` unset. - if (isReceiverOwnedButUnbound(site.inScope, receiverName, scopes)) { + if (isReceiverOwnedButUnbound(site.inScope, baseName, scopes)) { options.recordSourceBinding?.(site, { status: 'blocked', targetDefIds: [], @@ -1268,6 +1313,7 @@ export function emitReceiverBoundCalls( range: site.atRange, reason: 'receiver-owned-but-unbound', candidateIds: [], + siteKind: site.kind, }); handledSites.add(siteKey); continue; @@ -1929,11 +1975,22 @@ export function emitReceiverBoundCalls( // opted in. Only a bare tail is walked here; `ns.Type.field.m()` is the // compound resolver's shape. sourceBindingGrounded = true; + const classReceiverCandidate = provider.isBareClassReceiverCandidate; const classDef = findClassBindingInScope(site.inScope, receiverName, scopes, undefined, { onNameFallback, position: site.atRange, purpose: 'value', + classCandidateFilter: + classReceiverCandidate === undefined + ? undefined + : (candidate) => + classReceiverCandidate({ + candidate, + spelling: receiverName, + inScope: site.inScope, + scopes, + }), }) ?? resolveNamespaceQualifiedClass(receiverName, site.inScope, namespaceTargets, site.atRange); if (classDef !== undefined) { @@ -2360,6 +2417,7 @@ export function emitReceiverBoundCalls( position: typeRef.lookupPosition, purpose: typeRef.lookupPurpose ?? 'type', onNameFallback, + qualifiedTypeSpellings: provider.resolveQualifiedTypeSpellings === true, }; const qualifiedOwner = classOfQualifiedTypeSpelling( typeRef, @@ -3057,7 +3115,7 @@ export function emitReceiverBoundCalls( // First owner that declares one wins, matching every other walk in // this pass. let fieldOwnerId: string | undefined; - let fieldDeclaredType: string | undefined; + let fieldDeclaredType: ReturnType; for (const ownerId of [ headClass.nodeId, ...scopes.methodDispatch.mroFor(headClass.nodeId), @@ -3067,8 +3125,10 @@ export function emitReceiverBoundCalls( staticMemberReceiver.memberName, ); if (declared === undefined) continue; - fieldOwnerId = ownerId; - fieldDeclaredType = declared; + if (declared !== null) { + fieldOwnerId = ownerId; + fieldDeclaredType = declared; + } break; } // Resolve the declared type from where it was WRITTEN — the @@ -3079,14 +3139,18 @@ export function emitReceiverBoundCalls( const declaringScope = fieldOwnerId === undefined ? undefined : index.classScopeByDefId.get(fieldOwnerId)?.id; const receiverClass = - declaringScope === undefined || fieldDeclaredType === undefined + declaringScope === undefined || fieldDeclaredType == null ? undefined : resolveClassBindingForName( declaringScope, - fieldDeclaredType, + fieldDeclaredType.name, scopes, provider.stripTypePreservingDecoration, - { onNameFallback }, + { + onNameFallback, + purpose: fieldDeclaredType.purpose, + qualifiedTypeSpellings: provider.resolveQualifiedTypeSpellings === true, + }, ); if (receiverClass !== undefined) { const chain = [ @@ -3170,7 +3234,7 @@ export function emitReceiverBoundCalls( site, confidence, calleeCapture, - fieldDeclaredType, + fieldDeclaredType?.name, ); handledSites.add(siteKey); continue; @@ -3197,7 +3261,9 @@ export function emitReceiverBoundCalls( // could not type (`x = ns.untyped()`) is a drop too, not an exact miss. (typeRef !== undefined && BARE_TYPE_NAME_RE.test(receiverName) && - bindsNamespaceCallable(typeRef, namespaceTargets))) + (bindsNamespaceCallable(typeRef, namespaceTargets) || + bindsQualifiedCallable(typeRef)))) && + provider.isModuleExportAssignment?.(site, scopes, parsed) !== true ) { // Decoded once: both the shape census and the origin classifier read the // same chain, and this is inside the drop guard so a resolved site pays diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/return-shape-members.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/return-shape-members.ts index b5b1c24b20..36728d687b 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/return-shape-members.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/return-shape-members.ts @@ -38,6 +38,7 @@ import type { CallableFlowOperand, ParsedFile, Scope, ScopeId } from 'gitnexus-shared'; import type { KnowledgeGraph } from '../../../graph/types.js'; +import { answeredSiteKey } from '../resolution-outcome.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import type { GraphNodeLookup } from '../graph-bridge/node-lookup.js'; import { resolveCallerGraphId } from '../graph-bridge/ids.js'; @@ -328,6 +329,13 @@ export function emitReturnShapeMemberAccesses( propertyNameIndex: PropertyNameIndex, /** Sites this pass resolves, so the name fallback leaves them alone. */ handledSink: Set, + /** + * Receives the {@link answeredSiteKey} of every site this pass emitted an edge + * for. Narrower than `handledSink`, which also claims a site the producer's + * shape DISPROVED — that site is settled, but it has no edge, so a drop + * recorded for it must stand. + */ + answeredSink?: Set, ): ReturnShapeMemberStats { let emitted = 0; let memberNotOnShape = 0; @@ -509,6 +517,7 @@ export function emitReturnShapeMemberAccesses( }); // Claim the site so the name fallback cannot re-answer it differently. handledSink.add(siteKey); + answeredSink?.add(answeredSiteKey(parsed.filePath, site.atRange, site.kind, site.name)); emitted++; } } diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/unique-name-properties.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/unique-name-properties.ts index 24fa8faad7..ec3e4abb31 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/unique-name-properties.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/unique-name-properties.ts @@ -63,13 +63,14 @@ * rather than through `tryEmitEdge`, whose target side takes a def. */ -import type { ImportEdge, ParsedFile, ScopeId } from 'gitnexus-shared'; +import type { ImportEdge, ParsedFile, ReferenceSite, ScopeId } from 'gitnexus-shared'; import type { KnowledgeGraph } from '../../../graph/types.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import type { GraphNodeLookup } from '../graph-bridge/node-lookup.js'; import { resolveCallerGraphId } from '../graph-bridge/ids.js'; import { callableFlowSiteKey } from './callable-value-flow.js'; import { isTestFile } from '../../entry-point-scoring.js'; +import { answeredSiteKey } from '../resolution-outcome.js'; import { getLanguageFromFilename } from 'gitnexus-shared'; /** Language a definition lives in, for reporting which anchor a reader cannot reach. */ @@ -299,21 +300,6 @@ function buildDirectImportMap( return byFile; } -/** Is this Property id qualified by `.`, allowing a position suffix? */ -function idOwnedBy(id: string, owner: string): boolean { - const at = id.indexOf(`:${owner}.`); - if (at === -1) return false; - const rest = id.slice(at + owner.length + 2); - return !rest.includes('.') || rest.indexOf('@') < rest.indexOf('.'); -} - -/** Trailing symbol name of a graph id (`Function:a/b.js:buildB` -> `buildB`). */ -function simpleNameOfGraphId(graphId: string): string { - const tail = graphId.slice(graphId.lastIndexOf(':') + 1); - const at = tail.indexOf('@'); - return at === -1 ? tail : tail.slice(0, at); -} - /** * Pick the single candidate a read in `readingFile` can plausibly mean. * @@ -327,8 +313,7 @@ function narrowToSingleCandidate( candidatesIn: readonly PropertyCandidate[], readingFile: string, importedFiles: ReadonlySet | undefined, - /** Simple name of the callable the site sits in, when it could be resolved. */ - ownerName?: string, + site: ReferenceSite, ): { readonly id: string; readonly tier: string } | null { // DECLARED ANCHORS FIRST. A return shape is a real definition but a weaker // one: it says "some function builds an object with this key", where a named @@ -338,20 +323,13 @@ function narrowToSingleCandidate( // return shapes were indexed at all. let candidates = candidatesIn; - // A SITE INSIDE ITS OWN RETURN SHAPE BINDS TO ITS OWN KEY. - // - // `export function buildB(row) { return { tickIntervalMs: row.b } }` writes - // the key that IS `buildB.tickIntervalMs`. Ranking declared anchors above - // return shapes is right for a READ through a receiver, but applied here it - // handed that write to a same-named module const (`fnSettings.tickIntervalMs`) - // that `buildB` never touches — a wrong edge, reported at the confident tier, - // and the node the key actually defines was left with no writer at all. - // - // Checked before every other rule because it is evidence rather than ranking: - // the owner qualifier on the candidate id and the enclosing callable are the - // same symbol. Nothing else can outrank that. - if (ownerName !== undefined && ownerName.length > 0) { - const own = candidates.filter((c) => c.fromReturnShape && idOwnedBy(c.id, ownerName)); + // Only the key's declaration WRITE proves ownership. Other accesses inside + // the producer still use ordinary ranking, even when they share its key name. + if (site.kind === 'write') { + const position = `@${site.atRange.startLine - 1}:${site.atRange.startCol}`; + const own = candidates.filter( + (c) => c.fromReturnShape && c.filePath === readingFile && c.id.endsWith(position), + ); if (own.length === 1) return { id: own[0]!.id, tier: 'own-return-shape' }; } @@ -427,6 +405,13 @@ export function emitUniqueNamePropertyAccesses( * asserts nothing about what it means. */ reportOnly = false, + /** + * Receives the {@link answeredSiteKey} of every site this pass emitted an edge + * for, so the caller can withdraw a `receiver-unresolved` drop the + * receiver-bound pass recorded for it earlier. Never written in `reportOnly` + * mode: a site that was only counted still has no edge. + */ + answeredSink?: Set, ): UniqueNamePropertyStats { const byName = prebuiltPropertyNameIndex ?? buildPropertyNameIndex(graph); const ownFilePaths = new Set(parsedFiles.map((p) => p.filePath)); @@ -489,8 +474,6 @@ export function emitUniqueNamePropertyAccesses( continue; } - // Resolved BEFORE narrowing: the enclosing callable is evidence the - // ranking needs, not just the edge's source. const callerGraphId = resolveCallerGraphId( site.callerScope ?? site.inScope, indexes, @@ -503,7 +486,7 @@ export function emitUniqueNamePropertyAccesses( candidates, parsed.filePath, directImports.get(parsed.filePath), - simpleNameOfGraphId(callerGraphId), + site, ); if (choice === null) { ambiguous++; @@ -532,6 +515,7 @@ export function emitUniqueNamePropertyAccesses( reason: `${EDGE_REASON} (${choice.tier}): ${site.kind}`, evidence: [], }); + answeredSink?.add(answeredSiteKey(parsed.filePath, site.atRange, site.kind, site.name)); emitted++; } } diff --git a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts index 97f8a66b06..6f574720f6 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts @@ -110,6 +110,7 @@ import { } from '../utils/generic-instantiation.js'; import { buildWorkspaceResolutionIndex } from '../workspace-index.js'; import type { ResolutionOutcome, ResolutionOutcomeRecorder } from '../resolution-outcome.js'; +import { withdrawAnsweredReceiverDrops } from '../resolution-outcome.js'; import { logHeapProbe } from '../../utils/heap-probe.js'; import { parseTruthyEnv } from '../../utils/env.js'; @@ -699,6 +700,8 @@ export function runScopeResolution( if (extractionWarned) scopeExtractionFailedPaths.push(file.path); continue; } + const captureSideChannel = provider.languageProvider.collectCaptureSideChannel?.(file.path); + if (captureSideChannel !== undefined) parsed = { ...parsed, captureSideChannel }; if (input.pdg === true && provider.languageProvider.collectSourceCfgs) { const warnCfg = (message: string): void => { logger.warn(message); @@ -1018,11 +1021,9 @@ export function runScopeResolution( }); logHeapProbe('sr-post-workspaceIndex', `lang=${provider.language}`); - // Cross-file implicit-namespace visibility (C#). Must run before - // propagateImportedReturnTypes so the latter pass sees siblings' - // class bindings when chasing return-type chains across files. - // The hook writes to `bindingAugmentations` only; finalized - // `indexes.bindings` remains immutable post-finalize (I8). + // Complete implicit namespace visibility and refine provider-owned type facts + // before return propagation. New bindings use bindingAugmentations; existing + // scope typeBindings may be refined. indexes.bindings stays immutable (I8). if (provider.populateNamespaceSiblings !== undefined) { provider.populateNamespaceSiblings(parsedFiles, indexes, { fileContents: getFileContents(), @@ -1046,7 +1047,13 @@ export function runScopeResolution( // with chain-follow per importer; quadratic regressions show up // here, not in finalize). if (provider.propagatesReturnTypesAcrossImports !== false) { - propagateImportedReturnTypes(parsedFiles, indexes, workspaceIndex); + propagateImportedReturnTypes( + parsedFiles, + indexes, + workspaceIndex, + provider.resolveQualifiedCallee, + allFilePaths, + ); } const tRangeBindStart = PROF ? process.hrtime.bigint() : 0n; @@ -1242,6 +1249,7 @@ export function runScopeResolution( { recordResolutionOutcome, recordSourceBinding, + allFilePaths, calleeIdSink: calleeIdAccumulator, // The pass's only source of positive EXTERNAL evidence for a dropped // receiver (`console.log`, `fetch(...)`). Same hook, same spelling as @@ -1346,6 +1354,7 @@ export function runScopeResolution( calleeIdSink: calleeIdAccumulator, recordSourceBinding, isBuiltInName: provider.languageProvider.isBuiltInName, + allFilePaths, heritageTypeArguments, unresolvedInheritanceByClass, }, @@ -1443,6 +1452,7 @@ export function runScopeResolution( // several functions returning the same field name. Sites it resolves are // added to the skip set, so the fallback below never second-guesses them. const sharedPropertyIndex = input.prebuiltPropertyNameIndex ?? buildPropertyNameIndex(graph); + const answeredAfterReceiverPass = new Set(); const returnShapeMembers = callableFlowOnly ? { emitted: 0, memberNotOnShape: 0 } : emitReturnShapeMemberAccesses( @@ -1453,6 +1463,7 @@ export function runScopeResolution( uniqueNameSkipSites, sharedPropertyIndex, uniqueNameSkipSites, + answeredAfterReceiverPass, ); const nameFallbackDisabled = provider.fieldFallbackOnMethodLookup === false; @@ -1474,7 +1485,9 @@ export function runScopeResolution( finalized, sharedPropertyIndex, nameFallbackDisabled, + answeredAfterReceiverPass, ); + withdrawAnsweredReceiverDrops(resolutionOutcomes, answeredAfterReceiverPass); // value-ref registrations (#2437): USES edges at the registration sites // plus field-based dispatch — synthesized CALLS from member-call sites to diff --git a/gitnexus/src/core/ingestion/scope-resolution/pipeline/validate-bindings-immutability.ts b/gitnexus/src/core/ingestion/scope-resolution/pipeline/validate-bindings-immutability.ts index 19c2805afc..320b95bf19 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/pipeline/validate-bindings-immutability.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/pipeline/validate-bindings-immutability.ts @@ -75,10 +75,10 @@ export function validateBindingsImmutability( } // Third channel: `workspaceFqnBindings` (scope-independent, shared map - // populated by language namespace-sibling hooks — PHP FQN keys, C# - // global-namespace simple names). Like bindingAugmentations its inner - // arrays are mutable by contract (hooks `push()` directly), so freezing - // one is the same defect as freezing an augmentation bucket. + // populated by language namespace-sibling hooks — e.g. PHP FQN keys). Like + // bindingAugmentations its inner arrays are mutable by contract (hooks + // `push()` directly), so freezing one is the same defect as freezing an + // augmentation bucket. for (const [name, bucket] of indexes.workspaceFqnBindings) { if (Object.isFrozen(bucket)) { onWarn( diff --git a/gitnexus/src/core/ingestion/scope-resolution/resolution-outcome.ts b/gitnexus/src/core/ingestion/scope-resolution/resolution-outcome.ts index 8a14460a64..9ccbcdf531 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/resolution-outcome.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/resolution-outcome.ts @@ -233,3 +233,58 @@ export function classifyReceiverShape(decoded: DecodedReceiverChain | undefined) } export type ResolutionOutcomeRecorder = (outcome: ResolutionOutcome) => void; + +/** + * Identity of ONE reference site, for withdrawing that site's drop and no + * other's. + * + * Position alone is not enough: `cfg.timeouts` (a read of `timeouts`) and + * `cfg.timeouts.retry()` (a call of `retry`) both start at `cfg`, so a key of + * file + line + column names two sites. The kind, member name, and full range + * separate them, including repeated names such as `res.data.data`. + */ +export function answeredSiteKey( + filePath: string, + range: Range, + siteKind: ReferenceKind, + name: string, +): string { + return `${filePath}:${range.startLine}:${range.startCol}:${range.endLine}:${range.endCol}:${siteKind}:${name}`; +} + +/** + * Withdraw every `receiver-unresolved` drop whose site a LATER pass answered + * with an edge, keyed by {@link answeredSiteKey}. Returns how many it removed. + * + * The receiver-bound pass records a drop as soon as its own cases give up, but + * it is not the last pass to see a read or write: the return-shape and + * unique-name passes run after it and can still emit an `ACCESSES` edge for the + * same site. A drop says the site was lost with no candidate, and a site with an + * edge was not lost. A site those passes also left alone keeps its drop. + * + * A drop without a `siteKind` is kept: the key needs the kind, and guessing it + * would withdraw on a weaker identity than the one the passes recorded. + * Compacts in place, keeping the survivors in their recorded order. + */ +export function withdrawAnsweredReceiverDrops( + outcomes: ResolutionOutcome[], + answered: ReadonlySet, +): number { + if (answered.size === 0) return 0; + let kept = 0; + for (const outcome of outcomes) { + const isAnsweredDrop = + outcome.kind === 'suppressed' && + outcome.reason === 'receiver-unresolved' && + outcome.siteKind !== undefined && + answered.has( + answeredSiteKey(outcome.filePath, outcome.range, outcome.siteKind, outcome.name), + ); + if (isAnsweredDrop) continue; + outcomes[kept] = outcome; + kept++; + } + const withdrawn = outcomes.length - kept; + outcomes.length = kept; + return withdrawn; +} diff --git a/gitnexus/src/core/ingestion/scope-resolution/scope/walkers.ts b/gitnexus/src/core/ingestion/scope-resolution/scope/walkers.ts index 9b8fc5c875..42756d8848 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/scope/walkers.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/scope/walkers.ts @@ -49,6 +49,7 @@ import { definitionIdPosition } from '../utils/definition-id.js'; const EMPTY_BINDINGS: readonly BindingRef[] = Object.freeze([]); interface IndexedNameLookupOptions extends NameLookupOptions { + readonly classCandidateFilter?: (def: SymbolDefinition) => boolean; /** Add same-scope candidates beside legacy local bindings. Explicit name * claims still select their own candidates through the shared resolver. */ readonly expandLocalBindings?: ( @@ -58,6 +59,15 @@ interface IndexedNameLookupOptions extends NameLookupOptions { ) => readonly BindingRef[]; } +function compatibleClassBindings( + bindings: readonly BindingRef[], + accept?: (def: SymbolDefinition) => boolean, +): readonly BindingRef[] { + return accept === undefined + ? bindings + : bindings.filter((binding) => !isClassLike(binding.def.type) || accept(binding.def)); +} + /** Resolve ownership before any target-kind filtering or global fallback. */ export function lookupNameClaim( startScope: ScopeId, @@ -72,8 +82,14 @@ export function lookupNameClaim( scopes: scopes.scopeTree, importsAt: (scope) => scopes.imports?.get(scope.id) ?? scope.imports, bindingsAt: (scope, spelling) => { - const local = scope.bindings.get(spelling) ?? []; - const augmented = scopes.bindingAugmentations.get(scope.id)?.get(spelling) ?? []; + const local = compatibleClassBindings( + scope.bindings.get(spelling) ?? EMPTY_BINDINGS, + options.classCandidateFilter, + ); + const augmented = compatibleClassBindings( + scopes.bindingAugmentations.get(scope.id)?.get(spelling) ?? EMPTY_BINDINGS, + options.classCandidateFilter, + ); // Unrelated claims must not change the legacy local binding tier. // Providers may add candidates that share that selected tier. if (local.length > 0 && nameClaimsFor(scope, spelling).length === 0) { @@ -85,7 +101,7 @@ export function lookupNameClaim( ) ?? EMPTY_BINDINGS; return [ ...local, - ...additional, + ...compatibleClassBindings(additional, options.classCandidateFilter), ...augmented.filter( (binding) => binding.declarationRange !== undefined || binding.availableFrom !== undefined, @@ -94,10 +110,21 @@ export function lookupNameClaim( } return [ ...local, - ...(scopes.bindings.get(scope.id)?.get(spelling) ?? []), + ...compatibleClassBindings( + scopes.bindings.get(scope.id)?.get(spelling) ?? EMPTY_BINDINGS, + options.classCandidateFilter, + ), ...augmented, - ...(collectNamespaceFqnBindings(scope.id, spelling, scopes) ?? []), - ...(scopes.workspaceFqnBindings?.get(spelling) ?? []), + ...(collectNamespaceFqnBindings( + scope.id, + spelling, + scopes, + options.classCandidateFilter, + ) ?? []), + ...compatibleClassBindings( + scopes.workspaceFqnBindings?.get(spelling) ?? EMPTY_BINDINGS, + options.classCandidateFilter, + ), ]; }, }, @@ -166,11 +193,8 @@ export function lookupBindingsAt( const finalized = scopes.bindings.get(scopeId)?.get(name); const augmented = scopes.bindingAugmentations.get(scopeId)?.get(name); const workspace = scopes.workspaceFqnBindings?.get(name); - // Per-namespace channel (#1871 named-namespace generalization). Gated by - // accessibility: only a *module* scope carries an `accessibleNamespacesByScope` - // entry, so this collects nothing at child scopes and at module scopes only for - // the namespaces that file can see. Empty (no entry) for every non-C# bundle, - // so the behavior of the three pre-existing channels is unchanged. + // Providers attach visible namespace channels to their owning scopes. + // An absent entry leaves the pre-existing channels unchanged. const namespaceRefs = collectNamespaceFqnBindings(scopeId, name, scopes); const fLen = finalized?.length ?? 0; const aLen = augmented?.length ?? 0; @@ -182,11 +206,11 @@ export function lookupBindingsAt( if (fLen === 0 && aLen === 0 && nLen === 0) return workspace!; if (fLen === 0 && aLen === 0 && wLen === 0) return namespaceRefs!; // Merge in precedence order, deduped by `def.nodeId` so the strongest source - // wins duplicate metadata. Named-namespace refs come BEFORE the flat global - // `workspace` channel: pre-#1871 these lived in `bindingAugmentations` (which - // `lookupBindingsAt` already ranks above `workspaceFqnBindings`), so a name in - // both an accessible named namespace and the global namespace must still - // resolve named-first. Order: finalized > augmented > namespace > workspace. + // wins duplicate metadata. Namespace refs come BEFORE the flat `workspace` + // channel: pre-#1871 they lived in `bindingAugmentations` (which + // `lookupBindingsAt` already ranks above `workspaceFqnBindings`), and their + // relative order is the accessibility list's, which the provider sets. + // Order: finalized > augmented > namespace > workspace. const seen = new Set(); const out: BindingRef[] = []; for (const src of [finalized, augmented, namespaceRefs, workspace]) { @@ -203,16 +227,32 @@ export function lookupBindingsAt( /** * Collect `BindingRef`s for `name` from the per-namespace channel * (`namespaceFqnBindings`) across every namespace accessible from `scopeId`. - * Accessibility comes from `accessibleNamespacesByScope`, which is keyed by - * *module* scope id — so this returns `undefined` at non-module scopes and at - * every scope in a bundle that didn't populate the channel (all non-C# today). - * Language-neutral: keyed only by namespace strings and the index. + * Accessibility is supplied by the provider at declaration or module scopes. + * Optional precedence groups stop at the nearest matching group, preserving + * ambiguity within that group. Bundles without groups retain flat collection. */ function collectNamespaceFqnBindings( scopeId: ScopeId, name: string, scopes: ScopeResolutionIndexes, + acceptClass?: (def: SymbolDefinition) => boolean, ): readonly BindingRef[] | undefined { + const tiers = scopes.namespaceLookupTiersByScope?.get(scopeId); + if (tiers !== undefined) { + for (const tier of tiers) { + const candidates: BindingRef[] = []; + for (const namespace of tier) { + candidates.push( + ...compatibleClassBindings( + scopes.namespaceFqnBindings?.get(namespace)?.get(name) ?? EMPTY_BINDINGS, + acceptClass, + ), + ); + } + if (candidates.length > 0) return candidates; + } + return undefined; + } const namespaces = scopes.accessibleNamespacesByScope?.get(scopeId); if (namespaces === undefined || namespaces.length === 0) return undefined; let collected: BindingRef[] | undefined; @@ -220,7 +260,7 @@ function collectNamespaceFqnBindings( const bucket = scopes.namespaceFqnBindings?.get(ns)?.get(name); if (bucket !== undefined && bucket.length > 0) { if (collected === undefined) collected = []; - for (const r of bucket) collected.push(r); + for (const r of compatibleClassBindings(bucket, acceptClass)) collected.push(r); } } return collected; @@ -241,11 +281,11 @@ const EMPTY_NAMES: Iterable = Object.freeze([]) as readonly string[]; * * Scope: enumerates only the per-scope `bindings` and `bindingAugmentations` * channels. It deliberately EXCLUDES the scope-independent - * `workspaceFqnBindings` channel (PHP FQN keys, C# global-namespace simple - * names). `lookupBindingsAt` consults that third channel when resolving a - * specific name, but name *enumeration* here does not — those names apply at - * every scope and would flood per-scope callers. Callers that need - * workspace-level names must read `workspaceFqnBindings` directly. + * `workspaceFqnBindings` channel (FQN keys). `lookupBindingsAt` consults that + * third channel when resolving a specific name, but name *enumeration* here + * does not — those names apply at every scope and would flood per-scope + * callers. Callers that need workspace-level names must read + * `workspaceFqnBindings` directly. */ export function namesAtScope(scopeId: ScopeId, scopes: ScopeResolutionIndexes): Iterable { const finalized = scopes.bindings.get(scopeId); @@ -542,13 +582,12 @@ export function findReceiverTypeBinding( const claim = lookupNameClaim(startScope, receiverName, scopes, options); // An absent name keeps the type an undeclared write gave it in this scope. if (claim.status !== 'absent' || claim.typeBinding !== undefined) return claim.typeBinding; - const moduleScopeId = moduleScopeIdOf(startScope, scopes); // Fallback 1 — named namespaces accessible from this file (own + `using`d), // gated by `accessibleNamespacesByScope`. Consulted BEFORE the global channel // so a more-specific named binding wins, matching the pre-#1871 order where // these lived in the file's own `Scope.typeBindings` (the chain, above the // global fallback). Shared-channel routing avoids the O(files × names) blow-up. - const named = namespaceTypeBindingFor(moduleScopeId, receiverName, scopes); + const named = namespaceTypeBindingFor(startScope, receiverName, scopes); if (named !== undefined) return named; // Fallback 2 — global/default namespace: C# global types are visible from // every file (see `workspaceTypeBindings` doc), so this flat channel is the @@ -558,19 +597,24 @@ export function findReceiverTypeBinding( /** * Resolve a typeBinding for `name` from the per-namespace channel - * (`namespaceTypeBindings`) across the namespaces accessible from `moduleScopeId`. - * First accessible-namespace hit wins. Returns `undefined` when the module has no - * accessibility entry (non-module scope id, or a bundle that didn't populate the - * channel — all non-C# today). Shared by the two typeBindings chain-walkers so - * the named-namespace fallback stays identical between them. + * (`namespaceTypeBindings`) from the nearest scope carrying an accessibility + * entry. First accessible-namespace hit wins. Missing entries and parent cycles + * return no answer. Shared by the two post-finalize type-binding walkers. */ export function namespaceTypeBindingFor( - moduleScopeId: ScopeId | null, + startScopeId: ScopeId | null, name: string, scopes: ScopeResolutionIndexes, ): TypeRef | undefined { - if (moduleScopeId === null) return undefined; - const namespaces = scopes.accessibleNamespacesByScope?.get(moduleScopeId); + let scopeId = startScopeId; + const visited = new Set(); + let namespaces: readonly string[] | undefined; + while (scopeId !== null && !visited.has(scopeId)) { + visited.add(scopeId); + namespaces = scopes.accessibleNamespacesByScope?.get(scopeId); + if (namespaces !== undefined) break; + scopeId = scopes.scopeTree.getScope(scopeId)?.parent ?? null; + } if (namespaces === undefined) return undefined; for (const ns of namespaces) { const hit = scopes.namespaceTypeBindings?.get(ns)?.get(name); @@ -879,7 +923,7 @@ function soleBoundBaseName(bound: string): string | undefined { return base.length === 0 ? undefined : base; } -export type ClassBindingLookup = NameLookupOptions & { +export type ClassBindingLookup = IndexedNameLookupOptions & { /** A selected class came from a workspace-name guess, rather than a * binding/namespace decision. Observers must not treat it as edit proof. */ readonly onNameFallback?: () => void; @@ -902,6 +946,13 @@ export type ClassBindingLookup = NameLookupOptions & { * pass it is unchanged. */ readonly namespaceMemberVisible?: (def: SymbolDefinition) => boolean; + /** + * `ScopeResolver.resolveQualifiedTypeSpellings`. When true, + * {@link resolveClassBindingForName} answers a QUALIFIED spelling that bound + * nothing (`rp::C`, `a::Config`) through {@link resolveQualifiedClassSpelling}. + * Read by nothing else; absent (the default) leaves every lookup unchanged. + */ + readonly qualifiedTypeSpellings?: boolean; }; export function findClassBindingInScope( @@ -970,7 +1021,8 @@ export function findClassBindingInScope( def !== undefined && isClassLike(def.type) && targetFiles.has(def.filePath) && - (lookup?.namespaceMemberVisible?.(def) ?? true) + (lookup?.namespaceMemberVisible?.(def) ?? true) && + (lookup?.classCandidateFilter?.(def) ?? true) ) candidates.set(def.nodeId, def); } @@ -988,7 +1040,11 @@ export function findClassBindingInScope( const qnames = scopes.qualifiedNames.get(receiverName); if (qnames.length === 1) { const def = scopes.defs.get(qnames[0]!); - if (def !== undefined && isClassLike(def.type)) { + if ( + def !== undefined && + isClassLike(def.type) && + (lookup?.classCandidateFilter?.(def) ?? true) + ) { lookup?.onNameFallback?.(); return def; } @@ -1002,7 +1058,11 @@ export function findClassBindingInScope( const simpleIds = scopes.qualifiedNames.get(simple); if (simpleIds.length === 1) { const def = scopes.defs.get(simpleIds[0]!); - if (def !== undefined && isClassLike(def.type)) { + if ( + def !== undefined && + isClassLike(def.type) && + (lookup?.classCandidateFilter?.(def) ?? true) + ) { lookup?.onNameFallback?.(); return def; } @@ -1331,7 +1391,8 @@ export function resolveClassBindingForName( // // If a future case genuinely needs it, it must be gated on // `bindsTypeParameter` and land with a test that fails without it. - if (!rawClassName.includes('<')) return undefined; + if (!rawClassName.includes('<')) + return qualifiedSpellingFallback(scopeId, rawClassName, scopes, lookup); const baseName = stripTemplateArguments(rawClassName).replace(/\s+/g, ''); if (baseName.length === 0) return undefined; @@ -1372,8 +1433,61 @@ export function resolveClassBindingForName( // ── Base-name route ──────────────────────────────────────────────────────── // Nothing matched the arguments as written, so what is left to find is the // declaration written against its PARAMETERS — the one instantiation-agnostic - // declaration the erasure is entitled to reach. - return resolveErasedBaseName(scopeId, baseName, scopes, lexical); + // declaration the erasure is entitled to reach. A qualified base + // (`ns::Repo`) is tried only after both, so a specialization the + // argument match can reach is never bypassed by the argument-blind + // qualified route. + return ( + resolveErasedBaseName(scopeId, baseName, scopes, lexical) ?? + qualifiedSpellingFallback(scopeId, rawClassName, scopes, lookup) + ); +} + +/** {@link resolveQualifiedClassSpelling}, for the providers that opted in. */ +function qualifiedSpellingFallback( + scopeId: string, + rawClassName: string, + scopes: ScopeResolutionIndexes, + lookup: ClassBindingLookup | undefined, +): SymbolDefinition | undefined { + return lookup?.qualifiedTypeSpellings === true + ? resolveQualifiedClassSpelling(scopeId, rawClassName, scopes) + : undefined; +} + +/** + * The class a QUALIFIED declared-type spelling names — `rp::C`, `a::Config`, + * `rp::Box` — through {@link resolveQualifiedInheritanceBase}, the route a + * qualified inheritance base and a qualified type reference already take. + * + * The receiver-typing lookups above understand a qualifier only as a `.` + * namespace-import handle, and a language whose qualifier is a namespace path + * (an include binds no handle, and the index keys `rp::C` under `C`) never + * has one, so a qualified local, parameter or factory result typed nothing. + * Reducing the spelling to its tail is NOT the fix: the tail binds the nearest + * same-named class, which is exactly the class the qualifier was written to + * rule out (`a::Config` inside a `namespace b` that declares its own Config). + * The qualified route matches the qualifier against each candidate's + * namespace and refuses on a tie, so it binds the named class or nothing. + * + * Declines for an unqualified spelling and for a qualifier that is a type + * parameter in scope (`T::type` is a dependent name, not a namespace path). + */ +export function resolveQualifiedClassSpelling( + scopeId: string, + rawClassName: string, + scopes: ScopeResolutionIndexes, +): SymbolDefinition | undefined { + const normalized = stripTrailingTypeArguments(normalizeQualifiedName(rawClassName)); + const dot = normalized.indexOf('.'); + if (dot <= 0) return undefined; + if (bindsTypeParameter(scopeId, normalized.slice(0, dot), scopes)) return undefined; + return resolveQualifiedInheritanceBase( + scopeId, + rawClassName, + scopes, + findEnclosingClassDef(scopeId, scopes), + ); } /** diff --git a/gitnexus/src/core/ingestion/scope-resolution/unresolved-receivers.ts b/gitnexus/src/core/ingestion/scope-resolution/unresolved-receivers.ts index 4c94498190..40c0d13515 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/unresolved-receivers.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/unresolved-receivers.ts @@ -1,5 +1,5 @@ /** - * Aggregate `receiver-unresolved` resolution outcomes into the small, + * Aggregate unresolved and owned-but-unbound receiver calls into the small, * index-persisted summary that `impact()` / `context()` read to decide whether * their result is exact or a lower bound (#2744, the second half of #2708). * @@ -74,7 +74,7 @@ export interface UnresolvedReceiverSummary { * identical or the artifact churns on one map and not the other is exactly the */ /** - * A `receiver-unresolved` drop at a CALL site. + * An unresolved or owned-but-unbound receiver at a CALL site. * * ONE predicate, shared by the persisted summary and the per-file diagnostic — * the same contract `rankAndCap` states for its comparator. If the two ever @@ -86,8 +86,9 @@ export interface UnresolvedReceiverSummary { * (`x.argtypes = [...]`) arrive alongside lost method calls — measured at 25 of * 124 drops on the fixture corpus. Counting them made the consumer's "N call * sites invoking X were dropped" literally false. A missing `siteKind` counts as - * a call: the only emitter always sets it, and erring toward `lower-bound` is - * the safe direction for an epistemic signal. + * a call for `receiver-unresolved`, preserving the older recorder contract. + * Owned-but-unbound outcomes require an explicit call kind because that + * recorder also reports property accesses. * * Receiver ORIGIN is deliberately NOT decided here — the summary routes external * drops into their own bucket while the diagnostic excludes them, and collapsing @@ -98,8 +99,9 @@ function isUnresolvedReceiverCall( ): outcome is Extract { return ( outcome.kind === 'suppressed' && - outcome.reason === 'receiver-unresolved' && - (outcome.siteKind === undefined || outcome.siteKind === 'call') + ((outcome.reason === 'receiver-unresolved' && + (outcome.siteKind === undefined || outcome.siteKind === 'call')) || + (outcome.reason === 'receiver-owned-but-unbound' && outcome.siteKind === 'call')) ); } diff --git a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts b/gitnexus/src/core/ingestion/utils/package-dir-index.ts similarity index 87% rename from gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts rename to gitnexus/src/core/ingestion/utils/package-dir-index.ts index 30c4c2d96a..163e9ac865 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts +++ b/gitnexus/src/core/ingestion/utils/package-dir-index.ts @@ -30,30 +30,10 @@ * (`languages/kotlin/import-target.ts`); this index, the C# csproj index and * the legacy `go.ts` scan followed. * - * The strongest evidence that the rule was accidental is that a sixth - * implementation of the same question never had it. `import-resolvers/jvm.ts` - * answers "files directly inside a directory ending with " for - * Java and Kotlin wildcard imports, and has used `lastIndexOf` since #488. - * - * That is evidence about how the predicate was WRITTEN, not about live - * behaviour, and the distinction matters enough to spell out. `jvm.ts` is - * reached only through `provider.importResolver`, which `languages/java.ts` and - * `languages/kotlin.ts` do wire — but that field currently has no production - * READER. Its only reader anywhere is `import-target-adapter.ts`, whose own - * docblock says it is "threaded through `finalizeScopeModel`"; nothing threads - * it, and neither that module nor its two exports - * (`buildImportTargetWorkspace`, `resolveImportTargetAcrossLanguages`) is - * referenced outside its own unit test. So `jvm.ts`'s `resolveJvmWildcard` and - * `import-resolvers/go.ts`'s `resolveGoPackage` are dormant, while THIS index, - * `csharp.ts`'s `resolveCSharpImportInternal` and Kotlin's `dirChildren` are - * the ones that run. Whether those two dormant resolvers should be deleted or - * actually wired up is an open question and wants its own issue; it is not - * settled here. - * - * The argument survives that correction intact, because it never needed the - * resolvers to be live: an independent implementation of the same question, - * written without reference to the pre-index scan, reached for `lastIndexOf`. - * The extra clause was never a rule anyone chose. All six spellings now agree. + * The former JVM wildcard helper independently used `lastIndexOf` since #488, + * which helped identify the first-occurrence restriction as accidental. + * That dormant helper has been removed; this index and the active namespace + * resolvers retain the corrected suffix predicate. * * The length guard the `indexOf` form needed is gone with it: `endsWith` is * false for a shorter `D` instead of comparing -1 to -1. diff --git a/gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts b/gitnexus/src/core/ingestion/utils/per-file-set.ts similarity index 94% rename from gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts rename to gitnexus/src/core/ingestion/utils/per-file-set.ts index 4de0ee3612..f3d10aeead 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/per-file-set.ts +++ b/gitnexus/src/core/ingestion/utils/per-file-set.ts @@ -41,7 +41,7 @@ * `CountingSet`, driven by the contract test's `minimumParsedFileReads`. * * A THIRD shape — an array materialized from the file set — is what the type - * exists to reject. `import-resolvers/csharp.ts` used one until #2911, and it + * exists to reject. `languages/csharp/import-helpers.ts` used one until #2911, and it * is worth a compile error rather than a rule: copying an array mints a fresh * `WeakMap` key while traversing the Set zero extra times, so every * scan-counting guard stays green at its correct value while the index rebuilds @@ -49,9 +49,7 @@ * above and was caught only by a timing ratio in `bench/import-target/`. Derive * the array inside the builder from `getWorkspaceFileIndex(allFilePaths)` * instead. `string[]` is not assignable to `K`, so the shape cannot come back - * silently — `configs/swift.ts` keeps the one hand-rolled `WeakMap` on - * `ctx.allFileList` in the tree, deliberately and with its reasons written - * down, and it is deliberately NOT on this primitive. + * silently. * * `T extends object` is deliberate, chosen over probing `has` before `get`. * `WeakMap.get` returning `undefined` cannot distinguish "not built yet" from diff --git a/gitnexus/src/core/ingestion/import-resolvers/utils.ts b/gitnexus/src/core/ingestion/utils/suffix-index.ts similarity index 89% rename from gitnexus/src/core/ingestion/import-resolvers/utils.ts rename to gitnexus/src/core/ingestion/utils/suffix-index.ts index 5dec720bc2..262565d5a6 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/utils.ts +++ b/gitnexus/src/core/ingestion/utils/suffix-index.ts @@ -2,58 +2,6 @@ * Suffix-index helpers for import path resolution. */ -/** All file extensions to try during resolution */ -export const EXTENSIONS = [ - '', - // TypeScript/JavaScript - '.tsx', - '.ts', - '.mts', - '.cts', - '.jsx', - '.js', - '.mjs', - '.cjs', - '.vue', - '/index.tsx', - '/index.ts', - '/index.jsx', - '/index.js', - // Python - '.py', - '/__init__.py', - // Java - '.java', - // Kotlin - '.kt', - '.kts', - // C/C++ - '.c', - '.h', - '.cpp', - '.hpp', - '.cc', - '.cxx', - '.hxx', - '.hh', - '.cu', - '.cuh', - // C# - '.cs', - // Go - '.go', - // Rust - '.rs', - '/mod.rs', - // PHP - '.php', - '.phtml', - // Swift - '.swift', - // Ruby - '.rb', -]; - /** * Try to match a path (with extensions) against the known file set. * Returns the matched file path or null. @@ -61,8 +9,9 @@ export const EXTENSIONS = [ export function tryResolveWithExtensions( basePath: string, allFiles: ReadonlySet, + extensions: readonly string[], ): string | null { - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const candidate = basePath + ext; if (allFiles.has(candidate)) return candidate; } @@ -100,7 +49,7 @@ export interface SuffixIndex { * `dirSuffix` is matched as a SEGMENT-aligned directory suffix — every * returned file is a direct child of a directory `D` with * `D === dirSuffix || D.endsWith('/' + dirSuffix)`. Callers may rely on this - * and skip a direct-child re-check; `import-resolvers/csharp.ts` step 2 does + * and skip a direct-child re-check; `languages/csharp/import-helpers.ts` step 2 does * exactly that. It bounds what may be RETURNED, not what must be found: an * implementation is free to answer with fewer files, and the root-anchored * index in `languages/php/import-target.ts` answers only the `D === dirSuffix` @@ -128,14 +77,11 @@ export interface SuffixIndexOptions { * for every `i` — i.e. the "normalized" list is a LOWERCASED file list, not * merely a slash-normalized one. * - * `import-resolvers/pass-cache.ts` is the one caller that can make it: it - * builds `normalizedFileList` as `allFileList.map((f) => f.toLowerCase())`. * Every suffix of an all-lowercase path is itself lowercase, so * `suffix.toLowerCase() === suffix` and the case-folded map came out a * byte-identical copy of the exact one — same keys, same values, same * insertion order. Measured 14.00 MiB at 32 000 paths, 29.8% of the retained - * `ImportPassCache` — and one `ImportPassCache` is built per ts-family - * adapter per pass, so the waste was carried once for each of them. + * former ts-family cache. A caller supplying such a list can skip the copy. * * With this set, `getInsensitive` reads the exact map directly instead. It is * the same map the derivation below would have produced, so this is a skipped @@ -280,9 +226,8 @@ export function buildSuffixIndex( * churn. Measured on the 32k-path arms of `bench/import-target/`, it is * ~15% of the retained C# index and ~19% of the retained Ruby one. * - * Only `getFilesInDir` reads it, and only four call sites reach that: - * `import-resolvers/{php,csharp,jvm}.ts` and `import-resolvers/configs/ - * python.ts`. Every other consumer of this index — `workspace-file-index.ts` + * Only `getFilesInDir` reads it, through `languages/{php,csharp}/import-helpers.ts`. + * Every other consumer of this index — `workspace-file-index.ts` * serving Ruby, `languages/typescript/scope-resolver.ts`, * `languages/vue/import-target.ts`, `group/extractors/include-extractor.ts` * — asks only suffix questions and was paying the whole footprint for a map @@ -369,12 +314,9 @@ export function buildSuffixIndex( // imports is the whole pass — which is why the interface makes the result // `readonly` and the compiler refuses the mutation at the call site. // - // Sharing beats copying because no caller keeps the array: two only measure - // it and two build a fresh array from it, so a defensive copy would - // allocate a whole bucket per import on the path this index exists to keep - // flat. `package-dir-index.ts` reached the same conclusion the same way — - // read-only containers, plus one copy where a bucket genuinely LEAVES - // (`sortedRootFiles`), which is the case `configs/swift.ts` is in. + // Neither caller mutates the bucket: one checks its length, the other + // filters into a fresh result. A defensive copy would allocate a bucket + // per import without protecting any mutation boundary. getFilesInDir: (dirSuffix: string, extension: string) => { return getDirMap().get(`${dirSuffix}:${extension}`) || []; }, @@ -388,12 +330,13 @@ export function suffixResolve( pathParts: string[], normalizedFileList: readonly string[], allFileList: readonly string[], + extensions: readonly string[], index?: SuffixIndex, ): string | null { if (index) { for (let i = 0; i < pathParts.length; i++) { const suffix = pathParts.slice(i).join('/'); - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const suffixWithExt = suffix + ext; const result = index.get(suffixWithExt) || index.getInsensitive(suffixWithExt); if (result) return result; @@ -405,7 +348,7 @@ export function suffixResolve( // Fallback: linear scan (for backward compatibility) for (let i = 0; i < pathParts.length; i++) { const suffix = pathParts.slice(i).join('/'); - for (const ext of EXTENSIONS) { + for (const ext of extensions) { const suffixWithExt = suffix + ext; const suffixPattern = '/' + suffixWithExt; const matchIdx = normalizedFileList.findIndex( diff --git a/gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts b/gitnexus/src/core/ingestion/utils/workspace-file-index.ts similarity index 96% rename from gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts rename to gitnexus/src/core/ingestion/utils/workspace-file-index.ts index ad5c882eca..d050a9310f 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/workspace-file-index.ts +++ b/gitnexus/src/core/ingestion/utils/workspace-file-index.ts @@ -39,7 +39,7 @@ */ import { perFileSet } from './per-file-set.js'; -import { buildSuffixIndex, type SuffixIndex } from './utils.js'; +import { buildSuffixIndex, type SuffixIndex } from './suffix-index.js'; /** * `normalized` and `all` are `readonly string[]`, and — like @@ -49,10 +49,9 @@ import { buildSuffixIndex, type SuffixIndex } from './utils.js'; * pass, and these two are the largest shared arrays here (one element per file, * read by C#, Java, PHP and Ruby). `readonly` on the field is what makes the * compiler refuse the mutation at the call site instead of leaving it to a - * comment. `ImportPassCache` (`pass-cache.ts`) states the same contract the - * same way for the ts-family lists. + * comment. * - * The positional pairing is load-bearing too and depends on it: `csharp.ts` + * The positional pairing is load-bearing too and depends on it: the C# import helper * caches POSITIONS into `normalized` and reads the answer out of `all`, so a * reordering of either array alone silently re-points every cached position. */ diff --git a/gitnexus/src/core/ingestion/workers/parse-worker.ts b/gitnexus/src/core/ingestion/workers/parse-worker.ts index cb670da267..61b7449e15 100644 --- a/gitnexus/src/core/ingestion/workers/parse-worker.ts +++ b/gitnexus/src/core/ingestion/workers/parse-worker.ts @@ -678,7 +678,7 @@ const clearCaches = (): void => { // Keyed by class node startIndex (unique per AST node within a file). // ============================================================================ -const fieldInfoCache = new Map>(); +const fieldInfoCache = new Map>(); /** * Walk up from a definition node to find the nearest enclosing class/struct/interface @@ -811,14 +811,14 @@ const NOOP_SYMBOL_TABLE: SymbolTableReader = { /** * Get (or extract and cache) field info for a class node. - * Returns a name→FieldInfo map, or undefined if the provider has no field extractor + * Returns a name→declarations map, or undefined if the provider has no field extractor * or the class yielded no fields. */ function getFieldInfo( classNode: SyntaxNode, provider: LanguageProvider, context: FieldExtractorContext, -): Map | undefined { +): Map | undefined { if (!provider.fieldExtractor) return undefined; const cacheKey = classNode.startIndex; @@ -828,14 +828,52 @@ function getFieldInfo( const result = provider.fieldExtractor.extract(classNode, context); if (!result?.fields?.length) return undefined; - cached = new Map(); + cached = new Map(); for (const field of result.fields) { - cached.set(field.name, field); + const declarations = cached.get(field.name); + if (declarations !== undefined) declarations.push(field); + else cached.set(field.name, [field]); + } + for (const declarations of cached.values()) { + if (declarations.length > 1) { + declarations.sort((a, b) => a.line - b.line || (a.column ?? -1) - (b.column ?? -1)); + } } fieldInfoCache.set(cacheKey, cached); return cached; } +function fieldInfoLowerBound( + declarations: readonly FieldInfo[], + line: number, + column: number, +): number { + let lo = 0; + let hi = declarations.length; + while (lo < hi) { + const mid = Math.floor((lo + hi) / 2); + const field = declarations[mid]!; + if (field.line < line || (field.line === line && (field.column ?? -1) < column)) lo = mid + 1; + else hi = mid; + } + return lo; +} + +function selectFieldInfo( + declarations: readonly FieldInfo[] | undefined, + line: number, + column?: number, +): FieldInfo | undefined { + if (declarations === undefined || declarations.length === 0) return undefined; + if (declarations.length === 1) return declarations[0]; + const start = fieldInfoLowerBound(declarations, line, -1); + const end = fieldInfoLowerBound(declarations, line + 1, -1); + if (end - start === 1) return declarations[start]; + if (column === undefined) return undefined; + const index = fieldInfoLowerBound(declarations, line, column); + return index < end && declarations[index]?.column === column ? declarations[index] : undefined; +} + // ============================================================================ // MethodExtractor cache — extract method metadata once per class, reuse for each method. // Keyed by class node startIndex (unique per AST node within a file). @@ -2114,7 +2152,7 @@ const processFileGroup = ( const propEnclosingClassId = propEnclosingInfo?.qualifiedClassId ?? propEnclosingInfo?.classId ?? null; // Enrich routed properties with FieldExtractor metadata - let routedFieldMap: Map | undefined; + let routedFieldMap: Map | undefined; if (provider.fieldExtractor && typeEnv) { const classNode = findEnclosingClassNode(captureMap['call']); if (classNode) { @@ -2127,7 +2165,11 @@ const processFileGroup = ( } } for (const item of routed.items) { - const routedFieldInfo = routedFieldMap?.get(item.propName); + const routedFieldInfo = selectFieldInfo( + routedFieldMap?.get(item.propName), + captureMap['call'].startPosition.row + 1, + captureMap['call'].startPosition.column, + ); const propQualifiedName = propEnclosingInfo ? `${propEnclosingInfo.className}.${item.propName}` : item.propName; @@ -2971,7 +3013,11 @@ const processFileGroup = ( filePath: file.path, language, }); - const info = fieldMap?.get(nodeName); + const info = selectFieldInfo( + fieldMap?.get(nodeName), + definitionNode.startPosition.row + 1, + definitionNode.startPosition.column, + ); if (info) { declaredType = info.type ?? undefined; // Mutate methodProps BEFORE the `{...methodProps}` spread below — @@ -2979,6 +3025,9 @@ const processFileGroup = ( if (info.rawDeclaredType !== undefined) { methodProps.rawDeclaredType = info.rawDeclaredType; } + if (info.initializerType !== undefined) { + methodProps.initializerType = info.initializerType; + } // Field annotations ('@Name' strings, U2 PR #2200) — omit when empty. if (info.annotations !== undefined && info.annotations.length > 0) { methodProps.annotations = info.annotations; diff --git a/gitnexus/src/core/run-analyze.ts b/gitnexus/src/core/run-analyze.ts index f1e0b9f017..7cec865c21 100644 --- a/gitnexus/src/core/run-analyze.ts +++ b/gitnexus/src/core/run-analyze.ts @@ -44,7 +44,7 @@ import { sweepStagingArtifacts, } from '../storage/index-lock.js'; import { resolveEmbeddingRecovery } from '../storage/embedding-recovery.js'; -import { invalidateNodeWorkspacePackages } from './ingestion/import-resolvers/node-workspace-packages.js'; +import { invalidateNodeWorkspacePackages } from './ingestion/languages/typescript/workspace-packages.js'; import { logNameFallbackSummary, summarizeNameFallback, diff --git a/gitnexus/src/mcp/local/local-backend.ts b/gitnexus/src/mcp/local/local-backend.ts index 3b79cbbe58..b242d807d5 100644 --- a/gitnexus/src/mcp/local/local-backend.ts +++ b/gitnexus/src/mcp/local/local-backend.ts @@ -162,7 +162,6 @@ import { foldNumericToolArgumentAliases } from '../tool-arguments.js'; import { findImportCycles, IMPORT_CYCLE_LIMIT } from '../../core/graph/import-cycles.js'; import { decodeTaintPath } from '../../core/ingestion/taint/path-codec.js'; import { decodeReachingDefReason } from '../../core/ingestion/cfg/reaching-def-reason-codec.js'; -import { EXTENSIONS } from '../../core/ingestion/import-resolvers/utils.js'; import { compareCodeUnits } from '../../lib/utils.js'; import { lookupExternalCallCount, @@ -301,21 +300,14 @@ function ambiguityReport( }; } -/** Real source-file extensions (`.ts`, `.py`, …) from the resolver's list, - * excluding the empty entry and the `/index.*` forms — used to decide whether - * an `explain` target is a file path vs a (possibly dotted) symbol name. */ -const SOURCE_FILE_EXTENSIONS: readonly string[] = EXTENSIONS.filter( - (e) => e.startsWith('.') && !e.includes('/'), -); /** Recognize indexed source files and existing import suffixes; a bare dotted * symbol (`UserController.create`) remains a symbol target. */ -function looksLikeFilePath(target: string): boolean { - if (/[\\/]/.test(target)) return true; +async function looksLikeFilePath(target: string): Promise { + if (/[\\/]/.test(target) || getLanguageFromFilename(target) !== null) return true; + // Keep analyze-only language modules out of the MCP startup closure (#2802). + const { EXTENSIONS } = await import('../../core/ingestion/languages/import-candidates.js'); const lower = target.toLowerCase(); - return ( - getLanguageFromFilename(target) !== null || - SOURCE_FILE_EXTENSIONS.some((ext) => lower.endsWith(ext)) - ); + return EXTENSIONS.some((ext) => ext.startsWith('.') && !ext.includes('/') && lower.endsWith(ext)); } /** @@ -5911,7 +5903,7 @@ export class LocalBackend { anchor: { file: string; symbol?: string; startLine?: number; endLine?: number }; early?: Record; }> { - if (looksLikeFilePath(target)) { + if (await looksLikeFilePath(target)) { return { anchorClause: '(a.id STARTS WITH $idPrefix OR a.filePath = $targetPath OR a.filePath ENDS WITH $targetSuffix)', diff --git a/gitnexus/test/fixtures/cpp-qualified-receiver-boundaries.cpp b/gitnexus/test/fixtures/cpp-qualified-receiver-boundaries.cpp new file mode 100644 index 0000000000..b0b1032893 --- /dev/null +++ b/gitnexus/test/fixtures/cpp-qualified-receiver-boundaries.cpp @@ -0,0 +1,29 @@ +namespace impl { struct AliasC { int m(); }; } +namespace alias = impl; +struct Holder { alias::AliasC c; int alias_field() { return c.m(); } }; +int alias_brace() { auto c = alias::AliasC{}; return c.m(); } +struct A { int m(); }; +struct B { int m(); }; +struct Factory { A make(); }; +B make(); +int prototype_collision() { Factory factory; return factory.make().m(); } +namespace one { A overloaded(); } +namespace two { B overloaded(int); } +using namespace one; +using namespace two; +int using_overload() { return overloaded(1).m(); } +namespace rp { A produce(); } +template struct Client { + int dependent_bound() { auto x = rp::produce(); return x.m(); } + int dependent_inline() { return rp::produce().m(); } +}; +namespace outer { namespace nested { A produce(); } } +template struct DeepClient { + int dependent_outer() { return outer::nested::produce().m(); } +}; +int qualified_positive() { return rp::produce().m(); } + +struct AliasShadow { + struct alias { struct AliasC { int m(); }; }; + int alias_shadowed() { auto value = alias::AliasC{}; return value.m(); } +}; diff --git a/gitnexus/test/fixtures/csharp-captures-golden/expected-captures.json b/gitnexus/test/fixtures/csharp-captures-golden/expected-captures.json index 02d621116d..e7723c4967 100644 --- a/gitnexus/test/fixtures/csharp-captures-golden/expected-captures.json +++ b/gitnexus/test/fixtures/csharp-captures-golden/expected-captures.json @@ -191,6 +191,38 @@ "captureGroups": 25, "digest": "28246dd1c88ecfe07fcee84ba314dbd9e39ccd0c30f20b8fb4633ec71e48e375" }, + "csharp-global-namespace-precedence/Audit/Checker.cs": { + "captureGroups": 12, + "digest": "3d2b6d491fe36886ee16d556d17f725aa7e3abe4c3a060921b95651b3bc789f3" + }, + "csharp-global-namespace-precedence/Audit/Recorder.cs": { + "captureGroups": 12, + "digest": "807da0ef85a563fccf5a350d922c632ba82005bf4596af44784b2a3342904b1b" + }, + "csharp-global-namespace-precedence/Billing/Reports/Summary.cs": { + "captureGroups": 11, + "digest": "c0bb69ad176fdf9c98614e30caf5c5bbd0f19fc177c3599867df6d23ec42bf54" + }, + "csharp-global-namespace-precedence/Billing/Service.cs": { + "captureGroups": 16, + "digest": "67c79d86f33ef9e01aaafeed049dceb50797e1e69ba9280412f10682262a219b" + }, + "csharp-global-namespace-precedence/Billing/Voucher.cs": { + "captureGroups": 20, + "digest": "31c8376a7c60a5303dcc45a67258a25ce16434d93aeaa9de7a7fb6e21915d8d3" + }, + "csharp-global-namespace-precedence/Global/Voucher.cs": { + "captureGroups": 6, + "digest": "936e83dab4b1ed046d7ac5ae868c42672b55a92e475af7a7eff93b9645b946d9" + }, + "csharp-global-namespace-precedence/Program.cs": { + "captureGroups": 8, + "digest": "e7f5a4aed98f0dc1ac2ded7f90dd772dd8f3f33f3f54ffa4df1106585b4d03ad" + }, + "csharp-global-namespace-precedence/Tools/Importer.cs": { + "captureGroups": 10, + "digest": "59a1dc4ccdb9f278140bfce172460c55335c6e6810253a2570259f71a7c36dae" + }, "csharp-grandparent-resolution/Models/A.cs": { "captureGroups": 10, "digest": "159a52b959e021b1a34cc0dfbf1ba1a0748a0f29c84634948e2e85afc75db003" diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/a.h b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/a.h new file mode 100644 index 0000000000..b34d04249d --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/a.h @@ -0,0 +1,10 @@ +#ifndef QRT_A_H +#define QRT_A_H + +namespace a { +struct Config { + int m() { return 6; } +}; +} // namespace a + +#endif diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/callers.cpp b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/callers.cpp new file mode 100644 index 0000000000..a0ab2f8524 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/callers.cpp @@ -0,0 +1,58 @@ +#include "mod.h" +#include "other.h" +#include "a.h" + +// Qualified type spellings: `rp::C` must reach rp::C, never the global C that +// is visible here through other.h. +int declared_init() { rp::C x = rp::make(); return x.m(); } +int param_ns(rp::C x) { return x.m(); } +int param_ns_ptr(rp::C* x) { return x->m(); } +int param_template(rp::Box b) { return b.m(); } +int bare_global() { C x; return x.m(); } + +// Qualified declarations with no initializer. +int declared_ns() { rp::C x; return x.m(); } +int declared_ns_ptr() { rp::C* x = nullptr; return x->m(); } + +// Qualified brace-init and member field. +int brace_ns() { auto x = rp::C{}; return x.m(); } + +namespace b { +struct Config { + int m() { return 7; } +}; +int param_qualified(a::Config x) { return x.m(); } +int param_local(Config x) { return x.m(); } +int brace_qualified() { auto x = a::Config{}; return x.m(); } +struct Holder { + a::Config cfg; + int field_qualified() { return cfg.m(); } +}; +} // namespace b + +// Factories declared only by header prototypes (definitions live in mod.cpp, +// which nothing includes). +int auto_plain() { auto x = makeD(); return x.m(); } +int inline_plain() { return makeD().m(); } +int auto_ptr() { auto p = makeDp(); return p->m(); } +int global_factory() { auto y = make(); return y.m(); } + +// A block-scope `E y();` declares a local function; it must not leak a +// file-level `y => E` binding to other functions. +int vexing() { E y(); return 0; } +int uses_vexing_name() { return y.m(); } + +// Qualified factory callee. +int auto_ns() { auto x = rp::make(); return x.m(); } +int inline_ns() { return rp::make().m(); } +int ctor_ns() { auto x = rp::C(); return x.m(); } + +// An unknown qualified factory types nothing, and must not let the inner `x` +// fall through to the outer `D x`. +int shadowed_auto() { + D x; + { + auto x = rp::unknown(); + return x.m(); + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.cpp b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.cpp new file mode 100644 index 0000000000..761d7ba995 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.cpp @@ -0,0 +1,8 @@ +#include "mod.h" + +namespace rp { +C make() { return C(); } +} // namespace rp + +D makeD() { return D(); } +D* makeDp() { return nullptr; } diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.h b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.h new file mode 100644 index 0000000000..ef0ca79654 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/mod.h @@ -0,0 +1,34 @@ +#ifndef QRT_MOD_H +#define QRT_MOD_H + +namespace rp { +struct C { + int m() { return 1; } +}; +template +struct Box { + int m() { return 4; } +}; +C make(); +// Shares its tail with the global Widget below, in the same header. +struct Widget { + int m() { return 6; } +}; +Widget makeWidget(); +} // namespace rp + +struct Widget { + int n() { return 7; } +}; + +struct D { + int m() { return 3; } +}; +struct E { + int m() { return 5; } +}; + +D makeD(); +D* makeDp(); + +#endif diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/other.h b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/other.h new file mode 100644 index 0000000000..354a6aa965 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/other.h @@ -0,0 +1,9 @@ +#ifndef QRT_OTHER_H +#define QRT_OTHER_H + +struct C { + int m() { return 2; } +}; +C make(); + +#endif diff --git a/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/using.cpp b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/using.cpp new file mode 100644 index 0000000000..ec4019c4d2 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/cpp-qualified-receiver-typing/using.cpp @@ -0,0 +1,14 @@ +#include "mod.h" + +// `make` is reached through the using-directive; its return type is the +// namespace prototype's `C`, which must mean rp::C even though a global C +// exists elsewhere in the workspace. +int using_auto() { using namespace rp; auto x = make(); return x.m(); } +// The same call as an INLINE receiver: typed from the callee's definition, as +// the bound form above is, not from a return binding found by name. +int using_inline() { using namespace rp; return make().m(); } + +// The prototype's `Widget` is rp::Widget, not the global Widget declared in the +// same header. +int using_same_file() { using namespace rp; auto x = makeWidget(); return x.m(); } +int using_inline_same_file() { using namespace rp; return makeWidget().m(); } diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Checker.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Checker.cs new file mode 100644 index 0000000000..96bf7bb688 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Checker.cs @@ -0,0 +1,14 @@ +namespace Audit +{ + using Billing; + + public class Checker + { + public void Check(Voucher voucher) + { + // A using directive inside a namespace declaration is consulted at + // that namespace's level, before the global namespace. + voucher.Post(); + } + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Recorder.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Recorder.cs new file mode 100644 index 0000000000..e7c256fade --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Audit/Recorder.cs @@ -0,0 +1,12 @@ +namespace Audit.Trail; + +using Billing; + +public class Recorder +{ + public void Record(Voucher voucher) + { + // A using after a file-scoped namespace belongs to that namespace. + voucher.Post(); + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Reports/Summary.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Reports/Summary.cs new file mode 100644 index 0000000000..d8234a8138 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Reports/Summary.cs @@ -0,0 +1,11 @@ +namespace Billing.Reports +{ + public class Summary + { + public void Print(Voucher voucher) + { + // Enclosing namespace: Billing is searched before the global namespace. + voucher.Post(); + } + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Service.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Service.cs new file mode 100644 index 0000000000..6b25cd2c32 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Service.cs @@ -0,0 +1,16 @@ +namespace Billing; + +public class Service +{ + public static void Settle(Voucher voucher) + { + // Same namespace: Billing.Voucher hides the global Voucher. + voucher.Post(); + voucher.Payee.Notify(); + } + + public static Voucher Open() + { + return new Voucher(); + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Voucher.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Voucher.cs new file mode 100644 index 0000000000..cd8f3c0471 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Billing/Voucher.cs @@ -0,0 +1,22 @@ +namespace Billing; + +public class Voucher +{ + public Payee Payee { get; set; } = new Payee(); + + public void Post() + { + } + + public static Voucher Create() + { + return new Voucher(); + } +} + +public class Payee +{ + public void Notify() + { + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Global/Voucher.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Global/Voucher.cs new file mode 100644 index 0000000000..f720c63bd3 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Global/Voucher.cs @@ -0,0 +1,8 @@ +// Global (unnamed) namespace. An unrelated type that shares its simple name +// with `Billing.Voucher`. +public class Voucher +{ + public void Post() + { + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Program.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Program.cs new file mode 100644 index 0000000000..30bb405684 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Program.cs @@ -0,0 +1,8 @@ +public class Program +{ + public static void Main(Voucher voucher) + { + // Outside any namespace: the global Voucher. + voucher.Post(); + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Tools/Importer.cs b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Tools/Importer.cs new file mode 100644 index 0000000000..0188c22682 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/csharp-global-namespace-precedence/Tools/Importer.cs @@ -0,0 +1,11 @@ +using Billing; + +public class Importer +{ + public void Import(Voucher voucher) + { + // The global namespace's own types are searched before the + // compilation unit's using directives, so this is the global Voucher. + voucher.Post(); + } +} diff --git a/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/Cargo.toml b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/Cargo.toml new file mode 100644 index 0000000000..4d0c1980b1 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "rust-qualified-factory-return" +version = "0.1.0" +edition = "2021" diff --git a/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/main.rs b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/main.rs new file mode 100644 index 0000000000..37efd9ac49 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/main.rs @@ -0,0 +1,51 @@ +mod modx; +mod shadow; + +use crate::modx as rp; +use crate::modx::Other; + +// Module-factory bindings below are `C`; type-qualified and untyped cases are controls. +fn alias_call() -> i32 { + let x = rp::make(); + x.m() +} + +fn module_call() -> i32 { + let x = modx::make(); + x.m() +} + +fn crate_call() -> i32 { + let x = crate::modx::make(); + x.m() +} + +fn inline_alias() -> i32 { + rp::make().m() +} + +fn inline_module() -> i32 { + modx::make().m() +} + +fn inline_crate() -> i32 { + crate::modx::make().m() +} + +// A type-qualified call keeps naming the type: `Other::make()` is `Other`'s +// associated function, not the module-level `make`. +fn type_qualified() -> i32 { + let x = Other::make(); + x.m() +} + +fn untyped_alias() -> i32 { + let x = rp::untyped(); + x.m() +} + +fn untyped_inline() -> i32 { + modx::untyped().m() +} + +fn main() {} diff --git a/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/modx.rs b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/modx.rs new file mode 100644 index 0000000000..0f7c9faa60 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/modx.rs @@ -0,0 +1,27 @@ +pub struct C; + +impl C { + pub fn m(&self) -> i32 { + 1 + } +} + +pub struct Other; + +impl Other { + // Shares its name with the module-level `make` below, but returns `Other`. + pub fn make() -> Other { + Other + } + + pub fn m(&self) -> i32 { + 2 + } +} + +pub fn make() -> C { + C +} + +// No return annotation: nothing in the program says what a call returns. +pub fn untyped() {} diff --git a/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/shadow.rs b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/shadow.rs new file mode 100644 index 0000000000..b9a9eaa362 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/rust-qualified-factory-return/src/shadow.rs @@ -0,0 +1,11 @@ +use crate::modx; +use crate::modx::Other; + +// A path's leading segment names a module in the type namespace, so a `let` +// value named `modx` does not shadow it: `x` is still a `C`, while +// `modx.m()` dispatches on the local `Other`. +pub fn local_shadow() -> i32 { + let modx = Other; + let x = modx::make(); + x.m() + modx.m() +} diff --git a/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig b/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig index 007132c1ea..f55bc8106a 100644 --- a/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig +++ b/gitnexus/test/fixtures/lang-resolution/zig-filestruct/src/aliases.zig @@ -68,6 +68,15 @@ fn b11(orig: *Local) void { var cur = orig; cur.go(); } +// b12 — a FORWARDING type constructor imported by name. `generic.Bridge(T)` +// is `return Builder(T);`, so `Bridge(Local)` is `Builder(Local)` — a type +// only generic.zig can name. +const Bridge = generic.Bridge; +fn b12() void { + const bound = Bridge(Local); + bound.accessor("bound"); + Bridge(Local).prototypeChain(); +} // b9 — Lightpanda's `JsApi` shape: a container-level alias of a forwarding // type constructor, used by every member declaration of the container. diff --git a/gitnexus/test/fixtures/rust-captures-golden/expected-captures.json b/gitnexus/test/fixtures/rust-captures-golden/expected-captures.json index c4a0506f0a..2154bd4b85 100644 --- a/gitnexus/test/fixtures/rust-captures-golden/expected-captures.json +++ b/gitnexus/test/fixtures/rust-captures-golden/expected-captures.json @@ -651,6 +651,18 @@ "captureGroups": 13, "digest": "84d0e3980d4f725f8e0831b753a2570ddace613ebf6847ee1a5e86b9fcd4148b" }, + "rust-qualified-factory-return/src/main.rs": { + "captureGroups": 83, + "digest": "9983071279163d36e0a14bbf913db27942d6e4a634b44b24c5943b4f3fea26b5" + }, + "rust-qualified-factory-return/src/modx.rs": { + "captureGroups": 31, + "digest": "f83d9262f14ed04035419b9ff1a1f4fb6e7189b528474ab9d72a0ebcf09e5845" + }, + "rust-qualified-factory-return/src/shadow.rs": { + "captureGroups": 17, + "digest": "60d8b27fe58f6e18f736a1d66c2a092fe48aaeab1dfdbc689fdb5bb555fb95cc" + }, "rust-qualified-trait/src/main.rs": { "captureGroups": 8, "digest": "8c71cad628449f8c770fffe66f0aa1c33fc84c82de86fdb770887e00a937adcd" diff --git a/gitnexus/test/integration/commonjs-extraction-parity.test.ts b/gitnexus/test/integration/commonjs-extraction-parity.test.ts new file mode 100644 index 0000000000..90bea66dee --- /dev/null +++ b/gitnexus/test/integration/commonjs-extraction-parity.test.ts @@ -0,0 +1,92 @@ +import { beforeAll, describe, expect, it } from 'vitest'; +import type { ParsedFile } from 'gitnexus-shared'; +import { createKnowledgeGraph } from '../../src/core/graph/graph.js'; +import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.js'; +import { javascriptScopeResolver } from '../../src/core/ingestion/languages/javascript/scope-resolver.js'; +import { typescriptScopeResolver } from '../../src/core/ingestion/languages/typescript/scope-resolver.js'; +import { isCommonJsExportAssignment } from '../../src/core/ingestion/languages/typescript/cjs-export-receiver.js'; +import { runScopeResolution } from '../../src/core/ingestion/scope-resolution/pipeline/run.js'; +import { createWorkerPool } from '../../src/core/ingestion/workers/worker-pool.js'; +import type { ParseWorkerResult } from '../../src/core/ingestion/workers/parse-worker.js'; + +const cases = [ + { + path: 'common.js', + content: 'module.exports.value = 1;', + resolver: javascriptScopeResolver, + expected: true, + }, + { + path: 'esm.js', + content: 'export {}; module.exports.value = 1;', + resolver: javascriptScopeResolver, + expected: false, + }, + { + path: 'common.ts', + content: 'module.exports.value = 1;', + resolver: typescriptScopeResolver, + expected: true, + }, + { + path: 'esm.ts', + content: 'export {}; module.exports.value = 1;', + resolver: typescriptScopeResolver, + expected: false, + }, +]; + +describe('CommonJS metadata across extraction paths', () => { + let fromWorkers: Map; + + beforeAll(async () => { + const pool = createWorkerPool( + new URL('../../dist/core/ingestion/workers/parse-worker.js', import.meta.url), + 1, + ); + try { + const results = await pool.dispatch<{ path: string; content: string }, ParseWorkerResult>( + cases.map(({ path, content }) => ({ path, content })), + ); + const parsed = results.flatMap((result) => result.parsedFiles); + expect(parsed).toHaveLength(cases.length); + fromWorkers = new Map(parsed.map((file) => [file.filePath, file])); + } finally { + await pool.terminate(); + } + }, 120000); + + it.each(cases)( + '$path agrees for uncached main-thread and worker extraction', + ({ path, content, resolver, expected }) => { + for (const mode of ['uncached', 'worker'] as const) { + let observed = false; + let channel: unknown; + let exportAssignment: boolean | undefined; + runScopeResolution( + { + graph: createKnowledgeGraph(), + model: createSemanticModel(), + files: [{ path, content }], + ...(mode === 'worker' ? { preExtractedParsedFiles: fromWorkers } : {}), + onResolved: ({ parsedFiles, indexes }) => { + expect(parsedFiles).toHaveLength(1); + const parsed = parsedFiles[0]!; + channel = parsed.captureSideChannel; + const writes = parsed.referenceSites.filter( + (site) => site.kind === 'write' && site.name === 'value', + ); + expect(writes).toHaveLength(1); + exportAssignment = isCommonJsExportAssignment(writes[0]!, indexes, parsed); + observed = true; + }, + }, + resolver, + ); + expect(observed, mode).toBe(true); + expect(channel, mode).toBe(expected); + expect(exportAssignment, mode).toBe(expected); + } + }, + ); +}); diff --git a/gitnexus/test/integration/cpp-header-alias-order.test.ts b/gitnexus/test/integration/cpp-header-alias-order.test.ts new file mode 100644 index 0000000000..6c94c9fad7 --- /dev/null +++ b/gitnexus/test/integration/cpp-header-alias-order.test.ts @@ -0,0 +1,71 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ header alias activation and factory ownership', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-header-alias-order-')); + await fs.writeFile( + path.join(root, 'provider.h'), + 'namespace pkg { struct Cross { int m(); }; Cross make(); } namespace imported = pkg;', + ); + await fs.writeFile( + path.join(root, 'main.cpp'), + ` +struct Decoy { int m(); }; +void before_include() { imported::Cross x; x.m(); } +#include "provider.h" +void after_include() { imported::Cross x; x.m(); } +void bound_factory() { auto x = pkg::make(); x.m(); } +void inline_factory() { pkg::make().m(); } +void typed_value(int pkg) { pkg::Cross x; x.m(); } +void auto_value(auto pkg) { pkg::Cross x; x.m(); } +void alias_type() { using pkg = Decoy; pkg::Cross x; x.m(); } +void later_alias() { pkg::Cross x; using pkg = Decoy; x.m(); } +void later_alias_bound() { auto x = pkg::make(); using pkg = Decoy; x.m(); } +void later_alias_inline() { pkg::make().m(); using pkg = Decoy; } +void later_class_bound() { auto x = pkg::make(); struct pkg {}; x.m(); } +void later_class_inline() { pkg::make().m(); struct pkg {}; } +void prior_alias_bound() { using pkg = Decoy; auto x = pkg::make(); x.m(); } +void prior_alias_inline() { using pkg = Decoy; pkg::make().m(); } +template void dependent_type() { typename pkg::Cross x; x.m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + it.each([ + ['before_include', []], + ['after_include', ['Method:provider.h:Cross.m#0']], + ['bound_factory', ['Method:provider.h:Cross.m#0']], + ['inline_factory', ['Method:provider.h:Cross.m#0']], + ['typed_value', ['Method:provider.h:Cross.m#0']], + ['auto_value', ['Method:provider.h:Cross.m#0']], + ['alias_type', []], + ['later_alias', ['Method:provider.h:Cross.m#0']], + ['later_alias_bound', ['Method:provider.h:Cross.m#0']], + ['later_alias_inline', ['Method:provider.h:Cross.m#0']], + ['later_class_bound', ['Method:provider.h:Cross.m#0']], + ['later_class_inline', ['Method:provider.h:Cross.m#0']], + ['prior_alias_bound', []], + ['prior_alias_inline', []], + ['dependent_type', []], + ] as const)('%s uses only the visible producer', (caller, targets) => { + expect( + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId), + ).toEqual(targets); + }); +}); diff --git a/gitnexus/test/integration/cpp-namespace-order-boundaries.test.ts b/gitnexus/test/integration/cpp-namespace-order-boundaries.test.ts new file mode 100644 index 0000000000..18c6aa7502 --- /dev/null +++ b/gitnexus/test/integration/cpp-namespace-order-boundaries.test.ts @@ -0,0 +1,55 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ namespace spelling and header order', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-namespace-order-')); + const sources: Record = { + 'z_provider.h': 'namespace one { struct FirstProduct { int m(); }; } namespace first = one;', + 'a_consumer.h': + '#include "z_provider.h"\nnamespace second = first; struct FirstHolder { second::FirstProduct c; int first_use() { return c.m(); } };', + 'a_provider.h': + 'namespace two { struct SecondProduct { int m(); }; } namespace before = two;', + 'z_consumer.h': + '#include "a_provider.h"\nnamespace after = before; struct SecondHolder { after::SecondProduct c; int second_use() { return c.m(); } };', + 'main.cpp': ` +#include "a_consumer.h" +#include "z_consumer.h" +namespace outer { +namespace lib { inline namespace v1 { struct RelativeProduct { int m(); }; } } +struct Decoy { int m(); }; +void relative_brace() { auto x = lib::RelativeProduct{}; x.m(); } +struct RelativeHolder { lib::RelativeProduct field; void relative_field() { field.m(); } }; +} +`, + }; + for (const [name, source] of Object.entries(sources)) + await fs.writeFile(path.join(root, name), source); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + it.each([ + ['relative_brace', 'Method:main.cpp:RelativeProduct.m#0'], + ['relative_field', 'Method:main.cpp:RelativeProduct.m#0'], + ['first_use', 'Method:z_provider.h:FirstProduct.m#0'], + ['second_use', 'Method:a_provider.h:SecondProduct.m#0'], + ])('%s resolves its own namespace', (caller, target) => { + expect( + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId), + ).toEqual([target]); + }); +}); diff --git a/gitnexus/test/integration/cpp-qualified-alias-chain.test.ts b/gitnexus/test/integration/cpp-qualified-alias-chain.test.ts new file mode 100644 index 0000000000..057b90ecad --- /dev/null +++ b/gitnexus/test/integration/cpp-qualified-alias-chain.test.ts @@ -0,0 +1,55 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ chained namespace alias receiver types', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-alias-chain-')); + await fs.writeFile( + path.join(root, 'main.cpp'), + ` +namespace impl { struct C { int m(); }; } +namespace first = impl; +namespace second = first; +struct Decoy { int m(); }; +struct Holder { second::C c; int field_call() { return c.m(); } }; +int brace_call() { auto c = second::C{}; return c.m(); } +second::C make(); +namespace factory { second::C make(); } +int alias_return_inline() { return make().m(); } +int alias_return_bound() { auto c = make(); return c.m(); } +int qualified_alias_return_inline() { return factory::make().m(); } +int qualified_alias_return_bound() { auto c = factory::make(); return c.m(); } +int consumer_shadow() { using second = Decoy; return make().m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + it.each([ + 'field_call', + 'brace_call', + 'alias_return_inline', + 'alias_return_bound', + 'qualified_alias_return_inline', + 'qualified_alias_return_bound', + 'consumer_shadow', + ])('%s resolves the canonical alias target', (caller) => { + expect( + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId), + ).toEqual(['Method:main.cpp:C.m#0']); + }); +}); diff --git a/gitnexus/test/integration/cpp-qualified-callee-collisions.test.ts b/gitnexus/test/integration/cpp-qualified-callee-collisions.test.ts new file mode 100644 index 0000000000..108c00423b --- /dev/null +++ b/gitnexus/test/integration/cpp-qualified-callee-collisions.test.ts @@ -0,0 +1,71 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ qualified callee collisions', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-callee-collisions-')); + await fs.writeFile( + path.join(root, 'lib.h'), + ` +struct FreeProduct { void m(); }; +struct MemberProduct { void m(); }; +struct Factory { MemberProduct get() { return MemberProduct(); } }; +inline FreeProduct get() { return FreeProduct(); } +namespace real { struct AliasProduct { void m(); }; AliasProduct make(); } +namespace handle { struct WrongProduct { void m(); }; WrongProduct make(); } +`, + ); + await fs.writeFile( + path.join(root, 'main.cpp'), + ` +#include "lib.h" +void bound() { auto x = get(); x.m(); } +void inlined() { get().m(); } +namespace client { +namespace handle = real; +void alias_inline() { handle::make().m(); } +void alias_bound() { auto x = handle::make(); x.m(); } +} +void actual_namespace() { handle::make().m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + function owners(caller: string): string[] { + const edges = [...result.graph.iterRelationships()]; + return edges + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => { + const owner = edges.find( + (candidate) => candidate.type === 'HAS_METHOD' && candidate.targetId === edge.targetId, + ); + return String(owner && result.graph.getNode(owner.sourceId)?.properties.name); + }) + .sort(); + } + it.each(['bound', 'inlined'])('%s keeps the free function return type', (caller) => { + expect(owners(caller)).toEqual(['FreeProduct']); + }); + it.each(['alias_inline', 'alias_bound'])( + '%s cannot borrow a shadowed namespace factory', + (caller) => { + expect(owners(caller)).toEqual([]); + }, + ); + it('keeps a real namespace factory with the same spelling', () => { + expect(owners('actual_namespace')).toEqual(['WrongProduct']); + }); +}); diff --git a/gitnexus/test/integration/cpp-qualified-factory-review.test.ts b/gitnexus/test/integration/cpp-qualified-factory-review.test.ts new file mode 100644 index 0000000000..e59b036590 --- /dev/null +++ b/gitnexus/test/integration/cpp-qualified-factory-review.test.ts @@ -0,0 +1,99 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ qualified factory review boundaries', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-factory-review-')); + await fs.writeFile( + path.join(root, 'products.h'), + ` +namespace lib { inline namespace v1 { struct InlineProduct { int m(); }; } } +struct NoArg { int m(); }; +struct OneArg { int m(); }; +NoArg create(); +OneArg create(int); +namespace app { namespace json { struct ParsedDoc { void dump(); }; ParsedDoc parse(); } } +namespace outer { struct Factory { static NoArg make(); }; } +namespace Factory { OneArg make(); } +`, + ); + await fs.writeFile( + path.join(root, 'main.cpp'), + ` +#include "products.h" +void inline_brace() { auto x = lib::InlineProduct{}; x.m(); } +struct Holder { lib::InlineProduct field; void field_call() { field.m(); } }; +void overloaded_bound() { auto x = create(); x.m(); } +void overloaded_inline() { create().m(); } +void overloaded_argument_bound() { auto x = create(1); x.m(); } +void overloaded_argument_inline() { create(1).m(); } +void outer_mismatch_bound() { auto x = ext::json::parse(); x.dump(); } +void outer_mismatch_inline() { ext::json::parse().dump(); } +void outer_match_bound() { auto x = app::json::parse(); x.dump(); } +void outer_match_inline() { app::json::parse().dump(); } +namespace app { void relative_match() { json::parse().dump(); } } +void class_qualifier_collision() { outer::Factory::make().m(); } +void actual_factory_namespace() { Factory::make().m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + function targets(caller: string): string[] { + const edges = [...result.graph.iterRelationships()]; + return edges + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + ['m', 'dump'].includes(String(result.graph.getNode(edge.targetId)?.properties.name)), + ) + .map((edge) => { + const owner = edges.find( + (candidate) => candidate.type === 'HAS_METHOD' && candidate.targetId === edge.targetId, + ); + return String(owner && result.graph.getNode(owner.sourceId)?.properties.name); + }) + .sort(); + } + it.each(['inline_brace', 'field_call'])('%s sees through an inline namespace', (caller) => { + expect(targets(caller)).toEqual(['InlineProduct']); + }); + it.each([ + 'overloaded_bound', + 'overloaded_inline', + 'overloaded_argument_bound', + 'overloaded_argument_inline', + ])('%s leaves distinct prototype returns unresolved without overload selection', (caller) => { + // These calls are valid and distinguishable by arity in C++. Receiver + // typing currently lacks the selected overload's return identity. + expect(targets(caller)).toEqual([]); + }); + it.each(['outer_mismatch_bound', 'outer_mismatch_inline'])( + '%s cannot borrow a different outer namespace', + (caller) => { + expect(targets(caller)).toEqual([]); + }, + ); + it.each(['outer_match_bound', 'outer_match_inline', 'relative_match'])( + '%s keeps a factory in the written namespace', + (caller) => { + expect(targets(caller)).toEqual(['ParsedDoc']); + }, + ); + it('leaves an unsupported class-qualified factory unresolved without borrowing a namespace', () => { + // This is valid C++ and should eventually target NoArg::m. The current + // namespace factory hook cannot resolve a class owner. + expect(targets('class_qualifier_collision')).toEqual([]); + }); + it('keeps the real namespace that shares the class name', () => { + expect(targets('actual_factory_namespace')).toEqual(['OneArg']); + }); +}); diff --git a/gitnexus/test/integration/cpp-qualified-receiver-boundaries.test.ts b/gitnexus/test/integration/cpp-qualified-receiver-boundaries.test.ts new file mode 100644 index 0000000000..4c7b5b9d2b --- /dev/null +++ b/gitnexus/test/integration/cpp-qualified-receiver-boundaries.test.ts @@ -0,0 +1,61 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ qualified receiver boundaries', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-receiver-boundaries-')); + await fs.copyFile( + new URL('../fixtures/cpp-qualified-receiver-boundaries.cpp', import.meta.url), + path.join(root, 'main.cpp'), + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + function receiverOwners(caller: string, ids = false): string[] { + const edges = [...result.graph.iterRelationships()]; + return edges + .filter( + (e) => + e.type === 'CALLS' && + result.graph.getNode(e.sourceId)?.properties.name === caller && + result.graph.getNode(e.targetId)?.properties.name === 'm', + ) + .map((e) => { + const owner = edges.find((x) => x.type === 'HAS_METHOD' && x.targetId === e.targetId); + return ids + ? String(owner?.sourceId) + : String(owner && result.graph.getNode(owner.sourceId)?.properties.name); + }) + .sort(); + } + it.each(['alias_field', 'alias_brace'])('%s resolves the namespace alias', (caller) => { + expect(receiverOwners(caller)).toEqual(['AliasC']); + }); + it('keeps the method return separate from a same-name free prototype', () => { + expect(receiverOwners('prototype_collision')).toEqual(['A']); + }); + it('does not select a competing overload without call evidence', () => { + expect(receiverOwners('using_overload')).toEqual([]); + }); + it.each(['dependent_bound', 'dependent_inline', 'dependent_outer'])( + '%s does not borrow a namespace factory', + (caller) => { + expect(receiverOwners(caller)).toEqual([]); + }, + ); + it('alias_shadowed cannot borrow the namespace alias through a local class', () => { + const namespaceTarget = receiverOwners('alias_field', true); + expect(namespaceTarget).toHaveLength(1); + expect(receiverOwners('alias_shadowed', true)).not.toContain(namespaceTarget[0]); + }); + it('keeps the concrete namespace factory', () => { + expect(receiverOwners('qualified_positive')).toEqual(['A']); + }); +}); diff --git a/gitnexus/test/integration/cpp-qualified-template-review.test.ts b/gitnexus/test/integration/cpp-qualified-template-review.test.ts new file mode 100644 index 0000000000..ac96bfbbd5 --- /dev/null +++ b/gitnexus/test/integration/cpp-qualified-template-review.test.ts @@ -0,0 +1,84 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C++ lexical qualified factory boundaries', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'cpp-template-review-')); + await fs.writeFile( + path.join(root, 'original.h'), + ` +namespace original { struct C { int m(); }; } +namespace alias = original; +`, + ); + await fs.writeFile( + path.join(root, 'inner.h'), + ` +#include "original.h" +namespace inner { +namespace alias { struct C { int m(); }; } +int nearer(alias::C c) { return c.m(); } +} +`, + ); + await fs.writeFile( + path.join(root, 'main.cpp'), + ` +#include "inner.h" +namespace actual { struct Product { int m(); }; } +struct Wrong { int m(); }; +struct Factory { actual::Product make(); }; +struct AutoFactory { auto make() { return actual::Product{}; } }; +Wrong make(); +int qualified_method() { Factory f; return f.make().m(); } +int auto_method() { AutoFactory f; return f.make().m(); } +struct A { int m(); }; +struct B { int m(); }; +namespace rp { A produce(); } +struct Actual { static B produce(); }; +template int function_template() { return rp::produce().m(); } +template A* pointer_template() { rp::produce().m(); return nullptr; } +struct Owner { template int member_template() { return rp::produce().m(); } }; +int concrete() { return rp::produce().m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + function targets(caller: string): string[] { + return [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId) + .sort(); + } + it('lets a nearer namespace hide an outer alias', () => { + expect(targets('nearer')).toEqual(['Method:inner.h:C.m#0']); + }); + it('does not borrow a free prototype for a qualified method return', () => { + expect(targets('qualified_method')).toEqual(['Method:main.cpp:Product.m#0']); + }); + it.each(['function_template', 'member_template', 'pointer_template'])( + '%s retains dependent lookup', + (caller) => { + expect(targets(caller)).toEqual([]); + }, + ); + it('does not borrow a free return annotation for an undeduced auto method', () => { + expect(targets('auto_method')).toEqual([]); + }); + it('keeps the nondependent namespace factory', () => { + expect(targets('concrete')).toEqual(['Method:main.cpp:A.m#0']); + }); +}); diff --git a/gitnexus/test/integration/csharp-import-index-reuse.test.ts b/gitnexus/test/integration/csharp-import-index-reuse.test.ts index 8f4978260e..eeea90a4d8 100644 --- a/gitnexus/test/integration/csharp-import-index-reuse.test.ts +++ b/gitnexus/test/integration/csharp-import-index-reuse.test.ts @@ -3,7 +3,7 @@ * * The no-csproj `using` path reads TWO per-file-set indexes, each memoized on * the `allFilePaths` Set identity via its own WeakMap: the shared - * `getWorkspaceFileIndex` (`import-resolvers/workspace-file-index.ts`, used by + * `getWorkspaceFileIndex` (`utils/workspace-file-index.ts`, used by * both the csproj and no-csproj legs) and `getCsharpDirIndex` * (`languages/csharp/import-target.ts`, the namespace-directory index behind * `firstFileDirectlyInPkgDir`). A four-segment `using` used to cost up to eight diff --git a/gitnexus/test/integration/csharp-namespace-precedence-boundaries.test.ts b/gitnexus/test/integration/csharp-namespace-precedence-boundaries.test.ts new file mode 100644 index 0000000000..8edba6590b --- /dev/null +++ b/gitnexus/test/integration/csharp-namespace-precedence-boundaries.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('C# namespace lookup boundaries', () => { + it.each([ + { + name: 'an earlier dotted namespace cannot override a later namespace', + files: { + 'Mixed.cs': `namespace Billing.Reports { public class Empty {} } +namespace Audit { public class Checker { public void Check() { var v = new Voucher(); v.Post(); } } }`, + 'Billing.cs': 'namespace Billing; public class Voucher { public void Post() {} }', + 'Audit.cs': 'namespace Audit; public class Voucher { public void Post() {} }', + }, + caller: 'Check', + member: 'Post', + target: 'Audit.cs', + }, + { + name: 'a using inside one namespace cannot leak into a sibling namespace', + files: { + 'Mixed.cs': `namespace Tools { +using Lib; +public class Empty {} +} +namespace Consumer { public class Runner { public void Run() { var t = new Token(); t.Go(); } } }`, + 'Lib.cs': 'namespace Lib; public class Token { public void Go() {} }', + 'Global.cs': 'public class Token { public void Go() {} }', + }, + caller: 'Run', + member: 'Go', + target: 'Global.cs', + }, + { + name: 'a bare type name cannot select a generic type with a different arity', + files: { + 'Global.cs': 'public class ArityToken { public static void Apply() {} }', + 'Client.cs': `namespace Client { +public class ArityToken { public static void Apply() {} } +public class Runner { public void Run() { ArityToken.Apply(); } } +}`, + }, + caller: 'Run', + member: 'Apply', + target: 'Global.cs', + }, + { + name: 'a generic class keeps its own short name inside its body', + files: { + 'Global.cs': 'public class ArityToken { public static void Apply() {} }', + 'Client.cs': `namespace Client { +public class ArityToken { +public static void Apply() {} +public static void Run() { ArityToken.Apply(); } +} +}`, + }, + caller: 'Run', + member: 'Apply', + target: 'Client.cs', + }, + { + name: 'an incompatible generic type cannot hide an enclosing zero-arity type', + files: { + 'Billing.cs': + 'namespace Billing; public class ArityToken { public static void Apply() {} }', + 'Client.cs': `namespace Billing.Client { +public class ArityToken { public static void Apply() {} } +public class Runner { public void Run() { ArityToken.Apply(); } } +}`, + }, + caller: 'Run', + member: 'Apply', + target: 'Billing.cs', + }, + { + name: 'a same-name alias to a closed generic remains a class receiver', + files: { + 'Use.cs': + 'using Result = Lib.Result; public class Runner { public void Run() { Result.Apply(); } }', + 'Lib.cs': 'namespace Lib; public class Result { public static void Apply() {} }', + 'Global.cs': 'public class Result { public static void Apply() {} }', + }, + caller: 'Run', + member: 'Apply', + target: 'Lib.cs', + }, + { + name: 'a nested block namespace uses its qualified identity', + files: { + 'Use.cs': `namespace A { +namespace B { +public class Runner { public void Run() { var t = new Token(); t.Go(); } } +} +}`, + 'AB.cs': 'namespace A.B; public class Token { public void Go() {} }', + 'A.cs': 'namespace A; public class Token { public void Go() {} }', + 'B.cs': 'namespace B; public class Token { public void Go() {} }', + }, + caller: 'Run', + member: 'Go', + target: 'AB.cs', + }, + { + name: 'a trailing semicolon does not make a block namespace file-scoped', + files: { + 'Use.cs': `namespace Tools { +using Lib; +public class Empty {} +}; +public class Runner { public void Run() { var t = new Token(); t.Go(); } }`, + 'Lib.cs': 'namespace Lib; public class Token { public void Go() {} }', + 'Global.cs': 'public class Token { public void Go() {} }', + }, + caller: 'Run', + member: 'Go', + target: 'Global.cs', + }, + { + name: 'a file-scoped namespace may put its semicolon on the next line', + files: { + 'Use.cs': `namespace Actual +; +public class Runner { public void Run() { var t = new Token(); t.Go(); } }`, + 'Actual.cs': 'namespace Actual; public class Token { public void Go() {} }', + 'Global.cs': 'public class Token { public void Go() {} }', + }, + caller: 'Run', + member: 'Go', + target: 'Actual.cs', + }, + { + name: 'comment punctuation cannot classify a block namespace as file-scoped', + files: { + 'Use.cs': `namespace Tools /* ; */ +{ +using Lib; +public class Empty {} +}; +public class Runner { public void Run() { var t = new Token(); t.Go(); } }`, + 'Lib.cs': 'namespace Lib; public class Token { public void Go() {} }', + 'Global.cs': 'public class Token { public void Go() {} }', + }, + caller: 'Run', + member: 'Go', + target: 'Global.cs', + }, + ])( + '$name', + async ({ files, caller, member, target }) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'csharp-lookup-boundary-')); + try { + for (const [name, content] of Object.entries(files)) { + await fs.writeFile(path.join(root, name), content); + } + const result = await runPipelineFromRepo(root, () => {}, {}); + const targets = [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === member, + ) + .map((edge) => result.graph.getNode(edge.targetId)?.properties.filePath); + expect(targets).toEqual([target]); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, + 120000, + ); + + it('ranks the global type before a compilation-unit using in type references', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'csharp-type-reference-tier-')); + try { + await fs.writeFile( + path.join(root, 'ABilling.cs'), + 'namespace Billing; public class RefVoucher {}', + ); + await fs.writeFile(path.join(root, 'ZGlobal.cs'), 'public class RefVoucher {}'); + await fs.writeFile( + path.join(root, 'Use.cs'), + 'using Billing;\npublic class Box {}\npublic class Consumer { public Box field; }', + ); + const result = await runPipelineFromRepo(root, () => {}, {}); + const targets = [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'USES' && + result.graph.getNode(edge.sourceId)?.properties.filePath === 'Use.cs' && + result.graph.getNode(edge.targetId)?.properties.name === 'RefVoucher', + ) + .map((edge) => result.graph.getNode(edge.targetId)?.properties.filePath); + expect(targets).not.toEqual([]); + expect(new Set(targets)).toEqual(new Set(['ZGlobal.cs'])); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, 120000); +}); diff --git a/gitnexus/test/integration/field-info-worker-metadata.test.ts b/gitnexus/test/integration/field-info-worker-metadata.test.ts new file mode 100644 index 0000000000..79c86b7a53 --- /dev/null +++ b/gitnexus/test/integration/field-info-worker-metadata.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; +import { createWorkerPool } from '../../src/core/ingestion/workers/worker-pool.js'; +import type { ParseWorkerResult } from '../../src/core/ingestion/workers/parse-worker.js'; + +describe('field declaration metadata through the parse worker', () => { + it.each([ + ['static first', 'static p = new StaticTarget();\n p = new InstanceTarget();'], + ['instance first', 'p = new InstanceTarget();\n static p = new StaticTarget();'], + ['same line', 'static p = new StaticTarget(); p = new InstanceTarget();'], + ])( + 'keeps static and instance initializer metadata in separate worker records: %s', + async (_, fields) => { + const pool = createWorkerPool( + new URL('../../dist/core/ingestion/workers/parse-worker.js', import.meta.url), + 1, + ); + try { + const results = await pool.dispatch<{ path: string; content: string }, ParseWorkerResult>([ + { path: 'fields.ts', content: `class Holder {\n ${fields}\n}` }, + ]); + const properties = results + .flatMap((result) => result.nodes) + .filter((node) => node.label === 'Property'); + expect(properties).toHaveLength(2); + expect(properties.filter((node) => node.properties.isStatic === true)).toHaveLength(1); + expect( + properties.find((node) => node.properties.isStatic === true)?.properties.initializerType, + ).toBe('StaticTarget'); + expect( + properties.find((node) => node.properties.isStatic === false)?.properties.initializerType, + ).toBe('InstanceTarget'); + } finally { + await pool.terminate(); + } + }, + 120000, + ); + it('keeps readonly metadata when an accessor argument is on a later line', async () => { + const pool = createWorkerPool( + new URL('../../dist/core/ingestion/workers/parse-worker.js', import.meta.url), + 1, + ); + try { + const results = await pool.dispatch<{ path: string; content: string }, ParseWorkerResult>([ + { + path: 'reader.rb', + content: 'class Reader\n attr_reader(\n :foo\n )\n attr_reader :foo\nend\n', + }, + ]); + const properties = results + .flatMap((result) => result.nodes) + .filter((node) => node.label === 'Property'); + expect( + properties.map((node) => ({ + name: node.properties.name, + line: node.properties.startLine, + readonly: node.properties.isReadonly, + })), + ).toEqual([ + { name: 'foo', line: 2, readonly: true }, + { name: 'foo', line: 4, readonly: true }, + ]); + } finally { + await pool.terminate(); + } + }, 120000); +}); + +describe('Ruby accessor mutability on the logical property', () => { + it('combines readers and writers independently of declaration order', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ruby-accessor-mutability-')); + try { + await fs.writeFile( + path.join(root, 'accessors.rb'), + [ + 'class ReaderThenWriter', + ' attr_reader :foo', + ' attr_writer :foo', + 'end', + 'class WriterThenReader', + ' attr_writer :foo', + ' attr_reader :foo', + 'end', + 'class ReadersOnly', + ' attr_reader :foo', + ' attr_reader :foo', + 'end', + 'class MultiName', + ' attr_reader :foo, :bar', + ' attr_writer :bar', + 'end', + ].join('\n'), + ); + const result = await runPipelineFromRepo(root, () => {}, {}); + const properties = [...result.graph.iterNodes()].filter((node) => node.label === 'Property'); + const readonly = (owner: string, name = 'foo') => { + const property = properties.find( + (node) => node.id === `Property:accessors.rb:${owner}.${name}`, + ); + expect(property).toBeDefined(); + return property?.properties.isReadonly; + }; + expect(readonly('ReaderThenWriter')).toBe(false); + expect(readonly('WriterThenReader')).toBe(false); + expect(readonly('ReadersOnly')).toBe(true); + expect(readonly('MultiName')).toBe(true); + expect(readonly('MultiName', 'bar')).toBe(false); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, 120000); +}); diff --git a/gitnexus/test/integration/php-import-index-reuse.test.ts b/gitnexus/test/integration/php-import-index-reuse.test.ts index 439e2a0c31..3538628a32 100644 --- a/gitnexus/test/integration/php-import-index-reuse.test.ts +++ b/gitnexus/test/integration/php-import-index-reuse.test.ts @@ -7,7 +7,7 @@ * `index` of `undefined`, dropping it onto `suffixResolve`'s linear `findIndex` * — a pass over every file per path-part × per extension, 98 ms per import at * 20k files. They now read the shared `getWorkspaceFileIndex` - * (`import-resolvers/workspace-file-index.ts`), memoized on the `allFilePaths` + * (`utils/workspace-file-index.ts`), memoized on the `allFilePaths` * Set identity via a WeakMap, through a PHP-specific parity view that keeps the * three index-fed fast paths answering exactly what the scans answered (see the * `#2901` header in `import-target.ts` — passing the raw shared index straight diff --git a/gitnexus/test/integration/producer-return-disk-scope.test.ts b/gitnexus/test/integration/producer-return-disk-scope.test.ts new file mode 100644 index 0000000000..eb4d77c37d --- /dev/null +++ b/gitnexus/test/integration/producer-return-disk-scope.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; +import { TransitionalScopeTree } from '../../src/storage/scope-index-store.js'; + +describe('producer return facts after the disk scope seal', () => { + it.each([ + ['cold unannotated factory', 'def make():\n pass\n\ndef caller():\n make().m()\n'], + [ + 'annotated factory with a competing method', + 'class Product:\n def save(self): pass\nclass OtherProduct:\n def save(self): pass\ndef make() -> Product:\n return Product()\ndef caller():\n make().save()\n', + ], + ])( + '%s matches resident resolution', + async (name, source) => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'producer-return-repo-')); + const store = await fs.mkdtemp(path.join(os.tmpdir(), 'producer-return-store-')); + const previous = process.env.GITNEXUS_DISK_SCOPE_INDEX; + const seal = vi.spyOn(TransitionalScopeTree.prototype, 'seal'); + const outcomes: string[][] = []; + try { + await fs.writeFile(path.join(root, 'factory.py'), source); + for (const disk of [false, true]) { + process.env.GITNEXUS_DISK_SCOPE_INDEX = disk ? '1' : '0'; + seal.mockClear(); + const result = await runPipelineFromRepo(root, () => {}, { + parsedFileStorePath: path.join(store, disk ? 'disk' : 'resident'), + }); + expect(seal).toHaveBeenCalledTimes(disk ? 1 : 0); + const edges = [...result.graph.iterRelationships()]; + outcomes.push( + edges + .filter((edge) => ['CALLS', 'ACCESSES', 'IMPORTS'].includes(edge.type)) + .map((edge) => `${edge.type}:${edge.sourceId}->${edge.targetId}:${edge.reason ?? ''}`) + .sort(), + ); + if (name.startsWith('annotated')) { + const product = [...result.graph.iterNodes()].find( + (node) => node.label === 'Class' && node.properties.name === 'Product', + ); + const methods = new Set( + edges + .filter((edge) => edge.type === 'HAS_METHOD' && edge.sourceId === product?.id) + .map((edge) => edge.targetId), + ); + const targets = edges + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === 'caller' && + result.graph.getNode(edge.targetId)?.properties.name === 'save', + ) + .map((edge) => edge.targetId); + expect(targets).toHaveLength(1); + expect(methods.has(targets[0]!)).toBe(true); + } + } + expect(outcomes[1]).toEqual(outcomes[0]); + } finally { + seal.mockRestore(); + if (previous === undefined) delete process.env.GITNEXUS_DISK_SCOPE_INDEX; + else process.env.GITNEXUS_DISK_SCOPE_INDEX = previous; + await fs.rm(root, { recursive: true, force: true }); + await fs.rm(store, { recursive: true, force: true }); + } + }, + 120000, + ); +}); diff --git a/gitnexus/test/integration/python-import-index-reuse.test.ts b/gitnexus/test/integration/python-import-index-reuse.test.ts index 46b07afd9b..59a930d759 100644 --- a/gitnexus/test/integration/python-import-index-reuse.test.ts +++ b/gitnexus/test/integration/python-import-index-reuse.test.ts @@ -2,7 +2,7 @@ * Production-path regression guard for PR #1918 review finding P1. * * The Python file index (`getPythonFileIndex` in - * `import-resolvers/python-file-index.ts`) is + * `languages/python/import-file-index.ts`) is * memoized on the `allFilePaths` Set identity via a WeakMap. The registry- * primary path reaches it through `pythonScopeResolver.resolveImportTarget` * (the orchestrator adapter) — NOT by calling `resolvePythonImportTarget` diff --git a/gitnexus/test/integration/resolvers/cpp-qualified-receiver-typing.test.ts b/gitnexus/test/integration/resolvers/cpp-qualified-receiver-typing.test.ts new file mode 100644 index 0000000000..382541f586 --- /dev/null +++ b/gitnexus/test/integration/resolvers/cpp-qualified-receiver-typing.test.ts @@ -0,0 +1,99 @@ +/** + * C++ receiver typing through qualified type spellings, header prototypes and + * qualified factory callees. + * + * Every row names a caller in the `cpp-qualified-receiver-typing` fixture and + * the exact `m` targets it must reach, as `:.m`. The fixture puts + * a global `C` (other.h) beside `rp::C` (mod.h), and `a::Config` beside a + * `b::Config` declared in the caller's own namespace, so a lookup that drops + * the qualifier and lands on the nearer same-tail class fails a row instead of + * passing it. + */ +import { describe, it, expect, beforeAll } from 'vitest'; +import path from 'path'; +import { FIXTURES, getRelationships, runPipelineFromRepo, type PipelineResult } from './helpers.js'; + +const RP_C = 'mod.h:C.m'; +const GLOBAL_C = 'other.h:C.m'; +const D = 'mod.h:D.m'; + +describe('C++ qualified receiver typing', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'cpp-qualified-receiver-typing'), + () => {}, + ); + }, 60000); + + /** `:.m` for every CALLS edge from `caller` to a method `m`. */ + const memberTargets = (caller: string): string[] => + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === caller && edge.target === 'm') + .map((edge) => `${edge.targetFilePath}:${edge.rel.targetId.split(':')[2]?.split('#')[0]}`) + .sort(); + + it.each<[string, string[]]>([ + // A qualified spelling reaches the namespace member it names, never the + // global `C` that other.h makes visible under the same tail. + ['declared_init', [RP_C]], + ['param_ns', [RP_C]], + ['param_ns_ptr', [RP_C]], + ['param_template', ['mod.h:Box.m']], + ['bare_global', [GLOBAL_C]], + // `a::Config` written inside `namespace b`, which declares its own Config. + ['param_qualified', ['a.h:Config.m']], + ['param_local', ['callers.cpp:Config.m']], + ])('qualified type spelling: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); + + it.each<[string, string[]]>([ + ['declared_ns', [RP_C]], + ['declared_ns_ptr', [RP_C]], + ])('qualified declaration without initializer: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); + + it.each<[string, string[]]>([ + ['brace_ns', [RP_C]], + ['brace_qualified', ['a.h:Config.m']], + ['field_qualified', ['a.h:Config.m']], + ])('qualified brace-init and member field: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); + + it.each<[string, string[]]>([ + ['auto_plain', [D]], + ['inline_plain', [D]], + ['auto_ptr', [D]], + ['global_factory', [GLOBAL_C]], + // A namespace prototype's return type is looked up inside its namespace, + // never from the file's module scope where the global Widget sits. + ['using_auto', [RP_C]], + ['using_same_file', ['mod.h:Widget.m']], + // The block-scope `E y();` in `vexing` must not hoist a file-level `y`. + ['uses_vexing_name', []], + ])('header prototype return type: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); + + it.each<[string, string[]]>([ + ['using_inline', [RP_C]], + ['using_inline_same_file', ['mod.h:Widget.m']], + ])('inline call receiver typed by definition identity: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); + + it.each<[string, string[]]>([ + ['auto_ns', [RP_C]], + ['inline_ns', [RP_C]], + ['ctor_ns', [RP_C]], + // An unknown qualified factory types nothing, and the inner `x` must not + // fall through to the outer `D x`. + ['shadowed_auto', []], + ])('qualified factory callee: %s -> %j', (caller, expected) => { + expect(memberTargets(caller)).toEqual(expected); + }); +}); diff --git a/gitnexus/test/integration/resolvers/csharp.test.ts b/gitnexus/test/integration/resolvers/csharp.test.ts index 606eb485f2..e10f4771d9 100644 --- a/gitnexus/test/integration/resolvers/csharp.test.ts +++ b/gitnexus/test/integration/resolvers/csharp.test.ts @@ -11,6 +11,7 @@ import { getRelationships, getNodesByLabel, getNodesByLabelFull, + getResolutionOutcomes, edgeSet, runPipelineFromRepo, writeFixtureRepo, @@ -2904,3 +2905,55 @@ describe('C# inline constructor receiver resolution', () => { expect(call!.rel.targetId).toContain('Other.DoWork'); }); }); + +// --------------------------------------------------------------------------- +// Global-namespace precedence: a global type must not hide a same-named type +// that C# name lookup reaches first. Inside a namespace declaration a simple +// name binds to the current namespace, then each enclosing one, and the global +// namespace is the outermost. Each namespace declaration's using directives are +// consulted at that level. So the compilation unit's usings come after the +// global namespace's own types. The fixture pairs `Billing.Voucher` with an +// unrelated global `Voucher` in another file. +// --------------------------------------------------------------------------- + +describe('C# global-namespace type precedence', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'csharp-global-namespace-precedence'), + () => {}, + ); + }, 60000); + + it.each([ + ['Create', 'Voucher', 'Billing/Voucher.cs', 'own class, constructed inside itself'], + ['Open', 'Voucher', 'Billing/Voucher.cs', 'same-namespace sibling constructor'], + ['Settle', 'Post', 'Billing/Voucher.cs', 'same-namespace sibling member'], + ['Settle', 'Notify', 'Billing/Voucher.cs', 'field chain through the sibling'], + ['Print', 'Post', 'Billing/Voucher.cs', 'enclosing namespace'], + ['Check', 'Post', 'Billing/Voucher.cs', 'using inside a block namespace'], + ['Record', 'Post', 'Billing/Voucher.cs', 'using after a file-scoped namespace'], + ['Main', 'Post', 'Global/Voucher.cs', 'file outside any namespace'], + ['Import', 'Post', 'Global/Voucher.cs', 'global type before compilation-unit using'], + ])('%s -> %s resolves only into %s (%s)', (caller, callee, targetFile) => { + const targetFiles = getRelationships(result, 'CALLS') + .filter((e) => e.source === caller && e.target === callee) + .map((e) => e.targetFilePath); + expect(targetFiles).toEqual([targetFile]); + }); + + it('reads the Payee property of Billing.Voucher in the field chain', () => { + const reads = getRelationships(result, 'ACCESSES') + .filter((e) => e.source === 'Settle') + .map((e) => `${e.targetLabel}:${e.target}@${e.targetFilePath}`); + expect(reads).toEqual(['Property:Payee@Billing/Voucher.cs']); + }); + + it('leaves no receiver unresolved', () => { + const drops = getResolutionOutcomes(result).filter( + (outcome) => outcome.kind === 'suppressed' && outcome.reason === 'receiver-unresolved', + ); + expect(drops).toEqual([]); + }); +}); diff --git a/gitnexus/test/integration/resolvers/helpers.ts b/gitnexus/test/integration/resolvers/helpers.ts index ee41939230..ac87317ab4 100644 --- a/gitnexus/test/integration/resolvers/helpers.ts +++ b/gitnexus/test/integration/resolvers/helpers.ts @@ -6,7 +6,7 @@ import path from 'path'; import { runPipelineFromRepo } from '../../../src/core/ingestion/pipeline.js'; import type { PipelineOptions } from '../../../src/core/ingestion/pipeline.js'; import type { PipelineResult } from '../../../src/types/pipeline.js'; -import type { GraphRelationship } from 'gitnexus-shared'; +import type { GraphRelationship, ReferenceKind } from 'gitnexus-shared'; export const FIXTURES = path.resolve(__dirname, '..', '..', 'fixtures', 'lang-resolution'); export const CROSS_FILE_FIXTURES = path.resolve( @@ -68,6 +68,59 @@ export function getResolutionOutcomes(result: PipelineResult) { return result.resolutionOutcomes ?? []; } +/** File, 1-based start line, column, member name, and reference kind. */ +export type OutcomeSite = readonly [ + filePath: string, + line: number, + col: number, + name: string, + kind: ReferenceKind, +]; + +/** + * Reasons recorded for the requested kind and member at this start position. + * + * A call and a read can share both their member name and start position. + */ +export function suppressionReasonsAt( + result: PipelineResult, + [filePath, line, col, name, siteKind]: OutcomeSite, +): string[] { + return getResolutionOutcomes(result) + .flatMap((outcome) => + outcome.kind === 'suppressed' && + outcome.filePath === filePath && + outcome.range.startLine === line && + outcome.range.startCol === col && + outcome.name === name && + outcome.siteKind === siteKind + ? [outcome.reason] + : [], + ) + .sort(); +} + +/** + * True when an `ACCESSES` edge `sourceId -> targetId` was emitted for the site + * at `line:col`. The name-inference and return-shape passes key each edge id by + * the site position, which is what ties the edge to one site rather than to any + * access between the same two nodes. + */ +export function hasAccessesAtSite( + result: PipelineResult, + sourceId: string, + targetId: string, + line: number, + col: number, +): boolean { + return getRelationships(result, 'ACCESSES').some( + (edge) => + edge.rel.sourceId === sourceId && + edge.rel.targetId === targetId && + edge.rel.id.endsWith(`:${line}:${col}`), + ); +} + /** * Relationships whose source or target id does not resolve to a live graph node. * A non-empty result means the graph has dangling edges (an endpoint that was diff --git a/gitnexus/test/integration/resolvers/inferred-field-receiver-matrix.test.ts b/gitnexus/test/integration/resolvers/inferred-field-receiver-matrix.test.ts index 9ad4a6b62c..a932b571ad 100644 --- a/gitnexus/test/integration/resolvers/inferred-field-receiver-matrix.test.ts +++ b/gitnexus/test/integration/resolvers/inferred-field-receiver-matrix.test.ts @@ -213,6 +213,12 @@ export class StaticCtorThis { static constructor() { this.p = new Alien(); } run(x) { return this.p.inner().compute(x); } } +export class StaticReadOnly { + static q = new Alien(); +} +export class StaticReader { + readOnly(x) { return StaticReadOnly.q.inner().compute(x); } +} `; // ── Python ─────────────────────────────────────────────────────────────────── @@ -1197,6 +1203,11 @@ const CASES: readonly LanguageCase[] = [ // `Host.p` (static twin) Outer ✗ WRONG Alien ✓ correct // `Host.q` (static, no twin) — none, missed Alien ✓ correct // + // The `Host.q` cell has moved since, without touching the drop: the + // class-level receiver route types ONE hop from the static Property node's + // initializer type, so `Host.q.m()` now resolves `Alien.m` (the second row + // below). Only the twin row still pays the trade in full. + // // So the trade is NOT the "missed edge beats a wrong one" the comment on // `isStaticClassFieldBinding` claims, and this row is why that comment now // says otherwise. For a class with BOTH twins the wrong edge did not go @@ -1216,17 +1227,22 @@ const CASES: readonly LanguageCase[] = [ status: 'resolves', }, // The static-only shape — no instance twin, so nothing at all is left in - // the map and the chain simply loses its type. This is the genuine MISSED - // edge, and the common static shape; the row above is the rarer one. A - // `known-gap` row rather than a positive assertion because there is no - // surviving target to name — the whole point is that the edge is gone. It - // is protected from vacuity by the `every row has a live caller node` - // guard, the same way this file's other known-gap rows are. + // the map. This was the genuine MISSED edge, and the common static shape. + // The class-level receiver route does not read the map: it types + // `StaticReadOnly.q` from the static Property NODE, which now carries the + // type its initializer constructs when the field declares none. So the + // first hop resolves to `Alien.inner` — and not to `Outer.inner`, which + // `Alien` shares the name with, so this cannot pass on a wrong type. + // + // `Inner.compute` is still absent, and that is the remaining gap: the + // second hop's receiver `StaticReadOnly.q.inner()` goes through the + // compound fold, which types a field step only from the class-scope map + // the static binding is kept out of. { - name: 'static-read-without-a-twin-loses-its-type', + name: 'static-read-without-a-twin-types-from-its-initializer', callerId: `Method:${TS_FILE}:StaticReader.readOnly#1`, - targets: [], - status: 'known-gap', + targets: [`Method:${TS_FILE}:Alien.inner#0`], + status: 'resolves', }, ], }, @@ -1289,6 +1305,16 @@ const CASES: readonly LanguageCase[] = [ targets: [`Method:${JS_FILE}:Outer.inner#0`], status: 'resolves', }, + // JavaScript's half of the TypeScript static-only row: a field typed by + // nothing but its initializer, read through the class. JavaScript has no + // annotation to fall back on, so the initializer is the only evidence + // there is — the `Config.DEFAULT.validate()` shape. + { + name: 'static-read-without-a-twin-types-from-its-initializer', + callerId: `Method:${JS_FILE}:StaticReader.readOnly#1`, + targets: [`Method:${JS_FILE}:Alien.inner#0`], + status: 'resolves', + }, ], }, { diff --git a/gitnexus/test/integration/resolvers/javascript-object-properties.test.ts b/gitnexus/test/integration/resolvers/javascript-object-properties.test.ts index 6df379155c..efc4dc882f 100644 --- a/gitnexus/test/integration/resolvers/javascript-object-properties.test.ts +++ b/gitnexus/test/integration/resolvers/javascript-object-properties.test.ts @@ -31,7 +31,15 @@ */ import { describe, it, expect, beforeAll } from 'vitest'; import path from 'path'; -import { FIXTURES, getRelationships, runPipelineFromRepo, type PipelineResult } from './helpers.js'; +import { + FIXTURES, + getRelationships, + hasAccessesAtSite, + runPipelineFromRepo, + suppressionReasonsAt, + type OutcomeSite, + type PipelineResult, +} from './helpers.js'; describe('JavaScript plain-object property access (A1/A5)', () => { let result: PipelineResult; @@ -166,6 +174,76 @@ describe('JavaScript plain-object property access (A1/A5)', () => { expect(propertyNames()).not.toContain('notAConstructedField'); expect(writersOf('notAConstructedField')).toEqual([]); }); + + // The capture makes the ENCLOSING LITERAL the receiver, and the + // receiver-bound pass treats any receiver text holding a `.` or `(` as a + // compound expression to fold — which `{ x: row.a }`, `{ r: 0.5 }` and + // `{ ...seed, extra }` all do. The fold cannot type a literal, so each of + // these keys was recorded as a `receiver-unresolved` drop, and the drop + // stayed after the unique-name pass answered the same site with an edge. + // Each row pins both halves: the edge exists at THIS site, and no drop does. + it.each([ + [ + ['destructured.js', 26, 4, 'exitContract', 'write'], + 'Function:destructured.js:buildPlan', + 'Property:destructured.js:buildPlan.exitContract@25:4', + ], + [ + ['destructured.js', 27, 6, 'destructuredOnlyField', 'write'], + 'Function:destructured.js:buildPlan', + 'Property:destructured.js:destructuredDefaults.destructuredOnlyField', + ], + [ + ['destructured.js', 34, 4, 'destructuredOnlyField', 'write'], + 'Function:destructured.js:buildFlat', + 'Property:destructured.js:buildFlat.destructuredOnlyField@33:4', + ], + [ + ['frozen.js', 26, 20, 'extra', 'write'], + 'Function:frozen.js:buildRules', + 'Property:frozen.js:buildRules.extra@25:20', + ], + [ + ['return-shape-typed.js', 6, 4, 'ambiguousProducedField', 'write'], + 'Function:return-shape-typed.js:producerAlpha', + 'Property:return-shape-typed.js:producerAlpha.ambiguousProducedField@5:4', + ], + [ + ['return-shape-typed.js', 12, 4, 'ambiguousProducedField', 'write'], + 'Function:return-shape-typed.js:producerBeta', + 'Property:return-shape-typed.js:producerBeta.ambiguousProducedField@11:4', + ], + [ + ['return-shape.js', 8, 4, 'returnShapeOnlyField', 'write'], + 'Function:return-shape.js:formatAlert', + 'Property:return-shape.js:formatAlert.returnShapeOnlyField@7:4', + ], + [ + ['return-shape.js', 9, 4, 'sharedWithDeclared', 'write'], + 'Function:return-shape.js:formatAlert', + 'Property:return-shape.js:formatAlert.sharedWithDeclared@8:4', + ], + [ + ['return-shape.js', 20, 4, 'summaryOnlyField', 'write'], + 'Function:return-shape.js:formatSummary', + 'Property:return-shape.js:formatSummary.summaryOnlyField@19:4', + ], + [ + ['return-shape.js', 45, 13, 'anonReturnKey', 'write'], + 'File:return-shape.js', + 'Property:return-shape.js:fn@43:2.anonReturnKey@44:13', + ], + [ + ['return-shape.js', 53, 4, 'productionAndTestField', 'write'], + 'Function:return-shape.js:buildProductionShape', + 'Property:return-shape.js:buildProductionShape.productionAndTestField@52:4', + ], + ])('answers %j with an edge and records no drop for it', (site, sourceId, targetId) => { + expect({ + edge: hasAccessesAtSite(result, sourceId, targetId, site[1], site[2]), + suppressions: suppressionReasonsAt(result, site), + }).toEqual({ edge: true, suppressions: [] }); + }); }); // R3-4. The dominant shape in idiomatic JS and the one with no anchor at all: diff --git a/gitnexus/test/integration/resolvers/javascript.test.ts b/gitnexus/test/integration/resolvers/javascript.test.ts index deadef3af7..879d04de0e 100644 --- a/gitnexus/test/integration/resolvers/javascript.test.ts +++ b/gitnexus/test/integration/resolvers/javascript.test.ts @@ -1,8 +1,11 @@ /** * JavaScript: self/this resolution, parent resolution, super resolution */ -import { describe, it, expect, beforeAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import { summarizeUnresolvedReceivers } from '../../../src/core/ingestion/scope-resolution/unresolved-receivers.js'; import { FIXTURES, CROSS_FILE_FIXTURES, @@ -11,6 +14,9 @@ import { getNodesByLabelFull, edgeSet, runPipelineFromRepo, + suppressionReasonsAt, + writeFixtureRepo, + type OutcomeSite, type PipelineResult, } from './helpers.js'; @@ -321,6 +327,23 @@ describe('Field type resolution (JavaScript)', () => { expect(def!.properties.isStatic).toBe(true); expect(def!.properties.visibility).toBe('public'); }); + + // `static DEFAULT = new Config()` declares no type, and a static field's + // initializer binding is kept out of the class scope on purpose (it would + // retype an instance field of the same name). So `Config.DEFAULT` had no + // type anywhere and the call was dropped. The Property node now records the + // type its initializer constructs, and the class-level receiver route reads it. + it('records the type a static field initializer constructs on its Property node', () => { + const def = getNodesByLabelFull(result, 'Property').find((p) => p.name === 'DEFAULT'); + expect(def?.properties.initializerType).toBe('Config'); + }); + + it('resolves Config.DEFAULT.validate() through the static field initializer type', () => { + const targets = getRelationships(result, 'CALLS') + .filter((c) => c.source === 'validateConfig') + .map((c) => c.rel.targetId); + expect(targets).toEqual(['Method:models.js:Config.validate#0']); + }); }); // ACCESSES write edges from assignment expressions @@ -691,3 +714,263 @@ describe('JavaScript inline constructor receiver resolution', () => { expect(call!.rel.targetId).toContain('Legacy'); }); }); + +// --------------------------------------------------------------------------- +// CommonJS export assignments are declarations, not dropped member writes +// --------------------------------------------------------------------------- + +describe('CommonJS export assignment receivers (JavaScript)', () => { + let repoDir: string | undefined; + let result: PipelineResult; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-js-cjs-export-receiver-')); + writeFixtureRepo(repoDir, { + 'lib.js': `exports.memberRequest = function (url) { + return url; +}; +module.exports.arrowRequest = (url) => url; +function wrap(module) { + module.exports.wrapped = 1; +} +module.exports.api.nested = 1; +`, + 'esm-export.js': 'export {};\nmodule.exports.esmExport = 1;\n', + 'esm-import.js': 'import "./side-effect.js";\nmodule.exports.esmImport = 1;\n', + 'side-effect.js': 'const initialized = true;\n', + 'explicit.mjs': 'module.exports.explicitEsm = 1;\n', + }); + result = await runPipelineFromRepo(repoDir, () => {}, {}); + }, 60000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + }); + + // `module.exports.arrowRequest = …` DECLARES this module's `arrowRequest` + // export, exactly as `exports.memberRequest = …` on line 1 does. Its receiver + // merely has a dot in it, so the receiver-bound pass tried to fold + // `module.exports` as a value, failed, and filed the declaration as a dropped + // member write. The bare `exports` spelling never reached that path at all. + // + // Inside `wrap`, `module` is a PARAMETER: that write goes through a local + // value the resolver cannot type, so it is a real drop and must stay one. So + // is the last line, which writes INTO a value hanging off the export object + // rather than declaring an export. + it.each([ + [['lib.js', 1, 0, 'memberRequest', 'write'], []], + [['lib.js', 4, 0, 'arrowRequest', 'write'], []], + [['lib.js', 6, 2, 'wrapped', 'write'], ['receiver-unresolved']], + [['lib.js', 8, 0, 'nested', 'write'], ['receiver-unresolved']], + ])('records %j as %j', (site, reasons) => { + expect(suppressionReasonsAt(result, site)).toEqual(reasons); + }); + + // Instrumentation only: the declaration keeps the write edge it already had, + // and gains nothing. + it('keeps the module-level write edge to each exported function', () => { + const writes = getRelationships(result, 'ACCESSES') + .filter((e) => e.sourceLabel === 'File' && e.rel.reason === 'scope-resolution: write') + .map((e) => e.target) + .sort(); + expect(writes).toEqual(['arrowRequest', 'memberRequest']); + }); + + it.each(['esm-export.js', 'esm-import.js', 'explicit.mjs'])( + 'keeps a receiver drop for an unbound module in %s', + (filePath) => { + expect( + result.resolutionOutcomes?.some( + (outcome) => + outcome.kind === 'suppressed' && + outcome.filePath === filePath && + outcome.reason === 'receiver-unresolved' && + outcome.siteKind === 'write', + ), + ).toBe(true); + }, + ); +}); + +describe('Literal writes and owned receiver bases preserve bindings', () => { + let result: PipelineResult; + let fixtureRoot: string | undefined; + + beforeAll(async () => { + fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-literal-bindings-')); + writeFixtureRepo(fixtureRoot, { + 'private.js': `const config = { privateFlag: true }; +class PrivateProducer { + #make(row) { return { privateFlag: row.value }; } +} +`, + 'owned.dart': `class DartWorker { void go() {} } +class DartBundle { DartWorker worker = DartWorker(); } +class DartOwner { + DartBundle task = DartBundle(); + void loop(xs) { + for (final task in xs) { task.worker.go(); } + } +} +`, + 'input.js': `const config = { secretFlag: true }; +export class SignalService { + make(options) { + options.secretFlag = false; + return { secretFlag: options.secretFlag }; + } +} +new SignalService().make(config); +`, + 'foreign-reader.js': `const local = { foreignFlag: 1 }; +export class Service { make(obj) { return obj.foreignFlag; } } +`, + 'foreign-producer.js': `export class Service { make() { return { foreignFlag: 0.5 }; } } +`, + 'repeated.js': `function build() { return { data: { data: 1 } }; } +function use() { const res = build(); return res.data.data; } +`, + 'static.js': `class StaticService { go() {} } +class StaticOther { go() {} } +class StaticBase { static svc = new StaticService(); } +class NullChild extends StaticBase { static svc = null; } +class UnknownChild extends StaticBase { static svc = unknownFactory(); } +class InheritedChild extends StaticBase {} +class TypedChild extends StaticBase { static svc = new StaticOther(); } +function nullProbe() { return NullChild.svc.go(); } +function unknownProbe() { return UnknownChild.svc.go(); } +function inheritedProbe() { return InheritedChild.svc.go(); } +function typedProbe() { return TypedChild.svc.go(); } +`, + 'constructor.js': `class JsRepo { save() {} } +class JsActual { save() {} } +function jsShadow(JsRepo) { + class JsHolder { static item = new JsRepo(); } + JsHolder.item.save(); +} +jsShadow(JsActual); +`, + 'constructor.ts': `class TsRepo { save() {} } +class TsActual { save() {} } +function tsShadow(TsRepo: any) { + class TsHolder { static item = new TsRepo(); } + TsHolder.item.save(); +} +function tsAnnotated(TsRepo: any) { + class AnnotatedHolder { static item: TsRepo; } + AnnotatedHolder.item.save(); +} +tsShadow(TsActual); +tsAnnotated(TsActual); +`, + }); + result = await runPipelineFromRepo(fixtureRoot, () => {}, { skipGraphPhases: true }); + }, 120000); + + afterAll(() => { + if (fixtureRoot !== undefined) fs.rmSync(fixtureRoot, { recursive: true, force: true }); + }); + + it.each(['read', 'write'])('keeps an input property %s on the declared input', (kind) => { + const edges = getRelationships(result, 'ACCESSES').filter( + (e) => + e.rel.sourceId === 'Method:input.js:SignalService.make#1' && + e.rel.reason?.endsWith(`: ${kind}`), + ); + expect(edges.some((e) => e.rel.targetId === 'Property:input.js:config.secretFlag')).toBe(true); + if (kind === 'read') { + expect(edges.some((e) => e.rel.targetId.includes('SignalService.make.secretFlag@'))).toBe( + false, + ); + } + }); + + it('keeps the returned literal declaration write on its own key', () => { + const writes = getRelationships(result, 'ACCESSES').filter( + (e) => + e.rel.sourceId === 'Method:input.js:SignalService.make#1' && + e.rel.targetId === 'Property:input.js:SignalService.make.secretFlag@4:13' && + e.rel.reason?.endsWith(': write'), + ); + expect(writes).toHaveLength(1); + }); + + it('binds a private method literal write to its own returned key', () => { + const writes = getRelationships(result, 'ACCESSES').filter( + (e) => + e.sourceFilePath === 'private.js' && + e.sourceLabel !== 'File' && + e.rel.reason?.endsWith(': write'), + ); + expect(writes).toHaveLength(1); + expect(writes[0]?.rel.targetId).toContain( + 'Property:private.js:PrivateProducer.#make.privateFlag@', + ); + }); + + it('records a Dart chain on a masked field base as owned but unbound', () => { + expect(getRelationships(result, 'CALLS').filter((e) => e.source === 'loop')).toEqual([]); + expect( + result.resolutionOutcomes?.some( + (o) => + o.kind === 'suppressed' && + o.reason === 'receiver-owned-but-unbound' && + o.filePath === 'owned.dart' && + o.name === 'go', + ), + ).toBe(true); + const owned = + result.resolutionOutcomes?.filter((outcome) => outcome.filePath === 'owned.dart') ?? []; + expect(summarizeUnresolvedReceivers(owned)?.counts.go).toBe(1); + }); + + it('keeps the unresolved outer read when a repeated-name inner read was answered', () => { + const drops = result.resolutionOutcomes?.filter( + (outcome) => + outcome.kind === 'suppressed' && + outcome.reason === 'receiver-unresolved' && + outcome.filePath === 'repeated.js' && + outcome.name === 'data', + ); + expect(drops).toHaveLength(1); + expect(drops?.[0]).toMatchObject({ + range: { startLine: 2, startCol: 45, endCol: 58 }, + }); + expect( + getRelationships(result, 'ACCESSES').some( + (edge) => + edge.sourceFilePath === 'repeated.js' && + edge.rel.reason === 'scope-resolution: return-shape member: read', + ), + ).toBe(true); + }); + + it('does not borrow a same-named method return shape from another file', () => { + const reads = getRelationships(result, 'ACCESSES').filter( + (e) => e.rel.sourceId === 'Method:foreign-reader.js:Service.make#1', + ); + expect(reads.map((e) => e.rel.targetId)).toEqual([ + 'Property:foreign-reader.js:local.foreignFlag', + ]); + }); + + it.each(['nullProbe', 'unknownProbe'])('stops at an untyped static override in %s', (source) => { + expect(getRelationships(result, 'CALLS').filter((e) => e.source === source)).toEqual([]); + }); + + it.each([ + ['inheritedProbe', 'Method:static.js:StaticService.go#0'], + ['typedProbe', 'Method:static.js:StaticOther.go#0'], + ['tsAnnotated', 'Method:constructor.ts:TsRepo.save#0'], + ])('resolves the available field type in %s', (source, target) => { + expect( + getRelationships(result, 'CALLS') + .filter((e) => e.source === source) + .map((e) => e.rel.targetId), + ).toContain(target); + }); + + it.each(['jsShadow', 'tsShadow'])('respects the constructor value parameter in %s', (source) => { + expect(getRelationships(result, 'CALLS').filter((e) => e.source === source)).toEqual([]); + }); +}); diff --git a/gitnexus/test/integration/resolvers/member-call-producer.test.ts b/gitnexus/test/integration/resolvers/member-call-producer.test.ts index a023d96b0a..b55bd3aa44 100644 --- a/gitnexus/test/integration/resolvers/member-call-producer.test.ts +++ b/gitnexus/test/integration/resolvers/member-call-producer.test.ts @@ -20,7 +20,15 @@ */ import { describe, it, expect, beforeAll } from 'vitest'; import path from 'path'; -import { FIXTURES, getRelationships, runPipelineFromRepo, type PipelineResult } from './helpers.js'; +import { + FIXTURES, + getRelationships, + hasAccessesAtSite, + runPipelineFromRepo, + suppressionReasonsAt, + type OutcomeSite, + type PipelineResult, +} from './helpers.js'; describe('member-call producers (W2-1)', () => { let result: PipelineResult; @@ -75,4 +83,44 @@ describe('member-call producers (W2-1)', () => { // 0.5 name tier and get answered by an unrelated same-named key. expect(shapeTargetsOf('readAbsent')).toEqual([]); }); + + // The WRITE side of the same shapes: each producer writes the keys of the + // literal it returns. A METHOD's graph id carries its overload suffix + // (`SignalService.make#0`) while its keys are qualified `SignalService.make.`, + // so the own-return-shape match missed every method, three same-named + // candidates were left, and the write got no edge at all. Every row is also + // free of a `receiver-unresolved` drop: the literal's decimals made the + // receiver-bound pass file the site as one before the edge existed. + it.each([ + [ + ['src/producer.js', 5, 13, 'secretFlag', 'write'], + 'Method:src/producer.js:SignalService.make#0', + 'Property:src/producer.js:SignalService.make.secretFlag@4:13', + ], + [ + ['src/producer.js', 5, 38, 'wickRatio', 'write'], + 'Method:src/producer.js:SignalService.make#0', + 'Property:src/producer.js:SignalService.make.wickRatio@4:38', + ], + [ + ['src/producer.js', 9, 13, 'secretFlag', 'write'], + 'Method:src/producer.js:SignalService.other#0', + 'Property:src/producer.js:SignalService.other.secretFlag@8:13', + ], + [ + ['src/producer.js', 15, 11, 'secretFlag', 'write'], + 'Function:src/producer.js:makeSignal', + 'Property:src/producer.js:makeSignal.secretFlag@14:11', + ], + [ + ['src/producer.js', 15, 36, 'wickRatio', 'write'], + 'Function:src/producer.js:makeSignal', + 'Property:src/producer.js:makeSignal.wickRatio@14:36', + ], + ])('binds the producer write %j to its own key with no drop', (site, sourceId, targetId) => { + expect({ + edge: hasAccessesAtSite(result, sourceId, targetId, site[1], site[2]), + suppressions: suppressionReasonsAt(result, site), + }).toEqual({ edge: true, suppressions: [] }); + }); }); diff --git a/gitnexus/test/integration/resolvers/parameter-producer.test.ts b/gitnexus/test/integration/resolvers/parameter-producer.test.ts index ccac6e9ff4..662a65d016 100644 --- a/gitnexus/test/integration/resolvers/parameter-producer.test.ts +++ b/gitnexus/test/integration/resolvers/parameter-producer.test.ts @@ -17,7 +17,15 @@ */ import { describe, it, expect, beforeAll } from 'vitest'; import path from 'path'; -import { FIXTURES, getRelationships, runPipelineFromRepo, type PipelineResult } from './helpers.js'; +import { + FIXTURES, + getRelationships, + hasAccessesAtSite, + runPipelineFromRepo, + suppressionReasonsAt, + type OutcomeSite, + type PipelineResult, +} from './helpers.js'; describe('caller-derived parameter types (W2-2)', () => { let result: PipelineResult; @@ -142,4 +150,36 @@ describe('caller-derived parameter types (W2-2)', () => { expect(targets).toHaveLength(1); expect(targets[0]).toContain('makeSpike.wickRatio'); }); + + // Each producer WRITES the keys of its own returned literal, and the + // unique-name pass answers that write with the key it defines. The literal + // holds a decimal, so the receiver-bound pass had already filed the same site + // as a `receiver-unresolved` drop — and kept it after the edge was emitted. + it.each([ + [ + ['src/producer.js', 4, 11, 'wickRatio', 'write'], + 'Function:src/producer.js:makeSpike', + 'Property:src/producer.js:makeSpike.wickRatio@3:11', + ], + [ + ['src/producer.js', 4, 27, 'source', 'write'], + 'Function:src/producer.js:makeSpike', + 'Property:src/producer.js:makeSpike.source@3:27', + ], + [ + ['src/producer.js', 8, 11, 'wickRatio', 'write'], + 'Function:src/producer.js:makeCandle', + 'Property:src/producer.js:makeCandle.wickRatio@7:11', + ], + [ + ['src/producer.js', 8, 27, 'source', 'write'], + 'Function:src/producer.js:makeCandle', + 'Property:src/producer.js:makeCandle.source@7:27', + ], + ])('answers the producer write %j with its own key and no drop', (site, sourceId, targetId) => { + expect({ + edge: hasAccessesAtSite(result, sourceId, targetId, site[1], site[2]), + suppressions: suppressionReasonsAt(result, site), + }).toEqual({ edge: true, suppressions: [] }); + }); }); diff --git a/gitnexus/test/integration/resolvers/rust.test.ts b/gitnexus/test/integration/resolvers/rust.test.ts index 7ad1b5e779..f6d5f68dd0 100644 --- a/gitnexus/test/integration/resolvers/rust.test.ts +++ b/gitnexus/test/integration/resolvers/rust.test.ts @@ -9,6 +9,7 @@ import { getRelationships, getNodesByLabel, getNodesByLabelFull, + getResolutionOutcomes, findDanglingEdges, edgeSet, runPipelineFromRepo, @@ -217,6 +218,15 @@ describe('Rust ambiguous symbol resolution', () => { expect(imp.targetFilePath).not.toMatch(/src\/other\//); } }); + + it('types h from services::create_handler() as the imported models::Handler (#3498)', () => { + const calls = getRelationships(result, 'CALLS').filter( + (edge) => edge.source === 'main' && edge.target === 'handle', + ); + expect(calls.map((edge) => edge.rel.targetId)).toEqual([ + 'Function:src/models/handler.rs:Handler.handle#0', + ]); + }); }); describe('Rust call resolution with arity filtering', () => { @@ -3019,3 +3029,83 @@ describe('Rust type-qualified calls outrank a same-named module (#2745 review)', expect(ids).toContain('Function:src/lib.rs:Buffer.with_capacity'); }); }); + +// --------------------------------------------------------------------------- +// Module-qualified factory calls type their result (#3498 follow-up). +// +// `let x = rp::make(); x.m()` bound `x` to `rp`: the call-return rule kept only +// the text before the first `::` (the `Foo::new()` idiom), so the function name +// was gone and `make`'s declared `-> C` was never read. The aliased module path +// `rp::make()` also failed to resolve as a call, because `rp` names no module +// file. +// --------------------------------------------------------------------------- + +describe('Rust module-qualified factory result types (#3498 follow-up)', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'rust-qualified-factory-return'), + () => {}, + ); + }, 60000); + + const callsFrom = (source: string, target: string) => + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === target) + .map((edge) => edge.rel.targetId) + .sort(); + + it.each([ + 'alias_call', + 'module_call', + 'crate_call', + 'inline_alias', + 'inline_module', + 'inline_crate', + ])("types %s from make's return annotation", (source) => { + expect(callsFrom(source, 'm')).toEqual(['Function:src/modx.rs:C.m#0']); + }); + + it('does not let a let-bound value shadow the module segment of a path', () => { + expect(callsFrom('local_shadow', 'm')).toEqual([ + 'Function:src/modx.rs:C.m#0', + 'Function:src/modx.rs:Other.m#0', + ]); + }); + + it('keeps reading a type-qualified call as the type', () => { + expect(callsFrom('type_qualified', 'm')).toEqual(['Function:src/modx.rs:Other.m#0']); + }); + + it.each(['untyped_alias', 'untyped_inline'])( + 'does not guess a receiver type for %s', + (source) => { + expect(callsFrom(source, 'm')).toEqual([]); + }, + ); + + it.each([ + ['alias_call', 'make'], + ['inline_alias', 'make'], + ['untyped_alias', 'untyped'], + ])('resolves the aliased module path in %s to modx::%s', (source, target) => { + const edges = getRelationships(result, 'CALLS').filter( + (edge) => edge.source === source && edge.target === target, + ); + expect(edges.map((edge) => [edge.rel.targetId, edge.rel.reason])).toEqual([ + [`Function:src/modx.rs:${target}`, 'import-resolved'], + ]); + }); + + it('records the untyped receivers as dropped sites instead of an exact miss', () => { + const dropped = getResolutionOutcomes(result) + .filter((outcome) => outcome.kind === 'suppressed') + .filter( + (outcome) => outcome.reason === 'receiver-unresolved' && outcome.filePath === 'src/main.rs', + ) + .map((outcome) => `${outcome.range.startLine}:${outcome.siteKind}:${outcome.name}`) + .sort(); + expect(dropped).toEqual(['44:call:m', '44:read:m', '48:call:m', '48:read:m']); + }); +}); diff --git a/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts b/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts index cf752761e7..98496a5e56 100644 --- a/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts +++ b/gitnexus/test/integration/resolvers/typescript-esm-js-extension.test.ts @@ -1,7 +1,7 @@ /** * Integration test: TypeScript ESM .js extension imports produce CALLS edges. * - * Verifies the full pipeline: .js import → resolveImportPath strips .js → + * Verifies the full pipeline: .js import → import-target resolution strips .js → * resolves to .ts → scope-resolver emits CALLS edge. */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; diff --git a/gitnexus/test/integration/resolvers/typescript.test.ts b/gitnexus/test/integration/resolvers/typescript.test.ts index 4b3cadcda5..ea1becd004 100644 --- a/gitnexus/test/integration/resolvers/typescript.test.ts +++ b/gitnexus/test/integration/resolvers/typescript.test.ts @@ -13,7 +13,9 @@ import { edgeSet, getResolutionOutcomes, runPipelineFromRepo, + suppressionReasonsAt, writeFixtureRepo, + type OutcomeSite, type PipelineResult, } from './helpers.js'; @@ -3213,6 +3215,20 @@ describe('TS dynamic-this receiver seeding guard', () => { const calls = getRelationships(result, 'CALLS'); expect(calls.some((c) => c.target === 'go' && c.source === 'onClick')).toBe(false); }); + + // Both sites on `this.route.go()` are lost for ONE reason: the object-literal + // method owns `this` and gives it no type. The call's receiver is the chain + // `this.route`, and the owned-receiver check was asked about that whole text + // — which no scope owns — instead of its base `this`. So the call went on to + // the compound fold and was filed as a generic `receiver-unresolved` drop, + // or, when the read beside it (same start column) was handled first, as + // nothing at all. + it.each([ + [['app.ts', 17, 6, 'route', 'read'], ['receiver-owned-but-unbound']], + [['app.ts', 17, 6, 'go', 'call'], ['receiver-owned-but-unbound']], + ])('records %j under its real reason', (site, reasons) => { + expect(suppressionReasonsAt(result, site)).toEqual(reasons); + }); }); // --------------------------------------------------------------------------- diff --git a/gitnexus/test/integration/resolvers/zig.test.ts b/gitnexus/test/integration/resolvers/zig.test.ts index 84f6027aff..4f796b7316 100644 --- a/gitnexus/test/integration/resolvers/zig.test.ts +++ b/gitnexus/test/integration/resolvers/zig.test.ts @@ -3,16 +3,21 @@ */ import { describe, it, expect, beforeAll } from 'vitest'; import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; import { edgeSet, FIXTURES, getNodesByLabel, getNodesByLabelFull, getRelationships, + getResolutionOutcomes, runPipelineFromRepo, + writeFixtureRepo, type PipelineResult, } from './helpers.js'; import { SupportedLanguages } from '../../../src/config/supported-languages.js'; +import type { ResolutionOutcome } from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js'; import { describeGrammarPresence, optionalGrammarGate } from '../../helpers/optional-grammar.js'; // Vendored `tree-sitter-zig`: on a platform without a prebuild the grammar @@ -25,6 +30,48 @@ const zigAvailable = zig.available; describeGrammarPresence(zig); +/** The CALLS / ACCESSES / USES edges the reference site at `file:line:col` + * produced, as ` -> | `. A site edge's + * id ends with the site's `::` (see `tryEmitEdge`). */ +function edgesAtSite(result: PipelineResult, file: string, line: number, col: number): string[] { + return ['CALLS', 'ACCESSES', 'USES'] + .flatMap((type) => getRelationships(result, type)) + .filter((e) => e.sourceFilePath === file && e.rel.id.endsWith(`:${line}:${col}`)) + .map((e) => `${e.rel.type} ${e.rel.sourceId} -> ${e.rel.targetId} | ${e.rel.reason}`) + .sort(); +} + +/** Every CALLS / ACCESSES / USES edge into `targetId`, as + * ` | `. */ +function referencesInto(result: PipelineResult, targetId: string): string[] { + return ['CALLS', 'ACCESSES', 'USES'] + .flatMap((type) => getRelationships(result, type)) + .filter((e) => e.rel.targetId === targetId) + .map((e) => `${e.rel.type} ${e.rel.sourceId} | ${e.rel.reason}`) + .sort(); +} + +/** The `receiver-unresolved` drops recorded at `file:line:col`, as + * ` ` — the rows of the #3498 drop triage. */ +function receiverDropsAt( + result: PipelineResult, + file: string, + line: number, + col: number, +): string[] { + return getResolutionOutcomes(result) + .filter( + (o): o is Extract => + o.kind === 'suppressed' && + o.reason === 'receiver-unresolved' && + o.filePath === file && + o.range.startLine === line && + o.range.startCol === col, + ) + .map((o) => `${o.siteKind} ${o.name}`) + .sort(); +} + describe.skipIf(!zigAvailable)('Zig basic resolution', () => { let result: PipelineResult; @@ -675,6 +722,59 @@ describe.skipIf(!zigAvailable)('Zig idioms (zig-idioms fixture)', () => { expect(calls).toContain('viaAlias → get'); expect(calls).toContain('viaAlias → twice'); }); + + // #3498 drop triage, F-A: `const X = @import("f.zig").X;` reads `X` off the + // module it names. The `@import(…)` receiver had no namespace binding (the + // named-import rule claims the builtin), so every such read was recorded as + // a receiver drop, and a renaming alias (`const Gauge = ….DEFAULT_NS;`) + // emitted nothing at all. `Element.zig:35` is the `Gauge` shadow case above: + // `Gauge` stays an import binding, only the `.DEFAULT_NS` read resolves. + it.each([ + ['src/holder.zig', 6, 16, 'File:src/holder.zig', 'Struct:src/counter.zig:Counter'], + ['src/main.zig', 6, 14, 'File:src/main.zig', 'Struct:src/counter.zig:Stack'], + [ + 'src/webapi/Element.zig', + 35, + 14, + 'Struct:src/webapi/Element.zig:Element', + 'Const:src/webapi/dom_utils.zig:DEFAULT_NS', + ], + [ + 'src/webapi/hub.zig', + 9, + 18, + 'File:src/webapi/hub.zig', + 'Function:src/webapi/dom_utils.zig:scale', + ], + [ + 'src/webapi/hub.zig', + 10, + 23, + 'File:src/webapi/hub.zig', + 'Const:src/webapi/dom_utils.zig:DEFAULT_NS', + ], + ])( + 'reads the member of a one-member `@import(…).X` alias at %s:%i:%i through the module', + (file, line, col, source, target) => { + expect(receiverDropsAt(result, file, line, col)).toEqual([]); + expect(edgesAtSite(result, file, line, col)).toEqual([ + `ACCESSES ${source} -> ${target} | import-resolved`, + ]); + }, + ); + + it('types a type-constructor call used as a receiver (`Stack(u8).init()`) as the type it instantiates (#3498 F-D)', () => { + // `Stack` is a function returning `type`, so the inline call has no + // return-type binding to read and Zig declares no construction syntax: + // the receiver typed nothing and the call was dropped, while the bound + // form (`var t = Stack(u8).init(); t.top()`) resolved. Zig's + // `isTypeApplicationCall` hook says a TitleCase callee applies a type + // constructor, so the receiver is the class `Stack` names. + expect(receiverDropsAt(result, 'src/main.zig', 42, 12)).toEqual([]); + expect(edgesAtSite(result, 'src/main.zig', 42, 12)).toEqual([ + 'CALLS Function:src/main.zig:main -> Method:src/counter.zig:Stack.init#0 | import-resolved', + ]); + }); }); /** @@ -873,6 +973,23 @@ describe.skipIf(!zigAvailable)('Zig type aliases (zig-filestruct fixture, aliase expect(calls).toContain('b11 → go'); }); + it('types through a FORWARDING type constructor, in the scope that declared it (`Bridge(T)` is `Builder(T)`, #3498 F-B)', () => { + // `fn Bridge(comptime T: type) type { return Builder(T); }` names no + // container, and a `type` return binds nothing, so `Bridge(Local)` typed a + // Function that owns no members. The forwarding binding `Bridge ↦ Builder` + // is declared in generic.zig, which is where `Builder` is visible — not in + // aliases.zig. Bound (`const bound = Bridge(Local)`) and inline + // (`Bridge(Local).prototypeChain()`) spellings both reach Builder. + const fromB12 = getRelationships(result, 'CALLS') + .filter((e) => e.source === 'b12' && e.targetLabel === 'Method') + .map((e) => e.rel.targetId) + .sort(); + expect(fromB12).toEqual([ + 'Method:src/generic.zig:Builder.accessor#1', + 'Method:src/generic.zig:Builder.prototypeChain#0', + ]); + }); + it('a value const / value call is not a type alias and gains no edge', () => { // `const helperResult = generic.Thing.make();` is a call, not an alias; // `const max = 5;` is a literal. Neither may bind a phantom type that @@ -1095,6 +1212,47 @@ describe.skipIf(!zigAvailable)('Zig function-local and anonymous containers (F8) 'Function:src/Sorter.zig:Sorter."Sorter: local state" → Method:src/Sorter.zig:Sorter.test@L41$State.kill#0', ); }); + + // #3498 drop triage, F-C: `struct { fn lessThan … }.lessThan` (the comparator + // handed to `std.sort.pdq`) and `const byteSize = struct { fn it … }.it;` + // read a fn VALUE off an anonymous container. Its receiver text was the + // container's whole body, which names nothing, so each read was a receiver + // drop — and the only edge came from the read's position, which lies inside + // the container, so the container "accessed" its own fn. The receiver is the + // identity the container is minted under, and the read is attributed to the + // scope it is evaluated in. A value, so a reference: never CALLS. + it.each([ + [ + 16, + 17, + 'Method:src/Sorter.zig:Sorter$2.it#1', + ['ACCESSES Struct:src/Sorter.zig:Sorter | read'], + ], + [ + 23, + 38, + 'Method:src/Sorter.zig:Sorter.sortBoth$1.lessThan#3', + [ + 'ACCESSES Method:src/Sorter.zig:Sorter.sortBoth#0 | read', + 'USES Method:src/Sorter.zig:Sorter.sortBoth#0 | scope-resolution: value-ref', + ], + ], + [ + 28, + 38, + 'Method:src/Sorter.zig:Sorter.sortBoth$2.lessThan#3', + [ + 'ACCESSES Method:src/Sorter.zig:Sorter.sortBoth#0 | read', + 'USES Method:src/Sorter.zig:Sorter.sortBoth#0 | scope-resolution: value-ref', + ], + ], + ])( + 'reads the fn value of an anonymous container (Sorter.zig:%i:%i) from where it is evaluated', + (line, col, target, expected) => { + expect(receiverDropsAt(result, 'src/Sorter.zig', line, col)).toEqual([]); + expect(referencesInto(result, target)).toEqual(expected); + }, + ); }); describe.skipIf(!zigAvailable)( @@ -1227,6 +1385,23 @@ describe.skipIf(!zigAvailable)('Zig hub modules (`pub const X = @import(…)` re const intoUtil = calls.filter((c) => c.endsWith('@ src/stdx/util.zig')); expect(intoUtil).toEqual(['c11_hub_reexported_fn → helper @ src/stdx/util.zig']); }); + + // #3498 drop triage, F-A: the hub's own `pub const X = @import("x.zig").X;` + // reads `X` off the module it names, through that module — not by the + // lexical accident that the alias happens to share the member's name. + it.each([ + [2, 18, 'Struct:src/stdx/thing.zig:Thing'], + [3, 29, 'Struct:src/stdx/bounded_array.zig:BoundedArrayType'], + [4, 19, 'Function:src/stdx/util.zig:helper'], + ])( + 'reads the re-exported member at src/stdx/stdx.zig:%i:%i through its module', + (line, col, target) => { + expect(receiverDropsAt(result, 'src/stdx/stdx.zig', line, col)).toEqual([]); + expect(edgesAtSite(result, 'src/stdx/stdx.zig', line, col)).toEqual([ + `ACCESSES File:src/stdx/stdx.zig -> ${target} | import-resolved`, + ]); + }, + ); }); describe.skipIf(!zigAvailable)( @@ -1331,6 +1506,13 @@ describe.skipIf(!zigAvailable)( ]), ); }); + + it('reads the member of `pub const X = @import("x.zig").X;` through its module (#3498 F-A)', () => { + expect(receiverDropsAt(result, 'src/stdx/stdx.zig', 2, 29)).toEqual([]); + expect(edgesAtSite(result, 'src/stdx/stdx.zig', 2, 29)).toEqual([ + 'ACCESSES File:src/stdx/stdx.zig -> Struct:src/stdx/bounded_array.zig:BoundedArrayType | import-resolved', + ]); + }); }, ); @@ -1623,3 +1805,92 @@ describe.skipIf(!zigAvailable)('Zig namespace factory result types (#3498)', () ).toEqual(targets); }); }); + +describe.skipIf(!zigAvailable)('Zig type-constructor receiver boundaries', () => { + let result: PipelineResult; + + beforeAll(async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-zig-type-boundaries-')); + try { + writeFixtureRepo(root, { + 'src/Math.zig': `count: u32 = 0, + +pub fn Wrapper(comptime T: type) type { + return if (@sizeOf(T) == 0) struct {} else struct { + pub fn get() void {} + }; +} +pub fn Bridge(comptime T: type) type { return Wrapper(T); } +pub fn use() void { Wrapper(u8).get(); } +pub fn use2() void { const b = Bridge(u8); b.get(); } +`, + 'src/other.zig': 'pub const Wrapper = struct { pub fn get() void {} };\n', + 'src/third.zig': 'pub const Unrelated = struct { pub fn get() void {} };\n', + 'src/lib.zig': 'pub const Counter = struct {};\npub fn work() void {}\n', + 'src/other_work.zig': 'pub fn work() void {}\n', + 'src/typed.zig': `pub fn typedImport() void { + const Counter: type = @import("lib.zig").Counter; + _ = Counter; +} +`, + 'src/other_local.zig': 'pub const Local = struct { pub fn get() void {} };\n', + 'src/namespaced.zig': `const local = @import("local.zig"); +pub fn namespacePositive() void { local.Local(u8).get(); } +`, + 'src/whitespace.zig': `pub fn entry() void { + const Counter = @import("lib.zig").Counter; + _ = Counter; + @import( "lib.zig" ).work(); +} +`, + 'src/local.zig': `pub fn Local(comptime T: type) type { + _ = T; + return struct { pub fn get() void {} }; +} +pub fn positive() void { Local(u8).get(); } +`, + }); + result = await runPipelineFromRepo(root, () => {}); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }, 120000); + + it.each(['use', 'use2'])('%s cannot borrow a class from an unimported file', (caller) => { + const externalTargets = getRelationships(result, 'CALLS') + .filter( + (edge) => + edge.source === caller && edge.target === 'get' && edge.targetFilePath !== 'src/Math.zig', + ) + .map((edge) => edge.rel.targetId); + expect(externalTargets).toEqual([]); + }); + + it('keeps the lexically bound type-application receiver', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'positive' && edge.target === 'get') + .map((edge) => edge.targetFilePath); + expect(targets).toEqual(['src/local.zig']); + }); + + it('resolves a differently spaced inline import after a member alias', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'entry' && edge.target === 'work') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/lib.zig', reason: 'import-resolved' }]); + }); + + it('reads a member through an explicitly typed import alias initializer', () => { + const targets = getRelationships(result, 'ACCESSES') + .filter((edge) => edge.source === 'typedImport' && edge.target === 'Counter') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/lib.zig', reason: 'import-resolved' }]); + }); + + it('keeps a namespace-qualified type application despite an unrelated namesake', () => { + const targets = getRelationships(result, 'CALLS') + .filter((edge) => edge.source === 'namespacePositive' && edge.target === 'get') + .map((edge) => ({ file: edge.targetFilePath, reason: edge.rel.reason })); + expect(targets).toEqual([{ file: 'src/local.zig', reason: 'import-resolved' }]); + }); +}); diff --git a/gitnexus/test/integration/ruby-import-index-reuse.test.ts b/gitnexus/test/integration/ruby-import-index-reuse.test.ts index aae9147f0f..25e5661c9c 100644 --- a/gitnexus/test/integration/ruby-import-index-reuse.test.ts +++ b/gitnexus/test/integration/ruby-import-index-reuse.test.ts @@ -2,7 +2,7 @@ * Production-path regression guard for the Ruby import-resolution index (#2880). * * Ruby's bare `require` leg reads the shared `getWorkspaceFileIndex` - * (`import-resolvers/workspace-file-index.ts`), memoized on the `allFilePaths` + * (`utils/workspace-file-index.ts`), memoized on the `allFilePaths` * Set identity via a WeakMap. Before #2880 every single `require` materialized * two arrays AND built a whole `buildSuffixIndex` over the repo, then threw it * away — the most expensive of the four resolvers hoisted. diff --git a/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts b/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts index a9293c50c2..1e7ccd173d 100644 --- a/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts +++ b/gitnexus/test/integration/run-analyze-invalidates-workspace-memo.test.ts @@ -13,14 +13,14 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; type Workspace = - typeof import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + typeof import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); type Lock = typeof import('../../src/storage/index-lock.js'); const ctx = vi.hoisted(() => ({ invalidate: vi.fn(), acquire: vi.fn(), })); vi.mock( - '../../src/core/ingestion/import-resolvers/node-workspace-packages.js', + '../../src/core/ingestion/languages/typescript/workspace-packages.js', async (importOriginal) => { const actual = await importOriginal(); ctx.invalidate.mockImplementation(actual.invalidateNodeWorkspacePackages); diff --git a/gitnexus/test/integration/rust-qualified-factory-boundaries.test.ts b/gitnexus/test/integration/rust-qualified-factory-boundaries.test.ts new file mode 100644 index 0000000000..b08b141d52 --- /dev/null +++ b/gitnexus/test/integration/rust-qualified-factory-boundaries.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; +import { TransitionalScopeTree } from '../../src/storage/scope-index-store.js'; + +describe('Rust qualified factory boundaries', () => { + it('keeps an alias type parameter out of the enclosing module', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-alias-parameter-')); + try { + await fs.writeFile( + path.join(root, 'main.rs'), + 'mod T { pub struct Product; impl Product { pub fn m(&self) {} } pub fn make() -> Product { Product } }\ntype Alias = Option;\nfn caller() { let x = T::make(); x.m(); }\n', + ); + const result = await runPipelineFromRepo(root, () => {}, {}); + const calls = [...result.graph.iterRelationships()].filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === 'caller', + ); + expect( + calls.map((edge) => result.graph.getNode(edge.targetId)?.properties.name).sort(), + ).toEqual(['m', 'make']); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, 120000); + it('retains the outer unresolved call when its member repeats the inner callee', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-qualified-repeat-')); + try { + await fs.writeFile( + path.join(root, 'main.rs'), + 'mod factory { pub fn untyped() {} }\nfn caller() { factory::untyped().untyped(); }\n', + ); + const result = await runPipelineFromRepo(root, () => {}, {}); + const drops = result.resolutionOutcomes.filter( + (outcome) => + outcome.kind === 'suppressed' && + outcome.reason === 'receiver-unresolved' && + outcome.siteKind === 'call' && + outcome.name === 'untyped', + ); + expect(drops).toHaveLength(1); + const calls = [...result.graph.iterRelationships()].filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === 'caller' && + result.graph.getNode(edge.targetId)?.properties.name === 'untyped', + ); + expect(calls).toHaveLength(1); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }, 120000); + + it('resolves a cold inline-only module after sealing disk scopes', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-qualified-disk-')); + const store = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-qualified-store-')); + const previous = process.env.GITNEXUS_DISK_SCOPE_INDEX; + const original = TransitionalScopeTree.prototype.seal; + let seals = 0; + TransitionalScopeTree.prototype.seal = function (...args: Parameters) { + seals++; + return original.apply(this, args); + }; + try { + process.env.GITNEXUS_DISK_SCOPE_INDEX = '1'; + await fs.writeFile( + path.join(root, 'main.rs'), + 'mod factory { pub fn untyped() {} }\nfn caller() { factory::untyped().m(); }\n', + ); + const result = await runPipelineFromRepo(root, () => {}, { parsedFileStorePath: store }); + expect(seals).toBe(1); + expect( + [...result.graph.iterRelationships()].filter( + (edge) => + edge.type === 'CALLS' && result.graph.getNode(edge.targetId)?.properties.name === 'm', + ), + ).toEqual([]); + expect( + result.resolutionOutcomes.some( + (outcome) => + outcome.kind === 'suppressed' && + outcome.reason === 'receiver-unresolved' && + outcome.siteKind === 'call' && + outcome.name === 'm', + ), + ).toBe(true); + } finally { + TransitionalScopeTree.prototype.seal = original; + if (previous === undefined) delete process.env.GITNEXUS_DISK_SCOPE_INDEX; + else process.env.GITNEXUS_DISK_SCOPE_INDEX = previous; + await fs.rm(root, { recursive: true, force: true }); + await fs.rm(store, { recursive: true, force: true }); + } + }, 120000); +}); diff --git a/gitnexus/test/integration/rust-qualified-factory-collisions.test.ts b/gitnexus/test/integration/rust-qualified-factory-collisions.test.ts new file mode 100644 index 0000000000..3a0a64dd03 --- /dev/null +++ b/gitnexus/test/integration/rust-qualified-factory-collisions.test.ts @@ -0,0 +1,60 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('Rust qualified factory lexical and declaration identity', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-factory-collisions-')); + await fs.mkdir(path.join(root, 'src')); + await fs.writeFile( + path.join(root, 'Cargo.toml'), + '[package]\nname="collisions"\nversion="0.1.0"\nedition="2021"\n', + ); + for (const [file, name] of [ + ['a', 'A'], + ['b', 'B'], + ]) + await fs.writeFile( + path.join(root, `src/${file}.rs`), + `pub struct ${name}; impl ${name} { pub fn m(&self) {} } pub fn make() -> ${name} { ${name} }`, + ); + await fs.writeFile( + path.join(root, 'src/model.rs'), + `#[allow(non_camel_case_types)] pub struct model; impl model { pub fn make() -> Self { Self } pub fn m(&self) {} } pub struct Wrong; impl Wrong { pub fn m(&self) {} } pub fn make() -> Wrong { Wrong }`, + ); + await fs.writeFile( + path.join(root, 'src/main.rs'), + ` +mod a; mod b; mod model; +use crate::a as factory; +use crate::model::model as Maker; +fn scoped_import() { use crate::b as factory; factory::make().m(); } +fn type_import() { Maker::make().m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + const targets = (caller: string, name: string) => + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === name, + ) + .map((edge) => edge.targetId); + it('uses the nearest module import', () => { + expect(targets('scoped_import', 'm')).toEqual(['Function:src/b.rs:B.m#0']); + }); + it('does not reinterpret a resolved type import as its module', () => { + expect(targets('type_import', 'm')).not.toContain('Function:src/model.rs:Wrong.m#0'); + expect(targets('type_import', 'make')).not.toContain('Function:src/model.rs:make'); + }); +}); diff --git a/gitnexus/test/integration/rust-qualified-factory-spellings.test.ts b/gitnexus/test/integration/rust-qualified-factory-spellings.test.ts new file mode 100644 index 0000000000..14afe393e2 --- /dev/null +++ b/gitnexus/test/integration/rust-qualified-factory-spellings.test.ts @@ -0,0 +1,65 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('Rust qualified factory spelling follows declarations', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-factory-spellings-')); + await fs.mkdir(path.join(root, 'src')); + await fs.writeFile( + path.join(root, 'Cargo.toml'), + '[package]\nname="spellings"\nversion="0.1.0"\nedition="2021"\n', + ); + await fs.writeFile( + path.join(root, 'src/Factory.rs'), + 'pub struct Upper; impl Upper { pub fn m(&self) {} } pub fn make() -> Upper { Upper }', + ); + await fs.writeFile( + path.join(root, 'src/módulo.rs'), + 'pub struct Unicode; impl Unicode { pub fn m(&self) {} } pub fn hacer() -> Unicode { Unicode } pub fn créer() -> Unicode { Unicode }', + ); + await fs.writeFile( + path.join(root, 'src/main.rs'), + ` +mod Factory; +mod módulo; +#[allow(non_camel_case_types)] struct lowercase_type; +impl lowercase_type { fn new() -> Self { Self } fn m(&self) {} } +#[derive(Default)] #[allow(non_camel_case_types)] struct derived_type; +impl derived_type { fn m(&self) {} } +struct Decoy; impl Decoy { fn m(&self) {} } +fn lower_type() { let x = lowercase_type::new(); x.m(); } +fn derived_default() { let x = derived_type::default(); x.m(); } +fn upper_module() { let x = Factory::make(); x.m(); } +fn unicode_module() { let x = módulo::hacer(); x.m(); } +fn unicode_function() { let x = módulo::créer(); x.m(); } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + it.each([ + ['lower_type', 'Function:src/main.rs:lowercase_type.m#0'], + ['derived_default', 'Function:src/main.rs:derived_type.m#0'], + ['upper_module', 'Function:src/Factory.rs:Upper.m#0'], + ['unicode_module', 'Function:src/módulo.rs:Unicode.m#0'], + ['unicode_function', 'Function:src/módulo.rs:Unicode.m#0'], + ])('%s resolves its declared receiver', (caller, target) => { + expect( + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId), + ).toEqual([target]); + }); +}); diff --git a/gitnexus/test/integration/rust-qualified-type-shadowing.test.ts b/gitnexus/test/integration/rust-qualified-type-shadowing.test.ts new file mode 100644 index 0000000000..3c7a2abba6 --- /dev/null +++ b/gitnexus/test/integration/rust-qualified-type-shadowing.test.ts @@ -0,0 +1,55 @@ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { runPipelineFromRepo } from '../../src/core/ingestion/pipeline.js'; + +describe('Rust qualified factory type shadows', () => { + let root: string; + let result: Awaited>; + beforeAll(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'rust-factory-type-shadow-')); + await fs.writeFile( + path.join(root, 'main.rs'), + ` +mod factory { pub struct Wrong; impl Wrong { pub fn m(&self) {} } pub fn make() -> Wrong { Wrong } } +mod módulo { pub struct UnicodeWrong; impl UnicodeWrong { pub fn m(&self) {} } pub fn make() -> UnicodeWrong { UnicodeWrong } } +struct Other; impl Other { fn make() -> Self { Self } fn m(&self) {} } +fn type_alias() { type factory = Other; let x = factory::make(); x.m(); } +fn type_parameter() { factory::make().m(); } +fn const_parameter() { factory::make().m(); } +fn unicode_type_parameter() { módulo::make().m(); } +struct ConstHolder; +impl ConstHolder { fn struct_const_parameter() { factory::make().m(); } } +`, + ); + result = await runPipelineFromRepo(root, () => {}, {}); + }, 120000); + afterAll(async () => { + if (root) await fs.rm(root, { recursive: true, force: true }); + }); + const targets = (caller: string) => + [...result.graph.iterRelationships()] + .filter( + (edge) => + edge.type === 'CALLS' && + result.graph.getNode(edge.sourceId)?.properties.name === caller && + result.graph.getNode(edge.targetId)?.properties.name === 'm', + ) + .map((edge) => edge.targetId); + it('does not borrow a module through a local type alias', () => { + expect(targets('type_alias')).toEqual([]); + }); + it('does not borrow a module through a type parameter', () => { + expect(targets('type_parameter')).toEqual([]); + }); + it('keeps a module path visible beside a const generic value', () => { + expect(targets('const_parameter')).toEqual(['Function:main.rs:factory.Wrong.m#0']); + }); + it('does not borrow a module through a Unicode type parameter', () => { + expect(targets('unicode_type_parameter')).toEqual([]); + }); + it('keeps a module visible beside an impl const generic', () => { + expect(targets('struct_const_parameter')).toEqual(['Function:main.rs:factory.Wrong.m#0']); + }); +}); diff --git a/gitnexus/test/unit/commonjs-module-kind.test.ts b/gitnexus/test/unit/commonjs-module-kind.test.ts new file mode 100644 index 0000000000..dbf1a66ad3 --- /dev/null +++ b/gitnexus/test/unit/commonjs-module-kind.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import Parser from 'tree-sitter'; +import TypeScript from 'tree-sitter-typescript'; +import JavaScript from 'tree-sitter-javascript'; +import { + javascriptProvider, + typescriptProvider, +} from '../../src/core/ingestion/languages/typescript.js'; +import { extractParsedFile } from '../../src/core/ingestion/scope-extractor-bridge.js'; +import { isCommonJsModule } from '../../src/core/ingestion/languages/typescript/cjs-export-assignment.js'; +import type { SyntaxNode } from '../../src/core/ingestion/utils/ast-helpers.js'; + +describe('deep CommonJS classification', () => { + it.each([false, true])('handles a deep expression with trailing ESM=%s', (esm) => { + const node = (type: string, namedChildren: SyntaxNode[], text = '') => + ({ type, namedChildren, text, childForFieldName: () => null }) as unknown as SyntaxNode; + let expression = node('identifier', [], 'module'); + for (let i = 0; i < 20000; i++) expression = node('binary_expression', [expression]); + const root = node('program', esm ? [expression, node('export_statement', [])] : [expression]); + expect(isCommonJsModule(root, 'deep.ts')).toBe(!esm); + }); +}); + +describe.each([ + ['JavaScript', javascriptProvider, JavaScript, 'js', 'cjs', 'mjs'], + ['TypeScript', typescriptProvider, TypeScript.typescript, 'ts', 'cts', 'mts'], +] as const)( + '%s module-kind capture', + (_, provider, grammar, extension, commonJsExtension, esmExtension) => { + it.each([ + ['module.exports.value = 1;', extension, true], + ['export {}; module.exports.value = 1;', extension, false], + ['import "./dep"; module.exports.value = 1;', extension, false], + ['export {}; module.exports.value = 1;', commonJsExtension, true], + ['module.exports.value = 1;', esmExtension, false], + ] as const)('carries %j in .%s as %s through serialization', (source, suffix, expected) => { + const parser = new Parser(); + parser.setLanguage(grammar); + const tree = parser.parse(source); + const filePath = `module.${suffix}`; + const parsed = extractParsedFile(provider, source, filePath, undefined, tree); + expect(parsed).toBeDefined(); + const channel = provider.collectCaptureSideChannel?.(filePath); + expect(channel).toBe(expected); + expect( + JSON.parse(JSON.stringify({ ...parsed, captureSideChannel: channel })).captureSideChannel, + ).toBe(expected); + expect(provider.collectCaptureSideChannel?.(filePath)).toBeUndefined(); + }); + }, +); diff --git a/gitnexus/test/unit/dart-import-resolver.test.ts b/gitnexus/test/unit/dart-import-resolver.test.ts index 938c88913d..d38ec555cb 100644 --- a/gitnexus/test/unit/dart-import-resolver.test.ts +++ b/gitnexus/test/unit/dart-import-resolver.test.ts @@ -1,154 +1,6 @@ -/** - * Unit tests for the production Dart import resolution strategies. - * - * Tests dartPackageStrategy and dartRelativeStrategy from configs/dart.ts — - * the actual strategies composed by createImportResolver(dartImportConfig). - * - * Key behavioral note: - * - dartPackageStrategy returns { kind: 'files', files: [] } (absorbing sentinel) - * for dart: SDK imports and unresolved external packages, which stops the - * strategy chain. This differs from the old monolithic resolver that returned null. - * Both produce zero import edges at runtime (applyImportResult treats them identically). - */ - import { describe, it, expect } from 'vitest'; import { emitDartScopeCaptures } from '../../src/core/ingestion/languages/dart/captures.js'; import { interpretDartImport } from '../../src/core/ingestion/languages/dart/interpret.js'; -import { - dartPackageStrategy, - dartRelativeStrategy, -} from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { createImportResolver } from '../../src/core/ingestion/import-resolvers/resolver-factory.js'; -import { dartImportConfig } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import type { ResolveCtx } from '../../src/core/ingestion/import-resolvers/types.js'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; - -function makeCtx(files: string[]): ResolveCtx { - const allFileList = files; - const normalizedFileList = files.map((f) => f.replace(/\\/g, '/')); - const index = buildSuffixIndex(normalizedFileList, allFileList); - return { - allFilePaths: new Set(files), - allFileList, - normalizedFileList, - index, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, - }; -} - -// --------------------------------------------------------------------------- -// dartPackageStrategy — absorbs SDK / external package imports -// --------------------------------------------------------------------------- - -describe('dartPackageStrategy', () => { - describe('dart: SDK imports', () => { - it('absorbs dart:async with empty-files sentinel', () => { - const result = dartPackageStrategy("'dart:async'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs dart:io with empty-files sentinel', () => { - const result = dartPackageStrategy("'dart:io'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); - - describe('package: imports', () => { - it('resolves local package import to lib/', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = dartPackageStrategy("'package:my_app/models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('absorbs external package imports with empty-files sentinel', () => { - const ctx = makeCtx(['lib/main.dart']); - const result = dartPackageStrategy("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs malformed package import (no slash) with empty-files sentinel', () => { - const result = dartPackageStrategy("'package:http'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); - - describe('relative imports', () => { - it('returns null for relative imports (chains to dartRelativeStrategy)', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'models.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); - }); - - describe('quote stripping', () => { - it('strips single quotes', () => { - const result = dartPackageStrategy("'dart:core'", 'lib/main.dart', makeCtx([])); - // dart: is absorbed, proving quotes were stripped - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('strips double quotes', () => { - const result = dartPackageStrategy('"dart:core"', 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - }); -}); - -// --------------------------------------------------------------------------- -// dartRelativeStrategy — bare relative paths via standard resolution -// --------------------------------------------------------------------------- - -describe('dartRelativeStrategy', () => { - it('resolves bare relative path by prepending ./', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = dartRelativeStrategy("'./models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('returns null for unresolvable relative import', () => { - const ctx = makeCtx([]); - const result = dartRelativeStrategy("'nonexistent.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Full resolver — dartImportConfig composed via factory -// --------------------------------------------------------------------------- - -describe('Dart import resolver (full config)', () => { - const resolve = createImportResolver(dartImportConfig); - - it('absorbs dart: SDK imports', () => { - const result = resolve("'dart:async'", 'lib/main.dart', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('resolves local package: import', () => { - const ctx = makeCtx(['lib/models/user.dart']); - const result = resolve("'package:my_app/models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); - - it('absorbs external package: import', () => { - const ctx = makeCtx(['lib/main.dart']); - const result = resolve("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('resolves relative import via second strategy', () => { - const ctx = makeCtx(['lib/models/user.dart', 'lib/main.dart']); - const result = resolve("'./models/user.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: ['lib/models/user.dart'] }); - }); -}); describe('Dart import prefix semantic captures', () => { it('keeps prefixed imports as namespace handles and ordinary imports as wildcards', () => { diff --git a/gitnexus/test/unit/esm-extension-resolution.test.ts b/gitnexus/test/unit/esm-extension-resolution.test.ts deleted file mode 100644 index 7948880498..0000000000 --- a/gitnexus/test/unit/esm-extension-resolution.test.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Unit tests for TypeScript ESM .js extension resolution. - * - * TypeScript ESM requires imports to use .js extensions even when source - * files are .ts. The resolver must map .js → .ts (and .jsx → .tsx, - * .mjs → .mts, .cjs → .cts) when the literal .js file does not exist. - */ - -import { describe, it, expect } from 'vitest'; -import { resolveImportPath } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { stripJsExtension } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; -import { SupportedLanguages } from 'gitnexus-shared'; - -function makeCtx(files: string[]) { - // Match production normalization: only replace backslashes with forward slashes - const normalized = files.map((f) => f.replace(/\\/g, '/')); - const allFilesSet = new Set(files); - const index = buildSuffixIndex(normalized, files); - const cache = new Map(); - return { files, normalized, allFilesSet, index, cache }; -} - -function resolve( - currentFile: string, - importPath: string, - language: SupportedLanguages, - ctx: ReturnType, -): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - language, - null, - ctx.index, - ); -} - -describe('TypeScript ESM .js extension resolution', () => { - it('resolves ./utils.js to ./utils.ts when .js does not exist', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.ts']); - const result = resolve('src/index.ts', './utils.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/utils.ts'); - }); - - it('resolves ./component.jsx to ./component.tsx', () => { - const ctx = makeCtx(['src/app.ts', 'src/component.tsx']); - const result = resolve('src/app.ts', './component.jsx', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/component.tsx'); - }); - - it('resolves ./config.mjs to ./config.mts', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.mts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.mts'); - }); - - it('resolves ./legacy.cjs to ./legacy.cts', () => { - const ctx = makeCtx(['src/index.ts', 'src/legacy.cts']); - const result = resolve('src/index.ts', './legacy.cjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/legacy.cts'); - }); - - it('prefers actual .js file when it exists', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.js', 'src/utils.ts']); - const result = resolve('src/index.ts', './utils.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/utils.js'); - }); - - it('resolves relative path with ../ and .js extension', () => { - const ctx = makeCtx(['src/helpers/token.ts', 'src/core/engine.ts']); - const result = resolve( - 'src/core/engine.ts', - '../helpers/token.js', - SupportedLanguages.TypeScript, - ctx, - ); - expect(result).toBe('src/helpers/token.ts'); - }); - - it('works for JavaScript language too', () => { - const ctx = makeCtx(['src/index.js', 'src/utils.ts']); - const result = resolve('src/index.js', './utils.js', SupportedLanguages.JavaScript, ctx); - expect(result).toBe('src/utils.ts'); - }); - - it('does NOT apply ESM fallback for non-TS/JS languages', () => { - const ctx = makeCtx(['src/main.py', 'src/utils.ts']); - const result = resolve('src/main.py', './utils.js', SupportedLanguages.Python, ctx); - expect(result).toBeNull(); - }); - - it('returns null when neither .js nor .ts exists', () => { - const ctx = makeCtx(['src/index.ts']); - const result = resolve('src/index.ts', './missing.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBeNull(); - }); -}); - -describe('ESM extension resolution — .mjs/.cjs with competing siblings', () => { - it('resolves ./config.mjs to .ts when only .ts exists (no .mts)', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.ts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - // .ts wins because EXTENSIONS order tries .ts before .mts - expect(result).toBe('src/config.ts'); - }); - - it('resolves ./config.mjs to .mts when both .ts and .mts exist', () => { - // Note: EXTENSIONS order is .tsx, .ts, .mts, .cts — so .ts wins over .mts. - // This is intentional for a source-analysis tool: we resolve to the first - // matching source file. In practice, having both config.ts and config.mts - // in the same directory is extremely rare. - const ctx = makeCtx(['src/index.ts', 'src/config.ts', 'src/config.mts']); - const result = resolve('src/index.ts', './config.mjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.ts'); - }); - - it('resolves ./config.cjs to .cts when only .cts exists', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.cts']); - const result = resolve('src/index.ts', './config.cjs', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/config.cts'); - }); -}); - -describe('ESM extension resolution — directory index boundary', () => { - it('resolves ./dir.js to dir/index.ts when dir/ exists (bundler-mode)', () => { - // After stripping .js from "dir.js" → "dir", tryResolveWithExtensions probes - // "/index.ts" suffix. This matches bundler-mode behavior where bare directory - // imports resolve to index files. Intentional for source-analysis compatibility. - const ctx = makeCtx(['src/index.ts', 'src/dir/index.ts']); - const result = resolve('src/index.ts', './dir.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/dir/index.ts'); - }); - - it('resolves ./dir/index.js to dir/index.ts', () => { - const ctx = makeCtx(['src/index.ts', 'src/dir/index.ts']); - const result = resolve('src/index.ts', './dir/index.js', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/dir/index.ts'); - }); -}); - -describe('stripJsExtension', () => { - it('strips .js', () => expect(stripJsExtension('foo/bar.js')).toBe('foo/bar')); - it('strips .jsx', () => expect(stripJsExtension('foo/bar.jsx')).toBe('foo/bar')); - it('strips .mjs', () => expect(stripJsExtension('foo/bar.mjs')).toBe('foo/bar')); - it('strips .cjs', () => expect(stripJsExtension('foo/bar.cjs')).toBe('foo/bar')); - it('returns null for .ts', () => expect(stripJsExtension('foo/bar.ts')).toBeNull()); - it('returns null for no extension', () => expect(stripJsExtension('foo/bar')).toBeNull()); -}); - -describe('ESM extension resolution — path aliases with .js extensions', () => { - const aliasAtToSrc = new Map([['@/', 'src/']]); - const aliasTildeToSrc = new Map([['~/', 'src/']]); - - function resolveWithAlias( - currentFile: string, - importPath: string, - ctx: ReturnType, - aliases: Map, - baseUrl = '.', - ): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - SupportedLanguages.TypeScript, - { aliases, baseUrl }, - ctx.index, - ); - } - - it('resolves @/utils.js to src/utils.ts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.ts']); - const result = resolveWithAlias('src/index.ts', '@/utils.js', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/utils.ts'); - }); - - it('resolves @/component.jsx to src/component.tsx via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/component.tsx']); - const result = resolveWithAlias('src/index.ts', '@/component.jsx', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/component.tsx'); - }); - - it('resolves @/config.mjs to src/config.mts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/config.mts']); - const result = resolveWithAlias('src/index.ts', '@/config.mjs', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/config.mts'); - }); - - it('resolves @/legacy.cjs to src/legacy.cts via alias', () => { - const ctx = makeCtx(['src/index.ts', 'src/legacy.cts']); - const result = resolveWithAlias('src/index.ts', '@/legacy.cjs', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/legacy.cts'); - }); - - it('prefers actual .js file over TS fallback in alias resolution', () => { - const ctx = makeCtx(['src/index.ts', 'src/utils.js', 'src/utils.ts']); - const result = resolveWithAlias('src/index.ts', '@/utils.js', ctx, aliasAtToSrc, '.'); - expect(result).toBe('src/utils.js'); - }); - - it('resolves alias with baseUrl prefix', () => { - const ctx = makeCtx(['app/src/index.ts', 'app/src/helpers/token.ts']); - const result = resolveWithAlias( - 'app/src/index.ts', - '~/helpers/token.js', - ctx, - aliasTildeToSrc, - 'app', - ); - expect(result).toBe('app/src/helpers/token.ts'); - }); - - it('returns null when alias .js import has no matching source', () => { - const ctx = makeCtx(['src/index.ts']); - const result = resolveWithAlias('src/index.ts', '@/missing.js', ctx, aliasAtToSrc, '.'); - expect(result).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/field-extraction.test.ts b/gitnexus/test/unit/field-extraction.test.ts index 12d1d481e3..07a64d7fdf 100644 --- a/gitnexus/test/unit/field-extraction.test.ts +++ b/gitnexus/test/unit/field-extraction.test.ts @@ -1,7 +1,10 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { TypeScriptFieldExtractor } from '../../src/core/ingestion/field-extractors/typescript.js'; import { createFieldExtractor } from '../../src/core/ingestion/field-extractors/generic.js'; -import { typescriptConfig } from '../../src/core/ingestion/field-extractors/configs/typescript-javascript.js'; +import { + javascriptConfig, + typescriptConfig, +} from '../../src/core/ingestion/field-extractors/configs/typescript-javascript.js'; import { pythonConfig } from '../../src/core/ingestion/field-extractors/configs/python.js'; import { goConfig } from '../../src/core/ingestion/field-extractors/configs/go.js'; import { cppConfig } from '../../src/core/ingestion/field-extractors/configs/c-cpp.js'; @@ -9,11 +12,15 @@ import { rubyConfig } from '../../src/core/ingestion/field-extractors/configs/ru import { dartConfig } from '../../src/core/ingestion/field-extractors/configs/dart.js'; import { javaConfig, kotlinConfig } from '../../src/core/ingestion/field-extractors/configs/jvm.js'; import { swiftConfig } from '../../src/core/ingestion/field-extractors/configs/swift.js'; -import type { FieldExtractorContext } from '../../src/core/ingestion/field-types.js'; +import type { + ExtractedFields, + FieldExtractorContext, +} from '../../src/core/ingestion/field-types.js'; import type { TypeEnvironment } from '../../src/core/ingestion/type-env.js'; import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.js'; import Parser from 'tree-sitter'; import TypeScript from 'tree-sitter-typescript'; +import JavaScript from 'tree-sitter-javascript'; import Python from 'tree-sitter-python'; import Go from 'tree-sitter-go'; import Cpp from 'tree-sitter-cpp'; @@ -1501,3 +1508,63 @@ describeSwift('GenericFieldExtractor — Swift (F75 protocol property requiremen expect(matches[0].type).toBe('String'); }); }); + +// A JS/TS field with no declared type is typed only by what its initializer +// constructs. The scope query binds that type for an INSTANCE field, but a +// static field's binding is kept out of the class scope (it would retype an +// instance field of the same name), so the field extractor records it on the +// field instead, for the Property node. A declared type, when present, is the +// type, and nothing is recorded beside it. +describe('field initializer type (JS/TS)', () => { + const javascriptExtractor = createFieldExtractor(javascriptConfig); + const typescriptExtractor = new TypeScriptFieldExtractor(); + const context = createMockContext(); + const initializerTypeOf = ( + language: Parser.Language, + extract: (node: Parser.SyntaxNode) => ExtractedFields | null, + source: string, + field: string, + ): string | undefined => { + const classParser = new Parser(); + classParser.setLanguage(language); + const [classNode] = classParser.parse(source).rootNode.namedChildren; + return extract(classNode)?.fields.find((f) => f.name === field)?.initializerType; + }; + + it.each([ + ['static DEFAULT = new Config();', 'DEFAULT', 'Config'], + ['static repo = new models.Repo();', 'repo', 'models.Repo'], + ['p = new Outer();', 'p', 'Outer'], + ['#q = new Outer();', '#q', 'Outer'], + ['static n = 5;', 'n', undefined], + ['static made = make();', 'made', undefined], + ['static bare;', 'bare', undefined], + ])('JavaScript `%s` -> %s: %s', (member, field, expected) => { + expect( + initializerTypeOf( + JavaScript, + (node) => javascriptExtractor.extract(node, context), + `class C { ${member} }`, + field, + ), + ).toBe(expected); + }); + + it.each([ + ['static DEFAULT = new Config();', 'DEFAULT', 'Config'], + ['static repo = new models.Repo();', 'repo', 'models.Repo'], + ['private p = new Outer();', 'p', 'Outer'], + ['static r: Alien = new Alien();', 'r', undefined], + ['static n = 5;', 'n', undefined], + ['static made = make();', 'made', undefined], + ])('TypeScript `%s` -> %s: %s', (member, field, expected) => { + expect( + initializerTypeOf( + TypeScript.typescript, + (node) => typescriptExtractor.extract(node, context), + `class C { ${member} }`, + field, + ), + ).toBe(expected); + }); +}); diff --git a/gitnexus/test/unit/import-path-candidates.test.ts b/gitnexus/test/unit/import-path-candidates.test.ts new file mode 100644 index 0000000000..fd5fbe0bc8 --- /dev/null +++ b/gitnexus/test/unit/import-path-candidates.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; +import { + buildSuffixIndex, + suffixResolve, + tryResolveWithExtensions, +} from '../../src/core/ingestion/utils/suffix-index.js'; + +describe('caller-owned import path candidates', () => { + const files = ['pkg/item.alpha', 'pkg/item.beta']; + const extensions = ['.beta', '.alpha']; + + it('uses the caller priority and refuses extensions the caller did not select', () => { + const paths = new Set(files); + expect(tryResolveWithExtensions('pkg/item', paths, extensions)).toBe('pkg/item.beta'); + expect(tryResolveWithExtensions('pkg/item', paths, ['.missing'])).toBeNull(); + }); + + it.each(['indexed', 'linear'])('uses the same candidate policy for %s suffix lookup', (mode) => { + const index = mode === 'indexed' ? buildSuffixIndex(files, files) : undefined; + expect(suffixResolve(['item'], files, files, extensions, index)).toBe('pkg/item.beta'); + expect(suffixResolve(['item'], files, files, ['.missing'], index)).toBeNull(); + }); +}); diff --git a/gitnexus/test/unit/import-resolver-factory.test.ts b/gitnexus/test/unit/import-resolver-factory.test.ts deleted file mode 100644 index 90c0c5d955..0000000000 --- a/gitnexus/test/unit/import-resolver-factory.test.ts +++ /dev/null @@ -1,655 +0,0 @@ -/** - * Unit tests for the import resolver factory and per-strategy composition. - * - * Validates that: - * - createImportResolver chains strategies in order - * - First non-null result wins - * - Empty files array stops the chain (absorbing sentinel) - * - All per-language configs produce valid resolvers - */ - -import { describe, it, expect } from 'vitest'; -import { createImportResolver } from '../../src/core/ingestion/import-resolvers/resolver-factory.js'; -import { createStandardStrategy } from '../../src/core/ingestion/import-resolvers/standard.js'; -import type { - ImportResolutionConfig, - ImportResolverStrategy, - ResolveCtx, -} from '../../src/core/ingestion/import-resolvers/types.js'; -import { SupportedLanguages } from 'gitnexus-shared'; -import { buildSuffixIndex } from '../../src/core/ingestion/import-resolvers/utils.js'; - -// ── Per-language strategy imports (from config files) ────────────────── -import { goPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/go.js'; -import { - javaJvmStrategy, - kotlinJvmStrategy, -} from '../../src/core/ingestion/import-resolvers/configs/jvm.js'; -import { pythonImportStrategy } from '../../src/core/ingestion/import-resolvers/configs/python.js'; -import { csharpNamespaceStrategy } from '../../src/core/ingestion/import-resolvers/configs/csharp.js'; -import { dartPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { rustModuleStrategy } from '../../src/core/ingestion/import-resolvers/configs/rust.js'; -import { phpPsr4Strategy } from '../../src/core/ingestion/import-resolvers/configs/php.js'; -import { swiftPackageStrategy } from '../../src/core/ingestion/import-resolvers/configs/swift.js'; -import { rubyRequireStrategy } from '../../src/core/ingestion/import-resolvers/configs/ruby.js'; - -// ── Per-language config imports ──────────────────────────────────────── -import { - typescriptImportConfig, - javascriptImportConfig, - vueImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/typescript-javascript.js'; -import { - cImportConfig, - cppImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/c-cpp.js'; -import { goImportConfig } from '../../src/core/ingestion/import-resolvers/configs/go.js'; -import { - javaImportConfig, - kotlinImportConfig, -} from '../../src/core/ingestion/import-resolvers/configs/jvm.js'; -import { pythonImportConfig } from '../../src/core/ingestion/import-resolvers/configs/python.js'; -import { rustImportConfig } from '../../src/core/ingestion/import-resolvers/configs/rust.js'; -import { csharpImportConfig } from '../../src/core/ingestion/import-resolvers/configs/csharp.js'; -import { phpImportConfig } from '../../src/core/ingestion/import-resolvers/configs/php.js'; -import { swiftImportConfig } from '../../src/core/ingestion/import-resolvers/configs/swift.js'; -import { dartImportConfig } from '../../src/core/ingestion/import-resolvers/configs/dart.js'; -import { rubyImportConfig } from '../../src/core/ingestion/import-resolvers/configs/ruby.js'; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -function makeCtx(files: string[], overrides: Partial = {}): ResolveCtx { - const allFileList = files; - const normalizedFileList = files.map((p) => p.replace(/\\/g, '/')); - const allFilePaths = new Set(allFileList); - const index = buildSuffixIndex(normalizedFileList, allFileList); - return { - allFilePaths, - allFileList, - normalizedFileList, - index, - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - ...overrides, - }, - }; -} - -// --------------------------------------------------------------------------- -// createImportResolver — factory behavior -// --------------------------------------------------------------------------- - -describe('createImportResolver', () => { - it('returns null when no strategies match', () => { - const config: ImportResolutionConfig = { - language: SupportedLanguages.TypeScript, - strategies: [], - }; - const resolver = createImportResolver(config); - expect(resolver('./foo', 'src/index.ts', makeCtx([]))).toBeNull(); - }); - - it('returns first non-null result from strategy chain', () => { - const strategyA: ImportResolverStrategy = () => null; - const strategyB: ImportResolverStrategy = () => ({ kind: 'files', files: ['b.ts'] }); - const strategyC: ImportResolverStrategy = () => ({ kind: 'files', files: ['c.ts'] }); - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [strategyA, strategyB, strategyC], - }); - - const result = resolver('./foo', 'src/index.ts', makeCtx(['b.ts', 'c.ts'])); - expect(result).toEqual({ kind: 'files', files: ['b.ts'] }); - }); - - it('stops chain when strategy returns result with empty files (absorbing sentinel)', () => { - const absorber: ImportResolverStrategy = () => ({ kind: 'files', files: [] }); - const shouldNotRun: ImportResolverStrategy = () => ({ - kind: 'files', - files: ['should-not.ts'], - }); - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [absorber, shouldNotRun], - }); - - const result = resolver('./foo', 'src/index.ts', makeCtx([])); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('passes correct arguments to strategies', () => { - const ctx = makeCtx(['src/utils.ts']); - const captured: { raw: string; fp: string }[] = []; - - const spy: ImportResolverStrategy = (raw, fp) => { - captured.push({ raw, fp }); - return null; - }; - - const resolver = createImportResolver({ - language: SupportedLanguages.TypeScript, - strategies: [spy], - }); - - resolver('./utils', 'src/index.ts', ctx); - expect(captured).toEqual([{ raw: './utils', fp: 'src/index.ts' }]); - }); -}); - -// --------------------------------------------------------------------------- -// Per-language strategies — behavioral coverage -// -// The previous `typeof strategy === 'function'` assertions were tautological: -// TypeScript's `ImportResolverStrategy` type enforces the function shape at -// compile time, so those tests could never fail. Each strategy now has at -// least one behavioral assertion below; the Go and C# full-chain tests also -// double as strategy-order guards because their `kind: 'package'` output is -// unreachable through `createStandardStrategy`. -// --------------------------------------------------------------------------- - -describe('goPackageStrategy', () => { - it('resolves go.mod package imports to a package result with dirSuffix', () => { - const files = ['cmd/server/main.go', 'cmd/server/handler.go']; - const ctx = makeCtx(files, { goModule: { modulePath: 'example.com/app' } }); - - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - // `kind: 'package'` + `dirSuffix` is unique to goPackageStrategy — the - // standard strategy always returns `kind: 'files'`. Asserting the exact - // shape makes format regressions observable (e.g. prefix/suffix slash - // normalization) and makes strategy ordering observable via the - // full-chain test in `goImportConfig` below. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/cmd/server/', - }); - }); - - it('returns null for imports outside the go module (allows chain to continue)', () => { - const ctx = makeCtx(['vendor/other/pkg/foo.go'], { - goModule: { modulePath: 'example.com/app' }, - }); - const result = goPackageStrategy('github.com/other/pkg', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('returns null when goModule is not configured', () => { - const ctx = makeCtx(['cmd/server/main.go']); - expect(ctx.configs.goModule).toBeNull(); - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('returns null when module prefix matches but package directory has no .go files', () => { - // Documented fall-through in configs/go.ts:27 — when resolveGoPackageDir - // returns non-null but resolveGoPackage returns an empty files list - // (external module coincidentally sharing the prefix, or a subpackage with - // no .go sources), the strategy returns null so the chain can continue. - const ctx = makeCtx(['README.md', 'cmd/server/config.yaml'], { - goModule: { modulePath: 'example.com/app' }, - }); - const result = goPackageStrategy('example.com/app/cmd/server', 'main.go', ctx); - expect(result).toBeNull(); - }); - - it('goImportConfig full chain produces the package-kind result (strategy-order guard)', () => { - const files = ['cmd/server/main.go', 'cmd/server/handler.go']; - const ctx = makeCtx(files, { goModule: { modulePath: 'example.com/app' } }); - - const resolver = createImportResolver(goImportConfig); - const result = resolver('example.com/app/cmd/server', 'main.go', ctx); - // If goPackageStrategy were moved after createStandardStrategy, the - // standard strategy's suffix resolution would return a single file with - // `kind: 'files'` (or null), not `kind: 'package'` with a dirSuffix. - // Asserting the full shape (not just kind) guards against a future - // regression that emits `kind: 'package'` with mismatched files. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/cmd/server/', - }); - }); -}); - -describe('javaJvmStrategy', () => { - it('resolves wildcard imports to .java files in the package directory', () => { - const files = [ - 'src/main/java/com/example/foo/Bar.java', - 'src/main/java/com/example/foo/Baz.java', - 'src/main/java/com/example/other/Unrelated.java', - ]; - const ctx = makeCtx(files); - const result = javaJvmStrategy('com.example.foo.*', 'App.java', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'src/main/java/com/example/foo/Bar.java', - 'src/main/java/com/example/foo/Baz.java', - ]), - ); - expect(result?.files).not.toContain('src/main/java/com/example/other/Unrelated.java'); - }); - - it('resolves member imports to the owning class file', () => { - const files = ['src/main/java/com/example/Constants.java']; - const ctx = makeCtx(files); - // JVM member import: last segment is an ALL_CAPS constant / lowercase - // member; resolver walks back to the class path `com/example/Constants`. - const result = javaJvmStrategy('com.example.Constants.VALUE', 'App.java', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no matching .java files exist', () => { - const ctx = makeCtx(['src/main/java/other/Foo.java']); - const result = javaJvmStrategy('com.example.missing.*', 'App.java', ctx); - expect(result).toBeNull(); - }); -}); - -describe('kotlinJvmStrategy', () => { - it('resolves wildcard imports to files in the package directory', () => { - const files = [ - 'src/main/kotlin/com/example/foo/Bar.kt', - 'src/main/kotlin/com/example/foo/Baz.kt', - 'src/main/kotlin/com/example/other/Unrelated.kt', - ]; - const ctx = makeCtx(files); - - const result = kotlinJvmStrategy('com.example.foo.*', 'App.kt', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'src/main/kotlin/com/example/foo/Bar.kt', - 'src/main/kotlin/com/example/foo/Baz.kt', - ]), - ); - expect(result?.files).not.toContain('src/main/kotlin/com/example/other/Unrelated.kt'); - }); - - it('resolves member imports to the owning class file', () => { - const files = ['src/main/kotlin/com/example/Constants.kt']; - const ctx = makeCtx(files); - const result = kotlinJvmStrategy('com.example.Constants.VALUE', 'App.kt', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null for wildcard with no matching files (allows chain to continue)', () => { - const ctx = makeCtx(['src/main/kotlin/com/example/other/Foo.kt']); - const result = kotlinJvmStrategy('com.example.missing.*', 'App.kt', ctx); - expect(result).toBeNull(); - }); - - it('kotlinImportConfig full chain resolves wildcard via the JVM strategy', () => { - // Note: this is a behavioral smoke test, NOT a strategy-order guard. - // `createStandardStrategy(Kotlin)` explicitly returns null for any import - // ending in `.*` (see standard.ts:137), so reordering `kotlinImportConfig` - // strategies would still produce the same result — the standard strategy - // would return null and the chain would fall through to kotlinJvmStrategy - // regardless of position. A genuine ordering guard for Kotlin would need - // a non-wildcard fixture where both strategies resolve to different files. - const files = ['src/main/kotlin/com/example/foo/Bar.kt']; - const ctx = makeCtx(files); - const resolver = createImportResolver(kotlinImportConfig); - const result = resolver('com.example.foo.*', 'App.kt', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); -}); - -describe('rustModuleStrategy', () => { - it('resolves scoped grouped imports to per-item files', () => { - const files = ['src/models/User.rs', 'src/models/Repo.rs']; - const ctx = makeCtx(files); - // `use crate::models::{User, Repo}` — the strategy resolves each item - // individually against the allFilePaths set via resolveRustImportInternal. - const result = rustModuleStrategy('crate::models::{User, Repo}', 'src/lib.rs', ctx); - // Exact file discovery depends on resolveRustImportInternal's search - // heuristics; we assert the shape + that at least one item resolved. - expect(result?.kind).toBe('files'); - expect(result?.files.length).toBeGreaterThan(0); - }); - - it('returns null for non-grouped imports (delegates to standard fallback)', () => { - const ctx = makeCtx(['src/models.rs']); - // Plain `use crate::models` — rustModuleStrategy only handles grouped - // forms; standard strategy handles the crate:: -> path translation. - const result = rustModuleStrategy('crate::models', 'src/lib.rs', ctx); - expect(result).toBeNull(); - }); -}); - -describe('csharpNamespaceStrategy', () => { - it('resolves namespace imports via .csproj root-namespace mapping', () => { - const files = ['src/Services/Auth/AuthService.cs', 'src/Services/Auth/TokenService.cs']; - const ctx = makeCtx(files, { - csharpConfigs: [{ rootNamespace: 'MyCo', projectDir: 'src' }], - }); - - const result = csharpNamespaceStrategy('MyCo.Services.Auth', 'App.cs', ctx); - // Multi-file namespace resolution produces `kind: 'package'` with - // dirSuffix — unique to csharpNamespaceStrategy; the standard strategy - // always emits `kind: 'files'`. Asserting the full shape (including the - // exact dirSuffix format) guards against format regressions. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/src/Services/Auth/', - }); - }); - - it('returns null when no csharpConfigs are configured', () => { - const ctx = makeCtx(['src/Services/Auth/AuthService.cs']); - expect(ctx.configs.csharpConfigs).toEqual([]); - const result = csharpNamespaceStrategy('MyCo.Services.Auth', 'App.cs', ctx); - expect(result).toBeNull(); - }); - - it('no csproj + non-aligned BCL import: stops the chain instead of the ungated standard strategy (#2)', () => { - // Parity with the registry leg's no-csproj path. Without csproj configs the - // generic strategy would suffix-match `System.Threading.Tasks` onto the - // coincidental local `Legacy/Tasks.cs`. The gate sees the import aligns - // with no declared namespace, so the strategy returns an absorbing sentinel - // (`{ kind: 'files', files: [] }`) that STOPS the chain — the standard - // strategy never runs and no spurious edge is emitted. - const ctx = makeCtx(['Services/OrderService.cs', 'Legacy/Tasks.cs'], { - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Services', 'MyApp.Legacy']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy( - 'System.Threading.Tasks', - 'Services/OrderService.cs', - ctx, - ); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('no csproj + in-repo-aligned import: keeps delegating to the standard strategy (#2)', () => { - // An import that DOES align with a declared namespace must keep returning - // null so the generic strategy resolves it — legitimate no-csproj behavior - // is unchanged; only non-aligned (BCL) imports are stopped. - const ctx = makeCtx(['Services/OrderService.cs', 'Models/User.cs'], { - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Models', 'MyApp.Services']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy('MyApp.Models', 'Services/OrderService.cs', ctx); - expect(result).toBeNull(); - }); - - it('returns an empty files result (chain-stop) for a gated BCL import when csproj configs exist (#1881, #8)', () => { - // Legacy DAG leg of #1881: with csproj configs present, a BCL using like - // `System.Threading.Tasks` must NOT suffix-match the coincidental local - // `Legacy/Tasks.cs`. The strategy returns `{ kind: 'files', files: [] }` - // (absorbing sentinel) to STOP the chain, NOT null — null would let the - // generic suffix fallback re-introduce the spurious edge. - const ctx = makeCtx(['Services/OrderService.cs', 'Legacy/Tasks.cs'], { - csharpConfigs: [{ rootNamespace: 'MyApp', projectDir: '' }], - csharpNamespaces: { - declaredNamespaces: new Set(['MyApp.Services', 'MyApp.Legacy']), - rootNamespaces: new Set(['MyApp']), - truncated: false, - }, - }); - const result = csharpNamespaceStrategy( - 'System.Threading.Tasks', - 'Services/OrderService.cs', - ctx, - ); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('csharpImportConfig full chain produces package-kind (strategy-order guard)', () => { - const files = ['src/Services/Auth/AuthService.cs', 'src/Services/Auth/TokenService.cs']; - const ctx = makeCtx(files, { - csharpConfigs: [{ rootNamespace: 'MyCo', projectDir: 'src' }], - }); - - const resolver = createImportResolver(csharpImportConfig); - const result = resolver('MyCo.Services.Auth', 'App.cs', ctx); - // If csharpNamespaceStrategy were reordered after createStandardStrategy, - // the result would be `kind: 'files'` (suffix match) or null, never - // `kind: 'package'` with a dirSuffix. Asserting the full shape (not just - // kind) guards against a regression that emits `kind: 'package'` with - // mismatched files. - expect(result).toEqual({ - kind: 'package', - files: expect.arrayContaining(files), - dirSuffix: '/src/Services/Auth/', - }); - }); -}); - -describe('phpPsr4Strategy', () => { - it('resolves PSR-4 namespace imports via composer.json autoload map', () => { - const files = ['app/Services/UserService.php']; - const ctx = makeCtx(files, { - composerConfig: { - psr4: new Map([['App\\', 'app/']]), - }, - }); - const result = phpPsr4Strategy('App\\Services\\UserService', 'index.php', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no file matches the namespace via PSR-4 or suffix fallback', () => { - const ctx = makeCtx(['app/Services/OtherService.php'], { - composerConfig: { psr4: new Map([['App\\', 'app/']]) }, - }); - const result = phpPsr4Strategy('App\\Services\\UserService', 'index.php', ctx); - expect(result).toBeNull(); - }); -}); - -describe('swiftPackageStrategy', () => { - it('resolves SwiftPM target imports to files in the target directory', () => { - const files = [ - 'Package/Sources/SiuperModel/Foo.swift', - 'Package/Sources/SiuperModel/Bar.swift', - 'Package/Sources/Other/Unrelated.swift', - ]; - const ctx = makeCtx(files, { - swiftPackageConfig: { - targets: new Map([['SiuperModel', 'Package/Sources/SiuperModel']]), - }, - }); - const result = swiftPackageStrategy('SiuperModel', 'App.swift', ctx); - expect(result?.kind).toBe('files'); - expect(result?.files).toEqual( - expect.arrayContaining([ - 'Package/Sources/SiuperModel/Foo.swift', - 'Package/Sources/SiuperModel/Bar.swift', - ]), - ); - expect(result?.files).not.toContain('Package/Sources/Other/Unrelated.swift'); - }); - - it('returns null for unknown targets (external frameworks like Foundation)', () => { - const ctx = makeCtx(['Package/Sources/SiuperModel/Foo.swift'], { - swiftPackageConfig: { - targets: new Map([['SiuperModel', 'Package/Sources/SiuperModel']]), - }, - }); - const result = swiftPackageStrategy('Foundation', 'App.swift', ctx); - expect(result).toBeNull(); - }); - - it('does not resolve inferred grouping folders when the declaration is empty', () => { - const ctx = makeCtx(['Sources/Foundation/Thing.swift', 'Sources/App/main.swift'], { - swiftPackageConfig: { - origin: 'package.swift', - targets: new Map([ - ['Foundation', 'Sources/Foundation'], - ['App', 'Sources/App'], - ]), - declaredTargets: new Map(), - }, - }); - expect(swiftPackageStrategy('Foundation', 'Sources/App/main.swift', ctx)).toBeNull(); - expect(swiftPackageStrategy('App', 'Sources/App/main.swift', ctx)).toBeNull(); - }); - - it('ignores an inferred directories origin', () => { - const ctx = makeCtx(['Sources/Models/User.swift'], { - swiftPackageConfig: { - origin: 'directories', - targets: new Map([['Models', 'Sources/Models']]), - }, - }); - expect(swiftPackageStrategy('Models', 'Sources/App/main.swift', ctx)).toBeNull(); - }); -}); - -describe('rubyRequireStrategy', () => { - it('resolves require_relative paths via suffix matching', () => { - const files = ['lib/models/user.rb']; - const ctx = makeCtx(files); - const result = rubyRequireStrategy('./models/user', 'lib/app.rb', ctx); - expect(result).toEqual({ kind: 'files', files }); - }); - - it('returns null when no file matches the require path', () => { - const ctx = makeCtx(['lib/models/user.rb']); - const result = rubyRequireStrategy('./missing/file', 'lib/app.rb', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Per-language configs — all construct cleanly -// --------------------------------------------------------------------------- - -describe('per-language import configs', () => { - const configs: { name: string; config: ImportResolutionConfig }[] = [ - { name: 'TypeScript', config: typescriptImportConfig }, - { name: 'JavaScript', config: javascriptImportConfig }, - { name: 'Vue', config: vueImportConfig }, - { name: 'C', config: cImportConfig }, - { name: 'C++', config: cppImportConfig }, - { name: 'Go', config: goImportConfig }, - { name: 'Java', config: javaImportConfig }, - { name: 'Kotlin', config: kotlinImportConfig }, - { name: 'Python', config: pythonImportConfig }, - { name: 'Rust', config: rustImportConfig }, - { name: 'C#', config: csharpImportConfig }, - { name: 'PHP', config: phpImportConfig }, - { name: 'Swift', config: swiftImportConfig }, - { name: 'Dart', config: dartImportConfig }, - { name: 'Ruby', config: rubyImportConfig }, - ]; - - for (const { name, config } of configs) { - it(`${name} config has strategies and constructs a resolver`, () => { - expect(config.strategies.length).toBeGreaterThan(0); - expect(() => createImportResolver(config)).not.toThrow(); - }); - } -}); - -// --------------------------------------------------------------------------- -// createStandardStrategy — reusable across languages -// --------------------------------------------------------------------------- - -describe('createStandardStrategy', () => { - it('creates a reusable strategy from a language', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - expect(typeof strategy).toBe('function'); - }); - - it('resolves relative imports', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - const ctx = makeCtx(['src/utils.ts']); - const result = strategy('./utils', 'src/index.ts', ctx); - expect(result).toEqual({ kind: 'files', files: ['src/utils.ts'] }); - }); - - it('returns null for unresolvable imports', () => { - const strategy = createStandardStrategy(SupportedLanguages.TypeScript); - const ctx = makeCtx([]); - const result = strategy('./nonexistent', 'src/index.ts', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Python strategy — absorbs unresolved relative imports -// --------------------------------------------------------------------------- - -describe('pythonImportStrategy', () => { - it('absorbs unresolved relative imports with empty-files sentinel', () => { - const ctx = makeCtx([]); - const result = pythonImportStrategy('.nonexistent', 'src/app.py', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('returns null for non-relative imports (allows chain to continue)', () => { - const ctx = makeCtx([]); - const result = pythonImportStrategy('os', 'src/app.py', ctx); - expect(result).toBeNull(); - }); - - it('absorbs unresolved external dotted imports instead of suffix-matching local basename files', () => { - const ctx = makeCtx(['accounts/apps.py', 'billing/apps.py']); - const result = pythonImportStrategy('django.apps', 'accounts/apps.py', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs unresolved nested external dotted imports like django.urls and django.core.*', () => { - const ctx = makeCtx(['config/asgi.py', 'config/urls.py', 'config/wsgi.py']); - - expect(pythonImportStrategy('django.urls', 'config/urls.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - expect(pythonImportStrategy('django.core.asgi', 'config/asgi.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - expect(pythonImportStrategy('django.core.wsgi', 'config/wsgi.py', ctx)).toEqual({ - kind: 'files', - files: [], - }); - }); - - it('keeps dotted internal imports unresolved here when the leading package exists in-repo', () => { - const ctx = makeCtx(['accounts/models.py', 'billing/models.py']); - const result = pythonImportStrategy('accounts.models', 'billing/models.py', ctx); - expect(result).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// Dart strategies — absorbs SDK / external package imports -// --------------------------------------------------------------------------- - -describe('dartPackageStrategy', () => { - it('absorbs dart: SDK imports', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'dart:async'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('absorbs external package: imports', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'package:http/http.dart'", 'lib/main.dart', ctx); - expect(result).toEqual({ kind: 'files', files: [] }); - }); - - it('returns null for relative imports (chains to dartRelativeStrategy)', () => { - const ctx = makeCtx([]); - const result = dartPackageStrategy("'models.dart'", 'lib/main.dart', ctx); - expect(result).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts index d3ed9b42da..989f563214 100644 --- a/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts +++ b/gitnexus/test/unit/import-resolvers/csharp-csproj-parity.test.ts @@ -34,32 +34,28 @@ * below pins that: it drives the naive cleanup and asserts it CHANGES answers. * * The arms all assert the full `string[]` and its order — this resolver returns - * every match, not one, and `configs/csharp.ts` turns a multi-file result into a - * `kind: 'package'` edge set whose order reaches the graph. + * every match, not one, and the active scope resolver selects the first match. */ import { describe, expect, it } from 'vitest'; -import { - resolveCSharpImportInternal, - resolveCSharpNamespaceDir, -} from '../../../src/core/ingestion/import-resolvers/csharp.js'; +import { resolveCSharpImportInternal } from '../../../src/core/ingestion/languages/csharp/import-helpers.js'; import { buildSuffixIndex, suffixResolve, type SuffixIndex, -} from '../../../src/core/ingestion/import-resolvers/utils.js'; -import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/csharp-namespace-gate.js'; +} from '../../../src/core/ingestion/utils/suffix-index.js'; +import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; import type { CSharpProjectConfig, CSharpNamespaceEvidence, } from '../../../src/core/ingestion/language-config.js'; +import { EXTENSIONS } from '../../../src/core/ingestion/languages/import-candidates.js'; // ─── verbatim pre-change implementation ────────────────────────────────────── -// `git show HEAD~:gitnexus/src/core/ingestion/import-resolvers/csharp.ts`, body -// copied unchanged. Its helpers (`suffixResolve`, `csharpSuffixFallbackAllowed`, -// `SuffixIndex`) are imported from production because this PR does not touch -// them; only the function below changed. +// Frozen implementation from before the direct-child probe optimization. +// Its helpers (`suffixResolve`, `csharpSuffixFallbackAllowed`, `SuffixIndex`) +// are imported from production; the frozen function retains the original probe. /** * The direct-child probe the frozen copies below run — four call sites, two in @@ -164,7 +160,7 @@ function legacyResolveCSharpImportInternal( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } @@ -245,7 +241,7 @@ function skipStep3WhenIndexed( return []; } const pathParts = namespacePath.split('/').filter(Boolean); - const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, index); + const fallback = suffixResolve(pathParts, normalizedFileList, allFileList, EXTENSIONS, index); return fallback ? [fallback] : []; } @@ -458,19 +454,6 @@ describe('C# csproj leg — directory index vs the pre-change linear scan (#2902 } expect(current).toEqual(legacy); }); - - it('leaves `resolveCSharpNamespaceDir` — the sibling that shares the dirPrefix maths — alone', () => { - const dirs: Record = {}; - for (const [shape, configs] of CONFIG_SHAPES) { - for (const importPath of IMPORTS) { - dirs[`${shape} | ${importPath}`] = resolveCSharpNamespaceDir(importPath, configs); - } - } - expect(dirs['projectDir=src | App.Models']).toBe('/src/Models/'); - expect(dirs['no projectDir | App']).toBeNull(); - expect(dirs['no projectDir | App.Models']).toBe('/Models/'); - expect(dirs['no config matches | App.Models']).toBeNull(); - }); }); describe('C# csproj leg — the answers only step 3 can give (#2902)', () => { diff --git a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts deleted file mode 100644 index bf2d0e6534..0000000000 --- a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Coverage for `resolveGoPackage` (`import-resolvers/go.ts`), which had none. - * - * Go resolves package imports through two independent legs. The ScopeResolver - * leg (`languages/go/import-target.ts`) answers from `buildPackageDirIndex`; - * this one is the LanguageProvider leg, wired through `configs/go.ts`, and it - * is still a per-import scan. #2881 changed its membership rule — a directory - * whose name repeats higher in the path is now a member — and review found the - * change reached production with nothing watching it: `bench/import-target`'s - * go arm drives the indexed leg only, and no test called this function. - * - * These cases pin the rule and the two legs' agreement on it, so a revert fails - * here rather than silently moving Go IMPORTS edges in every repository that - * nests a package name inside itself (`internal/…/internal` is the shape Go - * actually produces). - * - * One caveat on "the LanguageProvider leg", recorded in #2929 review: nothing - * in production reads that field today. `configs/go.ts` reaches this function - * through `createImportResolver` → `LanguageProvider.importResolver`, and the - * only readers of `importResolver` are `import-target-adapter.ts:74-75`, whose - * two exports have no importer outside their own unit test. So the leg is wired - * but unreached, and this file is the only thing exercising it. - */ -import { describe, expect, it } from 'vitest'; -import { - resolveGoPackage, - resolveGoPackageDir, -} from '../../../src/core/ingestion/import-resolvers/go.js'; -import type { GoModuleConfig } from '../../../src/core/ingestion/language-config.js'; -import { - buildPackageDirIndex, - filesDirectlyInPkgDir, -} from '../../../src/core/ingestion/import-resolvers/package-dir-index.js'; - -const MOD: GoModuleConfig = { modulePath: 'example.com/mod' }; - -function resolve(files: readonly string[], importPath: string): string[] { - const normalized = files.map((f) => f.replace(/\\/g, '/')); - return resolveGoPackage(importPath, MOD, normalized, files); -} - -/** - * The indexed membership rule, for the agreement arm: the package-dir index - * the ScopeResolver leg's GOPATH match answers from, asked the module-relative - * path this leg asks. Not `resolveGoImportTarget` itself any more — its module - * leg now names the exact directory under the module root, deliberately unlike - * this leg's suffix match (see `languages/go/workspace-config.ts`). - */ -function indexed(files: readonly string[], importPath: string): readonly string[] { - const index = buildPackageDirIndex( - new Set(files), - (normalized) => normalized.endsWith('.go') && !normalized.endsWith('_test.go'), - ); - return filesDirectlyInPkgDir(index, importPath.slice(MOD.modulePath.length + 1)); -} - -describe('resolveGoPackage', () => { - it('returns every .go file directly inside the package directory', () => { - const files = ['internal/auth/service.go', 'internal/auth/token.go', 'internal/auth/sub/x.go']; - expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ - 'internal/auth/service.go', - 'internal/auth/token.go', - ]); - }); - - it('a package directory nested inside a same-named one IS a member (#2881)', () => { - // The scan asked `indexOf` for the FIRST `/pkg/` and then required nothing - // after it to hold a slash, so this resolved to nothing. Both halves of the - // shape: the repeat leading the path, and the repeat mid-path. - expect(resolve(['pkg/src/go/pkg/repo.go'], 'example.com/mod/pkg')).toEqual([ - 'pkg/src/go/pkg/repo.go', - ]); - expect(resolve(['a/pkg/b/pkg/x.go'], 'example.com/mod/pkg')).toEqual(['a/pkg/b/pkg/x.go']); - expect(resolve(['svc/internal/sub/internal/x.go'], 'example.com/mod/internal')).toEqual([ - 'svc/internal/sub/internal/x.go', - ]); - }); - - it('a repeated name that is not the parent directory is still not a member', () => { - // The rule is "the parent directory ends with the package path", not - // "the package path appears anywhere". - expect(resolve(['a/pkg/b/x.go'], 'example.com/mod/pkg')).toEqual([]); - expect(resolve(['internal/auth/sub/x.go'], 'example.com/mod/internal/auth')).toEqual([]); - }); - - it('multi-segment package paths match on the whole run, not the last segment', () => { - const files = ['a/internal/models/b/internal/models/user.go', 'a/models/other.go']; - expect(resolve(files, 'example.com/mod/internal/models')).toEqual([ - 'a/internal/models/b/internal/models/user.go', - ]); - }); - - it('_test.go files are a different package and never match', () => { - expect( - resolve( - ['internal/auth/service.go', 'internal/auth/service_test.go'], - 'example.com/mod/internal/auth', - ), - ).toEqual(['internal/auth/service.go']); - }); - - it('non-.go files never match, and the RAW path is returned for backslashes', () => { - expect( - resolve(['internal/auth/README.md', 'internal/auth/x.go'], 'example.com/mod/internal/auth'), - ).toEqual(['internal/auth/x.go']); - expect(resolve(['internal\\auth\\x.go'], 'example.com/mod/internal/auth')).toEqual([ - 'internal\\auth\\x.go', - ]); - }); - - it('an import outside the module, or the module root itself, resolves to nothing here', () => { - expect(resolve(['internal/auth/x.go'], 'github.com/other/repo/internal/auth')).toEqual([]); - // The root package is the caller's `findRootPackageFiles` leg, not this one. - expect(resolve(['main.go'], 'example.com/mod')).toEqual([]); - expect(resolveGoPackageDir('example.com/mod', MOD)).toBeNull(); - expect(resolveGoPackageDir('example.com/mod/internal/auth', MOD)).toBe('/internal/auth/'); - }); - - it('vendor/, testdata/ and nested-module directories all merge in (unmodelled)', () => { - // Go excludes all three from a package: `vendor/` is a dependency tree - // resolved against the vendoring module, the go tool ignores `testdata/` - // entirely, and a directory carrying its own `go.mod` is a separate module - // whose packages this module's import paths never name. - // - // This resolver models NONE of that — it matches on the parent directory's - // path suffix alone. That is unchanged by #2881: the pre-#2881 rule - // (first `//`, nothing but a filename after it) accepted all three - // shapes too. These assertions record what the function actually does so - // the gap is visible and a change to it is deliberate; they document the - // behaviour rather than endorse it. - const files = [ - 'go.mod', - 'internal/auth/service.go', - 'vendor/example.com/dep/internal/auth/vendored.go', - 'testdata/internal/auth/fixture.go', - 'sub/go.mod', // `sub/` is its own module; its packages are not ours - 'sub/internal/auth/other_module.go', - ]; - expect(resolve(files, 'example.com/mod/internal/auth')).toEqual([ - 'internal/auth/service.go', - 'vendor/example.com/dep/internal/auth/vendored.go', - 'testdata/internal/auth/fixture.go', - 'sub/internal/auth/other_module.go', - ]); - // A `go.mod` beside the files changes nothing — it is not read here. - expect(resolve(['sub/go.mod', 'sub/pkg/x.go'], 'example.com/mod/pkg')).toEqual([ - 'sub/pkg/x.go', - ]); - }); - - it('agrees with the indexed membership rule on the repeated-name shapes', () => { - // The two are independent implementations of one rule. Before #2881 they - // agreed on the wrong answer; they must agree on the right one, or this - // leg and the GOPATH match disagree about which files a package holds. - for (const files of [ - ['pkg/src/go/pkg/repo.go'], - ['a/pkg/b/pkg/x.go'], - ['a/pkg/b/x.go'], - ['internal/auth/service.go', 'internal/auth/token.go'], - ['a/internal/models/b/internal/models/user.go'], - ]) { - for (const target of [ - 'example.com/mod/pkg', - 'example.com/mod/internal/auth', - 'example.com/mod/internal/models', - ]) { - expect(resolve(files, target)).toEqual([...indexed(files, target)]); - } - } - }); -}); diff --git a/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts b/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts index c6e2fcc224..ce0e9f0a5e 100644 --- a/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts +++ b/gitnexus/test/unit/import-resolvers/python-importer-prefixes.test.ts @@ -1,6 +1,6 @@ /** * Gate for the single-segment bare-import ancestor walk in - * `import-resolvers/python.ts`: Python bare-import resolution must not scale + * `languages/python/import-helpers.ts`: Python bare-import resolution must not scale * with the importer's path depth. * * #2913 memoized the ancestor chains inside `languages/python/import-target.ts` @@ -34,11 +34,8 @@ * again, and with a non-vacuity assertion, because a perfect count is equally * true of a resolver that stopped resolving anything. * - * Both production surfaces are driven, not the helper: `pythonScopeResolver - * .resolveImportTarget` (the scope-resolution orchestrator's adapter, the one - * that pays the walk twice) and `pythonImportStrategy` (the import-resolver - * pipeline's, via `ImportTargetWorkspace`'s shared `ResolveCtx`). They thread - * different objects around the same Set, and the memo is keyed on the Set. + * The production entry point is `pythonScopeResolver.resolveImportTarget`, + * which can reach the walk twice. The memo is keyed on the shared file Set. * * `legacyPrefixes` is a verbatim copy of the pre-change inline code, in the * house style of `python-importer-ancestors.test.ts`: it is the specification, @@ -58,18 +55,12 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import type { ImportResolutionContext } from '../../../src/core/ingestion/scope-resolution/contract/scope-resolver.js'; import { pythonScopeResolver } from '../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { resolvePythonImportInternal } from '../../../src/core/ingestion/import-resolvers/python.js'; -import { getPythonFileIndex } from '../../../src/core/ingestion/import-resolvers/python-file-index.js'; +import { resolvePythonImportInternal } from '../../../src/core/ingestion/languages/python/import-helpers.js'; +import { getPythonFileIndex } from '../../../src/core/ingestion/languages/python/import-file-index.js'; /** The bare-import prefix memo, which lives inside the shared per-file-set index. */ const prefixMemo = (files: ReadonlySet): ReadonlyMap => getPythonFileIndex(files).bareImportPrefixesByDir; -import { pythonImportStrategy } from '../../../src/core/ingestion/import-resolvers/configs/python.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; -import type { - ImportResult, - ResolveCtx, -} from '../../../src/core/ingestion/import-resolvers/types.js'; import { IMPORTER_PATH_SHAPES, NO_PARSED_FILES, @@ -101,44 +92,11 @@ function legacyPrefixes(currentFile: string): string[] { // ─── surfaces ──────────────────────────────────────────────────────────────── -/** - * A `ResolveCtx` for the import-resolver pipeline surface. `allFilePaths` is - * the caller's Set passed THROUGH — the memo is keyed on its identity, so a - * copy here would measure nothing. - */ -function makeResolveCtx(allFilePaths: Set): ResolveCtx { - const allFileList = [...allFilePaths]; - const normalizedFileList = allFileList.map((file) => file.replace(/\\/g, '/')); - return { - allFilePaths, - allFileList, - normalizedFileList, - index: buildSuffixIndex(normalizedFileList, allFileList), - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, - }; -} - const ctxFor = (parsedImport: ParsedImport): ImportResolutionContext => ({ parsedFiles: NO_PARSED_FILES, parsedImport, }); -/** - * An `ImportResult` as the arms read it: the resolved path, or `null` for a - * miss. A stop-the-chain result carrying no files joins to `''`, which is - * neither the hit nor a miss — the same distinction the pre-collapse arm drew - * with `value?.kind === 'files' && value.files.join() === HIT_RESULT`. - */ -const resolvedPath = (result: ImportResult): ChainMemoResult => - result === null ? null : result.files.join(); - // ─── the workspace the surfaces are driven against ─────────────────────────── /** @@ -175,15 +133,11 @@ const WALK_TARGET = 'probe'; const ABSENT_TARGET = 'ghostmod'; /** - * The spelling sequence BOTH surfaces are driven with, `perImporter` rounds of + * The spelling sequence the adapter is driven with, `perImporter` rounds of * it plus the one spelling that must resolve: one target that walks the whole * chain and misses, one that the absence proof retires before the walk, and one * that hits at the workspace root. No spelling is varied per round — the Python * chain keeps no per-target cache, so a repeated target really is re-resolved. - * - * `resolve` is the only thing that differs between the orchestrator adapter and - * the import-resolver pipeline; everything about the sequence is shared, which - * is why the two used to be the same loop written twice. */ function drive( fromFile: string, @@ -209,25 +163,6 @@ const adapterArm = (mkImport: (targetRaw: string) => ParsedImport): ChainMemoArm hitResult: HIT_RESULT, }); -/** - * The import-resolver pipeline surface. One `ResolveCtx` per drive rather than - * one for the run, on purpose: everything the strategy reads off it is derived - * from the same Set (and `pythonImportStrategy` only ever WRITES - * `resolveCache`), so a fresh ctx around the same Set is exactly the "different - * objects, same Set" case the memo has to survive. - */ -const strategyArm: ChainMemoArm = { - memoOf: prefixMemo, - drive: (files, fromFile, perImporter) => { - const ctx = makeResolveCtx(files); - return drive(fromFile, perImporter, (target, from) => - resolvedPath(pythonImportStrategy(target, from, ctx)), - ); - }, - legacyChain: legacyPrefixes, - hitResult: HIT_RESULT, -}; - describe('Python bare-import prefix memo', () => { it.each([ { perImporter: 1, kind: 'namespace', mkImport: pythonNamespaceImport }, @@ -241,16 +176,6 @@ describe('Python bare-import prefix memo', () => { }, ); - it.each([ - { perImporter: 1, label: 'one import per importer' }, - { perImporter: 40, label: 'forty imports per importer' }, - ])( - 'holds one chain per importer DIRECTORY on the import-resolver surface too — $label', - ({ perImporter }) => { - expectOneChainPerImporterDir(strategyArm, new Set(WORKSPACE), perImporter); - }, - ); - it('reuses the SAME chain object, rather than rebuilding and re-storing it', () => { expectSameChainObjectReused(adapterArm(pythonNamedImport), new Set(WORKSPACE)); }); @@ -387,16 +312,11 @@ describe('Python bare-import ancestor walk — resolution', () => { }, ])('$why', ({ files, fromFile, expected }) => { const set = new Set(files); - // The helper, the scope-resolution adapter and the import-resolver - // strategy must agree: all three reach the same walk. + // The helper and scope-resolution adapter must reach the same walk. expect(resolvePythonImportInternal(fromFile, 'user', set)).toBe(expected); expect( resolveImportTarget('user', fromFile, set, undefined, ctxFor(pythonNamespaceImport('user'))), ).toBe(expected); - expect(pythonImportStrategy('user', fromFile, makeResolveCtx(set))).toEqual({ - kind: 'files', - files: [expected], - }); }); it.each([ diff --git a/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts b/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts index 3e4188c9c7..fe7bd4da92 100644 --- a/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts +++ b/gitnexus/test/unit/import-resolvers/suffix-index-lazy-dir-map.test.ts @@ -20,9 +20,8 @@ * * All of it is memory. `dirMap` is the array-valued map — one entry and one * array push per file per directory component, O(files × depth) in entries and - * in churn — and only four call sites ever read it - * (`import-resolvers/{php,csharp,jvm}.ts`, `import-resolvers/configs/ - * python.ts`), yet `workspace-file-index.ts` serving Ruby, + * in churn — and only `languages/{php,csharp}/import-helpers.ts` read it, yet + * `workspace-file-index.ts` serving Ruby, * `languages/typescript/scope-resolver.ts`, `languages/vue/import-target.ts` * and `group/extractors/include-extractor.ts` all built it and never touched * it: ~15% of the retained C# index and ~19% of the retained Ruby one on @@ -79,7 +78,7 @@ import { describe, expect, it } from 'vitest'; import { buildSuffixIndex, type SuffixIndex, -} from '../../../src/core/ingestion/import-resolvers/utils.js'; +} from '../../../src/core/ingestion/utils/suffix-index.js'; // ─── verbatim pre-change implementations ───────────────────────────────────── @@ -438,7 +437,7 @@ const ONE_PASS = RAW_FILES.length; /** Lookups driven bare before a count is read — the count must not move. */ const LOOKUP_REPEATS = 20; -/** `import-resolvers/pass-cache.ts` builds exactly this: lowercased, not slash-normalized. */ +/** A lowercased input list, rather than a slash-normalized one. */ const LOWERCASED_FILES: string[] = ALL_FILES.map((f) => f.toLowerCase()); // ─── parity: the directory map ─────────────────────────────────────────────── diff --git a/gitnexus/test/unit/node-workspace-memo-rejection.test.ts b/gitnexus/test/unit/node-workspace-memo-rejection.test.ts index 90dfac825d..67f52b8bad 100644 --- a/gitnexus/test/unit/node-workspace-memo-rejection.test.ts +++ b/gitnexus/test/unit/node-workspace-memo-rejection.test.ts @@ -85,7 +85,7 @@ describe('node-workspace-packages memo: a rejected invalidated load keeps the ne it('load B survives load A rejecting after invalidation', async () => { const { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const key = path.resolve(repo); ctx.gateRoot = key; diff --git a/gitnexus/test/unit/node-workspace-nested-roots.test.ts b/gitnexus/test/unit/node-workspace-nested-roots.test.ts index fca04a4385..d5cf47e8d5 100644 --- a/gitnexus/test/unit/node-workspace-nested-roots.test.ts +++ b/gitnexus/test/unit/node-workspace-nested-roots.test.ts @@ -5,7 +5,7 @@ import path from 'node:path'; import { loadNodeWorkspacePackages, resolveNodeWorkspaceImport, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; /** * C3 — a workspace declared BELOW the repo root (keycloak: `js/pnpm-workspace.yaml`). diff --git a/gitnexus/test/unit/node-workspace-packages.test.ts b/gitnexus/test/unit/node-workspace-packages.test.ts index ecfd8ef033..77439301a0 100644 --- a/gitnexus/test/unit/node-workspace-packages.test.ts +++ b/gitnexus/test/unit/node-workspace-packages.test.ts @@ -13,7 +13,7 @@ import { nodePackageNameOf, substituteStar, type NodeWorkspacePackages, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; import { resolveTsModule } from '../../src/core/ingestion/languages/typescript/module-resolution.js'; import type { TsconfigIndex } from '../../src/core/ingestion/languages/typescript/tsconfig.js'; diff --git a/gitnexus/test/unit/node-workspace-repo-root-race.test.ts b/gitnexus/test/unit/node-workspace-repo-root-race.test.ts index 5b9f9f7f4c..c684fde4bc 100644 --- a/gitnexus/test/unit/node-workspace-repo-root-race.test.ts +++ b/gitnexus/test/unit/node-workspace-repo-root-race.test.ts @@ -106,7 +106,7 @@ describe('node-workspace-packages: entry discovery is safe under concurrent scan it("repo B finishing mid-scan does not corrupt repo A's in-flight source-entry discovery", async () => { const { loadNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const pA = loadNodeWorkspacePackages(repoA); // Wait until A is blocked right before checking pkg2's real source file. diff --git a/gitnexus/test/unit/node-workspace-review-fixes.test.ts b/gitnexus/test/unit/node-workspace-review-fixes.test.ts index 881e08845f..288ae38936 100644 --- a/gitnexus/test/unit/node-workspace-review-fixes.test.ts +++ b/gitnexus/test/unit/node-workspace-review-fixes.test.ts @@ -13,7 +13,7 @@ import { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages, resolveNodeWorkspaceImport, -} from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +} from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; import { _captureLogger } from '../../src/core/logger.js'; function mkRepo(prefix: string) { diff --git a/gitnexus/test/unit/node-workspace-scan-determinism.test.ts b/gitnexus/test/unit/node-workspace-scan-determinism.test.ts index 77192baee7..602142d998 100644 --- a/gitnexus/test/unit/node-workspace-scan-determinism.test.ts +++ b/gitnexus/test/unit/node-workspace-scan-determinism.test.ts @@ -128,7 +128,7 @@ vi.mock('fs/promises', async (importOriginal) => { describe('M7 — workspace-root scan: sorted readdir + a cap that warns (50,010-directory synthetic tree)', () => { it('trips the cap and warns, and the run still completes deterministically for a result outside the capped subtree', async () => { const { loadNodeWorkspacePackages, invalidateNodeWorkspacePackages } = - await import('../../src/core/ingestion/import-resolvers/node-workspace-packages.js'); + await import('../../src/core/ingestion/languages/typescript/workspace-packages.js'); const results: { warned: boolean; diff --git a/gitnexus/test/unit/node-workspace-scope.test.ts b/gitnexus/test/unit/node-workspace-scope.test.ts index 1073305abe..8ee4fcf4a1 100644 --- a/gitnexus/test/unit/node-workspace-scope.test.ts +++ b/gitnexus/test/unit/node-workspace-scope.test.ts @@ -15,7 +15,7 @@ import { describe, it, expect, afterAll } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; const roots: string[] = []; diff --git a/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts b/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts index 9f99eed9e5..d6a0f38b6f 100644 --- a/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts +++ b/gitnexus/test/unit/node-workspace-vite-entry-comments.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; describe('vite lib.entry discovery ignores comments and refuses disagreeing entries', () => { let dir: string; diff --git a/gitnexus/test/unit/node-workspace-vite-structure.test.ts b/gitnexus/test/unit/node-workspace-vite-structure.test.ts index 87816eb3d6..b5f002dec6 100644 --- a/gitnexus/test/unit/node-workspace-vite-structure.test.ts +++ b/gitnexus/test/unit/node-workspace-vite-structure.test.ts @@ -2,7 +2,7 @@ import { afterAll, describe, expect, it } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { loadNodeWorkspacePackages } from '../../src/core/ingestion/import-resolvers/node-workspace-packages.js'; +import { loadNodeWorkspacePackages } from '../../src/core/ingestion/languages/typescript/workspace-packages.js'; const roots: string[] = []; afterAll(() => { diff --git a/gitnexus/test/unit/python-relative-imports.test.ts b/gitnexus/test/unit/python-relative-imports.test.ts new file mode 100644 index 0000000000..ad19eb78b3 --- /dev/null +++ b/gitnexus/test/unit/python-relative-imports.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest'; +import { resolvePythonImportInternal } from '../../src/core/ingestion/languages/python/import-helpers.js'; +import { resolvePythonImportTarget } from '../../src/core/ingestion/languages/python/import-target.js'; + +/** Both the helper and the public adapter must respect Python's file boundary. */ +function resolveBoth(files: string[], target = '.peer', fromFile = 'pkg/main.py') { + const allFilePaths = new Set([fromFile, ...files]); + return [ + resolvePythonImportInternal(fromFile, target, allFilePaths), + resolvePythonImportTarget( + { kind: 'namespace', targetRaw: target, localName: 'peer', importedName: '*' }, + { fromFile, allFilePaths }, + ), + ]; +} + +describe('Python relative import file candidates', () => { + it.each(['.ts', '.tsx', '.js', '.php', '.rb', ''])( + 'leaves a relative import unresolved when only peer%s exists', + (extension) => { + expect(resolveBoth([`pkg/peer${extension}`])).toEqual([null, null]); + }, + ); + + it('selects the Python module despite a same-named TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer.py'])).toEqual(['pkg/peer.py', 'pkg/peer.py']); + }); + + it('selects a Python package despite a same-named TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer/__init__.py'])).toEqual([ + 'pkg/peer/__init__.py', + 'pkg/peer/__init__.py', + ]); + }); + + it.each([ + ['.peer', 'pkg/main.py'], + ['..peer', 'pkg/child/main.py'], + ])('prefers a package over a module for %s from %s', (target, fromFile) => { + expect(resolveBoth(['pkg/peer.py', 'pkg/peer/__init__.py'], target, fromFile)).toEqual([ + 'pkg/peer/__init__.py', + 'pkg/peer/__init__.py', + ]); + }); + + it('resolves a parent-relative Python module without borrowing a TypeScript file', () => { + expect(resolveBoth(['pkg/peer.ts', 'pkg/peer.py'], '..peer', 'pkg/child/main.py')).toEqual([ + 'pkg/peer.py', + 'pkg/peer.py', + ]); + }); +}); diff --git a/gitnexus/test/unit/resolver-outcome-helpers.test.ts b/gitnexus/test/unit/resolver-outcome-helpers.test.ts new file mode 100644 index 0000000000..b201d2df5f --- /dev/null +++ b/gitnexus/test/unit/resolver-outcome-helpers.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { suppressionReasonsAt } from '../integration/resolvers/helpers.js'; +import type { PipelineResult } from '../../src/types/pipeline.js'; +import { createKnowledgeGraph } from '../../src/core/graph/graph.js'; + +describe('suppressionReasonsAt', () => { + it('separates a call and a read of the same member at the same position', () => { + const common = { + kind: 'suppressed' as const, + phase: 'receiver-bound-calls', + filePath: 'app.go', + name: 'save', + range: { startLine: 1, startCol: 0, endLine: 1, endCol: 10 }, + candidateIds: [], + }; + const result: PipelineResult = { + graph: createKnowledgeGraph(), + repoPath: '/repo', + totalFileCount: 1, + usedWorkerPool: false, + reparsedFileCount: 0, + scopeExtractionFailures: [], + unavailableScopeLanguageFiles: 0, + resolutionOutcomes: [ + { ...common, reason: 'receiver-unresolved', siteKind: 'call' }, + { ...common, reason: 'receiver-owned-but-unbound', siteKind: 'read' }, + ], + }; + expect(suppressionReasonsAt(result, ['app.go', 1, 0, 'save', 'call'])).toEqual([ + 'receiver-unresolved', + ]); + expect(suppressionReasonsAt(result, ['app.go', 1, 0, 'save', 'read'])).toEqual([ + 'receiver-owned-but-unbound', + ]); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/answered-receiver-drops.test.ts b/gitnexus/test/unit/scope-resolution/answered-receiver-drops.test.ts new file mode 100644 index 0000000000..6dddf5114b --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/answered-receiver-drops.test.ts @@ -0,0 +1,129 @@ +/** + * A `receiver-unresolved` drop is a claim that the site was lost with no + * candidate. The receiver-bound pass records it as soon as its own cases give + * up, but the read/write passes that run after it (return-shape members, + * unique-name properties) can still answer the same site with an `ACCESSES` + * edge. Such a site is not lost, so its drop is withdrawn — and ONLY its drop: + * every other outcome, and every drop at a site nothing answered, stays. + */ + +import { describe, it, expect } from 'vitest'; +import { + answeredSiteKey, + withdrawAnsweredReceiverDrops, +} from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js'; +import type { ResolutionOutcome } from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js'; + +type SiteKind = 'call' | 'read' | 'write'; + +const at = (startLine: number, startCol: number) => ({ + startLine, + startCol, + endLine: startLine, + endCol: startCol + 1, +}); + +function drop( + name: string, + siteKind: SiteKind, + line = 4, + col = 2, +): Extract { + return { + kind: 'suppressed', + reason: 'receiver-unresolved', + candidateIds: [], + phase: 'receiver-bound-calls', + filePath: 'src/producer.js', + name, + range: at(line, col), + siteKind, + }; +} + +/** The one site the later pass answered: the WRITE of `wickRatio` at 4:2. */ +const ANSWERED = new Set([answeredSiteKey('src/producer.js', at(4, 2), 'write', 'wickRatio')]); + +describe('withdrawAnsweredReceiverDrops', () => { + it('keeps an unanswered repeated-name chain that ends after the answered inner read', () => { + const inner = drop('data', 'read'); + const outer: ResolutionOutcome = { + ...drop('data', 'read'), + range: { ...at(4, 2), endCol: 12 }, + }; + const outcomes = [inner, outer]; + const answered = new Set([answeredSiteKey(inner.filePath, inner.range, 'read', 'data')]); + expect(withdrawAnsweredReceiverDrops(outcomes, answered)).toBe(1); + expect(outcomes).toEqual([outer]); + }); + + it.each<{ readonly label: string; readonly outcome: ResolutionOutcome; readonly kept: boolean }>([ + { label: 'the answered write itself', outcome: drop('wickRatio', 'write'), kept: false }, + // `a.b` and `a.b.c()` start at the same column, so position alone cannot + // tell the read the later pass answered from the call nothing answered. + { + label: 'a call at the same position with another name', + outcome: drop('save', 'call'), + kept: true, + }, + { + label: 'a read of the same name at the same position', + outcome: drop('wickRatio', 'read'), + kept: true, + }, + { + label: 'the same write one column over', + outcome: drop('wickRatio', 'write', 4, 3), + kept: true, + }, + { + label: 'a different suppression at the answered site', + outcome: { + kind: 'suppressed', + reason: 'member-lookup-ambiguous', + candidateIds: ['a', 'b'], + phase: 'receiver-bound-calls', + filePath: 'src/producer.js', + name: 'wickRatio', + range: at(4, 2), + siteKind: 'write', + }, + kept: true, + }, + { + label: 'a drop that carries no site kind', + outcome: { + kind: 'suppressed', + reason: 'receiver-unresolved', + candidateIds: [], + phase: 'receiver-bound-calls', + filePath: 'src/producer.js', + name: 'wickRatio', + range: at(4, 2), + }, + kept: true, + }, + ])('$label kept=$kept', ({ outcome, kept }) => { + const outcomes = [outcome]; + const withdrawn = withdrawAnsweredReceiverDrops(outcomes, ANSWERED); + expect({ outcomes, withdrawn }).toEqual({ + outcomes: kept ? [outcome] : [], + withdrawn: kept ? 0 : 1, + }); + }); + + it('keeps the survivors in their recorded order', () => { + const first = drop('save', 'call', 1, 0); + const answered = drop('wickRatio', 'write'); + const last = drop('secretFlag', 'write', 9, 9); + const outcomes = [first, answered, last]; + withdrawAnsweredReceiverDrops(outcomes, ANSWERED); + expect(outcomes).toEqual([first, last]); + }); + + it('withdraws nothing when nothing was answered', () => { + const outcomes = [drop('wickRatio', 'write')]; + expect(withdrawAnsweredReceiverDrops(outcomes, new Set())).toBe(0); + expect(outcomes).toHaveLength(1); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/cpp/cpp-captures.test.ts b/gitnexus/test/unit/scope-resolution/cpp/cpp-captures.test.ts index 80cff1d60e..8ace670cc5 100644 --- a/gitnexus/test/unit/scope-resolution/cpp/cpp-captures.test.ts +++ b/gitnexus/test/unit/scope-resolution/cpp/cpp-captures.test.ts @@ -615,6 +615,42 @@ describe('C++ pointer parameter — declared spelling', () => { }); }); +/** + * Which name a declaration binds, and to what type — for the shapes where the + * written declaration names no type directly (`auto`) or names it in a way only + * one syntactic position may claim (a function prototype). + */ +describe('C++ deduced and prototype type bindings', () => { + function rawTypeOf(src: string, name: string): string | undefined { + const parsed = extractParsedFile(cppProvider, src, 'test.cpp'); + const refs = (parsed?.scopes ?? []).flatMap((scope) => { + const ref = scope.typeBindings.get(name); + return ref === undefined ? [] : [ref.rawName]; + }); + return refs[0]; + } + + it.each<[string, string, string | undefined]>([ + // `auto` names no type; a leftover placeholder binds nothing. + ['void f() { auto n = 5; }', 'n', undefined], + ['auto g = [](auto v) { return v; };', 'v', undefined], + // A qualified callee is bound as written, like a bare one. + ['void f() { auto x = make(); }', 'x', 'make'], + ['void f() { auto x = rp::make(); }', 'x', 'rp::make'], + ['void f() { auto x = a::b::make(); }', 'x', 'a::b::make'], + // A template factory keeps its dedicated rule (the template argument). + ['void f() { auto x = std::make_shared(); }', 'x', 'Dog'], + // A prototype records its return type at namespace scope, through an + // include guard, and never in a function body (the most vexing parse). + ['D makeD();', 'makeD', 'D'], + ['D* makeP();', 'makeP', 'D'], + ['#ifndef G\n#define G\nnamespace rp { C make(); }\n#endif\n', 'make', 'C'], + ['void f() { E y(); }', 'y', undefined], + ])('%s binds %s to %s', (src, name, expected) => { + expect(rawTypeOf(src, name)).toBe(expected); + }); +}); + describe('written operator positions', () => { it('keeps distinct synthetic operator references on their actual tokens', () => { const source = 'int combine(A a, A b, A c) { return a + b + c; }'; diff --git a/gitnexus/test/unit/scope-resolution/cpp/cpp-qualified-ns-index.test.ts b/gitnexus/test/unit/scope-resolution/cpp/cpp-qualified-ns-index.test.ts index 098c832a49..d5bc0a25de 100644 --- a/gitnexus/test/unit/scope-resolution/cpp/cpp-qualified-ns-index.test.ts +++ b/gitnexus/test/unit/scope-resolution/cpp/cpp-qualified-ns-index.test.ts @@ -23,6 +23,7 @@ import { markCppInlineNamespaceRange, populateCppInlineNamespaceScopes, resolveCppQualifiedNamespaceMember, + splitCppQualifiedCallee, } from '../../../../src/core/ingestion/languages/cpp/inline-namespaces.js'; const NO_SCOPES = {} as unknown as ScopeResolutionIndexes; @@ -331,3 +332,18 @@ describe('C++ qualified-namespace member index (#2788)', () => { expect(resolveCppQualifiedNamespaceMember('outer', 'foo', files, NO_SCOPES)).toBeUndefined(); }); }); + +describe('splitCppQualifiedCallee', () => { + // Keep the written namespace path so a factory result cannot borrow a + // same-named nested namespace from another outer namespace. + it.each<[string, { receiver: string; member: string } | undefined]>([ + ['rp::make', { receiver: 'rp', member: 'make' }], + ['a::b::make', { receiver: 'a::b', member: 'make' }], + ['ns::Box::make', { receiver: 'ns::Box', member: 'make' }], + ['make', undefined], + ['::make', undefined], + ['Box', undefined], + ])('%s -> %j', (callee, expected) => { + expect(splitCppQualifiedCallee(callee)).toEqual(expected); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/csharp/csharp-hooks.test.ts b/gitnexus/test/unit/scope-resolution/csharp/csharp-hooks.test.ts index d768dde0d3..586759efdc 100644 --- a/gitnexus/test/unit/scope-resolution/csharp/csharp-hooks.test.ts +++ b/gitnexus/test/unit/scope-resolution/csharp/csharp-hooks.test.ts @@ -209,7 +209,7 @@ describe('populateCsharpNamespaceSiblings', () => { kind, parent, filePath, - range: { startLine: 1, startColumn: 0, endLine: 10, endColumn: 0 }, + range: { startLine: 1, startCol: 0, endLine: 10, endCol: 0 }, bindings: new Map(), imports: [], ownedDefs, @@ -235,11 +235,19 @@ describe('populateCsharpNamespaceSiblings', () => { const moduleA = scope('scope:a:module', 'Module', 'a.cs'); const moduleB = scope('scope:b:module', 'Module', 'b.cs'); const classB = scope('scope:b:class', 'Class', 'b.cs', moduleB.id, [sibling]); + const namespaceA = { + ...scope('scope:a:namespace', 'Namespace', 'a.cs', moduleA.id), + range: { startLine: 1, startCol: 0, endLine: 1, endCol: 15 }, + }; + const namespaceB = { + ...scope('scope:b:namespace', 'Namespace', 'b.cs', moduleB.id), + range: { startLine: 1, startCol: 0, endLine: 1, endCol: 15 }, + }; const parsedFiles: ParsedFile[] = [ { filePath: 'a.cs', moduleScope: moduleA.id, - scopes: Object.freeze([moduleA]), + scopes: Object.freeze([moduleA, namespaceA]), parsedImports: Object.freeze([]), localDefs: Object.freeze([]), referenceSites: Object.freeze([]), @@ -247,7 +255,7 @@ describe('populateCsharpNamespaceSiblings', () => { { filePath: 'b.cs', moduleScope: moduleB.id, - scopes: Object.freeze([moduleB, classB]), + scopes: Object.freeze([moduleB, namespaceB, classB]), parsedImports: Object.freeze([]), localDefs: Object.freeze([sibling]), referenceSites: Object.freeze([]), @@ -347,17 +355,25 @@ describe('populateCsharpNamespaceSiblings', () => { expect(namespaceFqnBindings.get('Demo')?.get('B')?.[0]?.def.nodeId).toBe('def:b.B'); }); - it('routes global-namespace types to workspaceFqnBindings, not per-scope augmentations (#1871 OOM guard)', () => { - // Types declared with NO `namespace` (the global/default namespace) are - // visible from every C# file, so the hook writes ONE workspace-level entry - // per simple name instead of O(scopes x defs) per-scope augmentations — - // the fix for the #1871 Unity-scale OOM. This pins both halves of that - // contract: global types are reachable via `workspaceFqnBindings`, and the - // per-scope augmentation channel stays empty for them. - // - // Note: the mock MUST supply `workspaceFqnBindings` — the global fast path - // reads `indexes.workspaceFqnBindings` directly, so omitting it (as the - // other tests in this suite do) would throw. + // Every channel the hook writes, so a test can assert which ones stayed empty. + const emptyIndexes = () => ({ + bindings: new Map>(), + bindingAugmentations: new Map>(), + workspaceFqnBindings: new Map(), + workspaceTypeBindings: new Map(), + namespaceFqnBindings: new Map>(), + namespaceTypeBindings: new Map>(), + accessibleNamespacesByScope: new Map(), + }); + + it('routes global-namespace types to the shared per-namespace channel under the global key (#1871 OOM guard)', () => { + // Types declared with NO `namespace` (the global/default namespace) get ONE + // shared entry per simple name instead of O(scopes x defs) per-scope + // augmentations — the fix for the #1871 Unity-scale OOM. They live in + // `namespaceFqnBindings['']`, gated per file like any other namespace, NOT + // in the scope-independent `workspaceFqnBindings` channel: that one answers + // at every scope, so a global type hid the file's own namespace siblings + // from any lookup that started inside a method. const defA = classDef('def:a.A', 'a.cs', 'A'); // simple name => global namespace const defB = classDef('def:b.B', 'b.cs', 'B'); const moduleA = scope('scope:a:module', 'Module', 'a.cs'); @@ -382,41 +398,34 @@ describe('populateCsharpNamespaceSiblings', () => { referenceSites: Object.freeze([]), } as ParsedFile, ]; - const bindingAugmentations = new Map>(); - const workspaceFqnBindings = new Map(); + const indexes = emptyIndexes(); - populateCsharpNamespaceSiblings( - parsedFiles, - { - bindings: new Map(), - bindingAugmentations, - workspaceFqnBindings, - } as unknown as ScopeResolutionIndexes, - { - fileContents: new Map([ - ['a.cs', 'class A { }\n'], // no `namespace` => global - ['b.cs', 'class B { }\n'], - ]), - }, - ); + populateCsharpNamespaceSiblings(parsedFiles, indexes as unknown as ScopeResolutionIndexes, { + fileContents: new Map([ + ['a.cs', 'class A { }\n'], // no `namespace` => global + ['b.cs', 'class B { }\n'], + ]), + }); - // Global types are reachable workspace-wide via simple-name keys. - expect(workspaceFqnBindings.get('A')?.map((b) => b.def.nodeId)).toEqual(['def:a.A']); - expect(workspaceFqnBindings.get('B')?.map((b) => b.def.nodeId)).toEqual(['def:b.B']); + const global = indexes.namespaceFqnBindings.get(''); + expect(global?.get('A')?.map((b) => b.def.nodeId)).toEqual(['def:a.A']); + expect(global?.get('B')?.map((b) => b.def.nodeId)).toEqual(['def:b.B']); // O(D) invariant: one entry per unique simple name, never scopes x defs. - expect(workspaceFqnBindings.size).toBe(2); - // The whole point of the fast path: no per-scope augmentation explosion. - expect(bindingAugmentations.size).toBe(0); - // Workspace entries carry the cross-file `namespace` origin (so shadowing - // precedence in lookupBindingsAt orders them after local/finalized). - expect(workspaceFqnBindings.get('A')?.[0]?.origin).toBe('namespace'); + expect(global?.size).toBe(2); + // Cross-file `namespace` origin, so lookupBindingsAt orders it after + // local/finalized bindings. + expect(global?.get('A')?.[0]?.origin).toBe('namespace'); + // Neither the per-scope nor the scope-independent channel is used. + expect(indexes.bindingAugmentations.size).toBe(0); + expect(indexes.workspaceFqnBindings.size).toBe(0); + // Every file can see the global namespace through its accessibility list. + expect(indexes.accessibleNamespacesByScope.get(moduleA.id)).toEqual(['']); + expect(indexes.accessibleNamespacesByScope.get(moduleB.id)).toEqual(['']); }); - it('keeps every declaration of a repeated global simple name (partial classes across files)', () => { - // Two global-namespace files each declare `Foo` (a partial class split - // across files => distinct nodeIds, same simple name). Both must survive - // in the workspace channel — the fast path de-dups by nodeId, not by name, - // so partial-class members from both files stay resolvable. + it('keeps every declaration of a repeated global simple name', () => { + // Two global-namespace files declare `Foo` with distinct nodeIds. + // Both declarations must survive the shared channel. const foo1 = classDef('def:foo1.Foo', 'foo1.cs', 'Foo'); const foo2 = classDef('def:foo2.Foo', 'foo2.cs', 'Foo'); const moduleA = scope('scope:foo1:module', 'Module', 'foo1.cs'); @@ -441,33 +450,111 @@ describe('populateCsharpNamespaceSiblings', () => { referenceSites: Object.freeze([]), } as ParsedFile, ]; - const bindingAugmentations = new Map>(); - const workspaceFqnBindings = new Map(); + const indexes = emptyIndexes(); - populateCsharpNamespaceSiblings( - parsedFiles, - { - bindings: new Map(), - bindingAugmentations, - workspaceFqnBindings, - } as unknown as ScopeResolutionIndexes, - { - fileContents: new Map([ - ['foo1.cs', 'class Foo { }\n'], - ['foo2.cs', 'class Foo { }\n'], - ]), - }, - ); + populateCsharpNamespaceSiblings(parsedFiles, indexes as unknown as ScopeResolutionIndexes, { + fileContents: new Map([ + ['foo1.cs', 'class Foo { }\n'], + ['foo2.cs', 'class Foo { }\n'], + ]), + }); - // Both partial declarations are kept (de-dup is by nodeId, not name). + // Both declarations are kept (de-dup is by nodeId, not name). expect( - workspaceFqnBindings - .get('Foo') + indexes.namespaceFqnBindings + .get('') + ?.get('Foo') ?.map((b) => b.def.nodeId) .sort(), ).toEqual(['def:foo1.Foo', 'def:foo2.Foo']); - expect(bindingAugmentations.size).toBe(0); + expect(indexes.bindingAugmentations.size).toBe(0); }); + + // C# name lookup order (ECMA-334, namespace and type names): the declared + // namespace, that declaration's using directives, then each enclosing + // namespace; the global namespace is the outermost, and the compilation + // unit's using directives come after its own types. Dotted prefixes of using + // targets are not lookup scopes and rank last. + const at = (line: number, col: number) => ({ + startLine: line, + startCol: col, + endLine: line, + endCol: col + 1, + }); + const usingOf = (target: string, line: number, col = 0): ParsedImport => ({ + kind: 'namespace', + localName: target.slice(target.lastIndexOf('.') + 1), + importedName: target, + targetRaw: target, + atRange: at(line, col), + }); + it.each([ + ['a file outside any namespace', 'class P { }\n', [], [], ['']], + [ + 'a compilation-unit using in a global file', + 'using Billing.Core;\nclass P { }\n', + [], + [usingOf('Billing.Core', 1)], + ['', 'Billing.Core', 'Billing'], + ], + [ + 'a compilation-unit using before a file-scoped namespace', + 'using Billing;\nnamespace Audit.Trail;\nclass R { }\n', + [{ ...at(2, 0), endCol: 22 }], + [usingOf('Billing', 1)], + ['Audit.Trail', 'Audit', '', 'Billing'], + ], + [ + 'a using after a file-scoped namespace', + 'namespace Audit.Trail;\nusing Billing;\nclass R { }\n', + [{ ...at(1, 0), endCol: 22 }], + [usingOf('Billing', 2)], + ['Audit.Trail', 'Billing', 'Audit', ''], + ], + [ + 'a using inside a block namespace', + 'namespace Audit.Trail {\n using Billing;\n class R { }\n}\n', + [{ startLine: 1, startCol: 0, endLine: 4, endCol: 1 }], + [usingOf('Billing', 2, 2)], + ['Audit.Trail', 'Billing', 'Audit', ''], + ], + ])( + 'orders accessible namespaces in C# lookup order for %s', + (_label, content, namespaceRanges, parsedImports, expected) => { + const moduleScope = scope('scope:f:module', 'Module', 'f.cs'); + const namespaceScopes = namespaceRanges.map( + (range, i) => + ({ + ...scope(`scope:f:ns${i}`, 'Namespace', 'f.cs', moduleScope.id), + range, + }) as Scope, + ); + const parsedFiles: ParsedFile[] = [ + { + filePath: 'f.cs', + moduleScope: moduleScope.id, + scopes: Object.freeze([moduleScope, ...namespaceScopes]), + parsedImports: Object.freeze(parsedImports), + localDefs: Object.freeze([]), + referenceSites: Object.freeze([]), + } as ParsedFile, + ]; + const indexes = emptyIndexes(); + + populateCsharpNamespaceSiblings(parsedFiles, indexes as unknown as ScopeResolutionIndexes, { + fileContents: new Map([['f.cs', content]]), + }); + + const blockNamespace = + _label === 'a using inside a block namespace' ? namespaceScopes[0] : undefined; + expect(indexes.accessibleNamespacesByScope.get(blockNamespace?.id ?? moduleScope.id)).toEqual( + expected, + ); + if (blockNamespace !== undefined) { + expect(indexes.accessibleNamespacesByScope.get(moduleScope.id)).toEqual(['']); + } + }, + ); }); describe('csharpReceiverBinding', () => { diff --git a/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts b/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts index d7b7084dd4..a69499504d 100644 --- a/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts +++ b/gitnexus/test/unit/scope-resolution/csharp/csharp-imports.test.ts @@ -18,7 +18,7 @@ import { getMaxFileSizeBytes } from '../../../../src/core/ingestion/utils/max-fi import { csharpSuffixFallbackAllowed, importAlignsWithDeclaredNamespaces, -} from '../../../../src/core/ingestion/csharp-namespace-gate.js'; +} from '../../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { csharpScopeResolver } from '../../../../src/core/ingestion/languages/csharp/scope-resolver.js'; import type { CSharpProjectConfig } from '../../../../src/core/ingestion/language-config.js'; import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; diff --git a/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts b/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts index 690ef291d7..7da9cb6f02 100644 --- a/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts +++ b/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts @@ -11,8 +11,8 @@ * reports a blast radius into code that cannot be affected. The reporter * measured 44 of 74 cross-package edges landing on two such files. * - * The mechanism is shared, which is why this file is: `import-resolvers/ - * utils.ts:suffixResolve` asks "does any file in this repo have a path ending + * The shared `utils/suffix-index.ts:suffixResolve` helper asks + * "does any file in this repo have a path ending * in this specifier?", retrying with each leading segment dropped, and most * languages still end their resolution chain there. * diff --git a/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts b/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts deleted file mode 100644 index 8459fc4bad..0000000000 --- a/gitnexus/test/unit/scope-resolution/import-target-adapter.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Unit tests for `import-target-adapter` (RFC #909 Ring 2 PKG #922). - * - * Exercises the language-dispatching FinalizeHook. We don't need the - * real per-language resolvers here — mock `ImportResolverFn`s let each - * branch be tested in isolation. Real-resolver integration is covered - * by the existing per-language import-resolver test suites. - */ - -import { describe, it, expect } from 'vitest'; -import { SupportedLanguages } from 'gitnexus-shared'; -import { - buildImportTargetWorkspace, - resolveImportTargetAcrossLanguages, - type ImportTargetWorkspace, -} from '../../../src/core/ingestion/import-target-adapter.js'; -import type { - ImportResolverFn, - ResolveCtx, -} from '../../../src/core/ingestion/import-resolvers/types.js'; -import type { LanguageProvider } from '../../../src/core/ingestion/language-provider.js'; - -// ─── Helpers ─────────────────────────────────────────────────────────────── - -const emptyCtx: ResolveCtx = { - allFilePaths: new Set(), - allFileList: [], - normalizedFileList: [], - index: { bySuffix: new Map() } as unknown as ResolveCtx['index'], - resolveCache: new Map(), - configs: { - tsconfigPaths: null, - goModule: null, - composerConfig: null, - swiftPackageConfig: null, - csharpConfigs: [], - }, -}; - -function fakeProvider(importResolver: ImportResolverFn | undefined): LanguageProvider { - return { importResolver } as unknown as LanguageProvider; -} - -function workspace( - entries: Array<[SupportedLanguages, ImportResolverFn | undefined]>, -): ImportTargetWorkspace { - const providers = new Map(); - for (const [lang, resolver] of entries) providers.set(lang, fakeProvider(resolver)); - return buildImportTargetWorkspace(providers, emptyCtx); -} - -// ─── buildImportTargetWorkspace ──────────────────────────────────────────── - -describe('buildImportTargetWorkspace', () => { - it('registers languages that expose an importResolver', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(ws.perLanguage.has(SupportedLanguages.Python)).toBe(true); - }); - - it("skips providers whose importResolver is absent (defensive — shouldn't happen in practice)", () => { - const ws = workspace([[SupportedLanguages.Python, undefined]]); - expect(ws.perLanguage.size).toBe(0); - }); - - it('threads the shared ResolveCtx into every entry', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['x.py'] }); - const tsResolver: ImportResolverFn = () => ({ kind: 'files', files: ['x.ts'] }); - const ws = workspace([ - [SupportedLanguages.Python, pyResolver], - [SupportedLanguages.TypeScript, tsResolver], - ]); - expect(ws.perLanguage.get(SupportedLanguages.Python)!.ctx).toBe(emptyCtx); - expect(ws.perLanguage.get(SupportedLanguages.TypeScript)!.ctx).toBe(emptyCtx); - }); -}); - -// ─── resolveImportTargetAcrossLanguages ──────────────────────────────────── - -describe('resolveImportTargetAcrossLanguages', () => { - it('dispatches to the resolver for the fromFile extension', () => { - let seenPath: string | undefined; - const pyResolver: ImportResolverFn = (raw, _file) => { - seenPath = raw; - return { kind: 'files', files: ['models/user.py'] }; - }; - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - const result = resolveImportTargetAcrossLanguages('models.user', 'src/app.py', ws); - expect(seenPath).toBe('models.user'); - expect(result).toBe('models/user.py'); - }); - - it('routes to different resolvers based on the fromFile extension', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const tsResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.ts'] }); - const ws = workspace([ - [SupportedLanguages.Python, pyResolver], - [SupportedLanguages.TypeScript, tsResolver], - ]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBe('resolved.py'); - expect(resolveImportTargetAcrossLanguages('x', 'a.ts', ws)).toBe('resolved.ts'); - }); - - it('returns null when the resolver returns null', () => { - const pyResolver: ImportResolverFn = () => null; - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(resolveImportTargetAcrossLanguages('external_pkg', 'app.py', ws)).toBeNull(); - }); - - it('takes the first file from a package-kind result', () => { - const resolver: ImportResolverFn = () => ({ - kind: 'package', - files: ['pkg/index.py', 'pkg/other.py'], - dirSuffix: 'pkg', - }); - const ws = workspace([[SupportedLanguages.Python, resolver]]); - expect(resolveImportTargetAcrossLanguages('pkg', 'app.py', ws)).toBe('pkg/index.py'); - }); - - it('returns null when a result has kind=files but an empty files[]', () => { - // Defensive: resolvers shouldn't return this shape, but tolerate it. - const resolver: ImportResolverFn = () => ({ kind: 'files', files: [] }); - const ws = workspace([[SupportedLanguages.Python, resolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); - - it('returns null when no resolver is registered for the language', () => { - const ws = workspace([]); // empty - // .py file but no Python resolver registered - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); - - it('returns null when fromFile has an unknown extension', () => { - const pyResolver: ImportResolverFn = () => ({ kind: 'files', files: ['resolved.py'] }); - const ws = workspace([[SupportedLanguages.Python, pyResolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'README.xyz', ws)).toBeNull(); - }); - - it('returns null when workspaceIndex is undefined / malformed', () => { - expect(resolveImportTargetAcrossLanguages('x', 'a.py', undefined)).toBeNull(); - // Cast to exercise the runtime guard against caller misuse. - expect(resolveImportTargetAcrossLanguages('x', 'a.py', {} as unknown)).toBeNull(); - }); - - it('swallows resolver exceptions and returns null (treated upstream as unresolved)', () => { - const throwingResolver: ImportResolverFn = () => { - throw new Error('resolver boom'); - }; - const ws = workspace([[SupportedLanguages.Python, throwingResolver]]); - expect(resolveImportTargetAcrossLanguages('x', 'a.py', ws)).toBeNull(); - }); -}); diff --git a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts index c01867847b..c23312a90f 100644 --- a/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/import-target-index-parity.test.ts @@ -68,10 +68,10 @@ import { clearKotlinPackageFacts, setKotlinPackageFact, } from '../../../src/core/ingestion/languages/kotlin/package-facts.js'; -import { resolveRubyImportInternal } from '../../../src/core/ingestion/import-resolvers/ruby.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; +import { resolveRubyImportInternal } from '../../../src/core/ingestion/languages/ruby/import-helpers.js'; +import { buildSuffixIndex } from '../../../src/core/ingestion/utils/suffix-index.js'; import { isHeritageMarker } from '../../../src/core/ingestion/utils/heritage-marker.js'; -import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/csharp-namespace-gate.js'; +import { csharpSuffixFallbackAllowed } from '../../../src/core/ingestion/languages/csharp/namespace-gate.js'; import { DART_HERITAGE_PREFIX } from '../../../src/core/ingestion/languages/dart/interpret.js'; import { CountingSet, countedParsedFilesWith } from '../../helpers/counting-file-set.js'; diff --git a/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts b/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts index 69bd454873..ee7adb690f 100644 --- a/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts +++ b/gitnexus/test/unit/scope-resolution/import-target-index-reuse.contract.test.ts @@ -418,9 +418,8 @@ const FIXTURES: ReadonlyMap = new Map< // `App\Legacy\Ghost`, whose directory does not exist — costs one // traversal per import: swapping this fixture onto that spelling posts // 201 traversals for 200 imports against 3 for two (measured). The - // residual is real and is out of this file's reach — it lives in - // `import-resolvers/php.ts`, which the #2901 hoist does not touch — so it - // is pinned by name in `php-import-target-parity.test.ts` and this + // residual lives in `languages/php/import-helpers.ts` and is pinned by + // name in `php-import-target-parity.test.ts`. This // fixture takes the leg that IS indexed rather than restating it. missTarget: (i) => `Vendor${i}\\Ghost\\Missing`, hitTarget: 'App\\Models\\User', diff --git a/gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts b/gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts index 3315d25bdc..45ae37cfde 100644 --- a/gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts +++ b/gitnexus/test/unit/scope-resolution/lexical-name-claims.test.ts @@ -43,12 +43,14 @@ function indexes( return { scopeTree: { getScope: (id: string) => [inner, outer].find((s) => s.id === id), + getChildren: (id: string) => + [inner, outer].filter((entry) => entry.parent === id).map((entry) => entry.id), byId: new Map([ [inner.id, inner], [outer.id, outer], ]), }, - moduleScopes: new Map([['caller.ts', outer.id]]), + moduleScopes: { byFilePath: new Map([['caller.ts', outer.id]]) }, bindings: new Map(), bindingAugmentations: new Map(), imports: new Map(), diff --git a/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts b/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts index 25118b542e..0c8e50d55f 100644 --- a/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts +++ b/gitnexus/test/unit/scope-resolution/php-import-target-parity.test.ts @@ -54,8 +54,8 @@ import { resolvePhpImportTargetInternal, type PhpResolveContext, } from '../../../src/core/ingestion/languages/php/import-target.js'; -import { resolvePhpImportInternal } from '../../../src/core/ingestion/import-resolvers/php.js'; -import { buildSuffixIndex } from '../../../src/core/ingestion/import-resolvers/utils.js'; +import { resolvePhpImportInternal } from '../../../src/core/ingestion/languages/php/import-helpers.js'; +import { buildSuffixIndex } from '../../../src/core/ingestion/utils/suffix-index.js'; import type { ComposerConfig } from '../../../src/core/ingestion/language-config.js'; import type { ImportResolutionContext } from '../../../src/core/ingestion/scope-resolution/contract/scope-resolver.js'; import { CountingSet } from '../../helpers/counting-file-set.js'; @@ -434,7 +434,7 @@ const GENERATED_CASES: readonly Case[] = generatedTargets().flatMap((target) => * - the PSR-4 namespace-directory fallback is NOT gated on the imported symbol * kind. It fires for a class import too, whenever the class-style path * misses, and returns the FIRST `.php` file directly in the namespace - * directory — see the "known limitation" note atop `import-resolvers/php.ts`. + * directory — see the "known limitation" note atop `languages/php/import-helpers.ts`. * Cases that lean on it are marked; their answers are order-dependent in * general and deterministic here only because the fixture pins the order. */ diff --git a/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts b/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts index 94a22f98cf..2c7e2697fa 100644 --- a/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts +++ b/gitnexus/test/unit/scope-resolution/python/python-import-probe-count.test.ts @@ -46,7 +46,7 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import { pythonScopeResolver } from '../../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { resolvePythonImportInternal } from '../../../../src/core/ingestion/import-resolvers/python.js'; +import { resolvePythonImportInternal } from '../../../../src/core/ingestion/languages/python/import-helpers.js'; import { NO_PARSED_FILES, pythonNamedImport, diff --git a/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts b/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts index f29ac144f7..e80926f351 100644 --- a/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts +++ b/gitnexus/test/unit/scope-resolution/python/python-importer-ancestors.test.ts @@ -53,7 +53,7 @@ import { describe, expect, it } from 'vitest'; import type { ParsedImport } from 'gitnexus-shared'; import { pythonScopeResolver } from '../../../../src/core/ingestion/languages/python/scope-resolver.js'; -import { getPythonFileIndex } from '../../../../src/core/ingestion/import-resolvers/python-file-index.js'; +import { getPythonFileIndex } from '../../../../src/core/ingestion/languages/python/import-file-index.js'; import { IMPORTER_PATH_SHAPES, countedParsedFiles, diff --git a/gitnexus/test/unit/scope-resolution/r/r-source-import-lookup.test.ts b/gitnexus/test/unit/scope-resolution/r/r-source-import-lookup.test.ts index 82c2f56392..42f21f7cca 100644 --- a/gitnexus/test/unit/scope-resolution/r/r-source-import-lookup.test.ts +++ b/gitnexus/test/unit/scope-resolution/r/r-source-import-lookup.test.ts @@ -10,7 +10,7 @@ import { resolveRImportInternal, resolveRImportTarget, } from '../../../../src/core/ingestion/languages/r/import-target.js'; -import { getWorkspaceFileIndex } from '../../../../src/core/ingestion/import-resolvers/workspace-file-index.js'; +import { getWorkspaceFileIndex } from '../../../../src/core/ingestion/utils/workspace-file-index.js'; // Raw spellings: the Windows-style duplicate of 'pkg/R/dup.R' comes FIRST, so first-wins must // return the backslash spelling for both lookups. diff --git a/gitnexus/test/unit/scope-resolution/rust/rust-call-return-path.test.ts b/gitnexus/test/unit/scope-resolution/rust/rust-call-return-path.test.ts new file mode 100644 index 0000000000..f9dbcb8d22 --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/rust/rust-call-return-path.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import type { CaptureMatch } from 'gitnexus-shared'; +import { interpretRustTypeBinding } from '../../../../src/core/ingestion/languages/rust/interpret.js'; + +const RANGE = { startLine: 0, startCol: 0, endLine: 0, endCol: 0 }; + +/** A minimal `let x = ()` call-return CaptureMatch. */ +function callReturnBinding(callee: string): CaptureMatch { + return { + '@type-binding.name': { name: '@type-binding.name', range: RANGE, text: 'x' }, + '@type-binding.type': { name: '@type-binding.type', range: RANGE, text: callee }, + '@type-binding.call-return': { name: '@type-binding.call-return', range: RANGE, text: '' }, + }; +} + +/** + * Preserve qualified callees until finalized scope ownership distinguishes a + * module factory from an associated function. Self and generic constructors + * keep their existing type spelling (#3498 follow-up). + */ +describe('Rust call-return binding of a qualified callee', () => { + it.each([ + ['Foo::new', 'Foo::new'], + ['Self::new', 'Self'], + ['Vec::::new', 'Vec'], + ['make', 'make'], + ])('reads %s as %s', (callee, expected) => { + expect(interpretRustTypeBinding(callReturnBinding(callee))?.rawTypeName).toBe(expected); + }); + + it.each(['rp::make', 'crate::modx::make', 'self::make', 'super::modx::make', 'a::b::make'])( + 'keeps the module path %s', + (callee) => { + expect(interpretRustTypeBinding(callReturnBinding(callee))?.rawTypeName).toBe(callee); + }, + ); +}); diff --git a/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts b/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts index bb41357b7e..e77e6272bb 100644 --- a/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts +++ b/gitnexus/test/unit/scope-resolution/typescript/typescript-imports.test.ts @@ -14,7 +14,7 @@ import { resolveTsImportTarget, type TsResolveContext, } from '../../../../src/core/ingestion/languages/typescript/import-target.js'; -import * as importResolverUtils from '../../../../src/core/ingestion/import-resolvers/utils.js'; +import * as importResolverUtils from '../../../../src/core/ingestion/utils/suffix-index.js'; import { typescriptScopeResolver } from '../../../../src/core/ingestion/languages/typescript/scope-resolver.js'; import type { SyntaxNode } from '../../../../src/core/ingestion/utils/ast-helpers.js'; import type { ParsedImport, WorkspaceIndex } from 'gitnexus-shared'; diff --git a/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts b/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts index 641d96f398..26e5a12190 100644 --- a/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts +++ b/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts @@ -33,7 +33,7 @@ function dropped( name: string, siteKind: 'call' | 'read' | 'write' = 'call', receiverOrigin?: ReceiverOrigin, -): ResolutionOutcome { +): Extract { return { kind: 'suppressed', reason: 'receiver-unresolved', @@ -48,6 +48,19 @@ function dropped( } describe('summarizeUnresolvedReceivers', () => { + it.each(['call', 'read', 'write'] as const)( + 'counts owned-but-unbound %s sites only when they are calls', + (siteKind) => { + const outcome: ResolutionOutcome = { + ...dropped('go', siteKind), + reason: 'receiver-owned-but-unbound', + }; + expect(summarizeUnresolvedReceivers([outcome])).toEqual( + siteKind === 'call' ? { counts: { go: 1 }, totalSites: 1 } : undefined, + ); + }, + ); + it('returns undefined when nothing was dropped, so a clean repo stores no key', () => { expect(summarizeUnresolvedReceivers([])).toBeUndefined(); }); diff --git a/gitnexus/test/unit/scope-resolution/walkers-augmentations.test.ts b/gitnexus/test/unit/scope-resolution/walkers-augmentations.test.ts index 60bbadb87c..93fd108872 100644 --- a/gitnexus/test/unit/scope-resolution/walkers-augmentations.test.ts +++ b/gitnexus/test/unit/scope-resolution/walkers-augmentations.test.ts @@ -85,6 +85,23 @@ function indexesForScopeLookup( } describe('lookupBindingsAt', () => { + it('retains ambiguity within the winning namespace tier and hides later tiers', () => { + const indexes: ScopeResolutionIndexes = { + ...indexesWith({}), + accessibleNamespacesByScope: new Map([[SCOPE, ['first', 'second', 'outer']]]), + namespaceLookupTiersByScope: new Map([[SCOPE, [['first', 'second'], ['outer']]]]), + namespaceFqnBindings: new Map([ + ['first', new Map([['name', [ref('A', 'namespace')]]])], + ['second', new Map([['name', [ref('B', 'namespace')]]])], + ['outer', new Map([['name', [ref('C', 'namespace')]]])], + ]), + }; + expect(lookupBindingsAt(SCOPE, 'name', indexes).map((binding) => binding.def.nodeId)).toEqual([ + 'A', + 'B', + ]); + }); + it('returns the finalized bucket when augmentations are absent', () => { const finalized = [ref('A'), ref('B')]; const out = lookupBindingsAt(SCOPE, 'name', indexesWith({ finalized })); diff --git a/gitnexus/test/unit/suffix-index-ambiguity.test.ts b/gitnexus/test/unit/suffix-index-ambiguity.test.ts index fd786c045a..cf196effae 100644 --- a/gitnexus/test/unit/suffix-index-ambiguity.test.ts +++ b/gitnexus/test/unit/suffix-index-ambiguity.test.ts @@ -8,13 +8,9 @@ */ import { describe, it, expect } from 'vitest'; -import { - buildSuffixIndex, - suffixResolve, -} from '../../src/core/ingestion/import-resolvers/utils.js'; -import { resolvePythonImportInternal } from '../../src/core/ingestion/import-resolvers/python.js'; -import { resolveImportPath } from '../../src/core/ingestion/import-resolvers/standard.js'; -import { SupportedLanguages } from '../../src/config/supported-languages.js'; +import { buildSuffixIndex, suffixResolve } from '../../src/core/ingestion/utils/suffix-index.js'; +import { resolvePythonImportInternal } from '../../src/core/ingestion/languages/python/import-helpers.js'; +import { EXTENSIONS } from '../../src/core/ingestion/languages/import-candidates.js'; // --------------------------------------------------------------------------- // Helpers @@ -24,8 +20,7 @@ function makeCtx(files: string[]) { const normalized = files.map((f) => f.replace(/\\/g, '/')); const allFilesSet = new Set(files); const index = buildSuffixIndex(normalized, files); - const cache = new Map(); - return { files, normalized, allFilesSet, index, cache }; + return { files, normalized, allFilesSet, index }; } /** Simulate the full dispatch: resolvePythonImport first, then suffixResolve fallback. */ @@ -39,27 +34,7 @@ function resolvePython( if (importPath.startsWith('.')) return null; const pathLike = importPath.replace(/\./g, '/'); const parts = pathLike.split('/').filter(Boolean); - return suffixResolve(parts, ctx.normalized, ctx.files, ctx.index); -} - -/** For non-Python languages, delegate directly to standard resolveImportPath. */ -function resolve( - currentFile: string, - importPath: string, - language: SupportedLanguages, - ctx: ReturnType, -): string | null { - return resolveImportPath( - currentFile, - importPath, - ctx.allFilesSet, - ctx.files, - ctx.normalized, - ctx.cache, - language, - null, - ctx.index, - ); + return suffixResolve(parts, ctx.normalized, ctx.files, EXTENSIONS, ctx.index); } // --------------------------------------------------------------------------- @@ -171,52 +146,3 @@ describe('resolvePythonImport — namespace packages (no __init__.py)', () => { expect(result).toBe('app/services/user/model.py'); }); }); - -// --------------------------------------------------------------------------- -// Ruby: bare require does NOT use proximity -// --------------------------------------------------------------------------- - -describe('resolveImportPath — Ruby bare require does not use proximity', () => { - it('returns first-indexed file for bare require (Ruby $LOAD_PATH excludes current directory)', () => { - const ctx = makeCtx([ - 'lib/core/helpers.rb', // indexed first - 'lib/utils/helpers.rb', - 'lib/utils/formatter.rb', - ]); - - // Ruby bare `require 'helpers'` searches $LOAD_PATH — current directory not included. - // No proximity bias; first-indexed file is returned, same as before. - const result = resolve('lib/utils/formatter.rb', 'helpers', SupportedLanguages.Ruby, ctx); - expect(result).toBe('lib/core/helpers.rb'); - }); - - it('resolves require_relative (dot-prefixed) to same-directory file via generic relative resolver', () => { - const ctx = makeCtx(['lib/utils/helpers.rb', 'lib/utils/formatter.rb']); - - // require_relative arrives as "./" — caught by generic relative resolver, not proximity - const result = resolve('lib/utils/formatter.rb', './helpers', SupportedLanguages.Ruby, ctx); - expect(result).toBe('lib/utils/helpers.rb'); - }); -}); - -// --------------------------------------------------------------------------- -// Other languages: no proximity applied -// --------------------------------------------------------------------------- - -describe('resolveImportPath — no proximity for Java or TypeScript', () => { - it('Java: fully-qualified import resolves to the correct file via unique suffix', () => { - const ctx = makeCtx(['src/com/a/User.java', 'src/com/b/User.java', 'src/com/b/Service.java']); - - // "com.b.User" → "com/b/User" → unique suffix; no ambiguity - const result = resolve('src/com/b/Service.java', 'com.b.User', SupportedLanguages.Java, ctx); - expect(result).toBe('src/com/b/User.java'); - }); - - it('TypeScript: relative import resolves via generic relative resolver', () => { - const ctx = makeCtx(['src/services/user.ts', 'src/services/auth.ts', 'src/models/user.ts']); - - // "./user" is explicit relative — resolved before proximity is checked - const result = resolve('src/services/auth.ts', './user', SupportedLanguages.TypeScript, ctx); - expect(result).toBe('src/services/user.ts'); - }); -}); diff --git a/gitnexus/test/unit/zig-extractors.test.ts b/gitnexus/test/unit/zig-extractors.test.ts index 0854f5fa7c..86c3322835 100644 --- a/gitnexus/test/unit/zig-extractors.test.ts +++ b/gitnexus/test/unit/zig-extractors.test.ts @@ -51,6 +51,7 @@ import { import { createFieldExtractor } from '../../src/core/ingestion/field-extractors/generic.js'; import { zigFieldConfig } from '../../src/core/ingestion/field-extractors/configs/zig.js'; import { zigProvider } from '../../src/core/ingestion/languages/zig.js'; +import { zigScopeResolver } from '../../src/core/ingestion/languages/zig/scope-resolver.js'; import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.js'; import { extract as extractScopes } from '../../src/core/ingestion/scope-extractor.js'; import { populateClassOwnedMembers } from '../../src/core/ingestion/scope-resolution/scope/walkers.js'; @@ -372,7 +373,9 @@ describeZig('Zig scope captures — `@import` in TYPE position is not an import const importNames = matches .filter((m) => m['@import.name'] !== undefined) .map((m) => `${m['@import.name']!.text}<-${m['@import.imported']?.text ?? '*'}`); - expect(importNames).toEqual(['z<-T']); + // `z`'s value reads `T` off `@import("n.zig")`, so that module is bound + // under its own text too (#3498 F-A); the type-position one is not. + expect(importNames).toEqual(['@import("n.zig")<-*', 'z<-T']); const variables = matches .filter((m) => m['@declaration.variable'] !== undefined) .map((m) => m['@declaration.name']!.text); @@ -831,6 +834,15 @@ test { importedName: 'Counter', targetRaw: 'net/counter.zig', }, + // The module a one-member import reads its member off, bound under the + // builtin's own text so the `.Counter` / `.Same` reads resolve through + // it (#3498 F-A) — once per distinct source per scope. + { + kind: 'namespace', + localName: '@import("counter.zig")', + importedName: 'counter', + targetRaw: 'counter.zig', + }, { kind: 'alias', localName: 'Renamed', @@ -964,6 +976,72 @@ pub fn f() !void { ]); }); + it.each([ + [ + 'a file-level re-export', + 'pub const Thing = @import("thing.zig").Thing;\n', + 'Thing', + 'thing.zig', + 'Thing', + ], + [ + 'a renaming alias', + 'const Gauge = @import("dom_utils.zig").DEFAULT_NS;\n', + 'Gauge', + 'dom_utils.zig', + 'DEFAULT_NS', + ], + [ + 'a fn-local alias', + 'fn f() void {\n const Counter = @import("counter.zig").Counter;\n _ = Counter;\n}\n', + 'Counter', + 'counter.zig', + 'Counter', + ], + ])( + 'binds the module of a one-member import (%s) under its own text, as the deep form already is', + (_shape, src, alias, file, member) => { + // `const X = @import("f.zig").X;` reads `X` off an `@import(…)` receiver. + // The named-import rule claims that builtin, so the receiver binding the + // deep form (`@import("lib.zig").B.work`) gets was never emitted and the + // read was a receiver drop (#3498 triage, F-A). The named import itself + // is unchanged; the module handle is added beside it. + const groups = emitZigScopeCaptures(src, 'x.zig'); + const handle = `@import("${file}")`; + const imports = groups + .filter((m) => m['@import.source'] !== undefined) + .map((m) => `${m['@import.name']?.text}<-${m['@import.imported']?.text ?? '*'}`); + expect(imports.sort()).toEqual([`${handle}<-*`, `${alias}<-${member}`]); + const reads = groups + .filter((m) => m['@reference.read'] !== undefined && m['@reference.name']?.text === member) + .map((m) => m['@reference.receiver']?.text); + expect(reads).toEqual([handle]); + }, + ); + + it('binds the namespace receiver of an explicitly typed member alias', () => { + const source = 'const Thing: type = @import("thing.zig").Thing;'; + const groups = emitZigScopeCaptures(source, 'main.zig'); + const handles = groups + .map(interpretZigImport) + .filter((imp) => imp?.kind === 'namespace') + .map((imp) => imp?.localName); + expect(handles).toEqual(['@import("thing.zig")']); + }); + + it('keeps both namespace handles when repeated inline imports use different whitespace', () => { + const source = `pub fn entry() void { + const Counter = @import("lib.zig").Counter; + _ = Counter; + @import( "lib.zig" ).work(); + }`; + const handles = emitZigScopeCaptures(source, 'main.zig') + .map(interpretZigImport) + .filter((imp) => imp?.kind === 'namespace') + .map((imp) => imp?.localName); + expect(handles.sort()).toEqual(['@import( "lib.zig" )', '@import("lib.zig")'].sort()); + }); + it('a function-scoped @import is not deferred: Zig imports are compile-time (importsExecuteWhereWritten: false)', () => { // C `#include` and Rust `use` answer the same. Without the flag the scope // extractor marks a body-level `@import` `runsOnlyWhenCalled`, hiding a @@ -1666,6 +1744,22 @@ const R = struct { pub fn go(self: *R) void { const q = self.current(); } }; ]); }); + it.each([ + ['Stack', true], + ['util.List', true], + ['@import("x.zig").Foo', true], + ['makeThing', false], + ['std.mem.eql', false], + ['self.items', false], + ])( + 'the resolver reads a receiver call of `%s` as a type application: %s (#3498 F-D)', + (callee, expected) => { + // The text twin of `isZigTypeConstructorCall`, for the compound + // resolver: `Stack(u8).init()` calls `init` on the TYPE `Stack(u8)`. + expect(zigScopeResolver.isTypeApplicationCall?.(callee)).toBe(expected); + }, + ); + it('emits nothing for a TitleCase callee (type constructor), a decl literal, an identifier or a field chain', () => { const src = ` fn f() void { @@ -1708,6 +1802,45 @@ pub fn make3() !List(u8) {} ]); }); + it.each([ + [ + 'a same-file constructor', + 'pub fn Bridge(comptime T: type) type {\n return Builder(T);\n}\n', + [ret('Bridge', 'Builder')], + ], + [ + 'a qualified constructor, past a comment', + 'pub fn Bridge(comptime T: type) type {\n // forwards\n return other.Builder(T);\n}\n', + [ret('Bridge', 'other.Builder')], + ], + [ + 'a body that is more than the return', + 'pub fn Bridge(comptime T: type) type {\n const U = T;\n return Builder(U);\n}\n', + [], + ], + [ + 'a value call (camelCase callee)', + 'pub fn Bridge(comptime T: type) type {\n return make(T);\n}\n', + [], + ], + [ + 'a call of a parameter', + 'pub fn Apply(comptime F: fn (type) type) type {\n return F(u8);\n}\n', + [], + ], + ['a container return', 'pub fn List(comptime T: type) type {\n return struct {};\n}\n', []], + ])( + 'binds a FORWARDING type constructor to the type it forwards to — %s', + (_shape, src, expected) => { + // `fn Bridge(comptime T: type) type { return Builder(T); }` (Lightpanda's + // `js.Bridge(T)`) names no container of its own: `type` returns bind + // nothing, so a receiver typed `Bridge(X)` reached a Function that owns + // no members (#3498 triage, F-B). `Bridge(X)` IS `Builder(X)`, so the + // return binding names the callee, declared in Bridge's own scope. + expect(bindingsOf(src)).toEqual(expected); + }, + ); + it('a file-struct’s `@This()` return names the file stem', () => { const src = ` count: u32 = 0, @@ -1906,6 +2039,34 @@ test "Page: local state" { expect(lts.every((d) => d.ownerId !== undefined)).toBe(true); }); + it('a member read off an anonymous container names it by its identity and sits at the member (#3498 F-C)', () => { + // `struct { fn lessThan … }.lessThan`: the receiver capture was the whole + // container body, which names nothing, and the site's anchor started at + // `struct` — INSIDE the container's own Class scope, so the read was + // attributed to the container itself. The receiver is the identity the + // container is minted under, and the site is anchored on the member, which + // is evaluated in the enclosing scope. + const sites = emitZigScopeCaptures(src, 'src/Page.zig') + .map((m) => ({ m, kind: ['@reference.read', '@reference.value-ref'].find((k) => k in m) })) + .filter( + ({ m, kind }) => + kind !== undefined && ['lessThan', 'it'].includes(m['@reference.name']?.text ?? ''), + ) + .map(({ m, kind }) => ({ + site: `${kind} ${m['@reference.receiver']?.text} . ${m['@reference.name']?.text}`, + atMember: + JSON.stringify(m[kind ?? '']?.range) === JSON.stringify(m['@reference.name']?.range), + })); + expect(sites.map((s) => s.site).sort()).toEqual([ + '@reference.read Page$1 . it', + '@reference.read Page.sortBoth$1 . lessThan', + '@reference.read Page.sortBoth$2 . lessThan', + '@reference.value-ref Page.sortBoth$1 . lessThan', + '@reference.value-ref Page.sortBoth$2 . lessThan', + ]); + expect(sites.every((s) => s.atMember)).toBe(true); + }); + it('a `@This()` alias inside a local container rewrites to the BINDING name (`R`), which is what the scope binds', () => { const localAliasSrc = ` pub fn string() void { diff --git a/gitnexus/test/unit/zig-import-resolver.test.ts b/gitnexus/test/unit/zig-import-resolver.test.ts index 932012d187..1078a2a330 100644 --- a/gitnexus/test/unit/zig-import-resolver.test.ts +++ b/gitnexus/test/unit/zig-import-resolver.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect } from 'vitest'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { resolveZigImportInternal } from '../../src/core/ingestion/import-resolvers/zig.js'; +import { resolveZigImportInternal } from '../../src/core/ingestion/languages/zig/import-helpers.js'; import { loadZigBuildConfig, loadZigWorkspaceIndex,