Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
108 commits
Select commit Hold shift + click to select a range
2b6a00d
fix: scope codegraph batch complexity targets to file paths
carlos-alm Jul 5, 2026
b28051a
fix: exclude parameters and interface/type members from dead-role cla…
carlos-alm Jul 5, 2026
17fbcba
fix: credit import-type usages as exports consumers
carlos-alm Jul 5, 2026
26918bb
fix: prevent fn-impact/query crash when -f/--file is passed
carlos-alm Jul 5, 2026
be6432c
fix: correct exported-symbol detection for literal and object-literal…
carlos-alm Jul 5, 2026
4ead840
fix: exclude primitive type keywords from ast --kind string matching
carlos-alm Jul 5, 2026
f6326bf
fix: resolve call edges through renamed import specifiers
carlos-alm Jul 5, 2026
590f560
fix: couple file_hashes updates with edge regeneration in incremental…
carlos-alm Jul 5, 2026
d3ea4a4
fix: compare signature-change diffs using new-file line ranges
carlos-alm Jul 5, 2026
c306812
feat: add environment doctor check for stale native binary and missin…
carlos-alm Jul 5, 2026
8bb5893
fix: eliminate non-deterministic ordering in community detection
carlos-alm Jul 6, 2026
46037b1
fix: sync update-graph.sh hook extension allowlist with EXTENSIONS
carlos-alm Jul 6, 2026
6a84cf9
fix: recompute directory structure metrics for affected directories o…
carlos-alm Jul 6, 2026
8d936d1
refactor: register hardcoded execFileSync/execSync maxBuffer values i…
carlos-alm Jul 6, 2026
11c84be
fix: gate blast-radius check on newly introduced risk, not pre-existi…
carlos-alm Jul 6, 2026
963301a
fix: gate identifier-argument dynamic call edges on callback-acceptin…
carlos-alm Jul 6, 2026
3e8035d
fix: gate Array.from's callback arg by position, not just callee name
carlos-alm Jul 6, 2026
879635e
fix: scope reexportedSymbols to actually-named re-export specifiers
carlos-alm Jul 6, 2026
0fe9fc3
fix: stop CFG block/edge count from overriding AST-derived cyclomatic…
carlos-alm Jul 6, 2026
ccf3c19
fix: backfill edges.technique for incrementally-inserted calls edges
carlos-alm Jul 6, 2026
d5b1162
fix: wrap remote embedding JSON parse failure in EngineError
carlos-alm Jul 6, 2026
8971017
refactor: extract shared platform-default-path helper in config.ts
carlos-alm Jul 6, 2026
056c5e4
refactor: decompose loadConfig and related high-effort functions in c…
carlos-alm Jul 6, 2026
0738171
refactor: decompose findDbPath and openRepo in db/connection.ts (docs…
carlos-alm Jul 6, 2026
6f2423c
refactor: dedupe busy/locked error detection into isBusyOrLockedError
carlos-alm Jul 6, 2026
4c02378
fix: log statSync failures in findDbPath instead of silently swallowi…
carlos-alm Jul 6, 2026
0698e16
test: add direct unit coverage for closeDbPair/closeDbPairDeferred/cl…
carlos-alm Jul 6, 2026
4ac3b99
fix: correct blast-radius/fn-impact computation for line-shifted decl…
carlos-alm Jul 6, 2026
6767f09
feat: wire points-to solver max-iterations cap through DEFAULTS.analy…
carlos-alm Jul 6, 2026
5f6f30a
refactor: route console.log calls in domain/search through logger
carlos-alm Jul 6, 2026
b479318
refactor: reduce cyclomatic complexity of computeDeltaModularityDirected
carlos-alm Jul 6, 2026
c39ac40
refactor: unify impact-level rendering format between audit and fn-im…
carlos-alm Jul 6, 2026
067674f
refactor: dedupe computeSavings via pct helper and persist partial to…
carlos-alm Jul 6, 2026
f6807b4
fix: add main.rs driver to rust dynamic tracer fixture
carlos-alm Jul 6, 2026
1c07a54
fix: scope diff file-header detection to between-hunk positions
carlos-alm Jul 6, 2026
bf82aa2
fix: update titan-grind's dead-symbol script for current roles --json…
carlos-alm Jul 6, 2026
cd02d27
fix: thread configured busyTimeoutMs through remaining read-only quer…
carlos-alm Jul 6, 2026
980b5dc
fix: resolve computed string-literal keys in object-literal extractio…
carlos-alm Jul 6, 2026
4a873a3
fix: add same-class bare-call fallback to incremental rebuild path (d…
carlos-alm Jul 6, 2026
8f3348a
fix: unify Object.defineProperty accessor fallback kind-filtering bet…
carlos-alm Jul 6, 2026
acf804c
refactor: share chunked statement-cache primitive between builder and…
carlos-alm Jul 6, 2026
986c851
refactor: cache prepared statements in applyEdgeTechniquesAfterNative…
carlos-alm Jul 6, 2026
71e9174
fix: replace fixed-depth directory-proximity check with symmetric dis…
carlos-alm Jul 6, 2026
d2935cc
refactor: remove unreachable Partition delta-computation interface me…
carlos-alm Jul 6, 2026
6515186
fix: emit reference edges for function identifiers used as object-lit…
carlos-alm Jul 6, 2026
30c491a
refactor: unify call-ref and tests rendering format between audit and…
carlos-alm Jul 6, 2026
9db911b
fix: classify destructured bindings as constant, not function (docs c…
carlos-alm Jul 6, 2026
70559fc
refactor: adopt timeMedian in remaining benchmark timing loops
carlos-alm Jul 6, 2026
822e0eb
refactor: decompose runPerfBenchmarks in token-benchmark.ts
carlos-alm Jul 6, 2026
fcdfe7d
fix: attribute liveness to Lua functions assigned to global/builtin i…
carlos-alm Jul 6, 2026
ee6362c
refactor: extract shared sedi() helper for tracer scripts
carlos-alm Jul 6, 2026
d4e6212
fix: restore reflection dynamicKind for .call/.apply/.bind (docs chec…
carlos-alm Jul 6, 2026
aec5d2b
fix: restrict entry-role classification to function/method-kind symbo…
carlos-alm Jul 6, 2026
d250f8d
fix: credit destructured dynamic import() bindings as exports consumers
carlos-alm Jul 6, 2026
75978e2
fix: recognize Lua function nodes in complexity metrics computation (…
carlos-alm Jul 6, 2026
af17b6d
fix: scope global call-resolution fallback to same-language candidate…
carlos-alm Jul 6, 2026
dd447bc
fix: credit instanceof ClassName checks as exports consumers
carlos-alm Jul 6, 2026
a79a8a1
fix: update automated-review workflow to use current claude-code-acti…
carlos-alm Jul 6, 2026
d84f6b5
refactor: widen outputResult signature, remove redundant casts at cal…
carlos-alm Jul 6, 2026
e7a2255
fix: port Leiden algorithm to native Rust for cross-engine community-…
carlos-alm Jul 7, 2026
b54972a
feat: detect exported-symbol loss from full file deletion in checkNoS…
carlos-alm Jul 7, 2026
1821a8b
fix(complexity): scope summary stats to file/target/kind filters
carlos-alm Jul 7, 2026
d45aba7
fix(extractors): label property_signature interface/type members as k…
carlos-alm Jul 7, 2026
69d8a6f
fix(roles): exclude genuine class/struct properties from dead-role cl…
carlos-alm Jul 7, 2026
db08219
fix(resolver): scope extends/implements edges to same-file/import/lan…
carlos-alm Jul 7, 2026
79cd761
fix: track inline per-specifier type-only import modifier
carlos-alm Jul 7, 2026
cbfa954
fix(native): widen NativeRepository file filters to accept string[]
carlos-alm Jul 7, 2026
c0e7eae
fix(native): remove unused source param from get_first_call_arg
carlos-alm Jul 7, 2026
2dabe21
fix(extractors): align native/WASM definitions order for object-liter…
carlos-alm Jul 7, 2026
b1eb9af
fix(extractors): capture top-level const definitions regardless of in…
carlos-alm Jul 7, 2026
4a1e279
fix: exclude PHP scalar type-hint/cast keywords from ast --kind string
carlos-alm Jul 7, 2026
40b5e24
fix: track barrel re-export renames (export { X as Y } from ...)
carlos-alm Jul 7, 2026
1506896
fix: record local alias for dynamic import() destructuring renames
carlos-alm Jul 7, 2026
2dfd6bc
fix: resolve renamed-import receiver calls in qualified-method lookup
carlos-alm Jul 7, 2026
ccea0cb
fix(native): propagate edge/node write failures out of run_pipeline
carlos-alm Jul 7, 2026
93ccfa3
fix(exports): discriminate file-level from symbol-level consumer entries
carlos-alm Jul 7, 2026
e105c26
docs: refresh CONTRIBUTING.md for TypeScript architecture and current…
carlos-alm Jul 7, 2026
5d99bf0
fix(exports): credit plain imports of TypeScript interfaces/type aliases
carlos-alm Jul 7, 2026
e0ab9dc
fix(hooks): point update-graph.sh fallback build path at dist/cli.js
carlos-alm Jul 7, 2026
730b49b
fix(hooks): resolve track-edits.sh's PROJECT_DIR from the edited file…
carlos-alm Jul 7, 2026
0d7e8e6
fix: capture removed files' cross-directory neighbors before purge
carlos-alm Jul 7, 2026
c5b9a34
docs: fix stale codegraph check flag names in recommended-practices.md
carlos-alm Jul 7, 2026
2de6550
fix(cycles): classify cycles whose only closing edges are speculative
carlos-alm Jul 7, 2026
e5fe754
fix(resolver): recognize identifier args to user-defined higher-order…
carlos-alm Jul 8, 2026
4eef28e
fix(native): scope barrel-only import skipping to transient barrel re…
carlos-alm Jul 8, 2026
4090355
refactor(ast-analysis): extract shared CFG/complexity result-merging …
carlos-alm Jul 8, 2026
bf8e969
fix(incremental): port CHA/RTA dispatch, points-to, and dynamic-sink …
carlos-alm Jul 8, 2026
51b9e23
fix(config): derive ENV_LLM_KEYS from ENV_LLM_MAP to prevent drift
carlos-alm Jul 8, 2026
a62bab7
fix(resolver): resolveByGlobal picks the single best match, not every…
carlos-alm Jul 8, 2026
8f52d28
fix(embed): resolve default DB path from positional dir, not cwd
carlos-alm Jul 8, 2026
59220a5
refactor(leiden): extract makePartition's inline getters to cut cyclo…
carlos-alm Jul 8, 2026
2e1aa11
docs: regenerate stale audit/diff-impact example output blocks
carlos-alm Jul 8, 2026
3d436ca
fix(rust): resolve self.field, unit-struct, and constructor-typed locals
carlos-alm Jul 8, 2026
668451c
docs: add missing titan-grind mirror to claude-code-skills examples
carlos-alm Jul 8, 2026
4bccd4b
fix(scripts): migrate ts-resolve-loader.js off deprecated module.regi…
carlos-alm Jul 8, 2026
25ba42f
fix(native): recover renamed import names in the FFI hybrid import-ed…
carlos-alm Jul 8, 2026
431c0e5
fix: reconnect reverse-dep edges correctly when a sibling group's siz…
carlos-alm Jul 8, 2026
ab6a685
fix: derive loadConfig() rootDir from --db path in read-only query fu…
carlos-alm Jul 8, 2026
17e265b
fix(native): thread config.db.busyTimeoutMs into NativeDatabase open …
carlos-alm Jul 8, 2026
fdedff8
fix(extractors): unwrap computed string-literal keys in typeMap/proto…
carlos-alm Jul 8, 2026
6ef1731
fix(native): add Object.defineProperty accessor dispatch post-pass to…
carlos-alm Jul 8, 2026
afca17f
fix(resolver): kind-filter same-file bare-name lookup for receiver-be…
carlos-alm Jul 8, 2026
801d290
fix(resolver): attribute new ClassName() calls to the constructor method
carlos-alm Jul 8, 2026
a45e74d
fix(extractors): attribute same-file ES6 getter/setter property reads…
carlos-alm Jul 8, 2026
453a768
fix(resolver): require invocation evidence for object-literal value-r…
carlos-alm Jul 8, 2026
1d957a4
fix(extractors): resolve inline object-literal dispatch tables on WASM
carlos-alm Jul 8, 2026
7355cdd
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 11, 2026
0003dba
fix(benchmark): categorize pts-dispatch-table edges under points-to t…
carlos-alm Jul 11, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 89 additions & 7 deletions src/extractors/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,7 @@ function dispatchQueryMatch(
classes: ClassRelation[],
exps: Export[],
callbackParamShapes: CallbackParamShapes,
arrayElemBindings: ArrayElemBinding[],
): void {
if (c.fn_node) {
handleFnCapture(c, definitions);
Expand Down Expand Up @@ -365,7 +366,7 @@ function dispatchQueryMatch(
if (cbDef) definitions.push(cbDef);
calls.push(...extractCallbackReferenceCalls(c.callmem_node, callbackParamShapes));
} else if (c.callsub_node) {
const callInfo = extractCallInfo(c.callsub_fn!, c.callsub_node);
const callInfo = extractCallInfo(c.callsub_fn!, c.callsub_node, arrayElemBindings);
if (callInfo) calls.push(callInfo);
calls.push(...extractCallbackReferenceCalls(c.callsub_node, callbackParamShapes));
} else if (c.newfn_node) {
Expand Down Expand Up @@ -421,7 +422,16 @@ function extractSymbolsQuery(tree: TreeSitterTree, query: TreeSitterQuery): Extr
// Build capture lookup for this match (1-3 captures each, very fast)
const c: Record<string, TreeSitterNode> = Object.create(null);
for (const cap of match.captures) c[cap.name] = cap.node;
dispatchQueryMatch(c, definitions, calls, imports, classes, exps, callbackParamShapes);
dispatchQueryMatch(
c,
definitions,
calls,
imports,
classes,
exps,
callbackParamShapes,
arrayElemBindings,
);
}

// Extract top-level constants via targeted walk (query patterns don't cover these)
Expand Down Expand Up @@ -1635,7 +1645,7 @@ function handleCallExpr(
ctx.calls.push({ name: 'this', line: nodeStartLine(node) });
return; // no further processing needed for this()-style calls
}
const callInfo = extractCallInfo(fn, node);
const callInfo = extractCallInfo(fn, node, ctx.arrayElemBindings);
if (callInfo) ctx.calls.push(callInfo);
if (fn.type === 'member_expression') {
const cbDef = extractCallbackDefinition(node, fn);
Expand Down Expand Up @@ -3502,7 +3512,11 @@ function extractReceiverName(objNode: TreeSitterNode | null): string | undefined
return objNode.text;
}

function extractCallInfo(fn: TreeSitterNode, callNode: TreeSitterNode): Call | null {
function extractCallInfo(
fn: TreeSitterNode,
callNode: TreeSitterNode,
arrayElemBindings?: ArrayElemBinding[],
): Call | null {
const fnType = fn.type;
if (fnType === 'identifier') {
if (fn.text === 'eval') {
Expand Down Expand Up @@ -3533,7 +3547,7 @@ function extractCallInfo(fn: TreeSitterNode, callNode: TreeSitterNode): Call | n
return extractMemberExprCallInfo(fn, callNode);
}
if (fnType === 'subscript_expression') {
return extractSubscriptCallInfo(fn, callNode);
return extractSubscriptCallInfo(fn, callNode, arrayElemBindings);
}
return null;
}
Expand Down Expand Up @@ -3689,8 +3703,72 @@ function extractMemberExprCallInfo(fn: TreeSitterNode, callNode: TreeSitterNode)
return { name: propText, line: callLine, receiver };
}

/**
* RES-2: inline object-literal dispatch table — `({a:fnA,b:fnB})[key]()`.
*
* Mirrors `extract_dispatch_table_call` in
* `crates/codegraph-core/src/extractors/javascript.rs`. When the subscript's
* object is an object literal (optionally unwrapped from a parenthesized
* expression) and the index is a bare identifier, records each property's
* identifier value as an `ArrayElemBinding` under a synthetic `<dt_line_col>`
* name and returns a `<dt_line_col>[*]` call — the existing points-to
* wildcard resolution path (already used for `const arr = [f1, f2]; arr[i]()`
* patterns) then resolves it to each concrete target identically on both
* engines (#1897).
*
* Returns `null` when the object isn't an object literal, or none of its
* property values are resolvable bare identifiers.
*/
function extractDispatchTableCall(
obj: TreeSitterNode | null,
index: TreeSitterNode,
callNode: TreeSitterNode,
arrayElemBindings: ArrayElemBinding[],
): Call | null {
if (!obj) return null;
// Unwrap parenthesized_expression: ({a:fn})[key]()
const objNode =
obj.type === 'parenthesized_expression'
? (obj.childForFieldName('expression') ?? obj.child(1) ?? obj)
: obj;
if (objNode.type !== 'object') return null;

const line = nodeStartLine(callNode);
const col = callNode.startPosition.column;
const tableName = `<dt_${line}_${col}>`;
let idx = 0;
for (let i = 0; i < objNode.childCount; i++) {
const child = objNode.child(i);
if (!child) continue;
if (child.type === 'shorthand_property_identifier') {
if (!BUILTIN_GLOBALS.has(child.text)) {
arrayElemBindings.push({ arrayName: tableName, index: idx, elemName: child.text });
idx++;
}
} else if (child.type === 'pair') {
const val = child.childForFieldName('value');
if (val?.type === 'identifier' && !BUILTIN_GLOBALS.has(val.text)) {
arrayElemBindings.push({ arrayName: tableName, index: idx, elemName: val.text });
idx++;
}
}
}
if (idx === 0) return null;
return {
name: `${tableName}[*]`,
line,
dynamic: true,
dynamicKind: 'dispatch-table',
keyExpr: index.text,
};
}

/** Extract call info from a subscript_expression function node (obj[key]()). */
function extractSubscriptCallInfo(fn: TreeSitterNode, callNode: TreeSitterNode): Call | null {
function extractSubscriptCallInfo(
fn: TreeSitterNode,
callNode: TreeSitterNode,
arrayElemBindings?: ArrayElemBinding[],
): Call | null {
const obj = fn.childForFieldName('object');
const index = fn.childForFieldName('index');
if (!index) return null;
Expand All @@ -3710,8 +3788,12 @@ function extractSubscriptCallInfo(fn: TreeSitterNode, callNode: TreeSitterNode):
}
}

// obj[variable]() — key is a variable; may be resolvable via pts (RES-1), else flagged
// obj[variable]() — key is a variable; may be resolvable via pts (RES-1/RES-2), else flagged
if (indexType === 'identifier') {
if (arrayElemBindings) {
const dispatchCall = extractDispatchTableCall(obj, index, callNode, arrayElemBindings);
if (dispatchCall) return dispatchCall;
}
const receiver = extractReceiverName(obj);
return {
name: '<dynamic:computed-key>',
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,8 @@ export type DynamicKind =
| 'reflection' // .call/.apply/.bind / Reflect.* / callable-ref — resolved when target is in codebase; sink edge emitted if unresolved
| 'eval' // eval() / new Function() — undecidable; always flagged
| 'unresolved-dynamic' // any other detected dynamic pattern; flagged
| 'value-ref'; // bare identifier used as a value reference rather than a call site — object-literal property value (dispatch-table pattern, e.g. `{ resolve: someFn }`, #1771), assignment to a Lua global/builtin identifier (e.g. `require = tracedRequire`, #1776), or the right operand of an `instanceof` check (e.g. `err instanceof CodegraphError`, #1784) — resolved against function/method/class-kind targets; class was added for instanceof, but the filter is per-kind rather than per-site, so all three sites share the same allow-list; unresolved (e.g. plain data references) are dropped silently, NOT flagged
| 'value-ref' // bare identifier used as a value reference rather than a call site — object-literal property value (dispatch-table pattern, e.g. `{ resolve: someFn }`, #1771), assignment to a Lua global/builtin identifier (e.g. `require = tracedRequire`, #1776), or the right operand of an `instanceof` check (e.g. `err instanceof CodegraphError`, #1784) — resolved against function/method/class-kind targets; class was added for instanceof, but the filter is per-kind rather than per-site, so all three sites share the same allow-list; unresolved (e.g. plain data references) are dropped silently, NOT flagged
| 'dispatch-table'; // inline object-literal subscript dispatch, e.g. `({a:fnA,b:fnB})[key]()` (#1897) — resolved via the points-to wildcard solver against synthetic `<dt_line_col>[*]` array-elem bindings seeded from each property's identifier value; never flagged (excluded from FLAG_ONLY_DYNAMIC_KINDS) so an unresolved table produces no sink edge, matching the named-array `[fn1,fn2][*]` dispatch pattern

/** A function/method call detected by an extractor. */
export interface Call {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// pts-dispatch-table: inline object-literal subscript dispatch {a:fnA,b:fnB}[k]()
function dtFn1() {}
function dtFn2() {}

function runDispatch(key) {
({ a: dtFn1, b: dtFn2 })[key]();
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@
"kind": "calls",
"mode": "pts-spread",
"notes": "y() inside consumer2 — spread consumer2(...[sprFn3, sprFn4]) binds sprFn4 to y"
},
{
"source": { "name": "runDispatch", "file": "dispatch-table.js" },
"target": { "name": "dtFn1", "file": "dispatch-table.js" },
"kind": "calls",
"mode": "pts-dispatch-table",
"notes": "({a:dtFn1,b:dtFn2})[key]() — inline dispatch table; pts resolves wildcard to each value"
},
{
"source": { "name": "runDispatch", "file": "dispatch-table.js" },
"target": { "name": "dtFn2", "file": "dispatch-table.js" },
"kind": "calls",
"mode": "pts-dispatch-table",
"notes": "({a:dtFn1,b:dtFn2})[key]() — inline dispatch table; pts resolves wildcard to each value"
}
]
}
1 change: 1 addition & 0 deletions tests/benchmarks/resolution/resolution-benchmark.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ const TECHNIQUE_MAP: Record<string, string> = {
'pts-array-from': 'points-to',
'pts-spread': 'points-to',
'pts-param': 'points-to',
'pts-dispatch-table': 'points-to',
'define-property': 'ts-native',
};

Expand Down
17 changes: 17 additions & 0 deletions tests/engines/parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,23 @@ router.get('/users/:id', authHandler);
Array.from(arr, mapCallback);
Array.from(arr, mapCallback, thisArg);
Uint8Array.from(arr, mapCallback);
`,
},
{
// Regression guard for #1897: WASM previously had no mirror of native's
// RES-2 inline object-literal dispatch-table detection
// (extract_dispatch_table_call), so `({a:fnA,b:fnB})[key]()` classified
// as a generic flagged computed-key sink on WASM while native resolved
// it via the pts wildcard. Both engines must now emit the exact same
// synthetic `<dt_line_col>[*]` call name (line/col computed identically).
name: 'JavaScript — inline object-literal dispatch table must agree between engines',
file: 'dispatch-table.js',
code: `
function dtFn1() {}
function dtFn2() {}
function runDispatch(key) {
return ({ a: dtFn1, b: dtFn2 })[key]();
}
`,
},
{
Expand Down
17 changes: 17 additions & 0 deletions tests/engines/query-walk-parity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,23 @@ function runDemo(users: string[]): void {
processEach(users, logUser);
findMergeCandidates(users);
}
`,
},
{
// Regression guard for #1897: inline object-literal dispatch-table
// subscript calls (`({a:fnA,b:fnB})[key]()`) must produce the same
// synthetic `<dt_line_col>[*]` call on both extraction paths — the query
// path threads `arrayElemBindings` through `dispatchQueryMatch`'s
// `callsub_node` branch, the walk path through `handleCallExpr`'s
// `ctx.arrayElemBindings`.
name: 'inline object-literal dispatch table (#1897)',
file: 'test.js',
code: `
function fnA() {}
function fnB() {}
function run(key) {
return ({ a: fnA, b: fnB })[key]();
}
`,
},
// TSX
Expand Down
91 changes: 91 additions & 0 deletions tests/parsers/javascript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1656,6 +1656,97 @@ function runDemo(reporter: Reporter, users: string[]): void {
});
});

describe('inline object-literal dispatch table extraction (RES-2, #1897)', () => {
// Mirrors the Rust `dispatch_table_emits_dt_call_and_array_elem_bindings`
// / `dispatch_table_parenthesized_object_also_works` unit tests in
// crates/codegraph-core/src/extractors/javascript.rs.
it('emits a <dt_line_col>[*] call and array-elem bindings for each identifier value', () => {
const symbols = parseJS(`
function dtFn1() {}
function dtFn2() {}
function runDispatch(key) { ({ a: dtFn1, b: dtFn2 })[key](); }
`);
const dtCall = symbols.calls.find(
(c) => c.name.startsWith('<dt_') && c.name.endsWith('>[*]'),
);
expect(dtCall).toBeDefined();
expect(dtCall?.dynamic).toBe(true);
expect(dtCall?.dynamicKind).toBe('dispatch-table');
expect(dtCall?.keyExpr).toBe('key');

const tableName = dtCall!.name.slice(0, -3); // strip trailing "[*]"
expect(symbols.arrayElemBindings).toContainEqual({
arrayName: tableName,
index: 0,
elemName: 'dtFn1',
});
expect(symbols.arrayElemBindings).toContainEqual({
arrayName: tableName,
index: 1,
elemName: 'dtFn2',
});
});

it('also detects the pattern without wrapping parens in a non-ambiguous expression position', () => {
// `{...}` needs parens only where it would otherwise be parsed as a
// block (statement position). In a `return` expression it's already
// unambiguous, so the object node is not wrapped in a
// parenthesized_expression — exercising the non-unwrap branch of
// extractDispatchTableCall, the mirror image of the first test above.
const symbols = parseJS(`
function fnA() {}
function fnB() {}
function run(k) { return { a: fnA, b: fnB }[k](); }
`);
const dtCall = symbols.calls.find(
(c) => c.name.startsWith('<dt_') && c.name.endsWith('>[*]'),
);
expect(dtCall).toBeDefined();
});

it('resolves the shorthand-property form (`{ fnA, fnB }[k]()`)', () => {
const symbols = parseJS(`
function fnA() {}
function fnB() {}
function run(k) { ({ fnA, fnB })[k](); }
`);
const dtCall = symbols.calls.find(
(c) => c.name.startsWith('<dt_') && c.name.endsWith('>[*]'),
);
expect(dtCall).toBeDefined();
const tableName = dtCall!.name.slice(0, -3);
expect(symbols.arrayElemBindings).toContainEqual({
arrayName: tableName,
index: 0,
elemName: 'fnA',
});
expect(symbols.arrayElemBindings).toContainEqual({
arrayName: tableName,
index: 1,
elemName: 'fnB',
});
});

it('falls back to the generic computed-key classification for a non-literal object', () => {
const symbols = parseJS(`function run(handlers, key) { return handlers[key](); }`);
expect(symbols.calls).toContainEqual(
expect.objectContaining({ name: '<dynamic:computed-key>', dynamicKind: 'computed-key' }),
);
expect(symbols.calls.find((c) => c.dynamicKind === 'dispatch-table')).toBeUndefined();
});

it('does not treat a string-literal key on an object literal as a dispatch table', () => {
const symbols = parseJS(`
function fnA() {}
function run() { return ({ a: fnA })['a'](); }
`);
expect(symbols.calls.find((c) => c.dynamicKind === 'dispatch-table')).toBeUndefined();
expect(symbols.calls).toContainEqual(
expect.objectContaining({ name: 'a', dynamicKind: 'computed-literal' }),
);
});
});

describe('instanceof value-ref extraction (#1784)', () => {
it('extracts a value-ref call for `instanceof ClassName`', () => {
const symbols = parseJS(`
Expand Down
37 changes: 37 additions & 0 deletions tests/unit/points-to.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,3 +477,40 @@ describe('buildPointsToMap — maxIterations cap (issue #1753)', () => {
expect(resolveViaPointsTo('a0', pts)).toEqual(['handler']);
});
});

describe('buildPointsToMap — dispatch-table pts constraints (RES-2, #1897)', () => {
it('seeds wildcard for synthetic dispatch-table array elem bindings', () => {
const defNames = new Set(['dtFn1', 'dtFn2']);
const arrayElemBindings = [
{ arrayName: '<dt_5_2>', index: 0, elemName: 'dtFn1' },
{ arrayName: '<dt_5_2>', index: 1, elemName: 'dtFn2' },
];
const pts = buildPointsToMap([], defNames, NO_IMPORTS, undefined, undefined, arrayElemBindings);
expect(resolveViaPointsTo('<dt_5_2>[*]', pts)).toContain('dtFn1');
expect(resolveViaPointsTo('<dt_5_2>[*]', pts)).toContain('dtFn2');
});

it('resolves only identifier values, not string keys', () => {
const defNames = new Set(['fn1']);
const arrayElemBindings = [{ arrayName: '<dt_1_0>', index: 0, elemName: 'fn1' }];
const pts = buildPointsToMap([], defNames, NO_IMPORTS, undefined, undefined, arrayElemBindings);
expect(resolveViaPointsTo('<dt_1_0>[*]', pts)).toEqual(['fn1']);
});

it('two dispatch tables in the same file use distinct synthetic names', () => {
const defNames = new Set(['fnA', 'fnB', 'fnC', 'fnD']);
const arrayElemBindings = [
{ arrayName: '<dt_3_0>', index: 0, elemName: 'fnA' },
{ arrayName: '<dt_3_0>', index: 1, elemName: 'fnB' },
{ arrayName: '<dt_7_0>', index: 0, elemName: 'fnC' },
{ arrayName: '<dt_7_0>', index: 1, elemName: 'fnD' },
];
const pts = buildPointsToMap([], defNames, NO_IMPORTS, undefined, undefined, arrayElemBindings);
expect(resolveViaPointsTo('<dt_3_0>[*]', pts)).toContain('fnA');
expect(resolveViaPointsTo('<dt_3_0>[*]', pts)).toContain('fnB');
expect(resolveViaPointsTo('<dt_3_0>[*]', pts)).not.toContain('fnC');
expect(resolveViaPointsTo('<dt_7_0>[*]', pts)).toContain('fnC');
expect(resolveViaPointsTo('<dt_7_0>[*]', pts)).toContain('fnD');
expect(resolveViaPointsTo('<dt_7_0>[*]', pts)).not.toContain('fnA');
});
});
Loading