Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
109 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
438f2da
fix(extractors): emit per-element definitions for array-pattern destr…
carlos-alm Jul 8, 2026
7b366c8
fix: resolve merge conflicts with main (docs check acknowledged)
carlos-alm Jul 11, 2026
458ace6
fix: format nested rest-pattern test added during merge resolution
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
152 changes: 139 additions & 13 deletions crates/codegraph-core/src/extractors/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1538,14 +1538,11 @@ fn handle_var_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
}
}
}
} else if is_const
&& (name_n.kind() == "identifier" || name_n.kind() == "array_pattern")
&& !in_function_scope
{
} else if is_const && name_n.kind() == "identifier" && !in_function_scope {
// Any other initializer shape becomes a "constant" Definition, regardless of
// complexity (call/member/parenthesized expressions, etc.) — mirroring how
// function declarations are captured regardless of body complexity, and the
// WASM/TS extractor's unconditional identifier + array_pattern branches (#1819).
// WASM/TS extractor's unconditional identifier branch (#1819).
symbols.definitions.push(Definition {
name: node_text(&name_n, source).to_string(),
kind: "constant".to_string(),
Expand All @@ -1559,10 +1556,14 @@ fn handle_var_decl(node: &Node, source: &[u8], symbols: &mut FileSymbols) {
// Phase 8.3f: extract function/arrow properties from object literals and seed
// typeMap composite keys so that this.method() inside Object.defineProperty
// accessor functions can resolve them.
if value_n.kind() == "object" && name_n.kind() == "identifier" {
if value_n.kind() == "object" {
let var_name = node_text(&name_n, source);
extract_object_literal_functions(&value_n, source, var_name, symbols);
}
} else if is_const && name_n.kind() == "array_pattern" && !in_function_scope {
// Array destructuring: `const [x, y] = ...` — one constant Definition per
// bound identifier (#1901). Scope guard mirrors the object_pattern branch above.
extract_array_pattern_bindings(&name_n, source, start_line(node), end_line(node), &mut symbols.definitions);
} else if !is_const && value_n.kind() == "object"
&& is_eligible_object_literal_declarator(&declarator)
{
Expand Down Expand Up @@ -3082,6 +3083,92 @@ fn extract_destructured_bindings(
}
}

/// Extract a per-element "constant" Definition from each bound identifier in
/// an array-destructuring pattern (`const [a, b] = fn()`) — the array-pattern
/// counterpart to `extract_destructured_bindings`'s per-property handling of
/// object patterns (#1773). Each bound name becomes its own resolvable node,
/// superseding the prior single-node-named-by-raw-pattern-text approach
/// (`[a, b]` as one unresolvable node), which was never a real identifier and
/// could never be a call target (#1901). Mirrors the TS extractor's
/// `extractArrayPatternBindings`.
fn extract_array_pattern_bindings(
pattern: &Node,
source: &[u8],
line: u32,
end_line: u32,
definitions: &mut Vec<Definition>,
) {
for i in 0..pattern.child_count() {
let Some(child) = pattern.child(i) else { continue };
match child.kind() {
"identifier" => {
definitions.push(Definition {
name: node_text(&child, source).to_string(),
kind: "constant".to_string(),
line,
end_line: Some(end_line),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
"assignment_pattern" => {
if let Some(left) = child.child_by_field_name("left") {
if left.kind() == "identifier" {
definitions.push(Definition {
name: node_text(&left, source).to_string(),
kind: "constant".to_string(),
line,
end_line: Some(end_line),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
}
}
}
"rest_pattern" | "rest_element" => {
// `rest_pattern`/`rest_element` has no named fields at all (verified
// against tree-sitter-javascript/typescript's node-types.json) — its
// single named child (after the `...` token) is whichever pattern the
// rest binds to. [...rest] binds a plain identifier; [...[a, b]] nests
// another array pattern whose own elements each need their own
// Definition. Scan all children (rather than assuming a fixed index)
// and recurse into a nested array_pattern instead of silently
// dropping it, mirroring extract_js_parameters' own rest_pattern scan.
for j in 0..child.child_count() {
let Some(inner) = child.child(j) else { continue };
match inner.kind() {
"identifier" => {
definitions.push(Definition {
name: node_text(&inner, source).to_string(),
kind: "constant".to_string(),
line,
end_line: Some(end_line),
decorators: None,
complexity: None,
cfg: None,
children: None,
});
break;
}
"array_pattern" => {
// [...[a, b]] — recurse so the nested pattern's own
// bound identifiers each get their own Definition.
extract_array_pattern_bindings(&inner, source, line, end_line, definitions);
break;
}
_ => {}
}
}
}
_ => {}
}
}
}

/// Mirrors `extractReceiverName` in src/extractors/javascript.ts: normalize a
/// call receiver node to a resolvable name. Inline-new (`new Foo().method()`)
/// and single-paren-wrapped new (`(new Foo()).method()`) yield the constructor
Expand Down Expand Up @@ -4732,14 +4819,53 @@ mod tests {
#[test]
fn extracts_const_array_pattern_with_call_expression_initializer() {
// Parity with the identifier case above: array-pattern names must also
// be discoverable regardless of initializer complexity.
// be discoverable regardless of initializer complexity — one
// definition per bound identifier (#1901), not a single node named
// by the raw pattern text.
let s = parse_js("const [a, b] = computePair();");
let def = s
.definitions
.iter()
.find(|d| d.name == "[a, b]")
.unwrap_or_else(|| panic!("[a, b] should be extracted as a definition"));
assert_eq!(def.kind, "constant");
for name in ["a", "b"] {
let def = s
.definitions
.iter()
.find(|d| d.name == name)
.unwrap_or_else(|| panic!("{name} should be extracted as a definition"));
assert_eq!(def.kind, "constant");
}
assert!(!s.definitions.iter().any(|d| d.name == "[a, b]"));
}

#[test]
fn extracts_array_pattern_default_and_rest_bindings_as_own_definitions() {
// #1901: array-pattern default-value and rest bindings each become
// their own "constant" Definition, matching the plain-identifier case.
let s = parse_js("const [a = 1, ...rest] = computeList();");
for name in ["a", "rest"] {
let def = s
.definitions
.iter()
.find(|d| d.name == name)
.unwrap_or_else(|| panic!("{name} should be extracted as a definition"));
assert_eq!(def.kind, "constant");
}
}

#[test]
fn extracts_nested_array_pattern_rest_bindings_as_own_definitions() {
// Greptile review (#2038): a rest element that itself nests another
// array pattern (`...[a, b]`) must recurse into it rather than
// silently skipping — `rest_pattern`/`rest_element` has no "name"
// field in the grammar, so the previous single-identifier check
// dropped the nested bindings entirely.
let s = parse_js("const [x, ...[a, b]] = computeList();");
for name in ["x", "a", "b"] {
let def = s
.definitions
.iter()
.find(|d| d.name == name)
.unwrap_or_else(|| panic!("{name} should be extracted as a definition"));
assert_eq!(def.kind, "constant");
}
assert!(!s.definitions.iter().any(|d| d.name.starts_with('[')));
}

#[test]
Expand Down
81 changes: 64 additions & 17 deletions src/extractors/javascript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -832,14 +832,13 @@ function extractDestructuredDeclarators(
if (binding) cjsRequireBindings.push(binding);
}
} else if (nameN && nameN.type === 'array_pattern') {
// `const [x, y] = ...` — emit a single constant node whose name is the
// full array pattern text (e.g. `[x, y]`), matching native engine behaviour.
definitions.push({
name: nameN.text,
kind: 'constant',
line: nodeStartLine(declNode),
endLine: nodeEndLine(declNode),
});
// `const [x, y] = ...` — one constant Definition per bound identifier (#1901).
extractArrayPatternBindings(
nameN,
nodeStartLine(declNode),
nodeEndLine(declNode),
definitions,
);
}
}
}
Expand Down Expand Up @@ -1383,6 +1382,60 @@ function extractDestructuredBindings(
}
}

/**
* Extract a per-element `constant` Definition from each bound identifier in an
* array-destructuring pattern (`const [a, b] = fn()`) — the array-pattern
* counterpart to `extractDestructuredBindings`'s per-property handling of
* object patterns (#1773). Each bound name becomes its own resolvable node
* (e.g. `a()`, `b()` calls can resolve to `a`/`b` directly), superseding the
* prior single-node-named-by-raw-pattern-text approach (`[a, b]` as one
* unresolvable node), which was never a real identifier and could never be a
* call target (#1901).
*/
function extractArrayPatternBindings(
pattern: TreeSitterNode,
line: number,
endLine: number,
definitions: Definition[],
): void {
for (let i = 0; i < pattern.childCount; i++) {
const child = pattern.child(i);
if (!child) continue;
if (child.type === 'identifier') {
// [a, b] — plain positional binding
definitions.push({ name: child.text, kind: 'constant', line, endLine });
} else if (child.type === 'assignment_pattern') {
// [a = defaultValue] — the bound name is the left-hand identifier
const left = child.childForFieldName('left');
if (left && left.type === 'identifier') {
definitions.push({ name: left.text, kind: 'constant', line, endLine });
}
} else if (child.type === 'rest_pattern' || child.type === 'rest_element') {
// `rest_pattern`/`rest_element` has no named fields at all (verified against
// tree-sitter-javascript/typescript's node-types.json) — its single named
// child (after the `...` token) is whichever pattern the rest binds to.
// [...rest] binds a plain identifier; [...[a, b]] nests another array
// pattern whose own elements each need their own Definition. Scan all
// children (rather than assuming a fixed index) and recurse into a nested
// array_pattern instead of silently dropping it, matching extractParameters'
// own rest_pattern scan.
for (let j = 0; j < child.childCount; j++) {
const inner = child.child(j);
if (!inner) continue;
if (inner.type === 'identifier') {
definitions.push({ name: inner.text, kind: 'constant', line, endLine });
break;
} else if (inner.type === 'array_pattern') {
// [...[a, b]] — recurse so the nested pattern's own bound
// identifiers each get their own Definition.
extractArrayPatternBindings(inner, line, endLine, definitions);
break;
}
}
}
}
}

function handleVariableDecl(node: TreeSitterNode, ctx: ExtractorOutput): void {
const isConst = node.text.startsWith('const ');
for (let i = 0; i < node.childCount; i++) {
Expand Down Expand Up @@ -1436,15 +1489,9 @@ function handleVariableDeclarator(
} else if (isConst && nameN.type === 'object_pattern' && !hasFunctionScopeAncestor(node)) {
handleConstObjectPatternAssignment(node, nameN, valueN, ctx);
} else if (isConst && nameN.type === 'array_pattern' && !hasFunctionScopeAncestor(node)) {
// Array destructuring: `const [x, y] = ...` — emit a single constant node
// whose name is the full array pattern text (e.g. `[x, y]`), matching
// native engine behaviour. Scope guard mirrors the object_pattern branch above.
ctx.definitions.push({
name: nameN.text,
kind: 'constant',
line: nodeStartLine(node),
endLine: nodeEndLine(node),
});
// Array destructuring: `const [x, y] = ...` — one constant Definition per
// bound identifier (#1901). Scope guard mirrors the object_pattern branch above.
extractArrayPatternBindings(nameN, nodeStartLine(node), nodeEndLine(node), ctx.definitions);
}
}

Expand Down
103 changes: 103 additions & 0 deletions tests/integration/issue-1901-array-pattern-definition.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* Integration test for #1901: engine parity for `const [a, b] = fn();`
* top-level array-pattern destructuring.
*
* Root cause: the native Rust extractor (`crates/codegraph-core/src/
* extractors/javascript.rs`, `handle_var_decl`) emitted no `Definition` at
* all for array-pattern name nodes, while the WASM/TS extractor
* (`src/extractors/javascript.ts`, both the walk path in
* `handleVariableDeclarator` and the query path in
* `extractDestructuredDeclarators`) emitted a single `Definition` whose
* `name` was the raw pattern source text (e.g. `"[a, b]"`) — not a real
* identifier, and never itself a valid call target.
*
* Fix: both engines now emit one `constant`-kind `Definition` per bound
* identifier (`a`, `b`, ...), mirroring how object-pattern destructuring
* already works per-property (#1773) — via `extractArrayPatternBindings`
* (WASM/TS) and `extract_array_pattern_bindings` (native).
*/

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { buildGraph } from '../../src/domain/graph/builder.js';
import { isNativeAvailable } from '../../src/infrastructure/native.js';

const FIXTURE = {
'sample.js': `
function getArr() { return [1, 2]; }
const [a, b] = getArr();
console.log(a, b);

function withDefaultsAndRest() { return [1, 2, 3]; }
const [c = 0, ...rest] = withDefaultsAndRest();
console.log(c, rest);
`,
};

function readNode(dbPath: string, file: string, name: string) {
const db = new Database(dbPath, { readonly: true });
try {
return db.prepare('SELECT name, kind FROM nodes WHERE file = ? AND name = ?').get(file, name) as
| { name: string; kind: string }
| undefined;
} finally {
db.close();
}
}

function expectPerElementBindings(dbPath: string) {
for (const name of ['a', 'b', 'c', 'rest']) {
const node = readNode(dbPath, 'sample.js', name);
expect(node, `${name} node not found`).toBeDefined();
expect(node!.kind, `${name} must be kind constant`).toBe('constant');
}
// The old single-node-named-by-raw-pattern-text approach must be gone.
expect(readNode(dbPath, 'sample.js', '[a, b]')).toBeUndefined();
expect(readNode(dbPath, 'sample.js', '[c = 0, ...rest]')).toBeUndefined();
}

describe('array-pattern destructuring Definition extraction (#1901) — WASM', () => {
let tmpDir: string;

beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1901-wasm-'));
for (const [rel, content] of Object.entries(FIXTURE)) {
fs.writeFileSync(path.join(tmpDir, rel), content);
}
await buildGraph(tmpDir, { engine: 'wasm', incremental: false, skipRegistry: true });
});

afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('extracts one constant definition per bound identifier', () => {
expectPerElementBindings(path.join(tmpDir, '.codegraph', 'graph.db'));
});
});

describe.skipIf(!isNativeAvailable())(
'array-pattern destructuring Definition extraction (#1901) — native',
() => {
let tmpDir: string;

beforeAll(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-1901-native-'));
for (const [rel, content] of Object.entries(FIXTURE)) {
fs.writeFileSync(path.join(tmpDir, rel), content);
}
await buildGraph(tmpDir, { engine: 'native', incremental: false, skipRegistry: true });
}, 60_000);

afterAll(() => {
fs.rmSync(tmpDir, { recursive: true, force: true });
});

it('extracts one constant definition per bound identifier (previously emitted none)', () => {
expectPerElementBindings(path.join(tmpDir, '.codegraph', 'graph.db'));
});
},
);
Loading
Loading