mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-23 00:41:36 +00:00
* chore(shared): apply Ring 2 SHARED review follow-ups in one diff Aggregates all actionable follow-ups from the 9 Ring 2 SHARED PRs (#949–#963) before proceeding to Ring 2 PKG. No behavior changes; docstring edits, test refinements, and one structural cleanup. ## #913 (DefIndex / ModuleScopeIndex / QualifiedNameIndex) - Rename `freezeIndex` → `wrapIndex` across all three index builders. The old name implied `Object.freeze` on the wrapper, which we never applied; `wrapIndex` more accurately describes the lightweight readonly-interface wrap. Safety surface (frozen bucket arrays, frozen miss-empty array, readonly Maps) is unchanged. - Document in `buildModuleScopeIndex` JSDoc that callers must pre-normalize `filePath` keys (no path-separator canonicalization happens here). Prevents silent cross-platform misses. - Add an explicit hit-path freeze assertion in `qualified-name-index.test.ts` (the existing test covered only the miss-path `EMPTY` array). ## #914 (MethodDispatchIndex) - Differentiate the C3 and BFS test cases: both tests now use distinct MRO orderings so they prove the materializer stores whatever order the `computeMro` callback produces (not that C3 and BFS yield identical output). - Add `implementsOfCalls` counter in the first-write-wins test, and document the call-count contract in `MethodDispatchInput.implementsOf` JSDoc: `implementsOf` fires **per occurrence** in `input.owners` (not per unique owner); `computeMro` fires at most once per unique owner. Callers with expensive `implementsOf` implementations should pre-dedupe `owners`. ## #916 (resolveTypeRef) - Document the deliberate exclusion of `'Type'` from `TYPE_KINDS` (verified no extractor in `gitnexus/src/core/ingestion/` emits `type: 'Type'` for annotation-relevant symbols). - Rename the namespace-origin test from `'resolves ...'` to `'returns null for a namespace-origin binding whose def is not a type kind'`, matching the failure-case intent. ## #918 (shadow diff + aggregate) - Remove the partial re-export `export type { ShadowAgreement, ShadowDiff };` from `aggregate.ts` — it omitted `ShadowCallsite` and diverged from the top-level barrel. Consumers import all three from the `gitnexus-shared` entry point. - Fix the invalid `'wildcard'` evidence kind in `diff.test.ts` fixture (that kind is not a valid `ResolutionEvidence.kind`). Replaced with `'global-name'`, a real kind the test treats identically. ## #912 (ScopeTree / PositionIndex / makeScopeId) - Document the touching-boundary semantics on `PositionIndex.atPosition`: when siblings share a boundary point, the right (later-start) sibling wins per the existing innermost-wins sort contract. - Resolve the layer-inversion flagged by review: move `ScopeLookup` from `resolve-type-ref.ts` to `types.ts` (its natural home in the data-model layer). `scope-tree.ts` now imports `ScopeLookup` from `types.js` directly; the old re-export from `resolve-type-ref.ts` is removed per repo convention (`feedback_no_reexport`). Barrel export moved alongside. ## #917 (ClassRegistry / MethodRegistry / FieldRegistry) - Replace the dangling "try a name-match among class-like defs" comment in `lookupReceiverType` with explicit prose that callers must pre-resolve via `resolveTypeRef` if they want richer semantics. No behavior change — the function already returned `undefined` on ambiguous/missing qnames. - Fix `tieBreakKey.origin` default for pure Step-2 candidates. Type-binding-only hits no longer falsely inherit `'local'` from `ensureCandidate`'s neutral default; they now demote to `'import'` on their first type-binding hit, and only a later Step-1 lexical hit can upgrade them back to `'local'`. Keeps the Appendix B cascade faithful to the true origin. - Document `'global-name'` in `evidence.ts`: currently reserved for Ring 3's byName global index; `lookupCore` never emits it today. The weight stays live so `composeEvidence` remains exhaustive over the origin union. - Rename the mislabeled Step-7 test from `'confidence DESC is the primary key'` (which actually tested hard-shadow baseline) to `'inner scope shadows outer, yielding single result'`, and add a separate test that actually exercises multi-candidate confidence ordering (local vs wildcard at the same scope). ## Verification - `tsc --noEmit` clean (both `gitnexus-shared` and `gitnexus`) - `gitnexus-shared` build clean - Combined scope-resolution / model / shadow suite: **260/260 pass** (+1 from the new multi-candidate ordering test in #917) ## Not addressed (non-actionable) - #949 CI "failure with zero failing tests": pre-existing Swift Node 22 grammar flake unrelated to #910 scope. - #950: the two non-blocking findings were already addressed in follow-up commit `cbac32ba` (ParsedImport discriminated union + `ScopeId | null` on the two hooks). - #915: the five in-scope findings were already addressed in follow-up commit `54515a7e` (dead code, unused params, multi-hop docs, cap-hit test, stats granularity). - #915 LanguageProvider.resolveImportTarget signature divergence + `findDefById` O(F×D) perf: tracked separately as follow-up issues for the Ring 3 migration window. * chore(shared): address ce:review findings on the follow-up diff ce:review (interactive) on PR #964 surfaced two P2s and several P3s. This commit applies all `safe_auto` fixes + both manual tests in-line so the PR ships with a cleaner review trail. ## P2 fixes - **Complete `freezeIndex` → `wrapIndex` rename.** The prior commit renamed 3 of 5 sibling index files; `method-dispatch-index.ts` and `position-index.ts` still carried the old name. Now all 5 helpers use the consistent `wrapIndex` naming. (maintainability + project-standards reviewers both flagged this.) - **Add regression tests for the `recordTypeBindingHit` origin demotion.** The prior commit introduced the `tieBreakKey.origin = 'import'` demotion for Step-2-only candidates without a direct test. Added: - `registries.test.ts`: two Step-2-only siblings under the same interface, asserting deterministic DefId.localeCompare tie-break AND the stronger invariant that composeEvidence never emits a where-found signal for Step-2-only candidates (no `signals.origin`). - `position-index.test.ts`: touching-boundary test proving the right-sibling-wins rule documented in the new JSDoc. (testing + kieran-typescript + api-contract reviewers all flagged these gaps.) ## P3 fixes - Fix wrong comment in `recordTypeBindingHit` that claimed Step 1 could later upgrade a demoted origin. Step 1 runs BEFORE Step 2 — the actual upgrade path is Step 3 (`seedFromOwnerScopedContributor`). Comment now describes execution order correctly. - Fix inaccurate "re-exported there" comment in `index.ts`. `types.ts` *defines* ScopeLookup natively; it's not a re-export. Phrasing now says "defined in types.ts and exported from the type-export block above — not from this module." - Update stale `scope-tree.ts` file-header prose that still referenced `ScopeLookup` as living in #916/resolve-type-ref.ts. Now points to `./types.js` with a cross-ref to both #916 and #917 consumers. - Expand `atPosition` touching-boundary JSDoc to name the mechanism (backward scan through start-sorted array) so readers can trace the binary-search code to the claim. - Add breadcrumb to `aggregate.ts` module header pointing future readers to `./diff.ts` / the top-level barrel for `ShadowAgreement`, `ShadowCallsite`, and `ShadowDiff`. - Remove unnecessary non-null assertion in `recordTypeBindingHit`. Local `const existingMroDepth = ...` lets TS narrow to `number` in the else-branch, eliminating the `!` without behavior change. ## Verification - `tsc --noEmit` clean (both `gitnexus-shared` and `gitnexus`) - `gitnexus-shared` build clean - Combined scope-resolution / model / shadow suite: **262/262 pass** (+2 from the new origin-demotion + touching-boundary regression tests)
145 lines
6 KiB
TypeScript
145 lines
6 KiB
TypeScript
/**
|
|
* `MethodDispatchIndex` — materialized view of class hierarchies keyed by
|
|
* `DefId` (RFC §3.1; Ring 2 SHARED #914).
|
|
*
|
|
* Two O(1)-access maps used by `Registry.lookupMethod` and interface-
|
|
* dispatch callers:
|
|
*
|
|
* - `mroByOwnerDefId` : owner class → full MRO ancestor chain
|
|
* (excludes the owner itself, in per-language
|
|
* strategy order).
|
|
* - `implsByInterfaceDefId` : interface/trait → classes that implement it.
|
|
*
|
|
* **Not an MRO implementation.** The build function is a pure aggregator: it
|
|
* asks the caller (via `computeMro` and `implementsOf` callbacks) for the
|
|
* per-language answers and materializes the two-way index. MRO strategies
|
|
* live where they already do today (`model/resolve.ts § c3Linearize`,
|
|
* `languages/ruby.ts § selectDispatch`, etc.) — this index does not
|
|
* reimplement them.
|
|
*
|
|
* Why callbacks and not a shared strategy registry: the five strategies
|
|
* (Python C3, Ruby kind-aware, Java/Kotlin linear, Rust qualified-syntax,
|
|
* COBOL none) already exist in the CLI package and depend on the CLI's
|
|
* `HeritageMap` + `SemanticModel`. Pulling them into `gitnexus-shared` would
|
|
* require migrating both — out of scope for #914. Callbacks let the shared
|
|
* build stay pure while honoring existing strategies verbatim.
|
|
*
|
|
* Consumed by: #917 (`Registry.lookupMethod` MRO fast path, interface
|
|
* dispatch resolver).
|
|
*/
|
|
|
|
import type { DefId } from './types.js';
|
|
|
|
// ─── Public contracts ───────────────────────────────────────────────────────
|
|
|
|
export interface MethodDispatchIndex {
|
|
/**
|
|
* Full MRO ancestor chain per owner class (excludes the owner itself).
|
|
* Order reflects the per-language strategy used by `computeMro`.
|
|
*/
|
|
readonly mroByOwnerDefId: ReadonlyMap<DefId, readonly DefId[]>;
|
|
/** Interfaces / traits → classes that implement them. */
|
|
readonly implsByInterfaceDefId: ReadonlyMap<DefId, readonly DefId[]>;
|
|
|
|
/** `mroByOwnerDefId.get`, with an empty frozen array on miss. */
|
|
mroFor(ownerDefId: DefId): readonly DefId[];
|
|
/** `implsByInterfaceDefId.get`, with an empty frozen array on miss. */
|
|
implementorsOf(interfaceDefId: DefId): readonly DefId[];
|
|
}
|
|
|
|
export interface MethodDispatchInput {
|
|
/**
|
|
* Owner defs to index (classes, structs, traits, interfaces — any kind
|
|
* that can appear on the owner side of a method-dispatch graph).
|
|
*/
|
|
readonly owners: readonly DefId[];
|
|
/**
|
|
* Return the full MRO ancestor chain for `ownerDefId`, **excluding the
|
|
* owner itself**, in the order dictated by the owner's language-specific
|
|
* MRO strategy.
|
|
*
|
|
* Contract:
|
|
* - Pure (no side effects).
|
|
* - Deterministic per input.
|
|
* - `undefined` not allowed — return `[]` when the owner has no parents.
|
|
*/
|
|
readonly computeMro: (ownerDefId: DefId) => readonly DefId[];
|
|
/**
|
|
* Return the set of interface/trait defs that `ownerDefId` implements.
|
|
* Transitive inclusion (e.g., `implements` on a parent class) is the
|
|
* caller's choice — the build function simply inverts whatever is
|
|
* returned.
|
|
*
|
|
* Repeated IDs in the output are deduplicated automatically.
|
|
*
|
|
* **Call-count contract.** `implementsOf` is invoked **once per
|
|
* occurrence** of an owner in `input.owners`, not once per unique
|
|
* owner. Duplicate owners therefore re-invoke it; dedup happens at
|
|
* the bucket layer (after the callback returns). Callers with
|
|
* expensive `implementsOf` implementations should pass a deduplicated
|
|
* `owners` list. `computeMro`, by contrast, is memoized by the first-
|
|
* write-wins policy and fires at most once per unique owner.
|
|
*/
|
|
readonly implementsOf: (ownerDefId: DefId) => readonly DefId[];
|
|
}
|
|
|
|
// ─── Builder ────────────────────────────────────────────────────────────────
|
|
|
|
export function buildMethodDispatchIndex(input: MethodDispatchInput): MethodDispatchIndex {
|
|
const mroByOwnerDefId = new Map<DefId, readonly DefId[]>();
|
|
const implsBuilding = new Map<DefId, DefId[]>();
|
|
const implsSeen = new Map<DefId, Set<DefId>>();
|
|
|
|
for (const ownerId of input.owners) {
|
|
// First-write-wins on duplicate owner ids: a stable policy consistent
|
|
// with sibling indexes (#913 DefIndex / ModuleScopeIndex).
|
|
if (!mroByOwnerDefId.has(ownerId)) {
|
|
const chain = input.computeMro(ownerId);
|
|
mroByOwnerDefId.set(ownerId, Object.freeze(chain.slice()));
|
|
}
|
|
|
|
for (const ifaceId of input.implementsOf(ownerId)) {
|
|
let seen = implsSeen.get(ifaceId);
|
|
if (seen === undefined) {
|
|
seen = new Set<DefId>();
|
|
implsSeen.set(ifaceId, seen);
|
|
}
|
|
if (seen.has(ownerId)) continue;
|
|
seen.add(ownerId);
|
|
|
|
let bucket = implsBuilding.get(ifaceId);
|
|
if (bucket === undefined) {
|
|
bucket = [];
|
|
implsBuilding.set(ifaceId, bucket);
|
|
}
|
|
bucket.push(ownerId);
|
|
}
|
|
}
|
|
|
|
const implsByInterfaceDefId = new Map<DefId, readonly DefId[]>();
|
|
for (const [ifaceId, owners] of implsBuilding) {
|
|
implsByInterfaceDefId.set(ifaceId, Object.freeze(owners.slice()));
|
|
}
|
|
|
|
return wrapIndex(mroByOwnerDefId, implsByInterfaceDefId);
|
|
}
|
|
|
|
// ─── Internal ───────────────────────────────────────────────────────────────
|
|
|
|
const EMPTY: readonly DefId[] = Object.freeze([]);
|
|
|
|
function wrapIndex(
|
|
mroByOwnerDefId: Map<DefId, readonly DefId[]>,
|
|
implsByInterfaceDefId: Map<DefId, readonly DefId[]>,
|
|
): MethodDispatchIndex {
|
|
return {
|
|
mroByOwnerDefId,
|
|
implsByInterfaceDefId,
|
|
mroFor(ownerDefId: DefId): readonly DefId[] {
|
|
return mroByOwnerDefId.get(ownerDefId) ?? EMPTY;
|
|
},
|
|
implementorsOf(interfaceDefId: DefId): readonly DefId[] {
|
|
return implsByInterfaceDefId.get(interfaceDefId) ?? EMPTY;
|
|
},
|
|
};
|
|
}
|