fix(go): resolve imports within selected modules (#3654)

* fix(go): resolve imports against every go.mod in the repository

The Go resolver read only the repository-root go.mod, and its import
target ignored the importing file. With no root go.mod, every import took
the GOPATH suffix match down to a two-segment tail. Two modules'
`internal/repository` then both answered `.../internal/repository`, and a
module whose directory differs from its path (`/vN`, `services/orders`
for `github.com/acme/orders`) resolved to nothing. With a root go.mod,
imports of a nested module were not the root's and dropped, while the
root module's own packages matched any directory ending in the package
path, including nested modules' trees.

Capture every go.mod and go.work from the scan's path list, as Dart does
for pubspec.yaml; standalone and rename callers rescan with the same
walker. For each import, the module whose path is the longest
`/`-prefix owns it. The package is the exact directory under that
module's root, unless a nested go.mod removes the directory from the
module. Several go.mod files declaring one path are disambiguated by the
importer's own module, then by its go.work `use` list, else left
unresolved. Unowned imports from inside a module stay unresolved; the
GOPATH suffix match remains only for importers outside every module.

In the combined lang-resolution corpus, no CALLS or ACCESSES edge is
removed or retargeted against the parent commit, and 70 are added outside
the two new fixtures. Drops are unchanged at 179: these sites were
silent. The import-target bench's go arm now passes no module config,
and its answers and fingerprint are unchanged. The scope-capture go
fingerprint moves for the new fixtures only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(go): look up an importer's module only when a path is contested

`locateGoImport` walked to the importer's nearest `go.mod` and `go.work` for
every import, though most imports (standard library, dependencies) are owned
by no in-repo module and need neither, and every candidate package directory
repeated the same ownership walk. The walks are now lazy (only a module path
several `go.mod` files declare consults them) and memoized per directory on
the config's index, and a path with no backslash skips the normalizing
replace. The Go package index is fetched once per import instead of per
candidate directory.

Behavior-preserving: the lang-resolution corpus emits the identical 3,002
CALLS/ACCESSES edges before and after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(go): surface go.mod read failures instead of dropping the module

Go's workspace capture skipped any manifest it could not read and turned a
failed standalone scan into "no modules". Either one silently erases a module
boundary: its imports then resolve against the enclosing module or fall back
to GOPATH suffix matching, the misresolution this capture exists to remove,
and a rename refresh compares a different config against its preview's.
`captureResolutionConfig` requires capture failures to throw.

- A manifest that fails to read now throws; the standalone scan propagates
  its error.
- Manifests skipped on purpose stay skipped, named in one place: symlinks,
  which can point outside the repository (Dart's manifest capture excludes
  them too), non-files, files over the source-file size cap, and files gone
  since the scan listed them.
- Manifests are read 32 at a time; capture blocks the scan, and k8s-style
  trees have hundreds of go.mod files.

Tests: data-driven rows for each skipped shape, a go.mod that fails to read,
and a standalone scan of a non-directory root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(bench): re-measure Go counts and fingerprint on top of #3651

Rebased onto main after #3651. Import resolution across every go.mod clears
the 13 Go call drops left in the combined corpus (go-chain-call,
go-grouped-type-decl, go-interface-field-dispatch,
go-pointer-receiver-field-chain): call drops 148 -> 135, all kinds 208 -> 195,
.go call drops 14 -> 1. No drop added; shape-arm states unchanged.

The scope-capture go fingerprint moves for the two new fixtures only: parking
them restores main's acee4449f691d9138e68e7b2b19da863fc2c89b0e9846acdf10e93d76b2eec78
byte-for-byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(go): read go.mod through one handle so it cannot change mid-check

CodeQL flagged the manifest read as a file-system race: `lstat` checked the
path and `readFile` then opened it again, so a different file could be read
than the one checked. The manifest is now opened once (O_NOFOLLOW refuses a
leaf symlink, O_NONBLOCK keeps a FIFO from hanging) and its type, size and
contents all come from that handle, the way Dart's manifest reader works. A
platform without O_NOFOLLOW still refuses a link after the open.

The read-permission test is POSIX-only: permission bits do not block reads
on Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(go): skip the unreadable-go.mod test as root; correct a fixture comment

Review follow-up for #3654.

- The permission test asserted EACCES on a mode-000 go.mod, which root can
  still open. It now skips for root as well as on Windows.
- The orders-service ledger fixture said it shares its method names with
  billing's; only Save is shared. The comment says so, in the same two
  lines. Comment text is part of the Go captures, so the golden gains the
  new text and the scope-capture go fingerprint moves:
  3ba3b6e1551311ddb0e9330c939ac995856b487303b6f64bc89da3689a6d9d2c ->
  b1dfa8e1a8d92fd9d5779a02bc4bd99f54ec87adae4a326be08b74cb48fd5ef3, with
  fixture and group counts unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(go): enforce module visibility (#3654)

Limit local providers to the importing module and peers selected by its
nearest go.work. Treat failed package-qualified receiver lookup as final
for direct calls, field chains, and method values so bare-name fallback
cannot recreate calls into independent modules.

Add import/call boundary regressions and remeasure receiver drops. The
same-corpus comparison removes exactly two false calls and adds no edges.

Validation: 7,263 resolver tests, both typechecks, lint, and import-target,
scope-capture, and receiver baseline checks pass. Two parser-identity
checks affected by local snapshot/build drift pass after freezing inputs
and rebuilding. The full local run continues; final CI remains required.

* fix(go): reject ambiguous package providers (#3654)

Check all selected module prefixes for package presence. Preserve a shorter-only provider and refuse imports supplied by multiple modules. Cover all four presence cases and correct the receiver suppression comment.

Note: the full local suite hit a host GLIBCXX_3.4.31 failure in parse-cache-identity-package.test.ts; focused Go tests and both TypeScript checks pass.

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Abhigyan Patwari 2026-10-21 23:54:18 +05:30 • committed by GitHub
parent 2b111f4488
commit 2b6542737a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
38 changed files with 1492 additions and 169 deletions

View file

@ -675,7 +675,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.
*
@ -1256,7 +1266,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`;
@ -1469,10 +1479,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
@ -1838,7 +1848,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') {
@ -2209,7 +2219,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

View file

@ -1,5 +1,42 @@
# 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,

View file

@ -199,21 +199,21 @@
}
},
"countArm": {
"callDrops": 148,
"totalDropsAllKinds": 208,
"callDrops": 138,
"totalDropsAllKinds": 200,
"bySiteKind": {
"call": 148,
"read": 40,
"call": 138,
"read": 42,
"write": 20
},
"callDropsByExtension": {
".java": 49,
".py": 24,
".ts": 17,
".go": 14,
".zig": 13,
".cs": 8,
".tsx": 6,
".go": 4,
".php": 4,
".rs": 4,
".kt": 4,
@ -222,16 +222,17 @@
".swift": 1
},
"callDropsByShape": {
"chain-field": 70,
"chain-field": 59,
"no-chain": 34,
"chain-call": 32,
"<<unclassified>>": 11,
"chain-call": 31,
"<<unclassified>>": 13,
"chain-unwrap": 1
},
"callDropsByOrigin": {
"in-program": 72,
"in-program": 60,
"external": 44,
"unknown": 32
"unknown": 32,
"<<unclassified>>": 2
}
}
}

View file

@ -1,7 +1,8 @@
{
"_comment": "Per-language baselines for bench/scope-capture/measure.mjs --check. fingerprint = order-independent sha256 over the lang-resolution/<lang>-* 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": "acee4449f691d9138e68e7b2b19da863fc2c89b0e9846acdf10e93d76b2eec78",
"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.",

View file

@ -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`.

View file

@ -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<string>,
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>): 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<string>, pkgPath: string): string[] {

View file

@ -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,
@ -19,6 +18,7 @@ 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),

View file

@ -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<string | null> {
// 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<GoWorkspaceConfig | null> {
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<GoWorkspaceConfig | null> {
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<GoWorkspaceConfig>;
return Array.isArray(candidate.modules) && Array.isArray(candidate.workFiles);
}
/** Lookup tables over one config, built once per config object. */
interface GoWorkspaceIndex {
readonly moduleByDir: ReadonlyMap<string, GoModule>;
/** Module path → every module declaring it, in `dir` order. */
readonly modulesByPath: ReadonlyMap<string, readonly GoModule[]>;
/** `go.work` directory → the module directories it uses. */
readonly usesByWorkDir: ReadonlyMap<string, ReadonlySet<string>>;
/** 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<string, GoModule | null>;
/** Directory → its nearest `go.work` uses (`null`: none), filled lazily. */
readonly workUsesByDir: Map<string, ReadonlySet<string> | 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<GoWorkspaceConfig, GoWorkspaceIndex>();
function indexOf(config: GoWorkspaceConfig): GoWorkspaceIndex {
const cached = INDEXES.get(config);
if (cached !== undefined) return cached;
const moduleByDir = new Map<string, GoModule>();
const modulesByPath = new Map<string, GoModule[]>();
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<string, ReadonlySet<string>>();
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<T>(byDir: ReadonlyMap<string, T>, 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<T>(
cache: Map<string, T | null>,
byDir: ReadonlyMap<string, T>,
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<string> | 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<string> | 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' };
}

View file

@ -1702,10 +1702,10 @@ export interface ScopeResolver {
* branch of `findClassBindingInScope` — candidates only from the files the
* qualifier's import resolves to, filtered by `isNamespaceMemberVisible` —
* with the unique-name fallback switched off for that attempt, so a hit is a
* namespace decision and never a name guess. Any miss (an unresolved import,
* no such type, two of them) falls back to the bare `rawName` lookup exactly
* as before, guesses included. That fallback is load-bearing: a type behind an
* import the resolver cannot follow still binds by a workspace-unique name.
* namespace decision and never a name guess. A miss (an unresolved import,
* no such type, two of them) is final: the bare `rawName` must not bind a type
* from another package. Bare lookup remains available when this hook returns
* no qualified spelling.
*
* The qualifier must name a FILE-level import: it is looked up from the module
* scope enclosing `declaredAtScope`, never from `declaredAtScope` itself. That

View file

@ -1133,8 +1133,8 @@ interface CallableTargetIndexes {
readonly byOwnerAndName: ReadonlyMap<string, readonly Target[]>;
readonly byFileAndName: ReadonlyMap<string, readonly Target[]>;
/** The class a receiver's QUALIFIED declared type names, when the provider
* recovers one (see `classOfQualifiedTypeSpelling`); absent otherwise. */
readonly classOfQualifiedReceiver?: (typeRef: TypeRef) => SymbolDefinition | undefined;
* recovers one; null refuses a qualified miss, undefined permits bare lookup. */
readonly classOfQualifiedReceiver?: (typeRef: TypeRef) => SymbolDefinition | null | undefined;
}
function buildCallableTargetIndexes(
@ -1612,18 +1612,16 @@ function receiverType(
});
}
/** The class a receiver's declared type names: its qualified spelling first,
* as receiver-bound calls ask it, then the bare `rawName` exactly as before. */
function classOfReceiverType(
typeRef: TypeRef,
inScope: ScopeId,
scopes: ScopeResolutionIndexes,
targetIndexes: CallableTargetIndexes,
): SymbolDefinition | undefined {
return (
targetIndexes.classOfQualifiedReceiver?.(typeRef) ??
resolveInheritanceBaseInScope(inScope, typeRef.rawName, scopes)
);
const qualified = targetIndexes.classOfQualifiedReceiver?.(typeRef);
return qualified === undefined
? resolveInheritanceBaseInScope(inScope, typeRef.rawName, scopes)
: (qualified ?? undefined);
}
function qualifiedReceiverLookup(

View file

@ -438,13 +438,6 @@ interface FoldState {
* (`resolveClassBindingForName` tries that first, and a name with no `<`
* returns immediately after it).
*
* ── THE QUALIFIED SPELLING GOES FIRST ────────────────────────────────────────
*
* Capture can also cut a namespace qualifier (`models.User` → `User`), and then
* the bare lookup cannot tell two packages' `User` apart. When the provider
* recovers the qualified spelling, {@link classOfQualifiedTypeSpelling} asks it
* first, grounded on the qualifier's import; only a miss reaches the bare
* lookup, which still answers as it always did.
*/
function classOfDeclaredType(
typeRef: TypeRef,
@ -464,29 +457,36 @@ function classOfDeclaredType(
// 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 qualified = classOfQualifiedTypeSpelling(
typeRef,
scopes,
options.qualifiedTypeLookupSpelling,
lookup,
options.namespaceMemberVisible,
);
const def =
classOfQualifiedTypeSpelling(
typeRef,
scopes,
options.qualifiedTypeLookupSpelling,
lookup,
options.namespaceMemberVisible,
) ??
resolveClassBindingForName(typeRef.declaredAtScope, spelling, scopes, stripDecoration, lookup);
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
* `undefined` — see `ScopeResolver.qualifiedTypeLookupSpelling` for why the
* qualifier has to be recovered at all.
* `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. Every miss returns `undefined` and the caller asks the bare `rawName`
* exactly as before; that lookup keeps its own fallback, which is what still
* reaches a workspace-unique type behind an import the resolver cannot follow.
* 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
@ -505,17 +505,19 @@ export function classOfQualifiedTypeSpelling(
qualifiedTypeLookupSpelling: ScopeResolver['qualifiedTypeLookupSpelling'],
lookup: ClassBindingLookup,
namespaceMemberVisible: ClassBindingLookup['namespaceMemberVisible'],
): SymbolDefinition | undefined {
): 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,
});
return (
findClassBindingInScope(importScope, qualified, scopes, undefined, {
...lookup,
namespaceMemberVisible,
uniqueQualifiedNameFallback: false,
}) ?? null
);
}
/**

View file

@ -2361,24 +2361,23 @@ export function emitReceiverBoundCalls(
purpose: typeRef.lookupPurpose ?? 'type',
onNameFallback,
};
// A namespace qualifier capture cut from `rawName` (`models.User` →
// `User`) is asked first, through the helper the compound resolver's
// declared-type lookup uses — a miss lands on the lookup below unchanged.
const qualifiedOwner = classOfQualifiedTypeSpelling(
typeRef,
scopes,
provider.qualifiedTypeLookupSpelling,
typeLookup,
namespaceMemberVisible,
);
let ownerDef =
classOfQualifiedTypeSpelling(
typeRef,
scopes,
provider.qualifiedTypeLookupSpelling,
typeLookup,
namespaceMemberVisible,
) ??
resolveClassBindingForName(
typeRef.declaredAtScope,
typeApplication ?? typeRef.rawName,
scopes,
undefined,
typeLookup,
);
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
@ -2399,6 +2398,7 @@ export function emitReceiverBoundCalls(
});
if (
ownerDef === undefined &&
qualifiedOwner !== null &&
typeApplication === undefined &&
!hasExplicitNameClaim(typeClaim, typeRef.rawName)
) {
@ -2425,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,
@ -2435,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',

View file

@ -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"
@ -443,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"

View file

@ -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()
}

View file

@ -0,0 +1,3 @@
module github.com/acme/billing
go 1.21

View file

@ -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 }

View file

@ -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()
}

View file

@ -0,0 +1,3 @@
module github.com/acme/orders
go 1.21

View file

@ -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 }

View file

@ -0,0 +1,7 @@
package main
import "example.com/generator/v2/models"
func Generate(tpl *models.Template) string {
return tpl.Render()
}

View file

@ -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

View file

@ -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 "" }

View file

@ -0,0 +1,5 @@
package models
type Template struct{}
func (t *Template) Render() string { return "" }

View file

@ -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()
}

View file

@ -0,0 +1,3 @@
module example.com/platform
go 1.21

View file

@ -0,0 +1,5 @@
package repository
type Ledger struct{}
func (s *Ledger) Save() error { return nil }

View file

@ -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() {}

View file

@ -0,0 +1,7 @@
package main
import "github.com/acme/ledger/internal/repository"
func Bill(ledger *repository.Ledger) error {
return ledger.Save()
}

View file

@ -0,0 +1,3 @@
module github.com/acme/ledger
go 1.21

View file

@ -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 }

View file

@ -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';

View file

@ -1,10 +1,11 @@
/**
* Go: package imports + cross-package calls + ambiguous struct disambiguation
*/
import { describe, it, expect, beforeAll, afterAll } 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,
@ -2352,16 +2353,11 @@ describe('Go package-qualified field and parameter types', () => {
expect(targetsOf(caller)).toEqual(expected);
});
// The qualified spelling is tried FIRST, not instead: when its import names
// no file in the workspace, the bare-name lookup still answers — and still
// refuses when the bare name is ambiguous. The field rows are the ones that
// need the declared-type lookup's own fallback; a parameter also has the
// simple-typeBinding case's unique-name fallback behind it.
it.each([
['refuses a bare name two packages declare', 'ArchiveForeign', []],
['refuses a bare name two packages declare', 'ArchiveForeignField', []],
['keeps the unique-name fallback', 'SpinGadget', ['Spin@gadgets/gizmo.go']],
['keeps the unique-name fallback', 'SpinGadgetField', ['Spin@gadgets/gizmo.go']],
['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);
});
@ -2506,3 +2502,185 @@ func run(f func()) {
).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>, 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);
},
);
});

View file

@ -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'],

View file

@ -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([

View file

@ -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);
});
});

View file

@ -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<Record<string, string>>): 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<Record<string, string>>, 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();
});
});

View file

@ -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>): string[] {
const result: string[] = [];
@ -103,6 +108,25 @@ function legacyFindAllFilesInPkgDir(allFilePaths: ReadonlySet<string>, pkgPath:
return result;
}
/** Files whose parent directory IS `dir`, in Set order: the module leg. */
function legacyFindFilesInExactDir(allFilePaths: ReadonlySet<string>, 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<string>,
@ -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);

View file

@ -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