diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f9ceca96f1..5404274b35 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -541,20 +541,29 @@ jobs: fi fi - # 4. Counter: 1 + max existing N for `${BASE}-rc.*`, else 1. + # 4. Counter: reserve versions present in either npm or Git. + # npm can accept a publish while its metadata still omits that + # version ("Your package is being processed"). Checkout fetched + # all tags, including detached release commits, so those tags + # keep the next run from allocating an already-used version. + GIT_RC_TAGS="$(git tag --list "v${BASE}-rc.*")" cat > /tmp/next_rc.mjs <<'NODESCRIPT' const base = process.env.BASE; const prefix = base + "-rc."; let v; try { v = JSON.parse(process.env.VERSIONS_JSON); } catch { v = []; } if (!Array.isArray(v)) v = [v]; - const ns = v + const tagged = process.env.GIT_RC_TAGS.split("\n") + .filter(Boolean).map(tag => tag.slice(1)); + const ns = [...v, ...tagged] .filter(s => typeof s === "string" && s.startsWith(prefix)) - .map(s => parseInt(s.slice(prefix.length), 10)) + .map(s => s.slice(prefix.length)) + .filter(s => /^\d+$/.test(s)) + .map(Number) .filter(n => Number.isInteger(n) && n >= 0); process.stdout.write(String(ns.length ? Math.max(...ns) + 1 : 1)); NODESCRIPT - NEXT_N="$(BASE="$BASE" VERSIONS_JSON="$VERSIONS_JSON" node /tmp/next_rc.mjs)" + NEXT_N="$(BASE="$BASE" VERSIONS_JSON="$VERSIONS_JSON" GIT_RC_TAGS="$GIT_RC_TAGS" node /tmp/next_rc.mjs)" RC_VERSION="${BASE}-rc.${NEXT_N}" echo "Computed rc: $RC_VERSION" diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index fba4aac8d9..3a6ec294e2 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -389,6 +389,7 @@ 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 | | `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 | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dc252e8d9f..b29d6073ea 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -272,7 +272,8 @@ routes between two modes based on the triggering event: from `latest`. Dispatching with `bump: patch|minor|major` **resets** the cycle from `latest`. - `N` is auto-incremented against existing `X.Y.Z-rc.*` entries on the - registry. First rc for a given base is `rc.1`. + registry and `vX.Y.Z-rc.*` Git tags, so delayed npm visibility cannot + reuse an allocated version. First rc for a given base is `rc.1`. - The RC is gated by CI, including the fixed-answer tool-accuracy check (`gitnexus/bench/tool-accuracy/`); its report is attached to every release. RCs do not wait for a paid agent evaluation. diff --git a/Dockerfile.cli b/Dockerfile.cli index 411905afed..e226b394fe 100644 --- a/Dockerfile.cli +++ b/Dockerfile.cli @@ -83,31 +83,18 @@ COPY --from=builder --chown=node:node /app/gitnexus/vendor ./gitnexus/vendor # unreachable from $PATH. RUN ln -s /app/gitnexus/dist/cli/index.js /usr/local/bin/gitnexus -# Bake the LadybugDB FTS extension into the image so BM25 keyword search works -# at runtime. The server runs the default `load-only` extension policy (the read -# pool pins `{ policy: 'load-only' }`), so a runtime `LOAD EXTENSION fts` never -# INSTALLs — the extension must already exist in the runtime user's HOME -# extension dir, or every keyword search silently degrades (no FTS indexes are -# written and ranking falls back to vector-only with only a `warning` field). -# Run the installer as the `node` user with the SAME HOME the server runs under, -# so `INSTALL fts` materializes the extension under `$HOME/.lbdb/extension` where -# the runtime `LOAD` resolves it offline. `ENV HOME` is pinned because Docker -# does not derive HOME from `USER`, so without it build-install and runtime-load -# would resolve different paths. Requires network egress for the one-time -# INSTALL; the build fails loudly if it cannot fetch the extension. The DB-size -# default comes from GITNEXUS_LBUG_MAX_DB_SIZE (single source of truth, matches -# the runtime) — it only sizes the throwaway scratch DB used to run INSTALL. -# The second `--verify-only` step re-LOADs the extension in a FRESH process -# under the same HOME, so a HOME/extension-dir mismatch fails the build here -# rather than silently degrading keyword search to vector-only at runtime. +# Verify the packaged FTS binary under the runtime user. ExtensionManager loads +# this same vendored path before trying HOME, including under load-only policy. +# The CDN can replace a versioned artifact with an ABI-incompatible rebuild; +# downloading it here would bypass the binary pinned and tested in this tree. +# A missing or unloadable packaged extension must still fail the build. ENV HOME=/home/node \ GITNEXUS_LBUG_MAX_DB_SIZE=17179869184 -RUN su node -s /bin/sh -c "HOME=/home/node node /app/gitnexus/scripts/install-duckdb-extension.mjs fts" \ - && su node -s /bin/sh -c "HOME=/home/node node /app/gitnexus/scripts/install-duckdb-extension.mjs fts --verify-only" +RUN su node -s /bin/sh -c "HOME=/home/node node /app/gitnexus/scripts/install-duckdb-extension.mjs fts --verify-bundled" # Published runtime assets (in package.json `files`). Placed AFTER the DuckDB -# FTS-extension RUN above so editing hook/skill content does not invalidate that -# network-fetching cache layer; they have no input dependency on it. +# FTS verification above so editing hook/skill content does not invalidate that +# cache layer; they have no input dependency on it. # `hooks/`: dist/cli/resolve-invocation.js does # `require('../../hooks/claude/resolve-analyze-cmd.cjs')` at module load — the # single source of truth for the npm-11 npx-crash invocation decision (#1939). diff --git a/gitnexus/bench/import-target/measure.mjs b/gitnexus/bench/import-target/measure.mjs index 40aff289d1..5a1773c10d 100644 --- a/gitnexus/bench/import-target/measure.mjs +++ b/gitnexus/bench/import-target/measure.mjs @@ -693,7 +693,17 @@ function mix(n) { return (x ^ (x >>> 16)) >>> 0; } -const GO_MODULE = { modulePath: 'example.com/mod' }; +/** + * The prefix the go arm's import paths share. Deliberately NOT a go.mod: the arm + * hands the resolver no module config, so every import takes the GOPATH suffix + * match. Under a go.mod a module-relative import names ONE directory below the + * module root, an exact map read; the suffix match is the leg that walks + * `PackageDirIndex` buckets once per path segment and merges same-tail + * directories — the costs and the #2881 nested-repeat rule the layouts below + * are built to reach. The answers are the ones the module leg gave while it + * still matched by suffix, so the fingerprints did not move with it. + */ +const GO_IMPORT_PREFIX = 'example.com/mod'; /** * The `csharp_csproj` arm's project configs — the whole reason that arm exists. * @@ -1350,7 +1360,7 @@ function buildParsedFiles(lang, files) { function uniqueTarget(lang, { local, r, d, j, dirs }) { if (lang === 'go') { return local - ? `${GO_MODULE.modulePath}/src/pkg${d}` + ? `${GO_IMPORT_PREFIX}/src/pkg${d}` : (r >>> 3) % 2 === 0 ? ['fmt', 'os', 'net/http', 'encoding/json'][(r >>> 4) % 4] : `github.com/org/repo${(r >>> 4) % 97}/pkg/util`; @@ -1589,10 +1599,10 @@ function collideTarget(lang, { local, r, d, j, dirs }) { if (lang === 'go') { return local ? // The replicated package is addressed by the path it shares, so the - // module leg matches every service at once (`dirCount > 1`). + // suffix match takes every service at once (`dirCount > 1`). d % 5 === 1 && d % 7 !== 0 - ? `${GO_MODULE.modulePath}/internal/shared` - : `${GO_MODULE.modulePath}/svc${d}/internal` + ? `${GO_IMPORT_PREFIX}/internal/shared` + : `${GO_IMPORT_PREFIX}/svc${d}/internal` : (r >>> 3) % 2 === 0 ? ['fmt', 'os', 'net/http', 'encoding/json'][(r >>> 4) % 4] : // Ends in the shared segment, so the GOPATH fallback walks the whole @@ -1981,7 +1991,7 @@ function resolveAll(lang, files, imports, pad = 0) { function resolveOne(lang, from, target, pass) { const allFilePaths = pass.allFilePaths; - if (lang === 'go') return resolveGoImportTarget(target, from, allFilePaths, GO_MODULE); + if (lang === 'go') return resolveGoImportTarget(target, from, allFilePaths); if (lang === 'dart') return resolveDartImportTarget(target, from, allFilePaths, pass.config); if (lang === 'ruby') return resolveRubyImportTarget(target, from, allFilePaths); if (lang === 'kotlin') { @@ -2379,7 +2389,7 @@ const HEAP_PROBE_TARGET = { // budgeted ones above, except `dart`: a spelling `uniqueTarget` already mints, and // one that MISSES, so the reading is the index and the cascade runs to the // end. Chosen from the miss family that reaches furthest into each cascade: - // - `go` names a missing package inside GO_MODULE, which reaches the + // - `go` names a missing package under GO_IMPORT_PREFIX, which reaches the // package-directory lookup and forces `PackageDirIndex`; // - `dart` is a relative miss (`./src/thing.dart`), not a `uniqueTarget` // spelling. No timing arm exercises the relative suffix fallback; this diff --git a/gitnexus/bench/python-scope/baseline-fingerprint.txt b/gitnexus/bench/python-scope/baseline-fingerprint.txt index ea4d5c6d0e..3118af7b76 100644 --- a/gitnexus/bench/python-scope/baseline-fingerprint.txt +++ b/gitnexus/bench/python-scope/baseline-fingerprint.txt @@ -1 +1 @@ -87a2b61f39203b4736e9aae28519f95db4926836d186e37e22572c214c85be0b +283fafc9b2c8ba02f45ee25bf79d1619f9951db765c99474bad24f401c6f7882 diff --git a/gitnexus/bench/receiver-resolution/BASELINE.md b/gitnexus/bench/receiver-resolution/BASELINE.md index 29348da839..09bd31166b 100644 --- a/gitnexus/bench/receiver-resolution/BASELINE.md +++ b/gitnexus/bench/receiver-resolution/BASELINE.md @@ -1,5 +1,117 @@ # Receiver-resolution baseline +## Go module visibility and qualified receiver refusal + +Local imports now select the importer's own module or a module selected by its +nearest `go.work`. An independent sibling's matching module path is insufficient. +Qualified receiver types also stop when their import cannot resolve, instead of +borrowing a same-named type from another package. Local `replace` directives +remain unmodelled. + +Compared with `85329b4de` on the same corpus, exactly two `CALLS` edges disappear: +`SpinGadget` and `Workshop.SpinGadgetField` in +`go-qualified-declared-types/services/foreign.go` no longer bind the unrelated +`gadgets.Gizmo.Spin`. No other `CALLS` or `ACCESSES` edge changes. + +The two invalid calls now report drops. `ArchiveForeign`, which already had no +edge, also reports its refused qualified lookup; the simple calls additionally +report their read sites. Call drops move from 135 to 138, all-kind drops from +195 to 200, and `.go` call drops from 1 to 4. Every shape-arm state is unchanged. + +## Go modules across several go.mod files + +The Go resolver read only the repository-root `go.mod` and matched every other +import by directory suffix. In this combined corpus several fixtures declare +packages under the same import path (`internal/repository`, +`example.com/chaincall/models`), so their imports answered from the wrong +fixture or from none, and the receivers typed through them dropped. Each +import now belongs to the module whose path is its longest prefix, and names +the exact directory under that module's root. + +Thirteen Go call drops clear, all `chain-field`/`chain-call` receivers in +`go-chain-call`, `go-grouped-type-decl`, `go-interface-field-dispatch` and +`go-pointer-receiver-field-chain`. Call drops move from 148 to 135, all-kind +drops from 208 to 195, `.go` call drops from 14 to 1, `chain-field` from 70 to +58, `chain-call` from 32 to 31, and `in-program` from 72 to 59. No drop was +added, and every shape-arm state is unchanged. Against main (`ab0b03846`) on +the same corpus, no `CALLS` or `ACCESSES` edge disappears or changes target, +and 70 are added outside the two new fixtures. + +## Go package-qualified declared types + +Go capture strips the package qualifier from field, parameter and local types, +so `*models.User` is stored as `User`. The receiver lookup then saw only the bare +name, and it resolves a bare name only while that name is unique in the +workspace. In this combined corpus, `User` is declared in 29 Go files and +`UserService` in 2. So every Go receiver chain rooted at a qualified parameter +(`models.User`, `*models.User`, `*models.UserService`) dropped, even though each +fixture resolves on its own and its standalone test passes. Receiver typing now +tries the qualified spelling first, grounded on the qualifier's import. If that +misses, it falls back to the bare name as before. A chain step keeps the +binding's own written spelling, and the qualified spelling must name `rawName` +itself, so a binding whose type a chain step replaced never borrows another +binding's package. + +Thirteen Go drops clear: 5 calls and 8 reads in `go-deep-field-chain`, +`go-field-types` and `go-mixed-chain`. Call drops move from 153 to 148, +all-kind drops from 221 to 208, and reads from 48 to 40. `.go` call drops fall +from 19 to 14, `chain-field` from 73 to 70, `chain-mixed` from 2 to 0, and +`in-program` from 77 to 72. No drop was added, and every shape-arm state is +unchanged. The remaining Go chain-field drops come from packages that several +fixtures declare under the same import path, which nested `go.mod` resolution +addresses separately. + +The new `go-qualified-declared-types` fixture records no drops. Compared with +main (`278863068`) on the same corpus, no `CALLS` or `ACCESSES` edge disappears +or changes target, with one exception inside the new fixture: main binds its +`Forward` to `api.User.Archive`, which is that row's bug. Outside the new +fixture, 19 edges are added. Thirteen belong to the chains cleared above. The +other six come from receivers that never recorded a drop: + +- five simple `user.Save()` and `repo.Save()` receivers built as `models.X{}` + or declared `var x models.X`, in `go-constructor-type-inference`, + `go-member-calls` and `go-receiver-resolution`; +- the field chain `s.cartRepo.Get()` in `go-interface-field-dispatch`. + +## Namespace factory results and shared-position drops (#3498) + +Two changes move this baseline; neither moves an edge outside the new +fixtures. A same-corpus A/B against `origin/main` (`7090ac80f`, 2,838 `CALLS` +and `ACCESSES` edges) emits the identical edges on both sides; the full +corpus with this PR's fixtures is 2,871. + +- **Namespace factory results.** `x = ns.make()` and inline `ns.make().m()` + now take `make`'s return annotation, as a named import of `make` already + did. The annotation must belong to the module's own `make` function (a + method of the same name never qualifies), the namespace must bind that + module (`import pkg.sub` binds `pkg`, not `pkg/sub.py`), and a dotted + annotation (`-> models.Order`) is not followed further; each of those + fails closed. A receiver bound to a namespace function with no usable + return type (`x = ns.untyped()`) is recorded as dropped rather than read + as an exact miss. The new `python-module-factory-return` fixture adds four + call drops: `x = rp.untyped()`, inline `rp.untyped().m()`, `x = untyped()`, + and `rp.make()` on a local `rp = Other()` that shadows the module alias. + The Zig `bridge.prototypeChain()` and `bridge.accessor("value")` namespace + calls in `zig-filestruct` are recorded as both a call and a read: +2 + calls, +2 reads. Dart (`final x = rp.make()`) binds the dotted callee so + the same lookup applies; its fixture's untyped and awaited (`Future`, + not unwrapped yet) factories add two call drops. Zig resolves the inline + form only: a file that imports a module cannot tell a namespace from a + file-struct, so `const x = rp.make()` keeps main's binding. +- **Shared start positions.** Sites are keyed by `file:line:col`, and an outer + call starts where its inner receiver does (`s.orderRepo.DeleteItem(id)` + starts at `s.orderRepo`). A resolved inner site used to hide the outer + site's drop. Now only a duplicate capture of the same site (same receiver + and member, which also covers a call's own callee read) hides one. This + adds 18 call drops (Go 14, TypeScript 1, Rust 1, JavaScript 1) and 2 + TypeScript reads. Each was checked against the corpus graph: none has a + `CALLS` edge to that member from its enclosing function. The Go sites + resolve when their fixture is analyzed alone, and are unresolved only in + the combined corpus, where several fixtures declare the same packages. The + same fix turns ten shape-arm cells from `INVISIBLE-GAP` to `VISIBLE-GAP`. + +Totals: call drops 128 -> 153, reads 44 -> 48, all kinds 192 -> 221. + ## Express inline-handler fixture (#3488) The new `express-inline-handlers` fixture reads `req.query.path` inside an diff --git a/gitnexus/bench/receiver-resolution/baseline.json b/gitnexus/bench/receiver-resolution/baseline.json index f320debea3..9deb7c6c94 100644 --- a/gitnexus/bench/receiver-resolution/baseline.json +++ b/gitnexus/bench/receiver-resolution/baseline.json @@ -38,11 +38,11 @@ "decoratedFieldType": "RESOLVES" }, "php": { - "arrowCallChain": "INVISIBLE-GAP", + "arrowCallChain": "VISIBLE-GAP", "arrowPropertyPath": "RESOLVES", "plainChain": "RESOLVES", - "plainDeepChain": "INVISIBLE-GAP", - "optionalChain": "INVISIBLE-GAP", + "plainDeepChain": "VISIBLE-GAP", + "optionalChain": "VISIBLE-GAP", "nonNullAssert": "N/A", "awaitParen": "N/A", "explicitTypeArgs": "N/A", @@ -116,7 +116,7 @@ "csharp": { "plainChain": "RESOLVES", "plainDeepChain": "RESOLVES", - "optionalChain": "INVISIBLE-GAP", + "optionalChain": "VISIBLE-GAP", "nonNullAssert": "VISIBLE-GAP", "awaitParen": "RESOLVES", "explicitTypeArgs": "VISIBLE-GAP", @@ -143,11 +143,11 @@ "optionalChain": "N/A", "nonNullAssert": "N/A", "awaitParen": "N/A", - "explicitTypeArgs": "INVISIBLE-GAP", + "explicitTypeArgs": "VISIBLE-GAP", "indexElement": "RESOLVES", "fieldReceiverCall": "RESOLVES", "decoratedReceiverBase": "RESOLVES", - "decoratedFieldType": "INVISIBLE-GAP" + "decoratedFieldType": "VISIBLE-GAP" }, "c": { "plainChain": "N/A", @@ -174,10 +174,10 @@ "decoratedFieldType": "RESOLVES" }, "swift": { - "plainChain": "INVISIBLE-GAP", - "plainDeepChain": "INVISIBLE-GAP", - "optionalChain": "INVISIBLE-GAP", - "nonNullAssert": "INVISIBLE-GAP", + "plainChain": "VISIBLE-GAP", + "plainDeepChain": "VISIBLE-GAP", + "optionalChain": "VISIBLE-GAP", + "nonNullAssert": "VISIBLE-GAP", "awaitParen": "VISIBLE-GAP", "explicitTypeArgs": "N/A", "indexElement": "INVISIBLE-GAP", @@ -199,39 +199,40 @@ } }, "countArm": { - "callDrops": 128, - "totalDropsAllKinds": 192, + "callDrops": 138, + "totalDropsAllKinds": 200, "bySiteKind": { - "call": 128, - "read": 44, + "call": 138, + "read": 42, "write": 20 }, "callDropsByExtension": { ".java": 49, - ".py": 20, - ".ts": 16, - ".zig": 11, + ".py": 24, + ".ts": 17, + ".zig": 13, ".cs": 8, ".tsx": 6, - ".go": 5, + ".go": 4, ".php": 4, + ".rs": 4, ".kt": 4, - ".rs": 3, - ".js": 1, + ".js": 2, + ".dart": 2, ".swift": 1 }, "callDropsByShape": { - "chain-field": 57, - "chain-call": 30, - "no-chain": 27, - "<>": 11, - "chain-mixed": 2, + "chain-field": 59, + "no-chain": 34, + "chain-call": 31, + "<>": 13, "chain-unwrap": 1 }, "callDropsByOrigin": { - "in-program": 55, + "in-program": 60, "external": 44, - "unknown": 29 + "unknown": 32, + "<>": 2 } } } diff --git a/gitnexus/bench/scope-capture/baselines.json b/gitnexus/bench/scope-capture/baselines.json index b05df10d2d..8d3ab71990 100644 --- a/gitnexus/bench/scope-capture/baselines.json +++ b/gitnexus/bench/scope-capture/baselines.json @@ -1,7 +1,9 @@ { "_comment": "Per-language baselines for bench/scope-capture/measure.mjs --check. fingerprint = order-independent sha256 over the lang-resolution/-* fixture corpus + a 20-entity synthetic source (correctness gate; re-baseline intentionally on a legitimate capture change). scaling_budget = max allowed (t800/t250)/(800/250); ~1.0 is linear, ~3.2 is quadratic. The synthetic source is now HERITAGE-BEARING for every language (each Entity extends/implements/embeds/uses-trait/conforms-to a shared base) so the #1951 @reference.inherits synth is gated at scale, not just the base capture loop. All languages thread the tree-sitter captured node instead of re-deriving it with findNodeAtRange(tree.rootNode,...) per match, so all are linear (go #1915, python #1918, ruby/php/rust/csharp #1951, java #1956).", "go": { - "fingerprint": "2cbf91984a03666ca5966fbdf0bd681f91dcda6e4c7bd9fa21e9f2daf524f9dc", + "fingerprint": "b1dfa8e1a8d92fd9d5779a02bc4bd99f54ec87adae4a326be08b74cb48fd5ef3", + "_rebaselined_go_nested_modules": "Go nested modules (root cause B of the #3498 corpus triage): new go-multi-module-workspace (7 Go files: two modules whose directories differ from their paths, both with internal/repository, plus a /v2 module in an unrelated directory) and go-root-with-nested-module (5 Go files: a root module with a nested module) fixtures for import resolution across several go.mod files. No Go emitter change; the fixtures are the only input that moved: parking both directories restores acee4449f691d9138e68e7b2b19da863fc2c89b0e9846acdf10e93d76b2eec78 byte-for-byte. The capture golden gains exactly 12 entries and no existing entry changes. Rebased onto #3651: fixture_count 134 -> 146, capture_groups_fp 2847 -> 2983; synthetic counts 5508/17608 unchanged; scaling 0.994 < the unchanged 1.5 budget. Prior acee4449f691d9138e68e7b2b19da863fc2c89b0e9846acdf10e93d76b2eec78 -> 3ba3b6e1551311ddb0e9330c939ac995856b487303b6f64bc89da3689a6d9d2c. Review follow-up: the orders-service ledger.go fixture comment was reworded (same two lines, comment text is captured) -> b1dfa8e1a8d92fd9d5779a02bc4bd99f54ec87adae4a326be08b74cb48fd5ef3; fixture_count and capture_groups_fp unchanged at 146 / 2983, scaling 1.044.", + "_rebaselined_go_qualified_declared_types": "Go qualified declared types (root cause A of the #3498 corpus triage): new go-qualified-declared-types fixture (12 files, models.User beside api.User and vault.Vault beside api.Vault) for the qualified declared-type lookup. No Go emitter change; the fixture is the only input that moved. The capture golden gains exactly 12 entries (268 groups) and no existing entry changes. fixture_count 122 -> 134, capture_groups_fp 2579 -> 2847; synthetic counts 5508/17608 unchanged; scaling 1.038 < the unchanged 1.5 budget. Prior 2cbf91984a03666ca5966fbdf0bd681f91dcda6e4c7bd9fa21e9f2daf524f9dc -> c4b286407b7171034116a8aabdc658c20d695f3df5152b0afb8db2ce134a1a92 (first 9 files) -> acee4449f691d9138e68e7b2b19da863fc2c89b0e9846acdf10e93d76b2eec78 (vault rows: a field, parameter and local named like their package).", "_rebaselined_3417_versioned_import_name": "#3417: splitGoImportStatement now uses the conventional package qualifier before a /vN module suffix. Compared the pre-fix 2539b08 and HEAD emitters over the SAME HEAD corpus: exactly two @import.name texts changed from v2 to bar for github.com/foo/bar/v2, in go-extern-qualified-signatures/memory/memory.go and store/store.go; every other capture tag, text, range and match order is unchanged. The capture golden already records both changes. fixture_count 122 and capture_groups_fp 2579 are unchanged, as are synthetic counts 5508/17608; scaling 0.977 < the unchanged 1.5 budget. Prior 2e3099db962f82f9d8641707a8b2bcf6875dafec1f54904f2dec7ac65ba22e9f -> fdc3a691e2ebbc5b0d6fe1da328864293587a75e296e106c705c7e31ee622a5b.", "_rebaselined_3190_ctor_qualified_name": "#3190: generic composite-literal constructors now carry @reference.qualified-name with the written pkg.Box[T] spelling so constructor fallback can tell a qualifier from a bare unique-name guess. DIGEST DRIFT ONLY: the tag is added to existing constructor matches (captureGroups unchanged on go-constructor-type-inference/cmd/main.go). Prior 990e4921a7ef0e6aa4d7da92b671de91fa2621cb27918adb27742740dc6ad902 -> 2e3099db962f82f9d8641707a8b2bcf6875dafec1f54904f2dec7ac65ba22e9f; capture_groups_fp 2579, fixture_count 122.", "_rebaselined_3190": "Corrected go-method-enrichment/app.go to share package animal with its declarations; its capture count is now 16 rather than 15. No Go emitter change. Scaling budget unchanged.", @@ -161,7 +163,7 @@ "_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: swift-callable-alternatives/App.swift (+1 file, +36 groups). Emitter delta: +6 / -3: `??` and ternary seeds and copies now name each operand; the 3 removed matches are the whole-expression seeds and copy that carried a `target-qualified-name` / `source-qualified-name` of the compound source. capture_groups_fp 1297 -> 1333, fixture_count 67 -> 68; synthetic counts unchanged; scaling 1.057 < 1.5. Prior decf74c01af0c7f403e203b19c2bd92dbf95b4562f6da2b0ac5117ef872204da -> c9fc553662f0db18027fba882e3ff730744f6153cc46eca7b00667fabd6a0df8." }, "dart": { - "fingerprint": "4690403d2be0d270e28a55791df82eaa627d26d28c52d81bfafa59761badcaf3", + "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.", @@ -173,7 +175,8 @@ "_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_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: dart-callable-alternatives/app.dart (+1 file, +33 groups). Emitter delta: +6 / -3: `??` and `?:` seeds and copies now name each operand; the 3 removed matches are the whole-expression seeds and copy that carried a qualified name of the compound source. capture_groups_fp 829 -> 862, fixture_count 36 -> 37; synthetic counts unchanged; scaling 1.033 < 1.5. Prior 3a8ddabbeb1cba47a4757451d4f79d726ca230fd15e860772b11526fbb1c6687 -> 795290a9524ee0dc38af635536e9744c401ec13828ec77822d39e59e1cd6e649.", "_rebaselined_3486_semantic_rename": "#3486: Compared actual origin/main (191a954b), committed dd3bf and frozen provider source over the same unchanged corpus. 2 existing prefixed package imports retain their explicit aliases (http/tool). Import sources, statement spans and all other matches are unchanged. Fixture entries 43; changed entries 1; capture groups 895 -> 895. Fingerprint regenerated from the runner's canonicalized capture records. Scaling budgets unchanged.", - "_rebaselined_3633_native_extension_types": "#3633: Compared the prior grammar and emitter at 89602560d with native extension-type capture over the same 42 Dart fixture files. Only dart-extension-types/models.dart changes: 11 module/type scope and declaration matches retain the original header text, and Box's declaration gains type-parameter metadata. All method, receiver and heritage captures are unchanged. Total capture groups remain 895 across 43 fixture/synthetic entries; synthetic scale counts stay 5011/16011. Measured scaling 1.127 < 1.5; budget unchanged. Prior 557bdc505af40590b21e53298584f14227b7d79220806425f8e7da25d78f9712 -> 4690403d2be0d270e28a55791df82eaa627d26d28c52d81bfafa59761badcaf3." + "_rebaselined_3633_native_extension_types": "#3633: Compared the prior grammar and emitter at 89602560d with native extension-type capture over the same 42 Dart fixture files. Only dart-extension-types/models.dart changes: 11 module/type scope and declaration matches retain the original header text, and Box's declaration gains type-parameter metadata. All method, receiver and heritage captures are unchanged. Total capture groups remain 895 across 43 fixture/synthetic entries; synthetic scale counts stay 5011/16011. Measured scaling 1.127 < 1.5; budget unchanged. Prior 557bdc505af40590b21e53298584f14227b7d79220806425f8e7da25d78f9712 -> 4690403d2be0d270e28a55791df82eaa627d26d28c52d81bfafa59761badcaf3.", + "_rebaselined_3498_prefixed_call_bindings": "#3498: a local initialized by exactly `prefix.member(...)` now gets a call-derived @type-binding.constructor whose type keeps the dotted callee, so the shared chain follow can type namespace factories (`final x = rp.make()`). Two existing fixture sites gain a binding, both in dart-method-enrichment/app.dart: `var sound = dog.speak()` and `var category = Animal.classify(\"dog\")`; neither variable is used as a receiver, and a full lang-resolution A/B against origin/main emits the identical CALLS/ACCESSES edges outside the new fixture. The new dart-prefixed-factory-return fixture adds its own captures. Prior 4690403d2be0d270e28a55791df82eaa627d26d28c52d81bfafa59761badcaf3 (897dfc745d4ba0dfe0ae5fcfffcd983563ddab6d0a870fc8ee0de1d8df2c7c87 with the existing fixtures alone) -> a8b2e674a7f695caba32b5a0912686119944e8e4874a6ceeb65b3b5ac420bebb. scaling_ratio 1.173 against the 1.5 budget. Review follow-up: the fixture gains an awaited `rp.makeAsync()` row (corpus growth only; the Dart emitter change in that commit is a docstring) -> 1c5b892a136318eddee3435225284896c2effb52dd51ca5717c92887ae4a39a3." }, "java": { "fingerprint": "41c4338f5813a73199dd5c2609313c11076812df21fd9c429039a833325870e0", diff --git a/gitnexus/bench/tool-accuracy/known-gaps.json b/gitnexus/bench/tool-accuracy/known-gaps.json index ec34aff9a0..5e9b867b7f 100644 --- a/gitnexus/bench/tool-accuracy/known-gaps.json +++ b/gitnexus/bench/tool-accuracy/known-gaps.json @@ -7,12 +7,6 @@ "issue": 3490, "reason": "Guard-style sanitizers are a documented taint limitation (#3490).", "baselineActual": ["handleGuarded -> runGit command-injection"] - }, - { - "id": "python.factory-qualified", - "issue": 3498, - "reason": "Module-qualified factory return type is not followed (#3498).", - "baselineActual": [] } ] } diff --git a/gitnexus/scripts/install-duckdb-extension.mjs b/gitnexus/scripts/install-duckdb-extension.mjs index 5acfb15831..b6a560939e 100644 --- a/gitnexus/scripts/install-duckdb-extension.mjs +++ b/gitnexus/scripts/install-duckdb-extension.mjs @@ -80,26 +80,35 @@ async function defaultConnect(lbugMaxDbSize) { * @param {string} extensionName * @param {object} [options] * @param {boolean} [options.verifyOnly] LOAD-only Docker build gate — no install. + * @param {boolean} [options.verifyBundled] LOAD the packaged FTS artifact without a download. * @param {string} [options.loadError] The parent's LOAD failure; selects the verb. * @param {(size: number) => Promise<{conn: {query: (sql: string) => Promise}, dispose: () => Promise}>} [options.connect] * Connection factory; injectable for offline unit tests. */ export async function installDuckDbExtension(extensionName, options = {}) { - const { verifyOnly = false, loadError, connect } = options; + const { verifyOnly = false, verifyBundled = false, loadError, connect } = options; if (!extensionName || !EXTENSION_NAME_PATTERN.test(extensionName)) { throw new Error(`Invalid DuckDB extension name: ${extensionName ?? ''}`); } + let loadTarget = extensionName; + if (verifyBundled) { + if (extensionName !== 'fts') throw new Error('Bundled verification only supports fts'); + const { resolveVendoredFtsPath } = await import('../dist/core/lbug/vendored-extension-path.js'); + const bundled = resolveVendoredFtsPath(); + if (!bundled) + throw new Error(`No packaged FTS artifact for ${process.platform}-${process.arch}`); + loadTarget = `'${bundled.replace(/\\/g, '/').replace(/'/g, "''")}'`; + } + const makeConnection = connect ?? (() => defaultConnect(resolveMaxDbSize())); const { conn, dispose } = await makeConnection(); try { - if (verifyOnly) { - // Prove a previously-baked extension is resolvable by a FRESH process - // under the current HOME (the runtime `LOAD EXTENSION` path) — no INSTALL, - // no network. Used as a Docker build-time gate so a HOME/extension-dir - // mismatch fails the build instead of silently degrading search at runtime. - await conn.query(`LOAD EXTENSION ${extensionName}`); + if (verifyOnly || verifyBundled) { + // LOAD must succeed without INSTALL or a network fallback, whether the + // caller verifies the packaged path or a named extension under HOME. + await conn.query(`LOAD EXTENSION ${loadTarget}`); console.log( `[install-ext] LOAD-only verify OK for '${extensionName}' (HOME=${process.env.HOME})`, ); @@ -117,6 +126,7 @@ export async function installDuckDbExtension(extensionName, options = {}) { if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { installDuckDbExtension(process.argv[2] ?? process.env.GITNEXUS_LBUG_EXTENSION_NAME, { verifyOnly: process.argv.includes('--verify-only'), + verifyBundled: process.argv.includes('--verify-bundled'), loadError: process.env.GITNEXUS_LBUG_EXTENSION_LOAD_ERROR, }).catch((err) => { console.error(err instanceof Error ? (err.stack ?? err.message) : String(err)); diff --git a/gitnexus/src/core/git-staleness.ts b/gitnexus/src/core/git-staleness.ts index e224b23192..9e3859926d 100644 --- a/gitnexus/src/core/git-staleness.ts +++ b/gitnexus/src/core/git-staleness.ts @@ -24,14 +24,14 @@ const execFileAsync = promisify(execFile); const STALENESS_TIMEOUT_MS = 5_000; const behindHint = (n: number): string => - `⚠️ Index is ${n} commit${n > 1 ? 's' : ''} behind HEAD. Run analyze tool to update.`; + `⚠️ Index is ${n} commit${n > 1 ? 's' : ''} behind HEAD. Run the CLI command \`npx gitnexus analyze\` from the repository directory to update.`; // Says only what a failed count plus a resolved HEAD establish: the index is not // at HEAD and the gap is uncountable. Reaching here does NOT prove the indexed // commit left history — that is the usual cause (a pruned `fetch --depth 1`), // but any other `rev-list` failure lands here too, so the cause is hedged. const DIVERGED_HINT = - "⚠️ Index is not at HEAD and the commit gap could not be counted — the recorded commit may no longer be in this clone's history. Run analyze tool to update."; + "⚠️ Index is not at HEAD and the commit gap could not be counted — the recorded commit may no longer be in this clone's history. Run the CLI command `npx gitnexus analyze` from the repository directory to update."; // `rev-list --count lastCommit..HEAD` answering 0 does NOT mean "HEAD is the // indexed commit" — it means "HEAD has no commits lastCommit lacks", which is @@ -39,7 +39,7 @@ const DIVERGED_HINT = // out an older commit than the one indexed, or switched to a line of history // behind it). That read a rollback as `current` until this hint existed. const REGRESSED_HINT = - '⚠️ Index is not at HEAD — the indexed commit is not reachable from the checked-out commit (the working tree may have checked out an older commit, or a different line of history). Run analyze tool to update.'; + '⚠️ Index is not at HEAD — the indexed commit is not reachable from the checked-out commit (the working tree may have checked out an older commit, or a different line of history). Run the CLI command `npx gitnexus analyze` from the repository directory to update.'; const unknown = (): StalenessInfo => ({ isStale: false, commitsBehind: 0, status: 'unknown' }); diff --git a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts b/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts index cb7e77ed0b..30c4c2d96a 100644 --- a/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts +++ b/gitnexus/src/core/ingestion/import-resolvers/package-dir-index.ts @@ -234,6 +234,20 @@ export function sortedRootFiles(index: PackageDirIndex): string[] { return [...index.rootFiles].sort(); } +/** + * Every accepted file directly inside exactly `dir` — a normalized directory + * with no leading or trailing slash — in `allFilePaths` iteration order. + * + * The anchored counterpart of {@link filesDirectlyInPkgDir}, for a caller that + * already knows where the package lives and must not also match every other + * directory ending in the same path. `''` answers nothing: root files have no + * directory, see {@link sortedRootFiles}. + */ +export function filesInDir(index: PackageDirIndex, dir: string): string[] { + const files = index.filesByDir.get(dir); + return files === undefined ? [] : files.map((f) => f.raw); +} + /** * The FIRST accepted file (in `allFilePaths` iteration order) directly inside a * directory ending with `pkgPath`, or `null`. diff --git a/gitnexus/src/core/ingestion/languages/dart/captures.ts b/gitnexus/src/core/ingestion/languages/dart/captures.ts index a671d1e227..802f5c6d72 100644 --- a/gitnexus/src/core/ingestion/languages/dart/captures.ts +++ b/gitnexus/src/core/ingestion/languages/dart/captures.ts @@ -619,6 +619,33 @@ function findDirectCallValue(initVarDef: SyntaxNode): SyntaxNode | null { return null; } +/** + * `prefix.member(…)` as the whole initializer, written directly or awaited: the + * dotted callee. The shared chain follow types a namespace function from its + * return annotation, and a member call through the receiver's class (#3498). + * An awaited `Future` is not unwrapped yet, so that receiver records a drop. + * Longer chains (`rp.make().other`) are left alone. + */ +function qualifiedCallValue(initVarDef: SyntaxNode): string | null { + let head = initVarDef.childForFieldName('value'); + if (head?.type === 'unary_expression') head = head.namedChild(0); + if (head?.type === 'await_expression') head = head.namedChild(0); + if (head?.type !== 'identifier') return null; + const member = head.nextNamedSibling; + const call = member?.nextNamedSibling; + const inner = member?.type === 'selector' ? member.namedChild(0) : null; + const name = inner?.type === 'unconditional_assignable_selector' ? selectorName(inner) : null; + if ( + name === null || + call?.type !== 'selector' || + call.namedChild(0)?.type !== 'argument_part' || + call.nextNamedSibling !== null + ) { + return null; + } + return `${head.text}.${name.text}`; +} + /** * Callee identifier of a class field initialized by a direct constructor call — * `var b = Outer();` / `final b = Outer();` — or `null` for anything else. @@ -644,13 +671,13 @@ function dartFieldConstructorCallee(nameNode: SyntaxNode): SyntaxNode | null { function emitVarTypeBinding(initVarDef: SyntaxNode, out: CaptureMatch[]): void { const nameNode = initVarDef.childForFieldName('name'); if (nameNode === null) return; - const calleeId = findDirectCallValue(initVarDef); - if (calleeId === null) return; + const callee = findDirectCallValue(initVarDef)?.text ?? qualifiedCallValue(initVarDef); + if (callee === null) return; out.push({ '@type-binding.constructor': nodeToCapture('@type-binding.constructor', initVarDef), '@type-binding.name': syntheticCapture('@type-binding.name', initVarDef, nameNode.text), - '@type-binding.type': syntheticCapture('@type-binding.type', initVarDef, calleeId.text), + '@type-binding.type': syntheticCapture('@type-binding.type', initVarDef, callee), }); } diff --git a/gitnexus/src/core/ingestion/languages/dart/interpret.ts b/gitnexus/src/core/ingestion/languages/dart/interpret.ts index 6872bfc014..94ffe5ac76 100644 --- a/gitnexus/src/core/ingestion/languages/dart/interpret.ts +++ b/gitnexus/src/core/ingestion/languages/dart/interpret.ts @@ -90,7 +90,12 @@ export function interpretDartTypeBinding(captures: CaptureMatch): ParsedTypeBind const typeCap = captures['@type-binding.type']; if (nameCap === undefined || typeCap === undefined) return null; - const rawType = normalizeDartType(typeCap.text); + // A call-derived `prefix.member` names a namespace function or a member + // call, not a library-prefixed type, so it keeps its prefix (#3498). + const rawType = + captures['@type-binding.constructor'] !== undefined && typeCap.text.includes('.') + ? typeCap.text + : normalizeDartType(typeCap.text); if ( rawType === '' || rawType === 'void' || diff --git a/gitnexus/src/core/ingestion/languages/go/import-target.ts b/gitnexus/src/core/ingestion/languages/go/import-target.ts index 14d9e2d480..c41c7d18aa 100644 --- a/gitnexus/src/core/ingestion/languages/go/import-target.ts +++ b/gitnexus/src/core/ingestion/languages/go/import-target.ts @@ -1,11 +1,12 @@ -import type { GoModuleConfig } from '../../language-config.js'; import { buildPackageDirIndex, filesDirectlyInPkgDir, + filesInDir, sortedRootFiles, type PackageDirIndex, } from '../../import-resolvers/package-dir-index.js'; import { perFileSet } from '../../import-resolvers/per-file-set.js'; +import { isGoWorkspaceConfig, locateGoImport } from './workspace-config.js'; /** * Resolve a Go import path to ALL .go files in the matching package directory. @@ -16,39 +17,42 @@ import { perFileSet } from '../../import-resolvers/per-file-set.js'; * IMPORTS edge fanout AND binding materialization for every exported symbol in * the package. * - * Strategy: - * 1. With go.mod: resolve only imports owned by that module - * 2. Without go.mod / GOPATH: progressively shorter directory suffixes + * Strategy (`resolutionConfig` is every go.mod / go.work in the repo, see + * `workspace-config.ts`): + * 1. An in-repo module owns the path: exactly one selected module must + * contain the package in the directory under its root. Never a suffix + * match — `…/internal/repository` names one module's directory, not every + * directory ending in `internal/repository`. + * 2. The importer is inside a module and nothing owns the path (standard + * library, dependencies): unresolved. + * 3. The importer is outside every module: progressively shorter directory + * suffixes, GOPATH style. */ export function resolveGoImportTarget( targetRaw: string, - _fromFile: string, + fromFile: string, allFilePaths: ReadonlySet, resolutionConfig?: unknown, ): string | readonly string[] | null { if (!targetRaw) return null; - const goModule = resolutionConfig as GoModuleConfig | undefined; - - // 1) go.mod is authoritative: only this module's exact path or subpackages - // can name files in the workspace. Standard-library and third-party - // imports must not fall through to the suffix matcher below. - if (goModule != null) { - const ownedByModule = - targetRaw === goModule.modulePath || targetRaw.startsWith(`${goModule.modulePath}/`); - if (!ownedByModule) return null; - - const relativePkg = - targetRaw === goModule.modulePath ? '' : targetRaw.slice(goModule.modulePath.length + 1); // e.g. "internal/models" - const files = - relativePkg === '' - ? findRootPackageFiles(allFilePaths) - : findAllFilesInPkgDir(allFilePaths, relativePkg); - if (files.length > 0) return files; - return null; + if (isGoWorkspaceConfig(resolutionConfig)) { + const location = locateGoImport(resolutionConfig, targetRaw, fromFile); + if (location.kind === 'external') return null; + if (location.kind === 'module') { + const index = getGoPackageIndex(allFilePaths); + let result: readonly string[] | null = null; + for (const dir of location.dirs) { + const files = filesInPkgDir(index, dir); + if (files.length === 0) continue; + if (result !== null) return null; + result = files; + } + return result; + } } - // 2) Non-go.mod / GOPATH: progressively shorter directory suffixes. + // GOPATH: progressively shorter directory suffixes. // "github.com/xxx/yyy/pkg" → try "github.com/xxx/yyy/pkg/" → "xxx/yyy/pkg/" → "yyy/pkg/" // Stop at ≥2 segments to avoid matching a single-segment suffix (e.g. // "pkg", "util", "internal") to a local directory with the same name. @@ -83,8 +87,10 @@ const getGoPackageIndex = perFileSet( buildPackageDirIndex(allFilePaths, isGoPackageFile), ); -function findRootPackageFiles(allFilePaths: ReadonlySet): string[] { - return sortedRootFiles(getGoPackageIndex(allFilePaths)); +/** The package in exactly `dir`: root files sorted, any other directory in + * Set order. */ +function filesInPkgDir(index: PackageDirIndex, dir: string): string[] { + return dir === '' ? sortedRootFiles(index) : filesInDir(index, dir); } function findAllFilesInPkgDir(allFilePaths: ReadonlySet, pkgPath: string): string[] { diff --git a/gitnexus/src/core/ingestion/languages/go/interpret.ts b/gitnexus/src/core/ingestion/languages/go/interpret.ts index c652cf3031..d5cb6e06b9 100644 --- a/gitnexus/src/core/ingestion/languages/go/interpret.ts +++ b/gitnexus/src/core/ingestion/languages/go/interpret.ts @@ -146,6 +146,39 @@ export function normalizeGoReturnType(text: string): string { return t; } +/** `pkg.Type` and nothing else: one qualifier, both halves Go identifiers + * (letters per the spec, so Unicode, not just ASCII). */ +const GO_QUALIFIED_TYPE_NAME_RE = /^[\p{L}_][\p{L}\p{Nd}_]*\.[\p{L}_][\p{L}\p{Nd}_]*$/u; + +/** + * Go's `ScopeResolver.qualifiedTypeLookupSpelling`: the `pkg.Type` a binding's + * written type names, or `undefined` when it names no package. + * + * `normalizeGoTypeName` cuts the qualifier at capture (`*models.User` → + * `User`), so `rawName` cannot tell `models.User` from `api.User`. The written + * spelling (`TypeRef.declaredSpelling`) still has it, and `normalizeGoReturnType` + * — the reduction return types already get — strips the same pointer, slice, + * map, channel and func wrappers while keeping it. A `rawName` that is already + * qualified (a return type) needs nothing from here. + */ +export function goQualifiedTypeLookupSpelling(typeRef: TypeRef): string | undefined { + const written = typeRef.declaredSpelling; + // No `.` in the written type means no qualifier to recover; most bindings + // take this exit before any wrapper stripping. + if (written === undefined || !written.includes('.') || typeRef.rawName.includes('.')) { + return undefined; + } + // `func() *models.User` leaves `*models.User` after the return is unwrapped. + const qualified = stripGoOuterTypePrefixes(normalizeGoReturnType(written)); + // The spelling must name `rawName` itself, only qualified: that is the cut + // `normalizeGoTypeName` made. A binding whose type a chain step replaced + // (`u *models.User` landing on a package-level `User *auth.Principal`) keeps + // its own spelling but not its own `rawName`, and must not borrow either. + return GO_QUALIFIED_TYPE_NAME_RE.test(qualified) && qualified.endsWith(`.${typeRef.rawName}`) + ? qualified + : undefined; +} + function stripGoOuterTypePrefixes(text: string): string { let t = text.trim(); let previous: string; diff --git a/gitnexus/src/core/ingestion/languages/go/scope-resolver.ts b/gitnexus/src/core/ingestion/languages/go/scope-resolver.ts index 4fa6494d2b..6680f503a3 100644 --- a/gitnexus/src/core/ingestion/languages/go/scope-resolver.ts +++ b/gitnexus/src/core/ingestion/languages/go/scope-resolver.ts @@ -3,7 +3,6 @@ import { SupportedLanguages } from 'gitnexus-shared'; import { buildMro, defaultLinearize } from '../../scope-resolution/passes/mro.js'; import { populateGoOwners, populateGoWorkspaceOwners } from './method-owners.js'; import type { ScopeResolver } from '../../scope-resolution/contract/scope-resolver.js'; -import { loadGoModulePath } from '../../language-config.js'; import { goProvider } from '../go.js'; import { goArityCompatibility, @@ -15,10 +14,11 @@ import { import { detectGoInterfaceImplementations } from './interface-impls.js'; import { populateGoRangeBindings } from './range-binding.js'; import { expandGoWildcardNames } from './expand-wildcards.js'; -import { goMapValueType } from './interpret.js'; +import { goMapValueType, goQualifiedTypeLookupSpelling } from './interpret.js'; import { goIsGlobalNameFallbackPlausible } from './name-fallback-visibility.js'; import { goIsNamespaceMemberVisible } from './namespace-member-visibility.js'; import { resolveGoImportBinding } from './import-binding.js'; +import { captureGoWorkspaceConfig, loadGoWorkspaceConfig } from './workspace-config.js'; import { emitMethodOwnerEdges } from '../../scope-resolution/graph-bridge/ownership.js'; /** Slice `[]T` and array `[N]T` / `[...]T` → the element spelling. Hoisted — @@ -30,7 +30,13 @@ export const goScopeResolver: ScopeResolver = { languageProvider: goProvider, importEdgeReason: 'go-scope: import', - loadResolutionConfig: (repoPath: string) => loadGoModulePath(repoPath), + // Every go.mod / go.work, not only the root's: modules nest, sit in + // directories named unlike their paths, and a repo may have no root module. + // Captured from the scan's path list during analyze; a rename refresh is + // handed only source paths, so it rescans for the manifests instead. + loadResolutionConfig: loadGoWorkspaceConfig, + captureResolutionConfig: captureGoWorkspaceConfig, + refreshResolutionConfig: (repoPath: string) => loadGoWorkspaceConfig(repoPath), resolveImportTarget: (targetRaw, fromFile, allFilePaths, resolutionConfig) => resolveGoImportTarget(targetRaw, fromFile, allFilePaths, resolutionConfig), @@ -55,6 +61,11 @@ export const goScopeResolver: ScopeResolver = { stripTypePreservingDecoration: (typeName) => typeName.startsWith('*') ? typeName.slice(1).trim() : undefined, + // `normalizeGoTypeName` drops the package qualifier from every binding but a + // return type, so `models.User` and `api.User` both arrive as `User`. This + // recovers `models.User` from the written spelling for receiver typing. + qualifiedTypeLookupSpelling: goQualifiedTypeLookupSpelling, + // The subscript counterpart of the stripper above, and the reason the two are // separate hooks: `*` is safe to strip at any class lookup, `[]` / `map[K]` // only where the source actually indexed. Answers the `index` route only — diff --git a/gitnexus/src/core/ingestion/languages/go/workspace-config.ts b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts new file mode 100644 index 0000000000..9c3dfa6ecb --- /dev/null +++ b/gitnexus/src/core/ingestion/languages/go/workspace-config.ts @@ -0,0 +1,393 @@ +/** + * 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. + * + * Go itself resolves an import against modules, not directory names: + * + * - a `go.mod` makes its directory a module root, and removes that subtree + * from every enclosing module — with or without a `go.work`; + * - the module providing `p` is one whose path is `p` or a prefix of it at a + * `/` boundary, and the package is the directory `p` minus that path under + * the module root. Exactly one selected module must contain the package; + * matching multiple module path prefixes is ambiguous only when more than + * one of their package directories contains Go files; + * - a `go.work` names the workspace's main modules (`use`). It selects the + * sibling modules available to an importer; it changes no module boundary. + * + * The importer's own module and modules selected by its nearest `go.work` + * can provide local packages. An independent sibling remains unresolved even + * when its module path is unique. Local `replace` directives are not modelled. + * + * Discovery reads the scan's path list (`captureGoWorkspaceConfig`), like + * Dart's `pubspec.yaml` capture, so the modules are the ones the analyzed file + * set lives in and no second directory walk runs during analyze. + */ + +import fs, { constants, type FileHandle } from 'node:fs/promises'; +import path from 'node:path'; +import { walkRepositoryPaths } from '../../filesystem-walker.js'; +import { isAbsoluteZigDepPath, normalizeZigDepPath } from '../../language-config.js'; +import { getMaxFileSizeBytes } from '../../utils/max-file-size.js'; + +/** One `go.mod`: the module path it declares and its repo-relative directory. */ +export interface GoModule { + readonly modulePath: string; + /** Forward slashes, no trailing slash; `''` is the repository root. */ + readonly dir: string; +} + +/** One `go.work`: its directory and the module directories it `use`s. */ +export interface GoWorkFile { + readonly dir: string; + /** Repo-relative, normalized like {@link GoModule.dir}. Entries outside the + * repository are dropped: no file of theirs is in the analyzed set. */ + readonly use: readonly string[]; +} + +/** Go's resolution config: plain data, so it clones and compares by value. */ +export interface GoWorkspaceConfig { + /** Sorted by `dir`. */ + readonly modules: readonly GoModule[]; + /** Sorted by `dir`. */ + readonly workFiles: readonly GoWorkFile[]; +} + +/** + * Where an import's package lives, as far as the repository's modules say. + * + * - `module`: an in-repo module path owns the import. `dirs` are the package + * directories to try, longest module path first; empty when the owning + * module is unselected, ambiguous or the directory is another module's + * tree. The suffix match never runs for an owned path. + * - `external`: the importer is inside a module and no in-repo module owns + * the path — standard library or a dependency. Module mode never consults + * directory names for those. + * - `gopath`: the importer is outside every module and nothing owns the path, + * so the GOPATH-style suffix match is the only evidence left. + */ +export type GoImportLocation = + | { readonly kind: 'module'; readonly dirs: readonly string[] } + | { readonly kind: 'external' } + | { readonly kind: 'gopath' }; + +const GO_MOD = 'go.mod'; +const GO_WORK = 'go.work'; + +/** A `//` comment runs to the end of the line in both files. */ +function stripLineComment(line: string): string { + const comment = line.indexOf('//'); + return (comment < 0 ? line : line.slice(0, comment)).trim(); +} + +/** One directive argument: bare, or `"…"` / `` `…` `` quoted. */ +function unquote(token: string): string { + const quote = token[0]; + if ((quote === '"' || quote === '`') && token.length >= 2 && token.endsWith(quote)) { + return token.slice(1, -1); + } + return token; +} + +const MODULE_DIRECTIVE_RE = /^module\s+("[^"]+"|`[^`]+`|\S+)$/; + +/** The path a `go.mod`'s `module` directive declares, or null. */ +export function parseGoModulePath(goMod: string): string | null { + for (const raw of goMod.split('\n')) { + const match = MODULE_DIRECTIVE_RE.exec(stripLineComment(raw)); + if (match !== null) return unquote(match[1] ?? '') || null; + } + return null; +} + +const USE_DIRECTIVE_RE = /^use\s+("[^"]+"|`[^`]+`|\S+)$/; +const USE_BLOCK_OPEN_RE = /^use\s*\($/; + +/** The directories a `go.work`'s `use` directives name, as written. */ +export function parseGoWorkUses(goWork: string): string[] { + const uses: string[] = []; + let inBlock = false; + for (const raw of goWork.split('\n')) { + const line = stripLineComment(raw); + if (line === '') continue; + if (inBlock) { + if (line === ')') inBlock = false; + else uses.push(unquote(line)); + continue; + } + if (USE_BLOCK_OPEN_RE.test(line)) { + inBlock = true; + continue; + } + const single = USE_DIRECTIVE_RE.exec(line); + if (single !== null) uses.push(unquote(single[1] ?? '')); + } + return uses; +} + +/** `rel` joined onto the repo-relative `base`, or null when it is absolute or + * escapes the repository — Swift's rule for package paths, Zig's for deps. */ +function rebase(base: string, rel: string): string | null { + if (isAbsoluteZigDepPath(rel)) return null; + return normalizeZigDepPath(base === '' ? rel : `${base}/${rel}`); +} + +/** Repo-relative parent directory of a repo-relative path; `''` at the root. */ +function parentDir(filePath: string): string { + const slash = filePath.lastIndexOf('/'); + return slash < 0 ? '' : filePath.slice(0, slash); +} + +/** Code-unit order, deliberately not `localeCompare`: the sorted config is + * compared by value across runs, so the order must not depend on the locale. */ +function byDir(a: { readonly dir: string }, b: { readonly dir: string }): number { + return a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0; +} + +/** Manifests read at once; capture blocks the scan, and a k8s-style tree has + * hundreds of `go.mod` files. */ +const MANIFEST_READ_CONCURRENCY = 32; + +/** + * A manifest's text, or null when it is deliberately not read: + * + * - a symlink — it can point outside the repository, and Dart's manifest + * capture excludes links the same way; + * - not a regular file, or larger than the source-file cap — indexing skips + * such files too; + * - gone since the scan listed it (the stable-workspace boundary). + * + * Any other read error throws: a module boundary that silently disappears + * would send its imports to the wrong module or to GOPATH matching, and the + * capture contract requires failures to surface. + */ +async function readGoManifest(absolute: string, maxBytes: number): Promise { + // Every check reads the opened handle, never the path again, so the file + // cannot change between the check and the read. O_NOFOLLOW refuses a leaf + // symlink outright; O_NONBLOCK keeps a FIFO named go.mod from hanging. + let handle: FileHandle; + try { + handle = await fs.open( + absolute, + constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0), + ); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ELOOP') return null; + // Platforms without O_NOFOLLOW report a link some other way. + if ((await fs.lstat(absolute).catch(() => null))?.isSymbolicLink()) return null; + throw error; + } + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > maxBytes) return null; + // Without O_NOFOLLOW the open followed a link; refuse it the same way. + if ((await fs.lstat(absolute).catch(() => null))?.isSymbolicLink()) return null; + return await handle.readFile('utf-8'); + } finally { + await handle.close(); + } +} + +/** + * Capture every `go.mod` / `go.work` among the scan's paths. Null when the + * repository declares no module: every import then takes the GOPATH match, as + * it did with no root `go.mod`. + * + * A manifest {@link readGoManifest} declines, or a `go.mod` that declares no + * `module`, is treated as absent: its files fall to the enclosing module, or + * to GOPATH matching. A manifest that fails to read throws. + */ +export async function captureGoWorkspaceConfig( + repoPath: string, + filePaths: readonly string[], +): Promise { + const manifests = filePaths.filter((filePath) => { + const name = filePath.slice(filePath.lastIndexOf('/') + 1); + return name === GO_MOD || name === GO_WORK; + }); + const maxBytes = getMaxFileSizeBytes(); + const contents: (string | null)[] = []; + for (let start = 0; start < manifests.length; start += MANIFEST_READ_CONCURRENCY) { + const batch = manifests.slice(start, start + MANIFEST_READ_CONCURRENCY); + contents.push( + ...(await Promise.all( + batch.map((filePath) => readGoManifest(path.join(repoPath, filePath), maxBytes)), + )), + ); + } + + const modules: GoModule[] = []; + const workFiles: GoWorkFile[] = []; + manifests.forEach((filePath, i) => { + const content = contents[i]; + if (content === null || content === undefined) return; + const dir = parentDir(filePath); + if (filePath.endsWith(GO_MOD)) { + const modulePath = parseGoModulePath(content); + if (modulePath !== null) modules.push({ modulePath, dir }); + return; + } + const use: string[] = []; + for (const rel of parseGoWorkUses(content)) { + const moduleDir = rebase(dir, rel); + if (moduleDir !== null) use.push(moduleDir); + } + workFiles.push({ dir, use: use.sort() }); + }); + if (modules.length === 0) return null; + // Sorted, so the value is a function of the tree and not of listing order: + // rename compares a refreshed config against its preview's by value. + return { modules: modules.sort(byDir), workFiles: workFiles.sort(byDir) }; +} + +/** Standalone callers (rename refresh) scan with the walker the pipeline uses, + * so they see the same manifests analyze captured. A scan failure throws + * rather than reading as "no modules", which would silently swap in GOPATH + * matching and a config unequal to the one a rename preview was built on. */ +export async function loadGoWorkspaceConfig(repoPath: string): Promise { + let captured: GoWorkspaceConfig | null = null; + await walkRepositoryPaths(repoPath, undefined, { + quiet: true, + onPathsDiscovered: async (paths) => { + captured = await captureGoWorkspaceConfig(repoPath, paths); + }, + }); + return captured; +} + +/** True for a value {@link captureGoWorkspaceConfig} produced. */ +export function isGoWorkspaceConfig(value: unknown): value is GoWorkspaceConfig { + if (typeof value !== 'object' || value === null) return false; + const candidate = value as Partial; + return Array.isArray(candidate.modules) && Array.isArray(candidate.workFiles); +} + +/** Lookup tables over one config, built once per config object. */ +interface GoWorkspaceIndex { + readonly moduleByDir: ReadonlyMap; + /** Module path → every module declaring it, in `dir` order. */ + readonly modulesByPath: ReadonlyMap; + /** `go.work` directory → the module directories it uses. */ + readonly usesByWorkDir: ReadonlyMap>; + /** Directory → its nearest module (`null`: none), filled as imports ask. A + * file's imports all start from one directory, and every candidate package + * directory is checked against its owner, so the walks repeat. */ + readonly ownerByDir: Map; + /** Directory → its nearest `go.work` uses (`null`: none), filled lazily. */ + readonly workUsesByDir: Map | null>; +} + +/** Keyed on the config's identity: the orchestrator threads one config object + * through every import of a pass, the same contract `perFileSet` relies on. */ +const INDEXES = new WeakMap(); + +function indexOf(config: GoWorkspaceConfig): GoWorkspaceIndex { + const cached = INDEXES.get(config); + if (cached !== undefined) return cached; + const moduleByDir = new Map(); + const modulesByPath = new Map(); + for (const module of config.modules) { + moduleByDir.set(module.dir, module); + const group = modulesByPath.get(module.modulePath); + if (group === undefined) modulesByPath.set(module.modulePath, [module]); + else group.push(module); + } + const usesByWorkDir = new Map>(); + for (const work of config.workFiles) usesByWorkDir.set(work.dir, new Set(work.use)); + const index: GoWorkspaceIndex = { + moduleByDir, + modulesByPath, + usesByWorkDir, + ownerByDir: new Map(), + workUsesByDir: new Map(), + }; + INDEXES.set(config, index); + return index; +} + +/** The entry of `byDir` at `dir` or its nearest ancestor — the `go.mod` (or + * `go.work`) Go would find walking up from there. O(depth). */ +function nearest(byDir: ReadonlyMap, dir: string): T | undefined { + let current = dir; + for (;;) { + const found = byDir.get(current); + if (found !== undefined) return found; + if (current === '') return undefined; + current = parentDir(current); + } +} + +/** {@link nearest}, memoized per directory in `cache` (`null` caches a miss). */ +function nearestCached( + cache: Map, + byDir: ReadonlyMap, + dir: string, +): T | undefined { + const cached = cache.get(dir); + if (cached !== undefined) return cached ?? undefined; + const found = nearest(byDir, dir); + cache.set(dir, found ?? null); + return found; +} + +function pickModule( + group: readonly GoModule[], + ownOf: () => GoModule | undefined, + workUsesOf: () => ReadonlySet | undefined, +): GoModule | undefined { + const own = ownOf(); + if (own !== undefined && group.includes(own)) return own; + const workUses = workUsesOf(); + if (workUses === undefined) return undefined; + if (own !== undefined && !workUses.has(own.dir)) return undefined; + const used = group.filter((module) => workUses.has(module.dir)); + return used.length === 1 ? used[0] : undefined; +} + +/** Where `importPath`, imported from `fromFile`, can live. */ +export function locateGoImport( + config: GoWorkspaceConfig, + importPath: string, + fromFile: string, +): GoImportLocation { + const index = indexOf(config); + const fromDir = parentDir(fromFile.includes('\\') ? fromFile.replace(/\\/g, '/') : fromFile); + const ownOf = (): GoModule | undefined => + nearestCached(index.ownerByDir, index.moduleByDir, fromDir); + const workUsesOf = (): ReadonlySet | undefined => + nearestCached(index.workUsesByDir, index.usesByWorkDir, fromDir); + + const dirs: string[] = []; + let owned = false; + // Each `/`-prefix of the import path, longest first, is a candidate module + // path: O(segments) map probes rather than a scan of every module. + let prefix = importPath; + for (;;) { + const group = index.modulesByPath.get(prefix); + if (group !== undefined) { + owned = true; + const module = pickModule(group, ownOf, workUsesOf); + if (module !== undefined) { + const rel = importPath.slice(prefix.length + 1); + const dir = module.dir === '' ? rel : rel === '' ? module.dir : `${module.dir}/${rel}`; + // A nested `go.mod` between the module root and the package takes the + // directory out of this module. + if (nearestCached(index.ownerByDir, index.moduleByDir, dir) === module) dirs.push(dir); + } + } + const slash = prefix.lastIndexOf('/'); + if (slash < 0) break; + prefix = prefix.slice(0, slash); + } + + if (owned) return { kind: 'module', dirs }; + return ownOf() === undefined ? { kind: 'gopath' } : { kind: 'external' }; +} diff --git a/gitnexus/src/core/ingestion/scope-extractor.ts b/gitnexus/src/core/ingestion/scope-extractor.ts index 324ef1b14e..b09d9d8496 100644 --- a/gitnexus/src/core/ingestion/scope-extractor.ts +++ b/gitnexus/src/core/ingestion/scope-extractor.ts @@ -115,6 +115,7 @@ import { typeApplicationArguments, } from './utils/template-arguments.js'; import { parseTypeParameterList } from './utils/type-parameters.js'; +import { followedStep } from './utils/type-ref-chain.js'; // ─── Narrow hook surface the extractor actually uses ─────────────────────── @@ -1312,7 +1313,7 @@ function followChainedRef(start: TypeRef, draftById: ReadonlyMap string | undefined; + /** * Whether the compound-receiver resolver should strip C-style cast * expressions from receiver-position text before resolving it — diff --git a/gitnexus/src/core/ingestion/scope-resolution/passes/callable-value-flow.ts b/gitnexus/src/core/ingestion/scope-resolution/passes/callable-value-flow.ts index 85efc93cfa..8e0f23a31b 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/callable-value-flow.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/callable-value-flow.ts @@ -14,6 +14,7 @@ import type { ParsedFile, ScopeId, SymbolDefinition, + TypeRef, } from 'gitnexus-shared'; import type { KnowledgeGraph } from '../../../graph/types.js'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; @@ -32,6 +33,8 @@ import { } from '../scope/walkers.js'; import { definitionIdPosition } from '../utils/definition-id.js'; import { narrowOverloadCandidates } from './overload-narrowing.js'; +import { classOfQualifiedTypeSpelling } from './compound-receiver.js'; +import type { ScopeResolver } from '../contract/scope-resolver.js'; /** * Per-site dispatch-target cap. Above it the site is treated as overflowed and @@ -90,6 +93,10 @@ export interface EmitCallableValueFlowInput { readonly deferredIndirectSites?: ReadonlySet; /** When set, skip a second `referenceSites` signature walk. */ readonly callSignaturesBySite?: ReadonlyMap; + /** `ScopeResolver.qualifiedTypeLookupSpelling` and its visibility filter, so a + * bound member (`f := p.Save`) types `p` the way receiver-bound calls do. */ + readonly qualifiedTypeLookupSpelling?: ScopeResolver['qualifiedTypeLookupSpelling']; + readonly isNamespaceMemberVisible?: ScopeResolver['isNamespaceMemberVisible']; } export interface DeferredIndirectCollection { @@ -231,7 +238,10 @@ export function emitCallableValueFlow(input: EmitCallableValueFlowInput): Callab ); const uniqueGraphTargets = dedupeTargets([...graphTargets.values()]); const globalBySimpleName = buildGlobalCallableIndex(uniqueGraphTargets); - const targetIndexes = buildCallableTargetIndexes(uniqueGraphTargets, input.scopes); + const targetIndexes: CallableTargetIndexes = { + ...buildCallableTargetIndexes(uniqueGraphTargets, input.scopes), + classOfQualifiedReceiver: qualifiedReceiverLookup(input), + }; const bindingKey = (filePath: string, operand: CallableFlowOperand): string => canonicalBindingKey(filePath, operand, input.scopes); @@ -1122,6 +1132,9 @@ interface CallableTargetIndexes { readonly byQualifiedName: ReadonlyMap; readonly byOwnerAndName: ReadonlyMap; readonly byFileAndName: ReadonlyMap; + /** The class a receiver's QUALIFIED declared type names, when the provider + * recovers one; null refuses a qualified miss, undefined permits bare lookup. */ + readonly classOfQualifiedReceiver?: (typeRef: TypeRef) => SymbolDefinition | null | undefined; } function buildCallableTargetIndexes( @@ -1282,8 +1295,11 @@ function resolveBoundMemberCandidates( indirection: 0, addressOf: false, }; - const typeRef = receiverType(receiverOperand, scopes) ?? receiverName; - const receiverClass = resolveInheritanceBaseInScope(inScope, typeRef, scopes); + const typeRef = receiverType(receiverOperand, scopes); + const receiverClass = + typeRef === undefined + ? resolveInheritanceBaseInScope(inScope, receiverName, scopes) + : classOfReceiverType(typeRef, inScope, scopes, targetIndexes); if (receiverClass === undefined) return []; const owners = [receiverClass.nodeId, ...scopes.methodDispatch.mroFor(receiverClass.nodeId)]; const out: Target[] = []; @@ -1548,10 +1564,11 @@ function expandMemberTargets( } const typeRef = receiverType(invoke.site.receiver, scopes); if (typeRef === undefined) return new Map(targets); - const receiverClass = resolveInheritanceBaseInScope( - invoke.site.receiver.inScope, + const receiverClass = classOfReceiverType( typeRef, + invoke.site.receiver.inScope, scopes, + targetIndexes, ); if (receiverClass === undefined) return new Map(targets); const ownerChain = [receiverClass.nodeId, ...scopes.methodDispatch.mroFor(receiverClass.nodeId)]; @@ -1588,11 +1605,43 @@ function expandMemberTargets( function receiverType( operand: CallableFlowOperand, scopes: ScopeResolutionIndexes, -): string | undefined { +): TypeRef | undefined { return findReceiverTypeBinding(operand.inScope, operand.name, scopes, { position: operand.atRange.startLine > 0 ? operand.atRange : undefined, purpose: 'value', - })?.rawName; + }); +} + +function classOfReceiverType( + typeRef: TypeRef, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + targetIndexes: CallableTargetIndexes, +): SymbolDefinition | undefined { + const qualified = targetIndexes.classOfQualifiedReceiver?.(typeRef); + return qualified === undefined + ? resolveInheritanceBaseInScope(inScope, typeRef.rawName, scopes) + : (qualified ?? undefined); +} + +function qualifiedReceiverLookup( + input: EmitCallableValueFlowInput, +): CallableTargetIndexes['classOfQualifiedReceiver'] { + const spelling = input.qualifiedTypeLookupSpelling; + if (spelling === undefined) return undefined; + const memberVisible = input.isNamespaceMemberVisible; + const namespaceMemberVisible = + memberVisible === undefined + ? undefined + : (member: SymbolDefinition): boolean => memberVisible({ member }); + return (typeRef) => + classOfQualifiedTypeSpelling( + typeRef, + input.scopes, + spelling, + { position: typeRef.lookupPosition, purpose: typeRef.lookupPurpose ?? 'type' }, + namespaceMemberVisible, + ); } function targetForDef( 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 69b1c1145d..4bc6465a6d 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/passes/compound-receiver.ts @@ -31,7 +31,8 @@ import { } from '../../utils/template-arguments.js'; import type { DecodedReceiverChain } from '../../utils/receiver-chain-codec.js'; import { decodeReceiverChain } from '../../utils/receiver-chain-codec.js'; -import type { DecorationStripper } from '../scope/walkers.js'; +import { namespaceCallReturnType } from './imported-return-types.js'; +import type { ClassBindingLookup, DecorationStripper } from '../scope/walkers.js'; import { findClassBindingInScope, lookupNameClaim, @@ -44,6 +45,7 @@ import { findReceiverTypeBinding, isClassLike, isNamespaceNameShadowed, + moduleScopeIdOf, } from '../scope/walkers.js'; /** Max depth for compound-receiver chain resolution (`a().b().c().d()`). @@ -181,6 +183,10 @@ 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.qualifiedTypeLookupSpelling`, tried before `rawName` by + * every {@link classOfDeclaredType} caller (member, head and fold lookups). + * Absent ⇒ `rawName` alone, exactly as before. */ + readonly qualifiedTypeLookupSpelling?: ScopeResolver['qualifiedTypeLookupSpelling']; } /** Is this hop the language's construction selector applied to the class @@ -431,27 +437,87 @@ interface FoldState { * resolves through the identical `findClassBindingInScope` call it did before * (`resolveClassBindingForName` tries that first, and a name with no `<` * returns immediately after it). + * */ function classOfDeclaredType( typeRef: TypeRef, scopes: ScopeResolutionIndexes, + options: ResolveCompoundReceiverOptions, stripDecoration?: DecorationStripper, - recordReceiverType?: ReceiverTypeRecorder, - onNameFallback?: () => void, ): SymbolDefinition | undefined { // `declaredAtScope`, never a scope the caller chose: all five sites passed // exactly this `TypeRef`'s own anchor, and taking it as a parameter is what // would let a sixth quietly not — which is the hole this helper exists to // close, one level up. + const lookup: ClassBindingLookup = { + position: typeRef.lookupPosition, + purpose: typeRef.lookupPurpose ?? 'type', + onNameFallback: options.onNameFallback, + }; + // 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. const spelling = erasedTypeApplication(typeRef) ?? typeRef.rawName; - const def = resolveClassBindingForName( - typeRef.declaredAtScope, - spelling, + const qualified = classOfQualifiedTypeSpelling( + typeRef, scopes, - stripDecoration, - { position: typeRef.lookupPosition, purpose: typeRef.lookupPurpose ?? 'type', onNameFallback }, + options.qualifiedTypeLookupSpelling, + lookup, + options.namespaceMemberVisible, + ); + const def = + qualified === undefined + ? resolveClassBindingForName( + typeRef.declaredAtScope, + spelling, + scopes, + stripDecoration, + lookup, + ) + : (qualified ?? undefined); + return noteReceiverType(options.recordReceiverType, spelling, def); +} + +/** + * The class a declared type's QUALIFIED spelling names (`models.User`), or + * `null` when that spelling cannot resolve. `undefined` means the provider + * supplied no qualified spelling, so the caller may try the bare name. + * + * NAMESPACE-GROUNDED ONLY. The workspace-wide unique-name fallback is off for + * this attempt, so a hit came from the qualifier's import (its target files, + * filtered by `namespaceMemberVisible`), never from a name that happens to be + * unique. A qualified miss is authoritative: the bare `rawName` cannot name + * a different package's declaration just because it is unique in the repo. + * + * FROM THE MODULE SCOPE, not from `declaredAtScope`. The hook's qualifier names + * a file-level import, and `declaredAtScope` is where the BINDING lives — a + * scope that can bind the qualifier's own name. `vault *vault.Vault` as a field, + * a parameter or a local is ordinary code, and asked from there the qualifier + * `vault` found the receiver itself rather than the import, so the namespace + * branch had no target files and the bare fallback refused the ambiguous name. + * + * Exported for the simple-typeBinding case in `receiver-bound-calls`, so a + * receiver typed through a field and one typed through a parameter cannot + * disagree on which package `models.User` means. + */ +export function classOfQualifiedTypeSpelling( + typeRef: TypeRef, + scopes: ScopeResolutionIndexes, + qualifiedTypeLookupSpelling: ScopeResolver['qualifiedTypeLookupSpelling'], + lookup: ClassBindingLookup, + namespaceMemberVisible: ClassBindingLookup['namespaceMemberVisible'], +): 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); + if (qualified === undefined || qualified === typeRef.rawName) return undefined; + const importScope = moduleScopeIdOf(typeRef.declaredAtScope, scopes) ?? typeRef.declaredAtScope; + return ( + findClassBindingInScope(importScope, qualified, scopes, undefined, { + ...lookup, + namespaceMemberVisible, + uniqueQualifiedNameFallback: false, + }) ?? null ); - return noteReceiverType(recordReceiverType, spelling, def); } /** @@ -520,9 +586,8 @@ function typeOfMemberOnClass( const def = classOfDeclaredType( memberType, scopes, + options, options.stripTypePreservingDecoration, - options.recordReceiverType, - options.onNameFallback, ); // The declared type is reported even when it resolved to no class: // `Promise` and `[]Repo` name nothing in the workspace, and an @@ -557,9 +622,8 @@ function typeOfMemberOnClass( const def = classOfDeclaredType( hoisted, scopes, + options, options.stripTypePreservingDecoration, - options.recordReceiverType, - options.onNameFallback, ); // Identical to the primary branch: a declared type that named no // class is still a usable position when the next step unwraps it. @@ -924,13 +988,7 @@ export function resolveCompoundReceiverClass( }); } - const viaTb = classOfDeclaredType( - tb, - scopes, - options.stripTypePreservingDecoration, - options.recordReceiverType, - options.onNameFallback, - ); + const viaTb = classOfDeclaredType(tb, scopes, options, options.stripTypePreservingDecoration); if (viaTb !== undefined) return viaTb; // Member-alias / call-result shapes store the RHS path on rawName @@ -1065,6 +1123,19 @@ export function resolveCompoundReceiverClass( // indistinguishable from an untyped member call here. Only the namespace // map makes the constructor interpretation safe. if (options.namespaceTargets?.has(objExpr) === true) { + // A namespace function with a return annotation types the call like a + // 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, + ); + if (viaReturn !== undefined) return viaReturn; return resolveConstructionExpressionClass(fnExpr, inScope, scopes, index, options); } return undefined; @@ -1255,13 +1326,7 @@ export function resolveCompoundReceiverClass( // two had a fixture. See `classOfDeclaredType` for why this cannot change a // `TypeRef` that was never reduced. let currentClass: SymbolDefinition | undefined = headType - ? classOfDeclaredType( - headType, - scopes, - undefined, - options.recordReceiverType, - options.onNameFallback, - ) + ? classOfDeclaredType(headType, scopes, options) : findClassBindingInScope(inScope, headMemberName, scopes, undefined, { onNameFallback: options.onNameFallback, position: options.lookupPosition, @@ -1417,13 +1482,7 @@ export function resolveCompoundReceiverClass( // grounds fell through here — a declined fold is documented as "no answer", // never a veto — and this walk re-minted `other.py:Mapped` from the // workspace index. Same rule, same lookup, so the two routes now agree. - let nextClass = classOfDeclaredType( - memberType, - scopes, - undefined, - options.recordReceiverType, - options.onNameFallback, - ); + let nextClass = classOfDeclaredType(memberType, scopes, options); if (nextClass === undefined) { const fromMap = unwrapMapValueToClass(memberType, scopes, options.onNameFallback); if (fromMap !== undefined) nextClass = fromMap; 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 a772c5e929..fd0b246571 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 @@ -39,10 +39,18 @@ * scope-resolution generalization plan. */ -import type { ParsedFile, Scope, ScopeId, SymbolDefinition, TypeRef } from 'gitnexus-shared'; +import type { + ImportEdge, + ParsedFile, + Scope, + ScopeId, + SymbolDefinition, + TypeRef, +} from 'gitnexus-shared'; import type { ScopeResolutionIndexes } from '../../model/scope-resolution-indexes.js'; import type { WorkspaceResolutionIndex } from '../workspace-index.js'; import { definitionIdPosition } from '../utils/definition-id.js'; +import { followedStep } from '../../utils/type-ref-chain.js'; import { lookupBindingsAt, lookupNameClaim, @@ -115,6 +123,107 @@ function producerTypeRef(defId: string, scopes: ScopeResolutionIndexes): TypeRef */ const RECHAIN_MAX_DEPTH = 8; +/** `head.member`, both plain identifiers. */ +const QUALIFIED_MEMBER_RE = /^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/; + +/** + * Every local name a resolved namespace import binds anywhere in the + * workspace. Most dotted bindings are member chains (`user.address`), or name + * an external module (`np.zeros`), and skip the scope-chain lookup entirely. + * Read from the finalized import map, never `scopeTree.byId`, which a sealed + * disk-backed tree cannot materialize. Import edges are fixed once finalize + * has run. + */ +const namespaceLocalNamesByIndexes = new WeakMap>(); + +/** + * A resolved namespace import whose local name stands for its target module. + * An unaliased path import (`import pkg.sub`) binds the root `pkg` while its + * target is the leaf `pkg/sub`, so the target's members are not `pkg`'s. + */ +function bindsTargetModule(edge: ImportEdge): boolean { + if ( + edge.kind !== 'namespace' || + edge.linkStatus === 'unresolved' || + edge.targetModuleScope === undefined + ) { + return false; + } + if (edge.explicitAlias === true || !edge.targetExportedName.startsWith(`${edge.localName}.`)) { + return true; + } + const file = edge.targetFile?.split(/[\\/]/).pop() ?? ''; + const dot = file.indexOf('.'); + return (dot === -1 ? file : file.slice(0, dot)) === edge.localName; +} +function namespaceLocalNames(scopes: ScopeResolutionIndexes): ReadonlySet { + let names = namespaceLocalNamesByIndexes.get(scopes); + if (names === undefined) { + const collected = new Set(); + for (const edges of scopes.imports.values()) { + for (const edge of edges) { + if (bindsTargetModule(edge)) collected.add(edge.localName); + } + } + names = collected; + namespaceLocalNamesByIndexes.set(scopes, names); + } + return names; +} + +/** + * Some providers hoist method return types to the module scope under the + * method's name, so a module-scope return binding named `member` can belong + * to a class method. Accept it only when it is anchored on a free function the + * module itself binds under that name: the declaration-anchor join + * `producerTypeRef` uses. Providers that bind receiver methods at module + * scope (`func (f *T) Create()`) put a `Method` there, which never qualifies. + */ +function isModuleOwnReturn(returned: TypeRef, module: Scope, member: string): boolean { + const anchor = returned.bindingRange; + if (anchor === undefined) return true; + return (module.bindings.get(member) ?? []).some((binding) => { + if (binding.origin !== 'local' || binding.def.type !== 'Function') return false; + const position = definitionIdPosition(binding.def.nodeId, binding.def.filePath); + return position?.line === anchor.startLine && position.column === anchor.startCol; + }); +} + +/** + * `ns.f` where `ns` is a namespace import and `f` has a return annotation in + * the target module: that return type, as a named import of `f` gets through + * `propagateImportedReturnTypes` (#3498). A class member (`ns.C`) has no + * return annotation and keeps resolving as a construction. + */ +export function namespaceCallReturnType( + rawName: string, + inScope: ScopeId, + scopes: ScopeResolutionIndexes, + position?: TypeRef['lookupPosition'], +): TypeRef | undefined { + const [, head, member] = QUALIFIED_MEMBER_RE.exec(rawName) ?? []; + if (head === undefined || member === undefined || !namespaceLocalNames(scopes).has(head)) { + return undefined; + } + const claim = lookupNameClaim(inScope, head, scopes, { position, purpose: 'value' }); + if (claim.bindings.some((binding) => binding.origin === 'local')) return undefined; + const targets = new Set(); + for (const edge of claim.imports) { + if (bindsTargetModule(edge) && edge.targetModuleScope !== undefined) { + targets.add(edge.targetModuleScope); + } + } + const [target] = targets; + if (targets.size !== 1 || target === undefined) return undefined; + const module = scopes.scopeTree.getScope(target); + const returned = module?.typeBindings.get(member); + return module !== undefined && + returned?.source === 'return-annotation' && + isModuleOwnReturn(returned, module, member) + ? 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 @@ -131,8 +240,28 @@ export function followChainPostFinalize( // accessibility-gated per-namespace fallback below can be consulted cheaply. const moduleScopeId = moduleScopeIdOf(fromScopeId, scopes); for (let depth = 0; depth < RECHAIN_MAX_DEPTH; depth++) { - if (current.rawName.includes('.')) return current; const lookupScope = current.declaredAtScope ?? fromScopeId; + if (current.rawName.includes('.')) { + const returned = namespaceCallReturnType( + current.rawName, + lookupScope, + scopes, + current.lookupPosition, + ); + // A qualified return type (`-> models.Order`) names a namespace of the + // producer's module, which the consumer's receiver lookup would read + // against its own imports. Stop at the call rather than hand it over. + if ( + returned === undefined || + returned.rawName.includes('.') || + visited.has(returned.rawName) + ) { + return current; + } + visited.add(returned.rawName); + current = followedStep(start, returned); + continue; + } const claim = lookupNameClaim(lookupScope, current.rawName, scopes, { position: current.lookupPosition, purpose: current.lookupPurpose, @@ -172,7 +301,7 @@ export function followChainPostFinalize( if (next === undefined) return current; if (visited.has(next.rawName)) return current; visited.add(next.rawName); - current = { ...next, bindingRange: start.bindingRange }; + current = followedStep(start, next); } return current; } 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 614b0aea0d..79d43545b9 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 @@ -88,6 +88,7 @@ import { findValueBindingInScope, isClassLike, isNamespaceNameShadowed, + type ClassBindingLookup, type DecorationStripper, resolveClassBindingForName, } from '../scope/walkers.js'; @@ -99,6 +100,7 @@ import { import { constructionSiteReason } from './free-call-fallback.js'; import type { CalleeIdSink } from '../graph-bridge/callee-id-sink.js'; import { + classOfQualifiedTypeSpelling, resolveCompoundReceiverClass, resolveCompoundReceiverTyped, } from '../passes/compound-receiver.js'; @@ -188,6 +190,7 @@ type ReceiverBoundProviderSubset = Pick< | 'stripReceiverCastExpressions' | 'constructionSyntax' | 'stripTypePreservingDecoration' + | 'qualifiedTypeLookupSpelling' | 'resolveQualifiedReceiverMember' | 'namespaceReceiverPaths' | 'namespaceBindingIdentity' @@ -213,6 +216,10 @@ type ReceiverBoundProviderSubset = Pick< /** A bare, undecorated identifier and nothing else — see {@link isBareTypeName}. */ const BARE_TYPE_NAME_RE = /^[A-Za-z_$][\w$]*$/; +const CALLABLE_TYPES: ReadonlySet = new Set([ + 'Function', + 'Method', +]); /** * A type name a built-in test may be asked about: a bare, undecorated @@ -478,6 +485,21 @@ export function emitReceiverBoundCalls( } return picked; }; + + // #3498: whether a receiver's binding is a namespace function call + // (`x = ns.f()`): `f` is in the program, so the result type it failed to + // provide is a loss, not completeness. + const bindsNamespaceCallable = ( + typeRef: TypeRef, + namespaceTargets: ReadonlyMap, + ): boolean => { + const [, head, member] = TWO_PART_RECEIVER_RE.exec(typeRef.rawName) ?? []; + if (head === undefined || member === undefined) return false; + return (namespaceTargets.get(head) ?? []).some((file) => { + const def = lookupNamespaceMember(file, member); + return def !== undefined && CALLABLE_TYPES.has(def.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 @@ -624,6 +646,7 @@ export function emitReceiverBoundCalls( stripReceiverCastExpressions: provider.stripReceiverCastExpressions === true, constructionSyntax: provider.constructionSyntax, stripTypePreservingDecoration: provider.stripTypePreservingDecoration, + qualifiedTypeLookupSpelling: provider.qualifiedTypeLookupSpelling, resolveThisViaEnclosingClass: provider.resolveThisViaEnclosingClass, }; // Loop-invariant: both hooks come off the pass arguments, so the options bag @@ -1144,6 +1167,10 @@ export function emitReceiverBoundCalls( ? { sink: options.calleeIdSink, filePath: parsed.filePath } : undefined; + // Duplicate captures of one site share a key and a member name. Distinct + // calls can share only the key (`ns.make().m()` starts where `ns.make()` + // does), so one's resolution must not hide the other's drop (#3498). + const siteIdentitiesByKey = new Map>(); for (const site of parsed.referenceSites) { if (site.kind !== 'call' && site.kind !== 'read' && site.kind !== 'write') continue; if (site.explicitReceiver === undefined) continue; @@ -1186,6 +1213,14 @@ export function emitReceiverBoundCalls( const receiverName = site.explicitReceiver.name; const memberName = site.name; const siteKey = `${parsed.filePath}:${site.atRange.startLine}:${site.atRange.startCol}`; + // A duplicate capture (or a call's own callee read) repeats the member + // on the same receiver; an outer call that starts where its inner one + // does (`a.f().f()`) has the inner call as its receiver. + const earlierAtKey = recordSiteMember( + siteIdentitiesByKey, + siteKey, + `${receiverName}.${memberName}`, + ); if (provider.suppressReceiverLookup !== undefined) { const baseName = @@ -2321,17 +2356,28 @@ export function emitReceiverBoundCalls( // takes the GROUNDED route rather than binding whatever the workspace // declares under that base name — see {@link erasedTypeApplication}. const typeApplication = erasedTypeApplication(typeRef); - let ownerDef = resolveClassBindingForName( - typeRef.declaredAtScope, - typeApplication ?? typeRef.rawName, + const typeLookup: ClassBindingLookup = { + position: typeRef.lookupPosition, + purpose: typeRef.lookupPurpose ?? 'type', + onNameFallback, + }; + const qualifiedOwner = classOfQualifiedTypeSpelling( + typeRef, scopes, - undefined, - { - position: typeRef.lookupPosition, - purpose: typeRef.lookupPurpose ?? 'type', - onNameFallback, - }, + provider.qualifiedTypeLookupSpelling, + typeLookup, + namespaceMemberVisible, ); + let ownerDef = + qualifiedOwner === undefined + ? resolveClassBindingForName( + typeRef.declaredAtScope, + typeApplication ?? typeRef.rawName, + scopes, + undefined, + typeLookup, + ) + : (qualifiedOwner ?? undefined); // `findClassBindingInScope(..., typeRef.rawName)` only works when // rawName is itself a class symbol reachable through scope bindings. // For languages with namespace-style imports (Go), imported types @@ -2352,6 +2398,7 @@ export function emitReceiverBoundCalls( }); if ( ownerDef === undefined && + qualifiedOwner !== null && typeApplication === undefined && !hasExplicitNameClaim(typeClaim, typeRef.rawName) ) { @@ -2378,7 +2425,7 @@ export function emitReceiverBoundCalls( // `rawName`; its callable-alias step retries the same name as a // construction). Asking again by a route that cannot see the grounds // would make the refusal decorative. - if (ownerDef === undefined && typeApplication === undefined) { + if (ownerDef === undefined && qualifiedOwner !== null && typeApplication === undefined) { ownerDef = resolveCompoundReceiverClass( receiverName, site.inScope, @@ -2388,24 +2435,11 @@ export function emitReceiverBoundCalls( { ...fileCompoundOpts, receiverChain: site.receiverChain }, ); } - // The receiver has a declared type, that type is a type APPLICATION, - // and its base name could not be connected to any declaration this - // file can see. The site is DROPPED, and dropped deliberately, so it - // must be marked handled: `emitReferencesViaLookup` would otherwise - // re-emit the very target the grounds refused, because the pre-resolved - // reference index answers a name with the single workspace definition - // that carries it and knows nothing about erasure. That is exactly why - // the static-only filter above marks handled too — a refusal this pass - // makes is not a refusal until the fallback emitter is told. - // - // Recorded as `receiver-unresolved` rather than silently: the receiver's - // TYPE could not be established, which is the reason's own definition, - // and a consumer counting resolver gaps must see this drop rather than - // read the absence as a resolved site. No `receiverOrigin` — the base - // name resolving in the index is precisely the evidence just rejected, - // so claiming `in-program` from it would relaunder the fabrication as a - // diagnostic, and the absent field hedges (the safe direction). - if (ownerDef === undefined && typeApplication !== undefined) { + // A qualified type or type application could not resolve to a visible + // declaration. Mark the site handled so the fallback reference emitter + // cannot reconnect it by bare name. Record the unresolved receiver, but + // omit receiverOrigin because no declaration was established. + if (ownerDef === undefined && (qualifiedOwner === null || typeApplication !== undefined)) { options.recordResolutionOutcome?.({ kind: 'suppressed', reason: 'receiver-unresolved', @@ -3151,9 +3185,19 @@ export function emitReceiverBoundCalls( // keyed by the MEMBER name, which is the only thing still known about a // dropped site (its callee is unknown by definition, so the drop cannot // be attributed to any target symbol). + // Every resolving case `continue`s, so a handled key here came from an + // earlier site or pre-seeding; it hides this drop only when that site + // was a duplicate capture of this one. + const hiddenByEarlierSite = handledSites.has(siteKey) && earlierAtKey !== 'shared-key'; if ( - (compoundReceiverUnresolved || receiverNamespace !== undefined) && - !handledSites.has(siteKey) + !hiddenByEarlierSite && + (compoundReceiverUnresolved || + receiverNamespace !== undefined || + // #3498: a plain receiver bound to a namespace call the analyzer + // 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))) ) { // 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 @@ -3243,6 +3287,33 @@ function splitClassLevelMemberReceiver( /** `Holder.repo` and nothing looser — see {@link splitClassLevelMemberReceiver}. */ const TWO_PART_RECEIVER_RE = /^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/; +/** How an earlier site in the same file relates to this one's position key. */ +export type EarlierSiteAtKey = 'new-key' | 'shared-key' | 'repeated-site'; + +/** Record a site's identity (receiver and member) at its start `siteKey` and say + * what was there before: nothing, a different call starting at the same + * position, or this same site (a duplicate capture). One map entry per key; + * a Set only on a collision. */ +export function recordSiteMember( + identitiesByKey: Map>, + siteKey: string, + identity: string, +): EarlierSiteAtKey { + const seen = identitiesByKey.get(siteKey); + if (seen === undefined) { + identitiesByKey.set(siteKey, identity); + return 'new-key'; + } + if (typeof seen === 'string') { + if (seen === identity) return 'repeated-site'; + identitiesByKey.set(siteKey, new Set([seen, identity])); + return 'shared-key'; + } + if (seen.has(identity)) return 'repeated-site'; + seen.add(identity); + return 'shared-key'; +} + /** Resolve a member by name on a class def, narrowing by argument * types when multiple overloads share the name. Falls back to the * first-seen def (legacy `findOwnedMember` semantics) when there's diff --git a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts index 2c4168d449..97f8a66b06 100644 --- a/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts +++ b/gitnexus/src/core/ingestion/scope-resolution/pipeline/run.ts @@ -1537,6 +1537,8 @@ export function runScopeResolution( collapseByCallerTarget: provider.collapseMemberCallsByCallerTarget === true, isCallableValueTarget: provider.isCallableValueTarget, hasFileLocalCallableLinkage: provider.hasFileLocalCallableLinkage, + qualifiedTypeLookupSpelling: provider.qualifiedTypeLookupSpelling, + isNamespaceMemberVisible: provider.isNamespaceMemberVisible, deferredIndirectSites, callSignaturesBySite: deferredIndirectCollection.callSignaturesBySite, onWarn: (warning) => diff --git a/gitnexus/src/core/ingestion/utils/type-ref-chain.ts b/gitnexus/src/core/ingestion/utils/type-ref-chain.ts new file mode 100644 index 0000000000..549607ef3e --- /dev/null +++ b/gitnexus/src/core/ingestion/utils/type-ref-chain.ts @@ -0,0 +1,14 @@ +import type { TypeRef } from 'gitnexus-shared'; + +/** + * One chain step: the binding takes the type the step reached, but keeps its + * own written spelling when it has one. A spelling is evidence about THIS + * binding — `member models.User`, normalized to `User`, can land on a sibling + * field named `User` whose spelling is `api.User`, and a consumer reading the + * spelling (a qualified lookup, an index step) must still see `models.User`. + */ +export function followedStep(start: TypeRef, next: TypeRef): TypeRef { + return start.declaredSpelling === undefined + ? { ...next, bindingRange: start.bindingRange } + : { ...next, bindingRange: start.bindingRange, declaredSpelling: start.declaredSpelling }; +} diff --git a/gitnexus/test/fixtures/go-captures-golden/expected-captures.json b/gitnexus/test/fixtures/go-captures-golden/expected-captures.json index b73a0fa513..ef70f5c7a7 100644 --- a/gitnexus/test/fixtures/go-captures-golden/expected-captures.json +++ b/gitnexus/test/fixtures/go-captures-golden/expected-captures.json @@ -271,6 +271,34 @@ "captureGroups": 19, "digest": "28ef663decb5e16b8cdbf16216849dff53d1e898a2cbd1dd1e68c116ce426cd8" }, + "go-multi-module-workspace/billing-service/cmd/billing/main.go": { + "captureGroups": 16, + "digest": "f3ada1a2161cba89c495c90a8ccd9f9d0cd56efc13ff1ac7e3c9078b109322ef" + }, + "go-multi-module-workspace/billing-service/internal/repository/ledger.go": { + "captureGroups": 15, + "digest": "67227def7d3fcf715a11aecf8f5caecb8a26f67daf583e5f8cb9c465689387fe" + }, + "go-multi-module-workspace/orders-service/cmd/orders/main.go": { + "captureGroups": 16, + "digest": "4e87ec9227431cd8a384e48846a595f2e71058931b39357602b19407cea7fe57" + }, + "go-multi-module-workspace/orders-service/internal/repository/ledger.go": { + "captureGroups": 15, + "digest": "3674ece23db6df045e050ff1e413649a803d9b900b435a9c633266426d73d732" + }, + "go-multi-module-workspace/tools/codegen/cmd/gen/main.go": { + "captureGroups": 10, + "digest": "3a130734eeb29dbe5c8c98ac652ec964fe3dd8cba30b1f96c7b06fa7125c7332" + }, + "go-multi-module-workspace/tools/codegen/legacy/template.go": { + "captureGroups": 8, + "digest": "b625d5ba562904fe9a87c549cabadb480d7493cee673c856aae9cc4fb6e774a3" + }, + "go-multi-module-workspace/tools/codegen/models/template.go": { + "captureGroups": 8, + "digest": "c7337983623acd224eaed5a0b103f099fff0d4b8ba25172b01cd4a4004c1269e" + }, "go-multi-return-inference/cmd/main.go": { "captureGroups": 38, "digest": "a1246c7603634e4e417310ca8cf105ff6465e3b466450f597b2f78ac25713c05" @@ -363,6 +391,54 @@ "captureGroups": 14, "digest": "9b1882cd492a04c605a5e6d32f2e264970eb8d4f359511d76b0ede6d8bff60c9" }, + "go-qualified-declared-types/api/bridge.go": { + "captureGroups": 10, + "digest": "7e5074af5bf2f058f35809b603efa6835035b923803937d326f27d69693bd33b" + }, + "go-qualified-declared-types/api/local.go": { + "captureGroups": 9, + "digest": "367ccdc55cca06a463d176678675eb58a0191b619442b7e647baed2d9403acd4" + }, + "go-qualified-declared-types/api/user.go": { + "captureGroups": 23, + "digest": "cf7aeb0e27271337a7c8ee64f5dcc58d9168711448ab38bd6c05705092613551" + }, + "go-qualified-declared-types/api/vault.go": { + "captureGroups": 11, + "digest": "7a69aed08d317da159ec3a7ebf4bbb432a55a05488098dbf8a817cb2d366d2dd" + }, + "go-qualified-declared-types/gadgets/gizmo.go": { + "captureGroups": 21, + "digest": "8229ee21ee3f3b22c4df1de78500ad22463d8cc52c80794bfa47b91842f024cb" + }, + "go-qualified-declared-types/models/user.go": { + "captureGroups": 23, + "digest": "ec29a949d55c6c32cb5209d4aa231b5ac63fc56f0edbb3076b698522e89ec775" + }, + "go-qualified-declared-types/services/aliased.go": { + "captureGroups": 10, + "digest": "e367811aaf0208b92e3d0b72697f960d4672801d1004a3ccfb8ec949bcfb8ff2" + }, + "go-qualified-declared-types/services/foreign.go": { + "captureGroups": 41, + "digest": "675bcf769ef59c71f47c6f94ebd54e2540200516622bad49534ce70b5e573dc8" + }, + "go-qualified-declared-types/services/locals.go": { + "captureGroups": 19, + "digest": "938bd4d0fd7d7eea69f24ff0d64c1dee5a2296fcbaf44d041716f151d2088dc9" + }, + "go-qualified-declared-types/services/service.go": { + "captureGroups": 60, + "digest": "ab0fac055b7a055140d1d99d21bafebc47f0d932b6ea6080c20f2d0deb3a16fb" + }, + "go-qualified-declared-types/services/vaults.go": { + "captureGroups": 30, + "digest": "1ddf14e740ffc861110385fb20fa8d91b66893aee95c4f8ac2c20348c8f8c15f" + }, + "go-qualified-declared-types/vault/vault.go": { + "captureGroups": 11, + "digest": "1cfdf63e480498cb6f79bf7450a8744ef446d50b69155d7b613040b764c5a995" + }, "go-receiver-method-free-call/example.go": { "captureGroups": 8, "digest": "ec13b52723d8078edbf36d3f85abd6d58fc6e2bfec781b978ff57659c7f0676a" @@ -395,6 +471,26 @@ "captureGroups": 17, "digest": "f208647af1057fe1819f68e62d4afe7dae891af386a4cc688d2d60840a0fbd00" }, + "go-root-with-nested-module/cmd/server/main.go": { + "captureGroups": 15, + "digest": "a1757bc0994d6bee5676d81bdbaf65785c8ea430b917f8cc139bb7c96edfc68d" + }, + "go-root-with-nested-module/internal/repository/ledger.go": { + "captureGroups": 8, + "digest": "3a56852829c12b76b4e97b0f8a32a0942f8e165aefc83a0e5e218ef161aeed25" + }, + "go-root-with-nested-module/pkg/clock/clock.go": { + "captureGroups": 7, + "digest": "3b1cc628c3ee80220dc4d58ba29f38c58ef47c901c900f2feefd96c1c0f57219" + }, + "go-root-with-nested-module/services/billing/cmd/billing/main.go": { + "captureGroups": 10, + "digest": "7b617a3316004439b9d7cf20b10e5c81b751d9340da786e76d06dfe49da5a0d1" + }, + "go-root-with-nested-module/services/billing/internal/repository/ledger.go": { + "captureGroups": 8, + "digest": "1312de223283786033ff968bf8c39d5fb67c51a10f0ee3c7780e54e458e62203" + }, "go-same-package-factory/main.go": { "captureGroups": 14, "digest": "16b78486154a15e873cf72f7085f0840bb14948632b5dbf38d843329ab3871d4" diff --git a/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/callers.dart b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/callers.dart new file mode 100644 index 0000000000..a9c6b69666 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/callers.dart @@ -0,0 +1,23 @@ +import 'mod.dart' as rp; + +int finalCall() { + final x = rp.make(); + return x.m(); +} + +int varCall() { + var x = rp.make(); + return x.m(); +} + +int inlineCall() => rp.make().m(); + +int untypedCall() { + final x = rp.untyped(); + return x.m(); +} + +Future awaitedCall() async { + final x = await rp.makeAsync(); + return x.m(); +} diff --git a/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/mod.dart b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/mod.dart new file mode 100644 index 0000000000..3975aff35b --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/lib/mod.dart @@ -0,0 +1,13 @@ +class C { + int m() => 1; +} + +class Other { + int m() => 2; +} + +C make() => C(); + +untyped() => C(); + +Future makeAsync() async => C(); diff --git a/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/pubspec.yaml b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/pubspec.yaml new file mode 100644 index 0000000000..f75c9b3399 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/dart-prefixed-factory-return/pubspec.yaml @@ -0,0 +1 @@ +name: prefixed_factory_return diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/cmd/billing/main.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/cmd/billing/main.go new file mode 100644 index 0000000000..646f4735c4 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/cmd/billing/main.go @@ -0,0 +1,10 @@ +package main + +import "github.com/acme/billing/internal/repository" + +func ChargeOrder(ledger *repository.Ledger) error { + if err := ledger.ChargeCard(42); err != nil { + return err + } + return ledger.Save() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/go.mod b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/go.mod new file mode 100644 index 0000000000..7d4fe8ddc8 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/go.mod @@ -0,0 +1,3 @@ +module github.com/acme/billing + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/internal/repository/ledger.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/internal/repository/ledger.go new file mode 100644 index 0000000000..aaa9d9daaf --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/billing-service/internal/repository/ledger.go @@ -0,0 +1,7 @@ +package repository + +type Ledger struct{} + +func (s *Ledger) Save() error { return nil } + +func (s *Ledger) ChargeCard(amount int) error { return nil } diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/cmd/orders/main.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/cmd/orders/main.go new file mode 100644 index 0000000000..0fb5277e95 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/cmd/orders/main.go @@ -0,0 +1,10 @@ +package main + +import "github.com/acme/orders/internal/repository" + +func PlaceOrder(ledger *repository.Ledger) error { + if err := ledger.ReserveStock("sku-1"); err != nil { + return err + } + return ledger.Save() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/go.mod b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/go.mod new file mode 100644 index 0000000000..c07f0258ad --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/go.mod @@ -0,0 +1,3 @@ +module github.com/acme/orders + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/internal/repository/ledger.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/internal/repository/ledger.go new file mode 100644 index 0000000000..d918cf59ff --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/orders-service/internal/repository/ledger.go @@ -0,0 +1,9 @@ +package repository + +// Ledger shares its name, package path tail and Save with billing's: for a +// Save call, only the module that owns the import tells the two apart. +type Ledger struct{} + +func (s *Ledger) Save() error { return nil } + +func (s *Ledger) ReserveStock(sku string) error { return nil } diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/cmd/gen/main.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/cmd/gen/main.go new file mode 100644 index 0000000000..7869255c8c --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/cmd/gen/main.go @@ -0,0 +1,7 @@ +package main + +import "example.com/generator/v2/models" + +func Generate(tpl *models.Template) string { + return tpl.Render() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/go.mod b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/go.mod new file mode 100644 index 0000000000..c542faaf9a --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/go.mod @@ -0,0 +1,4 @@ +// A major-version module whose directory names neither its path nor its suffix. +module example.com/generator/v2 + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/legacy/template.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/legacy/template.go new file mode 100644 index 0000000000..810cf715f6 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/legacy/template.go @@ -0,0 +1,7 @@ +package legacy + +// Same type and method name as models.Template, so a bare-name guess is +// ambiguous and only the import can pick models. +type Template struct{} + +func (t *Template) Render() string { return "" } diff --git a/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/models/template.go b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/models/template.go new file mode 100644 index 0000000000..3c1eb697d0 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-multi-module-workspace/tools/codegen/models/template.go @@ -0,0 +1,5 @@ +package models + +type Template struct{} + +func (t *Template) Render() string { return "" } diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/bridge.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/bridge.go new file mode 100644 index 0000000000..ddf6188217 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/bridge.go @@ -0,0 +1,9 @@ +package api + +import "example.com/go-qualified-declared-types/models" + +// The qualifier names models.User even though this package declares a User +// of its own. +func Forward(u models.User) bool { + return u.Archive() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/local.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/local.go new file mode 100644 index 0000000000..c897371318 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/local.go @@ -0,0 +1,6 @@ +package api + +// A bare, same-package spelling: `User` here is api.User. +func ArchiveLocal(u User) bool { + return u.Archive() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/user.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/user.go new file mode 100644 index 0000000000..2971dba5b2 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/user.go @@ -0,0 +1,20 @@ +package api + +// Same type names and method names as package models: only the package +// qualifier at the use site says which one a receiver means. +type Mailbox struct { + Pending int +} + +func (m *Mailbox) Purge() int { + return m.Pending +} + +type User struct { + Handle string + Inbox Mailbox +} + +func (u *User) Archive() bool { + return u.Handle != "" +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/vault.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/vault.go new file mode 100644 index 0000000000..4fbb91a08e --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/api/vault.go @@ -0,0 +1,10 @@ +package api + +// Collides with vault.Vault, method name included. +type Vault struct { + Slots int +} + +func (v *Vault) Stow() int { + return v.Slots +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/gadgets/gizmo.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/gadgets/gizmo.go new file mode 100644 index 0000000000..781112aa6f --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/gadgets/gizmo.go @@ -0,0 +1,19 @@ +package gadgets + +// The only Gizmo in the workspace. Rotor shares the method name, so a Spin() +// call resolves only once its receiver is typed. +type Gizmo struct { + Turns int +} + +func (g *Gizmo) Spin() int { + return g.Turns +} + +type Rotor struct { + Blades int +} + +func (r *Rotor) Spin() int { + return r.Blades +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/go.mod b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/go.mod new file mode 100644 index 0000000000..87f6cc37a1 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/go.mod @@ -0,0 +1,3 @@ +module example.com/go-qualified-declared-types + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/models/user.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/models/user.go new file mode 100644 index 0000000000..4cd2e6e6ae --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/models/user.go @@ -0,0 +1,18 @@ +package models + +type Mailbox struct { + Unread int +} + +func (m *Mailbox) Purge() int { + return m.Unread +} + +type User struct { + Name string + Inbox Mailbox +} + +func (u *User) Archive() bool { + return u.Name != "" +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/aliased.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/aliased.go new file mode 100644 index 0000000000..2092e87e3d --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/aliased.go @@ -0,0 +1,7 @@ +package services + +import m "example.com/go-qualified-declared-types/models" + +func ArchiveAliased(u m.User) bool { + return u.Archive() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/foreign.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/foreign.go new file mode 100644 index 0000000000..ebf3516d60 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/foreign.go @@ -0,0 +1,31 @@ +package services + +import ( + "example.com/elsewhere/ext" + "example.com/elsewhere/gadgets" +) + +// `ext` is not part of this module, so nothing here can say which workspace +// User this would be. +func ArchiveForeign(u ext.User) bool { + return u.Archive() +} + +// Also outside this module, but the workspace declares exactly one Gizmo. +func SpinGadget(g gadgets.Gizmo) int { + return g.Spin() +} + +// The same two shapes reached through struct fields. +type Workshop struct { + owner ext.User + gadget gadgets.Gizmo +} + +func (w *Workshop) ArchiveForeignField() bool { + return w.owner.Archive() +} + +func (w *Workshop) SpinGadgetField() int { + return w.gadget.Spin() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/locals.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/locals.go new file mode 100644 index 0000000000..2c160e6c9c --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/locals.go @@ -0,0 +1,13 @@ +package services + +import "example.com/go-qualified-declared-types/models" + +func ArchiveDeclared() bool { + var u models.User + return u.Archive() +} + +func ArchiveConstructed() bool { + u := &models.User{Name: "n"} + return u.Archive() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/service.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/service.go new file mode 100644 index 0000000000..32d248a630 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/service.go @@ -0,0 +1,36 @@ +package services + +import ( + "example.com/go-qualified-declared-types/api" + "example.com/go-qualified-declared-types/models" +) + +type Archiver struct { + member models.User + pointer *models.User + remote api.User +} + +func ArchiveByValue(u models.User) bool { + return u.Archive() +} + +func ArchiveByPointer(u *models.User) bool { + return u.Archive() +} + +func PurgeInbox(u models.User) int { + return u.Inbox.Purge() +} + +func (a *Archiver) ArchiveMember() bool { + return a.member.Archive() +} + +func (a *Archiver) ArchivePointer() bool { + return a.pointer.Archive() +} + +func (a *Archiver) ArchiveRemote() bool { + return a.remote.Archive() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/vaults.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/vaults.go new file mode 100644 index 0000000000..e441116590 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/services/vaults.go @@ -0,0 +1,23 @@ +package services + +import "example.com/go-qualified-declared-types/vault" + +// Each receiver below is named like its type's package. The qualifier in its +// type still names the import: Go resolves a parameter's or local's type +// before the name is in scope, and struct fields are never in lexical scope. +type Keeper struct { + vault *vault.Vault +} + +func (k *Keeper) StowField() int { + return k.vault.Stow() +} + +func StowParam(vault *vault.Vault) int { + return vault.Stow() +} + +func StowLocal() int { + var vault vault.Vault + return vault.Stow() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/vault/vault.go b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/vault/vault.go new file mode 100644 index 0000000000..d400ed06cc --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-qualified-declared-types/vault/vault.go @@ -0,0 +1,9 @@ +package vault + +type Vault struct { + Items int +} + +func (v *Vault) Stow() int { + return v.Items +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/cmd/server/main.go b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/cmd/server/main.go new file mode 100644 index 0000000000..bad676b092 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/cmd/server/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "example.com/platform/internal/repository" + "example.com/platform/pkg/clock" +) + +func Serve(ledger *repository.Ledger, clk *clock.Clock) error { + clk.Tick() + return ledger.Save() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/go.mod b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/go.mod new file mode 100644 index 0000000000..32225aea87 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/go.mod @@ -0,0 +1,3 @@ +module example.com/platform + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/internal/repository/ledger.go b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/internal/repository/ledger.go new file mode 100644 index 0000000000..2b839422ef --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/internal/repository/ledger.go @@ -0,0 +1,5 @@ +package repository + +type Ledger struct{} + +func (s *Ledger) Save() error { return nil } diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/pkg/clock/clock.go b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/pkg/clock/clock.go new file mode 100644 index 0000000000..f7ddd56c42 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/pkg/clock/clock.go @@ -0,0 +1,7 @@ +package clock + +// Clock exists only in the root module, so its import resolves no matter how +// the module root is anchored: the control for the root module's own imports. +type Clock struct{} + +func (c *Clock) Tick() {} diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/cmd/billing/main.go b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/cmd/billing/main.go new file mode 100644 index 0000000000..319656e6f3 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/cmd/billing/main.go @@ -0,0 +1,7 @@ +package main + +import "github.com/acme/ledger/internal/repository" + +func Bill(ledger *repository.Ledger) error { + return ledger.Save() +} diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/go.mod b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/go.mod new file mode 100644 index 0000000000..a2957431ac --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/go.mod @@ -0,0 +1,3 @@ +module github.com/acme/ledger + +go 1.21 diff --git a/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/internal/repository/ledger.go b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/internal/repository/ledger.go new file mode 100644 index 0000000000..9dffa75a81 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/go-root-with-nested-module/services/billing/internal/repository/ledger.go @@ -0,0 +1,7 @@ +package repository + +// A nested module: its own go.mod removes this tree from example.com/platform, +// so the root module's internal/repository never includes this file. +type Ledger struct{} + +func (s *Ledger) Save() error { return nil } diff --git a/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/callers.py b/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/callers.py new file mode 100644 index 0000000000..13ff52ef18 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/callers.py @@ -0,0 +1,42 @@ +import mod +import mod as rp +from mod import Other, untyped + + +def alias_call(): + x = rp.make() + return x.m() + + +def module_call(): + x = mod.make() + return x.m() + + +def inline_alias(): + return rp.make().m() + + +def class_through_alias(): + x = rp.C() + return x.m() + + +def shadowed_namespace(): + rp = Other() + x = rp.make() + return x.m() + + +def untyped_alias(): + x = rp.untyped() + return x.m() + + +def untyped_inline(): + return rp.untyped().m() + + +def untyped_named(): + x = untyped() + return x.m() diff --git a/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/mod.py b/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/mod.py new file mode 100644 index 0000000000..42a73a496d --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/python-module-factory-return/mod.py @@ -0,0 +1,16 @@ +class C: + def m(self): + return 1 + + +class Other: + def m(self): + return 2 + + +def make() -> C: + return C() + + +def untyped(): + return C() diff --git a/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/Page.zig b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/Page.zig new file mode 100644 index 0000000000..ebe99d5f90 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/Page.zig @@ -0,0 +1,11 @@ +const Page = @This(); + +size: u32 = 0, + +pub fn init() Page { + return .{}; +} + +pub fn m(self: Page) u32 { + return self.size; +} diff --git a/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/config.zig b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/config.zig new file mode 100644 index 0000000000..eb882785fa --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/config.zig @@ -0,0 +1,11 @@ +port: u16 = 0, + +const Self = @This(); + +pub fn init() Self { + return .{}; +} + +pub fn listen(self: Self) u16 { + return self.port; +} diff --git a/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/main.zig b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/main.zig new file mode 100644 index 0000000000..88c5f872a8 --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/main.zig @@ -0,0 +1,28 @@ +const rp = @import("mod.zig"); +const Page = @import("Page.zig"); +const page_mod = @import("Page.zig"); +const config = @import("config.zig"); + +pub fn aliasCall() i32 { + const x = rp.make(); + return x.m(); +} + +pub fn inlineCall() i32 { + return rp.make().m(); +} + +pub fn fileStructCall() u32 { + const p = Page.init(); + return p.m(); +} + +pub fn lowercaseFileStructCall() u32 { + const q = page_mod.init(); + return q.m(); +} + +pub fn lowercaseFileStructFileCall() u16 { + const c = config.init(); + return c.listen(); +} diff --git a/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/mod.zig b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/mod.zig new file mode 100644 index 0000000000..96f049a94d --- /dev/null +++ b/gitnexus/test/fixtures/lang-resolution/zig-namespace-factory-return/mod.zig @@ -0,0 +1,17 @@ +pub const C = struct { + pub fn m(self: C) i32 { + _ = self; + return 1; + } +}; + +pub const Other = struct { + pub fn m(self: Other) i32 { + _ = self; + return 2; + } +}; + +pub fn make() C { + return C{}; +} diff --git a/gitnexus/test/fixtures/python-captures-golden/expected-captures.json b/gitnexus/test/fixtures/python-captures-golden/expected-captures.json index 056da33039..71b6dace39 100644 --- a/gitnexus/test/fixtures/python-captures-golden/expected-captures.json +++ b/gitnexus/test/fixtures/python-captures-golden/expected-captures.json @@ -603,6 +603,14 @@ "captureGroups": 13, "digest": "d3032a370833cf67e68672de0ec85b199756f43984488f93a37de81501cac1c1" }, + "python-module-factory-return/callers.py": { + "captureGroups": 54, + "digest": "328eeab94d699fd28279ce150e097f7f260ffc39df741b9371eedb3752d2e34a" + }, + "python-module-factory-return/mod.py": { + "captureGroups": 20, + "digest": "c9fe0b8d85d828d0a07195c07b6a9a521bf64df084893db58fc4d9abbb00794e" + }, "python-module-import/app.py": { "captureGroups": 15, "digest": "29560a379fc78162c760c142019d480ddbdd56e807da5831bc39d2c559136f3e" diff --git a/gitnexus/test/integration/go-import-index-reuse.test.ts b/gitnexus/test/integration/go-import-index-reuse.test.ts index 44cd9dec52..cfd69391d6 100644 --- a/gitnexus/test/integration/go-import-index-reuse.test.ts +++ b/gitnexus/test/integration/go-import-index-reuse.test.ts @@ -26,14 +26,19 @@ import { describe, it, expect } from 'vitest'; import { goScopeResolver } from '../../src/core/ingestion/languages/go/scope-resolver.js'; import { CountingSet, expectDistinctFileSetsGetOwnIndex } from '../helpers/counting-file-set.js'; +import type { GoWorkspaceConfig } from '../../src/core/ingestion/languages/go/workspace-config.js'; // `resolveImportTarget` is a required member of `ScopeResolver`, so this is a // plain read — no optional call, and no `toBeDefined()` guarding a branch that // cannot be taken. const { resolveImportTarget } = goScopeResolver; -/** The value `loadGoModulePath` produces for a repo with a `go.mod`. */ -const GO_MODULE = { modulePath: 'example.com/mod' }; +/** The value `captureGoWorkspaceConfig` produces for a repo whose only + * `go.mod` is at its root. */ +const GO_MODULE: GoWorkspaceConfig = { + modules: [{ modulePath: 'example.com/mod', dir: '' }], + workFiles: [], +}; const FROM_FILE = 'main.go'; diff --git a/gitnexus/test/integration/resolvers/dart.test.ts b/gitnexus/test/integration/resolvers/dart.test.ts index 9f36a33d08..46045b9add 100644 --- a/gitnexus/test/integration/resolvers/dart.test.ts +++ b/gitnexus/test/integration/resolvers/dart.test.ts @@ -13,6 +13,7 @@ import { getRelationships, getNodesByLabel, getNodesByLabelFull, + getResolutionOutcomes, edgeSet, runPipelineFromRepo, type PipelineResult, @@ -149,6 +150,47 @@ describe.skipIf(!dartAvailable)('Dart field-type resolution', () => { }); }); +// ── Prefixed-import factory results (#3498) ───────────────────────────── + +describe.skipIf(!dartAvailable)('Dart prefixed-import factory result types (#3498)', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'dart-prefixed-factory-return'), + () => {}, + ); + }, 60000); + + const methodCalls = (source: string) => + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === 'm') + .map((edge) => edge.rel.targetId); + + it.each(['finalCall', 'varCall', 'inlineCall'])('resolves %s to C.m', (source) => { + expect(methodCalls(source)).toEqual(['Method:lib/mod.dart:C.m#0']); + }); + + // An awaited `Future` is captured like a direct call, but no Dart path + // unwraps the Future of an awaited result yet, named imports included. + it.each(['untypedCall', 'awaitedCall'])('does not guess a receiver type for %s', (source) => { + expect(methodCalls(source)).toEqual([]); + }); + + it('records the untyped and awaited factory results as dropped sites', () => { + expect( + getResolutionOutcomes(result) + .filter((outcome) => outcome.kind === 'suppressed') + .filter( + (outcome) => + outcome.reason === 'receiver-unresolved' && outcome.filePath === 'lib/callers.dart', + ) + .map((outcome) => `${outcome.range.startLine}:${outcome.name}`) + .sort(), + ).toEqual(['17:m', '22:m']); + }); +}); + // ── Phase 9: Call-result binding ──────────────────────────────────────── describe.skipIf(!dartAvailable)('Dart call-result binding', () => { diff --git a/gitnexus/test/integration/resolvers/go.test.ts b/gitnexus/test/integration/resolvers/go.test.ts index 3f5a63c9c3..8047cf730e 100644 --- a/gitnexus/test/integration/resolvers/go.test.ts +++ b/gitnexus/test/integration/resolvers/go.test.ts @@ -1,8 +1,11 @@ /** * Go: package imports + cross-package calls + ambiguous struct disambiguation */ -import { describe, it, expect, beforeAll } from 'vitest'; +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; import path from 'path'; +import fs from 'node:fs'; +import os from 'node:os'; +import { goScopeResolver } from '../../../src/core/ingestion/languages/go/scope-resolver.js'; import { FIXTURES, CROSS_FILE_FIXTURES, @@ -11,6 +14,7 @@ import { getNodesByLabelFull, edgeSet, runPipelineFromRepo, + writeFixtureRepo, type PipelineResult, } from './helpers.js'; @@ -2223,3 +2227,460 @@ describe('Go undecided interface satisfaction', () => { expect(edgeSet(implementsEdges)).toEqual(['Label → Named']); }); }); + +// #3498: `pkg.New().Do()` takes `New`'s return type from the package. Go binds +// receiver methods at package scope too, so a method sharing a function's name +// (`(*WidgetFactory).Create`) must not type `pkg.Create()`. +describe('Go package factory result types in inline chains (#3498)', () => { + let result: PipelineResult; + let repoDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-go-package-factory-')); + writeFixtureRepo(repoDir, { + 'go.mod': 'module example.com/factory\n\ngo 1.21\n', + 'pkg/pkg.go': `package pkg + +type Thing struct{} + +func (t *Thing) Do() int { return 1 } + +func New() *Thing { return &Thing{} } + +type Gadget struct{} + +func (g *Gadget) Spin() {} + +type Widget struct{} + +func (w *Widget) Spin() {} + +func Create() *Gadget { return &Gadget{} } + +type WidgetFactory struct{} + +func (f *WidgetFactory) Create() *Widget { return &Widget{} } +`, + 'main.go': `package main + +import "example.com/factory/pkg" + +func fresh() { +\tpkg.New().Do() +} + +func shadowedByMethod() { +\tpkg.Create().Spin() +} +`, + }); + result = await runPipelineFromRepo(repoDir, () => {}, {}); + }, 60000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + }); + + it.each([ + { source: 'fresh', member: 'Do', targets: ['Method:pkg/pkg.go:Thing.Do#0'] }, + { source: 'shadowedByMethod', member: 'Spin', targets: [] }, + ])('resolves $member called from $source to $targets', ({ source, member, targets }) => { + expect( + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === member) + .map((edge) => edge.rel.targetId), + ).toEqual(targets); + }); +}); + +// --------------------------------------------------------------------------- +// Package-qualified declared types (root cause A of the #3498 corpus triage) +// --------------------------------------------------------------------------- + +describe('Go package-qualified field and parameter types', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'go-qualified-declared-types'), + () => {}, + ); + }, 60000); + + /** Every CALLS target of `caller`, qualified by package dir and file — the + * two `User` types share their method names, so only the file tells which + * one a call bound to. Exact lists, so a wrong target fails the same row a + * missing one does. */ + const targetsOf = (caller: string): string[] => + getRelationships(result, 'CALLS') + .filter((e) => e.source === caller) + .map((e) => `${e.target}@${e.targetFilePath.split('/').slice(-2).join('/')}`) + .sort(); + + // Capture normalizes `models.User` to `User`, and both `models` and `api` + // declare one. Before the qualified spelling was consulted, every qualified + // row lost its member call, and `Forward` bound to its own package's + // `api.User`. The bare same-package row is the control. + it.each([ + ['a value parameter', 'ArchiveByValue', ['Archive@models/user.go']], + ['a pointer parameter', 'ArchiveByPointer', ['Archive@models/user.go']], + ['a parameter through an import alias', 'ArchiveAliased', ['Archive@models/user.go']], + ['a struct field', 'ArchiveMember', ['Archive@models/user.go']], + ['a pointer struct field', 'ArchivePointer', ['Archive@models/user.go']], + ['a struct field of the other package', 'ArchiveRemote', ['Archive@api/user.go']], + ['a field chain off a parameter', 'PurgeInbox', ['Purge@models/user.go']], + ['a declared local variable', 'ArchiveDeclared', ['Archive@models/user.go']], + // The composite literal's own constructor edge already resolved through + // the namespace; only the call on the value it produces did not. + [ + 'a pointer composite literal', + 'ArchiveConstructed', + ['Archive@models/user.go', 'User@models/user.go'], + ], + [ + 'a qualifier naming another package than its own namesake', + 'Forward', + ['Archive@models/user.go'], + ], + ['a bare same-package type', 'ArchiveLocal', ['Archive@api/user.go']], + // A receiver named like its type's package (`vault *vault.Vault`) binds the + // qualifier's own name where the type was written, so the qualifier has to + // be read from the file's imports, not from that scope. + ['a struct field named like its package', 'StowField', ['Stow@vault/vault.go']], + ['a parameter named like its package', 'StowParam', ['Stow@vault/vault.go']], + ['a local named like its package', 'StowLocal', ['Stow@vault/vault.go']], + ])('resolves %s to the type it names (%s)', (_shape, caller, expected) => { + expect(targetsOf(caller)).toEqual(expected); + }); + + it.each([ + ['refuses a bare name two packages declare', 'ArchiveForeign', []], + ['refuses a bare name two packages declare', 'ArchiveForeignField', []], + ['refuses a workspace-unique bare name', 'SpinGadget', []], + ['refuses a workspace-unique bare name', 'SpinGadgetField', []], + ])('behind an unresolved import, %s (%s)', (_behaviour, caller, expected) => { + expect(targetsOf(caller)).toEqual(expected); + }); +}); + +// #3498 review: a declared type's chain step must not hand the qualified lookup +// another binding's spelling. `member models.User` normalizes to `User`, and the +// extractor's chain-follow can land on a sibling field or a package-level +// field named `User`; the binding keeps its own spelling, so it still means +// `models.User` or, when the replaced type no longer matches, resolves nothing. +// A method value (`f := p.Save`) types `p` through the same qualified lookup. +describe('Go qualified declared types through chain steps and method values (#3498)', () => { + let result: PipelineResult; + let repoDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-go-qualified-chain-')); + writeFixtureRepo(repoDir, { + 'go.mod': 'module example.com/chain\n\ngo 1.21\n', + 'models/user.go': `package models + +type User struct{} + +func (u *User) Archive() {} + +func (u *User) Save() {} +`, + 'api/user.go': `package api + +type User struct{} + +func (u *User) Archive() {} +`, + 'api/principal.go': `package api + +type Principal struct{} + +func (p *Principal) Archive() {} +`, + 'auth/principal.go': `package auth + +type Principal struct{} + +func (p *Principal) Archive() {} +`, + 'services/archiver.go': `package services + +import ( +\t"example.com/chain/api" +\t"example.com/chain/models" +) + +type Archiver struct { +\tUser api.User +\tmember models.User +} + +func (a *Archiver) ArchiveMember() { +\ta.member.Archive() +} + +func (a *Archiver) ArchiveUser() { +\ta.User.Archive() +} + +func ArchiveParam(User api.User, member models.User) { +\tmember.Archive() +} +`, + 'held/session.go': `package held + +import "example.com/chain/auth" + +type Session struct { +\tUser *auth.Principal +} +`, + 'held/holder.go': `package held + +import "example.com/chain/models" + +type Holder struct { +\towner *models.User +} + +func (h *Holder) ArchiveHeld() { +\th.owner.Archive() +} +`, + 'values/local.go': `package values + +type User struct{} + +func (u *User) Save() {} +`, + 'values/values.go': `package values + +import "example.com/chain/models" + +func MethodValue(p *models.User) { +\tf := p.Save +\tf() +} + +func Callback(p *models.User) { +\trun(p.Save) +} + +func run(f func()) { +\tf() +} +`, + }); + result = await runPipelineFromRepo(repoDir, () => {}, {}); + }, 60000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + }); + + it.each([ + { + source: 'ArchiveMember', + member: 'Archive', + targets: ['Method:models/user.go:User.Archive#0'], + }, + { + source: 'ArchiveParam', + member: 'Archive', + targets: ['Method:models/user.go:User.Archive#0'], + }, + { source: 'ArchiveUser', member: 'Archive', targets: ['Method:api/user.go:User.Archive#0'] }, + { source: 'ArchiveHeld', member: 'Archive', targets: [] }, + { source: 'MethodValue', member: 'Save', targets: ['Method:models/user.go:User.Save#0'] }, + { source: 'run', member: 'Save', targets: ['Method:models/user.go:User.Save#0'] }, + ])('resolves $member called from $source to $targets', ({ source, member, targets }) => { + expect( + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === member) + .map((edge) => edge.rel.targetId) + .sort(), + ).toEqual(targets); + }); +}); + +// --------------------------------------------------------------------------- +// Several go.mod files in one repository: each import is owned by the module +// whose path is its longest prefix, and names the exact directory under that +// module's root. +// --------------------------------------------------------------------------- + +/** Every IMPORTS edge as `from → to`, repo-relative file paths. */ +const importEdgesOf = (result: PipelineResult): string[] => + getRelationships(result, 'IMPORTS') + .map((e) => `${e.sourceFilePath} → ${e.targetFilePath}`) + .sort(); + +/** Every CALLS target of `caller`, with the file it is declared in. Exact + * lists, so a call bound to the other module's same-named type fails the row + * a missing call does. */ +const callTargetsOf = (result: PipelineResult, caller: string): string[] => + getRelationships(result, 'CALLS') + .filter((e) => e.source === caller) + .map((e) => `${e.target}@${e.targetFilePath}`) + .sort(); + +describe('Go modules whose directories differ from their module paths', () => { + let result: PipelineResult; + let captureCount = 0; + let reloadCount = 0; + + beforeAll(async () => { + const capture = vi.spyOn(goScopeResolver, 'captureResolutionConfig'); + const reload = vi.spyOn(goScopeResolver, 'loadResolutionConfig'); + try { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'go-multi-module-workspace'), + () => {}, + ); + captureCount = capture.mock.calls.length; + reloadCount = reload.mock.calls.length; + } finally { + capture.mockRestore(); + reload.mockRestore(); + } + }, 60000); + + // The manifests come from the scan's own path list: no second directory walk. + it('captures the go.mod files once and never reloads them', () => { + expect(captureCount).toBe(1); + expect(reloadCount).toBe(0); + }); + + // No root go.mod. `orders-service/` and `billing-service/` both hold an + // `internal/repository`, and neither directory is named after its module, so + // the GOPATH suffix match reached `internal/repository` and returned both + // packages for either import. `tools/codegen/` declares + // `example.com/generator/v2`: no tail of that path names a directory at all. + it('resolves every import to a package of the importing module only', () => { + expect(importEdgesOf(result)).toEqual([ + 'billing-service/cmd/billing/main.go → billing-service/internal/repository/ledger.go', + 'orders-service/cmd/orders/main.go → orders-service/internal/repository/ledger.go', + 'tools/codegen/cmd/gen/main.go → tools/codegen/models/template.go', + ]); + }); + + it.each([ + [ + 'PlaceOrder', + [ + 'ReserveStock@orders-service/internal/repository/ledger.go', + 'Save@orders-service/internal/repository/ledger.go', + ], + ], + [ + 'ChargeOrder', + [ + 'ChargeCard@billing-service/internal/repository/ledger.go', + 'Save@billing-service/internal/repository/ledger.go', + ], + ], + ['Generate', ['Render@tools/codegen/models/template.go']], + ])('binds the calls in %s to types of the importing module', (caller, expected) => { + expect(callTargetsOf(result, caller)).toEqual(expected); + }); +}); + +describe('Go root module with a nested module', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo(path.join(FIXTURES, 'go-root-with-nested-module'), () => {}); + }, 60000); + + // `services/billing/go.mod` declares `github.com/acme/ledger`. Reading only + // the root go.mod dropped every import of that module (not owned by + // `example.com/platform`), and matched the root's own `internal/repository` + // against ANY directory ending in it — the nested module's included, though + // its go.mod removes that tree from the root module. `pkg/clock` exists only + // in the root module: the control that resolved either way. + it('anchors each import at its own module root', () => { + expect(importEdgesOf(result)).toEqual([ + 'cmd/server/main.go → internal/repository/ledger.go', + 'cmd/server/main.go → pkg/clock/clock.go', + 'services/billing/cmd/billing/main.go → services/billing/internal/repository/ledger.go', + ]); + }); + + it.each([ + ['Serve', ['Save@internal/repository/ledger.go', 'Tick@pkg/clock/clock.go']], + ['Bill', ['Save@services/billing/internal/repository/ledger.go']], + ])('binds the calls in %s to types of the importing module', (caller, expected) => { + expect(callTargetsOf(result, caller)).toEqual(expected); + }); +}); + +describe.each<[string, Record, string[], string[]]>([ + ['independent sibling modules', {}, [], []], + [ + 'selected workspace modules', + { 'go.work': 'go 1.21\nuse (\n./orders\n./billing\n)\n' }, + ['orders/main.go → billing/repository/ledger.go'], + ['Save@billing/repository/ledger.go'], + ], + ['workspace excludes the importing module', { 'go.work': 'go 1.21\nuse ./billing\n' }, [], []], + [ + 'nearest workspace excludes the sibling', + { + 'go.work': 'go 1.21\nuse (\n./orders\n./billing\n)\n', + 'orders/go.work': 'go 1.21\nuse .\n', + }, + [], + [], + ], +])('Go module visibility: %s', (_scenario, workFiles, expectedImports, expectedCalls) => { + let result: PipelineResult; + let repoDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-go-module-visibility-')); + writeFixtureRepo(repoDir, { + 'orders/go.mod': 'module example.com/orders\n\ngo 1.21\n', + 'billing/go.mod': 'module example.com/billing\n\ngo 1.21\n', + 'orders/main.go': `package main + +import "example.com/billing/repository" + +func PlaceOrder(ledger *repository.Ledger) error { + return ledger.Save() +} + +type Order struct { ledger *repository.Ledger } + +func PlaceOrderField(order *Order) error { + return order.ledger.Save() +} + +func PlaceOrderValue(ledger *repository.Ledger) error { + save := ledger.Save + return save() +} +`, + 'billing/repository/ledger.go': `package repository + +type Ledger struct{} + +func (l *Ledger) Save() error { return nil } +`, + ...workFiles, + }); + result = await runPipelineFromRepo(repoDir, () => {}); + }, 60000); + + afterAll(() => fs.rmSync(repoDir, { recursive: true, force: true })); + + it('only imports selected local providers', () => { + expect(importEdgesOf(result)).toEqual(expectedImports); + }); + + it.each(['PlaceOrder', 'PlaceOrderField', 'PlaceOrderValue'])( + 'only binds %s calls through selected local providers', + (caller) => { + expect(callTargetsOf(result, caller)).toEqual(expectedCalls); + }, + ); +}); diff --git a/gitnexus/test/integration/resolvers/python.test.ts b/gitnexus/test/integration/resolvers/python.test.ts index 08dcc2dea7..f0160b43fe 100644 --- a/gitnexus/test/integration/resolvers/python.test.ts +++ b/gitnexus/test/integration/resolvers/python.test.ts @@ -2537,6 +2537,209 @@ describe('Python nullable assignment result types (#3498)', () => { ); }); +describe('Python module-qualified factory result types (#3498)', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'python-module-factory-return'), + () => {}, + ); + }, 60000); + + const methodCalls = (source: string) => + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === 'm') + .map((edge) => edge.rel.targetId); + + it.each(['alias_call', 'module_call', 'inline_alias', 'class_through_alias'])( + 'resolves %s to C.m', + (source) => { + expect(methodCalls(source)).toEqual(['Method:mod.py:C.m#0']); + }, + ); + + it.each(['shadowed_namespace', 'untyped_alias', 'untyped_inline', 'untyped_named'])( + 'does not guess a receiver type for %s', + (source) => { + expect(methodCalls(source)).toEqual([]); + }, + ); + + 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 === 'callers.py', + ) + .map((outcome) => `${outcome.range.startLine}:${outcome.name}`) + .sort(); + expect(dropped).toEqual(['27:make', '33:m', '37:m', '42:m']); + }); +}); + +// #3498: two shapes where the namespace's module is not the module that owns +// the return annotation. `import pkg.b` binds `pkg` but targets `pkg/b.py`, and +// `-> models.Order` is spelled against the producer's own `models` import, not +// the caller's. Both fail closed (no edge, a recorded drop) instead of +// borrowing the wrong class. +describe('Python namespace factory results that name another module (#3498)', () => { + let result: PipelineResult; + let repoDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-python-namespace-factory-')); + writeFixtureRepo(repoDir, { + 'pkg/__init__.py': `class C1: + def m(self): + return 1 + + +def make() -> C1: + return C1() +`, + 'pkg/b.py': `class C2: + def m(self): + return 2 + + +def make() -> C2: + return C2() +`, + 'callers.py': `import pkg.b + + +def submodule_import(): + x = pkg.make() + return x.m() + + +def submodule_import_inline(): + return pkg.make().m() +`, + 'shop/__init__.py': '', + 'shop/models.py': `class Order: + def save(self): + return 1 +`, + 'shop/service.py': `from . import models + + +def get_order() -> models.Order: + return models.Order() +`, + 'billing/__init__.py': '', + 'billing/models.py': `class Order: + def save(self): + return 2 +`, + 'billing/views.py': `from . import models +import shop.service as svc + + +def producer_spelled_return(): + order = svc.get_order() + return order.save() + + +def local_order(): + order = models.Order() + return order.save() +`, + }); + result = await runPipelineFromRepo(repoDir, () => {}); + }, 60000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + }); + + it.each([ + { source: 'submodule_import', member: 'm', targets: [] }, + { source: 'submodule_import_inline', member: 'm', targets: [] }, + { source: 'producer_spelled_return', member: 'save', targets: [] }, + { + source: 'local_order', + member: 'save', + targets: ['Method:billing/models.py:Order.save#0'], + }, + ])('resolves $member called from $source to $targets', ({ source, member, targets }) => { + expect( + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === member) + .map((edge) => edge.rel.targetId), + ).toEqual(targets); + }); + + it('records the undecided receivers as dropped sites', () => { + const dropped = getResolutionOutcomes(result) + .filter((outcome) => outcome.kind === 'suppressed') + .filter((outcome) => outcome.reason === 'receiver-unresolved') + .map((outcome) => `${outcome.filePath}:${outcome.range.startLine}:${outcome.name}`) + .sort(); + expect(dropped).toEqual(['billing/views.py:7:save', 'callers.py:10:m', 'callers.py:6:m']); + }); +}); + +// #3498: the namespace lookup also runs in Phase 4, after the out-of-core seal +// has made `scopeTree.byId` throw. A partition whose namespace calls are all +// inline warms nothing before the seal, so the lookup must never need that walk. +// The seal is a memory optimization: the edges must match an in-memory run. +describe('Python inline namespace factory under the out-of-core scope seal (#3498)', () => { + let inMemory: PipelineResult; + let sealed: PipelineResult; + let repoDir: string; + let storeDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-python-sealed-factory-')); + storeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-python-sealed-store-')); + writeFixtureRepo(repoDir, { + 'mod.py': `class C: + def m(self): + return 1 + + +def make() -> C: + return C() +`, + 'callers.py': `import mod as rp + + +def inline_alias(): + return rp.make().m() +`, + }); + inMemory = await runPipelineFromRepo(repoDir, () => {}); + const prev = process.env.GITNEXUS_DISK_SCOPE_INDEX; + process.env.GITNEXUS_DISK_SCOPE_INDEX = '1'; + try { + sealed = await runPipelineFromRepo(repoDir, () => {}, { parsedFileStorePath: storeDir }); + } finally { + if (prev === undefined) delete process.env.GITNEXUS_DISK_SCOPE_INDEX; + else process.env.GITNEXUS_DISK_SCOPE_INDEX = prev; + } + }, 120000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + if (storeDir !== undefined) fs.rmSync(storeDir, { recursive: true, force: true }); + }); + + const callEdges = (result: PipelineResult): string[] => + getRelationships(result, 'CALLS') + .map((edge) => `${edge.source} -> ${edge.rel.targetId}`) + .sort(); + + it('resolves the inline call under the seal', () => { + expect(callEdges(sealed)).toContain('inline_alias -> Method:mod.py:C.m#0'); + }); + + it('emits the same CALLS edges as the in-memory run', () => { + expect(callEdges(sealed)).toEqual(callEdges(inMemory)); + }); +}); + // --------------------------------------------------------------------------- // Issue #289: static/classmethod classes must have HAS_METHOD edges // --------------------------------------------------------------------------- diff --git a/gitnexus/test/integration/resolvers/typescript.test.ts b/gitnexus/test/integration/resolvers/typescript.test.ts index 4046165ba6..4b3cadcda5 100644 --- a/gitnexus/test/integration/resolvers/typescript.test.ts +++ b/gitnexus/test/integration/resolvers/typescript.test.ts @@ -3682,3 +3682,97 @@ describe('TypeScript chain-typed receiver folding to an interface (Case 3b, #283 expect(runCalls.map((e) => basename(e.targetFilePath))).toEqual(['plain-cache.ts']); }); }); + +// #3498: `ns.make()` takes `make`'s return annotation from the namespace's +// module. A class method of the same name hoists its return type to the module +// under that name, so the lookup must stay anchored on the module function and +// fail closed instead of typing the receiver as the method's return. +describe('TypeScript namespace factory result types (#3498)', () => { + let result: PipelineResult; + let repoDir: string; + + beforeAll(async () => { + repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-ts-namespace-factory-')); + writeFixtureRepo(repoDir, { + 'src/mod.ts': `export class C { + m(): number { + return 1; + } +} + +export class Other { + m(): number { + return 2; + } +} + +export function make(): C { + return new C(); +} +`, + 'src/hoist.ts': `import { C, Other } from './mod'; + +export function build(): C { + return new C(); +} + +export class Builder { + build(): Other { + return new Other(); + } +} +`, + 'src/callers.ts': `import * as rp from './mod'; +import * as hz from './hoist'; + +export function aliasCall() { + const x = rp.make(); + return x.m(); +} + +export function inlineCall() { + return rp.make().m(); +} + +export function hoistedCall() { + const y = hz.build(); + return y.m(); +} + +export function hoistedInline() { + return hz.build().m(); +} +`, + }); + result = await runPipelineFromRepo(repoDir, () => {}, {}); + }, 60000); + + afterAll(() => { + if (repoDir !== undefined) fs.rmSync(repoDir, { recursive: true, force: true }); + }); + + it.each([ + { source: 'aliasCall', targets: ['Method:src/mod.ts:C.m#0'] }, + { source: 'inlineCall', targets: ['Method:src/mod.ts:C.m#0'] }, + { source: 'hoistedCall', targets: [] }, + { source: 'hoistedInline', targets: [] }, + ])('resolves m called from $source to $targets', ({ source, targets }) => { + expect( + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === 'm') + .map((edge) => edge.rel.targetId), + ).toEqual(targets); + }); + + it('records the hoisted sites as dropped instead of an exact miss', () => { + const dropped = getResolutionOutcomes(result) + .filter((outcome) => outcome.kind === 'suppressed') + .filter( + (outcome) => + outcome.reason === 'receiver-unresolved' && outcome.filePath === 'src/callers.ts', + ) + .map((outcome) => `${outcome.range.startLine}:${outcome.name}`) + .sort(); + expect(dropped).toEqual(['15:m', '19:m']); + }); +}); diff --git a/gitnexus/test/integration/resolvers/zig.test.ts b/gitnexus/test/integration/resolvers/zig.test.ts index ffdd227501..84f6027aff 100644 --- a/gitnexus/test/integration/resolvers/zig.test.ts +++ b/gitnexus/test/integration/resolvers/zig.test.ts @@ -1590,3 +1590,36 @@ describe.skipIf(!zigAvailable)('Zig monorepo package resolution', () => { expect(fromTool.map((e) => e.targetFilePath).join('\n')).not.toContain('packages/core/'); }); }); + +// #3498: an inline `rp.make().m()` on a namespace module takes `make`'s return +// type; file-struct handles, including a lowercase file with fields, keep +// naming the struct. A bound `const x = rp.make()` is not typed yet: the +// importing file cannot see whether the target is a namespace or a struct. +describe.skipIf(!zigAvailable)('Zig namespace factory result types (#3498)', () => { + let result: PipelineResult; + + beforeAll(async () => { + result = await runPipelineFromRepo( + path.join(FIXTURES, 'zig-namespace-factory-return'), + () => {}, + ); + }, 60000); + + it.each([ + { source: 'aliasCall', member: 'm', targets: [] }, + { source: 'inlineCall', member: 'm', targets: ['Method:mod.zig:C.m#0'] }, + { source: 'fileStructCall', member: 'm', targets: ['Method:Page.zig:Page.m#0'] }, + { source: 'lowercaseFileStructCall', member: 'm', targets: ['Method:Page.zig:Page.m#0'] }, + { + source: 'lowercaseFileStructFileCall', + member: 'listen', + targets: ['Method:config.zig:config.listen#0'], + }, + ])('resolves $member called from $source to $targets', ({ source, member, targets }) => { + expect( + getRelationships(result, 'CALLS') + .filter((edge) => edge.source === source && edge.target === member) + .map((edge) => edge.rel.targetId), + ).toEqual(targets); + }); +}); diff --git a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts index 2394a44d94..bf2d0e6534 100644 --- a/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts +++ b/gitnexus/test/unit/import-resolvers/go-package-resolve.test.ts @@ -27,7 +27,10 @@ import { resolveGoPackageDir, } from '../../../src/core/ingestion/import-resolvers/go.js'; import type { GoModuleConfig } from '../../../src/core/ingestion/language-config.js'; -import { resolveGoImportTarget } from '../../../src/core/ingestion/languages/go/import-target.js'; +import { + buildPackageDirIndex, + filesDirectlyInPkgDir, +} from '../../../src/core/ingestion/import-resolvers/package-dir-index.js'; const MOD: GoModuleConfig = { modulePath: 'example.com/mod' }; @@ -36,14 +39,19 @@ function resolve(files: readonly string[], importPath: string): string[] { return resolveGoPackage(importPath, MOD, normalized, files); } -/** The indexed leg, for the agreement arm. */ +/** + * 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 got = resolveGoImportTarget(importPath, 'main.go', new Set(files), MOD); - // `typeof got === 'string'`, not `Array.isArray(got)`: `Array.isArray` narrows - // to `any[]`, which does not subsume `readonly string[]`, so the false branch - // kept the array member and `[got]` did not typecheck (TS2322 under - // `tsconfig.test.json`). Runtime behaviour is identical. - return got === null ? [] : typeof got === 'string' ? [got] : got; + 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', () => { @@ -140,11 +148,10 @@ describe('resolveGoPackage', () => { ]); }); - it('agrees with the indexed leg on the repeated-name shapes', () => { - // The two legs are independent implementations of one rule. Before #2881 - // they agreed on the wrong answer; they must agree on the right one, or - // Go's LanguageProvider and ScopeResolver hooks disagree about which files - // a package holds. + 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'], diff --git a/gitnexus/test/unit/install-duckdb-extension.test.ts b/gitnexus/test/unit/install-duckdb-extension.test.ts index 3082b29438..c5d296462f 100644 --- a/gitnexus/test/unit/install-duckdb-extension.test.ts +++ b/gitnexus/test/unit/install-duckdb-extension.test.ts @@ -6,6 +6,9 @@ import { } from '../../scripts/install-duckdb-extension.mjs'; import { FILE_CORRUPTION_SIGNATURES as classifierSignatures } from '../../src/core/lbug/extension-load-error.js'; +const { resolveVendoredFtsPath } = vi.hoisted(() => ({ resolveVendoredFtsPath: vi.fn() })); +vi.mock('../../dist/core/lbug/vendored-extension-path.js', () => ({ resolveVendoredFtsPath })); + /** * Offline, network-free regression guard for the install-verb decision (#2374, * PR #2375). A revert to unconditional INSTALL or unconditional FORCE INSTALL @@ -81,6 +84,47 @@ describe('installDuckDbExtension issues the chosen SQL (#2374)', () => { ); expect(connect).not.toHaveBeenCalled(); }); + + it('verifies the bundled FTS by path without downloading a mutable CDN artifact', async () => { + resolveVendoredFtsPath.mockReturnValue("/app/owner's copy/libfts.lbug_extension"); + const factory = recordingConnect(); + await installDuckDbExtension('fts', { verifyBundled: true, connect: () => factory }); + expect(factory.conn.query.mock.calls).toEqual([ + ["LOAD EXTENSION '/app/owner''s copy/libfts.lbug_extension'"], + ]); + }); + + it('fails before connecting when the bundled FTS artifact is missing', async () => { + resolveVendoredFtsPath.mockReturnValue(null); + const connect = vi.fn(); + await expect(installDuckDbExtension('fts', { verifyBundled: true, connect })).rejects.toThrow( + /No packaged FTS artifact/, + ); + expect(connect).not.toHaveBeenCalled(); + }); + + it('rejects bundled verification for extensions that are not packaged', async () => { + const connect = vi.fn(); + await expect( + installDuckDbExtension('vector', { verifyBundled: true, connect }), + ).rejects.toThrow(/Bundled verification only supports fts/); + expect(connect).not.toHaveBeenCalled(); + }); + + it('propagates a bundled ABI mismatch and closes the scratch connection', async () => { + resolveVendoredFtsPath.mockReturnValue('/app/libfts.lbug_extension'); + const factory = recordingConnect(); + factory.conn.query.mockRejectedValue(new Error('undefined symbol: ValueVector::setAllNull')); + const dispose = vi.fn(async () => undefined); + await expect( + installDuckDbExtension('fts', { + verifyBundled: true, + connect: () => ({ ...factory, dispose }), + }), + ).rejects.toThrow(/undefined symbol/); + expect(factory.conn.query).toHaveBeenCalledTimes(1); + expect(dispose).toHaveBeenCalledOnce(); + }); }); describe('FILE_CORRUPTION_SIGNATURES parity (#2383 F5b)', () => { diff --git a/gitnexus/test/unit/publish-rc-version.test.ts b/gitnexus/test/unit/publish-rc-version.test.ts new file mode 100644 index 0000000000..3de9d9a163 --- /dev/null +++ b/gitnexus/test/unit/publish-rc-version.test.ts @@ -0,0 +1,138 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { load } from 'js-yaml'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const workflow = load( + readFileSync(path.resolve(__dirname, '../../../.github/workflows/publish.yml'), 'utf8'), +) as { jobs: { publish: { steps: { id?: string; run?: string }[] } } }; +const versionStep = workflow.jobs.publish.steps.find((step) => step.id === 'rc-version'); +if (!versionStep?.run) throw new Error('Missing RC version resolver'); +const script = versionStep.run; + +// Execute the workflow's actual resolver against real Git tags, with npm +// metadata held behind a completed publish as in run 39472555350. +describe.skipIf(process.platform === 'win32')('publish.yml RC version allocation', () => { + let dir: string; + + beforeEach(() => { + dir = mkdtempSync(path.join(os.tmpdir(), 'gitnexus-rc-version-')); + execFileSync('git', ['init', '--quiet', dir]); + execFileSync( + 'git', + [ + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.com', + '-c', + 'commit.gpgsign=false', + 'commit', + '--quiet', + '--allow-empty', + '-m', + 'fixture', + ], + { cwd: dir }, + ); + }); + + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + function resolve(versions: string[] | string, tags: string[], existingVersion = '') { + for (const tag of tags) execFileSync('git', ['tag', tag], { cwd: dir }); + return spawnSync( + 'bash', + [ + '-c', + ` + npm() { + case "$*" in + "view gitnexus version") echo '1.6.12' ;; + "view gitnexus versions --json") printf '%s' "$MOCK_VERSIONS" ;; + "view gitnexus@$MOCK_EXISTING_VERSION version") echo "$MOCK_EXISTING_VERSION" ;; + "view gitnexus@"*" version") echo 'E404 not found' >&2; return 1 ;; + *) echo "Unexpected npm invocation: $*" >&2; return 2 ;; + esac + } + npx() { + if [ "$*" = "--yes -p semver@7 semver -i patch 1.6.12" ]; then + echo '1.6.13' + else + echo "Unexpected npx invocation: $*" >&2; return 2 + fi + } + ${script.replaceAll('/tmp/', `${dir}/`)} + `, + ], + { + cwd: dir, + encoding: 'utf8', + timeout: 10_000, + env: { + ...process.env, + EVENT_NAME: 'push', + BUMP_INPUT: '', + PKG_NAME: 'gitnexus', + GITHUB_OUTPUT: path.join(dir, 'output'), + MOCK_VERSIONS: JSON.stringify(versions), + MOCK_EXISTING_VERSION: existingVersion, + }, + }, + ); + } + + it.each([ + { + name: 'skips an existing tag while npm is still processing its publication', + versions: ['1.6.13-rc.135'], + tags: ['v1.6.13-rc.136'], + next: 137, + }, + { + name: 'uses the highest reserved tag across multiple pending publications', + versions: ['1.6.13-rc.135'], + tags: ['v1.6.13-rc.136', 'v1.6.13-rc.138'], + next: 139, + }, + { + name: 'keeps npm as the floor when the registry is ahead of Git tags', + versions: ['1.6.13-rc.139'], + tags: ['v1.6.13-rc.136'], + next: 140, + }, + { + name: 'handles a single version returned by npm', + versions: '1.6.13-rc.135', + tags: [], + next: 136, + }, + { + name: 'starts at rc.1 when neither source reserves the selected base', + versions: [], + tags: ['v1.6.12-rc.999', 'v1.7.0-rc.999', 'v1.6.13-beta.999'], + next: 1, + }, + { + name: 'ignores tags with a nonnumeric RC suffix', + versions: ['1.6.13-rc.135'], + tags: ['v1.6.13-rc.999-extra', 'v1.6.13-rc.999.1'], + next: 136, + }, + ])('$name', ({ versions, tags, next }) => { + const result = resolve(versions, tags); + expect(result.status, result.stderr).toBe(0); + const version = `1.6.13-rc.${next}`; + expect(readFileSync(path.join(dir, 'output'), 'utf8')).toContain(`rc_version=${version}\n`); + // The allocated name must be available to the following tag-creation step. + execFileSync('git', ['tag', `v${version}`], { cwd: dir }); + }); + + it('still aborts when the allocated version appears in npm before publication', () => { + const result = resolve(['1.6.13-rc.135'], ['v1.6.13-rc.136'], '1.6.13-rc.137'); + expect(result.status).toBe(1); + expect(result.stdout).toContain('Version 1.6.13-rc.137 already exists on npm'); + }); +}); diff --git a/gitnexus/test/unit/repo-projection.test.ts b/gitnexus/test/unit/repo-projection.test.ts index cc8191e973..e58f27d8d9 100644 --- a/gitnexus/test/unit/repo-projection.test.ts +++ b/gitnexus/test/unit/repo-projection.test.ts @@ -29,7 +29,7 @@ const FRESH: StalenessInfo = { isStale: false, commitsBehind: 0 }; const BEHIND: StalenessInfo = { isStale: true, commitsBehind: 3, - hint: '⚠️ Index is 3 commits behind HEAD. Run analyze tool to update.', + hint: '⚠️ Index is 3 commits behind HEAD. Run the CLI command `npx gitnexus analyze` from the repository directory to update.', }; const meta = (over: Partial = {}): RepoMeta => 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 672ef35a90..690ef291d7 100644 --- a/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts +++ b/gitnexus/test/unit/scope-resolution/external-import-conformance.test.ts @@ -48,11 +48,16 @@ import { clearKotlinPackageFacts, setKotlinPackageFact, } from '../../../src/core/ingestion/languages/kotlin/package-facts.js'; +import type { GoWorkspaceConfig } from '../../../src/core/ingestion/languages/go/workspace-config.js'; /** The `composer.json` PSR-4 map `loadPhpComposerConfig` would have produced. */ const PHP_COMPOSER: ComposerConfig = { psr4: new Map([['App', 'app']]) }; -/** The value `loadGoModulePath` produces for a repo with a `go.mod`. */ -const GO_MODULE = { modulePath: 'example.com/mod' }; +/** The value `captureGoWorkspaceConfig` produces for a repo whose only + * `go.mod` is at its root. */ +const GO_MODULE: GoWorkspaceConfig = { + modules: [{ modulePath: 'example.com/mod', dir: '' }], + workFiles: [], +}; /** The root dependency scope `loadRubyResolutionConfig` would have produced. */ const RUBY_GEMS = { scopesByDirectory: new Map([ diff --git a/gitnexus/test/unit/scope-resolution/go/go-imports.test.ts b/gitnexus/test/unit/scope-resolution/go/go-imports.test.ts index 6cbbea6d3d..84ca7cd313 100644 --- a/gitnexus/test/unit/scope-resolution/go/go-imports.test.ts +++ b/gitnexus/test/unit/scope-resolution/go/go-imports.test.ts @@ -7,6 +7,7 @@ import { import { getGoParser } from '../../../../src/core/ingestion/languages/go/query.js'; import type { CaptureMatch } from 'gitnexus-shared'; import { resolveGoImportBinding } from '../../../../src/core/ingestion/languages/go/import-binding.js'; +import type { GoWorkspaceConfig } from '../../../../src/core/ingestion/languages/go/workspace-config.js'; function parseThenSplit(src: string): CaptureMatch[] { const tree = getGoParser().parse(src); @@ -162,13 +163,18 @@ describe('Go import binding names', () => { }); }); +/** The config a repository whose only go.mod sits at its root captures. */ +function rootModule(modulePath: string): GoWorkspaceConfig { + return { modules: [{ modulePath, dir: '' }], workFiles: [] }; +} + describe('Go import target resolution', () => { it('resolves module root imports to root package files', () => { const result = resolveGoImportTarget( 'example.com/lib', 'cmd/app/main.go', new Set(['root.go', 'extra.go', 'internal/model/model.go', 'root_test.go']), - { modulePath: 'example.com/lib' }, + rootModule('example.com/lib'), ); expect(result).toEqual(['extra.go', 'root.go']); @@ -179,7 +185,7 @@ describe('Go import target resolution', () => { 'example.com/lib/internal/models', 'cmd/app/main.go', new Set(['internal/models/user.go', 'internal/models/repo.go', 'root.go']), - { modulePath: 'example.com/lib' }, + rootModule('example.com/lib'), ); expect(Array.isArray(result)).toBe(true); @@ -196,7 +202,7 @@ describe('Go import target resolution', () => { targetRaw, 'main.go', new Set(['internal/models/user.go', 'main.go']), - { modulePath: 'example.com/mod' }, + rootModule('example.com/mod'), ); expect(result).toBeNull(); @@ -208,7 +214,7 @@ describe('Go import target resolution', () => { 'example.com/mod/v2/internal/models', 'cmd/app/main.go', new Set(['internal/models/user.go']), - { modulePath: 'example.com/mod/v2' }, + rootModule('example.com/mod/v2'), ); expect(result).toEqual(['internal/models/user.go']); @@ -240,3 +246,127 @@ describe('Go import target resolution', () => { expect(result as string[]).toEqual(['team/pkg/util.go']); }); }); + +describe('Go import target resolution across several go.mod files', () => { + /** No root module; neither service directory is named after its module. */ + const SERVICES: GoWorkspaceConfig = { + modules: [ + { modulePath: 'github.com/acme/billing', dir: 'billing-service' }, + { modulePath: 'github.com/acme/orders', dir: 'orders-service' }, + ], + workFiles: [], + }; + /** A root module and a nested one whose tree it must not include. */ + const ROOT_AND_TOOLS: GoWorkspaceConfig = { + modules: [ + { modulePath: 'example.com/app', dir: '' }, + { modulePath: 'example.com/tools', dir: 'tools' }, + ], + workFiles: [], + }; + const SERVICE_FILES = [ + 'orders-service/internal/repository/store.go', + 'orders-service/cmd/main.go', + 'billing-service/internal/repository/store.go', + 'scripts/internal/repository/legacy.go', + ]; + const ROOT_FILES = [ + 'main.go', + 'internal/models/user.go', + 'tools/internal/models/gen.go', + 'tools/main.go', + ]; + + it.each<[string, GoWorkspaceConfig, readonly string[], string, string, string[] | null]>([ + [ + "the owning module's directory, not every directory with that tail", + SERVICES, + SERVICE_FILES, + 'github.com/acme/orders/internal/repository', + 'orders-service/cmd/main.go', + ['orders-service/internal/repository/store.go'], + ], + [ + 'nothing for an unselected sibling module', + SERVICES, + SERVICE_FILES, + 'github.com/acme/billing/internal/repository', + 'orders-service/cmd/main.go', + null, + ], + [ + "a selected workspace module's public package", + { ...SERVICES, workFiles: [{ dir: '', use: ['orders-service', 'billing-service'] }] }, + ['billing-service/pkg/repository/store.go', 'orders-service/cmd/main.go'], + 'github.com/acme/billing/pkg/repository', + 'orders-service/cmd/main.go', + ['billing-service/pkg/repository/store.go'], + ], + [ + 'nothing for a dependency that shares the tail', + SERVICES, + SERVICE_FILES, + 'github.com/vendor/dep/internal/repository', + 'orders-service/cmd/main.go', + null, + ], + [ + 'the GOPATH match for an importer outside every module', + SERVICES, + SERVICE_FILES, + 'github.com/vendor/scripts/internal/repository', + 'scripts/main.go', + ['scripts/internal/repository/legacy.go'], + ], + [ + "the root module's own directory only", + ROOT_AND_TOOLS, + ROOT_FILES, + 'example.com/app/internal/models', + 'main.go', + ['internal/models/user.go'], + ], + [ + "nothing inside the nested module for the root module's path", + ROOT_AND_TOOLS, + ROOT_FILES, + 'example.com/app/tools/internal/models', + 'main.go', + null, + ], + [ + "a selected nested module's root package", + { ...ROOT_AND_TOOLS, workFiles: [{ dir: '', use: ['', 'tools'] }] }, + ROOT_FILES, + 'example.com/tools', + 'main.go', + ['tools/main.go'], + ], + ])('resolves to %s', (_case, config, files, targetRaw, fromFile, expected) => { + expect(resolveGoImportTarget(targetRaw, fromFile, new Set(files), config)).toEqual(expected); + }); + + it.each<[string, string[], string[] | null]>([ + ['the shorter module alone', ['parent/b/pkg/item.go'], ['parent/b/pkg/item.go']], + ['the longer module alone', ['child/pkg/item.go'], ['child/pkg/item.go']], + ['both modules', ['parent/b/pkg/item.go', 'child/pkg/item.go'], null], + ['neither module', [], null], + ])('requires a unique provider with the package in %s', (_case, files, expected) => { + const config: GoWorkspaceConfig = { + modules: [ + { modulePath: 'example.com/a', dir: 'parent' }, + { modulePath: 'example.com/a/b', dir: 'child' }, + ], + workFiles: [{ dir: '', use: ['parent', 'child'] }], + }; + + expect( + resolveGoImportTarget( + 'example.com/a/b/pkg', + 'parent/main.go', + new Set(['parent/main.go', ...files]), + config, + ), + ).toEqual(expected); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/go/go-type-binding.test.ts b/gitnexus/test/unit/scope-resolution/go/go-type-binding.test.ts index 823fb77b77..a9daf99134 100644 --- a/gitnexus/test/unit/scope-resolution/go/go-type-binding.test.ts +++ b/gitnexus/test/unit/scope-resolution/go/go-type-binding.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import type { TypeRef } from 'gitnexus-shared'; import { synthesizeGoReceiverBinding, synthesizeGoTypeBindings, @@ -7,6 +8,7 @@ import { normalizeGoTypeName, } from '../../../../src/core/ingestion/languages/go/index.js'; import { getGoParser } from '../../../../src/core/ingestion/languages/go/query.js'; +import { goQualifiedTypeLookupSpelling } from '../../../../src/core/ingestion/languages/go/interpret.js'; describe('Go receiver binding', () => { it('synthesizes receiver type binding for method', () => { @@ -287,3 +289,62 @@ func main() { u := User{Base: Base{ID: 1}} }`; expect(Array.isArray(matches)).toBe(true); }); }); + +describe('goQualifiedTypeLookupSpelling', () => { + /** A field or parameter TypeRef as the scope extractor builds one: the + * written type kept as `declaredSpelling`, `rawName` normalized from it. */ + const writtenAs = (written: string): TypeRef => ({ + rawName: normalizeGoTypeName(written), + declaredSpelling: written, + declaredAtScope: 'scope:test', + source: 'parameter-annotation', + }); + + it.each<[string, string | undefined]>([ + ['models.User', 'models.User'], + ['*models.User', 'models.User'], + ['[]*models.User', 'models.User'], + ['map[string]*models.User', 'models.User'], + ['chan models.User', 'models.User'], + ['func() *models.User', 'models.User'], + ['models.Box[int]', 'models.Box'], + ['[4]models.User', 'models.User'], + ['*User', undefined], + ['[]User', undefined], + ['interface{ Save() }', undefined], + ['a.b.User', undefined], + ])('recovers the qualified name written as %s', (written, expected) => { + expect(goQualifiedTypeLookupSpelling(writtenAs(written))).toBe(expected); + }); + + // A return type keeps its qualifier in `rawName`, and a TypeRef with no + // written spelling had nothing normalized away. + it.each<[string, TypeRef]>([ + [ + 'a return type', + { + rawName: 'models.User', + declaredSpelling: '*models.User', + declaredAtScope: 'scope:test', + source: 'return-annotation', + }, + ], + [ + 'no written spelling', + { rawName: 'User', declaredAtScope: 'scope:test', source: 'parameter-annotation' }, + ], + // A chain step replaced the type (`u *models.User` landed on a package-level + // `User *auth.Principal`) but kept the binding's own spelling. + [ + 'a spelling that does not qualify rawName', + { + rawName: 'Principal', + declaredSpelling: '*models.User', + declaredAtScope: 'scope:test', + source: 'parameter-annotation', + }, + ], + ])('declines %s', (_label, typeRef) => { + expect(goQualifiedTypeLookupSpelling(typeRef)).toBeUndefined(); + }); +}); diff --git a/gitnexus/test/unit/scope-resolution/go/go-workspace-config.test.ts b/gitnexus/test/unit/scope-resolution/go/go-workspace-config.test.ts new file mode 100644 index 0000000000..0f35686bb1 --- /dev/null +++ b/gitnexus/test/unit/scope-resolution/go/go-workspace-config.test.ts @@ -0,0 +1,354 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + captureGoWorkspaceConfig, + loadGoWorkspaceConfig, + locateGoImport, + parseGoModulePath, + parseGoWorkUses, + type GoImportLocation, + type GoWorkspaceConfig, +} from '../../../../src/core/ingestion/languages/go/workspace-config.js'; + +const temporary: string[] = []; +afterEach(() => { + for (const dir of temporary.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); + vi.unstubAllEnvs(); +}); +function fixture(files: Readonly>): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-go-workspace-')); + temporary.push(dir); + for (const [file, content] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); + fs.writeFileSync(path.join(dir, file), content); + } + return dir; +} + +describe('parseGoModulePath', () => { + it.each([ + ['a plain directive', 'module example.com/app\n\ngo 1.21\n', 'example.com/app'], + [ + 'a trailing comment', + '// header\nmodule github.com/acme/orders/v2 // Deprecated: use v3\n', + 'github.com/acme/orders/v2', + ], + ['a double-quoted path', 'module "example.com/quoted"\n', 'example.com/quoted'], + ['a raw-quoted path and CRLF', 'module `example.com/raw`\r\ngo 1.21\r\n', 'example.com/raw'], + ['no module directive', 'go 1.21\nrequire example.com/dep v1.0.0\n', null], + ['a commented-out directive', '// module example.com/commented\n', null], + ['an empty file', '', null], + ])('reads %s', (_shape, goMod, expected) => { + expect(parseGoModulePath(goMod)).toBe(expected); + }); +}); + +describe('parseGoWorkUses', () => { + it.each([ + ['a single directive', 'go 1.22\n\nuse ./api\n', ['./api']], + [ + 'a block with comments and quotes', + 'use (\n\t./api\n\t./web // frontend\n\t"./my tools"\n)\n', + ['./api', './web', './my tools'], + ], + ['the root and an escaping path, as written', 'use .\nuse ../outside\n', ['.', '../outside']], + ['a commented-out directive', 'go 1.22\n// use ./ignored\n', []], + ])('reads %s', (_shape, goWork, expected) => { + expect(parseGoWorkUses(goWork)).toEqual(expected); + }); +}); + +/** Two services whose directories are named unlike their modules, and a major- + * version module in a directory that names neither its path nor its suffix. */ +const MONOREPO: GoWorkspaceConfig = { + modules: [ + { modulePath: 'github.com/acme/billing', dir: 'billing-service' }, + { modulePath: 'github.com/acme/orders', dir: 'orders-service' }, + { modulePath: 'example.com/generator/v2', dir: 'tools/codegen' }, + ], + workFiles: [], +}; + +/** A root module, a nested module with an unrelated path, and a nested module + * whose path extends the root's. */ +const ROOT_AND_NESTED: GoWorkspaceConfig = { + modules: [ + { modulePath: 'example.com/platform', dir: '' }, + { modulePath: 'github.com/acme/ledger', dir: 'services/billing' }, + { modulePath: 'example.com/platform/tools', dir: 'tools' }, + ], + workFiles: [], +}; + +/** Two `go.mod` files declaring one path (copied examples, test data). */ +const DUPLICATE_MODULES = [ + { modulePath: 'example.com/app', dir: 'a' }, + { modulePath: 'example.com/app', dir: 'b' }, + { modulePath: 'example.com/consumer', dir: 'c' }, +]; +const DUPLICATES_WITH_WORK: GoWorkspaceConfig = { + modules: DUPLICATE_MODULES, + workFiles: [{ dir: '', use: ['a', 'c'] }], +}; +const DUPLICATES_WITHOUT_WORK: GoWorkspaceConfig = { modules: DUPLICATE_MODULES, workFiles: [] }; + +const moduleDirs = (dirs: readonly string[]): GoImportLocation => ({ kind: 'module', dirs }); + +describe('locateGoImport', () => { + it.each<[string, GoWorkspaceConfig, string, string, GoImportLocation]>([ + [ + 'the module owning the path, not the directory name', + MONOREPO, + 'github.com/acme/orders/internal/repository', + 'orders-service/cmd/orders/main.go', + moduleDirs(['orders-service/internal/repository']), + ], + [ + 'no unselected sibling module, even with a unique path', + MONOREPO, + 'github.com/acme/billing/internal/repository', + 'orders-service/cmd/orders/main.go', + moduleDirs([]), + ], + [ + 'a sibling selected by go.work', + { ...MONOREPO, workFiles: [{ dir: '', use: ['orders-service', 'billing-service'] }] }, + 'github.com/acme/billing/pkg/repository', + 'orders-service/cmd/orders/main.go', + moduleDirs(['billing-service/pkg/repository']), + ], + [ + 'no sibling selected by a workspace that excludes the importer', + { ...MONOREPO, workFiles: [{ dir: '', use: ['billing-service'] }] }, + 'github.com/acme/billing/pkg/repository', + 'orders-service/cmd/orders/main.go', + moduleDirs([]), + ], + [ + 'only the nearest workspace, not an outer workspace', + { + ...MONOREPO, + workFiles: [ + { dir: '', use: ['orders-service', 'billing-service'] }, + { dir: 'orders-service', use: ['orders-service'] }, + ], + }, + 'github.com/acme/billing/pkg/repository', + 'orders-service/cmd/orders/main.go', + moduleDirs([]), + ], + [ + 'a major-version module in an unrelated directory', + MONOREPO, + 'example.com/generator/v2/models', + 'tools/codegen/cmd/gen/main.go', + moduleDirs(['tools/codegen/models']), + ], + [ + 'a nested module root package', + MONOREPO, + 'example.com/generator/v2', + 'tools/codegen/cmd/gen/main.go', + moduleDirs(['tools/codegen']), + ], + [ + 'a Windows-separated importer', + MONOREPO, + 'github.com/acme/orders/internal/repository', + 'orders-service\\cmd\\orders\\main.go', + moduleDirs(['orders-service/internal/repository']), + ], + [ + 'no unselected module from outside every module', + MONOREPO, + 'github.com/acme/orders/internal/repository', + 'scripts/main.go', + moduleDirs([]), + ], + [ + 'the standard library from inside a module', + MONOREPO, + 'fmt', + 'orders-service/cmd/orders/main.go', + { kind: 'external' }, + ], + [ + 'a dependency sharing an in-repo path tail', + MONOREPO, + 'github.com/other/billing/internal/repository', + 'orders-service/cmd/orders/main.go', + { kind: 'external' }, + ], + [ + 'a module path that only shares characters, not a segment', + MONOREPO, + 'github.com/acme/orders-api/client', + 'orders-service/cmd/orders/main.go', + { kind: 'external' }, + ], + [ + 'an unowned path from outside every module', + MONOREPO, + 'github.com/other/lib/util', + 'scripts/main.go', + { kind: 'gopath' }, + ], + [ + "the root module's own package", + ROOT_AND_NESTED, + 'example.com/platform/internal/repository', + 'cmd/server/main.go', + moduleDirs(['internal/repository']), + ], + [ + 'no root module package from an independent nested module', + ROOT_AND_NESTED, + 'example.com/platform', + 'services/billing/cmd/billing/main.go', + moduleDirs([]), + ], + [ + 'the longest selected workspace module path', + { ...ROOT_AND_NESTED, workFiles: [{ dir: '', use: ['', 'tools'] }] }, + 'example.com/platform/tools/lint', + 'cmd/server/main.go', + moduleDirs(['tools/lint']), + ], + [ + 'no directory of the root module inside a nested module', + ROOT_AND_NESTED, + 'example.com/platform/services/billing/internal/repository', + 'cmd/server/main.go', + moduleDirs([]), + ], + [ + "a nested module's own package", + ROOT_AND_NESTED, + 'github.com/acme/ledger/internal/repository', + 'services/billing/cmd/billing/main.go', + moduleDirs(['services/billing/internal/repository']), + ], + [ + "the importer's own module among duplicates", + DUPLICATES_WITH_WORK, + 'example.com/app/models', + 'b/main.go', + moduleDirs(['b/models']), + ], + [ + 'the go.work module among duplicates', + DUPLICATES_WITH_WORK, + 'example.com/app/models', + 'c/main.go', + moduleDirs(['a/models']), + ], + [ + 'nothing among duplicates without a go.work', + DUPLICATES_WITHOUT_WORK, + 'example.com/app/models', + 'c/main.go', + moduleDirs([]), + ], + ])('selects %s', (_case, config, importPath, fromFile, expected) => { + expect(locateGoImport(config, importPath, fromFile)).toEqual(expected); + }); +}); + +describe('captureGoWorkspaceConfig', () => { + const NESTED = { + 'go.mod': 'module example.com/root\n', + 'svc/go.mod': 'module example.com/svc\n', + 'svc/main.go': 'package main\n', + // Declares no module: not a module root, the files stay the root's. + 'broken/go.mod': 'go 1.21\n', + 'go.work': 'use (\n\t./svc\n\t../outside\n\t/abs\n\t.\n)\n', + }; + + it.each<[string, Readonly>, GoWorkspaceConfig | null]>([ + [ + 'every go.mod and go.work, sorted, with in-repo uses only', + NESTED, + { + modules: [ + { modulePath: 'example.com/root', dir: '' }, + { modulePath: 'example.com/svc', dir: 'svc' }, + ], + workFiles: [{ dir: '', use: ['', 'svc'] }], + }, + ], + ['nothing when no go.mod declares a module', { 'main.go': 'package main\n' }, null], + ])('captures %s', async (_case, files, expected) => { + const dir = fixture(files); + // Reversed: the result must not depend on listing order. + const paths = Object.keys(files).reverse(); + expect(await captureGoWorkspaceConfig(dir, paths)).toEqual(expected); + }); + + it('loads the same config standalone as analyze captures from the scan', async () => { + const dir = fixture(NESTED); + expect(await loadGoWorkspaceConfig(dir)).toEqual( + await captureGoWorkspaceConfig(dir, Object.keys(NESTED)), + ); + }); + + // Manifests capture deliberately skips: each case lists `svc/go.mod` but + // leaves it unreadable as a manifest, so only the root module is captured. + const ROOT_ONLY: GoWorkspaceConfig = { + modules: [{ modulePath: 'example.com/root', dir: '' }], + workFiles: [], + }; + it.each<[string, (dir: string) => void]>([ + [ + 'a symlink, even to a real go.mod outside the repository', + (dir) => { + const outside = fixture({ 'go.mod': 'module example.com/outside\n' }); + fs.symlinkSync(path.join(outside, 'go.mod'), path.join(dir, 'svc/go.mod')); + }, + ], + [ + 'a manifest over the source-file size cap', + (dir) => { + fs.writeFileSync( + path.join(dir, 'svc/go.mod'), + `module example.com/svc\n${'//\n'.repeat(4096)}`, + ); + vi.stubEnv('GITNEXUS_MAX_FILE_SIZE', '1'); + }, + ], + ['a directory named go.mod', (dir) => fs.mkdirSync(path.join(dir, 'svc/go.mod'))], + ['a manifest gone since the scan listed it', () => undefined], + ])('skips %s', async (_case, arrange) => { + const dir = fixture({ 'go.mod': 'module example.com/root\n', 'svc/main.go': 'package main\n' }); + arrange(dir); + expect(await captureGoWorkspaceConfig(dir, ['go.mod', 'svc/go.mod'])).toEqual(ROOT_ONLY); + }); + + // A module boundary that silently vanished would send its imports to the + // wrong module, so a manifest that fails to read surfaces as an error. + // Permission bits do not block reads on Windows, or for root anywhere. + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'throws when a go.mod cannot be read', + async () => { + const dir = fixture({ + 'go.mod': 'module example.com/root\n', + 'svc/go.mod': 'module example.com/svc\n', + }); + const locked = path.join(dir, 'svc/go.mod'); + fs.chmodSync(locked, 0o000); + try { + await expect(captureGoWorkspaceConfig(dir, ['go.mod', 'svc/go.mod'])).rejects.toThrow( + /EACCES/, + ); + } finally { + fs.chmodSync(locked, 0o644); + } + }, + ); + + it('throws when the standalone scan fails instead of reporting no modules', async () => { + const dir = fixture({ 'go.mod': 'module example.com/root\n' }); + await expect(loadGoWorkspaceConfig(path.join(dir, 'go.mod'))).rejects.toThrow(); + }); +}); 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 e029c42602..c01867847b 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 @@ -56,6 +56,7 @@ import type { } from 'gitnexus-shared'; import { resolveGoImportTarget } from '../../../src/core/ingestion/languages/go/import-target.js'; +import type { GoWorkspaceConfig } from '../../../src/core/ingestion/languages/go/workspace-config.js'; import { resolveDartImportTarget } from '../../../src/core/ingestion/languages/dart/import-target.js'; import { resolveRubyImportTarget } from '../../../src/core/ingestion/languages/ruby/import-target.js'; import { @@ -75,6 +76,10 @@ import { DART_HERITAGE_PREFIX } from '../../../src/core/ingestion/languages/dart import { CountingSet, countedParsedFilesWith } from '../../helpers/counting-file-set.js'; // ─── pre-change implementations, minus the rule #2881 removed ──────────────── +// +// And with Go's module leg anchored at the module root, which the multi-module +// change made deliberately: a module-relative package path names ONE +// directory, so the module leg no longer shares the GOPATH leg's suffix match. function legacyFindRootPackageFiles(allFilePaths: ReadonlySet): string[] { const result: string[] = []; @@ -103,6 +108,25 @@ function legacyFindAllFilesInPkgDir(allFilePaths: ReadonlySet, pkgPath: return result; } +/** Files whose parent directory IS `dir`, in Set order: the module leg. */ +function legacyFindFilesInExactDir(allFilePaths: ReadonlySet, dir: string): string[] { + const result: string[] = []; + for (const raw of allFilePaths) { + const normalized = raw.replace(/\\/g, '/'); + if (!normalized.endsWith('.go') || normalized.endsWith('_test.go')) continue; + const slash = normalized.lastIndexOf('/'); + if (slash >= 0 && normalized.slice(0, slash) === dir) result.push(raw); + } + return result; +} + +/** The config `captureGoWorkspaceConfig` produces for a root-only go.mod. */ +function goRootModule(modulePath: string | undefined): GoWorkspaceConfig | undefined { + return modulePath === undefined + ? undefined + : { modules: [{ modulePath, dir: '' }], workFiles: [] }; +} + function legacyResolveGoImportTarget( targetRaw: string, allFilePaths: ReadonlySet, @@ -117,7 +141,7 @@ function legacyResolveGoImportTarget( const files = relativePkg === '' ? legacyFindRootPackageFiles(allFilePaths) - : legacyFindAllFilesInPkgDir(allFilePaths, relativePkg); + : legacyFindFilesInExactDir(allFilePaths, relativePkg); if (files.length > 0) return files; return null; } @@ -463,7 +487,7 @@ describe('import-target index hoist — output parity with the pre-change scans' for (let repo = 0; repo < 40; repo++) { const files = corpus(repo, '.go', 6 + (repo % 25)); for (const modulePath of [undefined, 'example.com/mod']) { - const config = modulePath === undefined ? undefined : { modulePath }; + const config = goRootModule(modulePath); for (const target of GO_TARGETS) { const actual = resolveGoImportTarget(target, 'main.go', files, config); const expected = legacyResolveGoImportTarget(target, files, modulePath); @@ -602,18 +626,19 @@ describe('import-target index hoist — output parity with the pre-change scans' { lang: 'go', why: 'a package dir nested inside itself DOES answer the query (#2881)', - files: ['a/pkg/b/pkg/x.go'], - // Addressed through the MODULE leg as the single segment `pkg`, not as - // `a/pkg`. `a/pkg` never reached the first-occurrence branch this case - // was named for: `'/a/pkg/b/pkg/'.endsWith('/a/pkg/')` is already false, - // so the `endsWith` form agreed with the old predicate and the case - // passed either way. With `pkg`, `endsWith('/pkg/')` is TRUE and ONLY the - // "…and that occurrence is the FIRST" half rejected it — which is exactly - // why this case is the one that flips, and why it is still the case that - // tells the two predicates apart. The module leg is required because the - // GOPATH cascade skips single-segment targets. - target: 'example.com/mod/pkg', - modulePath: 'example.com/mod', + files: ['x/pkg/a/x/pkg/y.go'], + // The queried path must REPEAT inside the directory for this case to + // tell the two predicates apart: `'/x/pkg/a/x/pkg/'.endsWith('/x/pkg/')` + // is TRUE, and ONLY the "…and that occurrence is the FIRST" half rejected + // it — which is exactly why this case is the one that flips. A target + // that does not repeat (`a/pkg` against `a/pkg/b/pkg`) fails `endsWith` + // outright and passes under either rule. + // + // It used to reach the suffix match through the MODULE leg as the single + // segment `pkg`, which the GOPATH cascade skips. The module leg is now + // anchored at the module root and asks for `pkg/` exactly, so the case + // moved to the GOPATH leg with a two-segment repeat instead. + target: 'x/pkg', }, { lang: 'go', @@ -671,7 +696,7 @@ describe('import-target index hoist — output parity with the pre-change scans' it.each(HANDBUILT)('$lang hand-built: $why', ({ lang, files, target, fromFile, modulePath }) => { const set = new Set(files); if (lang === 'go') { - const config = modulePath === undefined ? undefined : { modulePath }; + const config = goRootModule(modulePath); expect(resolveGoImportTarget(target, 'main.go', set, config)).toEqual( legacyResolveGoImportTarget(target, set, modulePath), ); @@ -791,9 +816,12 @@ describe('import-target index hoist — built once per file set, not once per im it('go builds one index for many imports (#2877)', () => { const files = countingCorpus(1, '.go'); for (let i = 0; i < 200; i++) { - resolveGoImportTarget(`example.com/mod/repo${i}/pkg`, 'main.go', files, { - modulePath: 'example.com/mod', - }); + resolveGoImportTarget( + `example.com/mod/repo${i}/pkg`, + 'main.go', + files, + goRootModule('example.com/mod'), + ); } // One pass: the package-dir index (root files are collected in the same pass). expect(files.scans).toBe(1); 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 af5cd09ed5..69bd454873 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 @@ -133,6 +133,7 @@ import { countedParsedFilesWith, pythonNamedImport, } from '../../helpers/counting-file-set.js'; +import type { GoWorkspaceConfig } from '../../../src/core/ingestion/languages/go/workspace-config.js'; /** * The minimum a language needs for one `resolveImportTarget` call to reach @@ -224,8 +225,12 @@ interface ImportTargetFixture { /** The `composer.json` PSR-4 map `loadPhpComposerConfig` would have produced. */ const PHP_COMPOSER: ComposerConfig = { psr4: new Map([['App', 'app']]) }; -/** The value `loadGoModulePath` produces for a repo with a `go.mod`. */ -const GO_MODULE = { modulePath: 'example.com/mod' }; +/** The value `captureGoWorkspaceConfig` produces for a repo whose only + * `go.mod` is at its root. */ +const GO_MODULE: GoWorkspaceConfig = { + modules: [{ modulePath: 'example.com/mod', dir: '' }], + workFiles: [], +}; /** * The `parsedImport` of an adapter that takes three or four parameters and so diff --git a/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts b/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts index 99301bec6f..641d96f398 100644 --- a/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts +++ b/gitnexus/test/unit/scope-resolution/unresolved-receivers.test.ts @@ -16,7 +16,11 @@ import type { ReceiverOrigin, ResolutionOutcome, } from '../../../src/core/ingestion/scope-resolution/resolution-outcome.js'; -import { classifyReceiverOrigin } from '../../../src/core/ingestion/scope-resolution/passes/receiver-bound-calls.js'; +import { + classifyReceiverOrigin, + recordSiteMember, + type EarlierSiteAtKey, +} from '../../../src/core/ingestion/scope-resolution/passes/receiver-bound-calls.js'; import { decodeReceiverChain } from '../../../src/core/ingestion/utils/receiver-chain-codec.js'; import { typescriptScopeResolver } from '../../../src/core/ingestion/languages/typescript/scope-resolver.js'; import { goScopeResolver } from '../../../src/core/ingestion/languages/go/scope-resolver.js'; @@ -509,3 +513,37 @@ describe('classifyReceiverShape', () => { ).toBe('chain-mixed'); }); }); + +// #3498: sites are keyed by start position, so `a.f().g()` puts `f` and `g` +// on one key. Only a duplicate capture of the same site (same receiver, same +// member) may hide a later drop at that key; a different call there must not. +describe('recordSiteMember', () => { + it.each<{ name: string; identities: string[]; expected: EarlierSiteAtKey[] }>([ + { name: 'first site at a key', identities: ['x.m'], expected: ['new-key'] }, + { + name: 'duplicate capture of one site, or a call and its callee read', + identities: ['x.m', 'x.m'], + expected: ['new-key', 'repeated-site'], + }, + { + name: 'outer call sharing the start of an inner call', + identities: ['rp.make', 'rp.make().m'], + expected: ['new-key', 'shared-key'], + }, + { + name: 'same member name nested in its own chain', + identities: ['a.f', 'a.f().f'], + expected: ['new-key', 'shared-key'], + }, + { + name: 'duplicate after a collision', + identities: ['rp.make', 'rp.make().m', 'rp.make'], + expected: ['new-key', 'shared-key', 'repeated-site'], + }, + ])('$name', ({ identities, expected }) => { + const identitiesByKey = new Map>(); + expect( + identities.map((identity) => recordSiteMember(identitiesByKey, 'a.py:1:4', identity)), + ).toEqual(expected); + }); +}); diff --git a/gitnexus/test/unit/staleness.test.ts b/gitnexus/test/unit/staleness.test.ts index 0e6084d7e0..c54d53d02e 100644 --- a/gitnexus/test/unit/staleness.test.ts +++ b/gitnexus/test/unit/staleness.test.ts @@ -215,11 +215,17 @@ describe('staleness status (#3256)', () => { }); }); - it('reports behind with the counted gap', async () => { - expect(await check(fixture.repo, fixture.c1)).toMatchObject({ + it.each([ + { commitsBehind: 1, commitKey: 'c2' as const, noun: 'commit' }, + { commitsBehind: 2, commitKey: 'c1' as const, noun: 'commits' }, + ])('reports $commitsBehind $noun behind with CLI guidance (#3524)', async (testCase) => { + expect(await check(fixture.repo, fixture[testCase.commitKey])).toEqual({ status: 'behind', isStale: true, - commitsBehind: 2, + commitsBehind: testCase.commitsBehind, + hint: + `⚠️ Index is ${testCase.commitsBehind} ${testCase.noun} behind HEAD. ` + + 'Run the CLI command `npx gitnexus analyze` from the repository directory to update.', }); }); @@ -229,6 +235,9 @@ describe('staleness status (#3256)', () => { // The hint claims only the uncountable gap, not that the commit left // history — every other `rev-list` failure reaches the same branch. expect(result.hint).toContain('could not be counted'); + expect(result.hint).toContain( + 'Run the CLI command `npx gitnexus analyze` from the repository directory to update.', + ); // The fail-open values the tests above pin are unchanged. expect(result).toMatchObject({ isStale: false, commitsBehind: 0 }); }); @@ -372,6 +381,9 @@ describe('staleness when the checkout has regressed behind the indexed commit (# expect(result.isStale).toBe(true); expect(result.commitsBehind).toBe(0); expect(result.hint).toContain('not reachable from the checked-out commit'); + expect(result.hint).toContain( + 'Run the CLI command `npx gitnexus analyze` from the repository directory to update.', + ); }); it('still reports current for the commit actually checked out', async () => { diff --git a/gitnexus/test/unit/tool-staleness.test.ts b/gitnexus/test/unit/tool-staleness.test.ts index ed89689848..5e8ba26fb4 100644 --- a/gitnexus/test/unit/tool-staleness.test.ts +++ b/gitnexus/test/unit/tool-staleness.test.ts @@ -15,7 +15,7 @@ import { attachToolStaleness } from '../../src/mcp/local/local-backend.js'; const STALE: StalenessInfo = { isStale: true, commitsBehind: 3, - hint: '⚠️ Index is 3 commits behind HEAD. Run analyze tool to update.', + hint: '⚠️ Index is 3 commits behind HEAD. Run the CLI command `npx gitnexus analyze` from the repository directory to update.', }; const FRESH: StalenessInfo = { isStale: false, commitsBehind: 0 };