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.

Merge origin/main into the Elixir complexity branch

Martin Vogel2e6ab84fd96f
diff --cc internal/cbm/extract_defs.c
index e2822d446,3a476e4b8..c9276df5f
--- a/internal/cbm/extract_defs.c
+++ b/internal/cbm/extract_defs.c
@@@ -4984,136 -9714,119 +9714,247 @@@ static TSNode elixir_call_args(TSNode n
return args;
}
- // Handle Elixir def/defp/defmacro — extract function definition.
+ // Fold one more clause of an Elixir function into the def already pushed for
+ // the previous clause. Every clause is its own `def` call, and an Elixir QN
+ // carries neither module nor arity, so all of them compute one qualified name
+ // and collide on a single graph node. cbm_gbuf_upsert_node breaks a same-QN
+ // collision by keeping the LARGEST start_line, so the survivor was the last
+ // clause in the file and get_code_snippet returned that clause as the whole
+ // function: `def admin?(%__MODULE__{role: :admin}), do: true` /
+ // `def admin?(%__MODULE__{}), do: false` read back as a predicate that always
+ // returns false. One node per function is right, so widen its span instead.
+ //
+ // Two bounds keep the widened span honest, and a clause folds only if it clears
+ // both:
+ // - Same module body. `scope` is the do_block the previous clause was written
+ // in, so a nested `defmodule` cannot merge with its parent: the QN carries
+ // no module, so `Outer.run` and `Outer.Inner.run` compute the same name and
+ // are array-adjacent when Inner is declared just above Outer's own clause.
+ // - Same group. Only the immediately preceding EXTRACTED definition is a
+ // candidate, so a def of another name between two same-named defs ends the
+ // group. That is a bound this code imposes, not a guarantee Elixir gives:
+ // the compiler only WARNS ("clauses with the same name and arity should be
+ // grouped together"), it warns per name AND arity while this QN is
+ // arity-free, and non-contiguous clauses do compile. Split clauses
+ // therefore keep separate nodes, which is the pre-existing behaviour.
+ // What the group bound does NOT exclude is a non-definition construct
+ // between two clauses: `@doc` / `@spec` are unary_operators, `use` /
+ // `alias` / `describe` are ordinary calls, and a `defimpl` block's inner
+ // defs are not extracted -- none of them push a def, so anything of that
+ // kind written between two clauses of one function ends up inside the
+ // widened span, and that is not rare. Measured by indexing one 970-file
+ // Elixir lib tree with the binary built from this commit's parent and with
+ // this one and diffing the `nodes` rows out of the two SQLite stores: 6,996
+ // Function nodes widen their span, none is added, none is lost and none
+ // narrows. Reading each widened span for a module-body construct written at
+ // the module's own two-space indent, which no clause body reaches, 169 of
+ // the 6,996 cover such a line. Counting each node once per kind, 123 cover
+ // a typespec attribute (@spec/@type/@typep/@opaque/@callback/
+ // @macrocallback), 100 an @doc or @typedoc, 46 a bare comment line, 14 an
+ // @impl, and none a `use`, `alias`, `import`, `require` or a module-level
+ // `quote`. Swallowed typespecs are the largest attribute kind, not an
+ // absent one.
+ //
+ // The widened span also admits a phantom call that a narrower span kept out,
+ // which is why the head suppression in extract_calls.c travels with this fold
+ // rather than after it. cbm.c flags self-recursion by finding the innermost
+ // Function whose [start_line, end_line] contains a recorded call whose short
+ // name matches the function's own, so any pre-existing phantom between the
+ // first and the last clause becomes a self-edge as soon as the span covers it.
+ // That cost is real and is measured rather than asserted away. Same corpus,
+ // reading each flagged node's own source span for any line that names it as a
+ // call, a capture or a pipe target, counting a one-line clause's body after
+ // `, do:` as such a line: self_recursive Function nodes go 129 -> 430, and the
+ // ones carrying no self-call form anywhere in their span go 6 -> 48. The lines
+ // responsible are the typespec heads the widened span now covers -- `@spec
+ // f(t) :: u` puts the declared name in a `call` node, and the unified walk
+ // reads it as code -- a separate defect with a separate fix, not something this
+ // fold can close.
+ //
+ // Skipping the typespec subtrees, later in this stack, closes that half: the
+ // same method then reports 389 self_recursive Function nodes and 8 with no
+ // self-call form, against 129 and 6 on the base. All 8 are the pre-existing
+ // phantom a local variable sharing the function's name mints (`defp slug(value)
+ // do slug = ...`), 6 of them already present on the base; the other 2 are
+ // guarded clauses that only have a node of their own to be flagged on because
+ // of this stack.
+ //
+ // What the fold and the head suppression together remove is 2,436 edges, none
+ // of them added back: see elixir_call_is_definition_role in extract_calls.c.
+ //
+ // A clause whose macro differs (`def` foo/1 beside `defp` foo/2) still folds,
+ // because the arity-free QN already puts both on one node; is_exported is then
+ // the OR over the folded clauses, so a name any clause exports stays exported.
+ // That OR changes a recorded flag, which the node diff confirms and which is
+ // worth stating rather than leaving to be discovered: on the same corpus
+ // exactly 6 Function nodes change is_exported, all false -> true and none the
+ // other way. Each is a `def` clause written above a `defp` clause of the same
+ // name, where the pre-patch last-clause-wins record reported a publicly
+ // callable name as unexported. Verified against the source in every one: the
+ // new value is the correct one.
+ // Returns true when the clause folded.
+ static bool fold_elixir_clause(CBMExtractCtx *ctx, const char *qn, TSNode scope, TSNode node,
+ uint32_t end_line, bool is_exported) {
+ if (!qn || ctx->result->defs.count <= 0 || ts_node_is_null(scope)) {
+ return false;
+ }
+ TSNode here = ts_node_parent(node);
+ if (ts_node_is_null(here) || !ts_node_eq(here, scope)) {
+ return false;
+ }
+ CBMDefinition *prev = &ctx->result->defs.items[ctx->result->defs.count - 1];
+ if (!prev->label || strcmp(prev->label, "Function") != 0 || !prev->qualified_name ||
+ strcmp(prev->qualified_name, qn) != 0) {
+ return false;
+ }
+ /* Only end_line moves. prev->start_line is already the minimum, so this
+ * takes no start_line argument: a clause folds only into the def pushed
+ * for the immediately preceding extracted clause of the same do_block, and
+ * extract_elixir_call pushes a do_block's children onto its stack in
+ * reverse index order so they pop in source order. A `start_line <
+ * prev->start_line` guard here would be unreachable; if that traversal
+ * ever stops being source-ordered, this is the line that has to change
+ * with it. */
+ if (end_line > prev->end_line) {
+ prev->end_line = end_line;
+ }
+ prev->is_exported = prev->is_exported || is_exported;
+ return true;
+ }
+
+ // Handle Elixir def/defp/defmacro — extract function definition. `scope` is the
+ // module body the previous clause was extracted from, and is updated to this
+ // def's own module body; see fold_elixir_clause for what it bounds.
+/* True when node `n` spans exactly the text `lit`. Avoids an arena allocation
+ * per node in the complexity walk, which visits every node of every def. */
+static bool elixir_node_text_is(TSNode n, const char *source, const char *lit) {
+ if (ts_node_is_null(n)) {
+ return false;
+ }
+ uint32_t s = ts_node_start_byte(n);
+ uint32_t e = ts_node_end_byte(n);
+ size_t len = strlen(lit);
+ return (size_t)(e - s) == len && strncmp(source + s, lit, len) == 0;
+}
+
+/* Elixir has no branching NODE TYPES. `if`, `unless`, `case`, `cond`, `with`,
+ * `for`, `try` and `receive` are ordinary `call` nodes told apart only by the
+ * identifier in callee position, and every case/cond/fn/rescue arm is a
+ * `stab_clause`. lang_specs.c cannot express that — the Elixir branch table is
+ * `{"call"}`, which would score every function call as a decision — and
+ * cbm_compute_complexity matches on node type, so the generic path is unusable
+ * and every Elixir function shipped complexity 0.
+ *
+ * Counted here: the branching construct itself, every `stab_clause`, the
+ * short-circuit operators, and `when` guards. Container AND arm are both
+ * counted, which is the convention the generic tables already use — Go counts
+ * `expression_switch_statement` plus each `expression_case`, Python counts
+ * `try_statement` plus each `except_clause`. Cognitive weighting is Campbell's,
+ * identical to the generic walk (+1 plus the current nesting depth). */
+static bool elixir_is_branch_call(TSNode call, const char *source) {
+ if (ts_node_child_count(call) == 0) {
+ return false;
+ }
+ TSNode callee = ts_node_child(call, 0);
+ if (ts_node_is_null(callee) || strcmp(ts_node_type(callee), "identifier") != 0) {
+ return false;
+ }
+ return elixir_node_text_is(callee, source, "if") ||
+ elixir_node_text_is(callee, source, "unless") ||
+ elixir_node_text_is(callee, source, "with") ||
+ elixir_node_text_is(callee, source, "for") ||
+ elixir_node_text_is(callee, source, "case") ||
+ elixir_node_text_is(callee, source, "cond") ||
+ elixir_node_text_is(callee, source, "try") ||
+ elixir_node_text_is(callee, source, "receive");
+}
+
+/* A comprehension (`for x <- xs, do: ...`) is Elixir's only real loop node.
+ * Enum.map/reduce iterate too, but they are plain function calls; counting them
+ * would make loop_depth meaningless, so they are left out. */
+static bool elixir_is_loop_call(TSNode call, const char *source) {
+ if (ts_node_child_count(call) == 0) {
+ return false;
+ }
+ TSNode callee = ts_node_child(call, 0);
+ return !ts_node_is_null(callee) && strcmp(ts_node_type(callee), "identifier") == 0 &&
+ elixir_node_text_is(callee, source, "for");
+}
+
+static bool elixir_is_branch_operator(TSNode node, const char *source) {
+ TSNode op = ts_node_child_by_field_name(node, TS_FIELD("operator"));
+ return elixir_node_text_is(op, source, "&&") || elixir_node_text_is(op, source, "||") ||
+ elixir_node_text_is(op, source, "and") || elixir_node_text_is(op, source, "or") ||
+ elixir_node_text_is(op, source, "when");
+}
+
+static void elixir_compute_complexity(TSNode node, const char *source, cbm_complexity_t *out) {
+ enum { ELIXIR_CX_STACK_CAP = 4096 };
+ struct {
+ TSNode node;
+ int bdepth;
+ int ldepth;
+ int adepth;
+ } stack[ELIXIR_CX_STACK_CAP];
+ memset(out, 0, sizeof(*out));
+ int top = 0;
+ stack[top].node = node;
+ stack[top].bdepth = 0;
+ stack[top].ldepth = 0;
+ stack[top].adepth = 0;
+ top++;
+ while (top > 0) {
+ int cur = --top;
+ TSNode n = stack[cur].node;
+ int bdepth = stack[cur].bdepth;
+ int ldepth = stack[cur].ldepth;
+ int adepth = stack[cur].adepth;
+ const char *kind = ts_node_type(n);
+ bool is_branch = false;
+ if (strcmp(kind, "stab_clause") == 0) {
+ is_branch = true;
+ } else if (strcmp(kind, "call") == 0) {
+ is_branch = elixir_is_branch_call(n, source);
+ } else if (strcmp(kind, "binary_operator") == 0) {
+ is_branch = elixir_is_branch_operator(n, source);
+ }
+ int child_b = bdepth;
+ int child_l = ldepth;
+ /* `conn.assigns.user` nests as dot(dot(conn)), so consecutive `dot`
+ * nodes deepen the chain and anything else resets it. */
+ int child_a = 0;
+ if (strcmp(kind, "dot") == 0) {
+ child_a = adepth + 1;
+ if (child_a > out->max_access_depth) {
+ out->max_access_depth = child_a;
+ }
+ }
+ if (is_branch) {
+ out->cyclomatic++;
+ out->cognitive += 1 + bdepth;
+ child_b = bdepth + 1;
+ }
+ if (strcmp(kind, "call") == 0 && elixir_is_loop_call(n, source)) {
+ out->loop_count++;
+ int d = ldepth + 1;
+ if (d > out->loop_depth) {
+ out->loop_depth = d;
+ }
+ child_l = d;
+ }
+ uint32_t nc = ts_node_child_count(n);
+ for (int i = (int)nc - 1; i >= 0 && top < ELIXIR_CX_STACK_CAP; i--) {
+ stack[top].node = ts_node_child(n, (uint32_t)i);
+ stack[top].bdepth = child_b;
+ stack[top].ldepth = child_l;
+ stack[top].adepth = child_a;
+ top++;
+ }
+ }
+}
+
- static void extract_elixir_func_def(CBMExtractCtx *ctx, TSNode node, const char *macro) {
+ static void extract_elixir_func_def(CBMExtractCtx *ctx, TSNode node, const char *macro,
+ TSNode *scope) {
CBMArena *a = ctx->arena;
TSNode args = elixir_call_args(node);
if (ts_node_is_null(args)) {
@@@ -5139,27 -9872,12 +10000,27 @@@
CBMDefinition def;
memset(&def, 0, sizeof(def));
def.name = name;
- def.qualified_name = cbm_fqn_compute(a, ctx->project, ctx->rel_path, name);
+ def.qualified_name = qn;
def.label = "Function";
def.file_path = ctx->rel_path;
- def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
- def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
- def.is_exported = (strcmp(macro, "def") == 0 || strcmp(macro, "defmacro") == 0);
+ def.start_line = start_line;
+ def.end_line = end_line;
+ def.is_exported = is_exported;
+ def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
+ cbm_complexity_t cx;
+ elixir_compute_complexity(node, ctx->source, &cx);
+ def.complexity = cx.cyclomatic;
+ def.cognitive = cx.cognitive;
+ def.loop_count = cx.loop_count;
+ def.loop_depth = cx.loop_depth;
+ def.max_access_depth = cx.max_access_depth;
+ /* Fingerprint off the body, not the whole def call: including the head
+ * would make every clause of a name look alike. Elixir was the only
+ * language emitting Functions with no fingerprint at all, so it never
+ * appeared in similarity or duplicate results. Runs after `lines` — the
+ * AST profile reads it. */
+ TSNode fp_body = cbm_find_child_by_kind(node, "do_block");
+ compute_fingerprint(ctx, &def, ts_node_is_null(fp_body) ? node : fp_body);
cbm_defs_push(&ctx->result->defs, a, def);
}
diff --cc tests/test_extraction.c
index ea883bd29,541b7bb2d..7bc8a3499
--- a/tests/test_extraction.c
+++ b/tests/test_extraction.c
@@@ -1005,45 -1937,805 +1937,844 @@@ TEST(elixir_function)
PASS();
}
- /* Elixir control flow is `call` nodes and `stab_clause` arms, not branch node
- * TYPES, so the generic complexity walk scored every Elixir function 0 and the
- * fingerprint was never computed at all — no similarity or duplicate detection. */
- TEST(elixir_complexity_and_fingerprint) {
+ /* ── Elixir def-head guard helpers (internal/cbm/helpers.c) ─────────
+ *
+ * `def name(args) when guard` parses its WHOLE head as one `when`
+ * binary_operator whose left operand is the `name(args)` call, and Elixir
+ * admits more than one guard on a clause, which tree-sitter-elixir nests
+ * right-associatively. Four walks read that same first argument and each asks a
+ * different question of it: the defs and call-scope walks want the head UNDER
+ * every guard, the usages walk wants it so that a parameter READ by the guard
+ * stays outside the binding, and the calls walk wants to know whether the node
+ * it is visiting IS that head or one of the guard operators above it.
+ *
+ * That last question is why cbm_elixir_def_head_is exists beside the unwrap,
+ * and it is exercised here on the AST rather than through cbm_extract_file
+ * because the two routes it has to answer for are indistinguishable from
+ * outside: `def f(x) when g` reaches the calls walk as the inner `f(x)` call,
+ * which the unwrap reaches, while `def f when g` has no inner call at all and
+ * reaches it as the `when` operator itself, which the unwrap does not. A test
+ * that only drives one walk sees whichever of the two that walk happens to hit.
+ *
+ * This file's helpers change no extraction behaviour on their own; the walks
+ * that consume them are separate changes. */
+
+ enum { ELIXIR_HEAD_PROBE_MAX = 16, ELIXIR_HEAD_STACK_MAX = 256 };
+
+ static bool head_probe_text_is(const char *source, TSNode node, const char *want) {
+ if (ts_node_is_null(node)) {
+ return false;
+ }
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ size_t len = strlen(want);
+ return end >= start && (size_t)(end - start) == len && memcmp(source + start, want, len) == 0;
+ }
+
+ /* The first argument of every `def`/`defp` call under `root`, in source order.
+ * That argument is what all four walks read, so it is what the helpers take. */
+ typedef struct {
+ TSNode signature[ELIXIR_HEAD_PROBE_MAX];
+ int count;
+ } elixir_head_probe_t;
+
+ static void collect_elixir_def_signatures(TSNode root, const char *source,
+ elixir_head_probe_t *out) {
+ TSNode stack[ELIXIR_HEAD_STACK_MAX];
+ int top = 0;
+ stack[top++] = root;
+ while (top > 0) {
+ TSNode cur = stack[--top];
+ uint32_t cc = ts_node_child_count(cur);
+ if (cc > 1 && strcmp(ts_node_type(cur), "call") == 0 &&
+ (head_probe_text_is(source, ts_node_child(cur, 0), "def") ||
+ head_probe_text_is(source, ts_node_child(cur, 0), "defp")) &&
+ out->count < ELIXIR_HEAD_PROBE_MAX) {
+ TSNode args = ts_node_child(cur, 1);
+ if (!ts_node_is_null(args) && ts_node_child_count(args) > 0) {
+ out->signature[out->count++] = ts_node_child(args, 0);
+ }
+ }
+ for (int i = (int)cc - 1; i >= 0 && top < ELIXIR_HEAD_STACK_MAX; i--) {
+ stack[top++] = ts_node_child(cur, (uint32_t)i);
+ }
+ }
+ }
+
+ TEST(elixir_def_head_is_covers_the_head_and_every_guard_above_it) {
+ const char *source = "defmodule Heads do\n"
+ " def plain(x), do: x\n"
+ " def guarded(x) when is_binary(x), do: x\n"
+ " def bare when true, do: :ok\n"
+ " def twice(x) when is_atom(x) when is_binary(x), do: x\n"
+ " def a + b, do: {a, b}\n"
+ "end\n";
+ const TSLanguage *language = cbm_ts_language(CBM_LANG_ELIXIR);
+ ASSERT_NOT_NULL(language);
+ TSParser *parser = ts_parser_new();
+ ASSERT_NOT_NULL(parser);
+ ASSERT_TRUE(ts_parser_set_language(parser, language));
+ TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
+ ASSERT_NOT_NULL(tree);
+
+ elixir_head_probe_t probe;
+ probe.count = 0;
+ collect_elixir_def_signatures(ts_tree_root_node(tree), source, &probe);
+ ASSERT_EQ(5, probe.count);
+
+ /* Unguarded: nothing to peel, and the head is the whole first argument.
+ * The name node inside it is NOT the head -- the calls walk compares the
+ * node it is visiting, and the `plain` identifier is one of those. */
+ TSNode plain = probe.signature[0];
+ ASSERT_FALSE(cbm_elixir_is_when_guard(plain));
+ ASSERT_TRUE(ts_node_eq(cbm_elixir_def_head_unwrap_guard(plain), plain));
+ ASSERT_TRUE(cbm_elixir_def_head_is(plain, plain));
+ ASSERT_FALSE(cbm_elixir_def_head_is(plain, ts_node_child(plain, 0)));
+
+ /* One guard: the first argument is the operator, the head is its left
+ * operand, and BOTH answer true -- the operator is the node the paren-less
+ * route hands the calls walk, the inner call is the node the peel route
+ * hands it. The guard expression answers false, or the walk would suppress
+ * a real call written inside a guard. */
+ TSNode guarded = probe.signature[1];
+ ASSERT_TRUE(cbm_elixir_is_when_guard(guarded));
+ TSNode guarded_head = cbm_elixir_def_head_unwrap_guard(guarded);
+ ASSERT_FALSE(ts_node_eq(guarded_head, guarded));
+ ASSERT_STR_EQ("call", ts_node_type(guarded_head));
+ ASSERT_TRUE(head_probe_text_is(source, guarded_head, "guarded(x)"));
+ ASSERT_TRUE(cbm_elixir_def_head_is(guarded, guarded));
+ ASSERT_TRUE(cbm_elixir_def_head_is(guarded, guarded_head));
+ TSNode guard_expr = ts_node_child_by_field_name(guarded, TS_FIELD("right"));
+ ASSERT_FALSE(ts_node_is_null(guard_expr));
+ ASSERT_TRUE(head_probe_text_is(source, guard_expr, "is_binary(x)"));
+ ASSERT_FALSE(cbm_elixir_def_head_is(guarded, guard_expr));
+
+ /* Paren-less: the head under the guard is a bare identifier, so there is no
+ * inner call for the peel route to produce. This is the shape that makes
+ * cbm_elixir_def_head_is necessary: the only node the calls walk ever sees
+ * for this clause is the operator. */
+ TSNode bare = probe.signature[2];
+ ASSERT_TRUE(cbm_elixir_is_when_guard(bare));
+ TSNode bare_head = cbm_elixir_def_head_unwrap_guard(bare);
+ ASSERT_STR_EQ("identifier", ts_node_type(bare_head));
+ ASSERT_TRUE(head_probe_text_is(source, bare_head, "bare"));
+ ASSERT_TRUE(cbm_elixir_def_head_is(bare, bare));
+ ASSERT_TRUE(cbm_elixir_def_head_is(bare, bare_head));
+
+ /* Two guards on one clause. tree-sitter-elixir nests them
+ * RIGHT-associatively -- `when(twice(x), when(is_atom(x), is_binary(x)))`,
+ * which is what this asserts -- so the head is still the outer operator's
+ * left operand and the peel reaches it in one step. The repeated peel is
+ * therefore a fixed point rather than a chain walk on this grammar; the
+ * nodes that must answer true are the operator and the head. */
+ TSNode twice = probe.signature[3];
+ ASSERT_TRUE(cbm_elixir_is_when_guard(twice));
+ TSNode second_guard = ts_node_child_by_field_name(twice, TS_FIELD("right"));
+ ASSERT_TRUE(cbm_elixir_is_when_guard(second_guard));
+ TSNode twice_head = cbm_elixir_def_head_unwrap_guard(twice);
+ ASSERT_TRUE(head_probe_text_is(source, twice_head, "twice(x)"));
+ ASSERT_TRUE(cbm_elixir_def_head_is(twice, twice));
+ ASSERT_TRUE(cbm_elixir_def_head_is(twice, twice_head));
+ /* The second guard is a `when` operator too, and it is NOT on the head
+ * chain: a walk that treated any `when` above the head as a declaration
+ * would suppress the calls written inside it. */
+ ASSERT_FALSE(cbm_elixir_def_head_is(twice, second_guard));
+
+ /* An operator definition's head is a binary_operator too, and unwrapping it
+ * would name the function after its own left parameter. Only the `when`
+ * token admits the peel, so `def a + b` is returned unchanged and its left
+ * operand is not a head. */
+ TSNode op_def = probe.signature[4];
+ ASSERT_STR_EQ("binary_operator", ts_node_type(op_def));
+ ASSERT_FALSE(cbm_elixir_is_when_guard(op_def));
+ ASSERT_TRUE(ts_node_eq(cbm_elixir_def_head_unwrap_guard(op_def), op_def));
+ ASSERT_TRUE(cbm_elixir_def_head_is(op_def, op_def));
+ TSNode op_lhs = ts_node_child_by_field_name(op_def, TS_FIELD("left"));
+ ASSERT_TRUE(head_probe_text_is(source, op_lhs, "a"));
+ ASSERT_FALSE(cbm_elixir_def_head_is(op_def, op_lhs));
+
+ ts_tree_delete(tree);
+ ts_parser_delete(parser);
+ PASS();
+ }
+
+ /* `def name(args) when guard` parses its whole head as a `when`
+ * binary_operator, so the name sits on the operator's left operand rather than
+ * directly under the call. The def extractor accepted only `call` and
+ * `identifier` there, so every guarded clause was dropped -- and a function
+ * whose clauses ALL carry guards never reached the graph at all, silently.
+ * Guards are ordinary Elixir: on one real 2.9k-function codebase this hid 216
+ * of 270 all-guarded functions, and every call edge touching them. */
+ TEST(extract_elixir_guarded_def_head) {
+ CBMFileResult *r = extract("defmodule Guarded do\n"
+ " def plain(x), do: x\n"
+ " def guarded(x) when is_binary(x), do: x\n"
+ " def guarded(x) when is_list(x), do: x\n"
+ " def multi(x, y) when is_binary(x) and is_integer(y), do: {x, y}\n"
+ " defp priv_guarded(x) when is_atom(x), do: x\n"
+ " def bare when true, do: :ok\n"
+ " def a + b, do: {a, b}\n"
+ " def c - d when is_integer(c), do: {c, d}\n"
+ " def multi_guard(x) when is_atom(x) when is_binary(x), do: x\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "guarded.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT(has_def(r, "Function", "plain"));
+ ASSERT(has_def(r, "Function", "guarded"));
+ ASSERT(has_def(r, "Function", "multi"));
+ ASSERT(has_def(r, "Function", "priv_guarded"));
+ ASSERT(has_def(r, "Function", "bare"));
+
+ /* Elixir admits more than one guard on a clause. tree-sitter-elixir nests
+ * those `when` operators right-associatively, so the declared head stays
+ * the outermost operator's left operand -- one node either way, and the
+ * peel must not stop short of it or return the guard. */
+ ASSERT(has_def(r, "Function", "multi_guard"));
+ ASSERT_EQ(count_defs_named(r, "Function", "multi_guard"), 1);
+
+ /* An operator definition is a binary_operator head too, but it is not a
+ * guard: unwrapping it names the function after its own LEFT PARAMETER.
+ * `def a + b` must not mint a function called `a`, nor `def c - d when ...`
+ * one called `c` -- the guard's left operand is itself the `c - d`
+ * operator, which names no function either. Neither operator form is
+ * extracted at all, which is what this grammar did before guards were
+ * handled; only the `when` token admits the unwrap. */
+ ASSERT_EQ(count_defs_named(r, "Function", "a"), 0);
+ ASSERT_EQ(count_defs_named(r, "Function", "c"), 0);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* A guard hides the head from the scope walk and from the calls walk.
+ * compute_elixir_func_qn accepts only a `call` or an `identifier` as a def's
+ * first argument, so a guarded clause resolved no QN and opened NO function
+ * scope: every call in its body was attributed to the FILE node, the function
+ * reported no outgoing edges, and its callees gained an in-edge from the file
+ * instead of from their caller. A paren-less guarded clause (`def f when g`) is
+ * worse still: it has no inner call node at all, so the guard operator itself
+ * falls through to extract_callee_name's first-identifier last resort and mints
+ * a phantom CALLS edge naming the function being defined. */
+ TEST(extract_elixir_guarded_def_head_scope) {
+ CBMFileResult *r = extract("defmodule Guards do\n"
+ " def target(x), do: x\n"
+ " def other(x), do: x\n"
+ " def unguarded_caller(a), do: target(a)\n"
+ " def guarded_caller(a) when is_binary(a) do\n"
+ " target(a)\n"
+ " other(a)\n"
+ " end\n"
+ " def bare_guarded when true, do: target(:ok)\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "guard_scope.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+
+ /* A paren-less guarded head is a definition, never a call to itself. */
+ ASSERT_EQ(count_calls_named(r, "bare_guarded"), 0);
+
+ /* Both calls in the guarded body source to the guarded function, and the
+ * paren-less clause's body call to that clause. */
+ ASSERT_EQ(count_calls_from(r, "target", "t.guard_scope.guarded_caller"), 1);
+ ASSERT_EQ(count_calls_from(r, "other", "t.guard_scope.guarded_caller"), 1);
+ ASSERT_EQ(count_calls_from(r, "target", "t.guard_scope.bare_guarded"), 1);
+
+ /* Control on the path the fix does not touch: an unguarded clause still
+ * sources its body call to itself. This is NOT a leak detector -- the walk
+ * expires scopes by tree depth (pop_expired_scopes), so a sibling clause
+ * always unwinds the previous one before pushing its own and "pushed but
+ * never popped" is not a state this walk can reach. */
+ ASSERT_EQ(count_calls_from(r, "target", "t.guard_scope.unguarded_caller"), 1);
+
+ /* Nothing falls back to the file node. */
+ ASSERT_EQ(count_calls_from(r, "target", "t.guard_scope"), 0);
+ ASSERT_EQ(count_calls_from(r, "other", "t.guard_scope"), 0);
+
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* The half the calls and scope assertions above cannot see: the usages walk
+ * asks whether an identifier sits inside the def's SIGNATURE, and treats
+ * everything that does as part of the binding rather than as a reference. A
+ * guard makes that signature the whole `when` operator, which spans the guard
+ * expression too -- so `a` read by `is_binary(a)` was classified as its own
+ * binding and emitted no USAGE row at all. A guard is an expression, not a
+ * pattern: the parameters are bound by `guarded(a, b)` and every mention of one
+ * to its right is a read, exactly as the same mention in the body already is.
+ * Unwrapping the signature to the head restores those rows without admitting
+ * the binding sites themselves, which is why each name is asserted both within
+ * its scope and in total. */
+ TEST(extract_elixir_guarded_def_head_guard_usages) {
+ CBMFileResult *r = extract("defmodule GuardUsage do\n"
+ " def plain(x), do: x\n"
+ " def guarded(a, b) when is_binary(a) and byte_size(a) > 3 do\n"
+ " b\n"
+ " end\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "guard_usage.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+
+ /* Both guard reads of the parameter are usages of the guarded clause. */
+ ASSERT_EQ(count_usages_from(r, "a", "t.guard_usage.guarded"), 2);
+ /* ...and nothing else claims `a`: the `a` in `guarded(a, b)` binds it. */
+ ASSERT_EQ(count_usages_named(r, "a"), 2);
+
+ /* The body read is unchanged, and the head's `b` is still a binding --
+ * an unwrap that took the guard instead of the head would add both head
+ * parameters here. */
+ ASSERT_EQ(count_usages_from(r, "b", "t.guard_usage.guarded"), 1);
+ ASSERT_EQ(count_usages_named(r, "b"), 1);
+
+ /* Control: an unguarded clause was never affected either way. */
+ ASSERT_EQ(count_usages_from(r, "x", "t.guard_usage.plain"), 1);
+ ASSERT_EQ(count_usages_named(r, "x"), 1);
+
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* Every clause of an Elixir function is its own `def` call, and an Elixir QN
+ * carries neither module nor arity, so all clauses compute one qualified name
+ * and collide on a single graph node. cbm_gbuf_upsert_node ranks a same-QN
+ * collision by LARGEST start_line, so the survivor was the last clause in the
+ * file and get_code_snippet returned that clause as the whole function: a
+ * two-clause `admin?` read back as `def admin?(%__MODULE__{}), do: false` --
+ * the graph asserting a predicate that always returns false. The node has to
+ * span its own clauses, and ONLY its own: the fold is bounded to the
+ * immediately preceding definition and to the enclosing module body, so a def
+ * of another name ends the group and two same-named functions in two modules
+ * stay two nodes. */
+ TEST(extract_elixir_clauses_fold_only_when_adjacent_in_one_module) {
+ CBMFileResult *r = extract("defmodule Roles do\n" /* 1 */
+ " def admin?(%{role: :admin}), do: true\n" /* 2 */
+ " def admin?(%{}), do: false\n" /* 3 */
+ "\n" /* 4 */
+ " def promote(user), do: user\n" /* 5 */
+ "\n" /* 6 */
+ " def admin?(_other), do: false\n" /* 7 */
+ "end\n" /* 8 */
+ "\n" /* 9 */
+ "defmodule Guests do\n" /* 10 */
+ " def admin?(:root), do: true\n" /* 11 */
+ " def admin?(_any), do: false\n" /* 12 */
+ "end\n", /* 13 */
+ CBM_LANG_ELIXIR, "t", "roles.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+
+ /* The two adjacent Roles clauses fold; the clause past `promote` is its own
+ * group; the Guests pair is a DIFFERENT function and stays its own node. */
+ ASSERT_EQ(3, count_defs_named(r, "Function", "admin?"));
+ ASSERT_EQ(1, count_defs_named(r, "Function", "promote"));
+
+ const CBMDefinition *admin[3] = {NULL, NULL, NULL};
+ const CBMDefinition *promote = NULL;
+ int seen = 0;
+ for (int i = 0; i < r->defs.count; i++) {
+ if (strcmp(r->defs.items[i].label, "Function") != 0) {
+ continue;
+ }
+ if (strcmp(r->defs.items[i].name, "admin?") == 0 && seen < 3) {
+ admin[seen++] = &r->defs.items[i];
+ } else if (strcmp(r->defs.items[i].name, "promote") == 0) {
+ promote = &r->defs.items[i];
+ }
+ }
+ ASSERT_NOT_NULL(admin[0]);
+ ASSERT_NOT_NULL(admin[1]);
+ ASSERT_NOT_NULL(admin[2]);
+ ASSERT_NOT_NULL(promote);
+
+ ASSERT_EQ(2, (int)admin[0]->start_line);
+ ASSERT_EQ(3, (int)admin[0]->end_line);
+ /* separated from lines 2-3 by `promote`, so it keeps its own span */
+ ASSERT_EQ(7, (int)admin[1]->start_line);
+ ASSERT_EQ(7, (int)admin[1]->end_line);
+ /* Guests.admin? never reaches back over the module boundary */
+ ASSERT_EQ(11, (int)admin[2]->start_line);
+ ASSERT_EQ(12, (int)admin[2]->end_line);
+ ASSERT_EQ(5, (int)promote->start_line);
+ ASSERT_EQ(5, (int)promote->end_line);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* A nested module is the one place where the "def of another name ends the
+ * group" rule is not enough: an Elixir QN carries no module, so `Outer.run` and
+ * `Outer.Inner.run` compute the SAME qualified name, and when Inner sits
+ * directly above Outer's own clause the two are adjacent in the extracted defs.
+ * The fold is bounded to the module body as well, so they stay two nodes. */
+ TEST(extract_elixir_nested_module_clauses_do_not_fold) {
+ CBMFileResult *r = extract("defmodule Outer do\n" /* 1 */
+ " defmodule Inner do\n" /* 2 */
+ " def run(a), do: a\n" /* 3 */
+ " end\n" /* 4 */
+ "\n" /* 5 */
+ " def run(b), do: b + 1\n" /* 6 */
+ "end\n", /* 7 */
+ CBM_LANG_ELIXIR, "t", "nested.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(2, count_defs_named(r, "Function", "run"));
+
+ const CBMDefinition *runs[2] = {NULL, NULL};
+ int seen = 0;
+ for (int i = 0; i < r->defs.count; i++) {
+ if (strcmp(r->defs.items[i].label, "Function") == 0 &&
+ strcmp(r->defs.items[i].name, "run") == 0 && seen < 2) {
+ runs[seen++] = &r->defs.items[i];
+ }
+ }
+ ASSERT_NOT_NULL(runs[0]);
+ ASSERT_NOT_NULL(runs[1]);
+ ASSERT_EQ(3, (int)runs[0]->start_line);
+ ASSERT_EQ(3, (int)runs[0]->end_line);
+ ASSERT_EQ(6, (int)runs[1]->start_line);
+ ASSERT_EQ(6, (int)runs[1]->end_line);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* Folding clauses has to decide is_exported for the merged node. A `def` clause
+ * and a `defp` clause of the same name AND arity are clauses of one function --
+ * a private guard clause or a nil short-circuit written above the public head
+ * is ordinary Elixir -- so is_exported is the OR over the folded clauses: the
+ * name is callable from outside if any clause exports it, and a wholly private
+ * function stays unexported. */
+ TEST(extract_elixir_folded_clause_is_exported_is_the_or) {
+ CBMFileResult *r = extract("defmodule Acc do\n" /* 1 */
+ " def build(l), do: build(l)\n" /* 2 */
+ " defp build([]), do: []\n" /* 3 */
+ "\n" /* 4 */
+ " defp trim(nil), do: nil\n" /* 5 */
+ " defp trim(s), do: s\n" /* 6 */
+ "end\n", /* 7 */
+ CBM_LANG_ELIXIR, "t", "acc.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(1, count_defs_named(r, "Function", "build"));
+ ASSERT_EQ(1, count_defs_named(r, "Function", "trim"));
+
+ const CBMDefinition *build = NULL;
+ const CBMDefinition *trim = NULL;
+ for (int i = 0; i < r->defs.count; i++) {
+ if (strcmp(r->defs.items[i].label, "Function") != 0) {
+ continue;
+ }
+ if (strcmp(r->defs.items[i].name, "build") == 0) {
+ build = &r->defs.items[i];
+ } else if (strcmp(r->defs.items[i].name, "trim") == 0) {
+ trim = &r->defs.items[i];
+ }
+ }
+ ASSERT_NOT_NULL(build);
+ ASSERT_NOT_NULL(trim);
+ ASSERT_EQ(2, (int)build->start_line);
+ ASSERT_EQ(3, (int)build->end_line);
+ ASSERT_TRUE(build->is_exported);
+ ASSERT_EQ(5, (int)trim->start_line);
+ ASSERT_EQ(6, (int)trim->end_line);
+ ASSERT_FALSE(trim->is_exported);
+ cbm_free_result(r);
+
+ /* The other direction, and the only one the `prev->is_exported ||` disjunct
+ * decides. Above, the exporting clause is the FIRST one, so a plain
+ * `prev->is_exported = is_exported` assignment would also have to lose it
+ * on the later defp -- but a last-clause-wins assignment happens to be
+ * right whenever the def comes last. Here the defp comes first and the def
+ * second, so the surviving flag can only be true if the fold ORs rather
+ * than assigns. */
+ CBMFileResult *o = extract("defmodule Ord do\n" /* 1 */
+ " defp z(1), do: 1\n" /* 2 */
+ " def z(2), do: 2\n" /* 3 */
+ "end\n", /* 4 */
+ CBM_LANG_ELIXIR, "t", "ord.ex");
+ ASSERT_NOT_NULL(o);
+ ASSERT_FALSE(o->has_error);
+ ASSERT_EQ(1, count_defs_named(o, "Function", "z"));
+ const CBMDefinition *z = NULL;
+ for (int i = 0; i < o->defs.count; i++) {
+ if (strcmp(o->defs.items[i].label, "Function") == 0 &&
+ strcmp(o->defs.items[i].name, "z") == 0) {
+ z = &o->defs.items[i];
+ }
+ }
+ ASSERT_NOT_NULL(z);
+ ASSERT_EQ(2, (int)z->start_line);
+ ASSERT_EQ(3, (int)z->end_line);
+ ASSERT_TRUE(z->is_exported);
+ cbm_free_result(o);
+ PASS();
+ }
+
+ /* First definition with this name, for the Elixir clause-fold tests below.
+ * find_def() is declared much further down this file. */
+ static const CBMDefinition *elixir_first_def(CBMFileResult *r, const char *name) {
+ for (int i = 0; i < r->defs.count; i++) {
+ if (r->defs.items[i].name && strcmp(r->defs.items[i].name, name) == 0) {
+ return &r->defs.items[i];
+ }
+ }
+ return NULL;
+ }
+
+ /* A guarded clause head is a DECLARATION of the name, never a call to it, and
+ * the call extractor has to agree with the def extractor about which node the
+ * head is. It did not: it suppressed a head only when the head node IS the
+ * def's first named argument, but `def f(x) when g` parses its whole head as a
+ * `when` binary_operator, so the inner `f(x)` was not that argument and was
+ * recorded as a call to `f`. Under the folded span that phantom lands inside
+ * the function's own node, and self-recursion is decided by line containment,
+ * so an ordinary two-clause guarded function reported itself recursive.
+ * Recursion is a load-bearing signal: `recursive` is a queryable node property
+ * and seeds the cycle detection in pass_complexity. */
+ TEST(extract_elixir_guarded_clause_head_is_not_a_self_call) {
+ CBMFileResult *r = extract("defmodule Guarded do\n" /* 1 */
+ " def f(x) when is_integer(x), do: x\n" /* 2 */
+ " def f(_x), do: 0\n" /* 3 */
+ "\n" /* 4 */
+ " def solo(x) when is_binary(x), do: x\n" /* 5 */
+ "end\n", /* 6 */
+ CBM_LANG_ELIXIR, "t", "guard_call.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+
+ /* No call to either name exists anywhere in this file. */
+ ASSERT_EQ(0, count_calls_named(r, "f"));
+ ASSERT_EQ(0, count_calls_named(r, "solo"));
+ /* The guard predicate IS a real call and stays one. */
+ ASSERT_EQ(1, count_calls_named(r, "is_integer"));
+ ASSERT_EQ(1, count_calls_named(r, "is_binary"));
+
+ ASSERT_EQ(1, count_defs_named(r, "Function", "f"));
+ const CBMDefinition *f = elixir_first_def(r, "f");
+ ASSERT_NOT_NULL(f);
+ ASSERT_EQ(2, (int)f->start_line);
+ ASSERT_EQ(3, (int)f->end_line);
+ ASSERT_FALSE(f->is_recursive);
+
+ /* A single guarded clause was wrong even before the span widened: the
+ * phantom landed on its own one-line node. */
+ const CBMDefinition *solo = elixir_first_def(r, "solo");
+ ASSERT_NOT_NULL(solo);
+ ASSERT_FALSE(solo->is_recursive);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* Every reference of any kind this file records for `name`, across all four
+ * extractors the unified walk runs over one subtree: a call site, a value
+ * usage, a read/write occurrence, a type reference. Suppressing a node in ONE
+ * of them does not remove a phantom reference, it moves it -- handle_calls
+ * declining a node leaves state->callee_expr unset, and handle_usages then
+ * reaches the bare identifier and mints a USAGE instead. USAGE and CALLS are
+ * separate rows in the edge table, so the relabelled phantom also escapes the
+ * UNIQUE(source,target,type) dedup that had been collapsing it onto a real
+ * call, and pass_importance counts an inbound reference that did not exist
+ * before. An assertion naming only r->calls cannot see any of that. */
+ static int elixir_any_ref_count(CBMFileResult *r, const char *name) {
+ int count = count_calls_named(r, name);
+ for (int i = 0; i < r->usages.count; i++) {
+ if (r->usages.items[i].ref_name && strcmp(r->usages.items[i].ref_name, name) == 0) {
+ count++;
+ }
+ }
+ for (int i = 0; i < r->rw.count; i++) {
+ if (r->rw.items[i].var_name && strcmp(r->rw.items[i].var_name, name) == 0) {
+ count++;
+ }
+ }
+ for (int i = 0; i < r->type_refs.count; i++) {
+ if (r->type_refs.items[i].type_name && strcmp(r->type_refs.items[i].type_name, name) == 0) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /* The head suppression has to REMOVE the phantom, not relabel it. What makes
+ * that hold for a def head is not the calls walk alone: is_elixir_def_binding in
+ * extract_usages.c already treats everything inside a def's first argument as
+ * a binding occurrence rather than a reference, so the identifier handle_calls
+ * declines is declined by handle_usages too. That agreement is the invariant
+ * under test, and it is why the counts below are over every extractor rather
+ * than over r->calls.
+ *
+ * `spec_subject` pins the boundary between the two mechanisms. A typespec
+ * subject is the same shape as a def head, and suppressing it in the calls walk
+ * would only relabel its phantom as a USAGE, because nothing treats it as a
+ * binding. It is removed instead by skipping the whole `@spec` subtree before
+ * any extractor sees it (is_elixir_typespec_attribute, extract_unified.c), so
+ * the assertion is both that no reference of any kind survives AND that what
+ * does survive is never a relabelling: the equality holds at 0 == 0 here, and
+ * would hold at 1 == 1 on a build with the subtree skip removed but the calls
+ * suppression left in place. */
+ TEST(extract_elixir_declaration_head_mints_no_reference_of_any_kind) {
+ CBMFileResult *r = extract("defmodule Heads do\n" /* 1 */
+ " def guarded(x) when is_integer(x), do: x\n" /* 2 */
+ " def guarded(_x), do: 0\n" /* 3 */
+ "\n" /* 4 */
+ " defp bare(x), do: x\n" /* 5 */
+ "\n" /* 6 */
+ " @spec spec_subject(integer) :: integer\n" /* 7 */
+ " def spec_subject(n), do: n\n" /* 8 */
+ "end\n", /* 9 */
+ CBM_LANG_ELIXIR, "t", "heads.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+
+ /* Nothing in this file references `guarded` or `bare`. Not as a call, not
+ * as a value, not as a read/write, not as a type. */
+ ASSERT_EQ(0, elixir_any_ref_count(r, "guarded"));
+ ASSERT_EQ(0, elixir_any_ref_count(r, "bare"));
+ /* The guard predicate is a real call and survives as one. */
+ ASSERT_EQ(1, count_calls_named(r, "is_integer"));
+ ASSERT_EQ(1, elixir_any_ref_count(r, "is_integer"));
+ /* Neither the @spec line nor the def head it precedes leaves a reference,
+ * and nothing has been relabelled into a usage, a read/write or a type
+ * reference. */
+ ASSERT_EQ(0, count_calls_named(r, "spec_subject"));
+ ASSERT_EQ(count_calls_named(r, "spec_subject"),
+ elixir_any_ref_count(r, "spec_subject"));
+
+ ASSERT_EQ(1, count_defs_named(r, "Function", "guarded"));
+ const CBMDefinition *guarded = elixir_first_def(r, "guarded");
+ ASSERT_NOT_NULL(guarded);
+ ASSERT_EQ(2, (int)guarded->start_line);
+ ASSERT_EQ(3, (int)guarded->end_line);
+ ASSERT_FALSE(guarded->is_recursive);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* The other direction: suppressing declaration heads must not blind the
+ * detector to real recursion, and folding must not lose a self-call written in
+ * a clause that is no longer the surviving one. `walk` recurses from its
+ * guarded second clause; exactly one call to `walk` is recorded (the body one,
+ * not the two heads) and the folded node is recursive. */
+ TEST(extract_elixir_real_recursion_survives_head_suppression) {
+ CBMFileResult *r = extract("defmodule Rec do\n" /* 1 */
+ " def walk([]), do: []\n" /* 2 */
+ " def walk([h | t]) when is_integer(h), do: [h | walk(t)]\n" /* 3 */
+ "end\n", /* 4 */
+ CBM_LANG_ELIXIR, "t", "rec.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT_EQ(1, count_calls_named(r, "walk"));
+ ASSERT_EQ(1, count_defs_named(r, "Function", "walk"));
+ const CBMDefinition *walk = elixir_first_def(r, "walk");
+ ASSERT_NOT_NULL(walk);
+ ASSERT_EQ(2, (int)walk->start_line);
+ ASSERT_EQ(3, (int)walk->end_line);
+ ASSERT_TRUE(walk->is_recursive);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* An Elixir module attribute parses as `unary_operator(@, call(<attr>, args))`,
+ * so a typespec line reaches the unified walk as ordinary code and every symbol
+ * it names collects a phantom inbound edge from the enclosing Module -- a CALLS
+ * onto the specified function, and for `@type` a USAGE plus a WRITES asserting
+ * a mutation that does not exist. On a codebase whose convention is @spec on
+ * every public function, fan_in then never reaches 0 and "which exported
+ * functions nothing calls" is unanswerable.
+ *
+ * All six heads in the skip list are exercised, so deleting any one entry from
+ * typespec_heads[] breaks this test.
+ *
+ * Two of the groups below pin a decision rather than a repair, and both are
+ * argued in is_elixir_typespec_attribute's comment:
+ *
+ * type_refs[] -- a typespec's type references are not indexed at all. A type
+ * declaration mints no node, so such a reference resolves onto nothing or
+ * onto a same-named FUNCTION, which is the pollution rather than a record of
+ * it. Restoring any of them must break this test.
+ *
+ * behaviour_contract_names[] -- accepted cost. A @callback / @macrocallback
+ * name is a function name, so before this change it resolved cross-file onto
+ * the functions implementing the behaviour. Nothing replaces that edge.
+ *
+ * The attribute NAME phantom outside the typespec family is deliberately still
+ * there: `@timeout` keeps its one reference, and its VALUE is ordinary
+ * compile-time code that still runs. `guarded` is pinned at 0 rather than 1
+ * because the guarded def head no longer mints a phantom either -- the calls
+ * walk now recognises a `when`-wrapped head as a declaration. */
+ TEST(extract_elixir_typespec_attribute_is_not_code) {
+ /* Names a typespec declares, plus the six attribute heads themselves.
+ * Every one carries a reference on the pristine build. */
+ static const char *const declared[] = {"with_spec", "entry", "secret", "handle",
+ "spec", "type", "typep", "opaque",
+ "callback", "macrocallback", NULL};
+ /* Accepted cost: these used to resolve onto the behaviour's implementors. */
+ static const char *const behaviour_contract_names[] = {"handle_it", "expand_it", NULL};
+ /* Pinned decision: type references are not indexed -- remote, bare-local
+ * and builtin alike. */
+ static const char *const type_refs[] = {"MyApp.User.t", "String.t", "MyApp.Vault.key",
+ "Macro.t", "t", "key",
+ "term", "integer", "reference",
+ "atom", NULL};
+ CBMFileResult *r = extract("defmodule Specced do\n"
+ " @timeout Application.compile_env(:app, :timeout)\n"
+ " @type entry :: String.t()\n"
+ " @typep secret :: MyApp.Vault.key()\n"
+ " @opaque handle :: reference()\n"
+ " @callback handle_it(term) :: :ok\n"
+ " @macrocallback expand_it(term) :: Macro.t()\n"
+ " @spec with_spec(MyApp.User.t()) :: integer\n"
+ " def with_spec(n), do: n\n"
+ " def without_spec(n), do: n\n"
+ " @spec guarded(atom) :: :ok\n"
+ " def guarded(x) when is_atom(x), do: :ok\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "specced.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ /* The definitions themselves are a separate pass and are unaffected. */
+ ASSERT(has_def(r, "Function", "with_spec"));
+ ASSERT(has_def(r, "Function", "without_spec"));
+ ASSERT(has_def(r, "Function", "guarded"));
+ /* Control on the instrument, not a pin: `without_spec` carries no typespec
+ * and is never called, so it reads 0 on the pristine build too. It is here
+ * to show elixir_any_ref_count does not score a definition as a reference,
+ * which is what would make every 0 below vacuous. It cannot fail first and
+ * cannot catch a regression. */
+ ASSERT_EQ(0, elixir_any_ref_count(r, "without_spec"));
+ for (const char *const *name = declared; *name; name++) {
+ ASSERT_EQ(0, elixir_any_ref_count(r, *name));
+ }
+ for (const char *const *name = behaviour_contract_names; *name; name++) {
+ ASSERT_EQ(0, elixir_any_ref_count(r, *name));
+ }
+ for (const char *const *name = type_refs; *name; name++) {
+ ASSERT_EQ(0, elixir_any_ref_count(r, *name));
+ }
+ /* A non-typespec attribute is untouched: its value really is compile-time
+ * code, and its name still mints the one phantom this fix does not close. */
+ ASSERT_EQ(1, count_calls_named(r, "Application.compile_env"));
+ ASSERT_EQ(1, elixir_any_ref_count(r, "timeout"));
+ /* Both phantoms onto `guarded` are gone: the @spec one to the subtree skip,
+ * the def-head one to the calls walk recognising a guarded head. */
+ ASSERT_EQ(0, elixir_any_ref_count(r, "guarded"));
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* tree-sitter-elixir gives a call's arguments node no field name, so the
+ * generic `arguments` field lookup returns null and first_string_arg was never
+ * populated for any Elixir call — Phoenix route paths, service URLs and config
+ * keys all key off it. */
+ TEST(elixir_call_string_argument) {
+ CBMFileResult *r = extract("defmodule Sample do\n"
+ " def run do\n"
+ " get(\"/wallets\", WalletController)\n"
+ " end\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "sample.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ int seen = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ if (strcmp(r->calls.items[i].callee_name, "get") != 0) {
+ continue;
+ }
+ seen = 1;
+ ASSERT_NOT_NULL(r->calls.items[i].first_string_arg);
+ ASSERT_STR_EQ("/wallets", r->calls.items[i].first_string_arg);
+ }
+ ASSERT_EQ(1, seen);
+ cbm_free_result(r);
+ PASS();
+ }
+
+ /* True when a channel with this name/transport/direction was extracted. */
+ static int has_channel(CBMFileResult *r, const char *name, const char *transport,
+ CBMChannelDirection dir) {
+ for (int i = 0; i < r->channels.count; i++) {
+ const CBMChannel *c = &r->channels.items[i];
+ if (c->channel_name && strcmp(c->channel_name, name) == 0 && c->transport &&
+ strcmp(c->transport, transport) == 0 && c->direction == dir)
+ return 1;
+ }
+ return 0;
+ }
+
+ /* Phoenix pub/sub and channel listeners. Both branches were unreachable: the
+ * emit side looked up an "arguments" FIELD that tree-sitter-elixir does not
+ * define, and the listener side dispatched on a "def" NODE TYPE that does not
+ * exist (Elixir defs are `call` nodes), so a Phoenix app produced no channels
+ * at all. */
+ TEST(elixir_channels_pubsub_and_handle_in) {
+ CBMFileResult *r =
+ extract("defmodule Acme.Notifier do\n"
+ " def announce(p) do\n"
+ " Phoenix.PubSub.broadcast(Acme.PubSub, \"user:created\", p)\n"
+ " end\n"
+ " def watch, do: Phoenix.PubSub.subscribe(Acme.PubSub, \"user:updated\")\n"
+ "end\n"
+ "defmodule AcmeWeb.RoomChannel do\n"
+ " def handle_in(\"new_msg\", payload, socket) do\n"
+ " push(socket, \"pong\", %{})\n"
+ " {:noreply, socket}\n"
+ " end\n"
+ " def handle_in(\"ping\", _p, socket) when is_map(socket) do\n"
+ " {:noreply, socket}\n"
+ " end\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "chan.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ ASSERT(has_channel(r, "user:created", "phoenix_pubsub", CBM_CHANNEL_EMIT));
+ ASSERT(has_channel(r, "user:updated", "phoenix_pubsub", CBM_CHANNEL_LISTEN));
+ /* handle_in clauses are listeners — including the guarded one. */
+ ASSERT(has_channel(r, "new_msg", "phoenix_channel", CBM_CHANNEL_LISTEN));
+ ASSERT(has_channel(r, "ping", "phoenix_channel", CBM_CHANNEL_LISTEN));
+ /* A bare push/broadcast inside the channel module is an emit. */
+ ASSERT(has_channel(r, "pong", "phoenix_channel", CBM_CHANNEL_EMIT));
+ cbm_free_result(r);
+ PASS();
+ }
+
++/* Elixir control flow is `call` nodes and `stab_clause` arms, not branch node
++ * TYPES, so the generic complexity walk scored every Elixir function 0 and the
++ * fingerprint was never computed at all — no similarity or duplicate detection. */
++TEST(elixir_complexity_and_fingerprint) {
+ CBMFileResult *r = extract("defmodule Cx do\n"
+ " def classify(x) do\n"
+ " case x do\n"
+ " 0 -> :zero\n"
+ " n when n > 0 -> :pos\n"
+ " _ -> :neg\n"
+ " end\n"
+ " end\n"
+ " def plain(a), do: a\n"
+ "end\n",
+ CBM_LANG_ELIXIR, "t", "cx.ex");
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error);
+ CBMDefinition *cls = NULL;
+ CBMDefinition *plain = NULL;
+ for (int i = 0; i < r->defs.count; i++) {
+ if (strcmp(r->defs.items[i].name, "classify") == 0)
+ cls = &r->defs.items[i];
+ if (strcmp(r->defs.items[i].name, "plain") == 0)
+ plain = &r->defs.items[i];
+ }
+ ASSERT_NOT_NULL(cls);
+ /* The `case` itself + its 3 arms + the second arm's own `when` guard. */
+ ASSERT_EQ(5, cls->complexity);
+ ASSERT(cls->cognitive > 0);
+ ASSERT(cls->lines > 0);
+ /* A straight-line body has no decisions but still gets a line count — a
+ * language must not become nonzero everywhere just by being measured. */
+ ASSERT_NOT_NULL(plain);
+ ASSERT_EQ(0, plain->complexity);
+ ASSERT(plain->lines > 0);
+ cbm_free_result(r);
+ PASS();
+}
+
/* --- Haskell --- */
TEST(haskell_function) {
CBMFileResult *r = extract("add :: Int -> Int -> Int\nadd x y = x + y\n\nmultiply :: Int -> "
@@@ -5471,8 -14527,21 +14566,22 @@@ SUITE(extraction)
/* Functional */
RUN_TEST(elixir_function);
+ RUN_TEST(elixir_def_head_is_covers_the_head_and_every_guard_above_it);
+ RUN_TEST(extract_elixir_guarded_def_head);
+ RUN_TEST(extract_elixir_clauses_fold_only_when_adjacent_in_one_module);
+ RUN_TEST(extract_elixir_nested_module_clauses_do_not_fold);
+ RUN_TEST(extract_elixir_folded_clause_is_exported_is_the_or);
+ RUN_TEST(extract_elixir_guarded_clause_head_is_not_a_self_call);
+ RUN_TEST(extract_elixir_declaration_head_mints_no_reference_of_any_kind);
+ RUN_TEST(extract_elixir_real_recursion_survives_head_suppression);
+ RUN_TEST(extract_elixir_typespec_attribute_is_not_code);
+ RUN_TEST(elixir_call_string_argument);
+ RUN_TEST(extract_elixir_guarded_def_head_scope);
+ RUN_TEST(extract_elixir_guarded_def_head_guard_usages);
+ RUN_TEST(elixir_channels_pubsub_and_handle_in);
+ RUN_TEST(elixir_complexity_and_fingerprint);
RUN_TEST(haskell_function);
+ RUN_TEST(haskell_infix_definition_name);
RUN_TEST(ocaml_function);
RUN_TEST(erlang_function);