mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* fix(ingestion): close merged review gaps Complete lexical ownership, import visibility and canonical worker merges; guard repeated work with purpose-named benchmarks. Refs #3915 * fix(hooks): read rg and grep options per tool so valid searches keep their query The unknown-option decline added in this PR returned null for valid command lines that the merge base augmented: `rg --color=never X`, `rg --no-heading X`, `rg --json X`, `rg -nC3 X`, `grep -rn --exclude-dir=node_modules X .` and others. extractPattern now classifies every option of ripgrep 14.1.1 and GNU grep 3.11 in one table per tool (value in the next token, boolean, pattern, pattern file, informational): - `--name=value` carries its own value and never declines the command; - a long option that takes a value consumes the next token (`--color always`, `--max-depth 3`, `--exclude-dir node_modules`, ...); - a short bundle is read letter by letter, so the last letter may take an attached value or the next token (`-nC3`, `-rnA 2`, `-inm5`); - letters and names the tools read differently are kept apart (`-r`, `-E`, `-T`, `-d`, `-h`, digits, `--color`, GNU long-name abbreviations, ripgrep's `-e=X`). An option the tool does not have, written without `=`, still declines, as do pattern files and options that print without searching. Against the installed binaries as the oracle on 93 command lines: the base build names a token the tool does not search for in 39, the PR head declines 71 searchable commands, this build does neither. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(ingestion): install the ownerless-read probe before reconciliation runs The wrapper called the real reconcileOwnership before wrapping lookupAllByOwner on model.fields and model.types, so the registry reads made by the first reconciliation call on a model (its own duplicate checks) were never counted. The lang-resolution fixture reconciles once per language on one model, so a reader reintroduced for the first language passed with `probe.reads === 0`. The probe is now installed first. With the ownerless skip of the field branch re-opened for the first reconciled language only, the previous test passes and this one fails with 99 reads; removing either skip outright fails it with 833 (fields) and 1541 (nested types) reads. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(java): pin that on-demand imports are not re-exported, per import form The test "does not expose imported members as members of the importing class" used `import b.*;` in Util.java, a type-import-on-demand, so it never put a static member of `b.Tools` in Util's scope and passed on the merge base. Util now uses `import static b.Tools.*;`, and the importer names both a static method and a static member type through `a.Util` (illegal under JLS 7.5.3). A second test covers the package form: a type that Util.java imports with `import c.*;` must not be reachable through `import b.Util.Lib;` (JLS 7.5.1) nor through `import b.*;` (JLS 7.5.2). A same-named type in another package keeps the workspace-unique-name fallback out of the result. Removing `reexportsName: false` from the package on-demand branch of interpretJavaImport (interpret.ts:41) fails the second test with `named -> src/c/Lib.java:Lib` and `:make`; removing it from the static on-demand branch (:66) fails the first with `wrong -> src/b/Tools.java:in`. Both fail in the grouped and the one-edge-per-file storage forms. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(ingestion): make ScopeResolutionIndexes.namespaceExportsByFile readonly `namespaceExportsByFile` was the only writable member of the bundle that SemanticModel.attachScopeIndexes freezes, so `model.scopes.namespaceExportsByFile = ...` compiled and then threw at run time. The member is now `readonly`. runScopeResolution no longer assigns it after building the bundle: the workspace index is built from `finalized.scopeTree` (the same tree the bundle carries), and the bundle is then created in one spread together with the populated method dispatch, the way that late member was already installed. The readers are unchanged. A write to the member through `ScopeResolutionIndexes` is now TS2540; the same file compiled on the previous head. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(ingestion): read the associative-merge opt-in from the Dart and Ruby providers bench/scope-processing/measure.mjs and finalize-binding-scaling.test.ts built their own finalize hooks with `mergeBindingsAreAssociative: true`, so deleting the opt-in from dartScopeResolver or rubyScopeResolver left the gate at exit 0 and the test green while the pipeline went back to one merge per incoming binding. Both now take `mergeBindings` and `mergeBindingsAreAssociative` from the provider objects. Sizes, budgets and the counted quantity (binding refs handed to the merge hook) are unchanged. With the opt-in removed from either provider the unit test fails (`expected 136 to be 16`) and `measure.mjs --check` exits 1 at `<lang>-bindings/16` (`8256 !== 128`, each binding enters its merge once). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(dart): pin show and hide on prefixed imports for every filtered consumer No test had a prefixed import with `show`, so inverting the `show` branch of namespaceImportAllowsMember (walkers.ts:2543) survived the suite: with `import 'x.dart' as p show User;`, `p.Other` resolved to the hidden class. The new suite imports one library under a prefix with no combinator, with `show`, with `hide`, through a re-exporting library, through three imports sharing one prefix with different `show` lists, and deferred with `show`. Each form reaches a visible and a filtered-out class through construction (inline, bound to a local, chained), a static member, a qualified callee, a qualified parameter type and an awaited `Future<p.T>`; every class declares the same member names, so a leak lands on another owner. Mutants of the filter killed by this file alone: show inverted, hide inverted, `some` -> `every`, the per-target-file conjunct, `?? true` -> `?? false`, and the filter call dropped at walkers.ts:1071, imported-return-types.ts:235 and :293 (and :281 together with :293), receiver-bound-calls.ts:1001, :2428 and :2774. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(dart): skip the new Dart suites when the parser cannot be initialised dart-branch-bindings, dart-inferred-result-scopes, dart-review-followups and review-followups-cache guarded only with isLanguageAvailable, which reports that the grammar module loaded, not that Parser.setLanguage accepts it. They now probe loadParser() and loadLanguage(Dart) in a try/catch, as dart.test.ts does, so a grammar that loads but fails at parser initialisation skips the suites instead of failing them in useFixture. With loadLanguage made to throw for Dart, the four suites and dart-prefixed-show-hide report 5 files / 31 tests skipped; with the previous guards the four suites still ran. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): read the SDK lower bound of any pub constraint and bound every manifest The package language version is the major.minor of the pubspec SDK lower bound. The previous pattern accepted only a leading `^X.Y.Z`, `>=X.Y.Z` or bare version followed by whitespace, so `>3.6.0`, `>=2.12.0-0 <3.0.0`, `^3.6.0-0`, `>=3.0.0-417.0.dev <4.0.0`, `>=3.0.0<4.0.0` and `<4.0.0 >=3.0.0` produced no version and the package silently got the 3.7 wildcard rules for `_`. `dartSdkLowerBoundLanguageVersion` now tokenizes the whole constraint: caret, `>=`, `>` and exact versions give a lower bound in any order, with or without whitespace, with pre-release and build suffixes; an exclusive `>X.Y.Z` uses X.Y; the greatest lower bound wins. `any`, an empty string, upper bounds only, or text that is not a constraint give null. `captureDartPackageConfig` now records the language-version boundary for every readable manifest before the package-name check. A nested pubspec whose `name` is missing or rejected used to register nothing, so its files inherited the enclosing package's version. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): re-capture only files whose capture depends on the package language version A package's language version comes from metadata that can change while every source file stays cached, so the parse worker always captures with the default (3.7+) rules and the resolver re-captures on the main thread for a pre-3.7 package. That re-capture ran for every file of such a package on every run, cold and warm: with `sdk: '>=3.0.0 <4.0.0'` and 800 cached files without any `_`, all 800 were re-read and re-captured. The only difference between the two language modes is how a parameter or local named `_` binds, and every such decision goes through `dartUsesWildcardVariables`. Its first question for a tree now records whether the answer came from the caller's version (no leading `// @dart=` override). The Dart provider publishes that as `ParsedFile.captureSideChannel` (`{ kind: 'dart', packageLanguageVersionSensitive: true }`, absent for every other file), which already survives the worker boundary, the ParsedFile store and the durable parse cache. `ScopeResolver.requiresPostExtractSourceText` receives the reused `ParsedFile` as a third argument (undefined when the caller has none, answered conservatively), so the predicate stays free of file I/O. `requiresDartPackageSource` is true only for a sensitive file inside a pre-3.7 package, and `applyDartPackageLanguageVersions` extracts only those files again. On N cached files of which K have a `_` parameter or local, a run reads K sources and makes K main-thread captures. The new integration test drives the durable cache through SDK bound flips across 3.7, pubspec removal and addition, nested pubspec added / renamed / removed, and `// @dart=` overrides added / removed, comparing the complete warm graph with a cold graph of the same tree and counting re-captured files and materialized sources at each step. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): keep the reused capture when a legacy file cannot be captured again `applyDartPackageLanguageVersions` threw "Dart language version requires source" / "Dart language-version extraction failed" when a file of a pre-3.7 package could not be extracted again. The phase passes `''` for a reused file whose source it could not read (deleted, renamed or unreadable between the scan and scope resolution), `extractParsedFile` returns undefined for empty text, and the throw then failed scope resolution for every language in the repository. A file whose source is missing, empty or whitespace-only, or whose extraction yields nothing, now keeps its reused `ParsedFile` (the default 3.7 capture). Each cause is reported in one warning per pass, with the exact count and at most five paths, through the logger the neighbouring package-config module uses. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): walk the capture tree on an explicit stack walkDartTree recursed once per syntax node, and its frame grew in this branch (one more parameter and the branch / loop token locals), so the nesting depth it tolerated fell below the merge base's: 500 nested argument closures overflowed the stack under vitest (callable-flow-stack-depth.test.ts), and outside vitest the limit moved from about 700 closures to about 600. The walk now keeps its pending nodes in explicit arrays and visits them in the same pre-order with the same owner and outer-owner values, so the call stack no longer bounds the depth. The ordered capture stream is byte-identical before and after for 423 Dart sources (every .dart file under test/ and bench/ plus the review fixtures). The stack-depth test gains a 2000-closure case. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(dart): expect the block-local binding in the scope-openers case `void block(Address x) { { final x = make(); use(x); } x.save(); }` now yields two bindings for `x`: the block's own local, typed by `make()`'s result on the Block scope (call-result inference counts declarations per lexical scope since this branch), and the parameter annotation on the Function scope. The graph is right at both sites (inner `x.save()` -> User.save, outer -> Address.save); only this capture-level expectation was stale. The other cases of the test are unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): keep a local function's return type in its declaring scope Local functions are routed through @declaration.function, so Pass A publishes their @type-binding.return, and dartBindingScopeFor hoisted every return binding to the Module scope. A local `Other fetch()` inside one function then retyped the result of every other `fetch()` in the file: the top-level or imported `User fetch()` called from another function, a method of the same name, and, through the exporting file, call sites in importing files. The hook now keeps the return binding of a callable declared inside a body or a statement scope in that scope, which is where the function's name binds. A call result of the local function still resolves inside the declaring scope (nested closures and blocks included); sites outside it read the top-level, imported or member return type again, and two local functions of one name in different functions no longer overwrite each other. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): step over comments in a cascade tree-sitter keeps a comment as a named sibling. In a commented cascade the node before a section was the comment, so its text became the receiver of that section and of every later one, and those calls were dropped with no outcome row. A comment inside a section, between a selector and the next selector or its arguments, ended the section's chain. emitCascadeReference now skips line, block and documentation comments before a section and inside one, so each section reads the cascade's real receiver. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(dart): name the return-binding exemption for what it withholds The local `accessor` in Pass A also covered @dart.callable-body (operators and factory constructors), which are not accessors. It is now `withholdsReturnBinding`, and the comment gives the reason for both: a factory constructor declares no return type, and an operator's binding would be named `operator *` (what the signature reader calls it), which no receiver or callee can spell, so no lookup reads it. No behaviour change. The merge base emitted no declaration capture for either, hence no return binding; a capture-level test pins that an operator and a factory publish none and that their bodies open a scope. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): refuse a name guess to a local callable outside its scope With local functions declared as Function nodes, the global-name fallback could bind a bare call to a local function of another function or of another file whenever the name was unique in the workspace (the merge base already did this for a closure bound to a local variable). A local callable's name is visible only in the body or block that declares it, so that call is impossible, not merely unproven. dartIsGlobalNameFallbackPlausible now refuses a candidate whose name is bound in a Function or Block scope when the call site lies outside that scope; the site is recorded as fallback-refused. A site inside the declaring scope keeps its candidate, and a site with no known scope is allowed as before. The unit-test ParsedFile stub gains the `scopes` array the type requires. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(ruby): keep local claims from hiding calls, constructor facts and heredoc order The ordered local-name claims of this PR stop an untyped local from borrowing an accessor's or an enclosing scope's type. Four side effects of that mechanism are fixed here; what it achieved is unchanged (ruby-review-followups, ruby-bare-read-shadows-method and ruby-yard-param-scope pass as before). A constructor fact reaches every read its assignment governs. A scope keeps one type fact per name, and the shared lookup drops it for a read whose claim is not the claim in force where the fact was written. Two claims for `repo = Repo.new` in the two arms of an `if` therefore left every read under the first one untyped. Consecutive writes that leave the local holding an instance of the same class (`x = K.new` again, or `x ||= …` over an instance) now share one claim. A write of another class still starts a new claim, so a read before it gets no edge rather than the later class. A local never stops a call of the same name. `name(args)`, `name()` and a bare name that is not a local read are method calls in Ruby whatever locals exist. `NameClaim.neverCallee` marks a declaration that a call expression can never invoke, and `NameLookupOptions.callee` marks a lookup made for a receiver-less callee (the free-call pass and the call registry set it); such a lookup does not see such a claim. Every Ruby local claim carries the mark, so call resolution outside a class is what it was before the claims existed, also for a local of the program or of a block. Inside a class the call still dispatches on `self`; when no ancestor defines the method, `resolveRubyReceiverMember` now reaches a top-level `def` of the file or of a required file (a method of Object) instead of reporting an ambiguity. A claim belongs to the scope node that declares the local. Claims were keyed by the start position of the scope, which `program` shares with a `def` or `class` that is the first token of the file, so the Module scope received that scope's claims and a later call was resolved past the file's own method. Claims are now keyed by scope node id and attached to the match of that node. A heredoc body is ordered where Ruby parses it: at its opener, before the rest of the opener's line. A declaration inside a body is therefore visible on the rest of each enclosing opener's line, and a declaration written after an opener is not visible in the bodies opened before it. Positions of sites stay physical; a claim whose visibility is not a suffix of the scope states it through `NameClaim.availableSpans`, and `NameClaim.order` ranks two such claims in parse order. Only declarations displaced by a heredoc carry them. Baselines: the Ruby capture golden and the scope-capture fingerprint change by `"neverCallee":true` on the claims of 19 fixture files and nothing else (76 files and the synthetic source are identical). The ruby-bare-reads fingerprints are unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(scope-resolution): apply an import's name filters in wildcard expansion `ParsedImport.nameFilters` (an ordered list of show / hide filters) was copied onto the import edge, but the wildcard expansion that produces one edge per exported name never read it, so a provider that pairs a wildcard import with filters would bind every name of the target. `expandWildcard` now keeps only the names the statement's filters admit. When they admit none, the original file-level edge is kept, as it already is for a target that publishes no name, so the file dependency survives. The predicate is exported as `importNameFiltersAllow` for providers that produce an import's names themselves. No provider reaches this path with filters today; the Dart provider stops using wildcard expansion in the next commit and applies the same predicate where it builds its import namespaces. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): publish each imported library's names once, one import per directive A plain `import` was rewritten into one named import per public name of the target's export closure, so imports, edge drafts, edges and bindings all grew with importers x exported names, and an import whose expansion was empty vanished together with its file-level IMPORTS edge. A plain import now stays ONE wildcard import and one import edge per directive. What it makes visible is published once per (library, combinator list) as a table in the shared per-namespace binding channel (`namespaceFqnBindings`), and each importing file lists the tables it sees. `show` / `hide` are applied where a table is built. Per importing file the lookup order is: its own override table (names it declares itself, and names two imports bring in as different declarations), then each imported namespace in directive order, so one declaration reached through a barrel and directly binds once. The tables are installed by a new optional `ScopeResolver` hook, `populateImportNamespaces`, called right after finalize: inheritance resolution reads bindings before `populateNamespaceSiblings` runs, and a superclass named through a barrel has to resolve there. Also in this change: - The export closure delivers a name along an `export` directive only when its state changes (absent, one declaration, ambiguous), so the work is bounded by the directives times the names they carry on chains and cycles alike, in any file order. A chain of 1,000 files that each declare one name took 166,666,500 name visits and now takes 499,500, the number of exported entries it produces. - The facts of a library (export closure, plain imports) travel on the ParsedFile under a module-private symbol instead of in WeakMaps keyed by the object, so the export-only veto on the name fallback holds when disk scope mode replaces every ParsedFile by a scope-stripped copy. - An unresolved `package:` import that names a candidate's own file keeps that candidate plausible for the name fallback even when the importing file also exports the library. Behaviour that differs from the previous rewrite: a call result is no longer typed through a function two imports declare differently (the first import's declaration used to win there); such a name stays ambiguous for that lookup. 800 importers of a 1,600-name barrel, whole pipeline, one machine, two runs each: 1,452,988 / 1,450,240 kB peak RSS and 14.5 / 13.4 s before, 307,656 / 290,656 kB and 1.8 / 1.8 s now (merge base: 295,336 / 297,728 kB, 1.8 / 1.8 s), with identical CALLS edges. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(dart): pin export closure rules; probe the parser before enabling the suite Three rules of the export closure had no assertion that fails when the rule is removed: a private name is never exported (the only private name in the suite was also dropped by a `show`), a name travels several export hops and around a cycle, and a library's own declaration wins over an exported one of the same name. The new fixture gives `save`, `make` and `open` two owners each and reaches every name through a prefix, so each edge is decided by one library's export namespace. The suite's skip guard only asked whether the Dart grammar module loaded. It now probes `loadParser()` and `loadLanguage(Dart)` like dart.test.ts, so a grammar that loads but fails in `setLanguage` skips the suite instead of failing it. The existing describe block is re-indented by the formatter because its header now fits on one line; its assertions are unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(dart): keep the local-callable refusal when scopes are sealed to disk The name fallback refuses a bare call to another function's local callable by reading an index of the candidate file's scopes. That index was built lazily, keyed by ParsedFile identity. Disk scope mode replaces every file by a `{ ...file, scopes: [] }` copy before the fallback runs, so the index came back empty there and the refusal was lost: `g -> f.helper` and `h -> f.helper` reappeared for `void f() { void helper() {} helper(); }`. The index is now built in the workspace-reference hook, while scopes are resident, and carried on the file under a module-private symbol, which a spread keeps. Direct callers that never ran the hook still index lazily. dart-import-edges.test.ts runs the shape in both modes; the disk-sealed case fails without the hook call. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(dart): pin that an ambiguous export stays refused downstream; correct stale comments An export closure name has three states: absent, one declaration, ambiguous. Ambiguity travels along `export` directives like a declaration does, so a library that re-exports an ambiguous name refuses it too, even when another of its exports carries a single declaration of that name. Dart rejects the upstream library (one name exported as two declarations), so picking the remaining declaration would resolve calls through a namespace the compiler never builds. The closure's doc comment now states this, and dart-library-exports.test.ts pins it ("Dart ambiguous exports travel"); the test fails when upstream ambiguity is ignored. Comment and title corrections, no behaviour change: - signature-bindings.ts: the sentence about a local function's return type had lost its subject. - dart-awaited-receiver-owner.test.ts: the UNRESOLVED comment still listed `prefixedQualifiedFactory`, which is resolved and has its own test. - ruby-yard-param-scope.test.ts: the header and the suite title still called a first-statement `@return` above `attr_reader` unattached; it is attached. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * refactor(ingestion): remove duplicated predicates and an eager per-file index No behaviour change. - dart/name-fallback-visibility: `recordDartLocalCallables` attaches its index only to a file that declares a local callable. A file without one answers the same from the lazy index, with or without its scopes, so it is no longer copied or given a retained scope-parent map. - scope/walkers: `namespaceImportAllowsMember` uses the shared `importNameFiltersAllow` instead of a second copy of the show/hide rule. - dart/language-version: one `dartVersionHasWildcardVariables(version)` for the `major.minor` parse that two modules repeated. - ruby/captures: one `rubyLocalScopeOf` for the scope-tag lookup that was written once for the node map and once for the match. - dart/captures: two comments state the invariant instead of the history. - hooks/claude: the option-table helper is named `optionNames`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * fix(hooks): decline a GNU grep long-option prefix that names several options GNU grep accepts a prefix of a long option only when it names one option: `grep --no query` exits 2 with "option '--no' is ambiguous". The hook accepted such a prefix whenever every matching option had the same kind, so it read `query` as the search pattern of a command that searched nothing. A prefix is now accepted only when all the names it matches are one option, where the two spellings `--color` / `--colour` count as one (`--col` stays valid, as in grep). Checked against GNU grep 3.11: `--no`, `--line`, `--nu` and `--co` are rejected; `--no-m`, `--line-n` and `--col` are accepted. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * test(ingestion): pin four reviewed behaviours and tighten one assertion No source change. - finalize-algorithm.test.ts: the private-wildcard test asserted `imports?.[0]?.targetDefId` is undefined, which also holds when the caller's import edge is gone. It now requires exactly one edge: `['helper', 'unresolved', undefined]`. - dart-package-language-version.test.ts: a `||` constraint reads as no language version. pub has no disjunction: `VersionConstraint.parse` rejects it as unknown text. - ruby-local-claims.test.ts: a call beside a same-named local or parameter reaches a top-level method whose `require` is written inside the method body or the class body. - ts-object-literal-namespace-import.test.ts (new): a method and an arrow property of an object literal reach a namespace import although a property of the literal has the import's name. Passes on the merge base as well. - ruby-yard-param-scope.test.ts: the header no longer claims a local-shadow case that suite does not contain. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
436 lines
15 KiB
TypeScript
436 lines
15 KiB
TypeScript
/**
|
|
* The contract every `ImportVisibility` implementation must satisfy.
|
|
*
|
|
* A relation is written the way source writes it: per scope, an ordered list
|
|
* of import statements, each with the files it resolves to. The reference
|
|
* answers below are computed from that description alone, so they do not
|
|
* depend on how any implementation stores it. To check an implementation, build
|
|
* it from each relation in `namedRelations` and `generatedRelations` and compare
|
|
* `observeVisibility` with `expectedVisibility`.
|
|
*/
|
|
import type { ImportEdge, ImportVisibility, ScopeId } from 'gitnexus-shared';
|
|
import { importTargetDirectory, isSelectableImport } from 'gitnexus-shared';
|
|
|
|
/** One import statement: how it is written, and the files it resolves to.
|
|
* `null` is a target that did not resolve to a file. */
|
|
export interface ImportStatement {
|
|
readonly edge: Omit<ImportEdge, 'targetFile'>;
|
|
readonly targets: readonly (string | null)[];
|
|
}
|
|
|
|
export interface ImportRelation {
|
|
readonly name: string;
|
|
readonly scopes: readonly {
|
|
readonly id: ScopeId;
|
|
readonly statements: readonly ImportStatement[];
|
|
}[];
|
|
/** Scopes and files to ask about, beyond those the relation mentions. */
|
|
readonly probeScopes: readonly ScopeId[];
|
|
readonly probeFiles: readonly string[];
|
|
}
|
|
|
|
/** What a consumer can observe about one visited target. */
|
|
export interface ObservedTarget {
|
|
readonly targetFile: string;
|
|
readonly kind: ImportEdge['kind'];
|
|
readonly localName: string;
|
|
readonly atRange: ImportEdge['atRange'];
|
|
readonly typeOnly: ImportEdge['typeOnly'];
|
|
readonly runsOnlyWhenCalled: ImportEdge['runsOnlyWhenCalled'];
|
|
}
|
|
|
|
export interface ObservedVisibility {
|
|
readonly scopes: readonly ScopeId[];
|
|
/** Whether finalize recorded the scope at all (`edgesAt` defined). */
|
|
readonly recorded: Readonly<Record<string, boolean>>;
|
|
/** Every import a reader can select by name, definition or kind, in order. */
|
|
readonly selectable: Readonly<Record<string, readonly ImportEdge[]>>;
|
|
readonly targets: Readonly<Record<string, readonly ObservedTarget[]>>;
|
|
readonly reaches: Readonly<Record<string, readonly string[]>>;
|
|
readonly membership: Readonly<Record<string, readonly string[]>>;
|
|
readonly reachesDirectory: Readonly<Record<string, readonly string[]>>;
|
|
readonly hasOtherThan: Readonly<Record<string, readonly string[]>>;
|
|
}
|
|
|
|
/** Every edge one statement stands for, one per target, in target order. */
|
|
export function edgesOfStatement(statement: ImportStatement): ImportEdge[] {
|
|
return statement.targets.map((targetFile) => ({ ...statement.edge, targetFile }));
|
|
}
|
|
|
|
/** The relation as the per-scope edge lists finalize has always produced. */
|
|
export function edgeMapOf(relation: ImportRelation): Map<ScopeId, readonly ImportEdge[]> {
|
|
return new Map(
|
|
relation.scopes.map((scope) => [scope.id, scope.statements.flatMap(edgesOfStatement)]),
|
|
);
|
|
}
|
|
|
|
/** The scopes, files and directories to ask an implementation about. */
|
|
export interface VisibilityQuestions {
|
|
readonly scopes: readonly ScopeId[];
|
|
readonly files: readonly string[];
|
|
readonly directories: readonly string[];
|
|
}
|
|
|
|
function questions(relation: ImportRelation): VisibilityQuestions {
|
|
const files = new Set<string>(relation.probeFiles);
|
|
for (const scope of relation.scopes)
|
|
for (const statement of scope.statements)
|
|
for (const target of statement.targets) if (target !== null) files.add(target);
|
|
return {
|
|
scopes: [...new Set([...relation.scopes.map((scope) => scope.id), ...relation.probeScopes])],
|
|
files: [...files],
|
|
directories: [...new Set([...files].map(importTargetDirectory))],
|
|
};
|
|
}
|
|
|
|
/** The answers the description of the relation requires. */
|
|
export function expectedVisibility(relation: ImportRelation): ObservedVisibility {
|
|
const asked = questions(relation);
|
|
const targetsOf = (id: ScopeId): ObservedTarget[] =>
|
|
(relation.scopes.find((scope) => scope.id === id)?.statements ?? []).flatMap((statement) =>
|
|
statement.targets.flatMap((targetFile) =>
|
|
targetFile === null
|
|
? []
|
|
: [
|
|
{
|
|
targetFile,
|
|
kind: statement.edge.kind,
|
|
localName: statement.edge.localName,
|
|
atRange: statement.edge.atRange,
|
|
typeOnly: statement.edge.typeOnly,
|
|
runsOnlyWhenCalled: statement.edge.runsOnlyWhenCalled,
|
|
},
|
|
],
|
|
),
|
|
);
|
|
const reached = (id: ScopeId): readonly string[] =>
|
|
asked.files.filter((file) => targetsOf(id).some((target) => target.targetFile === file));
|
|
const statementsOf = (id: ScopeId): readonly ImportStatement[] | undefined =>
|
|
relation.scopes.find((scope) => scope.id === id)?.statements;
|
|
return {
|
|
scopes: relation.scopes.map((scope) => scope.id),
|
|
recorded: Object.fromEntries(asked.scopes.map((id) => [id, statementsOf(id) !== undefined])),
|
|
selectable: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
(statementsOf(id) ?? []).flatMap(edgesOfStatement).filter(isSelectableImport),
|
|
]),
|
|
),
|
|
targets: Object.fromEntries(asked.scopes.map((id) => [id, targetsOf(id)])),
|
|
reaches: Object.fromEntries(asked.scopes.map((id) => [id, reached(id)])),
|
|
membership: Object.fromEntries(asked.scopes.map((id) => [id, reached(id)])),
|
|
reachesDirectory: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
asked.directories.filter((directory) =>
|
|
targetsOf(id).some((target) => importTargetDirectory(target.targetFile) === directory),
|
|
),
|
|
]),
|
|
),
|
|
hasOtherThan: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
asked.files.filter((file) => targetsOf(id).some((target) => target.targetFile !== file)),
|
|
]),
|
|
),
|
|
};
|
|
}
|
|
|
|
/** The answers an implementation gives to the same questions. */
|
|
export function observeVisibility(
|
|
relation: ImportRelation,
|
|
visibility: ImportVisibility,
|
|
): ObservedVisibility {
|
|
return observeAsked(questions(relation), visibility);
|
|
}
|
|
|
|
/** The answers an implementation gives to an explicit set of questions. */
|
|
export function observeAsked(
|
|
asked: VisibilityQuestions,
|
|
visibility: ImportVisibility,
|
|
): ObservedVisibility {
|
|
const visit = (id: ScopeId): ObservedTarget[] => {
|
|
const seen: ObservedTarget[] = [];
|
|
visibility.forEachTarget(id, (targetFile, via) =>
|
|
seen.push({
|
|
targetFile,
|
|
kind: via.kind,
|
|
localName: via.localName,
|
|
atRange: via.atRange,
|
|
typeOnly: via.typeOnly,
|
|
runsOnlyWhenCalled: via.runsOnlyWhenCalled,
|
|
}),
|
|
);
|
|
return seen;
|
|
};
|
|
return {
|
|
scopes: [...visibility.scopes()],
|
|
recorded: Object.fromEntries(
|
|
asked.scopes.map((id) => [id, visibility.edgesAt(id) !== undefined]),
|
|
),
|
|
selectable: Object.fromEntries(
|
|
asked.scopes.map((id) => [id, (visibility.edgesAt(id) ?? []).filter(isSelectableImport)]),
|
|
),
|
|
targets: Object.fromEntries(asked.scopes.map((id) => [id, visit(id)])),
|
|
reaches: Object.fromEntries(
|
|
asked.scopes.map((id) => [id, asked.files.filter((file) => visibility.reaches(id, file))]),
|
|
),
|
|
membership: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
asked.files.filter((file) => visibility.membership(id).has(file)),
|
|
]),
|
|
),
|
|
reachesDirectory: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
asked.directories.filter((directory) => visibility.reachesDirectory(id, directory)),
|
|
]),
|
|
),
|
|
hasOtherThan: Object.fromEntries(
|
|
asked.scopes.map((id) => [
|
|
id,
|
|
asked.files.filter((file) => visibility.membership(id).hasOtherThan(file)),
|
|
]),
|
|
),
|
|
};
|
|
}
|
|
|
|
const scopeId = (name: string): ScopeId => name as ScopeId;
|
|
const named = (localName: string, line: number): ImportStatement['edge'] => ({
|
|
localName,
|
|
targetExportedName: localName,
|
|
kind: 'named',
|
|
atRange: { startLine: line, startCol: 0, endLine: line, endCol: 20 },
|
|
});
|
|
const wildcard = (line: number, extra: Partial<ImportEdge> = {}): ImportStatement['edge'] => ({
|
|
localName: '',
|
|
targetExportedName: '',
|
|
kind: 'wildcard-expanded',
|
|
atRange: { startLine: line, startCol: 0, endLine: line, endCol: 20 },
|
|
...extra,
|
|
});
|
|
|
|
const PACKAGE_A = ['src/a/One.java', 'src/a/Two.java', 'src/a/Three.java'];
|
|
const PACKAGE_B = ['src/b/One.java', 'src/b/Four.java'];
|
|
|
|
/** Hand-written relations, one per property the pipeline relies on. */
|
|
export const namedRelations: readonly ImportRelation[] = [
|
|
{ name: 'no scopes at all', scopes: [], probeScopes: [scopeId('absent')], probeFiles: ['x'] },
|
|
{
|
|
name: 'a scope whose import list is empty',
|
|
scopes: [{ id: scopeId('m'), statements: [] }],
|
|
probeScopes: [],
|
|
probeFiles: ['src/a/One.java'],
|
|
},
|
|
{
|
|
name: 'explicit imports interleaved with wildcards',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: named('One', 1), targets: ['src/a/One.java'] },
|
|
{ edge: wildcard(2), targets: PACKAGE_B },
|
|
{ edge: named('Zed', 3), targets: ['src/z/Zed.java'] },
|
|
{ edge: wildcard(4), targets: PACKAGE_A },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: ['src/a/Missing.java', 'Root.java'],
|
|
},
|
|
{
|
|
name: 'more wildcards in one scope than are probed one by one',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: named('One', 1), targets: ['src/a/One.java'] },
|
|
...Array.from({ length: 20 }, (_, i) => ({
|
|
edge: wildcard(i + 2),
|
|
targets: [`src/p${i}/T.java`],
|
|
})),
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: ['src/p20/T.java'],
|
|
},
|
|
{
|
|
name: 'the same wildcard written twice',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: wildcard(1), targets: PACKAGE_A },
|
|
{ edge: wildcard(2), targets: PACKAGE_A },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: [],
|
|
},
|
|
{
|
|
name: 'overlapping target sets and a file named both ways',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: wildcard(1), targets: PACKAGE_A },
|
|
{ edge: named('Two', 2), targets: ['src/a/Two.java'] },
|
|
{ edge: wildcard(3), targets: ['src/a/Three.java', 'src/c/Five.java'] },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: [],
|
|
},
|
|
{
|
|
name: 'a scope that imports its own file, alone and among others',
|
|
scopes: [
|
|
{ id: scopeId('only-self'), statements: [{ edge: wildcard(1), targets: ['Self.java'] }] },
|
|
{
|
|
id: scopeId('self-and-more'),
|
|
statements: [{ edge: wildcard(1), targets: ['Self.java', 'Other.java'] }],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: ['Self.java', 'Other.java'],
|
|
},
|
|
{
|
|
name: 'unresolved targets beside resolved ones',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: named('Gone', 1), targets: [null] },
|
|
{ edge: wildcard(2), targets: [null, 'src/a/One.java', null] },
|
|
{ edge: { ...named('Ext', 3), linkStatus: 'unresolved' }, targets: [null] },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: [],
|
|
},
|
|
{
|
|
name: 'a wildcard that resolves to no file',
|
|
scopes: [{ id: scopeId('m'), statements: [{ edge: wildcard(1), targets: [] }] }],
|
|
probeScopes: [],
|
|
probeFiles: ['src/a/One.java'],
|
|
},
|
|
{
|
|
name: 'presence flags travel with each target',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: wildcard(1, { runsOnlyWhenCalled: true }), targets: PACKAGE_A },
|
|
{ edge: { ...named('T', 2), typeOnly: true }, targets: ['src/t/T.ts'] },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [],
|
|
probeFiles: [],
|
|
},
|
|
{
|
|
name: 'imports selected by name, namespace, definition and exported name beside a wildcard',
|
|
scopes: [
|
|
{
|
|
id: scopeId('m'),
|
|
statements: [
|
|
{ edge: wildcard(1), targets: PACKAGE_A },
|
|
{
|
|
edge: { ...named('ns', 2), kind: 'namespace', targetExportedName: 'pkg.ns' },
|
|
targets: ['src/ns/index.ts'],
|
|
},
|
|
{
|
|
// A wildcard a language expands to names is selectable, never nameless.
|
|
edge: {
|
|
...wildcard(3),
|
|
localName: 'Expanded',
|
|
targetExportedName: 'Expanded',
|
|
targetDefId: 'def:Expanded',
|
|
},
|
|
targets: ['src/a/Two.java'],
|
|
},
|
|
{
|
|
edge: { ...named('Alias', 4), kind: 'alias', targetDefId: 'def:Real' },
|
|
targets: ['src/r/Real.ts'],
|
|
},
|
|
{ edge: { ...named('Gone', 5), linkStatus: 'unresolved' }, targets: [null] },
|
|
{ edge: wildcard(6), targets: PACKAGE_B },
|
|
],
|
|
},
|
|
],
|
|
probeScopes: [scopeId('absent')],
|
|
probeFiles: [],
|
|
},
|
|
{
|
|
name: 'several scopes of one file and files at the root',
|
|
scopes: [
|
|
{ id: scopeId('module'), statements: [{ edge: wildcard(1), targets: PACKAGE_A }] },
|
|
{ id: scopeId('function'), statements: [{ edge: named('R', 9), targets: ['Root.java'] }] },
|
|
{ id: scopeId('other'), statements: [{ edge: wildcard(1), targets: PACKAGE_B }] },
|
|
],
|
|
probeScopes: [scopeId('absent')],
|
|
probeFiles: ['src/a', 'src/a/One.java/x'],
|
|
},
|
|
];
|
|
|
|
/** Deterministic generator (mulberry32): the same seed always gives the same relation. */
|
|
export function prng(seed: number): () => number {
|
|
let state = seed >>> 0;
|
|
return () => {
|
|
state = (state + 0x6d2b79f5) >>> 0;
|
|
let t = state;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* A relation drawn from a small universe, so duplicates, overlaps, self-targets,
|
|
* unresolved targets and empty lists all occur often. Packages are shared
|
|
* arrays: every wildcard over one package holds the same array instance, as a
|
|
* provider that resolves a package once would hand it out.
|
|
*/
|
|
export function generatedRelation(seed: number): ImportRelation {
|
|
const next = prng(seed);
|
|
const pick = (count: number): number => Math.floor(next() * count);
|
|
const directories = ['', 'src', 'src/a', 'src/b', 'lib/deep/x'];
|
|
const packages = Array.from({ length: 4 }, (_, p) =>
|
|
Array.from({ length: pick(5) }, (_unused, f) => {
|
|
const directory = directories[(p + pick(2)) % directories.length]!;
|
|
return `${directory}${directory === '' ? '' : '/'}F${p}_${f}.java`;
|
|
}),
|
|
);
|
|
const loose = ['Self0.java', 'Self1.java', 'src/a/F0_0.java', 'src/z/Lone.java'];
|
|
const scopes = Array.from({ length: 1 + pick(4) }, (_, s) => ({
|
|
id: scopeId(`scope${s}`),
|
|
statements: Array.from({ length: pick(7) }, (_unused, index): ImportStatement => {
|
|
const line = index + 1;
|
|
const shape = pick(5);
|
|
return shape < 2
|
|
? {
|
|
edge: wildcard(line, pick(4) === 0 ? { runsOnlyWhenCalled: true } : {}),
|
|
targets: packages[pick(4)]!,
|
|
}
|
|
: shape === 2
|
|
? { edge: wildcard(line), targets: [null, loose[pick(4)]!, `Self${s % 2}.java`] }
|
|
: shape === 3
|
|
? { edge: named(`N${line}`, line), targets: [pick(3) === 0 ? null : loose[pick(4)]!] }
|
|
: { edge: named(`D${line}`, line), targets: [packages[pick(4)]![0] ?? null] };
|
|
}),
|
|
}));
|
|
return {
|
|
name: `generated relation, seed ${seed}`,
|
|
scopes,
|
|
probeScopes: [scopeId('absent')],
|
|
probeFiles: [...loose, 'src/never/Imported.java'],
|
|
};
|
|
}
|
|
|
|
export const generatedRelations: readonly ImportRelation[] = Array.from({ length: 60 }, (_, i) =>
|
|
generatedRelation(1000 + i),
|
|
);
|