GitNexus/gitnexus/test/integration/resolvers/ruby-yard-param-scope.test.ts
Gergő Magyar 111fa82ea1
fix(ingestion): close resolver, import and benchmark review gaps (#3945)
* 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>
2026-11-15 17:06:51 +00:00

1429 lines
35 KiB
TypeScript

/**
* RUBY-01 — YARD `@param` types must bind to the DECLARING method, never to
* the enclosing class/module (docs/languages/ruby-ingestion-gaps.md).
*
* The YARD pass in `languages/ruby/captures.ts` anchors every synthesized
* `@type-binding.parameter` on the `method` node. Pass 4 of the scope
* extractor auto-hoists a binding whose anchor range EQUALS the innermost
* scope's range to that scope's parent (built for Python's
* `@type-binding.return`, whose anchor is the `function_definition`). A method
* node is its own `@scope.function`, so the parameter binding used to land on
* the Class (or Module, for a top-level `def`) scope — and every sibling with
* a same-named parameter borrowed it. `rubyBindingScopeFor` now pins
* `@type-binding.parameter` to the innermost (method) scope.
*
* Contract, per sibling pair and in BOTH declaration orders:
* - the typed call resolves to the exact `User#save` node ID, and only it;
* - the untyped sibling's call stays unresolved (no CALLS edge at all);
* - the decoy `AuditLog#save` is never chosen by anyone.
*
* Four pairs: typed-first in a class, untyped-first in a class, a
* top-level pair (Module scope is the parent there — the shape the receiver
* benchmark recorded), and a pair whose tag uses the alternate YARD order
* `@param [Type] name` (a second capture path in the YARD pass). The decoy exists so an unresolved receiver has TWO
* `save` candidates: a name-only guess would be visible as a wrong edge
* rather than hidden behind a unique name.
*
* The second and third suites are the review corpus for the pin, retargeted
* to pin-only expectations: RUBY-01 ships WITHOUT inferring an instance
* variable's type from a YARD-typed parameter (per-file capture cannot see
* class reopenings, mixins or generated writers, so that inference could
* still publish a wrong field type — see "Future: field typing from typed
* parameters" in docs/languages/ruby-ingestion-gaps.md). Every `@user.save`
* after `@user = user`, and every `holder.user.save` through `attr_reader`,
* is therefore a DOCUMENTED MISSING EDGE asserted as `[]`; a YARD `@return`
* on a hand-written reader still types its chain; and no untyped program may
* ever reach `User#save` or `AuditLog#save`. Missing beats wrong.
*
* The fourth suite guards the pin's own side effect: in the method scope the
* tag's `parameter-annotation` fact outranks a local's `constructor-inferred`
* one, so a tag may only type a name that is a formal parameter, is never
* REBOUND in the body (binding-target semantics: the name itself, or the name
* reached through a destructuring list, `for`, `rescue =>`, or a `case … in` /
* rightward pattern — including the hash shorthand `{user:}`), and is not
* `self`. A write INTO the parameter (`user.name = x`, `user[0] = 1`,
* `user.count += 1`, `user.a, user.b = …`), a read as a block-parameter
* default, a pinned `^user` or `^(user)`, and a read inside a nested block or
* lambda all keep the tag. Every rebinding case asserts `[]` with the guard
* and flips to a wrong User#save without it; of the kept cases, ten were lost
* on fdb945742 (mention-based guard) and `expression_pin_read` on f4d0f8a64 —
* the rest are controls that also held before. A block, lambda or nested-def
* PARAMETER of the same name (`block_param`, `block_local`, `lambda_shadow`,
* `nested_def_inner`) no longer declines the tag: since RUBY-03 it is listed
* on its own scope, where the receiver walk stops, so those sites still
* assert `[]` and the tagged use beside them resolves (`nested_def`; see
* ruby-block-param-lexical-stop.test.ts for the block and lambda forms).
*
* The fifth suite pins the review's reassign-then-use table (coercion,
* decorator, association and use-before-rebind idioms): a declined tag makes
* the method resolve exactly like its untagged twin, and every case there
* fails with the guard removed. The in-class reader forms (`user.save`,
* `self.user.save` through `attr_reader :user`) are pinned in the second
* suite: main resolved them only through the leaked class-scope binding. The
* sixth suite pins that a bare `@type [T]` synthesizes no binding (the removed
* capture bound the empty name). The last suite pins `@return` above
* `attr_reader`: the tag types the in-class read whether the accessor is the
* FIRST statement of the class body or follows another statement. Explicit `target()`
* beside a same-named parameter lives in ruby-param-shadow-call.test.ts
* (pre-existing behaviour, passes on main).
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import path from 'path';
import fs from 'node:fs';
import os from 'node:os';
import {
getNodesByLabel,
getRelationships,
runPipelineFromRepo,
writeFixtureRepo,
type PipelineResult,
type RelEdge,
} from './helpers.js';
import { emitRubyScopeCaptures } from '../../../src/core/ingestion/languages/ruby/index.js';
const TYPED = ['typed_first_typed', 'untyped_first_typed', 'top_typed', 'alt_order_typed'] as const;
const UNTYPED = [
'typed_first_untyped',
'untyped_first_untyped',
'top_untyped',
'alt_order_untyped',
] as const;
describe('Ruby YARD @param binds to the declaring method, not its siblings (RUBY-01)', () => {
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let decoySaveId: string;
const saveCallsFrom = (source: string): RelEdge[] =>
getRelationships(result, 'CALLS').filter((c) => c.source === source && c.target === 'save');
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-param-scope-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
def save
true
end
end
class AuditLog
def save
false
end
end
`,
'typed_first.rb': `require_relative 'models'
class TypedFirst
# @param user [User]
def typed_first_typed(user)
user.save
end
def typed_first_untyped(user)
user.save
end
end
`,
'untyped_first.rb': `require_relative 'models'
class UntypedFirst
def untyped_first_untyped(user)
user.save
end
# @param user [User]
def untyped_first_typed(user)
user.save
end
end
`,
'top_level.rb': `require_relative 'models'
# @param user [User]
def top_typed(user)
user.save
end
def top_untyped(user)
user.save
end
`,
'alt_order.rb': `require_relative 'models'
class AltOrder
# @param [User] user
def alt_order_typed(user)
user.save
end
def alt_order_untyped(user)
user.save
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
// Exact owner IDs come from the graph, not from a hand-written string, so
// the assertions below compare full node IDs rather than member names.
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === 'save');
if (edge === undefined) throw new Error(`fixture lost ${owner}#save`);
return edge.rel.targetId;
};
userSaveId = own('User');
decoySaveId = own('AuditLog');
expect(userSaveId).not.toBe(decoySaveId);
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it.each(TYPED)('%s resolves user.save to the exact User#save node', (fn) => {
const edges = saveCallsFrom(fn);
expect(edges.map((e) => e.rel.targetId)).toEqual([userSaveId]);
});
it.each(UNTYPED)('%s (untyped sibling) keeps user.save unresolved', (fn) => {
// The leak made this edge point at User#save through the typed sibling's
// YARD tag — a wrong edge, not a missing one. Nothing may be emitted here.
expect(saveCallsFrom(fn)).toEqual([]);
});
it('never picks the decoy AuditLog#save from any function', () => {
const toDecoy = getRelationships(result, 'CALLS').filter((c) => c.rel.targetId === decoySaveId);
expect(toDecoy).toEqual([]);
});
});
describe('Ruby YARD @param on initialize does not type the ivar (documented boundary)', () => {
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let decoySaveId: string;
const saveCallsFrom = (source: string): RelEdge[] =>
getRelationships(result, 'CALLS').filter((c) => c.source === source && c.target === 'save');
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-ivar-boundary-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
def save
true
end
end
class AuditLog
def save
false
end
end
`,
'holders.rb': `require_relative 'models'
class TypedHolder
attr_reader :user
# @param user [User]
def initialize(user)
@user = user
end
def typed_inside
@user.save
end
def typed_sibling(user)
user.save
end
def reader_inside
user.save
end
def self_reader_inside
self.user.save
end
end
class UntypedHolder
attr_reader :user
def initialize(user)
@user = user
end
def untyped_inside
@user.save
end
end
class ShadowedHolder
attr_reader :user
# @param user [User]
def initialize(user)
user = AuditLog.new
@user = user
end
end
`,
'app.rb': `require_relative 'holders'
# @param holder [TypedHolder]
def typed_holder_chain(holder)
holder.user.save
end
# @param holder [UntypedHolder]
def untyped_holder_chain(holder)
holder.user.save
end
# @param holder [ShadowedHolder]
def shadowed_holder_chain(holder)
holder.user.save
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === 'save');
if (edge === undefined) throw new Error(`fixture lost ${owner}#save`);
return edge.rel.targetId;
};
userSaveId = own('User');
decoySaveId = own('AuditLog');
expect(userSaveId).not.toBe(decoySaveId);
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it.each(['typed_inside', 'typed_holder_chain'] as const)(
'%s stays unresolved: the tag types the parameter, never the ivar (boundary)',
(fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
},
);
it("keeps the parameter type away from a sibling method's untyped `user` parameter", () => {
expect(saveCallsFrom('typed_sibling')).toEqual([]);
});
it.each(['reader_inside', 'self_reader_inside'] as const)(
'%s: the in-class attr_reader forms (`user.save`, `self.user.save`) no longer resolve — main typed them only through the leaked class-scope `user` binding',
(fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
},
);
it.each(['untyped_holder_chain', 'untyped_inside'] as const)(
'%s stays unresolved when initialize(user) carries no YARD tag',
(fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
},
);
it('does not type anything from a parameter that was rewritten as a local', () => {
expect(saveCallsFrom('shadowed_holder_chain')).toEqual([]);
});
it('never picks User#save or the decoy AuditLog#save from any function', () => {
const picked = getRelationships(result, 'CALLS').filter(
(c) => c.rel.targetId === userSaveId || c.rel.targetId === decoySaveId,
);
expect(picked.map((c) => `${c.source} -> ${c.rel.targetId}`)).toEqual([]);
});
});
describe('Ruby YARD ivar typing review corpus: documented boundaries (these hold on main by design — the pin never types an ivar)', () => {
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let decoySaveId: string;
const saveCallsFrom = (source: string): RelEdge[] =>
getRelationships(result, 'CALLS').filter((c) => c.source === source && c.target === 'save');
const saveTargets = (source: string): string[] =>
saveCallsFrom(source).map((e) => e.rel.targetId);
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-review-corpus-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
def save
true
end
end
class AuditLog
def save
false
end
end
`,
'f3_override.rb': `require_relative 'models'
class OverrideHolder
attr_reader :user
# @return [AuditLog]
def user
AuditLog.new
end
# @param user [User]
def initialize(user)
@user = user
end
end
class DefineMethodHolder
attr_reader :user
define_method(:user) { AuditLog.new }
# @param user [User]
def initialize(user)
@user = user
end
end
`,
'f4_conflict.rb': `require_relative 'models'
class ConflictHolder
# @param user [User]
def initialize(user)
@user = user
end
# @param log [AuditLog]
def replace(log)
@user = log
end
def conflict_persist
@user.save
end
end
class AgreeHolder
# @param user [User]
def initialize(user)
@user = user
end
# @param other [User]
def replace(other)
@user = other
end
def agree_persist
@user.save
end
end
class NilWriteHolder
# @param user [User]
def initialize(user)
@user = user
end
def reset
@user = nil
end
def nil_write_persist
@user.save
end
end
`,
'r3_ownership.rb': `require_relative 'models'
class BlockWriteHolder
# @param user [User]
def initialize(user)
@user = user
[AuditLog.new].each { |log| @user = log }
end
def block_write_persist
@user.save
end
end
class IvarMultiAssignHolder
# @param user [User]
def initialize(user)
@user = user
@user, unused = AuditLog.new, nil
end
def ivar_multi_assign_persist
@user.save
end
end
class ReopenedHolder
# @param user [User]
def initialize(user)
@user = user
end
def reopened_persist
@user.save
end
end
class ReopenedHolder
def replace(log)
@user = log
end
end
class CrossFileHolder
# @param user [User]
def initialize(user)
@user = user
end
def cross_file_persist
@user.save
end
end
module Storage
# @param user [User]
def initialize(user)
@user = user
end
def mixin_persist
@user.save
end
end
class MixinHolder
include Storage
def replace(log)
@user = log
end
end
class AccessorWriterHolder
attr_accessor :user
# @param user [User]
def initialize(user)
@user = user
end
def accessor_writer_persist
@user.save
end
end
class AttrWriterHolder
attr_writer :user
# @param user [User]
def initialize(user)
@user = user
end
def attr_writer_persist
@user.save
end
end
class ArrayParamHolder
# @param users [Array<User>]
def initialize(users)
@users = users
end
def array_param_persist
@users.save
end
end
`,
'r3_reopen_other_file.rb': `require_relative 'r3_ownership'
class CrossFileHolder
def replace(log)
@user = log
end
end
`,
'app.rb': `require_relative 'f3_override'
require_relative 'r3_ownership'
require_relative 'r3_reopen_other_file'
# @param holder [OverrideHolder]
def f3_override_chain(holder)
holder.user.save
end
# @param holder [DefineMethodHolder]
def f3_define_method_chain(holder)
holder.user.save
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string, method: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === method);
if (edge === undefined) throw new Error(`fixture lost ${owner}#${method}`);
return edge.rel.targetId;
};
userSaveId = own('User', 'save');
decoySaveId = own('AuditLog', 'save');
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('a hand-written reader keeps its own @return [AuditLog]', () => {
expect(saveTargets('f3_override_chain')).toEqual([decoySaveId]);
});
it('a define_method(:user) reader is untyped', () => {
expect(saveCallsFrom('f3_define_method_chain')).toEqual([]);
});
it.each(['conflict_persist', 'agree_persist', 'nil_write_persist'] as const)(
'typed writes: %s stays unresolved (boundary)',
(fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
},
);
it.each([
'block_write_persist',
'ivar_multi_assign_persist',
'reopened_persist',
'cross_file_persist',
'mixin_persist',
'accessor_writer_persist',
'attr_writer_persist',
'array_param_persist',
] as const)('ownership and writer hazards: %s stays unresolved', (fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
});
it('no untyped program ever reaches User#save or AuditLog#save', () => {
const wrong = getRelationships(result, 'CALLS').filter(
(c) =>
(c.rel.targetId === userSaveId || c.rel.targetId === decoySaveId) &&
c.source !== 'f3_override_chain',
);
expect(wrong.map((c) => `${c.source} -> ${c.rel.targetId}`)).toEqual([]);
});
});
describe('Ruby YARD @param beside a rebound local: every rebinding form declines the tag, every write INTO the variable keeps it', () => {
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let decoySaveId: string;
let selfTaggedSaveId: string;
const saveCallsFrom = (source: string): RelEdge[] =>
getRelationships(result, 'CALLS').filter((c) => c.source === source && c.target === 'save');
const saveTargets = (source: string): string[] =>
saveCallsFrom(source).map((e) => e.rel.targetId);
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-rebound-local-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
attr_accessor :name, :count, :a, :b
def save
true
end
end
class AuditLog
def save
false
end
end
`,
'rebound.rb': `require_relative 'models'
# Every method here carries a tag that is WRONG for the value the call sees:
# with the guard the tag is declined (no edge); without it the tag wins and
# the call resolves to User#save against an AuditLog.
class Rebound
# @param user [AuditLog]
def ra(user)
user = User.new
user.save
end
# @param user [AuditLog]
def dd(account)
user = User.new
user.save
end
# @param user [User]
def multi_assign(user)
a, user = 1, AuditLog.new
user.save
end
# @param user [User]
def trailing_comma(user)
user, = [AuditLog.new]
user.save
end
# @param user [User]
def nested_destructure(user)
(a, user), b = [[1, AuditLog.new], 2]
user.save
end
# @param user [User]
def splat_assign(user)
a, *user = 1, AuditLog.new
user.save
end
# @param user [User]
def or_assign(user)
user ||= AuditLog.new
user.save
end
# @param user [User]
def op_assign(user)
user += 1
user.save
end
# @param user [User]
def for_loop(user)
for user in [AuditLog.new]
end
user.save
end
# @param user [User]
def for_multi(user)
for a, user in [[1, AuditLog.new]]
end
user.save
end
# @param user [User]
def rescue_var(user)
begin
raise 'x'
rescue => user
end
user.save
end
# @param user [User]
def implicit_rescue(user)
user.save
rescue => user
user.save
end
# @param user [User]
def block_param(user)
[AuditLog.new].each { |user| user.save }
end
# @param user [User]
def block_local(user)
[1].each { |x; user| user.save }
end
# @param user [User]
def lambda_param(user)
lambda_shadow = ->(user) { user.save }
end
# @param user [User]
def nested_def(user)
def nested_def_inner(user)
user.save
end
user.save
end
# @param user [User]
def hash_pattern_shorthand(user, payload)
case payload
in {user:}
user.save
end
end
# @param user [User]
def rightward_hash_shorthand(user, payload)
payload => {user:}
user.save
end
# @param user [User]
def test_pattern_hash(user, payload)
if payload in {user:}
user.save
end
end
# @param user [User]
def array_pattern(user, v)
case v
in [user]
user.save
end
end
# @param user [User]
def as_pattern_in_hash(user, v)
case v
in {u: AuditLog => user}
user.save
end
end
# @param user [User]
def splat_pattern(user, v)
case v
in [*user]
user.save
end
end
# @param user [User]
def hash_splat_pattern(user, v)
case v
in {**user}
user.save
end
end
end
`,
'kept.rb': `require_relative 'models'
# Every method here writes INTO the parameter or merely reads it; the tag must
# keep typing the call (exact User#save). "lost on fdb945742" marks the ten
# cases the mention-based guard declined; expression_pin_read was lost on
# f4d0f8a64; the rest are controls that also held before.
class Kept
# @param user [User] (lost on fdb945742)
def attr_write(user, n)
user.name = n
user.save
end
# @param user [User] (lost on fdb945742)
def other_attr_named_user(post, user)
post.user = user
user.save
end
# @param user [User] (lost on fdb945742)
def self_attr_write(user)
self.user = user
user.save
end
def user=(value)
@user = value
end
# @param user [User] (lost on fdb945742)
def index_write(user)
user[0] = 1
user.save
end
# @param user [User] (lost on fdb945742)
def memo_index_key(user)
@cache[user.id] = user
user.save
end
# @param user [User] (lost on fdb945742)
def attr_op_assign(user)
user.count += 1
user.save
end
# @param user [User] (lost on fdb945742)
def safe_nav_write(user, x)
user&.name = x
user.save
end
# @param user [User] (lost on fdb945742)
def masgn_attr(user)
user.a, user.b = 1, 2
user.save
end
# @param user [User] (lost on fdb945742)
def block_param_default_read(user, xs)
xs.each { |x, y = user| y }
user.save
end
# @param user [User] (lost on fdb945742)
def pin_pattern_read(user, v)
case v
in ^user then 1
end
user.save
end
# @param user [User] (lost on f4d0f8a64)
def expression_pin_read(user, payload)
case payload
in ^(user) then 1
end
user.save
end
# @param user [User] (control: held on fdb945742)
def read_in_block(user)
[1].each { user.save }
end
# @param user [User] (control: held on fdb945742)
def read_in_lambda(user)
lambda_reader = -> { user.save }
end
# @param user [User] (control: held on fdb945742)
def read_in_lambda_call(user)
-> { user.save }.call
end
# @param user [User] (control: held on fdb945742)
def other_local_eq_user(user)
other = user
user.save
end
# @param user [User] (control: held on fdb945742)
def hash_value(user)
opts = { user: user }
user.save
end
# @param user [User] (control: held on fdb945742)
def keyword_arg_call(user)
g(user: user)
user.save
end
# @param user [User] (control: held on fdb945742)
def tagged_formal_kept(user)
user.save
end
end
class SelfTagged
def save
true
end
# @param self [AuditLog]
def self_tagged
save
end
end
`,
'constructs.rb': `require_relative 'models'
class Constructs
# @param user [User]
def self.singleton_typed(user)
user.save
end
def self.singleton_untyped(user)
user.save
end
class << self
# @param user [User]
def eigen_typed(user)
user.save
end
def eigen_untyped(user)
user.save
end
end
# @param user [User]
def endless_typed(user) = user.save
def endless_untyped(user) = user.save
end
module Outer
module Inner
class Deep
# @param user [User]
def deep_typed(user)
user.save
end
def deep_untyped(user)
user.save
end
end
# @param user [User]
def self.module_singleton_typed(user)
user.save
end
def self.module_singleton_untyped(user)
user.save
end
end
end
RSpec.describe 'constructs' do
# @param user [User]
def spec_typed(user)
user.save
end
def spec_untyped(user)
user.save
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === 'save');
if (edge === undefined) throw new Error(`fixture lost ${owner}#save`);
return edge.rel.targetId;
};
userSaveId = own('User');
decoySaveId = own('AuditLog');
selfTaggedSaveId = own('SelfTagged');
expect(userSaveId).not.toBe(decoySaveId);
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it.each(['ra', 'dd'] as const)(
'%s: a local `user = User.new` beats a `@param user [AuditLog]` tag (exact User#save)',
(fn) => {
expect(saveTargets(fn)).toEqual([userSaveId]);
},
);
it.each([
'multi_assign',
'trailing_comma',
'nested_destructure',
'splat_assign',
'or_assign',
'op_assign',
'for_loop',
'for_multi',
'rescue_var',
'implicit_rescue',
'hash_pattern_shorthand',
'rightward_hash_shorthand',
'test_pattern_hash',
'array_pattern',
'as_pattern_in_hash',
'splat_pattern',
'hash_splat_pattern',
] as const)('rebinding: %s declines the tag — no edge (User#save would be wrong)', (fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
});
it.each(['block_param', 'block_local', 'lambda_shadow', 'nested_def_inner'] as const)(
'shadowing: %s declares the name on its own scope — the receiver walk stops there, no edge',
(fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
},
);
it('nested_def: the tagged parameter beside a nested `def inner(user)` keeps the tag (exact User#save)', () => {
expect(saveTargets('nested_def')).toEqual([userSaveId]);
});
it.each([
'attr_write',
'other_attr_named_user',
'self_attr_write',
'index_write',
'memo_index_key',
'attr_op_assign',
'safe_nav_write',
'masgn_attr',
'block_param_default_read',
'pin_pattern_read',
'expression_pin_read',
'read_in_block',
'lambda_reader',
'read_in_lambda_call',
'other_local_eq_user',
'hash_value',
'keyword_arg_call',
'tagged_formal_kept',
] as const)(
'kept: %s writes into or reads the parameter, so the tag still types it (exact User#save)',
(fn) => {
expect(saveTargets(fn)).toEqual([userSaveId]);
},
);
it('self_tagged: `@param self` never retypes the receiver (bare save stays SelfTagged#save)', () => {
expect(saveTargets('self_tagged')).toEqual([selfTaggedSaveId]);
});
it('an assigned lambda is its own call source, so the lambda cases above are asserted on it', () => {
// `lambda_shadow = ->(user) { … }` / `lambda_reader = -> { … }` are declared
// as Functions named after the local; their calls are emitted from them.
const fns = getNodesByLabel(result, 'Function');
expect(fns).toContain('lambda_shadow');
expect(fns).toContain('lambda_reader');
});
// Known unguarded rebindings — a regex named capture `/(?<user>\w+)/ =~ s`,
// `binding.local_variable_set(:user, …)` and `eval` — are recorded in
// docs/languages/ruby-ingestion-gaps.md, not as `it.todo`: CI's execution
// audit (scripts/test-completeness.ts) counts a todo as unverified.
it.each([
'singleton_typed',
'eigen_typed',
'endless_typed',
'deep_typed',
'module_singleton_typed',
'spec_typed',
] as const)('construct coverage: %s resolves to the exact User#save', (fn) => {
expect(saveTargets(fn)).toEqual([userSaveId]);
});
it.each([
'singleton_untyped',
'eigen_untyped',
'endless_untyped',
'deep_untyped',
'module_singleton_untyped',
'spec_untyped',
] as const)('construct coverage: untyped sibling %s stays unresolved', (fn) => {
expect(saveCallsFrom(fn)).toEqual([]);
});
it('never picks the decoy AuditLog#save from any function', () => {
const toDecoy = getRelationships(result, 'CALLS').filter((c) => c.rel.targetId === decoySaveId);
expect(toDecoy.map((c) => `${c.source} -> ${c.rel.targetId}`)).toEqual([]);
});
});
describe('Ruby YARD @param beside the reassign-then-use idioms: a declined tag resolves exactly like its untagged twin', () => {
// The review table for the pin (PR #3871): with the tag in the method scope,
// its `parameter-annotation` fact (strength 2) would beat the local's
// `constructor-inferred` one (strength 1) whatever the statement order, so
// the coercion and decorator idioms below would resolve through the tag.
// The rebinding guard declines the tag instead, so each method resolves as
// its untagged twin (and as main) does. Every case here fails with the guard
// removed (`yardParamNameIsBindable` -> true); none depends on the pin.
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let userFullNameId: string;
let auditSaveId: string;
let optionsSaveId: string;
let decoratorFullNameId: string;
const targetsOf = (source: string, method: string): string[] =>
getRelationships(result, 'CALLS')
.filter((c) => c.source === source && c.target === method)
.map((e) => e.rel.targetId);
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-reassign-idioms-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
def save
true
end
def full_name
'u'
end
# @return [Account]
def account
Account.new
end
end
class AuditLog
def save
false
end
end
class Account
def save
true
end
end
class Options
def initialize(hash)
end
def save
true
end
end
class UserDecorator
def initialize(user)
end
def full_name
'd'
end
end
`,
'idioms.rb': `require_relative 'models'
class Idioms
# @param user [User]
def reassign_then_use(user)
user = AuditLog.new
user.save
end
def reassign_then_use_untagged(user)
user = AuditLog.new
user.save
end
# @param user [User]
def decorate(user)
user = UserDecorator.new(user)
user.full_name
end
# @param user [User]
def follow_association(user)
user = user.account
user.save
end
# @param opts [Hash]
def coerce(opts)
opts = Options.new(opts)
opts.save
end
# @param user [User]
def use_before_rebind(user)
user.save
user = AuditLog.new
end
def use_before_rebind_untagged(user)
user.save
user = AuditLog.new
end
end
# @param user [User]
def top_reassign_then_use(user)
user = AuditLog.new
user.save
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string, method: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === method);
if (edge === undefined) throw new Error(`fixture lost ${owner}#${method}`);
return edge.rel.targetId;
};
userSaveId = own('User', 'save');
userFullNameId = own('User', 'full_name');
auditSaveId = own('AuditLog', 'save');
optionsSaveId = own('Options', 'save');
decoratorFullNameId = own('UserDecorator', 'full_name');
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it.each(['reassign_then_use', 'top_reassign_then_use'] as const)(
'%s: `user = AuditLog.new; user.save` under `@param user [User]` resolves to the local (exact AuditLog#save), like its untagged twin',
(fn) => {
expect(targetsOf(fn, 'save')).toEqual([auditSaveId]);
expect(targetsOf(fn, 'save')).toEqual(targetsOf('reassign_then_use_untagged', 'save'));
},
);
it('decorate: `user = UserDecorator.new(user); user.full_name` resolves to the decorator (exact UserDecorator#full_name)', () => {
expect(targetsOf('decorate', 'full_name')).toEqual([decoratorFullNameId]);
});
it('coerce: `opts = Options.new(opts); opts.save` under `@param opts [Hash]` keeps the local (exact Options#save)', () => {
expect(targetsOf('coerce', 'save')).toEqual([optionsSaveId]);
});
it('follow_association: `user = user.account; user.save` gets no edge (User#save would be wrong; Account#save is a missing edge, as on main)', () => {
expect(targetsOf('follow_association', 'save')).toEqual([]);
});
it('use_before_rebind: `user.save; user = AuditLog.new` resolves exactly like its untagged twin — the pre-existing flow-insensitive local answer (AuditLog#save, as on main), pinned on purpose', () => {
expect(targetsOf('use_before_rebind', 'save')).toEqual(
targetsOf('use_before_rebind_untagged', 'save'),
);
expect(targetsOf('use_before_rebind', 'save')).toEqual([auditSaveId]);
});
it('no rebound method reaches User#save or User#full_name through its declined tag', () => {
const picked = getRelationships(result, 'CALLS').filter(
(c) => c.rel.targetId === userSaveId || c.rel.targetId === userFullNameId,
);
expect(picked.map((c) => `${c.source} -> ${c.rel.targetId}`)).toEqual([]);
});
});
describe('Ruby YARD `@type [T]` synthesizes no type binding (the inert capture was removed)', () => {
it('a bare `# @type [User]` above a method emits no @type-binding.parameter capture (it used to bind the empty name, which nothing reads)', () => {
const src = `class TypeTagOnly
# @type [User]
def type_only(user)
user.save
end
end
`;
const names = emitRubyScopeCaptures(src, 'type_only.rb')
.filter((m) => m['@type-binding.parameter'] !== undefined)
.map((m) => m['@type-binding.name']?.text);
expect(names).toEqual([]);
});
});
describe('Ruby YARD @return above attr_reader: attached as the first statement of the class body and after another statement', () => {
let result: PipelineResult;
let tmpDir: string;
let userSaveId: string;
let decoySaveId: string;
const saveCallsFrom = (source: string): RelEdge[] =>
getRelationships(result, 'CALLS').filter((c) => c.source === source && c.target === 'save');
beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ruby-yard-return-attr-first-'));
writeFixtureRepo(tmpDir, {
'models.rb': `class User
def save
true
end
end
class AuditLog
def save
false
end
end
`,
'readers.rb': `require_relative 'models'
class FirstStatementReader
# @return [User]
attr_reader :user
def initialize(user)
@user = user
end
def first_statement_reader_inside
user.save
end
end
class LaterStatementReader
LABEL = 'later'
# @return [User]
attr_reader :user
def initialize(user)
@user = user
end
def later_statement_reader_inside
user.save
end
end
`,
});
result = await runPipelineFromRepo(tmpDir, () => {});
const hasMethod = getRelationships(result, 'HAS_METHOD');
const own = (owner: string): string => {
const edge = hasMethod.find((e) => e.source === owner && e.target === 'save');
if (edge === undefined) throw new Error(`fixture lost ${owner}#save`);
return edge.rel.targetId;
};
userSaveId = own('User');
decoySaveId = own('AuditLog');
expect(userSaveId).not.toBe(decoySaveId);
}, 60000);
afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('attaches @return to an attr_reader that opens the class body', () => {
expect(saveCallsFrom('first_statement_reader_inside').map((e) => e.rel.targetId)).toEqual([
userSaveId,
]);
});
it('later_statement_reader_inside (control): the same tag after another statement types the in-class read to the exact User#save', () => {
expect(saveCallsFrom('later_statement_reader_inside').map((e) => e.rel.targetId)).toEqual([
userSaveId,
]);
});
it('never picks the decoy AuditLog#save from any function', () => {
const toDecoy = getRelationships(result, 'CALLS').filter((c) => c.rel.targetId === decoySaveId);
expect(toDecoy).toEqual([]);
});
});