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.

perf(lsp): make per-file and cross-file LSP walkers O(n); fix two crashes

Martin Vogel1b9d9c136fc5
diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.c
index cd54fcad8..b776f08b7 100644
--- a/internal/cbm/lsp/c_lsp.c
+++ b/internal/cbm/lsp/c_lsp.c
@@ -1,4 +1,5 @@
#include "c_lsp.h"
+#include "lsp_node_iter.h"
#include "../helpers.h"
#include <string.h>
#include <stdio.h>
@@ -3647,10 +3648,16 @@ recurse:;
}
}
- // Recurse into children
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- c_resolve_calls_in_node(ctx, ts_node_child(node, i));
+ // Recurse into children via a cursor (O(n)); ts_node_child(node,i) is O(i)
+ // in tree-sitter → O(n²) on a wide node.
+ {
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ c_resolve_calls_in_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
}
if (push_scope) {
@@ -3959,10 +3966,14 @@ static void c_process_namespace(CLSPContext* ctx, TSNode ns_node) {
TSNode body = ts_node_child_by_field_name(ns_node, "body", 4);
if (!ts_node_is_null(body)) {
- uint32_t nc = ts_node_child_count(body);
- for (uint32_t i = 0; i < nc; i++) {
- c_process_body_child(ctx, ts_node_child(body, i));
+ // Cursor walk (O(n)); namespace bodies can be very wide.
+ TSTreeCursor cursor = ts_tree_cursor_new(body);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ c_process_body_child(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
}
+ ts_tree_cursor_delete(&cursor);
}
ctx->current_namespace = saved_ns;
@@ -4094,10 +4105,11 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
// Pre-pass: register method declarations (no body) as methods in registry.
// This allows template return type substitution for methods like T& value();
if (ctx->enclosing_class_qn) {
- uint32_t nc = ts_node_child_count(body);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(body, i);
- if (ts_node_is_null(child) || !ts_node_is_named(child)) continue;
+ uint32_t bkn = 0;
+ TSNode* bkids = cbm_lsp_collect_children(ctx->arena, body, &bkn);
+ for (uint32_t i = 0; i < bkn; i++) {
+ TSNode child = bkids[i];
+ if (!ts_node_is_named(child)) continue;
const char* ck = ts_node_type(child);
// field_declaration, declaration, or function_definition = method
if (strcmp(ck, "field_declaration") != 0 && strcmp(ck, "declaration") != 0 &&
@@ -4200,10 +4212,11 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
}
}
- uint32_t nc = ts_node_child_count(body);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(body, i);
- if (ts_node_is_null(child) || !ts_node_is_named(child)) continue;
+ uint32_t bkn = 0;
+ TSNode* bkids = cbm_lsp_collect_children(ctx->arena, body, &bkn);
+ for (uint32_t i = 0; i < bkn; i++) {
+ TSNode child = bkids[i];
+ if (!ts_node_is_named(child)) continue;
c_process_body_child(ctx, child);
}
}
@@ -4225,14 +4238,16 @@ __attribute__((no_sanitize("address")))
void c_lsp_process_file(CLSPContext* ctx, TSNode root) {
if (ts_node_is_null(root)) return;
- uint32_t nc = ts_node_child_count(root);
+ // Collect top-level children once (O(n)); both passes reuse the array.
+ // Indexing ts_node_child(root,i) per iteration is O(i) → O(n²) on a wide root.
+ uint32_t kn = 0;
+ TSNode* kids = cbm_lsp_collect_children(ctx->arena, root, &kn);
TSNode child; // Hoisted: prevents ASan stack-use-after-scope between passes
TSNode inner;
// Pass 1: process using declarations and global variables
- for (uint32_t i = 0; i < nc; i++) {
- child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ child = kids[i];
const char* ck = ts_node_type(child);
if (strcmp(ck, "using_declaration") == 0 ||
@@ -4258,9 +4273,8 @@ void c_lsp_process_file(CLSPContext* ctx, TSNode root) {
}
// Pass 2: process functions, namespaces, classes, templates
- for (uint32_t i = 0; i < nc; i++) {
- child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ child = kids[i];
c_process_body_child(ctx, child);
}
}
diff --git a/internal/cbm/lsp/cs_lsp.c b/internal/cbm/lsp/cs_lsp.c
index ef516d0f9..0a4bcc9ba 100644
--- a/internal/cbm/lsp/cs_lsp.c
+++ b/internal/cbm/lsp/cs_lsp.c
@@ -40,6 +40,7 @@
*/
#include "cs_lsp.h"
+#include "lsp_node_iter.h"
#include "../helpers.h"
#include <ctype.h>
#include <stdio.h>
@@ -1611,11 +1612,14 @@ static void cs_resolve_calls_in_node(CSLSPContext *ctx, TSNode node) {
if (strcmp(kind, "block") == 0) {
CBMScope *prev = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, prev);
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(node, i);
- if (!ts_node_is_null(c)) cs_resolve_calls_in_node(ctx, c);
- }
+ // Cursor walk (O(n)); ts_node_child(node,i) is O(i) → O(n²) on a wide block.
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ cs_resolve_calls_in_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
ctx->current_scope = prev;
return;
}
@@ -1637,10 +1641,14 @@ static void cs_resolve_calls_in_node(CSLSPContext *ctx, TSNode node) {
/* Recurse into children. We do NOT pre-bind anything that would only be
* available after the child is processed — left-to-right walk is fine for
* most C# constructs at a Light-Semantic-Pass level. */
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(node, i);
- if (ts_node_is_null(c)) continue;
+ // Cursor walk (O(n)); ts_node_child(node,i) is O(i) → O(n²) on a wide node.
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (!ts_tree_cursor_goto_first_child(&cursor)) {
+ ts_tree_cursor_delete(&cursor);
+ return;
+ }
+ do {
+ TSNode c = ts_tree_cursor_current_node(&cursor);
const char *ck = ts_node_type(c);
/* Don't recurse into nested type/method bodies — they're processed by
* the pass-2 walker which rebuilds enclosing context. */
@@ -1659,7 +1667,8 @@ static void cs_resolve_calls_in_node(CSLSPContext *ctx, TSNode node) {
continue;
}
cs_resolve_calls_in_node(ctx, c);
- }
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ ts_tree_cursor_delete(&cursor);
}
/* ── method/constructor processing ──────────────────────────────── */
@@ -2163,11 +2172,13 @@ void cs_lsp_process_file(CSLSPContext *ctx, TSNode root) {
/* Pass 2: walk top-level. file-scoped namespaces apply to ALL siblings,
* so we keep the namespace pushed for the rest of the walk. */
- uint32_t nc = ts_node_child_count(root);
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t kn = 0;
+ TSNode *kids = cbm_lsp_collect_children(ctx->arena, root, &kn);
bool file_scoped_active = false;
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(root, i);
- if (ts_node_is_null(c) || !ts_node_is_named(c)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode c = kids[i];
+ if (!ts_node_is_named(c)) continue;
const char *k = ts_node_type(c);
if (strcmp(k, "using_directive") == 0) continue;
if (strcmp(k, "file_scoped_namespace_declaration") == 0) {
diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c
index ff4612385..af3e1c61a 100644
--- a/internal/cbm/lsp/go_lsp.c
+++ b/internal/cbm/lsp/go_lsp.c
@@ -1,4 +1,5 @@
#include "go_lsp.h"
+#include "lsp_node_iter.h"
#include "../helpers.h"
#include <string.h>
#include <stdio.h>
@@ -1453,10 +1454,16 @@ recurse:;
return;
}
- // Recurse into children
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- resolve_calls_in_node(ctx, ts_node_child(node, i));
+ // Recurse into children via a cursor (O(n)); ts_node_child(node,i) is O(i)
+ // → O(n²) on a wide node.
+ {
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ resolve_calls_in_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
}
if (push_scope) {
@@ -1590,13 +1597,14 @@ static void process_function(GoLSPContext* ctx, TSNode func_node) {
void go_lsp_process_file(GoLSPContext* ctx, TSNode root) {
if (ts_node_is_null(root)) return;
- uint32_t nc = ts_node_child_count(root);
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t kn = 0;
+ TSNode* kids = cbm_lsp_collect_children(ctx->arena, root, &kn);
// Pass 1: Bind package-level var/const declarations into root scope.
// Must happen before processing functions so all globals are visible.
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode child = kids[i];
const char* kind = ts_node_type(child);
if (strcmp(kind, "var_declaration") == 0 || strcmp(kind, "const_declaration") == 0) {
@@ -1610,9 +1618,8 @@ void go_lsp_process_file(GoLSPContext* ctx, TSNode root) {
}
// Pass 2: Process function/method bodies
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode child = kids[i];
const char* kind = ts_node_type(child);
if (strcmp(kind, "function_declaration") == 0 ||
@@ -1778,10 +1785,11 @@ void cbm_run_go_lsp(CBMArena* arena, CBMFileResult* result,
// Phase 1b: Scan AST for struct definitions to populate embedded_types
{
- uint32_t root_nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < root_nc; i++) {
- TSNode top = ts_node_child(root, i);
- if (ts_node_is_null(top)) continue;
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t rkn = 0;
+ TSNode* rkids = cbm_lsp_collect_children(arena, root, &rkn);
+ for (uint32_t i = 0; i < rkn; i++) {
+ TSNode top = rkids[i];
const char* tk = ts_node_type(top);
// type_declaration contains type_spec children
if (strcmp(tk, "type_declaration") != 0) continue;
@@ -2284,10 +2292,11 @@ static const CBMType* parse_type_node_with_params(CBMArena* arena, TSNode node,
static void extract_type_params_from_ast(CBMArena* arena, CBMTypeRegistry* reg,
TSNode root, const char* source, const char* module_qn) {
- uint32_t root_nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < root_nc; i++) {
- TSNode top = ts_node_child(root, i);
- if (ts_node_is_null(top)) continue;
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t rkn = 0;
+ TSNode* rkids = cbm_lsp_collect_children(arena, root, &rkn);
+ for (uint32_t i = 0; i < rkn; i++) {
+ TSNode top = rkids[i];
if (strcmp(ts_node_type(top), "function_declaration") != 0) continue;
// Check for type_parameter_list (field name: "type_parameters", 15 chars)
@@ -2544,10 +2553,11 @@ void cbm_run_go_lsp_cross(
// 3. Phase 1b: Scan AST for struct definitions to populate embedded_types
{
- uint32_t root_nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < root_nc; i++) {
- TSNode top = ts_node_child(root, i);
- if (ts_node_is_null(top)) continue;
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t rkn = 0;
+ TSNode* rkids = cbm_lsp_collect_children(arena, root, &rkn);
+ for (uint32_t i = 0; i < rkn; i++) {
+ TSNode top = rkids[i];
if (strcmp(ts_node_type(top), "type_declaration") != 0) continue;
uint32_t td_nc = ts_node_child_count(top);
for (uint32_t j = 0; j < td_nc; j++) {
diff --git a/internal/cbm/lsp/lsp_node_iter.h b/internal/cbm/lsp/lsp_node_iter.h
new file mode 100644
index 000000000..033962f14
--- /dev/null
+++ b/internal/cbm/lsp/lsp_node_iter.h
@@ -0,0 +1,42 @@
+/*
+ * lsp_node_iter.h — O(n) child enumeration for the per-language LSP walkers.
+ *
+ * tree-sitter's ts_node_child(node, i) is O(i): it walks the child iterator
+ * from the first child every call. So the common idiom
+ *
+ * uint32_t nc = ts_node_child_count(node);
+ * for (uint32_t i = 0; i < nc; i++) { TSNode c = ts_node_child(node, i); ... }
+ *
+ * is O(n²) over a node's children — catastrophic on a wide root (e.g. a program
+ * node holding hundreds of thousands of top-level statements, as in TS's
+ * reallyLargeFile.ts fixture: 583K comment lines made the per-file LSP passes
+ * run for ~133 minutes). cbm_lsp_collect_children() enumerates the children in
+ * a single O(n) cursor pass into an arena array; callers then index the array.
+ */
+#ifndef CBM_LSP_NODE_ITER_H
+#define CBM_LSP_NODE_ITER_H
+
+#include "../arena.h"
+#include "tree_sitter/api.h"
+
+/* Collect `node`'s children into an arena array (source order) via one O(n)
+ * cursor pass. Returns NULL and sets *out_n=0 for a childless node or on OOM. */
+static inline TSNode* cbm_lsp_collect_children(CBMArena* arena, TSNode node, uint32_t* out_n) {
+ uint32_t nc = ts_node_child_count(node);
+ *out_n = 0;
+ if (nc == 0) return NULL;
+ TSNode* kids = (TSNode*)cbm_arena_alloc(arena, (size_t)nc * sizeof(TSNode));
+ if (!kids) return NULL;
+ uint32_t kn = 0;
+ TSTreeCursor cur = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cur)) {
+ do {
+ kids[kn++] = ts_tree_cursor_current_node(&cur);
+ } while (kn < nc && ts_tree_cursor_goto_next_sibling(&cur));
+ }
+ ts_tree_cursor_delete(&cur);
+ *out_n = kn;
+ return kids;
+}
+
+#endif /* CBM_LSP_NODE_ITER_H */
diff --git a/internal/cbm/lsp/php_lsp.c b/internal/cbm/lsp/php_lsp.c
index 3e0e6787a..d2d940858 100644
--- a/internal/cbm/lsp/php_lsp.c
+++ b/internal/cbm/lsp/php_lsp.c
@@ -18,6 +18,7 @@
*/
#include "php_lsp.h"
+#include "lsp_node_iter.h"
#include "../helpers.h"
#include <ctype.h>
#include <stdio.h>
@@ -2066,11 +2067,15 @@ static void php_resolve_calls_in_node(PHPLSPContext *ctx, TSNode node) {
}
}
- /* Recurse. */
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(node, i);
- if (!ts_node_is_null(c)) php_resolve_calls_in_node(ctx, c);
+ /* Recurse via a cursor (O(n)); ts_node_child(node,i) is O(i) → O(n²) on a wide node. */
+ {
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ php_resolve_calls_in_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
}
}
@@ -2373,10 +2378,11 @@ void php_lsp_process_file(PHPLSPContext *ctx, TSNode root) {
if (ts_node_is_null(root)) return;
/* Pass 1: namespace + use declarations. */
- uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(root, i);
- if (ts_node_is_null(c)) continue;
+ // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²).
+ uint32_t kn = 0;
+ TSNode *kids = cbm_lsp_collect_children(ctx->arena, root, &kn);
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode c = kids[i];
const char *k = ts_node_type(c);
if (strcmp(k, "namespace_definition") == 0) {
set_namespace_from_decl(ctx, c);
@@ -2386,9 +2392,8 @@ void php_lsp_process_file(PHPLSPContext *ctx, TSNode root) {
}
/* Pass 2: process classes and top-level functions. */
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(root, i);
- if (ts_node_is_null(c)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode c = kids[i];
const char *k = ts_node_type(c);
if (strcmp(k, "class_declaration") == 0 || strcmp(k, "trait_declaration") == 0 ||
strcmp(k, "interface_declaration") == 0 || strcmp(k, "enum_declaration") == 0) {
@@ -3670,10 +3675,11 @@ void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
php_class_field_table_t tab = {0};
/* First pass to populate the use map (so type names in property
* declarations resolve correctly). */
- uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(root, i);
- if (ts_node_is_null(c)) continue;
+ /* Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). */
+ uint32_t pkn = 0;
+ TSNode *pkids = cbm_lsp_collect_children(ctx.arena, root, &pkn);
+ for (uint32_t i = 0; i < pkn; i++) {
+ TSNode c = pkids[i];
const char *k = ts_node_type(c);
if (strcmp(k, "namespace_definition") == 0) {
set_namespace_from_decl(&ctx, c);
@@ -3873,10 +3879,11 @@ void cbm_run_php_lsp_cross(
* resolve to the right type during the call walk. */
{
php_class_field_table_t tab = {0};
- uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_child(root, i);
- if (ts_node_is_null(c)) continue;
+ /* Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). */
+ uint32_t pkn = 0;
+ TSNode *pkids = cbm_lsp_collect_children(ctx.arena, root, &pkn);
+ for (uint32_t i = 0; i < pkn; i++) {
+ TSNode c = pkids[i];
const char *k = ts_node_type(c);
if (strcmp(k, "namespace_definition") == 0) {
set_namespace_from_decl(&ctx, c);
diff --git a/internal/cbm/lsp/ts_lsp.c b/internal/cbm/lsp/ts_lsp.c
index ccf4672d3..048b3a459 100644
--- a/internal/cbm/lsp/ts_lsp.c
+++ b/internal/cbm/lsp/ts_lsp.c
@@ -50,6 +50,31 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
static const CBMRegisteredFunc* lookup_method(TSLSPContext* ctx, const CBMType* recv,
const char* method_name);
static char* node_text(TSLSPContext* ctx, TSNode node);
+
+// Collect a node's children into an arena array via a single O(n) cursor pass.
+// Returns NULL (and sets *out_n=0) for a childless node or on OOM. Use this in
+// place of the `for (i=0; i<count; i++) ts_node_child(node, i)` idiom: in
+// tree-sitter ts_node_child(node, i) is O(i), so that loop is O(n²) on a wide
+// node — e.g. a program root holding hundreds of thousands of top-level nodes
+// (the reallyLargeFile.ts fixture is 583K lines of comment markup → 583K
+// children, which made the per-file LSP passes run for ~133 minutes).
+static TSNode* collect_children(CBMArena* arena, TSNode node, uint32_t* out_n) {
+ uint32_t nc = ts_node_child_count(node);
+ *out_n = 0;
+ if (nc == 0) return NULL;
+ TSNode* kids = (TSNode*)cbm_arena_alloc(arena, (size_t)nc * sizeof(TSNode));
+ if (!kids) return NULL;
+ uint32_t kn = 0;
+ TSTreeCursor cur = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cur)) {
+ do {
+ kids[kn++] = ts_tree_cursor_current_node(&cur);
+ } while (kn < nc && ts_tree_cursor_goto_next_sibling(&cur));
+ }
+ ts_tree_cursor_delete(&cur);
+ *out_n = kn;
+ return kids;
+}
static const CBMType* simplify_type(TSLSPContext* ctx, const CBMType* t);
static const CBMType* unwrap_passthrough_template(const CBMType* t);
@@ -1318,13 +1343,17 @@ static const CBMRegisteredFunc* lookup_method(TSLSPContext* ctx, const CBMType*
// Pull the underlying return type out of a FUNC signature, collapsing single-element
// return arrays to that element.
-static const CBMType* return_type_of(const CBMType* sig) {
+static const CBMType* return_type_of(CBMArena* arena, const CBMType* sig) {
if (!sig || sig->kind != CBM_TYPE_FUNC) return cbm_type_unknown();
if (!sig->data.func.return_types || !sig->data.func.return_types[0]) return cbm_type_unknown();
if (!sig->data.func.return_types[1]) return sig->data.func.return_types[0];
int count = 0;
while (sig->data.func.return_types[count]) count++;
- return cbm_type_tuple(NULL, sig->data.func.return_types, count);
+ // Multi-return → build a tuple. Needs a real arena: passing NULL here
+ // crashed in cbm_arena_alloc when the cross-resolve path evaluated a
+ // multi-return signature (only reachable once the per-file LSP O(n²) was
+ // fixed and the resolve phase actually ran).
+ return cbm_type_tuple(arena, sig->data.func.return_types, count);
}
const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
@@ -1409,7 +1438,7 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
ts_node_type(fn), fn_type ? (int)fn_type->kind : -1);
}
if (fn_type && fn_type->kind == CBM_TYPE_FUNC) {
- result = return_type_of(fn_type);
+ result = return_type_of(ctx->arena, fn_type);
// Polymorphic `this` return type: when the registered signature uses
// `this` (TYPE_PARAM "this"), substitute the actual receiver type
@@ -2111,8 +2140,13 @@ static void process_callback_arrow(TSLSPContext* ctx, TSNode arrow, const CBMTyp
TSNode body = ts_node_child_by_field_name(arrow, "body", TS_LSP_FIELD_LEN("body"));
if (!ts_node_is_null(body)) {
if (strcmp(ts_node_type(body), "statement_block") == 0) {
- uint32_t bc = ts_node_child_count(body);
- for (uint32_t i = 0; i < bc; i++) process_node(ctx, ts_node_child(body, i));
+ TSTreeCursor cursor = ts_tree_cursor_new(body);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ process_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
} else {
process_node(ctx, body);
}
@@ -2354,12 +2388,22 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// Process the function child for nested call resolution.
process_node(ctx, fn_node);
+ // param_types is NULL-terminated (no count field). Measure its
+ // length so we never index past the terminator: a call may pass
+ // more args than the function declares params (e.g. excess/variadic
+ // args), and the extra args simply have no expected type. Indexing
+ // param_types[i] by the raw arg count read out of bounds → garbage
+ // CBMType* → crash on expected->kind.
+ uint32_t param_count = 0;
+ while (fn_type->data.func.param_types[param_count]) param_count++;
+
uint32_t argc = ts_node_named_child_count(args);
for (uint32_t i = 0; i < argc; i++) {
TSNode arg = ts_node_named_child(args, i);
if (ts_node_is_null(arg)) continue;
const char* ak = ts_node_type(arg);
- const CBMType* expected = fn_type->data.func.param_types[i];
+ const CBMType* expected =
+ (i < param_count) ? fn_type->data.func.param_types[i] : NULL;
if ((strcmp(ak, "arrow_function") == 0 ||
strcmp(ak, "function_expression") == 0) &&
expected && expected->kind == CBM_TYPE_FUNC) {
@@ -2611,9 +2655,17 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
return;
}
- // Default: recurse into children.
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t i = 0; i < nc; i++) process_node(ctx, ts_node_child(node, i));
+ // Default: recurse into children via a cursor (O(n)). ts_node_child(node,i)
+ // is O(i) in tree-sitter → O(n²) when `node` is a wide block/root.
+ {
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ process_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
+ }
}
static void process_function_body(TSLSPContext* ctx, TSNode func_node, const char* func_qn,
@@ -2665,8 +2717,13 @@ static void process_function_body(TSLSPContext* ctx, TSNode func_node, const cha
// arrow): walk the expression directly — process_node on that handles
// call_expression resolution.
if (strcmp(ts_node_type(body), "statement_block") == 0) {
- uint32_t nc = ts_node_child_count(body);
- for (uint32_t i = 0; i < nc; i++) process_node(ctx, ts_node_child(body, i));
+ TSTreeCursor cursor = ts_tree_cursor_new(body);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ process_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
} else {
process_node(ctx, body);
}
@@ -2681,12 +2738,14 @@ void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
if (!ctx || ts_node_is_null(root)) return;
if (ctx->dts_mode) return;
- uint32_t nc = ts_node_child_count(root);
+ // Collect top-level children once (O(n)); both passes reuse the array.
+ // See collect_children: indexing ts_node_child(root,i) here would be O(n²).
+ uint32_t kn = 0;
+ TSNode* kids = collect_children(ctx->arena, root, &kn);
// Pass 1: bind module-level declarations into root scope.
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode child = kids[i];
const char* kind = ts_node_type(child);
if (strcmp(kind, "lexical_declaration") == 0 ||
strcmp(kind, "variable_declaration") == 0) {
@@ -2695,9 +2754,8 @@ void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
}
// Pass 2: process functions, methods, and class bodies.
- for (uint32_t i = 0; i < nc; i++) {
- TSNode child = ts_node_child(root, i);
- if (ts_node_is_null(child)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode child = kids[i];
const char* kind = ts_node_type(child);
if (strcmp(kind, "function_declaration") == 0) {
@@ -3852,10 +3910,10 @@ static void parse_jsdoc_block(TSLSPContext* ctx, const char* text, size_t len,
static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
if (!ctx->js_mode || ts_node_is_null(root) || !reg || !ctx->module_qn) return;
- uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode n = ts_node_child(root, i);
- if (ts_node_is_null(n)) continue;
+ uint32_t kn = 0;
+ TSNode* kids = collect_children(ctx->arena, root, &kn);
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode n = kids[i];
if (strcmp(ts_node_type(n), "function_declaration") != 0) continue;
// Find the immediate preceding comment sibling (skip whitespace nodes which
@@ -3863,8 +3921,7 @@ static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegist
// comment nodes).
TSNode prev = {0};
for (int j = (int)i - 1; j >= 0; j--) {
- TSNode candidate = ts_node_child(root, (uint32_t)j);
- if (ts_node_is_null(candidate)) continue;
+ TSNode candidate = kids[j];
const char* ck = ts_node_type(candidate);
if (strcmp(ck, "comment") == 0) { prev = candidate; break; }
// Anything else: stop — JSDoc must be immediately preceding.
@@ -3932,11 +3989,11 @@ static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegist
// implicit return-type inference at a coarse level (single-return common case).
static void infer_implicit_returns(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
if (ts_node_is_null(root) || !reg || !ctx->module_qn) return;
- uint32_t nc = ts_node_child_count(root);
+ uint32_t kn = 0;
+ TSNode* kids = collect_children(ctx->arena, root, &kn);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode n = ts_node_child(root, i);
- if (ts_node_is_null(n)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode n = kids[i];
const char* k = ts_node_type(n);
TSNode decl = n;
@@ -3998,11 +4055,11 @@ static void infer_implicit_returns(TSLSPContext* ctx, TSNode root, CBMTypeRegist
// embedded_types / type_param_names.
static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
if (ts_node_is_null(root) || !reg) return;
- uint32_t nc = ts_node_child_count(root);
+ uint32_t kn = 0;
+ TSNode* kids = collect_children(ctx->arena, root, &kn);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode n = ts_node_child(root, i);
- if (ts_node_is_null(n)) continue;
+ for (uint32_t i = 0; i < kn; i++) {
+ TSNode n = kids[i];
const char* k = ts_node_type(n);
TSNode decl = n;
if (strcmp(k, "export_statement") == 0) {
@@ -4233,6 +4290,234 @@ void cbm_run_ts_lsp(CBMArena* arena, CBMFileResult* result,
// ── Cross-file entry point (Phase 3) ──────────────────────────────────────────
+/* Register a batch of CBMLSPDef[] into a registry. Mirrors the inline
+ * loop in cbm_run_ts_lsp_cross — KEEP IN SYNC. Shared by the Tier 2
+ * pre-built registry builder + per-file overlay builder. Def-driven
+ * (return/field/embedded/method info from def strings). */
+static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
+ CBMLSPDef* defs, int def_count) {
+ for (int i = 0; i < def_count; i++) {
+ const CBMLSPDef* d = &defs[i];
+ if (!d->qualified_name || !d->short_name || !d->label) continue;
+
+ if (strcmp(d->label, "Class") == 0 || strcmp(d->label, "Interface") == 0) {
+ CBMRegisteredType rt;
+ memset(&rt, 0, sizeof(rt));
+ rt.qualified_name = d->qualified_name;
+ rt.short_name = d->short_name;
+ rt.is_interface = (strcmp(d->label, "Interface") == 0);
+ if (d->embedded_types && d->embedded_types[0]) {
+ int n = 1;
+ for (const char* s = d->embedded_types; *s; s++) if (*s == '|') n++;
+ const char** arr = (const char**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const char*));
+ if (arr) {
+ int idx = 0;
+ const char* start = d->embedded_types;
+ for (const char* s = d->embedded_types;; s++) {
+ if (*s == '|' || *s == '\0') {
+ arr[idx++] = cbm_arena_strndup(arena, start, (size_t)(s - start));
+ if (*s == '\0') break;
+ start = s + 1;
+ }
+ }
+ arr[idx] = NULL;
+ rt.embedded_types = arr;
+ }
+ }
+ if (d->field_defs && d->field_defs[0]) {
+ int n = 1;
+ for (const char* s = d->field_defs; *s; s++) if (*s == '|') n++;
+ const char** fn_arr = (const char**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const char*));
+ const CBMType** ft_arr = (const CBMType**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const CBMType*));
+ if (fn_arr && ft_arr) {
+ int idx = 0;
+ const char* start = d->field_defs;
+ for (const char* s = d->field_defs;; s++) {
+ if (*s == '|' || *s == '\0') {
+ char* pair = cbm_arena_strndup(arena, start, (size_t)(s - start));
+ char* colon = pair ? strchr(pair, ':') : NULL;
+ if (pair && colon) {
+ *colon = '\0';
+ fn_arr[idx] = pair;
+ ft_arr[idx] = parse_ts_type_text(arena, colon + 1,
+ d->def_module_qn);
+ idx++;
+ }
+ if (*s == '\0') break;
+ start = s + 1;
+ }
+ }
+ fn_arr[idx] = NULL;
+ ft_arr[idx] = NULL;
+ rt.field_names = fn_arr;
+ rt.field_types = ft_arr;
+ }
+ }
+ cbm_registry_add_type(reg, rt);
+ if (d->method_names_str && d->method_names_str[0]) {
+ int n = 1;
+ for (const char* s = d->method_names_str; *s; s++) if (*s == '|') n++;
+ const char** mn_arr = (const char**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const char*));
+ const char** mqn_arr = (const char**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const char*));
+ if (mn_arr && mqn_arr) {
+ int idx = 0;
+ const char* start = d->method_names_str;
+ for (const char* s = d->method_names_str;; s++) {
+ if (*s == '|' || *s == '\0') {
+ char* m = cbm_arena_strndup(arena, start, (size_t)(s - start));
+ mn_arr[idx] = m;
+ mqn_arr[idx] = cbm_arena_sprintf(arena, "%s.%s", d->qualified_name, m);
+ idx++;
+ if (*s == '\0') break;
+ start = s + 1;
+ }
+ }
+ mn_arr[idx] = NULL;
+ mqn_arr[idx] = NULL;
+ if (reg->type_count > 0) {
+ CBMRegisteredType* rt_just = &reg->types[reg->type_count - 1];
+ rt_just->method_names = mn_arr;
+ rt_just->method_qns = mqn_arr;
+ }
+ }
+ }
+ } else if (strcmp(d->label, "Function") == 0 || strcmp(d->label, "Method") == 0) {
+ CBMRegisteredFunc rf;
+ memset(&rf, 0, sizeof(rf));
+ rf.qualified_name = d->qualified_name;
+ rf.short_name = d->short_name;
+ rf.min_params = -1;
+ if (d->return_types && d->return_types[0]) {
+ int n = 1;
+ for (const char* s = d->return_types; *s; s++) if (*s == '|') n++;
+ const CBMType** rets = (const CBMType**)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const CBMType*));
+ if (rets) {
+ int idx = 0;
+ const char* start = d->return_types;
+ for (const char* s = d->return_types;; s++) {
+ if (*s == '|' || *s == '\0') {
+ char* part = cbm_arena_strndup(arena, start, (size_t)(s - start));
+ rets[idx++] = parse_ts_type_text(arena, part, d->def_module_qn);
+ if (*s == '\0') break;
+ start = s + 1;
+ }
+ }
+ rets[idx] = NULL;
+ rf.signature = cbm_type_func(arena, NULL, NULL, rets);
+ }
+ }
+ if (strcmp(d->label, "Method") == 0 && d->receiver_type) {
+ rf.receiver_type = d->receiver_type;
+ }
+ cbm_registry_add_func(reg, rf);
+ }
+ }
+}
+
+/* Tier 2: build a project-wide TS/JS/TSX registry ONCE from all defs
+ * (filters by lang). Shared READ-ONLY *base* across resolve workers.
+ * Per-file overlays (built by cbm_run_ts_lsp_cross_with_registry)
+ * chain to this via the registry fallback pointer. */
+CBMTypeRegistry* cbm_ts_build_cross_registry(CBMArena* arena, CBMLSPDef* defs, int def_count) {
+ if (!arena) return NULL;
+ CBMTypeRegistry* reg = (CBMTypeRegistry*)cbm_arena_alloc(arena, sizeof(*reg));
+ if (!reg) return NULL;
+ cbm_registry_init(reg, arena);
+ cbm_ts_stdlib_register(reg, arena);
+ for (int i = 0; i < def_count; i++) {
+ CBMLSPDef* d = &defs[i];
+ if (d->lang != CBM_LANG_JAVASCRIPT && d->lang != CBM_LANG_TYPESCRIPT &&
+ d->lang != CBM_LANG_TSX) {
+ continue;
+ }
+ ts_register_lsp_defs(arena, reg, d, 1);
+ }
+ cbm_registry_finalize(reg);
+ return reg;
+}
+
+/* Tier 2 per-file resolve. Builds a SMALL per-file overlay registry P
+ * containing only this file's own-module defs (so the AST refinement
+ * passes — which mutate type shapes/aliases of locally-declared types
+ * — operate on P, not the shared base). P chains to the shared base
+ * `reg` for cross-file + stdlib lookups. This preserves the per-file
+ * AST refinement quality while avoiding re-registering imported
+ * modules' defs in every file. */
+void cbm_run_ts_lsp_cross_with_registry(CBMArena* arena,
+ const char* source, int source_len,
+ const char* module_qn,
+ bool js_mode, bool jsx_mode, bool dts_mode,
+ CBMTypeRegistry* reg,
+ CBMLSPDef* defs, int def_count,
+ const char** import_names, const char** import_qns,
+ int import_count,
+ TSTree* cached_tree,
+ CBMResolvedCallArray* out) {
+ if (!arena || !out || !reg) return;
+
+ /* Per-file overlay: register only the file's own-module defs so the
+ * AST passes can refine them. Imports/stdlib resolve via fallback. */
+ CBMTypeRegistry overlay;
+ cbm_registry_init(&overlay, arena);
+ overlay.fallback = reg;
+ for (int i = 0; i < def_count; i++) {
+ CBMLSPDef* d = &defs[i];
+ const char* dm = d->def_module_qn ? d->def_module_qn : "";
+ if (module_qn && strcmp(dm, module_qn) == 0) {
+ ts_register_lsp_defs(arena, &overlay, d, 1);
+ }
+ }
+
+ TSTree* tree = cached_tree;
+ bool owns_tree = false;
+ if (!tree) {
+ if (!source || source_len <= 0) return;
+ TSParser* parser = ts_parser_new();
+ if (!parser) return;
+ const TSLanguage* lang = jsx_mode ? (js_mode ? tree_sitter_javascript()
+ : tree_sitter_tsx())
+ : (js_mode ? tree_sitter_javascript()
+ : tree_sitter_typescript());
+ ts_parser_set_language(parser, lang);
+ tree = ts_parser_parse_string(parser, NULL, source, source_len);
+ ts_parser_delete(parser);
+ if (!tree) return;
+ owns_tree = true;
+ }
+ TSNode root = ts_tree_root_node(tree);
+ if (ts_node_is_null(root)) {
+ if (owns_tree) ts_tree_delete(tree);
+ return;
+ }
+
+ cbm_registry_finalize(&overlay);
+
+ TSLSPContext ctx;
+ ts_lsp_init(&ctx, arena, source, source_len, &overlay, module_qn,
+ js_mode, jsx_mode, dts_mode, out);
+ for (int i = 0; i < import_count; i++) {
+ if (import_names && import_qns && import_names[i] && import_qns[i]) {
+ ts_lsp_add_import(&ctx, import_names[i], import_qns[i]);
+ }
+ }
+
+ ast_sweep_shapes(&ctx, root, &overlay);
+ rebuild_signatures_from_ast(&ctx, root, &overlay);
+ convert_signature_type_params(&ctx, root, &overlay);
+ apply_jsdoc_signatures(&ctx, root, &overlay);
+ infer_implicit_returns(&ctx, root, &overlay);
+
+ ts_lsp_process_file(&ctx, root);
+
+ if (owns_tree) ts_tree_delete(tree);
+}
+
void cbm_run_ts_lsp_cross(CBMArena* arena,
const char* source, int source_len,
const char* module_qn,
diff --git a/internal/cbm/lsp/ts_lsp.h b/internal/cbm/lsp/ts_lsp.h
index f59fd46fa..61831d65c 100644
--- a/internal/cbm/lsp/ts_lsp.h
+++ b/internal/cbm/lsp/ts_lsp.h
@@ -103,6 +103,26 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
TSTree* cached_tree,
CBMResolvedCallArray* out);
+// Tier 2: build a project-wide TS/JS/TSX registry ONCE from all defs
+// (filters by lang). Shared READ-ONLY base; per-file overlays chain to
+// it via the registry fallback pointer.
+CBMTypeRegistry* cbm_ts_build_cross_registry(CBMArena* arena, CBMLSPDef* defs, int def_count);
+
+// Tier 2 per-file resolve. Builds a small per-file overlay (the file's
+// own-module defs, AST-refined) that chains to the shared base `reg`.
+// `defs`/`def_count` are the file's relevant defs (own + imports); only
+// own-module ones are registered into the overlay.
+void cbm_run_ts_lsp_cross_with_registry(CBMArena* arena,
+ const char* source, int source_len,
+ const char* module_qn,
+ bool js_mode, bool jsx_mode, bool dts_mode,
+ CBMTypeRegistry* reg,
+ CBMLSPDef* defs, int def_count,
+ const char** import_names, const char** import_qns,
+ int import_count,
+ TSTree* cached_tree,
+ CBMResolvedCallArray* out);
+
// Register the TypeScript / JavaScript stdlib subset (Promise, Array<T>, Map<K,V>, Set<T>,
// Object, Function, console, JSON) into a registry. v1 is hand-curated; a generator script
// will replace this in v1.3.
diff --git a/internal/cbm/lsp/type_registry.c b/internal/cbm/lsp/type_registry.c
index fbf3a3444..1fc9c011f 100644
--- a/internal/cbm/lsp/type_registry.c
+++ b/internal/cbm/lsp/type_registry.c
@@ -146,10 +146,8 @@ void cbm_registry_add_type(CBMTypeRegistry* reg, CBMRegisteredType type) {
reg->types[reg->type_count++] = type;
}
-const CBMRegisteredFunc* cbm_registry_lookup_method(const CBMTypeRegistry* reg,
+static const CBMRegisteredFunc* lookup_method_self(const CBMTypeRegistry* reg,
const char* receiver_qn, const char* method_name) {
- if (!reg || !receiver_qn || !method_name) return NULL;
-
// Hashed path when registry is finalized.
if (reg->method_buckets && reg->method_bucket_count > 0) {
uint64_t h = fnv1a_pair(receiver_qn, method_name);
@@ -178,10 +176,18 @@ const CBMRegisteredFunc* cbm_registry_lookup_method(const CBMTypeRegistry* reg,
return NULL;
}
-const CBMRegisteredType* cbm_registry_lookup_type(const CBMTypeRegistry* reg,
- const char* qualified_name) {
- if (!reg || !qualified_name) return NULL;
+const CBMRegisteredFunc* cbm_registry_lookup_method(const CBMTypeRegistry* reg,
+ const char* receiver_qn, const char* method_name) {
+ if (!reg || !receiver_qn || !method_name) return NULL;
+ const CBMRegisteredFunc* r = lookup_method_self(reg, receiver_qn, method_name);
+ if (!r && reg->fallback) {
+ return cbm_registry_lookup_method(reg->fallback, receiver_qn, method_name);
+ }
+ return r;
+}
+static const CBMRegisteredType* lookup_type_self(const CBMTypeRegistry* reg,
+ const char* qualified_name) {
if (reg->type_qn_buckets && reg->type_qn_bucket_count > 0) {
uint64_t h = fnv1a(qualified_name);
int slot = (int)(h & (uint64_t)(reg->type_qn_bucket_count - 1));
@@ -205,10 +211,18 @@ const CBMRegisteredType* cbm_registry_lookup_type(const CBMTypeRegistry* reg,
return NULL;
}
-const CBMRegisteredFunc* cbm_registry_lookup_func(const CBMTypeRegistry* reg,
+const CBMRegisteredType* cbm_registry_lookup_type(const CBMTypeRegistry* reg,
const char* qualified_name) {
if (!reg || !qualified_name) return NULL;
+ const CBMRegisteredType* r = lookup_type_self(reg, qualified_name);
+ if (!r && reg->fallback) {
+ return cbm_registry_lookup_type(reg->fallback, qualified_name);
+ }
+ return r;
+}
+static const CBMRegisteredFunc* lookup_func_self(const CBMTypeRegistry* reg,
+ const char* qualified_name) {
if (reg->func_qn_buckets && reg->func_qn_bucket_count > 0) {
uint64_t h = fnv1a(qualified_name);
int slot = (int)(h & (uint64_t)(reg->func_qn_bucket_count - 1));
@@ -232,6 +246,16 @@ const CBMRegisteredFunc* cbm_registry_lookup_func(const CBMTypeRegistry* reg,
return NULL;
}
+const CBMRegisteredFunc* cbm_registry_lookup_func(const CBMTypeRegistry* reg,
+ const char* qualified_name) {
+ if (!reg || !qualified_name) return NULL;
+ const CBMRegisteredFunc* r = lookup_func_self(reg, qualified_name);
+ if (!r && reg->fallback) {
+ return cbm_registry_lookup_func(reg->fallback, qualified_name);
+ }
+ return r;
+}
+
const CBMRegisteredType* cbm_registry_resolve_alias(const CBMTypeRegistry* reg, const char* type_qn) {
if (!reg || !type_qn) return NULL;
const CBMRegisteredType* rt = cbm_registry_lookup_type(reg, type_qn);
@@ -311,7 +335,11 @@ const CBMRegisteredFunc* cbm_registry_lookup_method_by_args(const CBMTypeRegistr
}
}
}
- return range_match ? range_match : first_match;
+ const CBMRegisteredFunc* res = range_match ? range_match : first_match;
+ if (!res && reg->fallback) {
+ return cbm_registry_lookup_method_by_args(reg->fallback, receiver_qn, method_name, arg_count);
+ }
+ return res;
}
// --- Overload scoring by parameter type ---
@@ -405,7 +433,12 @@ const CBMRegisteredFunc* cbm_registry_lookup_method_by_types(const CBMTypeRegist
if (s > best_score) { best_score = s; best = f; }
}
}
- return best ? best : first_match;
+ const CBMRegisteredFunc* res = best ? best : first_match;
+ if (!res && reg->fallback) {
+ return cbm_registry_lookup_method_by_types(reg->fallback, receiver_qn, method_name,
+ arg_types, arg_count);
+ }
+ return res;
}
const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_types(const CBMTypeRegistry* reg,
@@ -436,7 +469,12 @@ const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_types(const CBMTypeRegist
if (s > best_score) { best_score = s; best = f; }
}
}
- return best ? best : first_match;
+ const CBMRegisteredFunc* res = best ? best : first_match;
+ if (!res && reg->fallback) {
+ return cbm_registry_lookup_symbol_by_types(reg->fallback, package_qn, name,
+ arg_types, arg_count);
+ }
+ return res;
}
const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_args(const CBMTypeRegistry* reg,
@@ -467,7 +505,11 @@ const CBMRegisteredFunc* cbm_registry_lookup_symbol_by_args(const CBMTypeRegistr
}
}
}
- return range_match ? range_match : first_match;
+ const CBMRegisteredFunc* res = range_match ? range_match : first_match;
+ if (!res && reg->fallback) {
+ return cbm_registry_lookup_symbol_by_args(reg->fallback, package_qn, name, arg_count);
+ }
+ return res;
}
// --- TS-specific helpers ---
diff --git a/internal/cbm/lsp/type_registry.h b/internal/cbm/lsp/type_registry.h
index 31224edf7..e7b1f7cda 100644
--- a/internal/cbm/lsp/type_registry.h
+++ b/internal/cbm/lsp/type_registry.h
@@ -63,7 +63,7 @@ typedef struct {
} CBMRegistryHashEntry;
// Cross-file type/function registry.
-typedef struct {
+typedef struct CBMTypeRegistry {
CBMRegisteredFunc* funcs;
int func_count;
int func_cap;
@@ -74,6 +74,13 @@ typedef struct {
CBMArena* arena; // owns all string data
+ /* Optional fallback registry (Tier 2 two-level lookup). When a
+ * lookup misses in this registry, it chains to `fallback`. Used by
+ * TS/PHP cross-LSP: a small per-file registry (the file's own
+ * AST-refined types) chains to a shared, immutable base registry
+ * (stdlib + all project defs) built once. NULL = no chaining. */
+ const struct CBMTypeRegistry* fallback;
+
// Hash indexes (built lazily by cbm_registry_finalize, NULL until then).
// Lookups fall back to linear scan when these are NULL.
int* func_qn_buckets; // bucket → first entry index in func_qn_entries; -1 = empty
diff --git a/src/pipeline/pass_lsp_cross.h b/src/pipeline/pass_lsp_cross.h
index 51f9f3bf2..f3ba6e17f 100644
--- a/src/pipeline/pass_lsp_cross.h
+++ b/src/pipeline/pass_lsp_cross.h
@@ -33,6 +33,7 @@
#include "lsp/py_lsp.h" /* cbm_py_build_cross_registry / cbm_run_py_lsp_cross_with_registry */
#include "lsp/c_lsp.h" /* cbm_c_build_cross_registry / cbm_run_c_lsp_cross_with_registry */
#include "lsp/cs_lsp.h" /* cbm_cs_build_cross_registry / cbm_run_cs_lsp_cross_with_registry */
+#include "lsp/ts_lsp.h" /* cbm_ts_build_cross_registry / cbm_run_ts_lsp_cross_with_registry */
#include "pipeline/pipeline_internal.h"
#include <stdbool.h>
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index bb7ea6d96..2d8d6edcd 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -2070,8 +2070,39 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
result->cached_tree, &result->resolved_calls);
used_prebuilt = true;
break;
- /* TS/JS/TSX, PHP fall through to the per-file build
- * path below until their _with_registry variants land. */
+ case CBM_LANG_JAVASCRIPT:
+ case CBM_LANG_TYPESCRIPT:
+ case CBM_LANG_TSX: {
+ /* TS uses a per-file OVERLAY chained to the shared
+ * base (prebuilt): the file's own-module defs are
+ * registered into the overlay so the AST refinement
+ * passes can mutate them; imports/stdlib resolve via
+ * the shared base. Filter to own+imports so the
+ * overlay builder can pick out own-module defs. */
+ bool js, jsx, dts;
+ cbm_pxc_ts_modes(lang, rel, &js, &jsx, &dts);
+ CBMLSPDef *ts_defs = rc->all_defs;
+ int ts_def_count = rc->def_count;
+ CBMLSPDef *ts_filtered = NULL;
+ if (rc->module_def_index) {
+ int fc = 0;
+ ts_filtered = cbm_pxc_filter_defs_for_file(
+ rc->module_def_index, rc->all_defs,
+ def_module, imp_vals, imp_count, &fc);
+ if (ts_filtered) { ts_defs = ts_filtered; ts_def_count = fc; }
+ }
+ cbm_run_ts_lsp_cross_with_registry(
+ &result->arena, result->source, result->source_len,
+ def_module, js, jsx, dts, prebuilt,
+ ts_defs, ts_def_count,
+ imp_keys, imp_vals, imp_count,
+ result->cached_tree, &result->resolved_calls);
+ free(ts_filtered);
+ used_prebuilt = true;
+ break;
+ }
+ /* PHP falls through to the per-file build path below
+ * until its overlay variant lands. */
default:
break;
}
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index a0d5e18d0..aa0c60559 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -633,6 +633,8 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
cbm_c_build_cross_registry(&cross_lsp_arena, all_defs, def_count);
cross_registries.cs =
cbm_cs_build_cross_registry(&cross_lsp_arena, all_defs, def_count);
+ cross_registries.ts =
+ cbm_ts_build_cross_registry(&cross_lsp_arena, all_defs, def_count);
}
cbm_log_info("pass.timing", "pass", "lsp_cross_prepare", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));