Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(python): carry bare-call parameter bindings in the walk

Martin Vogel97517a4652f3
diff --git a/internal/cbm/extract_calls.c b/internal/cbm/extract_calls.c
index cb81fc543..b481fab6d 100644
--- a/internal/cbm/extract_calls.c
+++ b/internal/cbm/extract_calls.c
@@ -2970,28 +2970,8 @@ static bool python_receiver_is_exempt(CBMExtractCtx *ctx, TSNode receiver) {
* a bare `identifier`, the `name` field of default/typed parameters, and the
* identifier under a `*args` / `**kwargs` splat. A shape with no identifier (the
* bare `*` keyword separator) yields NULL and simply matches nothing. */
-static const char *python_parameter_name(CBMExtractCtx *ctx, TSNode param) {
- if (ts_node_is_null(param)) {
- return NULL;
- }
- if (strcmp(ts_node_type(param), "identifier") == 0) {
- return cbm_node_text(ctx->arena, param, ctx->source);
- }
- TSNode name = ts_node_child_by_field_name(param, TS_FIELD("name"));
- if (!ts_node_is_null(name) && strcmp(ts_node_type(name), "identifier") == 0) {
- return cbm_node_text(ctx->arena, name, ctx->source);
- }
- /* `*args` / `**kwargs`, and any typed shape without a `name` field: the
- * bound identifier is the first named child. */
- TSNode first = ts_node_named_child(param, 0);
- if (!ts_node_is_null(first) && strcmp(ts_node_type(first), "identifier") == 0) {
- return cbm_node_text(ctx->arena, first, ctx->source);
- }
- return NULL;
-}
-
/* True when the callee of a BARE Python call `foo()` is bound as a parameter of
- * an enclosing function or lambda — the bare-call counterpart of
+ * an enclosing function or lambda -- the bare-call counterpart of
* python_receiver_is_exempt above.
*
* A parameter binding shadows any module-level `foo` for the whole body, so
@@ -2999,92 +2979,25 @@ static const char *python_parameter_name(CBMExtractCtx *ctx, TSNode param) {
* fabricates the edge BY CONSTRUCTION: `def _run_with_heavy_slot(run): run()`
* must not bind an unrelated `SatoriLive.run`. Unlike a receiver type this is
* decidable from the AST outright, with no flow analysis and no list of
- * "generic-looking" callee names — Python forbids `global` on a parameter, and a
- * parameter is in scope for the entire body regardless of position, so there is
- * no ordering subtlety to get wrong.
- *
- * Enclosing scopes are walked to the file root so a closure over an outer
- * parameter counts (`def outer(run): def inner(): return run()`).
+ * "generic-looking" callee names -- Python forbids `global` on a parameter, and
+ * a parameter is in scope for the entire body regardless of position.
*
- * LOCAL ASSIGNMENTS are deliberately NOT covered. They are flow- and
- * binding-form-sensitive (`for`, `with ... as`, `except ... as`, `:=`,
- * unpacking, plus `global`/`nonlocal` overrides), so a partial body scan would
- * suppress the wrong edges invisibly — the same failure mode that rules out a
- * hardcoded name list. Parameters alone already cover the Callable-parameter
- * shape that motivated this guard. Cost is O(enclosing depth x params) per bare
- * call, never the corpus.
+ * The answer is CARRIED BY THE WALK rather than recomputed here. The unified
+ * walk binds a def's or lambda's parameters when it opens that scope and
+ * unwinds them when it closes it, so this is an O(1) map lookup. Deciding it
+ * by ascending the tree instead -- with ts_node_parent() or with a copied walk
+ * cursor -- costs O(depth) per call, and since every level of f(f(f(...))) is
+ * itself a bare call, that is quadratic across the file: the 30,000-deep
+ * fixture in tests/test_stack_overflow.c turned it into a hang rather than a
+ * slowdown. An O(1) lookup needs no hop cap, so unlike a capped walk this can
+ * no longer fail open on deep-but-ordinary code.
*
- * Known and accepted: `def inner(): global run; return run()` nested in a
- * function whose parameter is `run` is still flagged. Detecting it needs exactly
- * the body scan this helper avoids, and it costs one edge in a shape that
- * essentially does not occur. */
-static bool python_callee_is_bound_parameter(CBMExtractCtx *ctx, WalkState *state, TSNode call_node,
+ * It still answers false if the walk's own tracking hit an allocation failure,
+ * which costs a suppression and never a true edge. */
+static bool python_callee_is_bound_parameter(CBMExtractCtx *ctx, WalkState *state,
TSNode callee_ident) {
- /* Ancestors are walked with the UNIFIED WALK'S OWN CURSOR, not ts_node_parent().
- *
- * ts_node_parent() is not O(1): it restarts at the tree root and descends to
- * find the parent (vendored ts_runtime/src/node.c), so it costs O(depth) per
- * hop. A parent-chain walk is therefore O(depth^2) per call, and since every
- * level of f(f(f(...))) is ITSELF a bare call, O(depth^3) across the file --
- * tests/test_stack_overflow.c nests 30,000 deep, which is a hang, not a
- * slowdown. Capping the hop COUNT does not fix that, because the cost is per
- * hop; the walk itself has to be cheap.
- *
- * ts_tree_cursor_goto_parent() IS O(1) -- the cursor carries its path stack --
- * so copying the walk cursor and ascending costs nothing per hop. Same reason
- * CBMWalkScope keeps a frame stack instead of recomputing enclosing state, and
- * same current_cursor idiom (including the identity guard) as
- * usage_current_field_name in extract_usages.c.
- *
- * The hop cap then bounds the remaining O(depth) per call. 64 rather than
- * Lean's 20 above: that walk looks for an IMMEDIATE declaration boundary,
- * while this one crosses whatever statement/expression nesting separates a
- * call from its enclosing def, so it needs headroom before it can bite on
- * ordinary code.
- *
- * Both the cap and a missing/mismatched cursor FAIL OPEN -- return false, do
- * NOT suppress. A guard whose whole justification is precision must never
- * destroy an edge it did not actually prove was fabricated, so either can
- * only ever cost a suppression, never a true edge. Pinned in
- * test_extraction.c. */
- enum { PY_MAX_SCOPE_WALK_DEPTH = 64 };
-
const char *callee_name = cbm_node_text(ctx->arena, callee_ident, ctx->source);
- if (!callee_name || !callee_name[0]) {
- return false;
- }
- /* Only trust the shared cursor when it is actually parked on this call. */
- if (!state || !state->current_cursor ||
- !ts_node_eq(ts_tree_cursor_current_node(state->current_cursor), call_node)) {
- return false;
- }
-
- TSTreeCursor up = ts_tree_cursor_copy(state->current_cursor);
- bool bound = false;
- for (int walked = 0; walked < PY_MAX_SCOPE_WALK_DEPTH && !bound; walked++) {
- if (!ts_tree_cursor_goto_parent(&up)) {
- break;
- }
- TSNode scope = ts_tree_cursor_current_node(&up);
- const char *kind = ts_node_type(scope);
- if (strcmp(kind, "function_definition") != 0 && strcmp(kind, "lambda") != 0) {
- continue;
- }
- TSNode params = ts_node_child_by_field_name(scope, TS_FIELD("parameters"));
- if (ts_node_is_null(params)) {
- continue;
- }
- uint32_t count = ts_node_named_child_count(params);
- for (uint32_t i = 0; i < count; i++) {
- const char *pname = python_parameter_name(ctx, ts_node_named_child(params, i));
- if (pname && strcmp(pname, callee_name) == 0) {
- bound = true;
- break;
- }
- }
- }
- ts_tree_cursor_delete(&up);
- return bound;
+ return cbm_walk_python_param_is_bound(state, callee_name);
}
static bool is_objectscript_language(CBMLanguage language) {
@@ -3722,8 +3635,7 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
TSNode obj = ts_node_child_by_field_name(fn, TS_FIELD("object"));
call.is_method = !python_receiver_is_exempt(ctx, obj);
} else if (!ts_node_is_null(fn) && strcmp(ts_node_type(fn), "identifier") == 0) {
- call.callee_is_locally_bound =
- python_callee_is_bound_parameter(ctx, state, node, fn);
+ call.callee_is_locally_bound = python_callee_is_bound_parameter(ctx, state, fn);
}
}
// TS/JS/TSX receiver-aware guard (#592/#606 direction; same intent
diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.c
index a5e314272..5c2905f9c 100644
--- a/internal/cbm/extract_unified.c
+++ b/internal/cbm/extract_unified.c
@@ -119,11 +119,196 @@ static uint32_t add_lexical_scope(WalkState *state, TSNode node, CBMLexicalScope
return scope->id;
}
+/* ── #1912: Python parameter bindings held live by the walk ───────────────────
+ *
+ * A bare Python call `run()` cannot honestly resolve to a project function by
+ * short name when `run` is bound as a parameter of an enclosing def or lambda:
+ * the parameter shadows any module-level `run` for the whole body, so the match
+ * is fabricated by construction.
+ *
+ * Deciding that per call by ASCENDING the tree is the trap this replaces. Both
+ * ts_node_parent() (O(depth) per hop) and a walk-cursor ascent (O(1) per hop,
+ * O(depth) per call) are per-call costs, and every level of f(f(f(...))) is
+ * itself a bare call, so the file-wide cost is quadratic or worse -- exactly
+ * what CBMWalkScope's comment records for the state it replaced. Scanning the
+ * frame stack has the same shape.
+ *
+ * So the walk carries the answer instead: a name -> active-count map, pushed
+ * when a Python function or lambda scope opens and unwound when it closes.
+ * Lookup is O(1), which is what removes the need for a hop cap.
+ *
+ * A COUNT, not a flag: `def outer(run): def inner(run):` binds one name twice,
+ * and leaving the inner scope must not unbind the outer one.
+ *
+ * Every failure path answers "not bound", which can only ever cost a
+ * suppression -- never a true edge. */
+
+static uint32_t py_param_hash(const char *s) {
+ uint32_t h = 2166136261u; /* FNV-1a */
+ for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
+ h = (h ^ *p) * 16777619u;
+ }
+ return h ? h : 1u; /* 0 marks an empty slot */
+}
+
+static CBMParamSlot *py_param_slot(WalkState *state, const char *name, uint32_t hash) {
+ int mask = state->py_param_slot_capacity - 1;
+ int i = (int)(hash & (uint32_t)mask);
+ for (;;) {
+ CBMParamSlot *slot = &state->py_param_slots[i];
+ if (slot->hash == 0) {
+ return slot; /* free slot -- caller decides whether to claim it */
+ }
+ if (slot->hash == hash && strcmp(slot->name, name) == 0) {
+ return slot;
+ }
+ i = (i + 1) & mask;
+ }
+}
+
+static bool py_param_grow(WalkState *state) {
+ int new_capacity = state->py_param_slot_capacity * PAIR_LEN;
+ if (new_capacity <= state->py_param_slot_capacity) {
+ return false;
+ }
+ CBMParamSlot *grown =
+ (CBMParamSlot *)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ return false;
+ }
+ memset(grown, 0, (size_t)new_capacity * sizeof(*grown));
+ CBMParamSlot *old = state->py_param_slots;
+ int old_capacity = state->py_param_slot_capacity;
+ state->py_param_slots = grown;
+ state->py_param_slot_capacity = new_capacity;
+ for (int i = 0; i < old_capacity; i++) {
+ if (old[i].hash != 0) {
+ *py_param_slot(state, old[i].name, old[i].hash) = old[i];
+ }
+ }
+ return true;
+}
+
+static bool py_param_stack_reserve(WalkState *state) {
+ if (state->py_param_stack_count < state->py_param_stack_capacity) {
+ return true;
+ }
+ int new_capacity = state->py_param_stack_capacity * PAIR_LEN;
+ if (new_capacity <= state->py_param_stack_capacity) {
+ return false;
+ }
+ const char **grown =
+ (const char **)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ return false;
+ }
+ memcpy(grown, state->py_param_stack, (size_t)state->py_param_stack_count * sizeof(*grown));
+ state->py_param_stack = grown;
+ state->py_param_stack_capacity = new_capacity;
+ return true;
+}
+
+/* Bind one parameter name for the lifetime of the frame currently on top. */
+static void py_param_bind(WalkState *state, const char *name) {
+ if (state->py_param_tracking_failed || !name || !name[0]) {
+ return;
+ }
+ /* Grow before inserting: the probe below must always find a free slot, and
+ * a table above ~70% load degrades toward linear probing. */
+ if ((state->py_param_slot_used + 1) * 10 >= state->py_param_slot_capacity * 7) {
+ if (!py_param_grow(state)) {
+ state->py_param_tracking_failed = true;
+ return;
+ }
+ }
+ if (!py_param_stack_reserve(state)) {
+ state->py_param_tracking_failed = true;
+ return;
+ }
+ uint32_t hash = py_param_hash(name);
+ CBMParamSlot *slot = py_param_slot(state, name, hash);
+ if (slot->hash == 0) {
+ slot->hash = hash;
+ slot->name = name;
+ slot->count = 0;
+ state->py_param_slot_used++;
+ }
+ slot->count++;
+ state->py_param_stack[state->py_param_stack_count++] = name;
+}
+
+/* Unwind to a frame's entry height, undoing exactly what that frame bound. */
+static void py_param_unwind_to(WalkState *state, int base) {
+ if (state->py_param_tracking_failed) {
+ return;
+ }
+ while (state->py_param_stack_count > base) {
+ const char *name = state->py_param_stack[--state->py_param_stack_count];
+ CBMParamSlot *slot = py_param_slot(state, name, py_param_hash(name));
+ if (slot->hash != 0 && slot->count > 0) {
+ slot->count--;
+ }
+ }
+}
+
+bool cbm_walk_python_param_is_bound(const WalkState *state, const char *name) {
+ if (!state || !name || !name[0] || state->py_param_tracking_failed ||
+ state->py_param_slot_used == 0) {
+ return false;
+ }
+ const CBMParamSlot *slot = py_param_slot((WalkState *)state, name, py_param_hash(name));
+ return slot->hash != 0 && slot->count > 0;
+}
+
+/* The identifier a Python parameter node binds. Handles the bare, typed,
+ * defaulted, keyword-only, *args and **kwargs shapes. */
+static const char *py_parameter_name(CBMExtractCtx *ctx, TSNode param) {
+ if (ts_node_is_null(param)) {
+ return NULL;
+ }
+ if (strcmp(ts_node_type(param), "identifier") == 0) {
+ return cbm_node_text(ctx->arena, param, ctx->source);
+ }
+ TSNode name = ts_node_child_by_field_name(param, TS_FIELD("name"));
+ if (!ts_node_is_null(name) && strcmp(ts_node_type(name), "identifier") == 0) {
+ return cbm_node_text(ctx->arena, name, ctx->source);
+ }
+ /* `*args` / `**kwargs`, and any typed shape without a `name` field: the
+ * bound identifier is the first named child. */
+ TSNode first = ts_node_named_child(param, 0);
+ if (!ts_node_is_null(first) && strcmp(ts_node_type(first), "identifier") == 0) {
+ return cbm_node_text(ctx->arena, first, ctx->source);
+ }
+ return NULL;
+}
+
+/* Bind this node's parameters into the frame just pushed for it. Called after
+ * every push in push_boundary_scopes, so the top frame is this node's own and
+ * pop_expired_scopes unwinds them at exactly the right depth. */
+static void py_bind_scope_parameters(CBMExtractCtx *ctx, TSNode node, WalkState *state) {
+ if (ctx->language != CBM_LANG_PYTHON || state->scope_top == 0) {
+ return;
+ }
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "function_definition") != 0 && strcmp(kind, "lambda") != 0) {
+ return;
+ }
+ TSNode params = ts_node_child_by_field_name(node, TS_FIELD("parameters"));
+ if (ts_node_is_null(params)) {
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(params);
+ for (uint32_t i = 0; i < count; i++) {
+ py_param_bind(state, py_parameter_name(ctx, ts_node_named_child(params, i)));
+ }
+}
+
static bool push_scope(WalkState *state, uint8_t kind, uint32_t depth, const char *qn) {
if (!ensure_scope_capacity(state)) {
return false;
}
CBMWalkScope *f = &state->scopes[state->scope_top];
+ f->prev_py_param_stack_count = state->py_param_stack_count;
f->kind = kind;
f->depth = depth;
f->qn = qn;
@@ -260,6 +445,7 @@ static void pop_expired_scopes(WalkState *state, uint32_t cur_depth) {
state->inside_import = f->prev_inside_import;
state->loop_depth = f->prev_loop_depth;
state->branch_depth = f->prev_branch_depth;
+ py_param_unwind_to(state, f->prev_py_param_stack_count);
}
}
@@ -2354,6 +2540,7 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
}
push_lexical_boundary(node, state, depth);
+ py_bind_scope_parameters(ctx, node, state);
push_call_scope(state, depth, invocation);
if (is_actual_import_boundary(ctx, node, spec) && !is_export_of_declaration(node)) {
push_scope(state, SCOPE_IMPORT, depth, NULL);
@@ -2387,6 +2574,14 @@ void cbm_extract_unified(CBMExtractCtx *ctx) {
state.scope_capacity = MAX_SCOPES;
state.lexical_scopes = state.inline_lexical_scopes;
state.lexical_scope_capacity = INLINE_LEXICAL_SCOPES;
+ state.py_param_slots = state.inline_py_param_slots;
+ state.py_param_slot_capacity = INLINE_PY_PARAM_SLOTS;
+ state.py_param_slot_used = 0;
+ memset(state.inline_py_param_slots, 0, sizeof(state.inline_py_param_slots));
+ state.py_param_stack = state.inline_py_param_stack;
+ state.py_param_stack_capacity = INLINE_PY_PARAM_STACK;
+ state.py_param_stack_count = 0;
+ state.py_param_tracking_failed = false;
state.usage_start_index = ctx->result->usages.count;
state.root_lexical_scope_id = add_lexical_scope(&state, ctx->root, CBM_LEXICAL_SCOPE_MODULE);
/* Base walk-state tuple (previously established by the first
diff --git a/internal/cbm/extract_unified.h b/internal/cbm/extract_unified.h
index 820d2dc0a..f80237229 100644
--- a/internal/cbm/extract_unified.h
+++ b/internal/cbm/extract_unified.h
@@ -18,6 +18,8 @@
#define INLINE_LEXICAL_SCOPES 64
#define INLINE_LEXICAL_BINDINGS 64
#define INLINE_PYTHON_DIRECTIVES 16
+#define INLINE_PY_PARAM_SLOTS 64
+#define INLINE_PY_PARAM_STACK 64
// ObjectScript type map: variable name → class name (for instance_method_call
// resolution). Stack-allocated, per-method scope. Overflow is silent (no crash).
@@ -51,6 +53,15 @@ typedef struct {
bool raw_call_emitted;
} CBMInvocationDescriptor;
+/* One name bound as a function/lambda parameter by a scope currently OPEN on
+ * the walk stack. A count, not a flag: `def outer(run): def inner(run):` binds
+ * the same name twice and the inner pop must not unbind the outer. */
+typedef struct {
+ const char *name;
+ uint32_t hash;
+ int count;
+} CBMParamSlot;
+
typedef struct {
const char *qn;
uint32_t depth;
@@ -73,6 +84,9 @@ typedef struct {
bool prev_inside_import;
int prev_loop_depth;
int prev_branch_depth;
+ /* #1912: py_param_stack height on entry. Pop unwinds back to it, so a
+ * frame unbinds exactly the parameters it bound and nothing else. */
+ int prev_py_param_stack_count;
} CBMWalkScope;
typedef enum {
@@ -158,11 +172,43 @@ typedef struct {
CBMPythonDirective inline_python_directives[INLINE_PYTHON_DIRECTIVES];
int python_directive_capacity;
int python_directive_count;
+ /* #1912 -- Python bare-call shadowing. A name bound as a parameter by ANY
+ * enclosing function or lambda shadows every project function, so a bare
+ * `run()` under `def outer(run)` cannot honestly resolve by short name.
+ *
+ * Maintained as a live name->count map pushed and popped BY THE WALK, not
+ * recomputed per call. Walking ancestors (either ts_node_parent or a
+ * cursor) and scanning the frame stack are both O(depth) per call, and
+ * since every level of f(f(f(...))) is itself a bare call that is
+ * quadratic across the file -- the same trap CBMWalkScope records above.
+ * Lookup here is O(1), so no hop cap and no fail-open cap are needed.
+ *
+ * The other binding table (CBMLexicalBinding) cannot serve this: it is
+ * qsort-ed in cbm_finalize_lexical_usages AFTER the walk and its
+ * active_end stays 0 until then, so its binary search is invalid from
+ * handle_calls, which runs mid-walk and before handle_usages. */
+ CBMParamSlot *py_param_slots;
+ CBMParamSlot inline_py_param_slots[INLINE_PY_PARAM_SLOTS];
+ int py_param_slot_capacity;
+ int py_param_slot_used;
+ const char **py_param_stack;
+ const char *inline_py_param_stack[INLINE_PY_PARAM_STACK];
+ int py_param_stack_capacity;
+ int py_param_stack_count;
+ /* Allocation failure: stop tracking and answer "not bound" forever after,
+ * which can only cost a suppression, never a true edge. */
+ bool py_param_tracking_failed;
+
CBMLanguage language;
os_type_map_t os_type_map; // ObjectScript variable → type mapping
} WalkState;
+/* #1912: is `name` bound as a parameter by a Python function or lambda scope
+ * currently open on the walk stack? O(1). Answers false on any failure, so a
+ * caller can only ever lose a suppression, never a true edge. */
+bool cbm_walk_python_param_is_bound(const WalkState *state, const char *name);
+
// Per-node handler prototypes. Each is called once per node during the
// unified cursor walk, replacing the old recursive walk_* functions.
CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
diff --git a/tests/test_extraction.c b/tests/test_extraction.c
index 654bfe406..55000a395 100644
--- a/tests/test_extraction.c
+++ b/tests/test_extraction.c
@@ -1225,19 +1225,18 @@ TEST(form_procedure) {
/* --- Oracle PL/SQL --- */
TEST(plsql_package_and_call) {
- const char *src =
- "CREATE OR REPLACE PACKAGE BODY emp_pkg AS\n"
- " FUNCTION hire(p_name VARCHAR2) RETURN NUMBER IS\n"
- " v_sal NUMBER;\n"
- " BEGIN\n"
- " v_sal := util_pkg.calc_salary(p_name);\n"
- " IF v_sal > 0 THEN\n"
- " RETURN v_sal;\n"
- " END IF;\n"
- " RAISE no_data_found;\n"
- " END;\n"
- "END emp_pkg;\n"
- "/\n";
+ const char *src = "CREATE OR REPLACE PACKAGE BODY emp_pkg AS\n"
+ " FUNCTION hire(p_name VARCHAR2) RETURN NUMBER IS\n"
+ " v_sal NUMBER;\n"
+ " BEGIN\n"
+ " v_sal := util_pkg.calc_salary(p_name);\n"
+ " IF v_sal > 0 THEN\n"
+ " RETURN v_sal;\n"
+ " END IF;\n"
+ " RAISE no_data_found;\n"
+ " END;\n"
+ "END emp_pkg;\n"
+ "/\n";
CBMFileResult *r = extract(src, CBM_LANG_PLSQL, "t", "emp_pkg.pkb");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
@@ -2202,9 +2201,10 @@ TEST(dbt_source_and_two_arg_ref) {
/* Both dbt builtins name the relation in their LAST string argument:
* source('group','table') -> table, and the two-argument
* ref('package','model') form -> model. */
- CBMFileResult *r = extract("SELECT * FROM {{ source('raw', 'customers') }}\n"
- "UNION ALL SELECT * FROM {{ ref('analytics', 'legacy_customers') }}\n",
- CBM_LANG_SQL, "t", "models/stg_customers.sql");
+ CBMFileResult *r =
+ extract("SELECT * FROM {{ source('raw', 'customers') }}\n"
+ "UNION ALL SELECT * FROM {{ ref('analytics', 'legacy_customers') }}\n",
+ CBM_LANG_SQL, "t", "models/stg_customers.sql");
ASSERT_NOT_NULL(r);
ASSERT(has_def(r, "Model", "stg_customers"));
ASSERT(has_usage(r, "customers"));
@@ -3276,8 +3276,8 @@ TEST(vue_embedded_structure_negative_controls_issue1410) {
}
TEST(vue_embedded_structure_host_controls_issue1410) {
- CBMFileResult *plain = extract("function plainTs(): void { target(); }\n", CBM_LANG_TYPESCRIPT,
- "t", "plain.ts");
+ CBMFileResult *plain =
+ extract("function plainTs(): void { target(); }\n", CBM_LANG_TYPESCRIPT, "t", "plain.ts");
ASSERT_NOT_NULL(plain);
ASSERT_FALSE(plain->has_error);
ASSERT_EQ(count_defs_named(plain, "Function", "plainTs"), 1);
@@ -3735,11 +3735,11 @@ TEST(extract_java_method_annotations_issue382) {
/* ── ArkTS (HarmonyOS .ets) ─────────────────────────────────────── */
TEST(arkts_component_struct) {
- CBMFileResult *r = extract(
- "@Entry\n@Component\nstruct Index {\n @State message: string = 'Hello'\n\n"
- " build() {\n Column() {\n Text(this.message).fontSize(20)\n }\n"
- " .width('100%')\n }\n}\n",
- CBM_LANG_ARKTS, "t", "Index.ets");
+ CBMFileResult *r =
+ extract("@Entry\n@Component\nstruct Index {\n @State message: string = 'Hello'\n\n"
+ " build() {\n Column() {\n Text(this.message).fontSize(20)\n }\n"
+ " .width('100%')\n }\n}\n",
+ CBM_LANG_ARKTS, "t", "Index.ets");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT(has_def(r, "Struct", "Index"));
@@ -3770,12 +3770,12 @@ TEST(arkts_exported_struct_decorators) {
}
TEST(arkts_member_decorators) {
- CBMFileResult *r = extract(
- "@Component\nstruct S {\n @State a: number = 0\n @Prop b: string\n"
- " @Link c: boolean\n @Provide('k') d: string = ''\n @Consume('k') e: string\n"
- " @StorageLink('s') f: number = 1\n @State @Watch('onW') g: boolean = false\n\n"
- " build() {\n }\n}\n",
- CBM_LANG_ARKTS, "t", "S.ets");
+ CBMFileResult *r =
+ extract("@Component\nstruct S {\n @State a: number = 0\n @Prop b: string\n"
+ " @Link c: boolean\n @Provide('k') d: string = ''\n @Consume('k') e: string\n"
+ " @StorageLink('s') f: number = 1\n @State @Watch('onW') g: boolean = false\n\n"
+ " build() {\n }\n}\n",
+ CBM_LANG_ARKTS, "t", "S.ets");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT(decorators_contain(find_def_by_name(r, "a"), "State"));
@@ -3815,11 +3815,11 @@ TEST(arkts_no_phantom_builtin_defs) {
}
TEST(arkts_builder_extend_styles) {
- CBMFileResult *r = extract(
- "@Builder\nfunction card(t: string) {\n Column() {\n Text(t)\n }\n}\n\n"
- "@Extend(Text)\nfunction fancy(size: number) {\n .fontSize(size)\n}\n\n"
- "@Styles\nfunction pressed() {\n .backgroundColor('#eee')\n}\n",
- CBM_LANG_ARKTS, "t", "b.ets");
+ CBMFileResult *r =
+ extract("@Builder\nfunction card(t: string) {\n Column() {\n Text(t)\n }\n}\n\n"
+ "@Extend(Text)\nfunction fancy(size: number) {\n .fontSize(size)\n}\n\n"
+ "@Styles\nfunction pressed() {\n .backgroundColor('#eee')\n}\n",
+ CBM_LANG_ARKTS, "t", "b.ets");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT(has_def(r, "Function", "card"));
@@ -4903,17 +4903,22 @@ TEST(extract_python_bare_call_flags_locally_bound_callee) {
PASS();
}
-/* The scope walk behind the bare-call flag is BOUNDED (64 ancestors). An
- * unbounded walk is QUADRATIC in a file's nesting depth -- every level of
- * f(f(f(...))) is itself a bare call re-walking its own chain -- which hung
- * stack_overflow_b's 30,000-deep fixture rather than merely slowing it.
+/* The bare-call flag is DEPTH-INDEPENDENT, and the binding is UNWOUND when its
+ * scope closes.
*
- * This pins the cap's CONTRACT deterministically rather than by wall clock (a
- * timing assertion would be a lottery, not a gate): within the cap the shadowed
- * callee is flagged; past it the guard FAILS OPEN and leaves the call alone, so
- * the cap can only ever cost a suppression, never a true edge. Removing the cap
- * flips the deep case to flagged and fails this test. */
-TEST(extract_python_bare_call_scope_walk_is_bounded) {
+ * Both properties come from the same design decision. The answer is carried by
+ * the unified walk -- parameters are bound when a def or lambda scope opens and
+ * unwound when it closes -- rather than recomputed per call by ascending the
+ * tree. An ascending walk is O(depth) per call, and every level of f(f(f(...)))
+ * is itself a bare call, so it is quadratic in a file's nesting depth; that hung
+ * stack_overflow_b's 30,000-deep fixture rather than merely slowing it. An
+ * earlier cut capped the ascent at 64 ancestors and FAILED OPEN past it, which
+ * silently stopped suppressing on deep-but-ordinary code.
+ *
+ * Pinned deterministically rather than by wall clock -- a timing assertion would
+ * be a lottery, not a gate. The depth case fails if a cap is reintroduced; the
+ * unwind case fails if a frame's bindings outlive its scope. */
+TEST(extract_python_bare_call_flag_is_depth_independent) {
/* Shallow: return_statement / block / function_definition — 3 ancestors. */
CBMFileResult *shallow = extract("def shallow(handler):\n"
" return handler()\n",
@@ -4931,9 +4936,9 @@ TEST(extract_python_bare_call_scope_walk_is_bounded) {
ASSERT_EQ(shallow_seen, 1);
cbm_free_result(shallow);
- /* Deep: 200 parenthesized_expression ancestors put the SAME call well past
- * the cap, so the enclosing parameter is never reached and the call stays
- * unflagged. */
+ /* Deep: 200 parenthesized_expression ancestors separate the SAME call from
+ * its enclosing def. The parameter still shadows it, so it stays flagged --
+ * depth changes nothing. This is the case a 64-ancestor cap got wrong. */
const int PARENS = 200;
size_t sz = (size_t)PARENS * 2 + 128;
char *src = malloc(sz);
@@ -4955,12 +4960,51 @@ TEST(extract_python_bare_call_scope_walk_is_bounded) {
const char *cn = deep->calls.items[i].callee_name;
if (cn && strcmp(cn, "handler") == 0) {
deep_seen++;
- ASSERT_FALSE(deep->calls.items[i].callee_is_locally_bound);
+ ASSERT_TRUE(deep->calls.items[i].callee_is_locally_bound);
}
}
ASSERT_EQ(deep_seen, 1);
cbm_free_result(deep);
free(src);
+
+ /* Unwind: `handler` is a parameter of shadowed() and a module-level function
+ * of the same name. The call INSIDE shadowed() is flagged; the call in
+ * sibling(), after that scope closed, must NOT be — it really does resolve
+ * to the module-level def. A binding that outlived its frame would flag it
+ * and destroy a true edge, which is the one direction this guard must never
+ * fail in. Nested same-name defs also pin the count: leaving the inner scope
+ * must not unbind the outer one. */
+ CBMFileResult *unwound = extract("def handler():\n"
+ " return 1\n"
+ "\n"
+ "def shadowed(handler):\n"
+ " def inner(handler):\n"
+ " return handler()\n"
+ " return inner(handler) or handler()\n"
+ "\n"
+ "def sibling():\n"
+ " return handler()\n",
+ CBM_LANG_PYTHON, "t", "u.py");
+ ASSERT_NOT_NULL(unwound);
+ ASSERT_FALSE(unwound->has_error);
+ int flagged = 0;
+ int unflagged = 0;
+ for (int i = 0; i < unwound->calls.count; i++) {
+ const char *cn = unwound->calls.items[i].callee_name;
+ if (!cn || strcmp(cn, "handler") != 0) {
+ continue;
+ }
+ if (unwound->calls.items[i].callee_is_locally_bound) {
+ flagged++;
+ } else {
+ unflagged++;
+ }
+ }
+ /* Two shadowed calls (inner body, and shadowed()'s own tail) and exactly one
+ * unshadowed call in sibling(). */
+ ASSERT_EQ(flagged, 2);
+ ASSERT_EQ(unflagged, 1);
+ cbm_free_result(unwound);
PASS();
}
@@ -5372,8 +5416,8 @@ TEST(extract_c_test_dir_marks_is_test_issue1294) {
* not be (#1294). */
TEST(extract_python_method_test_dir_marks_is_test_issue1294) {
const char *src = "class Foo:\n"
- " def helper(self):\n"
- " pass\n";
+ " def helper(self):\n"
+ " pass\n";
/* Python's LSP layer injects synthetic builtin stub Methods (str.upper,
* dict.get, ...) into defs.items alongside real ones (py_builtins.c), so
@@ -6644,7 +6688,7 @@ SUITE(extraction) {
RUN_TEST(extract_flag_exempt_method_call_not_flagged_is_method);
RUN_TEST(extract_python_member_call_flags_is_method);
RUN_TEST(extract_python_bare_call_flags_locally_bound_callee);
- RUN_TEST(extract_python_bare_call_scope_walk_is_bounded);
+ RUN_TEST(extract_python_bare_call_flag_is_depth_independent);
RUN_TEST(extract_ts_member_call_flags_is_method);
RUN_TEST(extract_ts_this_super_receiver_not_flagged);
RUN_TEST(extract_js_member_call_flags_is_method);