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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
perf(ts): memoize expression-type evaluation per node
Martin Vogel51770de0b6c6
diff --git a/Makefile.cbm b/Makefile.cbmindex e31a1bb40..5b90c388e 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -713,9 +713,9 @@ BUILD_DIR = build/c# Grammar + tree-sitter runtime: compiled without -Werror (upstream code has warnings)GRAMMAR_CFLAGS = -std=c11 -D_DEFAULT_SOURCE -O2 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC)GRAMMAR_CFLAGS_TEST = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \- $(SANITIZED_DEFINE) $(SANITIZE)+ -DCBM_ENABLE_TEST_SEAMS=1 $(SANITIZED_DEFINE) $(SANITIZE)GRAMMAR_CFLAGS_TSAN = -std=c11 -D_DEFAULT_SOURCE -g -O1 -w -I$(CBM_DIR) -I$(TS_INCLUDE) -I$(TS_SRC) \- -DCBM_SANITIZED_BUILD=1 $(TSAN_SANITIZE)+ -DCBM_ENABLE_TEST_SEAMS=1 -DCBM_SANITIZED_BUILD=1 $(TSAN_SANITIZE)# Object files for grammars + ts_runtime + lsp_all + preprocessorGRAMMAR_OBJS_TEST = $(patsubst $(CBM_DIR)/%.c,$(BUILD_DIR)/%.o,$(GRAMMAR_SRCS))diff --git a/internal/cbm/lsp/ts_lsp.c b/internal/cbm/lsp/ts_lsp.cindex 0f3c96cb3..fc8b8911f 100644--- a/internal/cbm/lsp/ts_lsp.c+++ b/internal/cbm/lsp/ts_lsp.c@@ -70,6 +70,107 @@ static void ts_type_budget_reset(size_t source_len) {g_ts_type_budget_warned = false;}+/* Bumped on every degraded eval return (depth cap or budget exhaustion). An+ * evaluation whose subtree bumped this counter must NOT be memoized: its value+ * embeds the degradation, and first-eval-wins would freeze it for call sites+ * that could have evaluated the node fully. */+static _Thread_local unsigned long g_ts_eval_degraded;++/* Expression-type memo (per file): node.id -> evaluated CBMType.+ *+ * ts_signature_for_call re-evaluates a call's argument expressions while+ * resolving overloads, and boolean/spread chains re-enter the same+ * subexpression once per enclosing alternative — the TS suite's+ * objectSpreadRepeatedComplexity.js builds a union of 2^(n-1) members and+ * measured 11+ s for a 3.6 KB file while emitting the same 5-node graph+ * v0.9.0 emits in 0.14 s. Expression types are position-pure within a file+ * pass (one node = one scope path, and the per-file walk is single-threaded+ * and deterministic), so one eval per node is the correct semantics, not a+ * cache trade-off. Degraded results are never stored (see+ * g_ts_eval_degraded). Arena-backed, linear-probed, power-of-two capacity;+ * grows by rehash and dies with the file pass. */+typedef struct TsEvalMemo {+ const void **keys; /* TSNode.id; NULL = empty slot */+ const CBMType **vals;+ uint32_t cap;+ uint32_t count;+} TsEvalMemo;++static uint32_t ts_memo_slot(const TsEvalMemo *m, const void *id) {+ uint64_t x = (uint64_t)(uintptr_t)id;+ x ^= x >> 33;+ x *= 0xff51afd7ed558ccdULL;+ x ^= x >> 33;+ uint32_t i = (uint32_t)x & (m->cap - 1);+ while (m->keys[i] && m->keys[i] != id)+ i = (i + 1) & (m->cap - 1);+ return i;+}++static const CBMType *ts_memo_get(const TsEvalMemo *m, const void *id) {+ if (!m || !m->cap)+ return NULL;+ uint32_t i = ts_memo_slot(m, id);+ return m->keys[i] ? m->vals[i] : NULL;+}++static void ts_memo_put(TSLSPContext *ctx, const void *id, const CBMType *t) {+ TsEvalMemo *m = ctx->eval_memo;+ if (!m) {+ m = (TsEvalMemo *)cbm_arena_alloc(ctx->arena, sizeof(*m));+ if (!m)+ return;+ m->cap = 1024;+ m->count = 0;+ m->keys = (const void **)cbm_arena_alloc(ctx->arena, m->cap * sizeof(*m->keys));+ m->vals = (const CBMType **)cbm_arena_alloc(ctx->arena, m->cap * sizeof(*m->vals));+ if (!m->keys || !m->vals)+ return;+ memset(m->keys, 0, m->cap * sizeof(*m->keys));+ memset(m->vals, 0, m->cap * sizeof(*m->vals));+ ctx->eval_memo = m;+ }+ if (m->count * 10 >= m->cap * 7) { /* grow at 70% load */+ TsEvalMemo bigger = {0};+ bigger.cap = m->cap * 2;+ bigger.keys = (const void **)cbm_arena_alloc(ctx->arena, bigger.cap * sizeof(*bigger.keys));+ bigger.vals =+ (const CBMType **)cbm_arena_alloc(ctx->arena, bigger.cap * sizeof(*bigger.vals));+ if (!bigger.keys || !bigger.vals)+ return; /* keep serving from the full table; stores stop */+ memset(bigger.keys, 0, bigger.cap * sizeof(*bigger.keys));+ memset(bigger.vals, 0, bigger.cap * sizeof(*bigger.vals));+ for (uint32_t i = 0; i < m->cap; i++) {+ if (!m->keys[i])+ continue;+ uint32_t j = ts_memo_slot(&bigger, m->keys[i]);+ bigger.keys[j] = m->keys[i];+ bigger.vals[j] = m->vals[i];+ }+ bigger.count = m->count;+ *m = bigger; /* old arrays stay in the arena */+ }+ uint32_t i = ts_memo_slot(m, id);+ if (!m->keys[i]) {+ m->keys[i] = id;+ m->vals[i] = t;+ m->count++;+ }+}++#ifdef CBM_ENABLE_TEST_SEAMS+/* Complexity-regression seam: expose the thread's remaining eval budget and+ * the warned flag after a cbm_run_ts_lsp call. Budget units consumed are a+ * deterministic work counter — the memo turns the spread-bomb class from+ * O(2^n) evals into O(nodes), which tests assert without wall-clock. */+long cbm_ts_lsp_test_budget_remaining(void) {+ return g_ts_type_budget;+}+bool cbm_ts_lsp_test_budget_warned(void) {+ return g_ts_type_budget_warned;+}+#endif+#define TS_LSP_MAX_EVAL_DEPTH 64#define TS_LSP_FIELD_LEN(s) ((uint32_t)(sizeof(s) - 1))@@ -1978,8 +2079,17 @@ static const CBMType *return_type_of(CBMArena *arena, const CBMType *sig) {const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {if (!ctx || ts_node_is_null(node))return cbm_type_unknown();- if (ctx->eval_depth > TS_LSP_MAX_EVAL_DEPTH)+ /* Memo hit: O(1), charges no budget, ignores depth — the value came from a+ * completed, non-degraded evaluation of this exact node. */+ {+ const CBMType *memo = ts_memo_get(ctx->eval_memo, node.id);+ if (memo)+ return memo;+ }+ if (ctx->eval_depth > TS_LSP_MAX_EVAL_DEPTH) {+ g_ts_eval_degraded++;return cbm_type_unknown();+ }/* Depth alone does not bound WORK: crafted expressions (e.g. the TS test* suite's repeated object spreads) stay under the depth cap while fanning* out exponentially — one 3.6 KB baseline file measured 11 s here. Charge@@ -1998,10 +2108,14 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {fprintf(stderr, " [tslsp] expression-eval budget exhausted; degrading to ""unknown\n");}+ g_ts_eval_degraded++;return cbm_type_unknown();}}ctx->eval_depth++;+ /* Snapshot for the memo-store guard: any degraded return in this subtree+ * bumps the counter and blocks the store below. */+ unsigned long degraded_before = g_ts_eval_degraded;const CBMType *result = cbm_type_unknown();const char *kind = ts_node_type(node);@@ -2261,6 +2375,11 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {}ctx->eval_depth--;+ /* Store only completed, non-degraded evaluations (see g_ts_eval_degraded);+ * result is never NULL here (initialized to unknown), so NULL stays the+ * empty-slot sentinel. */+ if (result && g_ts_eval_degraded == degraded_before)+ ts_memo_put(ctx, node.id, result);return result;}diff --git a/internal/cbm/lsp/ts_lsp.h b/internal/cbm/lsp/ts_lsp.hindex 63fc14476..c34ceb4ad 100644--- a/internal/cbm/lsp/ts_lsp.h+++ b/internal/cbm/lsp/ts_lsp.h@@ -61,12 +61,23 @@ typedef struct {// Recursion guard for ts_eval_expr_type (mirrors c_lsp).int eval_depth;+ // Expression-type memo: node.id -> evaluated type (lazily created on the+ // first completed eval; see TsEvalMemo in ts_lsp.c). Kills the exponential+ // re-evaluation of shared subexpressions under overload resolution.+ struct TsEvalMemo *eval_memo;// Recursion guard for lookup_member_type: cyclic type graphs (mutually// recursive unions/wrappers across registered types) otherwise recurse// without bound — stack overflow on real repos.int member_depth;} TSLSPContext;+#ifdef CBM_ENABLE_TEST_SEAMS+// Complexity-regression seam: remaining expression-eval budget / warned flag+// for the calling thread, valid after a cbm_run_ts_lsp on the same thread.+long cbm_ts_lsp_test_budget_remaining(void);+bool cbm_ts_lsp_test_budget_warned(void);+#endif+// --- Initialization ---// Initialise a TSLSPContext for processing one file. Mode flags select dialect.diff --git a/tests/test_ts_lsp.c b/tests/test_ts_lsp.cindex 47d3b1d83..52c3bbacb 100644--- a/tests/test_ts_lsp.c+++ b/tests/test_ts_lsp.c@@ -4131,6 +4131,49 @@ TEST(tslsp_nested_class_resolution) {/* JavaScript relies on local `new` inference here, while TypeScript and TSX use* explicit parameter types below. All three parser modes must preserve the* full ordinary call-expression span, independent of JSX-specific behavior. */+/* ── Expression-eval complexity guard ─────────────────────────────────────────+ *+ * The objectSpreadRepeatedComplexity class (TS conformance suite): a chain of+ * `...(c[i] && c[j] && {...})` spreads makes the union fan out 2^(n-1) ways,+ * and overload resolution re-evaluates shared subexpressions once per+ * alternative. The per-node memo turns that into one eval per node. Guarded+ * via the deterministic budget counter, not wall-clock: without the memo this+ * source burns the entire eval budget (warned=true); with it, consumption+ * stays around the node count. */+TEST(tslsp_eval_memo_bounds_spread_bomb_work) {+ /* The tsc-compiled form of that file: nested Object.assign(...) member+ * calls. Resolving the stdlib method evaluates every argument expression+ * once per lookup path (method dispatch + namespace fallback), and the+ * first argument is itself the next nested call — without the memo the+ * shared subtree re-walks once per enclosing level: 2^n evals. */+ char src[16384];+ int off = snprintf(src, sizeof(src), "\"use strict\";\nfunction f(cnd) {\n return ");+ for (int i = 18; i >= 0; i--) {+ off += snprintf(src + off, sizeof(src) - (size_t)off, "Object.assign(");+ }+ off += snprintf(src + off, sizeof(src) - (size_t)off, "{}");+ for (int i = 0; i < 19; i++) {+ off += snprintf(src + off, sizeof(src) - (size_t)off,+ ", (cnd[%d] && cnd[%d] && {\n prop%da: 1,\n prop%db: 1,\n"+ " }))",+ 2 * i + 1, 2 * i + 2, i, i);+ }+ snprintf(src + off, sizeof(src) - (size_t)off, ";\n}\n");++ CBMFileResult *r = extract_js(src);+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(r->defs.count, 1); /* f extracted; the graph itself is tiny */++ /* Same thread ran the eval: the seam reads its final budget state. */+ ASSERT_FALSE(cbm_ts_lsp_test_budget_warned());+ long budget0 = 1000000 + (long)strlen(src) * 64;+ long consumed = budget0 - cbm_ts_lsp_test_budget_remaining();+ ASSERT_LT(consumed, 100000);++ cbm_free_result(r);+ PASS();+}+TEST(tslsp_js_ordinary_same_leaf_calls_join_by_exact_site) {static const char source[] = "class Alpha { render() {} }\n""class Beta { render() {} }\n"@@ -4641,6 +4684,9 @@ SUITE(ts_lsp) {RUN_TEST(tslsp_void_returning_method);RUN_TEST(tslsp_nested_class_resolution);+ /* Expression-eval complexity guard. */+ RUN_TEST(tslsp_eval_memo_bounds_spread_bomb_work);+/* Ordinary same-leaf occurrence identity (JS / TS / TSX). */RUN_TEST(tslsp_js_ordinary_same_leaf_calls_join_by_exact_site);RUN_TEST(tslsp_ts_ordinary_same_leaf_calls_join_by_exact_site);