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.

Bound LSP resolve recursion depth (stack-overflow crashes indexing real repos)

Martin Vogel9f981a161269
diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.c
index 121afc41a..fda90c585 100644
--- a/internal/cbm/lsp/c_lsp.c
+++ b/internal/cbm/lsp/c_lsp.c
@@ -8,39 +8,40 @@
/* Safe kind accessor — returns CBM_TYPE_UNKNOWN for NULL types.
* Prevents SEGV in c_eval_expr_type_inner on unusual C++ AST shapes. */
-static inline CBMTypeKind safe_kind(const CBMType* t) {
+static inline CBMTypeKind safe_kind(const CBMType *t) {
return t ? t->kind : CBM_TYPE_UNKNOWN;
}
// Forward declarations
-static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node);
-static void c_emit_resolved_call(CLSPContext* ctx, const char* callee_qn, const char* strategy, float confidence);
-static void c_emit_unresolved_call(CLSPContext* ctx, const char* expr_text, const char* reason);
-static const CBMType* c_lookup_field_type(CLSPContext* ctx, const char* type_qn, const char* field_name, int depth);
-static void c_process_function(CLSPContext* ctx, TSNode func_node);
-static void c_process_namespace(CLSPContext* ctx, TSNode ns_node);
-static void c_process_class(CLSPContext* ctx, TSNode class_node);
-static void c_process_body_child(CLSPContext* ctx, TSNode child);
-static const char* type_to_qn(const CBMType* t);
-const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_pointer);
-const CBMType* c_eval_expr_type(CLSPContext* ctx, TSNode node);
+static void c_resolve_calls_in_node(CLSPContext *ctx, TSNode node);
+static void c_emit_resolved_call(CLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence);
+static void c_emit_unresolved_call(CLSPContext *ctx, const char *expr_text, const char *reason);
+static const CBMType *c_lookup_field_type(CLSPContext *ctx, const char *type_qn,
+ const char *field_name, int depth);
+static void c_process_function(CLSPContext *ctx, TSNode func_node);
+static void c_process_namespace(CLSPContext *ctx, TSNode ns_node);
+static void c_process_class(CLSPContext *ctx, TSNode class_node);
+static void c_process_body_child(CLSPContext *ctx, TSNode child);
+static const char *type_to_qn(const CBMType *t);
+const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_pointer);
+const CBMType *c_eval_expr_type(CLSPContext *ctx, TSNode node);
// External tree-sitter language functions (defined in grammar_*.c)
-extern const TSLanguage* tree_sitter_c(void);
-extern const TSLanguage* tree_sitter_cpp(void);
+extern const TSLanguage *tree_sitter_c(void);
+extern const TSLanguage *tree_sitter_cpp(void);
// --- Smart pointer names for deref ---
// Checks suffix: "std.shared_ptr", "test.main.std.shared_ptr" both match
-static bool is_smart_ptr(const char* name) {
- if (!name) return false;
+static bool is_smart_ptr(const char *name) {
+ if (!name)
+ return false;
// Extract short name after last dot (or use full name)
- const char* short_name = strrchr(name, '.');
+ const char *short_name = strrchr(name, '.');
short_name = short_name ? short_name + 1 : name;
// Check if the short name is a smart pointer type AND the QN contains "std"
- if (strcmp(short_name, "unique_ptr") == 0 ||
- strcmp(short_name, "shared_ptr") == 0 ||
- strcmp(short_name, "weak_ptr") == 0 ||
- strcmp(short_name, "auto_ptr") == 0 ||
+ if (strcmp(short_name, "unique_ptr") == 0 || strcmp(short_name, "shared_ptr") == 0 ||
+ strcmp(short_name, "weak_ptr") == 0 || strcmp(short_name, "auto_ptr") == 0 ||
strcmp(short_name, "scoped_ptr") == 0) {
return strstr(name, "std") != NULL || strstr(name, "boost") != NULL;
}
@@ -48,15 +49,15 @@ static bool is_smart_ptr(const char* name) {
}
// --- Helper: get node text ---
-static char* c_node_text(CLSPContext* ctx, TSNode node) {
+static char *c_node_text(CLSPContext *ctx, TSNode node) {
return cbm_node_text(ctx->arena, node, ctx->source);
}
// --- Initialization ---
-void c_lsp_init(CLSPContext* ctx, CBMArena* arena, const char* source, int source_len,
- const CBMTypeRegistry* registry, const char* module_qn, bool cpp_mode,
- CBMResolvedCallArray* out) {
+void c_lsp_init(CLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn, bool cpp_mode,
+ CBMResolvedCallArray *out) {
memset(ctx, 0, sizeof(CLSPContext));
ctx->arena = arena;
ctx->source = source;
@@ -67,19 +68,22 @@ void c_lsp_init(CLSPContext* ctx, CBMArena* arena, const char* source, int sourc
ctx->resolved_calls = out;
ctx->current_scope = cbm_scope_push(arena, NULL);
- const char* debug_env = getenv("CBM_LSP_DEBUG");
+ const char *debug_env = getenv("CBM_LSP_DEBUG");
ctx->debug = (debug_env && debug_env[0]);
}
-void c_lsp_add_include(CLSPContext* ctx, const char* header_path, const char* ns_qn) {
+void c_lsp_add_include(CLSPContext *ctx, const char *header_path, const char *ns_qn) {
if (ctx->include_count % 32 == 0) {
int new_cap = ctx->include_count + 32;
- const char** new_paths = (const char**)cbm_arena_alloc(ctx->arena, (new_cap + 1) * sizeof(const char*));
- const char** new_qns = (const char**)cbm_arena_alloc(ctx->arena, (new_cap + 1) * sizeof(const char*));
- if (!new_paths || !new_qns) return;
+ const char **new_paths =
+ (const char **)cbm_arena_alloc(ctx->arena, (new_cap + 1) * sizeof(const char *));
+ const char **new_qns =
+ (const char **)cbm_arena_alloc(ctx->arena, (new_cap + 1) * sizeof(const char *));
+ if (!new_paths || !new_qns)
+ return;
if (ctx->include_paths && ctx->include_count > 0) {
- memcpy(new_paths, ctx->include_paths, ctx->include_count * sizeof(const char*));
- memcpy(new_qns, ctx->include_ns_qns, ctx->include_count * sizeof(const char*));
+ memcpy(new_paths, ctx->include_paths, ctx->include_count * sizeof(const char *));
+ memcpy(new_qns, ctx->include_ns_qns, ctx->include_count * sizeof(const char *));
}
ctx->include_paths = new_paths;
ctx->include_ns_qns = new_qns;
@@ -90,13 +94,15 @@ void c_lsp_add_include(CLSPContext* ctx, const char* header_path, const char* ns
}
// --- Helper: add using namespace ---
-static void c_add_using_namespace(CLSPContext* ctx, const char* ns_qn) {
+static void c_add_using_namespace(CLSPContext *ctx, const char *ns_qn) {
if (ctx->using_ns_count >= ctx->using_ns_cap) {
int new_cap = ctx->using_ns_cap == 0 ? 16 : ctx->using_ns_cap * 2;
- const char** new_arr = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- if (!new_arr) return;
+ const char **new_arr =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ if (!new_arr)
+ return;
if (ctx->using_namespaces && ctx->using_ns_count > 0)
- memcpy(new_arr, ctx->using_namespaces, ctx->using_ns_count * sizeof(const char*));
+ memcpy(new_arr, ctx->using_namespaces, ctx->using_ns_count * sizeof(const char *));
ctx->using_namespaces = new_arr;
ctx->using_ns_cap = new_cap;
}
@@ -104,15 +110,18 @@ static void c_add_using_namespace(CLSPContext* ctx, const char* ns_qn) {
}
// --- Helper: add using declaration ---
-static void c_add_using_decl(CLSPContext* ctx, const char* short_name, const char* full_qn) {
+static void c_add_using_decl(CLSPContext *ctx, const char *short_name, const char *full_qn) {
if (ctx->using_decl_count >= ctx->using_decl_cap) {
int new_cap = ctx->using_decl_cap == 0 ? 16 : ctx->using_decl_cap * 2;
- const char** new_names = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- const char** new_qns = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- if (!new_names || !new_qns) return;
+ const char **new_names =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ const char **new_qns =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ if (!new_names || !new_qns)
+ return;
if (ctx->using_decl_names && ctx->using_decl_count > 0) {
- memcpy(new_names, ctx->using_decl_names, ctx->using_decl_count * sizeof(const char*));
- memcpy(new_qns, ctx->using_decl_qns, ctx->using_decl_count * sizeof(const char*));
+ memcpy(new_names, ctx->using_decl_names, ctx->using_decl_count * sizeof(const char *));
+ memcpy(new_qns, ctx->using_decl_qns, ctx->using_decl_count * sizeof(const char *));
}
ctx->using_decl_names = new_names;
ctx->using_decl_qns = new_qns;
@@ -124,15 +133,18 @@ static void c_add_using_decl(CLSPContext* ctx, const char* short_name, const cha
}
// --- Helper: add namespace alias ---
-static void c_add_ns_alias(CLSPContext* ctx, const char* alias, const char* full_qn) {
+static void c_add_ns_alias(CLSPContext *ctx, const char *alias, const char *full_qn) {
if (ctx->ns_alias_count >= ctx->ns_alias_cap) {
int new_cap = ctx->ns_alias_cap == 0 ? 8 : ctx->ns_alias_cap * 2;
- const char** new_names = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- const char** new_qns = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- if (!new_names || !new_qns) return;
+ const char **new_names =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ const char **new_qns =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ if (!new_names || !new_qns)
+ return;
if (ctx->ns_alias_names && ctx->ns_alias_count > 0) {
- memcpy(new_names, ctx->ns_alias_names, ctx->ns_alias_count * sizeof(const char*));
- memcpy(new_qns, ctx->ns_alias_qns, ctx->ns_alias_count * sizeof(const char*));
+ memcpy(new_names, ctx->ns_alias_names, ctx->ns_alias_count * sizeof(const char *));
+ memcpy(new_qns, ctx->ns_alias_qns, ctx->ns_alias_count * sizeof(const char *));
}
ctx->ns_alias_names = new_names;
ctx->ns_alias_qns = new_qns;
@@ -144,15 +156,18 @@ static void c_add_ns_alias(CLSPContext* ctx, const char* alias, const char* full
}
// --- Helper: track function pointer target ---
-static void c_add_fp_target(CLSPContext* ctx, const char* var_name, const char* target_qn) {
+static void c_add_fp_target(CLSPContext *ctx, const char *var_name, const char *target_qn) {
if (ctx->fp_count >= ctx->fp_cap) {
int new_cap = ctx->fp_cap == 0 ? 16 : ctx->fp_cap * 2;
- const char** new_names = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- const char** new_qns = (const char**)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char*));
- if (!new_names || !new_qns) return;
+ const char **new_names =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ const char **new_qns =
+ (const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
+ if (!new_names || !new_qns)
+ return;
if (ctx->fp_var_names && ctx->fp_count > 0) {
- memcpy(new_names, ctx->fp_var_names, ctx->fp_count * sizeof(const char*));
- memcpy(new_qns, ctx->fp_target_qns, ctx->fp_count * sizeof(const char*));
+ memcpy(new_names, ctx->fp_var_names, ctx->fp_count * sizeof(const char *));
+ memcpy(new_qns, ctx->fp_target_qns, ctx->fp_count * sizeof(const char *));
}
ctx->fp_var_names = new_names;
ctx->fp_target_qns = new_qns;
@@ -164,7 +179,7 @@ static void c_add_fp_target(CLSPContext* ctx, const char* var_name, const char*
}
// Look up function pointer target
-static const char* c_lookup_fp_target(CLSPContext* ctx, const char* var_name) {
+static const char *c_lookup_fp_target(CLSPContext *ctx, const char *var_name) {
for (int i = ctx->fp_count - 1; i >= 0; i--) {
if (strcmp(ctx->fp_var_names[i], var_name) == 0)
return ctx->fp_target_qns[i];
@@ -178,25 +193,27 @@ static const char* c_lookup_fp_target(CLSPContext* ctx, const char* var_name) {
// dynamically (GetProcAddress, dlsym, or custom resolver).
// Returns the function name string (without quotes), or NULL.
// Sets *out_has_cast to true if the expression was wrapped in a cast.
-static const char* c_extract_dll_resolve_name(CLSPContext* ctx, TSNode expr, bool* out_has_cast) {
- if (ts_node_is_null(expr)) return NULL;
+static const char *c_extract_dll_resolve_name(CLSPContext *ctx, TSNode expr, bool *out_has_cast) {
+ if (ts_node_is_null(expr))
+ return NULL;
*out_has_cast = false;
// Unwrap cast expressions to find inner call
TSNode inner = expr;
- const char* ik = ts_node_type(inner);
+ const char *ik = ts_node_type(inner);
for (int unwrap_depth = 0; unwrap_depth < 8; unwrap_depth++) {
// Standard cast nodes: (Type)expr, static_cast<T>(expr) etc.
- if (strcmp(ik, "cast_expression") == 0 ||
- strcmp(ik, "static_cast_expression") == 0 ||
+ if (strcmp(ik, "cast_expression") == 0 || strcmp(ik, "static_cast_expression") == 0 ||
strcmp(ik, "reinterpret_cast_expression") == 0 ||
strcmp(ik, "dynamic_cast_expression") == 0 ||
strcmp(ik, "const_cast_expression") == 0) {
*out_has_cast = true;
uint32_t nc = ts_node_named_child_count(inner);
- if (nc == 0) return NULL;
+ if (nc == 0)
+ return NULL;
inner = ts_node_named_child(inner, nc - 1);
- if (ts_node_is_null(inner)) return NULL;
+ if (ts_node_is_null(inner))
+ return NULL;
ik = ts_node_type(inner);
continue;
}
@@ -205,23 +222,24 @@ static const char* c_extract_dll_resolve_name(CLSPContext* ctx, TSNode expr, boo
if (strcmp(ik, "call_expression") == 0) {
TSNode fn = ts_node_child_by_field_name(inner, "function", 8);
if (!ts_node_is_null(fn)) {
- char* fname = NULL;
- const char* fk = ts_node_type(fn);
+ char *fname = NULL;
+ const char *fk = ts_node_type(fn);
if (strcmp(fk, "template_function") == 0) {
TSNode nn = ts_node_child_by_field_name(fn, "name", 4);
- if (!ts_node_is_null(nn)) fname = c_node_text(ctx, nn);
+ if (!ts_node_is_null(nn))
+ fname = c_node_text(ctx, nn);
} else if (strcmp(fk, "identifier") == 0) {
fname = c_node_text(ctx, fn);
}
- if (fname && (strcmp(fname, "static_cast") == 0 ||
- strcmp(fname, "reinterpret_cast") == 0 ||
- strcmp(fname, "dynamic_cast") == 0 ||
- strcmp(fname, "const_cast") == 0)) {
+ if (fname &&
+ (strcmp(fname, "static_cast") == 0 || strcmp(fname, "reinterpret_cast") == 0 ||
+ strcmp(fname, "dynamic_cast") == 0 || strcmp(fname, "const_cast") == 0)) {
*out_has_cast = true;
TSNode cargs = ts_node_child_by_field_name(inner, "arguments", 9);
if (!ts_node_is_null(cargs) && ts_node_named_child_count(cargs) > 0) {
inner = ts_node_named_child(cargs, 0);
- if (ts_node_is_null(inner)) return NULL;
+ if (ts_node_is_null(inner))
+ return NULL;
ik = ts_node_type(inner);
continue;
}
@@ -233,57 +251,68 @@ static const char* c_extract_dll_resolve_name(CLSPContext* ctx, TSNode expr, boo
}
// Must be a call_expression
- if (strcmp(ik, "call_expression") != 0) return NULL;
+ if (strcmp(ik, "call_expression") != 0)
+ return NULL;
// Scan call arguments for a string literal
TSNode args = ts_node_child_by_field_name(inner, "arguments", 9);
- if (ts_node_is_null(args)) return NULL;
+ if (ts_node_is_null(args))
+ return NULL;
uint32_t anc = ts_node_named_child_count(args);
for (uint32_t i = 0; i < anc; i++) {
TSNode arg = ts_node_named_child(args, i);
- if (ts_node_is_null(arg)) continue;
- const char* ak = ts_node_type(arg);
+ if (ts_node_is_null(arg))
+ continue;
+ const char *ak = ts_node_type(arg);
if (strcmp(ak, "string_literal") != 0 && strcmp(ak, "raw_string_literal") != 0)
continue;
- char* text = c_node_text(ctx, arg);
- if (!text) continue;
+ char *text = c_node_text(ctx, arg);
+ if (!text)
+ continue;
size_t len = strlen(text);
- if (len < 2 || text[0] != '"' || text[len - 1] != '"') continue;
- char* name = cbm_arena_strndup(ctx->arena, text + 1, len - 2);
- if (!name || !name[0]) continue;
+ if (len < 2 || text[0] != '"' || text[len - 1] != '"')
+ continue;
+ char *name = cbm_arena_strndup(ctx->arena, text + 1, len - 2);
+ if (!name || !name[0])
+ continue;
// Validate: function names are identifiers (no spaces, path separators, dots)
bool valid = true;
- for (const char* p = name; *p; p++) {
+ for (const char *p = name; *p; p++) {
if (*p == ' ' || *p == '/' || *p == '\\' || *p == '.') {
valid = false;
break;
}
}
- if (valid) return name;
+ if (valid)
+ return name;
}
return NULL;
}
// --- Helper: pending template calls (member calls on TYPE_PARAM inside templates) ---
-static void c_add_pending_template_call(CLSPContext* ctx, const char* func_qn,
- const char* type_param, const char* method_name, int arg_count) {
- if (!func_qn || !type_param || !method_name) return;
+static void c_add_pending_template_call(CLSPContext *ctx, const char *func_qn,
+ const char *type_param, const char *method_name,
+ int arg_count) {
+ if (!func_qn || !type_param || !method_name)
+ return;
if (ctx->pending_tc_count >= ctx->pending_tc_cap) {
int new_cap = ctx->pending_tc_cap == 0 ? 16 : ctx->pending_tc_cap * 2;
size_t sz = new_cap * sizeof(ctx->pending_template_calls[0]);
- void* new_arr = cbm_arena_alloc(ctx->arena, sz);
- if (!new_arr) return;
+ void *new_arr = cbm_arena_alloc(ctx->arena, sz);
+ if (!new_arr)
+ return;
if (ctx->pending_template_calls && ctx->pending_tc_count > 0)
memcpy(new_arr, ctx->pending_template_calls,
- ctx->pending_tc_count * sizeof(ctx->pending_template_calls[0]));
+ ctx->pending_tc_count * sizeof(ctx->pending_template_calls[0]));
ctx->pending_template_calls = new_arr;
ctx->pending_tc_cap = new_cap;
}
- const char* func_qn_copy = cbm_arena_strdup(ctx->arena, func_qn);
- const char* type_param_copy = cbm_arena_strdup(ctx->arena, type_param);
- const char* method_name_copy = cbm_arena_strdup(ctx->arena, method_name);
- if (!func_qn_copy || !type_param_copy || !method_name_copy) return;
+ const char *func_qn_copy = cbm_arena_strdup(ctx->arena, func_qn);
+ const char *type_param_copy = cbm_arena_strdup(ctx->arena, type_param);
+ const char *method_name_copy = cbm_arena_strdup(ctx->arena, method_name);
+ if (!func_qn_copy || !type_param_copy || !method_name_copy)
+ return;
int i = ctx->pending_tc_count++;
ctx->pending_template_calls[i].func_qn = func_qn_copy;
@@ -294,15 +323,17 @@ static void c_add_pending_template_call(CLSPContext* ctx, const char* func_qn,
// Resolve pending template calls for a function being called with known arg types.
// Deduces type params from call-site args and resolves stored method calls.
-static void c_resolve_pending_template_calls(CLSPContext* ctx,
- const CBMRegisteredFunc* callee, const CBMType** call_arg_types, int call_arg_count) {
- if (!callee || !callee->type_param_names || !call_arg_types) return;
+static void c_resolve_pending_template_calls(CLSPContext *ctx, const CBMRegisteredFunc *callee,
+ const CBMType **call_arg_types, int call_arg_count) {
+ if (!callee || !callee->type_param_names || !call_arg_types)
+ return;
// Build type param → concrete type mapping from call-site arguments
- const char** tpn = callee->type_param_names;
- const CBMType* param_map[8] = {0};
+ const char **tpn = callee->type_param_names;
+ const CBMType *param_map[8] = {0};
int tpn_count = 0;
- while (tpn[tpn_count] && tpn_count < 8) tpn_count++;
+ while (tpn[tpn_count] && tpn_count < 8)
+ tpn_count++;
// Match call arg types against function param types to deduce type params.
// The call site may contain more arguments than the parsed function signature
@@ -311,22 +342,24 @@ static void c_resolve_pending_template_calls(CLSPContext* ctx,
if (callee->signature && callee->signature->kind == CBM_TYPE_FUNC &&
callee->signature->data.func.param_types) {
int formal_count = 0;
- while (callee->signature->data.func.param_types[formal_count]) formal_count++;
+ while (callee->signature->data.func.param_types[formal_count])
+ formal_count++;
int limit = call_arg_count < formal_count ? call_arg_count : formal_count;
for (int i = 0; i < limit; i++) {
- const CBMType* formal = callee->signature->data.func.param_types[i];
- if (!formal || !call_arg_types[i]) continue;
+ const CBMType *formal = callee->signature->data.func.param_types[i];
+ if (!formal || !call_arg_types[i])
+ continue;
// Unwrap references/pointers
- while (formal && (formal->kind == CBM_TYPE_REFERENCE ||
- formal->kind == CBM_TYPE_RVALUE_REF ||
- formal->kind == CBM_TYPE_POINTER)) {
- formal = (formal->kind == CBM_TYPE_POINTER) ?
- formal->data.pointer.elem : formal->data.reference.elem;
+ while (formal &&
+ (formal->kind == CBM_TYPE_REFERENCE || formal->kind == CBM_TYPE_RVALUE_REF ||
+ formal->kind == CBM_TYPE_POINTER)) {
+ formal = (formal->kind == CBM_TYPE_POINTER) ? formal->data.pointer.elem
+ : formal->data.reference.elem;
}
if (formal && formal->kind == CBM_TYPE_TYPE_PARAM) {
for (int j = 0; j < tpn_count; j++) {
if (strcmp(tpn[j], formal->data.type_param.name) == 0) {
- const CBMType* arg = call_arg_types[i];
+ const CBMType *arg = call_arg_types[i];
arg = c_simplify_type(ctx, arg, false);
param_map[j] = arg;
}
@@ -336,25 +369,26 @@ static void c_resolve_pending_template_calls(CLSPContext* ctx,
}
// Resolve pending calls for this function — emit with template func as caller
- const char* saved_func_qn = ctx->enclosing_func_qn;
+ const char *saved_func_qn = ctx->enclosing_func_qn;
ctx->enclosing_func_qn = callee->qualified_name;
for (int i = 0; i < ctx->pending_tc_count; i++) {
- if (!ctx->pending_template_calls[i].func_qn ||
- !ctx->pending_template_calls[i].type_param ||
+ if (!ctx->pending_template_calls[i].func_qn || !ctx->pending_template_calls[i].type_param ||
!ctx->pending_template_calls[i].method_name)
continue;
if (strcmp(ctx->pending_template_calls[i].func_qn, callee->qualified_name) != 0)
continue;
- const char* tp = ctx->pending_template_calls[i].type_param;
- const char* method = ctx->pending_template_calls[i].method_name;
+ const char *tp = ctx->pending_template_calls[i].type_param;
+ const char *method = ctx->pending_template_calls[i].method_name;
// Find which type param this is
for (int j = 0; j < tpn_count; j++) {
- if (strcmp(tpn[j], tp) != 0 || !param_map[j]) continue;
- const char* concrete_qn = type_to_qn(param_map[j]);
- if (!concrete_qn) continue;
+ if (strcmp(tpn[j], tp) != 0 || !param_map[j])
+ continue;
+ const char *concrete_qn = type_to_qn(param_map[j]);
+ if (!concrete_qn)
+ continue;
// Look up the method on the concrete type
- const CBMRegisteredFunc* m = c_lookup_member(ctx, concrete_qn, method);
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, concrete_qn, method);
if (m) {
c_emit_resolved_call(ctx, m->qualified_name, "lsp_template_instantiation", 0.90f);
}
@@ -365,13 +399,24 @@ static void c_resolve_pending_template_calls(CLSPContext* ctx,
}
// --- Helper: extract call argument types for overload scoring ---
-static const CBMType** c_extract_call_arg_types(CLSPContext* ctx, TSNode call_node, int* out_count) {
+static const CBMType **c_extract_call_arg_types(CLSPContext *ctx, TSNode call_node,
+ int *out_count) {
TSNode args = ts_node_child_by_field_name(call_node, "arguments", 9);
- if (ts_node_is_null(args)) { *out_count = 0; return NULL; }
+ if (ts_node_is_null(args)) {
+ *out_count = 0;
+ return NULL;
+ }
uint32_t nc = ts_node_named_child_count(args);
- if (nc == 0) { *out_count = 0; return NULL; }
- const CBMType** types = (const CBMType**)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const CBMType*));
- if (!types) { *out_count = 0; return NULL; }
+ if (nc == 0) {
+ *out_count = 0;
+ return NULL;
+ }
+ const CBMType **types =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const CBMType *));
+ if (!types) {
+ *out_count = 0;
+ return NULL;
+ }
int count = 0;
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(args, i);
@@ -385,23 +430,29 @@ static const CBMType** c_extract_call_arg_types(CLSPContext* ctx, TSNode call_no
}
// --- Helper: parse template parameter defaults ---
-static void c_parse_template_params(CLSPContext* ctx, TSNode template_decl) {
+static void c_parse_template_params(CLSPContext *ctx, TSNode template_decl) {
TSNode params = ts_node_child_by_field_name(template_decl, "parameters", 10);
- if (ts_node_is_null(params)) return;
+ if (ts_node_is_null(params))
+ return;
ctx->template_param_count = 0;
uint32_t nc = ts_node_named_child_count(params);
- if (nc == 0) return;
+ if (nc == 0)
+ return;
- const char** names = (const char**)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const char*));
- const CBMType** defaults = (const CBMType**)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const CBMType*));
- if (!names || !defaults) return;
+ const char **names =
+ (const char **)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const char *));
+ const CBMType **defaults =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, (nc + 1) * sizeof(const CBMType *));
+ if (!names || !defaults)
+ return;
int idx = 0;
for (uint32_t i = 0; i < nc && idx < 16; i++) {
TSNode param = ts_node_named_child(params, i);
- if (ts_node_is_null(param)) continue;
- const char* pk = ts_node_type(param);
+ if (ts_node_is_null(param))
+ continue;
+ const char *pk = ts_node_type(param);
// type_parameter_declaration: template<class T = int>
// optional_type_parameter_declaration: template<class T = Default>
@@ -421,9 +472,11 @@ static void c_parse_template_params(CLSPContext* ctx, TSNode template_decl) {
}
}
- char* pname = NULL;
- if (!ts_node_is_null(name_node)) pname = c_node_text(ctx, name_node);
- if (!pname) pname = cbm_arena_sprintf(ctx->arena, "T%d", idx);
+ char *pname = NULL;
+ if (!ts_node_is_null(name_node))
+ pname = c_node_text(ctx, name_node);
+ if (!pname)
+ pname = cbm_arena_sprintf(ctx->arena, "T%d", idx);
names[idx] = pname;
@@ -450,19 +503,19 @@ static void c_parse_template_params(CLSPContext* ctx, TSNode template_decl) {
}
// Resolve a template type parameter using defaults from current template scope
-static const CBMType* c_resolve_template_param(CLSPContext* ctx, const char* param_name) {
- if (!param_name || !ctx->template_param_names) return NULL;
+static const CBMType *c_resolve_template_param(CLSPContext *ctx, const char *param_name) {
+ if (!param_name || !ctx->template_param_names)
+ return NULL;
for (int i = 0; i < ctx->template_param_count; i++) {
- if (ctx->template_param_names[i] &&
- strcmp(ctx->template_param_names[i], param_name) == 0) {
- return ctx->template_param_defaults[i]; // may be NULL if no default
+ if (ctx->template_param_names[i] && strcmp(ctx->template_param_names[i], param_name) == 0) {
+ return ctx->template_param_defaults[i]; // may be NULL if no default
}
}
return NULL;
}
// --- Helper: resolve namespace alias ---
-static const char* c_resolve_ns_alias(CLSPContext* ctx, const char* name) {
+static const char *c_resolve_ns_alias(CLSPContext *ctx, const char *name) {
for (int i = 0; i < ctx->ns_alias_count; i++) {
if (strcmp(ctx->ns_alias_names[i], name) == 0)
return ctx->ns_alias_qns[i];
@@ -471,34 +524,39 @@ static const char* c_resolve_ns_alias(CLSPContext* ctx, const char* name) {
}
// --- C/C++ builtin check ---
-static bool is_c_builtin_type(const char* name) {
- static const char* builtins[] = {
- "int", "char", "short", "long", "float", "double", "void",
- "bool", "size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t",
- "int8_t", "int16_t", "int32_t", "int64_t",
- "uint8_t", "uint16_t", "uint32_t", "uint64_t",
- "wchar_t", "char16_t", "char32_t", "char8_t",
- "unsigned", "signed",
- NULL
- };
- for (const char** b = builtins; *b; b++) {
- if (strcmp(name, *b) == 0) return true;
+static bool is_c_builtin_type(const char *name) {
+ static const char *builtins[] = {
+ "int", "char", "short", "long", "float", "double", "void",
+ "bool", "size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t", "int8_t",
+ "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t",
+ "wchar_t", "char16_t", "char32_t", "char8_t", "unsigned", "signed", NULL};
+ for (const char **b = builtins; *b; b++) {
+ if (strcmp(name, *b) == 0)
+ return true;
}
return false;
}
-static bool is_c_builtin_func(const char* name) {
+static bool is_c_builtin_func(const char *name) {
// C stdlib functions are registered in the registry, not hardcoded here.
// But we skip certain compiler builtins that should not generate CALLS edges.
- static const char* skip[] = {
- "__builtin_expect", "__builtin_unreachable", "__builtin_offsetof",
- "__builtin_va_start", "__builtin_va_end", "__builtin_va_arg",
- "sizeof", "alignof", "_Alignof", "typeof", "decltype",
- "static_assert", "_Static_assert",
- NULL
- };
- for (const char** b = skip; *b; b++) {
- if (strcmp(name, *b) == 0) return true;
+ static const char *skip[] = {"__builtin_expect",
+ "__builtin_unreachable",
+ "__builtin_offsetof",
+ "__builtin_va_start",
+ "__builtin_va_end",
+ "__builtin_va_arg",
+ "sizeof",
+ "alignof",
+ "_Alignof",
+ "typeof",
+ "decltype",
+ "static_assert",
+ "_Static_assert",
+ NULL};
+ for (const char **b = skip; *b; b++) {
+ if (strcmp(name, *b) == 0)
+ return true;
}
return false;
}
@@ -509,28 +567,31 @@ static bool is_c_builtin_func(const char* name) {
// Converts "::" to "." for our QN format.
// Inline ABI namespaces to strip during QN construction.
// Only ABI-internal segments, NOT __detail (contains internal types).
-static bool is_inline_abi_ns(const char* seg, size_t seg_len) {
+static bool is_inline_abi_ns(const char *seg, size_t seg_len) {
return (seg_len == 3 && memcmp(seg, "__1", 3) == 0) ||
(seg_len == 7 && memcmp(seg, "__cxx11", 7) == 0) ||
(seg_len == 9 && memcmp(seg, "__gnu_cxx", 9) == 0);
}
-static const char* c_build_qn(CLSPContext* ctx, const char* text) {
- if (!text) return NULL;
+static const char *c_build_qn(CLSPContext *ctx, const char *text) {
+ if (!text)
+ return NULL;
// Replace :: with . and strip inline ABI namespaces
size_t len = strlen(text);
- char* buf = (char*)cbm_arena_alloc(ctx->arena, len + 1);
- if (!buf) return text;
+ char *buf = (char *)cbm_arena_alloc(ctx->arena, len + 1);
+ if (!buf)
+ return text;
size_t j = 0;
for (size_t i = 0; i < len; i++) {
if (text[i] == ':' && i + 1 < len && text[i + 1] == ':') {
// Peek at next segment to check for inline ABI namespace
size_t seg_start = i + 2;
size_t seg_end = seg_start;
- while (seg_end < len && text[seg_end] != ':') seg_end++;
+ while (seg_end < len && text[seg_end] != ':')
+ seg_end++;
size_t seg_len = seg_end - seg_start;
- if (seg_len > 0 && is_inline_abi_ns(text + seg_start, seg_len) &&
- seg_end + 1 < len && text[seg_end] == ':' && text[seg_end + 1] == ':') {
+ if (seg_len > 0 && is_inline_abi_ns(text + seg_start, seg_len) && seg_end + 1 < len &&
+ text[seg_end] == ':' && text[seg_end + 1] == ':') {
// Skip ABI ns + its trailing ::
i = seg_end + 1; // loop increments to seg_end+2 = after "::"
// Don't emit a dot — we're removing this segment
@@ -555,12 +616,14 @@ static const char* c_build_qn(CLSPContext* ctx, const char* text) {
// 4. Using namespaces
// 5. Current namespace
// 6. Module scope
-static const char* c_resolve_name(CLSPContext* ctx, const char* name) {
- if (!name) return NULL;
+static const char *c_resolve_name(CLSPContext *ctx, const char *name) {
+ if (!name)
+ return NULL;
// 1. Scope lookup
- const CBMType* t = cbm_scope_lookup(ctx->current_scope, name);
- if (!cbm_type_is_unknown(t)) return NULL; // found in scope, not a function
+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
+ if (!cbm_type_is_unknown(t))
+ return NULL; // found in scope, not a function
// 2. Using declarations
for (int i = 0; i < ctx->using_decl_count; i++) {
@@ -570,29 +633,34 @@ static const char* c_resolve_name(CLSPContext* ctx, const char* name) {
// 3. Enclosing class (implicit this)
if (ctx->enclosing_class_qn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_method(ctx->registry,
- ctx->enclosing_class_qn, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_method(ctx->registry, ctx->enclosing_class_qn, name);
+ if (f)
+ return f->qualified_name;
}
// 4. Using namespaces
for (int i = 0; i < ctx->using_ns_count; i++) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- ctx->using_namespaces[i], name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->using_namespaces[i], name);
+ if (f)
+ return f->qualified_name;
}
// 5. Current namespace + parent namespaces
if (ctx->current_namespace) {
- const char* ns = ctx->current_namespace;
+ const char *ns = ctx->current_namespace;
while (ns && ns[0]) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry, ns, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(ctx->registry, ns, name);
+ if (f)
+ return f->qualified_name;
// Walk up: "a.b.c" -> "a.b" -> "a"
- const char* dot = strrchr(ns, '.');
- if (!dot) break;
- char* parent = (char*)cbm_arena_alloc(ctx->arena, (size_t)(dot - ns) + 1);
- if (!parent) break;
+ const char *dot = strrchr(ns, '.');
+ if (!dot)
+ break;
+ char *parent = (char *)cbm_arena_alloc(ctx->arena, (size_t)(dot - ns) + 1);
+ if (!parent)
+ break;
memcpy(parent, ns, (size_t)(dot - ns));
parent[dot - ns] = '\0';
ns = parent;
@@ -601,27 +669,32 @@ static const char* c_resolve_name(CLSPContext* ctx, const char* name) {
// 6. Module scope
if (ctx->module_qn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- ctx->module_qn, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, name);
+ if (f)
+ return f->qualified_name;
}
// 7. Global scope (no prefix — C stdlib functions)
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, name);
+ if (f)
+ return f->qualified_name;
return NULL;
}
// --- ADL (Argument-Dependent Lookup) ---
// Extract the namespace from a qualified name: "std.vector" → "std", "boost.asio.ip" → "boost.asio"
-static const char* extract_namespace_from_qn(CBMArena* arena, const char* qn) {
- if (!qn) return NULL;
- const char* dot = strrchr(qn, '.');
- if (!dot || dot == qn) return NULL;
+static const char *extract_namespace_from_qn(CBMArena *arena, const char *qn) {
+ if (!qn)
+ return NULL;
+ const char *dot = strrchr(qn, '.');
+ if (!dot || dot == qn)
+ return NULL;
size_t len = (size_t)(dot - qn);
- char* ns = (char*)cbm_arena_alloc(arena, len + 1);
- if (!ns) return NULL;
+ char *ns = (char *)cbm_arena_alloc(arena, len + 1);
+ if (!ns)
+ return NULL;
memcpy(ns, qn, len);
ns[len] = '\0';
return ns;
@@ -629,43 +702,53 @@ static const char* extract_namespace_from_qn(CBMArena* arena, const char* qn) {
// ADL: resolve unqualified function call by searching namespaces of argument types.
// E.g., swap(a, b) where a is std::string → look up std::swap.
-static const char* c_adl_resolve(CLSPContext* ctx, const char* name, TSNode call_node) {
- if (!ctx->cpp_mode || !name) return NULL;
+static const char *c_adl_resolve(CLSPContext *ctx, const char *name, TSNode call_node) {
+ if (!ctx->cpp_mode || !name)
+ return NULL;
TSNode args = ts_node_child_by_field_name(call_node, "arguments", 9);
- if (ts_node_is_null(args)) return NULL;
+ if (ts_node_is_null(args))
+ return NULL;
uint32_t nc = ts_node_named_child_count(args);
- if (nc == 0) return NULL;
+ if (nc == 0)
+ return NULL;
// Collect unique namespace QNs from argument types (max 8 to bound work)
- const char* namespaces[8];
+ const char *namespaces[8];
int ns_count = 0;
for (uint32_t i = 0; i < nc && ns_count < 8; i++) {
TSNode arg = ts_node_named_child(args, i);
- if (ts_node_is_null(arg)) continue;
+ if (ts_node_is_null(arg))
+ continue;
- const CBMType* arg_type = c_eval_expr_type(ctx, arg);
- const char* qn = type_to_qn(c_simplify_type(ctx, arg_type, false));
- if (!qn) continue;
+ const CBMType *arg_type = c_eval_expr_type(ctx, arg);
+ const char *qn = type_to_qn(c_simplify_type(ctx, arg_type, false));
+ if (!qn)
+ continue;
- const char* ns = extract_namespace_from_qn(ctx->arena, qn);
- if (!ns) continue;
+ const char *ns = extract_namespace_from_qn(ctx->arena, qn);
+ if (!ns)
+ continue;
// Deduplicate
bool dup = false;
for (int j = 0; j < ns_count; j++) {
- if (strcmp(namespaces[j], ns) == 0) { dup = true; break; }
+ if (strcmp(namespaces[j], ns) == 0) {
+ dup = true;
+ break;
+ }
}
- if (!dup) namespaces[ns_count++] = ns;
+ if (!dup)
+ namespaces[ns_count++] = ns;
}
// Try each namespace
for (int i = 0; i < ns_count; i++) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- namespaces[i], name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(ctx->registry, namespaces[i], name);
+ if (f)
+ return f->qualified_name;
}
return NULL;
@@ -674,8 +757,9 @@ static const char* c_adl_resolve(CLSPContext* ctx, const char* name, TSNode call
// Resolve a name to a function QN via registry only (skips scope check).
// Used for function pointer target resolution where the name IS in scope
// as a function definition but we need the registry QN, not NULL.
-static const char* c_resolve_name_to_func_qn(CLSPContext* ctx, const char* name) {
- if (!name) return NULL;
+static const char *c_resolve_name_to_func_qn(CLSPContext *ctx, const char *name) {
+ if (!name)
+ return NULL;
// Using declarations
for (int i = 0; i < ctx->using_decl_count; i++) {
@@ -685,28 +769,33 @@ static const char* c_resolve_name_to_func_qn(CLSPContext* ctx, const char* name)
// Enclosing class
if (ctx->enclosing_class_qn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_method(ctx->registry,
- ctx->enclosing_class_qn, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_method(ctx->registry, ctx->enclosing_class_qn, name);
+ if (f)
+ return f->qualified_name;
}
// Using namespaces
for (int i = 0; i < ctx->using_ns_count; i++) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- ctx->using_namespaces[i], name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->using_namespaces[i], name);
+ if (f)
+ return f->qualified_name;
}
// Current namespace + parents
if (ctx->current_namespace) {
- const char* ns = ctx->current_namespace;
+ const char *ns = ctx->current_namespace;
while (ns && ns[0]) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry, ns, name);
- if (f) return f->qualified_name;
- const char* dot = strrchr(ns, '.');
- if (!dot) break;
- char* parent = (char*)cbm_arena_alloc(ctx->arena, (size_t)(dot - ns) + 1);
- if (!parent) break;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(ctx->registry, ns, name);
+ if (f)
+ return f->qualified_name;
+ const char *dot = strrchr(ns, '.');
+ if (!dot)
+ break;
+ char *parent = (char *)cbm_arena_alloc(ctx->arena, (size_t)(dot - ns) + 1);
+ if (!parent)
+ break;
memcpy(parent, ns, (size_t)(dot - ns));
parent[dot - ns] = '\0';
ns = parent;
@@ -715,40 +804,44 @@ static const char* c_resolve_name_to_func_qn(CLSPContext* ctx, const char* name)
// Module scope
if (ctx->module_qn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- ctx->module_qn, name);
- if (f) return f->qualified_name;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, name);
+ if (f)
+ return f->qualified_name;
}
// Global scope
- const CBMRegisteredFunc* gf = cbm_registry_lookup_func(ctx->registry, name);
- if (gf) return gf->qualified_name;
+ const CBMRegisteredFunc *gf = cbm_registry_lookup_func(ctx->registry, name);
+ if (gf)
+ return gf->qualified_name;
return NULL;
}
// Resolve a name to a type (for identifiers used as types)
-static const CBMType* c_resolve_name_to_type(CLSPContext* ctx, const char* name) {
- if (!name) return cbm_type_unknown();
+static const CBMType *c_resolve_name_to_type(CLSPContext *ctx, const char *name) {
+ if (!name)
+ return cbm_type_unknown();
// Builtin types
- if (is_c_builtin_type(name)) return cbm_type_builtin(ctx->arena, name);
+ if (is_c_builtin_type(name))
+ return cbm_type_builtin(ctx->arena, name);
// Scope lookup: typedef/using aliases are bound here.
// If the name resolves to an alias, follow it to the underlying type.
{
- const CBMType* scoped = cbm_scope_lookup(ctx->current_scope, name);
+ const CBMType *scoped = cbm_scope_lookup(ctx->current_scope, name);
if (scoped && scoped->kind == CBM_TYPE_ALIAS) {
- const CBMType* resolved = cbm_type_resolve_alias(scoped);
- if (resolved && !cbm_type_is_unknown(resolved)) return resolved;
+ const CBMType *resolved = cbm_type_resolve_alias(scoped);
+ if (resolved && !cbm_type_is_unknown(resolved))
+ return resolved;
}
}
// Template type parameters (T, U, etc.)
if (ctx->in_template && ctx->template_param_names) {
for (int i = 0; i < ctx->template_param_count; i++) {
- if (ctx->template_param_names[i] &&
- strcmp(ctx->template_param_names[i], name) == 0) {
+ if (ctx->template_param_names[i] && strcmp(ctx->template_param_names[i], name) == 0) {
// Return default if available, otherwise TYPE_PARAM
if (ctx->template_param_defaults && ctx->template_param_defaults[i])
return ctx->template_param_defaults[i];
@@ -760,50 +853,57 @@ static const CBMType* c_resolve_name_to_type(CLSPContext* ctx, const char* name)
// Using declarations
for (int i = 0; i < ctx->using_decl_count; i++) {
if (strcmp(ctx->using_decl_names[i], name) == 0) {
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, ctx->using_decl_qns[i]);
- if (rt) return cbm_type_named(ctx->arena, rt->qualified_name);
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, ctx->using_decl_qns[i]);
+ if (rt)
+ return cbm_type_named(ctx->arena, rt->qualified_name);
}
}
// Enclosing class (nested types: Factory::Product)
if (ctx->enclosing_class_qn) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->enclosing_class_qn, name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->enclosing_class_qn, name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
}
// Current namespace
if (ctx->current_namespace) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
}
// Module scope
if (ctx->module_qn) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
}
// Using namespaces
for (int i = 0; i < ctx->using_ns_count; i++) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->using_namespaces[i], name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->using_namespaces[i], name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
}
// Try std:: prefix (very common)
if (ctx->cpp_mode) {
- const char* std_qn = cbm_arena_sprintf(ctx->arena, "std.%s", name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, std_qn);
- if (rt) return cbm_type_named(ctx->arena, std_qn);
+ const char *std_qn = cbm_arena_sprintf(ctx->arena, "std.%s", name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, std_qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, std_qn);
}
// Unresolved — return named with module prefix
if (ctx->module_qn) {
return cbm_type_named(ctx->arena,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name));
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name));
}
return cbm_type_named(ctx->arena, name);
}
@@ -812,32 +912,33 @@ static const CBMType* c_resolve_name_to_type(CLSPContext* ctx, const char* name)
// c_parse_type_node: AST type node -> CBMType
// ============================================================================
-const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
- if (ts_node_is_null(node)) return cbm_type_unknown();
- const char* kind = ts_node_type(node);
+const CBMType *c_parse_type_node(CLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return cbm_type_unknown();
+ const char *kind = ts_node_type(node);
// primitive_type: int, double, char, void, bool
if (strcmp(kind, "primitive_type") == 0) {
- char* name = c_node_text(ctx, node);
+ char *name = c_node_text(ctx, node);
return name ? cbm_type_builtin(ctx->arena, name) : cbm_type_unknown();
}
// sized_type_specifier: unsigned int, long long, etc.
if (strcmp(kind, "sized_type_specifier") == 0) {
- char* name = c_node_text(ctx, node);
+ char *name = c_node_text(ctx, node);
return name ? cbm_type_builtin(ctx->arena, name) : cbm_type_unknown();
}
// type_identifier: Foo, MyClass
if (strcmp(kind, "type_identifier") == 0) {
- char* name = c_node_text(ctx, node);
- if (!name) return cbm_type_unknown();
+ char *name = c_node_text(ctx, node);
+ if (!name)
+ return cbm_type_unknown();
return c_resolve_name_to_type(ctx, name);
}
// qualified_identifier: std::vector, ns::Foo
- if (strcmp(kind, "qualified_identifier") == 0 ||
- strcmp(kind, "scoped_type_identifier") == 0) {
+ if (strcmp(kind, "qualified_identifier") == 0 || strcmp(kind, "scoped_type_identifier") == 0) {
// Check if name field is a template_type (e.g., std::vector<Widget>)
// If so, build scoped QN prefix and delegate to template_type handler
TSNode name_child = ts_node_child_by_field_name(node, "name", 4);
@@ -845,50 +946,58 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
strcmp(ts_node_type(name_child), "template_type") == 0) {
// Build scope prefix from scope chain
TSNode scope_node = ts_node_child_by_field_name(node, "scope", 5);
- char* scope_text = NULL;
+ char *scope_text = NULL;
if (!ts_node_is_null(scope_node)) {
scope_text = c_node_text(ctx, scope_node);
if (scope_text) {
- const char* alias_qn = c_resolve_ns_alias(ctx, scope_text);
- if (alias_qn) scope_text = (char*)alias_qn;
+ const char *alias_qn = c_resolve_ns_alias(ctx, scope_text);
+ if (alias_qn)
+ scope_text = (char *)alias_qn;
}
}
// Parse the template_type's own name
TSNode tmpl_name = ts_node_child_by_field_name(name_child, "name", 4);
TSNode tmpl_args = ts_node_child_by_field_name(name_child, "arguments", 9);
- char* tmpl_name_text = NULL;
- if (!ts_node_is_null(tmpl_name)) tmpl_name_text = c_node_text(ctx, tmpl_name);
- if (!tmpl_name_text) return cbm_type_unknown();
+ char *tmpl_name_text = NULL;
+ if (!ts_node_is_null(tmpl_name))
+ tmpl_name_text = c_node_text(ctx, tmpl_name);
+ if (!tmpl_name_text)
+ return cbm_type_unknown();
// Build full QN: scope.template_name
- const char* template_qn;
+ const char *template_qn;
if (scope_text) {
- const char* scoped = cbm_arena_sprintf(ctx->arena, "%s::%s", scope_text, tmpl_name_text);
+ const char *scoped =
+ cbm_arena_sprintf(ctx->arena, "%s::%s", scope_text, tmpl_name_text);
template_qn = c_build_qn(ctx, scoped);
} else {
template_qn = c_build_qn(ctx, tmpl_name_text);
}
// Resolve against registry
- const CBMRegisteredType* trt = cbm_registry_lookup_type(ctx->registry, template_qn);
+ const CBMRegisteredType *trt = cbm_registry_lookup_type(ctx->registry, template_qn);
if (!trt && ctx->module_qn) {
- const char* mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, template_qn);
+ const char *mod_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, template_qn);
trt = cbm_registry_lookup_type(ctx->registry, mod_qn);
- if (trt) template_qn = mod_qn;
+ if (trt)
+ template_qn = mod_qn;
}
// Parse template arguments
- const CBMType* targs[16];
+ const CBMType *targs[16];
int targ_count = 0;
if (!ts_node_is_null(tmpl_args)) {
uint32_t nc = ts_node_named_child_count(tmpl_args);
for (uint32_t i = 0; i < nc && targ_count < 15; i++) {
TSNode arg = ts_node_named_child(tmpl_args, i);
- if (ts_node_is_null(arg)) continue;
- const char* ak = ts_node_type(arg);
+ if (ts_node_is_null(arg))
+ continue;
+ const char *ak = ts_node_type(arg);
if (strcmp(ak, "type_descriptor") == 0) {
if (ts_node_named_child_count(arg) > 0)
- targs[targ_count++] = c_parse_type_node(ctx, ts_node_named_child(arg, 0));
+ targs[targ_count++] =
+ c_parse_type_node(ctx, ts_node_named_child(arg, 0));
} else {
targs[targ_count++] = c_parse_type_node(ctx, arg);
}
@@ -900,28 +1009,31 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
return cbm_type_named(ctx->arena, template_qn);
}
- char* text = c_node_text(ctx, node);
- if (!text) return cbm_type_unknown();
+ char *text = c_node_text(ctx, node);
+ if (!text)
+ return cbm_type_unknown();
// Check for namespace alias at start
TSNode scope_node = ts_node_child_by_field_name(node, "scope", 5);
if (!ts_node_is_null(scope_node)) {
- char* scope_text = c_node_text(ctx, scope_node);
+ char *scope_text = c_node_text(ctx, scope_node);
if (scope_text) {
- const char* alias_qn = c_resolve_ns_alias(ctx, scope_text);
+ const char *alias_qn = c_resolve_ns_alias(ctx, scope_text);
if (alias_qn) {
if (!ts_node_is_null(name_child)) {
- char* name = c_node_text(ctx, name_child);
- if (name) text = (char*)cbm_arena_sprintf(ctx->arena, "%s::%s", alias_qn, name);
+ char *name = c_node_text(ctx, name_child);
+ if (name)
+ text = (char *)cbm_arena_sprintf(ctx->arena, "%s::%s", alias_qn, name);
}
}
}
}
- const char* qn = c_build_qn(ctx, text);
+ const char *qn = c_build_qn(ctx, text);
// Check registry
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
return cbm_type_named(ctx->arena, qn);
}
@@ -930,52 +1042,60 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
TSNode args_node = ts_node_child_by_field_name(node, "arguments", 9);
- char* name_text = NULL;
+ char *name_text = NULL;
if (!ts_node_is_null(name_node)) {
name_text = c_node_text(ctx, name_node);
}
- if (!name_text) return cbm_type_unknown();
+ if (!name_text)
+ return cbm_type_unknown();
- const char* template_qn = c_build_qn(ctx, name_text);
+ const char *template_qn = c_build_qn(ctx, name_text);
// Try resolving short name to full QN
- const CBMRegisteredType* trt = cbm_registry_lookup_type(ctx->registry, template_qn);
+ const CBMRegisteredType *trt = cbm_registry_lookup_type(ctx->registry, template_qn);
if (!trt && ctx->module_qn) {
// Try with module prefix
- const char* mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, template_qn);
+ const char *mod_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, template_qn);
trt = cbm_registry_lookup_type(ctx->registry, mod_qn);
- if (trt) template_qn = mod_qn;
+ if (trt)
+ template_qn = mod_qn;
}
if (!trt && ctx->current_namespace) {
- // Try with current namespace prefix (e.g., inside namespace std, "shared_ptr" → "std.shared_ptr")
- const char* ns_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->current_namespace, template_qn);
+ // Try with current namespace prefix (e.g., inside namespace std, "shared_ptr" →
+ // "std.shared_ptr")
+ const char *ns_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, template_qn);
trt = cbm_registry_lookup_type(ctx->registry, ns_qn);
- if (trt) template_qn = ns_qn;
+ if (trt)
+ template_qn = ns_qn;
// Also try module + namespace
if (!trt && ctx->module_qn) {
- const char* full_qn = cbm_arena_sprintf(ctx->arena, "%s.%s.%s",
- ctx->module_qn, ctx->current_namespace, template_qn);
+ const char *full_qn = cbm_arena_sprintf(ctx->arena, "%s.%s.%s", ctx->module_qn,
+ ctx->current_namespace, template_qn);
trt = cbm_registry_lookup_type(ctx->registry, full_qn);
- if (trt) template_qn = full_qn;
+ if (trt)
+ template_qn = full_qn;
}
}
if (!trt) {
// Try with std:: prefix
- const char* std_qn = cbm_arena_sprintf(ctx->arena, "std.%s", template_qn);
+ const char *std_qn = cbm_arena_sprintf(ctx->arena, "std.%s", template_qn);
trt = cbm_registry_lookup_type(ctx->registry, std_qn);
- if (trt) template_qn = std_qn;
+ if (trt)
+ template_qn = std_qn;
}
// Parse template arguments
- const CBMType* targs[16];
+ const CBMType *targs[16];
int targ_count = 0;
if (!ts_node_is_null(args_node)) {
uint32_t nc = ts_node_named_child_count(args_node);
for (uint32_t i = 0; i < nc && targ_count < 15; i++) {
TSNode arg = ts_node_named_child(args_node, i);
- if (ts_node_is_null(arg)) continue;
- const char* ak = ts_node_type(arg);
+ if (ts_node_is_null(arg))
+ continue;
+ const char *ak = ts_node_type(arg);
if (strcmp(ak, "type_descriptor") == 0) {
// type_descriptor wraps a type node
if (ts_node_named_child_count(arg) > 0) {
@@ -994,11 +1114,10 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
}
// pointer_declarator / pointer (*) in type context
- if (strcmp(kind, "pointer_declarator") == 0 ||
- strcmp(kind, "pointer_type") == 0) {
+ if (strcmp(kind, "pointer_declarator") == 0 || strcmp(kind, "pointer_type") == 0) {
if (ts_node_named_child_count(node) > 0) {
return cbm_type_pointer(ctx->arena,
- c_parse_type_node(ctx, ts_node_named_child(node, 0)));
+ c_parse_type_node(ctx, ts_node_named_child(node, 0)));
}
return cbm_type_pointer(ctx->arena, cbm_type_unknown());
}
@@ -1008,7 +1127,7 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
strcmp(kind, "abstract_reference_declarator") == 0) {
if (ts_node_named_child_count(node) > 0) {
return cbm_type_reference(ctx->arena,
- c_parse_type_node(ctx, ts_node_named_child(node, 0)));
+ c_parse_type_node(ctx, ts_node_named_child(node, 0)));
}
return cbm_type_reference(ctx->arena, cbm_type_unknown());
}
@@ -1034,8 +1153,7 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
// array_declarator: int[10]
if (strcmp(kind, "array_declarator") == 0 || strcmp(kind, "array_type") == 0) {
if (ts_node_named_child_count(node) > 0) {
- return cbm_type_slice(ctx->arena,
- c_parse_type_node(ctx, ts_node_named_child(node, 0)));
+ return cbm_type_slice(ctx->arena, c_parse_type_node(ctx, ts_node_named_child(node, 0)));
}
return cbm_type_unknown();
}
@@ -1050,11 +1168,12 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "struct_specifier") == 0 || strcmp(kind, "class_specifier") == 0) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
if (!ts_node_is_null(name_node)) {
- char* name = c_node_text(ctx, name_node);
- if (name) return c_resolve_name_to_type(ctx, name);
+ char *name = c_node_text(ctx, name_node);
+ if (name)
+ return c_resolve_name_to_type(ctx, name);
}
// Anonymous struct
- CBMType* t = (CBMType*)cbm_arena_alloc(ctx->arena, sizeof(CBMType));
+ CBMType *t = (CBMType *)cbm_arena_alloc(ctx->arena, sizeof(CBMType));
memset(t, 0, sizeof(CBMType));
t->kind = CBM_TYPE_STRUCT;
return t;
@@ -1064,8 +1183,9 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "enum_specifier") == 0) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
if (!ts_node_is_null(name_node)) {
- char* name = c_node_text(ctx, name_node);
- if (name) return c_resolve_name_to_type(ctx, name);
+ char *name = c_node_text(ctx, name_node);
+ if (name)
+ return c_resolve_name_to_type(ctx, name);
}
return cbm_type_builtin(ctx->arena, "int");
}
@@ -1076,7 +1196,7 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
// Find the actual type node (skip qualifiers)
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "type_qualifier") != 0) {
return c_parse_type_node(ctx, child);
}
@@ -1091,8 +1211,9 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
// dependent_type: in template scope
if (strcmp(kind, "dependent_type") == 0 || strcmp(kind, "dependent_name") == 0) {
- char* text = c_node_text(ctx, node);
- if (text) return cbm_type_named(ctx->arena, c_build_qn(ctx, text));
+ char *text = c_node_text(ctx, node);
+ if (text)
+ return cbm_type_named(ctx->arena, c_build_qn(ctx, text));
return cbm_type_unknown();
}
@@ -1103,7 +1224,7 @@ const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node) {
// c_simplify_type: multi-step type unwrapping (clangd simplifyType)
// ============================================================================
-const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_pointer) {
+const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_pointer) {
for (int i = 0; i < 64 && t; i++) {
// Resolve aliases
if (t->kind == CBM_TYPE_ALIAS) {
@@ -1116,12 +1237,12 @@ const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_p
// Resolve template type parameters using defaults
if (t->kind == CBM_TYPE_TYPE_PARAM && ctx->in_template) {
- const CBMType* resolved = c_resolve_template_param(ctx, t->data.type_param.name);
+ const CBMType *resolved = c_resolve_template_param(ctx, t->data.type_param.name);
if (resolved) {
t = resolved;
continue;
}
- break; // no default available
+ break; // no default available
}
// Unwrap references
@@ -1130,7 +1251,8 @@ const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_p
continue;
}
- if (!unwrap_pointer) break;
+ if (!unwrap_pointer)
+ break;
// Unwrap pointer
if (t->kind == CBM_TYPE_POINTER) {
@@ -1148,47 +1270,53 @@ const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_p
// Named type with operator->
if (t->kind == CBM_TYPE_NAMED) {
- const CBMRegisteredFunc* op = cbm_registry_lookup_method(ctx->registry,
- t->data.named.qualified_name, "operator->");
+ const CBMRegisteredFunc *op = cbm_registry_lookup_method(
+ ctx->registry, t->data.named.qualified_name, "operator->");
if (op && op->signature && op->signature->kind == CBM_TYPE_FUNC &&
op->signature->data.func.return_types && op->signature->data.func.return_types[0]) {
t = op->signature->data.func.return_types[0];
// deref the pointer return
- if (t->kind == CBM_TYPE_POINTER) t = t->data.pointer.elem;
+ if (t->kind == CBM_TYPE_POINTER)
+ t = t->data.pointer.elem;
break;
}
}
// Template type with operator-> (e.g., optional<Widget>::operator->)
if (t->kind == CBM_TYPE_TEMPLATE) {
- const char* tqn = t->data.template_type.template_name;
- const CBMRegisteredFunc* op = c_lookup_member(ctx, tqn, "operator->");
+ const char *tqn = t->data.template_type.template_name;
+ const CBMRegisteredFunc *op = c_lookup_member(ctx, tqn, "operator->");
if (op && op->signature && op->signature->kind == CBM_TYPE_FUNC &&
op->signature->data.func.return_types && op->signature->data.func.return_types[0]) {
- const CBMType* ret = op->signature->data.func.return_types[0];
+ const CBMType *ret = op->signature->data.func.return_types[0];
// Substitute template params using receiver's template args
if (ret->kind == CBM_TYPE_TYPE_PARAM || ret->kind == CBM_TYPE_POINTER ||
ret->kind == CBM_TYPE_REFERENCE) {
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, tqn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, tqn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, tqn));
}
if (rt && rt->type_param_names) {
- ret = cbm_type_substitute(ctx->arena, ret,
- rt->type_param_names, t->data.template_type.template_args);
+ ret = cbm_type_substitute(ctx->arena, ret, rt->type_param_names,
+ t->data.template_type.template_args);
} else {
- const char* fb[] = {"T", "K", "V", NULL};
- const CBMType* fa[3] = {NULL};
+ const char *fb[] = {"T", "K", "V", NULL};
+ const CBMType *fa[3] = {NULL};
int na = t->data.template_type.arg_count;
- if (na > 0) fa[0] = t->data.template_type.template_args[0];
- if (na > 1) fa[1] = t->data.template_type.template_args[1];
- if (na > 2) fa[2] = t->data.template_type.template_args[2];
+ if (na > 0)
+ fa[0] = t->data.template_type.template_args[0];
+ if (na > 1)
+ fa[1] = t->data.template_type.template_args[1];
+ if (na > 2)
+ fa[2] = t->data.template_type.template_args[2];
ret = cbm_type_substitute(ctx->arena, ret, fb, fa);
}
}
t = ret;
- if (t->kind == CBM_TYPE_POINTER) t = t->data.pointer.elem;
+ if (t->kind == CBM_TYPE_POINTER)
+ t = t->data.pointer.elem;
break;
}
// Fallback: known smart pointer types — use first template arg
@@ -1205,12 +1333,16 @@ const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_p
}
// Get the QN string from a type (for member lookup)
-static const char* type_to_qn(const CBMType* t) {
- if (!t) return NULL;
+static const char *type_to_qn(const CBMType *t) {
+ if (!t)
+ return NULL;
switch (t->kind) {
- case CBM_TYPE_NAMED: return t->data.named.qualified_name;
- case CBM_TYPE_TEMPLATE: return t->data.template_type.template_name;
- default: return NULL;
+ case CBM_TYPE_NAMED:
+ return t->data.named.qualified_name;
+ case CBM_TYPE_TEMPLATE:
+ return t->data.template_type.template_name;
+ default:
+ return NULL;
}
}
@@ -1218,52 +1350,55 @@ static const char* type_to_qn(const CBMType* t) {
// c_eval_expr_type: recursive expression type evaluator
// ============================================================================
-static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node);
+static const CBMType *c_eval_expr_type_inner(CLSPContext *ctx, TSNode node);
#define C_EVAL_DEPTH_LIMIT 256
#define C_EVAL_MAX_STEPS_PER_FILE 10000
-const CBMType* c_eval_expr_type(CLSPContext* ctx, TSNode node) {
- if (ts_node_is_null(node)) return cbm_type_unknown();
+const CBMType *c_eval_expr_type(CLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return cbm_type_unknown();
/* Expression type evaluation is best-effort. Some recovery-mode C++ ASTs
* can repeatedly drive member/type lookup without increasing recursion
* depth. Keep a generous per-file work budget so pathological expressions
* degrade to unknown instead of hanging repository indexing. */
- if (ctx->eval_depth > C_EVAL_DEPTH_LIMIT ||
- ctx->eval_steps++ > C_EVAL_MAX_STEPS_PER_FILE) {
+ if (ctx->eval_depth > C_EVAL_DEPTH_LIMIT || ctx->eval_steps++ > C_EVAL_MAX_STEPS_PER_FILE) {
if (ctx->debug && ctx->eval_steps == C_EVAL_MAX_STEPS_PER_FILE + 2) {
fprintf(stderr, " [clsp] expression eval step budget exhausted; returning unknown\n");
}
return cbm_type_unknown();
}
ctx->eval_depth++;
- const CBMType* result = c_eval_expr_type_inner(ctx, node);
+ const CBMType *result = c_eval_expr_type_inner(ctx, node);
ctx->eval_depth--;
return result ? result : cbm_type_unknown();
}
-static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
- const char* kind = ts_node_type(node);
+static const CBMType *c_eval_expr_type_inner(CLSPContext *ctx, TSNode node) {
+ const char *kind = ts_node_type(node);
// --- identifier: scope lookup ---
if (strcmp(kind, "identifier") == 0) {
- char* name = c_node_text(ctx, node);
- if (!name) return cbm_type_unknown();
+ char *name = c_node_text(ctx, node);
+ if (!name)
+ return cbm_type_unknown();
// Scope lookup
- const CBMType* t = cbm_scope_lookup(ctx->current_scope, name);
- if (!cbm_type_is_unknown(t)) return t;
+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
+ if (!cbm_type_is_unknown(t))
+ return t;
// Check if it's a registered function (before type check — functions
// return FUNC type which lets call_expression extract return types)
- const char* fqn = c_resolve_name(ctx, name);
+ const char *fqn = c_resolve_name(ctx, name);
if (fqn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, fqn);
- if (f && f->signature) return f->signature;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, fqn);
+ if (f && f->signature)
+ return f->signature;
}
// Check if it's a type name (for constructor calls / casts)
- const CBMType* type = c_resolve_name_to_type(ctx, name);
+ const CBMType *type = c_resolve_name_to_type(ctx, name);
if (type && type->kind == CBM_TYPE_NAMED) {
// Could be a constructor call — return as type
return type;
@@ -1276,7 +1411,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "this") == 0) {
if (ctx->enclosing_class_qn) {
return cbm_type_pointer(ctx->arena,
- cbm_type_named(ctx->arena, ctx->enclosing_class_qn));
+ cbm_type_named(ctx->arena, ctx->enclosing_class_qn));
}
return cbm_type_unknown();
}
@@ -1288,11 +1423,13 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (ts_node_is_null(arg_node) || ts_node_is_null(field_node))
return cbm_type_unknown();
- char* field_name = c_node_text(ctx, field_node);
- if (!field_name) return cbm_type_unknown();
+ char *field_name = c_node_text(ctx, field_node);
+ if (!field_name)
+ return cbm_type_unknown();
- const CBMType* obj_type = c_eval_expr_type(ctx, arg_node);
- if (cbm_type_is_unknown(obj_type)) return cbm_type_unknown();
+ const CBMType *obj_type = c_eval_expr_type(ctx, arg_node);
+ if (cbm_type_is_unknown(obj_type))
+ return cbm_type_unknown();
// Determine if this is . or -> access
// Check for "->" operator in node text
@@ -1301,28 +1438,33 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
- if (op && strcmp(op, "->") == 0) { is_arrow = true; break; }
+ char *op = c_node_text(ctx, child);
+ if (op && strcmp(op, "->") == 0) {
+ is_arrow = true;
+ break;
+ }
}
}
// Simplify type for member lookup
- const CBMType* base;
+ const CBMType *base;
if (is_arrow) {
base = c_simplify_type(ctx, obj_type, true); // unwrap pointer/smart ptr
} else {
base = c_simplify_type(ctx, obj_type, false); // just unwrap refs/aliases
}
- const char* type_qn = type_to_qn(base);
- if (!type_qn) return cbm_type_unknown();
+ const char *type_qn = type_to_qn(base);
+ if (!type_qn)
+ return cbm_type_unknown();
// Look up method
- const CBMRegisteredFunc* method = c_lookup_member(ctx, type_qn, field_name);
- if (method && method->signature) return method->signature;
+ const CBMRegisteredFunc *method = c_lookup_member(ctx, type_qn, field_name);
+ if (method && method->signature)
+ return method->signature;
// Look up field
- const CBMType* field_type = c_lookup_field_type(ctx, type_qn, field_name, 0);
+ const CBMType *field_type = c_lookup_field_type(ctx, type_qn, field_name, 0);
if (field_type && !cbm_type_is_unknown(field_type)) {
// Template field substitution: if field type is TYPE_PARAM (or NAMED matching
// a template param name) and receiver is a TEMPLATE type, substitute using
@@ -1333,15 +1475,16 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// may register template fields as NAMED("V") rather than TYPE_PARAM("V"))
if (!is_tparam && field_type->kind == CBM_TYPE_NAMED &&
base->kind == CBM_TYPE_TEMPLATE) {
- const CBMRegisteredType* trt = cbm_registry_lookup_type(ctx->registry, type_qn);
+ const CBMRegisteredType *trt = cbm_registry_lookup_type(ctx->registry, type_qn);
if (!trt && ctx->module_qn) {
- trt = cbm_registry_lookup_type(ctx->registry,
+ trt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
}
if (trt && trt->type_param_names) {
- const char* fname_qn = field_type->data.named.qualified_name;
+ const char *fname_qn = field_type->data.named.qualified_name;
// Extract short name from QN (after last dot)
- const char* short_fn = strrchr(fname_qn, '.');
+ const char *short_fn = strrchr(fname_qn, '.');
short_fn = short_fn ? short_fn + 1 : fname_qn;
for (int tpi = 0; trt->type_param_names[tpi]; tpi++) {
if (strcmp(trt->type_param_names[tpi], short_fn) == 0) {
@@ -1355,24 +1498,30 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
if (is_tparam && base->kind == CBM_TYPE_TEMPLATE &&
base->data.template_type.template_args) {
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, type_qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
}
if (rt && rt->type_param_names) {
- field_type = cbm_type_substitute(ctx->arena, field_type,
- rt->type_param_names, base->data.template_type.template_args);
+ field_type = cbm_type_substitute(ctx->arena, field_type, rt->type_param_names,
+ base->data.template_type.template_args);
} else {
// Fallback: positional T, K, V
- const char* params[] = {"T", "K", "V", "T1", "T2", NULL};
- const CBMType* args[5] = {NULL};
+ const char *params[] = {"T", "K", "V", "T1", "T2", NULL};
+ const CBMType *args[5] = {NULL};
int nargs = base->data.template_type.arg_count;
- if (nargs > 0) args[0] = base->data.template_type.template_args[0];
- if (nargs > 0) args[1] = base->data.template_type.template_args[0];
- if (nargs > 1) args[2] = base->data.template_type.template_args[1];
- if (nargs > 0) args[3] = base->data.template_type.template_args[0];
- if (nargs > 1) args[4] = base->data.template_type.template_args[1];
+ if (nargs > 0)
+ args[0] = base->data.template_type.template_args[0];
+ if (nargs > 0)
+ args[1] = base->data.template_type.template_args[0];
+ if (nargs > 1)
+ args[2] = base->data.template_type.template_args[1];
+ if (nargs > 0)
+ args[3] = base->data.template_type.template_args[0];
+ if (nargs > 1)
+ args[4] = base->data.template_type.template_args[1];
field_type = cbm_type_substitute(ctx->arena, field_type, params, args);
}
}
@@ -1383,10 +1532,10 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
// --- qualified_identifier / scoped_identifier: ns::Class::method or Enum::Value ---
- if (strcmp(kind, "qualified_identifier") == 0 ||
- strcmp(kind, "scoped_identifier") == 0) {
- char* text = c_node_text(ctx, node);
- if (!text) return cbm_type_unknown();
+ if (strcmp(kind, "qualified_identifier") == 0 || strcmp(kind, "scoped_identifier") == 0) {
+ char *text = c_node_text(ctx, node);
+ if (!text)
+ return cbm_type_unknown();
// Check if name child is template_function: ns::func<T> → strip template args
TSNode qi_name_child = ts_node_child_by_field_name(node, "name", 4);
@@ -1399,63 +1548,65 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Build scope::bare_name without template args
TSNode scope_node = ts_node_child_by_field_name(node, "scope", 5);
TSNode tmpl_bare = ts_node_child_by_field_name(qi_name_child, "name", 4);
- char* scope_text = !ts_node_is_null(scope_node) ? c_node_text(ctx, scope_node) : NULL;
- char* bare_name = !ts_node_is_null(tmpl_bare) ? c_node_text(ctx, tmpl_bare) : NULL;
+ char *scope_text = !ts_node_is_null(scope_node) ? c_node_text(ctx, scope_node) : NULL;
+ char *bare_name = !ts_node_is_null(tmpl_bare) ? c_node_text(ctx, tmpl_bare) : NULL;
if (bare_name) {
text = scope_text
- ? (char*)cbm_arena_sprintf(ctx->arena, "%s::%s", scope_text, bare_name)
- : bare_name;
+ ? (char *)cbm_arena_sprintf(ctx->arena, "%s::%s", scope_text, bare_name)
+ : bare_name;
}
}
- const char* qn = c_build_qn(ctx, text);
+ const char *qn = c_build_qn(ctx, text);
// Try as function: module-prefixed first (shadows stdlib stubs), then bare QN
- const CBMRegisteredFunc* f = NULL;
+ const CBMRegisteredFunc *f = NULL;
if (ctx->module_qn) {
- f = cbm_registry_lookup_func(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn));
+ f = cbm_registry_lookup_func(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn));
}
- if (!f) f = cbm_registry_lookup_func(ctx->registry, qn);
+ if (!f)
+ f = cbm_registry_lookup_func(ctx->registry, qn);
// Namespace fallback: extract_defs may omit namespace from QN.
// "utils.create_logger" → try just "create_logger" with module prefix
if (!f) {
- const char* ns_dot = strrchr(qn, '.');
+ const char *ns_dot = strrchr(qn, '.');
if (ns_dot && ctx->module_qn) {
- const char* bare = ns_dot + 1;
- f = cbm_registry_lookup_func(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, bare));
- if (!f) f = cbm_registry_lookup_func(ctx->registry, bare);
+ const char *bare = ns_dot + 1;
+ f = cbm_registry_lookup_func(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, bare));
+ if (!f)
+ f = cbm_registry_lookup_func(ctx->registry, bare);
}
}
if (f && f->signature) {
// If template args present, substitute into return type
if (qi_has_tmpl_args && !ts_node_is_null(qi_tmpl_args) &&
- f->signature->kind == CBM_TYPE_FUNC &&
- f->signature->data.func.return_types &&
+ f->signature->kind == CBM_TYPE_FUNC && f->signature->data.func.return_types &&
f->signature->data.func.return_types[0]) {
- const CBMType* base_ret = f->signature->data.func.return_types[0];
- const CBMType* targs[16];
+ const CBMType *base_ret = f->signature->data.func.return_types[0];
+ const CBMType *targs[16];
int targ_count = 0;
uint32_t tnc = ts_node_named_child_count(qi_tmpl_args);
for (uint32_t ti = 0; ti < tnc && targ_count < 15; ti++) {
TSNode targ = ts_node_named_child(qi_tmpl_args, ti);
- if (ts_node_is_null(targ)) continue;
- const char* tak = ts_node_type(targ);
+ if (ts_node_is_null(targ))
+ continue;
+ const char *tak = ts_node_type(targ);
if (strcmp(tak, "type_descriptor") == 0) {
if (ts_node_named_child_count(targ) > 0)
- targs[targ_count++] = c_parse_type_node(ctx,
- ts_node_named_child(targ, 0));
+ targs[targ_count++] =
+ c_parse_type_node(ctx, ts_node_named_child(targ, 0));
} else {
targs[targ_count++] = c_parse_type_node(ctx, targ);
}
}
if (targ_count > 0) {
- const char** tpn = f->type_param_names;
+ const char **tpn = f->type_param_names;
if (tpn) {
base_ret = cbm_type_substitute(ctx->arena, base_ret, tpn, targs);
} else {
- const char* fallback[] = {"T", "U", "V", "W", NULL};
+ const char *fallback[] = {"T", "U", "V", "W", NULL};
base_ret = cbm_type_substitute(ctx->arena, base_ret, fallback, targs);
}
// If return type is still NAMED after substitution (no TYPE_PARAM was
@@ -1464,16 +1615,18 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// e.g., make_shared<Widget> returns NAMED("std.shared_ptr") →
// TEMPLATE("std.shared_ptr", [Widget])
if (base_ret->kind == CBM_TYPE_NAMED) {
- const CBMType** final_targs = (const CBMType**)cbm_arena_alloc(
- ctx->arena, (targ_count + 1) * sizeof(const CBMType*));
- for (int i = 0; i < targ_count; i++) final_targs[i] = targs[i];
+ const CBMType **final_targs = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (targ_count + 1) * sizeof(const CBMType *));
+ for (int i = 0; i < targ_count; i++)
+ final_targs[i] = targs[i];
final_targs[targ_count] = NULL;
- base_ret = cbm_type_template(ctx->arena,
- base_ret->data.named.qualified_name, final_targs, targ_count);
+ base_ret =
+ cbm_type_template(ctx->arena, base_ret->data.named.qualified_name,
+ final_targs, targ_count);
}
}
- const CBMType** rets = (const CBMType**)cbm_arena_alloc(
- ctx->arena, 2 * sizeof(const CBMType*));
+ const CBMType **rets =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
rets[0] = base_ret;
rets[1] = NULL;
return cbm_type_func(ctx->arena, NULL, NULL, rets);
@@ -1482,57 +1635,63 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
// Try as type (bare QN then module-prefixed)
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, qn);
- if (rt) return cbm_type_named(ctx->arena, qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, qn);
if (!rt && ctx->module_qn) {
- const char* mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn);
+ const char *mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn);
rt = cbm_registry_lookup_type(ctx->registry, mod_qn);
- if (rt) return cbm_type_named(ctx->arena, mod_qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, mod_qn);
}
// Try as enum member: Enum::Value → look up Enum type, return int/enum type
- const char* dot = strrchr(qn, '.');
+ const char *dot = strrchr(qn, '.');
if (dot) {
size_t prefix_len = (size_t)(dot - qn);
- char* enum_qn = (char*)cbm_arena_alloc(ctx->arena, prefix_len + 1);
+ char *enum_qn = (char *)cbm_arena_alloc(ctx->arena, prefix_len + 1);
if (enum_qn) {
memcpy(enum_qn, qn, prefix_len);
enum_qn[prefix_len] = '\0';
- const CBMRegisteredType* enum_rt = cbm_registry_lookup_type(ctx->registry, enum_qn);
+ const CBMRegisteredType *enum_rt = cbm_registry_lookup_type(ctx->registry, enum_qn);
if (enum_rt) {
return cbm_type_named(ctx->arena, enum_qn);
}
// Try with module prefix
if (ctx->module_qn) {
- const char* fqn_enum = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, enum_qn);
+ const char *fqn_enum =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, enum_qn);
enum_rt = cbm_registry_lookup_type(ctx->registry, fqn_enum);
- if (enum_rt) return cbm_type_named(ctx->arena, fqn_enum);
+ if (enum_rt)
+ return cbm_type_named(ctx->arena, fqn_enum);
}
}
// Template heuristic: T::member where T is a template param with default
if (ctx->in_template && dot) {
size_t prefix_len2 = (size_t)(dot - qn);
- char* scope_name = (char*)cbm_arena_alloc(ctx->arena, prefix_len2 + 1);
+ char *scope_name = (char *)cbm_arena_alloc(ctx->arena, prefix_len2 + 1);
if (scope_name) {
memcpy(scope_name, qn, prefix_len2);
scope_name[prefix_len2] = '\0';
- const CBMType* default_type = c_resolve_template_param(ctx, scope_name);
+ const CBMType *default_type = c_resolve_template_param(ctx, scope_name);
if (default_type) {
default_type = c_simplify_type(ctx, default_type, false);
- const char* default_qn = type_to_qn(default_type);
+ const char *default_qn = type_to_qn(default_type);
if (default_qn) {
// Try as method: DefaultType::member
- const char* member = dot + 1;
- const CBMRegisteredFunc* mf = cbm_registry_lookup_method(
- ctx->registry, default_qn, member);
- if (mf && mf->signature) return mf->signature;
+ const char *member = dot + 1;
+ const CBMRegisteredFunc *mf =
+ cbm_registry_lookup_method(ctx->registry, default_qn, member);
+ if (mf && mf->signature)
+ return mf->signature;
// Try as static function
- const char* dep_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- default_qn, member);
- const CBMRegisteredFunc* sf = cbm_registry_lookup_func(
- ctx->registry, dep_qn);
- if (sf && sf->signature) return sf->signature;
+ const char *dep_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", default_qn, member);
+ const CBMRegisteredFunc *sf =
+ cbm_registry_lookup_func(ctx->registry, dep_qn);
+ if (sf && sf->signature)
+ return sf->signature;
}
}
}
@@ -1547,46 +1706,51 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "template_function") == 0) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
TSNode args_node = ts_node_child_by_field_name(node, "arguments", 9);
- if (ts_node_is_null(name_node)) return cbm_type_unknown();
+ if (ts_node_is_null(name_node))
+ return cbm_type_unknown();
- char* name = c_node_text(ctx, name_node);
- if (!name) return cbm_type_unknown();
+ char *name = c_node_text(ctx, name_node);
+ if (!name)
+ return cbm_type_unknown();
// Look up the function — handle both simple and qualified names
- const CBMRegisteredFunc* f = NULL;
- const char* nk = ts_node_type(name_node);
+ const CBMRegisteredFunc *f = NULL;
+ const char *nk = ts_node_type(name_node);
if (strcmp(nk, "qualified_identifier") == 0 || strcmp(nk, "scoped_identifier") == 0) {
// Qualified: std::make_shared → std.make_shared
- const char* qn = c_build_qn(ctx, name);
+ const char *qn = c_build_qn(ctx, name);
f = cbm_registry_lookup_func(ctx->registry, qn);
if (!f && ctx->module_qn) {
- const char* mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn);
+ const char *mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn);
f = cbm_registry_lookup_func(ctx->registry, mod_qn);
}
} else {
- const char* fqn = c_resolve_name(ctx, name);
- if (fqn) f = cbm_registry_lookup_func(ctx->registry, fqn);
+ const char *fqn = c_resolve_name(ctx, name);
+ if (fqn)
+ f = cbm_registry_lookup_func(ctx->registry, fqn);
}
- if (!f || !f->signature) return cbm_type_unknown();
+ if (!f || !f->signature)
+ return cbm_type_unknown();
// Get the base return type from the function signature
- const CBMType* base_ret = NULL;
- if (f->signature->kind == CBM_TYPE_FUNC &&
- f->signature->data.func.return_types &&
+ const CBMType *base_ret = NULL;
+ if (f->signature->kind == CBM_TYPE_FUNC && f->signature->data.func.return_types &&
f->signature->data.func.return_types[0]) {
base_ret = f->signature->data.func.return_types[0];
}
- if (!base_ret) return f->signature;
+ if (!base_ret)
+ return f->signature;
// Parse explicit template arguments from <...>
- const CBMType* targs[16];
+ const CBMType *targs[16];
int targ_count = 0;
if (!ts_node_is_null(args_node)) {
uint32_t nc = ts_node_named_child_count(args_node);
for (uint32_t i = 0; i < nc && targ_count < 15; i++) {
TSNode arg = ts_node_named_child(args_node, i);
- if (ts_node_is_null(arg)) continue;
- const char* ak = ts_node_type(arg);
+ if (ts_node_is_null(arg))
+ continue;
+ const char *ak = ts_node_type(arg);
if (strcmp(ak, "type_descriptor") == 0) {
if (ts_node_named_child_count(arg) > 0)
targs[targ_count++] = c_parse_type_node(ctx, ts_node_named_child(arg, 0));
@@ -1598,19 +1762,19 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Substitute explicit template args into return type
if (targ_count > 0) {
- const char** tpn = f->type_param_names;
+ const char **tpn = f->type_param_names;
if (tpn) {
// Use registered type param names (e.g., ["T", NULL])
base_ret = cbm_type_substitute(ctx->arena, base_ret, tpn, targs);
} else {
// Fallback: positional T, U, V
- const char* fallback_names[] = {"T", "U", "V", "W", NULL};
+ const char *fallback_names[] = {"T", "U", "V", "W", NULL};
base_ret = cbm_type_substitute(ctx->arena, base_ret, fallback_names, targs);
}
}
// Wrap return type in FUNC signature
- const CBMType** rets = cbm_arena_alloc(ctx->arena, 2 * sizeof(CBMType*));
+ const CBMType **rets = cbm_arena_alloc(ctx->arena, 2 * sizeof(CBMType *));
rets[0] = base_ret;
rets[1] = NULL;
return cbm_type_func(ctx->arena, NULL, NULL, rets);
@@ -1619,18 +1783,20 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- call_expression: f(args) ---
if (strcmp(kind, "call_expression") == 0) {
TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
- if (ts_node_is_null(func_node)) return cbm_type_unknown();
+ if (ts_node_is_null(func_node))
+ return cbm_type_unknown();
// Special-case std::move/std::forward: return operand's type (rvalue ref)
{
- const char* fk = ts_node_type(func_node);
- char* fname = NULL;
+ const char *fk = ts_node_type(func_node);
+ char *fname = NULL;
if (strcmp(fk, "qualified_identifier") == 0 || strcmp(fk, "scoped_identifier") == 0 ||
strcmp(fk, "identifier") == 0) {
fname = c_node_text(ctx, func_node);
} else if (strcmp(fk, "template_function") == 0) {
TSNode name_node = ts_node_child_by_field_name(func_node, "name", 4);
- if (!ts_node_is_null(name_node)) fname = c_node_text(ctx, name_node);
+ if (!ts_node_is_null(name_node))
+ fname = c_node_text(ctx, name_node);
}
if (fname && (strcmp(fname, "std::move") == 0 || strcmp(fname, "move") == 0 ||
strcmp(fname, "std::forward") == 0 || strcmp(fname, "forward") == 0)) {
@@ -1638,31 +1804,30 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (!ts_node_is_null(call_args) && ts_node_named_child_count(call_args) > 0) {
TSNode first_arg = ts_node_named_child(call_args, 0);
if (!ts_node_is_null(first_arg)) {
- const CBMType* arg_type = c_eval_expr_type(ctx, first_arg);
+ const CBMType *arg_type = c_eval_expr_type(ctx, first_arg);
// Unwrap to base type — move/forward preserves the type
arg_type = c_simplify_type(ctx, arg_type, false);
- if (!cbm_type_is_unknown(arg_type)) return arg_type;
+ if (!cbm_type_is_unknown(arg_type))
+ return arg_type;
}
}
}
}
- const CBMType* func_type = c_eval_expr_type(ctx, func_node);
- if (!func_type) return cbm_type_unknown();
+ const CBMType *func_type = c_eval_expr_type(ctx, func_node);
+ if (!func_type)
+ return cbm_type_unknown();
// FUNC type -> return its return type
- if (func_type->kind == CBM_TYPE_FUNC &&
- func_type->data.func.return_types && func_type->data.func.return_types[0]) {
- const CBMType* ret = func_type->data.func.return_types[0];
+ if (func_type->kind == CBM_TYPE_FUNC && func_type->data.func.return_types &&
+ func_type->data.func.return_types[0]) {
+ const CBMType *ret = func_type->data.func.return_types[0];
// Template param substitution: try receiver's template args (method calls)
// then try TAD from call-site argument types (free function calls)
- bool needs_subst = (ret->kind == CBM_TYPE_TYPE_PARAM ||
- ret->kind == CBM_TYPE_NAMED ||
- ret->kind == CBM_TYPE_POINTER ||
- ret->kind == CBM_TYPE_REFERENCE ||
+ bool needs_subst = (ret->kind == CBM_TYPE_TYPE_PARAM || ret->kind == CBM_TYPE_NAMED ||
+ ret->kind == CBM_TYPE_POINTER || ret->kind == CBM_TYPE_REFERENCE ||
ret->kind == CBM_TYPE_RVALUE_REF ||
- ret->kind == CBM_TYPE_TEMPLATE ||
- ret->kind == CBM_TYPE_SLICE);
+ ret->kind == CBM_TYPE_TEMPLATE || ret->kind == CBM_TYPE_SLICE);
if (needs_subst) {
bool substituted = false;
@@ -1671,7 +1836,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (strcmp(ts_node_type(func_node), "field_expression") == 0) {
TSNode arg_node = ts_node_child_by_field_name(func_node, "argument", 8);
if (!ts_node_is_null(arg_node)) {
- const CBMType* obj_type = c_eval_expr_type(ctx, arg_node);
+ const CBMType *obj_type = c_eval_expr_type(ctx, arg_node);
// Use false to preserve TEMPLATE type — we need template args
// for substitution, not the pointed-to type from operator->
obj_type = c_simplify_type(ctx, obj_type, false);
@@ -1679,39 +1844,50 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
obj_type->data.template_type.template_args) {
// Use registered type_param_names if available
TSNode field_node = ts_node_child_by_field_name(func_node, "field", 5);
- char* method_name = !ts_node_is_null(field_node) ?
- c_node_text(ctx, field_node) : NULL;
- const char* recv_qn = type_to_qn(obj_type);
- const CBMRegisteredFunc* mf = (recv_qn && method_name) ?
- c_lookup_member(ctx, recv_qn, method_name) : NULL;
- const char** tpn = mf ? mf->type_param_names : NULL;
+ char *method_name =
+ !ts_node_is_null(field_node) ? c_node_text(ctx, field_node) : NULL;
+ const char *recv_qn = type_to_qn(obj_type);
+ const CBMRegisteredFunc *mf =
+ (recv_qn && method_name)
+ ? c_lookup_member(ctx, recv_qn, method_name)
+ : NULL;
+ const char **tpn = mf ? mf->type_param_names : NULL;
// Try class template param names from registered type
if (!tpn && recv_qn) {
- const CBMRegisteredType* rrt = cbm_registry_lookup_type(ctx->registry, recv_qn);
+ const CBMRegisteredType *rrt =
+ cbm_registry_lookup_type(ctx->registry, recv_qn);
if (!rrt && ctx->module_qn) {
- rrt = cbm_registry_lookup_type(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, recv_qn));
+ rrt = cbm_registry_lookup_type(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s",
+ ctx->module_qn, recv_qn));
}
- if (rrt && rrt->type_param_names) tpn = rrt->type_param_names;
+ if (rrt && rrt->type_param_names)
+ tpn = rrt->type_param_names;
}
// Build substitution from receiver template args
int nargs = obj_type->data.template_type.arg_count;
if (tpn) {
// Use actual type param names from class/function registration
- ret = cbm_type_substitute(ctx->arena, ret, tpn,
- obj_type->data.template_type.template_args);
+ ret =
+ cbm_type_substitute(ctx->arena, ret, tpn,
+ obj_type->data.template_type.template_args);
substituted = true;
} else {
// Fallback: positional params T, K, V, T1, T2
- const char* params[] = {"T", "K", "V", "T1", "T2", NULL};
- const CBMType* pargs[5] = {NULL};
- if (nargs > 0) pargs[0] = obj_type->data.template_type.template_args[0];
- if (nargs > 0) pargs[1] = obj_type->data.template_type.template_args[0];
- if (nargs > 1) pargs[2] = obj_type->data.template_type.template_args[1];
- if (nargs > 0) pargs[3] = obj_type->data.template_type.template_args[0];
- if (nargs > 1) pargs[4] = obj_type->data.template_type.template_args[1];
+ const char *params[] = {"T", "K", "V", "T1", "T2", NULL};
+ const CBMType *pargs[5] = {NULL};
+ if (nargs > 0)
+ pargs[0] = obj_type->data.template_type.template_args[0];
+ if (nargs > 0)
+ pargs[1] = obj_type->data.template_type.template_args[0];
+ if (nargs > 1)
+ pargs[2] = obj_type->data.template_type.template_args[1];
+ if (nargs > 0)
+ pargs[3] = obj_type->data.template_type.template_args[0];
+ if (nargs > 1)
+ pargs[4] = obj_type->data.template_type.template_args[1];
ret = cbm_type_substitute(ctx->arena, ret, params, pargs);
substituted = true;
}
@@ -1722,39 +1898,41 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Strategy 2: TAD — deduce template params from call-site argument types
if (!substituted) {
// Find the registered function to get its type_param_names and param_types
- const CBMRegisteredFunc* rf = NULL;
- const char* fn_type = ts_node_type(func_node);
+ const CBMRegisteredFunc *rf = NULL;
+ const char *fn_type = ts_node_type(func_node);
if (strcmp(fn_type, "identifier") == 0) {
- char* fname = c_node_text(ctx, func_node);
+ char *fname = c_node_text(ctx, func_node);
if (fname) {
- const char* fqn = c_resolve_name(ctx, fname);
- if (fqn) rf = cbm_registry_lookup_func(ctx->registry, fqn);
+ const char *fqn = c_resolve_name(ctx, fname);
+ if (fqn)
+ rf = cbm_registry_lookup_func(ctx->registry, fqn);
}
} else if (strcmp(fn_type, "qualified_identifier") == 0 ||
strcmp(fn_type, "scoped_identifier") == 0) {
- char* fname = c_node_text(ctx, func_node);
+ char *fname = c_node_text(ctx, func_node);
if (fname) {
- const char* qn = c_build_qn(ctx, fname);
+ const char *qn = c_build_qn(ctx, fname);
rf = cbm_registry_lookup_func(ctx->registry, qn);
}
} else if (strcmp(fn_type, "template_function") == 0) {
TSNode name_node = ts_node_child_by_field_name(func_node, "name", 4);
if (!ts_node_is_null(name_node)) {
- char* fname = c_node_text(ctx, name_node);
+ char *fname = c_node_text(ctx, name_node);
if (fname) {
- const char* nk = ts_node_type(name_node);
+ const char *nk = ts_node_type(name_node);
if (strcmp(nk, "qualified_identifier") == 0 ||
strcmp(nk, "scoped_identifier") == 0) {
- const char* qn = c_build_qn(ctx, fname);
+ const char *qn = c_build_qn(ctx, fname);
rf = cbm_registry_lookup_func(ctx->registry, qn);
if (!rf && ctx->module_qn) {
- rf = cbm_registry_lookup_func(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->module_qn, qn));
+ rf = cbm_registry_lookup_func(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s",
+ ctx->module_qn, qn));
}
} else {
- const char* fqn = c_resolve_name(ctx, fname);
- if (fqn) rf = cbm_registry_lookup_func(ctx->registry, fqn);
+ const char *fqn = c_resolve_name(ctx, fname);
+ if (fqn)
+ rf = cbm_registry_lookup_func(ctx->registry, fqn);
}
}
}
@@ -1766,39 +1944,53 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Deduce: match call-site arg types against param types
// to bind type_param_names
int tp_count = 0;
- while (rf->type_param_names[tp_count]) tp_count++;
+ while (rf->type_param_names[tp_count])
+ tp_count++;
if (tp_count > 0 && tp_count <= 8) {
- const CBMType* deduced[8] = {NULL};
+ const CBMType *deduced[8] = {NULL};
TSNode call_args = ts_node_child_by_field_name(node, "arguments", 9);
int pi = 0;
if (!ts_node_is_null(call_args)) {
uint32_t anc = ts_node_named_child_count(call_args);
- for (uint32_t ai = 0; ai < anc && rf->signature->data.func.param_types[pi]; ai++) {
+ for (uint32_t ai = 0;
+ ai < anc && rf->signature->data.func.param_types[pi]; ai++) {
TSNode carg = ts_node_named_child(call_args, ai);
- if (ts_node_is_null(carg)) continue;
- const CBMType* arg_t = c_eval_expr_type(ctx, carg);
- if (cbm_type_is_unknown(arg_t)) { pi++; continue; }
+ if (ts_node_is_null(carg))
+ continue;
+ const CBMType *arg_t = c_eval_expr_type(ctx, carg);
+ if (cbm_type_is_unknown(arg_t)) {
+ pi++;
+ continue;
+ }
// Unwrap ref/ptr from param type
- const CBMType* param_t = rf->signature->data.func.param_types[pi];
+ const CBMType *param_t =
+ rf->signature->data.func.param_types[pi];
while (param_t && (param_t->kind == CBM_TYPE_REFERENCE ||
param_t->kind == CBM_TYPE_RVALUE_REF ||
param_t->kind == CBM_TYPE_POINTER)) {
- if (param_t->kind == CBM_TYPE_POINTER) param_t = param_t->data.pointer.elem;
- else param_t = param_t->data.reference.elem;
+ if (param_t->kind == CBM_TYPE_POINTER)
+ param_t = param_t->data.pointer.elem;
+ else
+ param_t = param_t->data.reference.elem;
}
// If param type is TYPE_PARAM, bind it
if (param_t && param_t->kind == CBM_TYPE_TYPE_PARAM) {
for (int ti = 0; ti < tp_count; ti++) {
- if (strcmp(rf->type_param_names[ti], param_t->data.type_param.name) == 0) {
+ if (strcmp(rf->type_param_names[ti],
+ param_t->data.type_param.name) == 0) {
// Unwrap ref/ptr from actual arg too
- const CBMType* unwrapped = arg_t;
- while (unwrapped && (unwrapped->kind == CBM_TYPE_REFERENCE ||
- unwrapped->kind == CBM_TYPE_RVALUE_REF ||
- unwrapped->kind == CBM_TYPE_POINTER)) {
- if (unwrapped->kind == CBM_TYPE_POINTER) unwrapped = unwrapped->data.pointer.elem;
- else unwrapped = unwrapped->data.reference.elem;
+ const CBMType *unwrapped = arg_t;
+ while (unwrapped &&
+ (unwrapped->kind == CBM_TYPE_REFERENCE ||
+ unwrapped->kind == CBM_TYPE_RVALUE_REF ||
+ unwrapped->kind == CBM_TYPE_POINTER)) {
+ if (unwrapped->kind == CBM_TYPE_POINTER)
+ unwrapped = unwrapped->data.pointer.elem;
+ else
+ unwrapped = unwrapped->data.reference.elem;
}
- if (!deduced[ti]) deduced[ti] = unwrapped;
+ if (!deduced[ti])
+ deduced[ti] = unwrapped;
break;
}
}
@@ -1809,12 +2001,16 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Apply deduced substitutions
bool any_deduced = false;
for (int ti = 0; ti < tp_count; ti++) {
- if (deduced[ti]) { any_deduced = true; break; }
+ if (deduced[ti]) {
+ any_deduced = true;
+ break;
+ }
}
if (any_deduced) {
- const CBMType* substituted_ret = cbm_type_substitute(ctx->arena, ret,
- rf->type_param_names, deduced);
- if (substituted_ret) ret = substituted_ret;
+ const CBMType *substituted_ret = cbm_type_substitute(
+ ctx->arena, ret, rf->type_param_names, deduced);
+ if (substituted_ret)
+ ret = substituted_ret;
}
}
}
@@ -1822,7 +2018,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
// Unwrap references in return type
- if (!ret) return cbm_type_unknown();
+ if (!ret)
+ return cbm_type_unknown();
if (ret->kind == CBM_TYPE_REFERENCE || ret->kind == CBM_TYPE_RVALUE_REF)
ret = ret->data.reference.elem;
return ret;
@@ -1846,7 +2043,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "type_identifier") == 0 || strcmp(ck, "template_type") == 0 ||
strcmp(ck, "scoped_type_identifier") == 0 || strcmp(ck, "primitive_type") == 0) {
return cbm_type_pointer(ctx->arena, c_parse_type_node(ctx, child));
@@ -1863,31 +2060,40 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- subscript_expression: a[i] ---
if (strcmp(kind, "subscript_expression") == 0) {
TSNode arg_node = ts_node_child_by_field_name(node, "argument", 8);
- if (ts_node_is_null(arg_node)) return cbm_type_unknown();
- const CBMType* arr_type = c_eval_expr_type(ctx, arg_node);
- if (!arr_type) return cbm_type_unknown();
+ if (ts_node_is_null(arg_node))
+ return cbm_type_unknown();
+ const CBMType *arr_type = c_eval_expr_type(ctx, arg_node);
+ if (!arr_type)
+ return cbm_type_unknown();
// Array/slice: return element
- if (arr_type->kind == CBM_TYPE_SLICE) return arr_type->data.slice.elem;
- if (arr_type->kind == CBM_TYPE_POINTER) return arr_type->data.pointer.elem;
+ if (arr_type->kind == CBM_TYPE_SLICE)
+ return arr_type->data.slice.elem;
+ if (arr_type->kind == CBM_TYPE_POINTER)
+ return arr_type->data.pointer.elem;
// Template with operator[]: return via method lookup
- const char* qn = type_to_qn(c_simplify_type(ctx, arr_type, false));
+ const char *qn = type_to_qn(c_simplify_type(ctx, arr_type, false));
if (qn) {
- const CBMRegisteredFunc* op = cbm_registry_lookup_method(ctx->registry, qn, "operator[]");
+ const CBMRegisteredFunc *op =
+ cbm_registry_lookup_method(ctx->registry, qn, "operator[]");
if (op && op->signature && op->signature->kind == CBM_TYPE_FUNC &&
op->signature->data.func.return_types && op->signature->data.func.return_types[0]) {
- const CBMType* ret = op->signature->data.func.return_types[0];
- if (ret->kind == CBM_TYPE_REFERENCE) ret = ret->data.reference.elem;
+ const CBMType *ret = op->signature->data.func.return_types[0];
+ if (ret->kind == CBM_TYPE_REFERENCE)
+ ret = ret->data.reference.elem;
// Substitute template params
if (ret->kind == CBM_TYPE_TYPE_PARAM && arr_type->kind == CBM_TYPE_TEMPLATE) {
- const char* params[] = {"T", "K", "V", NULL};
- const CBMType* args[3] = {NULL};
+ const char *params[] = {"T", "K", "V", NULL};
+ const CBMType *args[3] = {NULL};
int nargs = arr_type->data.template_type.arg_count;
- if (nargs > 0) args[0] = arr_type->data.template_type.template_args[0];
- if (nargs > 0) args[1] = arr_type->data.template_type.template_args[0];
- if (nargs > 1) args[2] = arr_type->data.template_type.template_args[1];
+ if (nargs > 0)
+ args[0] = arr_type->data.template_type.template_args[0];
+ if (nargs > 0)
+ args[1] = arr_type->data.template_type.template_args[0];
+ if (nargs > 1)
+ args[2] = arr_type->data.template_type.template_args[1];
ret = cbm_type_substitute(ctx->arena, ret, params, args);
}
return ret;
@@ -1899,7 +2105,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- cast expressions ---
if (strcmp(kind, "cast_expression") == 0) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
- if (!ts_node_is_null(type_node)) return c_parse_type_node(ctx, type_node);
+ if (!ts_node_is_null(type_node))
+ return c_parse_type_node(ctx, type_node);
// Fallback: first named child might be type_descriptor
if (ts_node_named_child_count(node) > 0) {
TSNode first = ts_node_named_child(node, 0);
@@ -1913,7 +2120,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
strcmp(kind, "reinterpret_cast_expression") == 0 ||
strcmp(kind, "const_cast_expression") == 0) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
- if (!ts_node_is_null(type_node)) return c_parse_type_node(ctx, type_node);
+ if (!ts_node_is_null(type_node))
+ return c_parse_type_node(ctx, type_node);
return cbm_type_unknown();
}
@@ -1924,42 +2132,47 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// Try "operand" field name
operand = ts_node_child_by_field_name(node, "operand", 7);
}
- if (ts_node_is_null(operand)) return cbm_type_unknown();
+ if (ts_node_is_null(operand))
+ return cbm_type_unknown();
// Get operator from first non-named child
for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
- if (!op) continue;
+ char *op = c_node_text(ctx, child);
+ if (!op)
+ continue;
if (strcmp(op, "*") == 0) {
- const CBMType* inner = c_eval_expr_type(ctx, operand);
+ const CBMType *inner = c_eval_expr_type(ctx, operand);
inner = c_simplify_type(ctx, inner, false);
// TEMPLATE with operator*(): look up and substitute return type
if (inner && inner->kind == CBM_TYPE_TEMPLATE) {
- const char* tqn = inner->data.template_type.template_name;
- const CBMRegisteredFunc* opf = c_lookup_member(ctx, tqn, "operator*");
+ const char *tqn = inner->data.template_type.template_name;
+ const CBMRegisteredFunc *opf = c_lookup_member(ctx, tqn, "operator*");
if (opf && opf->signature && opf->signature->kind == CBM_TYPE_FUNC &&
opf->signature->data.func.return_types &&
opf->signature->data.func.return_types[0]) {
- const CBMType* ret = opf->signature->data.func.return_types[0];
- const CBMRegisteredType* rt = cbm_registry_lookup_type(
- ctx->registry, tqn);
+ const CBMType *ret = opf->signature->data.func.return_types[0];
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, tqn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, tqn));
}
if (rt && rt->type_param_names) {
- ret = cbm_type_substitute(ctx->arena, ret,
- rt->type_param_names,
- inner->data.template_type.template_args);
+ ret = cbm_type_substitute(ctx->arena, ret, rt->type_param_names,
+ inner->data.template_type.template_args);
} else {
- const char* fb[] = {"T", "K", "V", NULL};
- const CBMType* fa[3] = {NULL};
+ const char *fb[] = {"T", "K", "V", NULL};
+ const CBMType *fa[3] = {NULL};
int na = inner->data.template_type.arg_count;
- if (na > 0) fa[0] = inner->data.template_type.template_args[0];
- if (na > 1) fa[1] = inner->data.template_type.template_args[1];
- if (na > 2) fa[2] = inner->data.template_type.template_args[2];
+ if (na > 0)
+ fa[0] = inner->data.template_type.template_args[0];
+ if (na > 1)
+ fa[1] = inner->data.template_type.template_args[1];
+ if (na > 2)
+ fa[2] = inner->data.template_type.template_args[2];
ret = cbm_type_substitute(ctx->arena, ret, fb, fa);
}
if (ret->kind == CBM_TYPE_REFERENCE)
@@ -1987,39 +2200,43 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- pointer_expression: *p or &x (C tree-sitter uses this instead of unary_expression) ---
if (strcmp(kind, "pointer_expression") == 0) {
TSNode arg = ts_node_child_by_field_name(node, "argument", 8);
- if (ts_node_is_null(arg)) return cbm_type_unknown();
+ if (ts_node_is_null(arg))
+ return cbm_type_unknown();
// Check operator
for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
+ char *op = c_node_text(ctx, child);
if (op && strcmp(op, "*") == 0) {
- const CBMType* inner = c_eval_expr_type(ctx, arg);
+ const CBMType *inner = c_eval_expr_type(ctx, arg);
inner = c_simplify_type(ctx, inner, false);
if (inner && inner->kind == CBM_TYPE_TEMPLATE) {
- const char* tqn = inner->data.template_type.template_name;
- const CBMRegisteredFunc* opf = c_lookup_member(ctx, tqn, "operator*");
+ const char *tqn = inner->data.template_type.template_name;
+ const CBMRegisteredFunc *opf = c_lookup_member(ctx, tqn, "operator*");
if (opf && opf->signature && opf->signature->kind == CBM_TYPE_FUNC &&
opf->signature->data.func.return_types &&
opf->signature->data.func.return_types[0]) {
- const CBMType* ret = opf->signature->data.func.return_types[0];
- const CBMRegisteredType* rt = cbm_registry_lookup_type(
- ctx->registry, tqn);
+ const CBMType *ret = opf->signature->data.func.return_types[0];
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, tqn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, tqn));
}
if (rt && rt->type_param_names) {
- ret = cbm_type_substitute(ctx->arena, ret,
- rt->type_param_names,
- inner->data.template_type.template_args);
+ ret = cbm_type_substitute(ctx->arena, ret, rt->type_param_names,
+ inner->data.template_type.template_args);
} else {
- const char* fb[] = {"T", "K", "V", NULL};
- const CBMType* fa[3] = {NULL};
+ const char *fb[] = {"T", "K", "V", NULL};
+ const CBMType *fa[3] = {NULL};
int na = inner->data.template_type.arg_count;
- if (na > 0) fa[0] = inner->data.template_type.template_args[0];
- if (na > 1) fa[1] = inner->data.template_type.template_args[1];
- if (na > 2) fa[2] = inner->data.template_type.template_args[2];
+ if (na > 0)
+ fa[0] = inner->data.template_type.template_args[0];
+ if (na > 1)
+ fa[1] = inner->data.template_type.template_args[1];
+ if (na > 2)
+ fa[2] = inner->data.template_type.template_args[2];
ret = cbm_type_substitute(ctx->arena, ret, fb, fa);
}
if (ret->kind == CBM_TYPE_REFERENCE)
@@ -2029,7 +2246,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
return cbm_type_deref(inner);
}
- if (op && strcmp(op, "&") == 0) return cbm_type_pointer(ctx->arena, c_eval_expr_type(ctx, arg));
+ if (op && strcmp(op, "&") == 0)
+ return cbm_type_pointer(ctx->arena, c_eval_expr_type(ctx, arg));
break;
}
}
@@ -2039,7 +2257,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- update_expression: ++i, i++ ---
if (strcmp(kind, "update_expression") == 0) {
TSNode operand = ts_node_child_by_field_name(node, "argument", 8);
- if (!ts_node_is_null(operand)) return c_eval_expr_type(ctx, operand);
+ if (!ts_node_is_null(operand))
+ return c_eval_expr_type(ctx, operand);
return cbm_type_unknown();
}
@@ -2050,24 +2269,25 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
- if (op && (strcmp(op, "==") == 0 || strcmp(op, "!=") == 0 ||
- strcmp(op, "<") == 0 || strcmp(op, ">") == 0 ||
- strcmp(op, "<=") == 0 || strcmp(op, ">=") == 0 ||
+ char *op = c_node_text(ctx, child);
+ if (op && (strcmp(op, "==") == 0 || strcmp(op, "!=") == 0 || strcmp(op, "<") == 0 ||
+ strcmp(op, ">") == 0 || strcmp(op, "<=") == 0 || strcmp(op, ">=") == 0 ||
strcmp(op, "&&") == 0 || strcmp(op, "||") == 0)) {
return cbm_type_builtin(ctx->arena, "bool");
}
break;
}
}
- if (!ts_node_is_null(left)) return c_eval_expr_type(ctx, left);
+ if (!ts_node_is_null(left))
+ return c_eval_expr_type(ctx, left);
return cbm_type_unknown();
}
// --- conditional_expression: a ? b : c ---
if (strcmp(kind, "conditional_expression") == 0) {
TSNode consequence = ts_node_child_by_field_name(node, "consequence", 11);
- if (!ts_node_is_null(consequence)) return c_eval_expr_type(ctx, consequence);
+ if (!ts_node_is_null(consequence))
+ return c_eval_expr_type(ctx, consequence);
return cbm_type_unknown();
}
@@ -2079,7 +2299,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- comma_expression ---
if (strcmp(kind, "comma_expression") == 0) {
TSNode right = ts_node_child_by_field_name(node, "right", 5);
- if (!ts_node_is_null(right)) return c_eval_expr_type(ctx, right);
+ if (!ts_node_is_null(right))
+ return c_eval_expr_type(ctx, right);
return cbm_type_unknown();
}
@@ -2090,7 +2311,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- lambda_expression ---
if (strcmp(kind, "lambda_expression") == 0) {
- const CBMType* ret_type = NULL;
+ const CBMType *ret_type = NULL;
// Phase A: trailing return type on declarator (e.g., [](int x) -> Widget { ... })
TSNode declarator = ts_node_child_by_field_name(node, "declarator", 10);
@@ -2099,8 +2320,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
for (uint32_t di = 0; di < dnc; di++) {
TSNode ch = ts_node_named_child(declarator, di);
if (strcmp(ts_node_type(ch), "trailing_return_type") == 0) {
- TSNode type_desc = ts_node_named_child_count(ch) > 0 ?
- ts_node_named_child(ch, 0) : ch;
+ TSNode type_desc =
+ ts_node_named_child_count(ch) > 0 ? ts_node_named_child(ch, 0) : ch;
ret_type = c_parse_type_node(ctx, type_desc);
break;
}
@@ -2114,8 +2335,9 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
uint32_t bnc = ts_node_named_child_count(body);
for (uint32_t bi = 0; bi < bnc; bi++) {
TSNode stmt = ts_node_named_child(body, bi);
- if (ts_node_is_null(stmt)) continue;
- const char* sk = ts_node_type(stmt);
+ if (ts_node_is_null(stmt))
+ continue;
+ const char *sk = ts_node_type(stmt);
// Skip nested lambdas, loops, etc. — only immediate returns
if (strcmp(sk, "return_statement") == 0) {
if (ts_node_named_child_count(stmt) > 0) {
@@ -2129,7 +2351,8 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
}
if (ret_type && !cbm_type_is_unknown(ret_type)) {
- const CBMType** ret_types = (const CBMType**)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType*));
+ const CBMType **ret_types =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
if (ret_types) {
ret_types[0] = ret_type;
ret_types[1] = NULL;
@@ -2143,7 +2366,7 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "co_await_expression") == 0) {
if (ts_node_named_child_count(node) > 0) {
TSNode operand = ts_node_named_child(node, 0);
- const CBMType* op_type = c_eval_expr_type(ctx, operand);
+ const CBMType *op_type = c_eval_expr_type(ctx, operand);
// co_await returns the result of operator co_await or the awaitable's await_resume
// Heuristic: if operand is a template type (e.g., Task<T>), return first template arg
op_type = c_simplify_type(ctx, op_type, false);
@@ -2152,9 +2375,9 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
return op_type->data.template_type.template_args[0];
}
// Fallback: check for await_resume method
- const char* op_qn = type_to_qn(op_type);
+ const char *op_qn = type_to_qn(op_type);
if (op_qn) {
- const CBMRegisteredFunc* ar = c_lookup_member(ctx, op_qn, "await_resume");
+ const CBMRegisteredFunc *ar = c_lookup_member(ctx, op_qn, "await_resume");
if (ar && ar->signature && ar->signature->kind == CBM_TYPE_FUNC &&
ar->signature->data.func.return_types &&
ar->signature->data.func.return_types[0]) {
@@ -2174,8 +2397,9 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
for (uint32_t fi = 0; fi < fnc; fi++) {
TSNode child = ts_node_named_child(node, fi);
if (!ts_node_is_null(child)) {
- const CBMType* ct = c_eval_expr_type(ctx, child);
- if (!cbm_type_is_unknown(ct)) return ct;
+ const CBMType *ct = c_eval_expr_type(ctx, child);
+ if (!cbm_type_is_unknown(ct))
+ return ct;
}
}
return cbm_type_unknown();
@@ -2199,8 +2423,9 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
uint32_t anc = ts_node_named_child_count(assoc);
if (anc > 0) {
TSNode val = ts_node_named_child(assoc, anc - 1);
- const CBMType* vt = c_eval_expr_type(ctx, val);
- if (!cbm_type_is_unknown(vt)) return vt;
+ const CBMType *vt = c_eval_expr_type(ctx, val);
+ if (!cbm_type_is_unknown(vt))
+ return vt;
}
}
}
@@ -2209,10 +2434,10 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- Literals ---
if (strcmp(kind, "number_literal") == 0) {
- char* text = c_node_text(ctx, node);
+ char *text = c_node_text(ctx, node);
if (text) {
// Check for float suffix or decimal point
- for (const char* p = text; *p; p++) {
+ for (const char *p = text; *p; p++) {
if (*p == '.' || *p == 'f' || *p == 'F' || *p == 'e' || *p == 'E')
return cbm_type_builtin(ctx->arena, "double");
}
@@ -2238,14 +2463,16 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// --- compound_literal_expression: (Type){...} ---
if (strcmp(kind, "compound_literal_expression") == 0) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
- if (!ts_node_is_null(type_node)) return c_parse_type_node(ctx, type_node);
+ if (!ts_node_is_null(type_node))
+ return c_parse_type_node(ctx, type_node);
return cbm_type_unknown();
}
// --- assignment_expression: a = b (returns LHS type) ---
if (strcmp(kind, "assignment_expression") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", 4);
- if (!ts_node_is_null(left)) return c_eval_expr_type(ctx, left);
+ if (!ts_node_is_null(left))
+ return c_eval_expr_type(ctx, left);
return cbm_type_unknown();
}
@@ -2261,56 +2488,63 @@ static const CBMType* c_eval_expr_type_inner(CLSPContext* ctx, TSNode node) {
// c_lookup_member: method/field lookup with base class traversal
// ============================================================================
-static const CBMRegisteredFunc* c_lookup_member_depth(CLSPContext* ctx,
- const char* type_qn, const char* member_name, int depth) {
- if (!type_qn || !member_name) return NULL;
- if (depth > CBM_LSP_MAX_LOOKUP_DEPTH) return NULL;
+static const CBMRegisteredFunc *c_lookup_member_depth(CLSPContext *ctx, const char *type_qn,
+ const char *member_name, int depth) {
+ if (!type_qn || !member_name)
+ return NULL;
+ if (depth > CBM_LSP_MAX_LOOKUP_DEPTH)
+ return NULL;
// Direct method lookup
- const CBMRegisteredFunc* f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name);
- if (f) return f;
+ const CBMRegisteredFunc *f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name);
+ if (f)
+ return f;
// Try module-prefixed QN (e.g., "Container" -> "test.main.Container")
if (ctx->module_qn) {
- const char* prefixed = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn);
+ const char *prefixed = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn);
f = cbm_registry_lookup_method(ctx->registry, prefixed, member_name);
- if (f) return f;
+ if (f)
+ return f;
}
// Scope-based alias: using Vec = std::vector<T>;
// Vec is in scope as ALIAS → follow to underlying type's QN
{
- const CBMType* scoped = cbm_scope_lookup(ctx->current_scope, type_qn);
+ const CBMType *scoped = cbm_scope_lookup(ctx->current_scope, type_qn);
if (scoped && scoped->kind == CBM_TYPE_ALIAS) {
- const CBMType* underlying = cbm_type_resolve_alias(scoped);
+ const CBMType *underlying = cbm_type_resolve_alias(scoped);
if (underlying && !cbm_type_is_unknown(underlying)) {
- const char* alias_target_qn = type_to_qn(underlying);
+ const char *alias_target_qn = type_to_qn(underlying);
if (alias_target_qn) {
f = c_lookup_member_depth(ctx, alias_target_qn, member_name, depth + 1);
- if (f) return f;
+ if (f)
+ return f;
}
}
}
}
// Check registered type for alias and base classes
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, type_qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
+ rt = cbm_registry_lookup_type(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
}
if (rt) {
// Alias chain
if (rt->alias_of) {
f = c_lookup_member_depth(ctx, rt->alias_of, member_name, depth + 1);
- if (f) return f;
+ if (f)
+ return f;
}
// Base classes (embedded_types stores base class QNs)
if (rt->embedded_types) {
for (int i = 0; rt->embedded_types[i]; i++) {
f = c_lookup_member_depth(ctx, rt->embedded_types[i], member_name, depth + 1);
- if (f) return f;
+ if (f)
+ return f;
}
}
}
@@ -2318,27 +2552,32 @@ static const CBMRegisteredFunc* c_lookup_member_depth(CLSPContext* ctx,
return NULL;
}
-const CBMRegisteredFunc* c_lookup_member(CLSPContext* ctx, const char* type_qn, const char* member_name) {
+const CBMRegisteredFunc *c_lookup_member(CLSPContext *ctx, const char *type_qn,
+ const char *member_name) {
return c_lookup_member_depth(ctx, type_qn, member_name, 0);
}
// Field type lookup
-static const CBMType* c_lookup_field_type(CLSPContext* ctx, const char* type_qn,
- const char* field_name, int depth) {
- if (!type_qn || !field_name || depth > 5) return NULL;
+static const CBMType *c_lookup_field_type(CLSPContext *ctx, const char *type_qn,
+ const char *field_name, int depth) {
+ if (!type_qn || !field_name || depth > 5)
+ return NULL;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, type_qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn);
if (!rt && ctx->module_qn) {
- rt = cbm_registry_lookup_type(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
+ rt = cbm_registry_lookup_type(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn));
}
- if (!rt) return NULL;
+ if (!rt)
+ return NULL;
- if (rt->alias_of) return c_lookup_field_type(ctx, rt->alias_of, field_name, depth + 1);
+ if (rt->alias_of)
+ return c_lookup_field_type(ctx, rt->alias_of, field_name, depth + 1);
if (rt->field_names) {
for (int i = 0; rt->field_names[i]; i++) {
- if (strcmp(rt->field_names[i], field_name) == 0 && rt->field_types && rt->field_types[i])
+ if (strcmp(rt->field_names[i], field_name) == 0 && rt->field_types &&
+ rt->field_types[i])
return rt->field_types[i];
}
}
@@ -2346,8 +2585,10 @@ static const CBMType* c_lookup_field_type(CLSPContext* ctx, const char* type_qn,
// Base classes
if (rt->embedded_types) {
for (int i = 0; rt->embedded_types[i]; i++) {
- const CBMType* f = c_lookup_field_type(ctx, rt->embedded_types[i], field_name, depth + 1);
- if (f) return f;
+ const CBMType *f =
+ c_lookup_field_type(ctx, rt->embedded_types[i], field_name, depth + 1);
+ if (f)
+ return f;
}
}
return NULL;
@@ -2358,12 +2599,12 @@ static const CBMType* c_lookup_field_type(CLSPContext* ctx, const char* type_qn,
// ============================================================================
// Parse a declaration to extract type and declarators
-static const CBMType* c_parse_declaration_type(CLSPContext* ctx, TSNode decl_node) {
+static const CBMType *c_parse_declaration_type(CLSPContext *ctx, TSNode decl_node) {
// Look for type node in declaration children
uint32_t nc = ts_node_named_child_count(decl_node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(decl_node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
// Skip declarators and non-type specifiers
if (strcmp(ck, "init_declarator") == 0 || strcmp(ck, "identifier") == 0 ||
@@ -2371,9 +2612,8 @@ static const CBMType* c_parse_declaration_type(CLSPContext* ctx, TSNode decl_nod
strcmp(ck, "array_declarator") == 0 || strcmp(ck, "function_declarator") == 0 ||
strcmp(ck, "storage_class_specifier") == 0 || strcmp(ck, "type_qualifier") == 0 ||
strcmp(ck, "virtual") == 0 || strcmp(ck, "explicit") == 0 ||
- strcmp(ck, "virtual_function_specifier") == 0 ||
- strcmp(ck, "access_specifier") == 0 || strcmp(ck, "friend") == 0 ||
- strcmp(ck, "comment") == 0)
+ strcmp(ck, "virtual_function_specifier") == 0 || strcmp(ck, "access_specifier") == 0 ||
+ strcmp(ck, "friend") == 0 || strcmp(ck, "comment") == 0)
continue;
// Found a type node
@@ -2382,20 +2622,21 @@ static const CBMType* c_parse_declaration_type(CLSPContext* ctx, TSNode decl_nod
return cbm_type_unknown();
}
-void c_process_statement(CLSPContext* ctx, TSNode node) {
- if (ts_node_is_null(node)) return;
- const char* kind = ts_node_type(node);
+void c_process_statement(CLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
// declaration: Type var = expr; or Type var1, var2;
if (strcmp(kind, "declaration") == 0) {
- const CBMType* base_type = c_parse_declaration_type(ctx, node);
+ const CBMType *base_type = c_parse_declaration_type(ctx, node);
bool has_auto = false;
// Check if type is auto/decltype
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "placeholder_type_specifier") == 0 || strcmp(ck, "auto") == 0) {
has_auto = true;
break;
@@ -2409,13 +2650,13 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Process each declarator
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "init_declarator") == 0) {
TSNode decl = ts_node_child_by_field_name(child, "declarator", 10);
TSNode value = ts_node_child_by_field_name(child, "value", 5);
- const CBMType* var_type = base_type;
+ const CBMType *var_type = base_type;
// For auto, infer from initializer
if (has_auto && !ts_node_is_null(value)) {
@@ -2424,8 +2665,8 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Get variable name from declarator
if (!ts_node_is_null(decl)) {
- const char* dk = ts_node_type(decl);
- char* var_name = NULL;
+ const char *dk = ts_node_type(decl);
+ char *var_name = NULL;
if (strcmp(dk, "identifier") == 0) {
var_name = c_node_text(ctx, decl);
@@ -2439,7 +2680,8 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
uint32_t dnc = ts_node_named_child_count(inner);
inner = dnc > 0 ? ts_node_named_child(inner, dnc - 1) : (TSNode){0};
}
- if (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "identifier") == 0)
+ if (!ts_node_is_null(inner) &&
+ strcmp(ts_node_type(inner), "identifier") == 0)
var_name = c_node_text(ctx, inner);
// For auto*, the deduced type already includes pointer depth
// (e.g., auto* w = new Widget() → eval gives Widget*)
@@ -2450,12 +2692,12 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
} else if (strcmp(dk, "reference_declarator") == 0) {
if (ts_node_named_child_count(decl) > 0) {
TSNode inner = ts_node_named_child(decl, 0);
- const char* ik = ts_node_type(inner);
+ const char *ik = ts_node_type(inner);
if (strcmp(ik, "identifier") == 0) {
var_name = c_node_text(ctx, inner);
} else if (strcmp(ik, "structured_binding_declarator") == 0) {
// const auto& [a, b] = expr; — delegate to structured binding
- const CBMType* rhs_type = cbm_type_unknown();
+ const CBMType *rhs_type = cbm_type_unknown();
if (!ts_node_is_null(value)) {
rhs_type = c_eval_expr_type(ctx, value);
rhs_type = c_simplify_type(ctx, rhs_type, false);
@@ -2465,25 +2707,33 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
for (uint32_t bi = 0; bi < bnc; bi++) {
TSNode bn = ts_node_named_child(inner, bi);
if (strcmp(ts_node_type(bn), "identifier") == 0) {
- char* bname = c_node_text(ctx, bn);
- if (!bname) continue;
- const CBMType* elem_type = cbm_type_unknown();
+ char *bname = c_node_text(ctx, bn);
+ if (!bname)
+ continue;
+ const CBMType *elem_type = cbm_type_unknown();
if (rhs_type && rhs_type->kind == CBM_TYPE_TEMPLATE &&
rhs_type->data.template_type.template_args) {
int nta = rhs_type->data.template_type.arg_count;
if (binding_idx < nta)
- elem_type = rhs_type->data.template_type.template_args[binding_idx];
+ elem_type = rhs_type->data.template_type
+ .template_args[binding_idx];
}
- if (cbm_type_is_unknown(elem_type) && rhs_type && rhs_type->kind == CBM_TYPE_SLICE)
+ if (cbm_type_is_unknown(elem_type) && rhs_type &&
+ rhs_type->kind == CBM_TYPE_SLICE)
elem_type = rhs_type->data.slice.elem;
if (cbm_type_is_unknown(elem_type) && rhs_type) {
- const char* rhs_qn = type_to_qn(rhs_type);
- const CBMRegisteredType* rt = rhs_qn ?
- cbm_registry_lookup_type(ctx->registry, rhs_qn) : NULL;
+ const char *rhs_qn = type_to_qn(rhs_type);
+ const CBMRegisteredType *rt =
+ rhs_qn ? cbm_registry_lookup_type(ctx->registry,
+ rhs_qn)
+ : NULL;
if (!rt && rhs_qn && ctx->module_qn)
- rt = cbm_registry_lookup_type(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, rhs_qn));
- if (rt && rt->field_types && rt->field_types[binding_idx])
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
+ cbm_arena_sprintf(ctx->arena, "%s.%s",
+ ctx->module_qn, rhs_qn));
+ if (rt && rt->field_types &&
+ rt->field_types[binding_idx])
elem_type = rt->field_types[binding_idx];
}
cbm_scope_bind(ctx->current_scope, bname, elem_type);
@@ -2498,10 +2748,11 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
var_type = cbm_type_reference(ctx->arena, var_type);
} else if (strcmp(dk, "function_declarator") == 0) {
// Function pointer: int (*fp)(int) = &target_func;
- // Walk into function_declarator → parenthesized_declarator → pointer_declarator → identifier
+ // Walk into function_declarator → parenthesized_declarator →
+ // pointer_declarator → identifier
TSNode inner = ts_node_child_by_field_name(decl, "declarator", 10);
while (!ts_node_is_null(inner)) {
- const char* ik = ts_node_type(inner);
+ const char *ik = ts_node_type(inner);
if (strcmp(ik, "identifier") == 0) {
var_name = c_node_text(ctx, inner);
break;
@@ -2519,14 +2770,15 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
} else if (strcmp(dk, "array_declarator") == 0) {
// Type var[N]; — extract name and wrap in slice
TSNode inner = ts_node_child_by_field_name(decl, "declarator", 10);
- if (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "identifier") == 0) {
+ if (!ts_node_is_null(inner) &&
+ strcmp(ts_node_type(inner), "identifier") == 0) {
var_name = c_node_text(ctx, inner);
}
var_type = cbm_type_slice(ctx->arena, var_type);
} else if (strcmp(dk, "structured_binding_declarator") == 0) {
// auto [a, b] = expr;
// Try to decompose pair/tuple from initializer type
- const CBMType* rhs_type = cbm_type_unknown();
+ const CBMType *rhs_type = cbm_type_unknown();
if (!ts_node_is_null(value)) {
rhs_type = c_eval_expr_type(ctx, value);
rhs_type = c_simplify_type(ctx, rhs_type, false);
@@ -2536,15 +2788,17 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
for (uint32_t bi = 0; bi < bnc; bi++) {
TSNode bn = ts_node_named_child(decl, bi);
if (strcmp(ts_node_type(bn), "identifier") == 0) {
- char* bname = c_node_text(ctx, bn);
- if (!bname) continue;
- const CBMType* elem_type = cbm_type_unknown();
+ char *bname = c_node_text(ctx, bn);
+ if (!bname)
+ continue;
+ const CBMType *elem_type = cbm_type_unknown();
// Decompose std::pair<T1,T2> → first=T1, second=T2
if (rhs_type && rhs_type->kind == CBM_TYPE_TEMPLATE &&
rhs_type->data.template_type.template_args) {
int nta = rhs_type->data.template_type.arg_count;
if (binding_idx < nta) {
- elem_type = rhs_type->data.template_type.template_args[binding_idx];
+ elem_type =
+ rhs_type->data.template_type.template_args[binding_idx];
}
}
// Decompose array (SLICE) → each binding gets element type
@@ -2554,12 +2808,15 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
// Decompose struct fields
if (cbm_type_is_unknown(elem_type) && rhs_type) {
- const char* rhs_qn = type_to_qn(rhs_type);
- const CBMRegisteredType* rt = rhs_qn ?
- cbm_registry_lookup_type(ctx->registry, rhs_qn) : NULL;
+ const char *rhs_qn = type_to_qn(rhs_type);
+ const CBMRegisteredType *rt =
+ rhs_qn ? cbm_registry_lookup_type(ctx->registry, rhs_qn)
+ : NULL;
if (!rt && rhs_qn && ctx->module_qn)
- rt = cbm_registry_lookup_type(ctx->registry,
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, rhs_qn));
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn,
+ rhs_qn));
if (rt && rt->field_types && rt->field_types[binding_idx]) {
elem_type = rt->field_types[binding_idx];
}
@@ -2578,10 +2835,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Accept pointer, func, or named types (typedef function pointers
// like fn_t appear as CBM_TYPE_NAMED, not FUNC/POINTER).
if (var_type && (var_type->kind == CBM_TYPE_FUNC ||
- var_type->kind == CBM_TYPE_POINTER ||
- var_type->kind == CBM_TYPE_NAMED)) {
+ var_type->kind == CBM_TYPE_POINTER ||
+ var_type->kind == CBM_TYPE_NAMED)) {
if (!ts_node_is_null(value)) {
- const char* vk = ts_node_type(value);
+ const char *vk = ts_node_type(value);
// pointer_expression with & operator: &foo
if (strcmp(vk, "pointer_expression") == 0 ||
strcmp(vk, "unary_expression") == 0) {
@@ -2589,9 +2846,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
for (uint32_t vi = 0; vi < vnc; vi++) {
TSNode vch = ts_node_named_child(value, vi);
if (strcmp(ts_node_type(vch), "identifier") == 0) {
- char* target_name = c_node_text(ctx, vch);
+ char *target_name = c_node_text(ctx, vch);
if (target_name) {
- const char* target_qn = c_resolve_name_to_func_qn(ctx, target_name);
+ const char *target_qn =
+ c_resolve_name_to_func_qn(ctx, target_name);
if (target_qn) {
c_add_fp_target(ctx, var_name, target_qn);
}
@@ -2602,9 +2860,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
// Direct identifier: fp = foo (function decays to pointer)
else if (strcmp(vk, "identifier") == 0) {
- char* target_name = c_node_text(ctx, value);
+ char *target_name = c_node_text(ctx, value);
if (target_name) {
- const char* target_qn = c_resolve_name_to_func_qn(ctx, target_name);
+ const char *target_qn =
+ c_resolve_name_to_func_qn(ctx, target_name);
if (target_qn) {
c_add_fp_target(ctx, var_name, target_qn);
}
@@ -2616,11 +2875,12 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Fallback: if RHS is an identifier resolving to a known function,
// track as fp target even when var_type is unknown (typedef func ptrs).
if (!c_lookup_fp_target(ctx, var_name) && !ts_node_is_null(value)) {
- const char* vk = ts_node_type(value);
+ const char *vk = ts_node_type(value);
if (strcmp(vk, "identifier") == 0) {
- char* target_name = c_node_text(ctx, value);
+ char *target_name = c_node_text(ctx, value);
if (target_name) {
- const char* target_qn = c_resolve_name_to_func_qn(ctx, target_name);
+ const char *target_qn =
+ c_resolve_name_to_func_qn(ctx, target_name);
if (target_qn) {
c_add_fp_target(ctx, var_name, target_qn);
}
@@ -2634,13 +2894,14 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// treat the string as an external function name.
if (!c_lookup_fp_target(ctx, var_name) && !ts_node_is_null(value)) {
bool has_cast = false;
- const char* dll_func = c_extract_dll_resolve_name(ctx, value, &has_cast);
+ const char *dll_func =
+ c_extract_dll_resolve_name(ctx, value, &has_cast);
if (dll_func) {
bool is_fp_type = var_type && (var_type->kind == CBM_TYPE_FUNC ||
var_type->kind == CBM_TYPE_POINTER);
if (is_fp_type || has_cast) {
- const char* target_qn = cbm_arena_sprintf(ctx->arena,
- "external.%s", dll_func);
+ const char *target_qn =
+ cbm_arena_sprintf(ctx->arena, "external.%s", dll_func);
c_add_fp_target(ctx, var_name, target_qn);
}
}
@@ -2649,7 +2910,7 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
} else if (strcmp(ck, "identifier") == 0) {
// Bare declaration without initializer: Type var;
- char* var_name = c_node_text(ctx, child);
+ char *var_name = c_node_text(ctx, child);
if (var_name && var_name[0]) {
cbm_scope_bind(ctx->current_scope, var_name, base_type);
}
@@ -2664,9 +2925,9 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
inner = dnc > 0 ? ts_node_named_child(inner, dnc - 1) : (TSNode){0};
}
if (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "identifier") == 0) {
- char* var_name = c_node_text(ctx, inner);
+ char *var_name = c_node_text(ctx, inner);
if (var_name) {
- const CBMType* vt = base_type;
+ const CBMType *vt = base_type;
for (int d = 0; d < ptr_depth; d++)
vt = cbm_type_pointer(ctx->arena, vt);
cbm_scope_bind(ctx->current_scope, var_name, vt);
@@ -2676,10 +2937,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Type var[N]; without initializer
TSNode inner = ts_node_child_by_field_name(child, "declarator", 10);
if (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "identifier") == 0) {
- char* var_name = c_node_text(ctx, inner);
+ char *var_name = c_node_text(ctx, inner);
if (var_name) {
cbm_scope_bind(ctx->current_scope, var_name,
- cbm_type_slice(ctx->arena, base_type));
+ cbm_type_slice(ctx->arena, base_type));
}
}
}
@@ -2689,8 +2950,9 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// using_declaration: using namespace std; or using std::cout;
if (strcmp(kind, "using_declaration") == 0) {
- char* text = c_node_text(ctx, node);
- if (!text) return;
+ char *text = c_node_text(ctx, node);
+ if (!text)
+ return;
// "using namespace XXX;"
if (strstr(text, "namespace")) {
@@ -2698,11 +2960,12 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "identifier") == 0 || strcmp(ck, "qualified_identifier") == 0 ||
strcmp(ck, "scoped_identifier") == 0) {
- char* ns_name = c_node_text(ctx, child);
- if (ns_name) c_add_using_namespace(ctx, c_build_qn(ctx, ns_name));
+ char *ns_name = c_node_text(ctx, child);
+ if (ns_name)
+ c_add_using_namespace(ctx, c_build_qn(ctx, ns_name));
}
}
} else if (strstr(text, "enum")) {
@@ -2710,20 +2973,23 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "identifier") == 0 || strcmp(ck, "qualified_identifier") == 0 ||
strcmp(ck, "scoped_identifier") == 0 || strcmp(ck, "type_identifier") == 0) {
- char* enum_text = c_node_text(ctx, child);
+ char *enum_text = c_node_text(ctx, child);
if (enum_text) {
- const char* enum_qn = c_build_qn(ctx, enum_text);
+ const char *enum_qn = c_build_qn(ctx, enum_text);
// Try to find the enum type in registry, import its members
- const CBMRegisteredType* et = cbm_registry_lookup_type(ctx->registry, enum_qn);
+ const CBMRegisteredType *et =
+ cbm_registry_lookup_type(ctx->registry, enum_qn);
if (!et && ctx->module_qn) {
- enum_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, enum_qn);
+ enum_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, enum_qn);
et = cbm_registry_lookup_type(ctx->registry, enum_qn);
}
if (!et && ctx->current_namespace) {
- enum_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, enum_text);
+ enum_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace,
+ enum_text);
et = cbm_registry_lookup_type(ctx->registry, enum_qn);
}
// Even if enum type not found, add as using namespace for name lookup
@@ -2736,13 +3002,14 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
- if (strcmp(ck, "qualified_identifier") == 0 || strcmp(ck, "scoped_identifier") == 0) {
- char* full_text = c_node_text(ctx, child);
+ const char *ck = ts_node_type(child);
+ if (strcmp(ck, "qualified_identifier") == 0 ||
+ strcmp(ck, "scoped_identifier") == 0) {
+ char *full_text = c_node_text(ctx, child);
if (full_text) {
- const char* qn = c_build_qn(ctx, full_text);
+ const char *qn = c_build_qn(ctx, full_text);
// Extract short name (last component)
- const char* short_name = strrchr(qn, '.');
+ const char *short_name = strrchr(qn, '.');
short_name = short_name ? short_name + 1 : qn;
c_add_using_decl(ctx, short_name, qn);
}
@@ -2757,15 +3024,16 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
if (!ts_node_is_null(name_node) && !ts_node_is_null(type_node)) {
- char* alias_name = c_node_text(ctx, name_node);
- const CBMType* target = c_parse_type_node(ctx, type_node);
+ char *alias_name = c_node_text(ctx, name_node);
+ const CBMType *target = c_parse_type_node(ctx, type_node);
if (alias_name && target) {
// Build alias QN
- const char* alias_qn = ctx->current_namespace ?
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, alias_name) :
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, alias_name);
+ const char *alias_qn =
+ ctx->current_namespace
+ ? cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, alias_name)
+ : cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, alias_name);
cbm_scope_bind(ctx->current_scope, alias_name,
- cbm_type_alias(ctx->arena, alias_qn, target));
+ cbm_type_alias(ctx->arena, alias_qn, target));
}
}
return;
@@ -2775,19 +3043,19 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "type_definition") == 0) {
// Get the type being aliased and the alias name(s).
// Tree-sitter produces: type_definition { type_spec alias_name }
- // For "typedef RealWidget Widget": { type_identifier("RealWidget") type_identifier("Widget") }
- // For "typedef struct Foo Bar": { struct_specifier type_identifier("Bar") }
- // The first type_identifier may be the source type (when no specifier precedes it).
- const CBMType* target = cbm_type_unknown();
+ // For "typedef RealWidget Widget": { type_identifier("RealWidget")
+ // type_identifier("Widget") } For "typedef struct Foo Bar": { struct_specifier
+ // type_identifier("Bar") } The first type_identifier may be the source type (when no
+ // specifier precedes it).
+ const CBMType *target = cbm_type_unknown();
uint32_t nc = ts_node_named_child_count(node);
bool found_type = false;
int first_type_id_idx = -1;
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (!found_type && strcmp(ck, "type_identifier") != 0 &&
- strcmp(ck, "pointer_declarator") != 0 &&
- strcmp(ck, "identifier") != 0) {
+ strcmp(ck, "pointer_declarator") != 0 && strcmp(ck, "identifier") != 0) {
target = c_parse_type_node(ctx, child);
found_type = true;
} else if (!found_type && strcmp(ck, "type_identifier") == 0 && first_type_id_idx < 0) {
@@ -2797,13 +3065,15 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
target = c_parse_type_node(ctx, child);
found_type = true;
} else if (found_type && strcmp(ck, "type_identifier") == 0) {
- char* alias_name = c_node_text(ctx, child);
+ char *alias_name = c_node_text(ctx, child);
if (alias_name) {
- const char* alias_qn = ctx->current_namespace ?
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, alias_name) :
- cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, alias_name);
+ const char *alias_qn =
+ ctx->current_namespace
+ ? cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace,
+ alias_name)
+ : cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, alias_name);
cbm_scope_bind(ctx->current_scope, alias_name,
- cbm_type_alias(ctx->arena, alias_qn, target));
+ cbm_type_alias(ctx->arena, alias_qn, target));
}
}
}
@@ -2823,8 +3093,8 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
}
if (!ts_node_is_null(name_node) && !ts_node_is_null(value_node)) {
- char* alias = c_node_text(ctx, name_node);
- char* target = c_node_text(ctx, value_node);
+ char *alias = c_node_text(ctx, name_node);
+ char *target = c_node_text(ctx, value_node);
if (alias && target) {
c_add_ns_alias(ctx, alias, c_build_qn(ctx, target));
}
@@ -2838,9 +3108,9 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
TSNode right = ts_node_child_by_field_name(node, "right", 5);
- const CBMType* elem_type = cbm_type_unknown();
+ const CBMType *elem_type = cbm_type_unknown();
if (!ts_node_is_null(right)) {
- const CBMType* container_type = c_eval_expr_type(ctx, right);
+ const CBMType *container_type = c_eval_expr_type(ctx, right);
// Deduce element type: container's begin()->operator* or element type
if (container_type) {
if (container_type->kind == CBM_TYPE_SLICE) {
@@ -2848,31 +3118,31 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
} else if (container_type->kind == CBM_TYPE_TEMPLATE &&
container_type->data.template_type.arg_count > 0) {
// Map containers: element is pair<K,V> not just K
- const char* tname = container_type->data.template_type.template_name;
+ const char *tname = container_type->data.template_type.template_name;
if (tname && container_type->data.template_type.arg_count >= 2 &&
(strstr(tname, "map") || strstr(tname, "Map"))) {
- const CBMType* pair_args[3];
+ const CBMType *pair_args[3];
pair_args[0] = container_type->data.template_type.template_args[0];
pair_args[1] = container_type->data.template_type.template_args[1];
pair_args[2] = NULL;
- elem_type = cbm_type_template(ctx->arena, "std.pair",
- pair_args, 2);
+ elem_type = cbm_type_template(ctx->arena, "std.pair", pair_args, 2);
} else {
elem_type = container_type->data.template_type.template_args[0];
}
}
// Iterator protocol fallback: begin() -> iter -> operator*() -> elem
if (cbm_type_is_unknown(elem_type) && container_type->kind == CBM_TYPE_NAMED) {
- const char* cqn = container_type->data.named.qualified_name;
- const CBMRegisteredFunc* begin_fn = c_lookup_member(ctx, cqn, "begin");
+ const char *cqn = container_type->data.named.qualified_name;
+ const CBMRegisteredFunc *begin_fn = c_lookup_member(ctx, cqn, "begin");
if (begin_fn && begin_fn->signature &&
begin_fn->signature->kind == CBM_TYPE_FUNC &&
begin_fn->signature->data.func.return_types &&
begin_fn->signature->data.func.return_types[0]) {
- const CBMType* iter_type = begin_fn->signature->data.func.return_types[0];
- const char* iter_qn = type_to_qn(iter_type);
+ const CBMType *iter_type = begin_fn->signature->data.func.return_types[0];
+ const char *iter_qn = type_to_qn(iter_type);
if (iter_qn) {
- const CBMRegisteredFunc* deref = c_lookup_member(ctx, iter_qn, "operator*");
+ const CBMRegisteredFunc *deref =
+ c_lookup_member(ctx, iter_qn, "operator*");
if (deref && deref->signature &&
deref->signature->kind == CBM_TYPE_FUNC &&
deref->signature->data.func.return_types &&
@@ -2887,7 +3157,7 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// If explicit type, use that
if (!ts_node_is_null(type_node)) {
- const char* tk = ts_node_type(type_node);
+ const char *tk = ts_node_type(type_node);
if (strcmp(tk, "placeholder_type_specifier") != 0 && strcmp(tk, "auto") != 0) {
elem_type = c_parse_type_node(ctx, type_node);
}
@@ -2897,7 +3167,7 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
if (!ts_node_is_null(decl)) {
// Unwrap reference_declarator to get inner declarator
TSNode bind_target = decl;
- const char* dk = ts_node_type(bind_target);
+ const char *dk = ts_node_type(bind_target);
if (strcmp(dk, "reference_declarator") == 0 &&
ts_node_named_child_count(bind_target) > 0) {
bind_target = ts_node_named_child(bind_target, 0);
@@ -2905,8 +3175,9 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
if (strcmp(dk, "identifier") == 0) {
- char* var_name = c_node_text(ctx, bind_target);
- if (var_name) cbm_scope_bind(ctx->current_scope, var_name, elem_type);
+ char *var_name = c_node_text(ctx, bind_target);
+ if (var_name)
+ cbm_scope_bind(ctx->current_scope, var_name, elem_type);
} else if (strcmp(dk, "structured_binding_declarator") == 0) {
// for (auto& [k, v] : container) — decompose elem_type
uint32_t bnc = ts_node_named_child_count(bind_target);
@@ -2914,9 +3185,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
for (uint32_t bi = 0; bi < bnc; bi++) {
TSNode bn = ts_node_named_child(bind_target, bi);
if (strcmp(ts_node_type(bn), "identifier") == 0) {
- char* bname = c_node_text(ctx, bn);
- if (!bname) continue;
- const CBMType* bt = cbm_type_unknown();
+ char *bname = c_node_text(ctx, bn);
+ if (!bname)
+ continue;
+ const CBMType *bt = cbm_type_unknown();
// TEMPLATE decomposition (e.g., pair<K,V>)
if (elem_type && elem_type->kind == CBM_TYPE_TEMPLATE &&
elem_type->data.template_type.template_args &&
@@ -2930,11 +3202,12 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
}
// Struct field decomposition
if (cbm_type_is_unknown(bt) && elem_type) {
- const char* eq = type_to_qn(elem_type);
- const CBMRegisteredType* rt = eq ?
- cbm_registry_lookup_type(ctx->registry, eq) : NULL;
+ const char *eq = type_to_qn(elem_type);
+ const CBMRegisteredType *rt =
+ eq ? cbm_registry_lookup_type(ctx->registry, eq) : NULL;
if (!rt && eq && ctx->module_qn)
- rt = cbm_registry_lookup_type(ctx->registry,
+ rt = cbm_registry_lookup_type(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, eq));
if (rt && rt->field_types && rt->field_types[binding_idx])
bt = rt->field_types[binding_idx];
@@ -2952,28 +3225,32 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "parameter_declaration") == 0) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
TSNode decl = ts_node_child_by_field_name(node, "declarator", 10);
- if (ts_node_is_null(type_node)) return;
+ if (ts_node_is_null(type_node))
+ return;
- const CBMType* param_type = c_parse_type_node(ctx, type_node);
+ const CBMType *param_type = c_parse_type_node(ctx, type_node);
if (!ts_node_is_null(decl)) {
- const char* dk = ts_node_type(decl);
+ const char *dk = ts_node_type(decl);
if (strcmp(dk, "identifier") == 0) {
- char* name = c_node_text(ctx, decl);
- if (name) cbm_scope_bind(ctx->current_scope, name, param_type);
+ char *name = c_node_text(ctx, decl);
+ if (name)
+ cbm_scope_bind(ctx->current_scope, name, param_type);
} else if (strcmp(dk, "pointer_declarator") == 0) {
int ptr_depth = 0;
TSNode inner = decl;
- while (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "pointer_declarator") == 0) {
+ while (!ts_node_is_null(inner) &&
+ strcmp(ts_node_type(inner), "pointer_declarator") == 0) {
ptr_depth++;
uint32_t dnc = ts_node_named_child_count(inner);
inner = dnc > 0 ? ts_node_named_child(inner, dnc - 1) : (TSNode){0};
}
if (!ts_node_is_null(inner) && strcmp(ts_node_type(inner), "identifier") == 0) {
- char* name = c_node_text(ctx, inner);
+ char *name = c_node_text(ctx, inner);
if (name) {
- const CBMType* vt = param_type;
- for (int d = 0; d < ptr_depth; d++) vt = cbm_type_pointer(ctx->arena, vt);
+ const CBMType *vt = param_type;
+ for (int d = 0; d < ptr_depth; d++)
+ vt = cbm_type_pointer(ctx->arena, vt);
cbm_scope_bind(ctx->current_scope, name, vt);
}
}
@@ -2981,9 +3258,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
if (ts_node_named_child_count(decl) > 0) {
TSNode inner = ts_node_named_child(decl, 0);
if (strcmp(ts_node_type(inner), "identifier") == 0) {
- char* name = c_node_text(ctx, inner);
- if (name) cbm_scope_bind(ctx->current_scope, name,
- cbm_type_reference(ctx->arena, param_type));
+ char *name = c_node_text(ctx, inner);
+ if (name)
+ cbm_scope_bind(ctx->current_scope, name,
+ cbm_type_reference(ctx->arena, param_type));
}
}
}
@@ -2996,8 +3274,10 @@ void c_process_statement(CLSPContext* ctx, TSNode node) {
// Emit helpers
// ============================================================================
-static void c_emit_resolved_call(CLSPContext* ctx, const char* callee_qn, const char* strategy, float confidence) {
- if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn) return;
+static void c_emit_resolved_call(CLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence) {
+ if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
+ return;
CBMResolvedCall rc;
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
@@ -3007,8 +3287,9 @@ static void c_emit_resolved_call(CLSPContext* ctx, const char* callee_qn, const
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
-static void c_emit_unresolved_call(CLSPContext* ctx, const char* expr_text, const char* reason) {
- if (!ctx->resolved_calls || !ctx->enclosing_func_qn) return;
+static void c_emit_unresolved_call(CLSPContext *ctx, const char *expr_text, const char *reason) {
+ if (!ctx->resolved_calls || !ctx->enclosing_func_qn)
+ return;
CBMResolvedCall rc;
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
@@ -3022,9 +3303,27 @@ static void c_emit_unresolved_call(CLSPContext* ctx, const char* expr_text, cons
// resolve_calls_in_node: walk AST and resolve calls
// ============================================================================
-static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
- if (ts_node_is_null(node)) return;
- const char* kind = ts_node_type(node);
+static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node);
+
+#define C_LSP_MAX_WALK_DEPTH 512
+
+/* Depth-guarded entry: the AST walk recurses per nesting level and crashed
+ * with a stack overflow on deeply nested real-world C++ (bitcoin, SIGSEGV in
+ * cbm_type_substitute under hundreds of recursive c_resolve_calls_in_node
+ * frames via c_adl_resolve). Past the cap the subtree is skipped — its calls
+ * stay unresolved, which is graceful degradation, not a crash. */
+static void c_resolve_calls_in_node(CLSPContext *ctx, TSNode node) {
+ if (ctx->walk_depth >= C_LSP_MAX_WALK_DEPTH)
+ return;
+ ctx->walk_depth++;
+ c_resolve_calls_in_node_inner(ctx, node);
+ ctx->walk_depth--;
+}
+
+static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
// Process statements for scope building
c_process_statement(ctx, node);
@@ -3033,16 +3332,16 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "call_expression") == 0) {
TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
if (!ts_node_is_null(func_node)) {
- const char* fk = ts_node_type(func_node);
+ const char *fk = ts_node_type(func_node);
// field_expression: obj.method() or ptr->method()
if (strcmp(fk, "field_expression") == 0) {
TSNode arg_node = ts_node_child_by_field_name(func_node, "argument", 8);
TSNode field_node = ts_node_child_by_field_name(func_node, "field", 5);
if (!ts_node_is_null(arg_node) && !ts_node_is_null(field_node)) {
- char* field_name = c_node_text(ctx, field_node);
+ char *field_name = c_node_text(ctx, field_node);
if (field_name) {
- const CBMType* obj_type = c_eval_expr_type(ctx, arg_node);
+ const CBMType *obj_type = c_eval_expr_type(ctx, arg_node);
// Determine if arrow or dot
bool is_arrow = false;
@@ -3050,32 +3349,43 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
for (uint32_t fi = 0; fi < fnc; fi++) {
TSNode ch = ts_node_child(func_node, fi);
if (!ts_node_is_named(ch)) {
- char* op = c_node_text(ctx, ch);
- if (op && strcmp(op, "->") == 0) { is_arrow = true; break; }
+ char *op = c_node_text(ctx, ch);
+ if (op && strcmp(op, "->") == 0) {
+ is_arrow = true;
+ break;
+ }
}
}
- const CBMType* base = is_arrow ?
- c_simplify_type(ctx, obj_type, true) :
- c_simplify_type(ctx, obj_type, false);
+ const CBMType *base = is_arrow ? c_simplify_type(ctx, obj_type, true)
+ : c_simplify_type(ctx, obj_type, false);
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
int arg_count = 0;
- const CBMType** arg_types = c_extract_call_arg_types(ctx, node, &arg_count);
- if (ctx->debug) fprintf(stderr, " [clsp] member call: type_qn=%s field=%s args=%d\n", type_qn, field_name, arg_count);
+ const CBMType **arg_types =
+ c_extract_call_arg_types(ctx, node, &arg_count);
+ if (ctx->debug)
+ fprintf(stderr,
+ " [clsp] member call: type_qn=%s field=%s args=%d\n",
+ type_qn, field_name, arg_count);
// Use type-aware overload scoring
- const CBMRegisteredFunc* method = cbm_registry_lookup_method_by_types(
+ const CBMRegisteredFunc *method = cbm_registry_lookup_method_by_types(
ctx->registry, type_qn, field_name, arg_types, arg_count);
// Fall back to c_lookup_member for base class traversal
- if (!method) method = c_lookup_member(ctx, type_qn, field_name);
- if (ctx->debug) fprintf(stderr, " [clsp] member call result: %s\n", method ? method->qualified_name : "NULL");
+ if (!method)
+ method = c_lookup_member(ctx, type_qn, field_name);
+ if (ctx->debug)
+ fprintf(stderr, " [clsp] member call result: %s\n",
+ method ? method->qualified_name : "NULL");
if (method) {
- const char* strategy = "lsp_type_dispatch";
+ const char *strategy = "lsp_type_dispatch";
// Check if resolved through base class — prefer derived override
- if (method->receiver_type && strcmp(method->receiver_type, type_qn) != 0) {
- const CBMRegisteredFunc* override_m = cbm_registry_lookup_method(
- ctx->registry, type_qn, field_name);
+ if (method->receiver_type &&
+ strcmp(method->receiver_type, type_qn) != 0) {
+ const CBMRegisteredFunc *override_m =
+ cbm_registry_lookup_method(ctx->registry, type_qn,
+ field_name);
if (override_m) {
method = override_m;
strategy = "lsp_virtual_dispatch";
@@ -3093,26 +3403,25 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
}
// TYPE_PARAM receiver: store as pending template call
- if (base && base->kind == CBM_TYPE_TYPE_PARAM &&
- ctx->enclosing_func_qn && ctx->in_template) {
+ if (base && base->kind == CBM_TYPE_TYPE_PARAM && ctx->enclosing_func_qn &&
+ ctx->in_template) {
int ac = 0;
c_extract_call_arg_types(ctx, node, &ac);
- c_add_pending_template_call(ctx,
- ctx->enclosing_func_qn,
- base->data.type_param.name,
- field_name, ac);
+ c_add_pending_template_call(ctx, ctx->enclosing_func_qn,
+ base->data.type_param.name, field_name, ac);
}
// Unresolved
if (cbm_type_is_unknown(obj_type)) {
- char* arg_text = c_node_text(ctx, arg_node);
+ char *arg_text = c_node_text(ctx, arg_node);
c_emit_unresolved_call(ctx,
- cbm_arena_sprintf(ctx->arena, "%s.%s",
- arg_text ? arg_text : "?", field_name),
- "unknown_receiver_type");
+ cbm_arena_sprintf(ctx->arena, "%s.%s",
+ arg_text ? arg_text : "?",
+ field_name),
+ "unknown_receiver_type");
} else if (type_qn) {
- c_emit_unresolved_call(ctx,
- cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, field_name),
+ c_emit_unresolved_call(
+ ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, field_name),
"method_not_found");
}
}
@@ -3122,30 +3431,32 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// qualified_identifier: ns::func() or Class::static_method()
// Also handles ns::func<T>() where name child is template_function
- if (strcmp(fk, "qualified_identifier") == 0 ||
- strcmp(fk, "scoped_identifier") == 0) {
- char* text = c_node_text(ctx, func_node);
+ if (strcmp(fk, "qualified_identifier") == 0 || strcmp(fk, "scoped_identifier") == 0) {
+ char *text = c_node_text(ctx, func_node);
if (text) {
- const char* qn = c_build_qn(ctx, text);
+ const char *qn = c_build_qn(ctx, text);
// Strip template args from last component only:
// std.get<Widget> → std.get, but Registry<int>.init stays unchanged
- const char* angle = strchr(qn, '<');
+ const char *angle = strchr(qn, '<');
if (angle) {
- // Only strip if no '.' follows the '<' (i.e., template is in the last segment)
- const char* dot_after = strchr(angle, '.');
+ // Only strip if no '.' follows the '<' (i.e., template is in the last
+ // segment)
+ const char *dot_after = strchr(angle, '.');
if (!dot_after) {
size_t strip_len = (size_t)(angle - qn);
- char* stripped = (char*)cbm_arena_alloc(ctx->arena, strip_len + 1);
+ char *stripped = (char *)cbm_arena_alloc(ctx->arena, strip_len + 1);
memcpy(stripped, qn, strip_len);
stripped[strip_len] = '\0';
qn = stripped;
} else {
- // Strip <...> segment but keep what follows: Registry<int>.init → Registry.init
- const char* close = strchr(angle, '>');
+ // Strip <...> segment but keep what follows: Registry<int>.init →
+ // Registry.init
+ const char *close = strchr(angle, '>');
if (close && close < dot_after) {
size_t prefix_len = (size_t)(angle - qn);
size_t suffix_len = strlen(dot_after);
- char* stripped = (char*)cbm_arena_alloc(ctx->arena, prefix_len + suffix_len + 1);
+ char *stripped = (char *)cbm_arena_alloc(
+ ctx->arena, prefix_len + suffix_len + 1);
memcpy(stripped, qn, prefix_len);
memcpy(stripped + prefix_len, dot_after, suffix_len);
stripped[prefix_len + suffix_len] = '\0';
@@ -3154,33 +3465,35 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
}
}
int arg_count = 0;
- const CBMType** arg_types = c_extract_call_arg_types(ctx, node, &arg_count);
+ const CBMType **arg_types = c_extract_call_arg_types(ctx, node, &arg_count);
// Module-prefixed first (shadows stdlib stubs), then bare QN
- const CBMRegisteredFunc* f = NULL;
+ const CBMRegisteredFunc *f = NULL;
if (ctx->module_qn) {
- f = cbm_registry_lookup_func(ctx->registry,
+ f = cbm_registry_lookup_func(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn));
}
- if (!f) f = cbm_registry_lookup_func(ctx->registry, qn);
+ if (!f)
+ f = cbm_registry_lookup_func(ctx->registry, qn);
if (f) {
c_emit_resolved_call(ctx, f->qualified_name, "lsp_scoped", 0.95f);
goto recurse;
}
// Try as method (Class::method) with type-aware overload resolution
- const char* dot = strrchr(qn, '.');
+ const char *dot = strrchr(qn, '.');
if (dot) {
size_t prefix_len = dot - qn;
- char* class_qn = (char*)cbm_arena_alloc(ctx->arena, prefix_len + 1);
+ char *class_qn = (char *)cbm_arena_alloc(ctx->arena, prefix_len + 1);
memcpy(class_qn, qn, prefix_len);
class_qn[prefix_len] = '\0';
- const CBMRegisteredFunc* m = cbm_registry_lookup_method_by_types(
+ const CBMRegisteredFunc *m = cbm_registry_lookup_method_by_types(
ctx->registry, class_qn, dot + 1, arg_types, arg_count);
// Try with module prefix
if (!m && ctx->module_qn) {
- const char* mod_class = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->module_qn, class_qn);
- m = cbm_registry_lookup_method_by_types(
- ctx->registry, mod_class, dot + 1, arg_types, arg_count);
+ const char *mod_class =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, class_qn);
+ m = cbm_registry_lookup_method_by_types(ctx->registry, mod_class,
+ dot + 1, arg_types, arg_count);
}
if (m) {
c_emit_resolved_call(ctx, m->qualified_name, "lsp_scoped", 0.95f);
@@ -3190,10 +3503,12 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// Namespace fallback: extract_defs may omit namespace from QN.
// "utils.create_logger" → try "create_logger" and "mod.create_logger"
if (dot && ctx->module_qn) {
- const char* bare_name = dot + 1;
- const CBMRegisteredFunc* nf = cbm_registry_lookup_func(ctx->registry, bare_name);
+ const char *bare_name = dot + 1;
+ const CBMRegisteredFunc *nf =
+ cbm_registry_lookup_func(ctx->registry, bare_name);
if (!nf) {
- nf = cbm_registry_lookup_func(ctx->registry,
+ nf = cbm_registry_lookup_func(
+ ctx->registry,
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, bare_name));
}
if (nf) {
@@ -3210,51 +3525,55 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (strcmp(fk, "template_function") == 0) {
TSNode name_node = ts_node_child_by_field_name(func_node, "name", 4);
if (!ts_node_is_null(name_node)) {
- char* name = c_node_text(ctx, name_node);
+ char *name = c_node_text(ctx, name_node);
if (name) {
- const char* nk = ts_node_type(name_node);
- const CBMRegisteredFunc* f = NULL;
+ const char *nk = ts_node_type(name_node);
+ const CBMRegisteredFunc *f = NULL;
if (strcmp(nk, "qualified_identifier") == 0 ||
strcmp(nk, "scoped_identifier") == 0) {
- const char* qn = c_build_qn(ctx, name);
+ const char *qn = c_build_qn(ctx, name);
f = cbm_registry_lookup_func(ctx->registry, qn);
if (!f && ctx->module_qn) {
- const char* mod_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->module_qn, qn);
+ const char *mod_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, qn);
f = cbm_registry_lookup_func(ctx->registry, mod_qn);
}
// Try as Class::method
if (!f) {
- const char* dot = strrchr(qn, '.');
+ const char *dot = strrchr(qn, '.');
if (dot) {
size_t plen = dot - qn;
- char* cls = (char*)cbm_arena_alloc(ctx->arena, plen + 1);
+ char *cls = (char *)cbm_arena_alloc(ctx->arena, plen + 1);
memcpy(cls, qn, plen);
cls[plen] = '\0';
- const CBMRegisteredFunc* m = cbm_registry_lookup_method(
- ctx->registry, cls, dot + 1);
+ const CBMRegisteredFunc *m =
+ cbm_registry_lookup_method(ctx->registry, cls, dot + 1);
if (!m && ctx->module_qn) {
- const char* mc = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->module_qn, cls);
+ const char *mc = cbm_arena_sprintf(ctx->arena, "%s.%s",
+ ctx->module_qn, cls);
m = cbm_registry_lookup_method(ctx->registry, mc, dot + 1);
}
- if (m) f = m;
+ if (m)
+ f = m;
}
}
} else {
- const char* fqn = c_resolve_name(ctx, name);
- if (fqn) f = cbm_registry_lookup_func(ctx->registry, fqn);
+ const char *fqn = c_resolve_name(ctx, name);
+ if (fqn)
+ f = cbm_registry_lookup_func(ctx->registry, fqn);
}
if (f) {
c_emit_resolved_call(ctx, f->qualified_name, "lsp_template", 0.95f);
// Resolve pending template calls at this call site
if (ctx->pending_tc_count > 0 && f->type_param_names) {
int ac = 0;
- const CBMType** at = c_extract_call_arg_types(ctx, node, &ac);
- if (at) c_resolve_pending_template_calls(ctx, f, at, ac);
+ const CBMType **at = c_extract_call_arg_types(ctx, node, &ac);
+ if (at)
+ c_resolve_pending_template_calls(ctx, f, at, ac);
}
} else {
- c_emit_unresolved_call(ctx, c_build_qn(ctx, name), "template_not_in_registry");
+ c_emit_unresolved_call(ctx, c_build_qn(ctx, name),
+ "template_not_in_registry");
}
}
}
@@ -3263,61 +3582,65 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// Direct identifier call: func()
if (strcmp(fk, "identifier") == 0) {
- char* name = c_node_text(ctx, func_node);
+ char *name = c_node_text(ctx, func_node);
if (name && !is_c_builtin_func(name)) {
// Check function pointer target map FIRST (before scope type check)
// because C function pointer declarators like int (*fp)(int)
// parse as pointer(int) in scope, not as FUNC type.
- const char* fp_target = c_lookup_fp_target(ctx, name);
+ const char *fp_target = c_lookup_fp_target(ctx, name);
if (fp_target) {
// Distinguish DLL/dynamic resolution from static fp targets
bool is_dll = (strncmp(fp_target, "external.", 9) == 0);
c_emit_resolved_call(ctx, fp_target,
- is_dll ? "lsp_dll_resolve" : "lsp_func_ptr",
- is_dll ? 0.80f : 0.85f);
+ is_dll ? "lsp_dll_resolve" : "lsp_func_ptr",
+ is_dll ? 0.80f : 0.85f);
goto recurse;
}
// Check if it's a variable with callable type
- const CBMType* var_type = cbm_scope_lookup(ctx->current_scope, name);
+ const CBMType *var_type = cbm_scope_lookup(ctx->current_scope, name);
if (!cbm_type_is_unknown(var_type)) {
if (var_type->kind == CBM_TYPE_FUNC) {
// Function type variable without tracked target — can't resolve
goto recurse;
}
// Functor call: variable with operator()
- const CBMType* base = c_simplify_type(ctx, var_type, false);
- const char* type_qn = type_to_qn(base);
+ const CBMType *base = c_simplify_type(ctx, var_type, false);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
- const CBMRegisteredFunc* op = c_lookup_member(ctx, type_qn, "operator()");
+ const CBMRegisteredFunc *op =
+ c_lookup_member(ctx, type_qn, "operator()");
if (op) {
- c_emit_resolved_call(ctx, op->qualified_name, "lsp_operator", 0.90f);
+ c_emit_resolved_call(ctx, op->qualified_name, "lsp_operator",
+ 0.90f);
goto recurse;
}
}
}
// Check if it's a type name (constructor call)
- const CBMType* type = c_resolve_name_to_type(ctx, name);
+ const CBMType *type = c_resolve_name_to_type(ctx, name);
if (type && type->kind == CBM_TYPE_NAMED) {
- const char* type_qn_str = type->data.named.qualified_name;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, type_qn_str);
+ const char *type_qn_str = type->data.named.qualified_name;
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, type_qn_str);
if (rt && !rt->is_interface) {
// Constructor call
- const char* ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn_str, name);
+ const char *ctor_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn_str, name);
c_emit_resolved_call(ctx, ctor_qn, "lsp_constructor", 0.95f);
goto recurse;
}
}
// Regular function call
- const char* fqn = c_resolve_name(ctx, name);
+ const char *fqn = c_resolve_name(ctx, name);
if (fqn) {
// Check if this is implicit 'this' call
- const char* strategy = "lsp_direct";
+ const char *strategy = "lsp_direct";
if (ctx->enclosing_class_qn) {
- const CBMRegisteredFunc* m = cbm_registry_lookup_method(ctx->registry,
- ctx->enclosing_class_qn, name);
+ const CBMRegisteredFunc *m = cbm_registry_lookup_method(
+ ctx->registry, ctx->enclosing_class_qn, name);
if (m && strcmp(fqn, m->qualified_name) == 0) {
strategy = "lsp_implicit_this";
}
@@ -3325,16 +3648,18 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
c_emit_resolved_call(ctx, fqn, strategy, 0.95f);
// Resolve pending template calls at this call site
if (ctx->pending_tc_count > 0) {
- const CBMRegisteredFunc* called = cbm_registry_lookup_func(ctx->registry, fqn);
+ const CBMRegisteredFunc *called =
+ cbm_registry_lookup_func(ctx->registry, fqn);
if (called && called->type_param_names) {
int ac = 0;
- const CBMType** at = c_extract_call_arg_types(ctx, node, &ac);
- if (at) c_resolve_pending_template_calls(ctx, called, at, ac);
+ const CBMType **at = c_extract_call_arg_types(ctx, node, &ac);
+ if (at)
+ c_resolve_pending_template_calls(ctx, called, at, ac);
}
}
} else {
// ADL: search namespaces of argument types
- const char* adl_qn = c_adl_resolve(ctx, name, node);
+ const char *adl_qn = c_adl_resolve(ctx, name, node);
if (adl_qn) {
c_emit_resolved_call(ctx, adl_qn, "lsp_adl", 0.90f);
} else {
@@ -3351,14 +3676,14 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (strcmp(kind, "declaration") == 0 && ctx->cpp_mode) {
// Check for Foo x(args) or Foo x{args} patterns
uint32_t nc = ts_node_named_child_count(node);
- const CBMType* decl_type = cbm_type_unknown();
+ const CBMType *decl_type = cbm_type_unknown();
bool has_type = false;
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
- if (!has_type && (strcmp(ck, "type_identifier") == 0 ||
- strcmp(ck, "scoped_type_identifier") == 0 ||
- strcmp(ck, "template_type") == 0)) {
+ const char *ck = ts_node_type(child);
+ if (!has_type &&
+ (strcmp(ck, "type_identifier") == 0 || strcmp(ck, "scoped_type_identifier") == 0 ||
+ strcmp(ck, "template_type") == 0)) {
decl_type = c_parse_type_node(ctx, child);
has_type = true;
}
@@ -3366,15 +3691,17 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// Check if value is argument_list (constructor with parens)
TSNode value = ts_node_child_by_field_name(child, "value", 5);
if (!ts_node_is_null(value)) {
- const char* vk = ts_node_type(value);
+ const char *vk = ts_node_type(value);
if (strcmp(vk, "argument_list") == 0 || strcmp(vk, "initializer_list") == 0) {
- const char* type_qn = type_to_qn(decl_type);
+ const char *type_qn = type_to_qn(decl_type);
if (type_qn) {
- const char* short_name = strrchr(type_qn, '.');
+ const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
- const char* last_colon = strrchr(type_qn, ':');
- if (last_colon) short_name = last_colon + 1;
- const char* ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
+ const char *last_colon = strrchr(type_qn, ':');
+ if (last_colon)
+ short_name = last_colon + 1;
+ const char *ctor_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
c_emit_resolved_call(ctx, ctor_qn, "lsp_constructor", 0.90f);
}
}
@@ -3390,7 +3717,7 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_named_child(node, i);
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "type_identifier") == 0 || strcmp(ck, "template_type") == 0 ||
strcmp(ck, "scoped_type_identifier") == 0) {
type_node = child;
@@ -3399,12 +3726,12 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
}
}
if (!ts_node_is_null(type_node)) {
- const CBMType* t = c_parse_type_node(ctx, type_node);
- const char* type_qn = type_to_qn(t);
+ const CBMType *t = c_parse_type_node(ctx, type_node);
+ const char *type_qn = type_to_qn(t);
if (type_qn) {
- const char* short_name = strrchr(type_qn, '.');
+ const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
- const char* ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
+ const char *ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
c_emit_resolved_call(ctx, ctor_qn, "lsp_constructor", 0.95f);
}
}
@@ -3418,13 +3745,13 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
operand = ts_node_named_child(node, 0);
}
if (!ts_node_is_null(operand)) {
- const CBMType* ptr_type = c_eval_expr_type(ctx, operand);
- const CBMType* base = c_simplify_type(ctx, ptr_type, true);
- const char* type_qn = type_to_qn(base);
+ const CBMType *ptr_type = c_eval_expr_type(ctx, operand);
+ const CBMType *base = c_simplify_type(ctx, ptr_type, true);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
- const char* short_name = strrchr(type_qn, '.');
+ const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
- const char* dtor_qn = cbm_arena_sprintf(ctx->arena, "%s.~%s", type_qn, short_name);
+ const char *dtor_qn = cbm_arena_sprintf(ctx->arena, "%s.~%s", type_qn, short_name);
c_emit_resolved_call(ctx, dtor_qn, "lsp_destructor", 0.90f);
}
}
@@ -3434,21 +3761,23 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (ctx->cpp_mode && strcmp(kind, "binary_expression") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", 4);
if (!ts_node_is_null(left)) {
- const CBMType* lhs_type = c_eval_expr_type(ctx, left);
- const CBMType* base = c_simplify_type(ctx, lhs_type, false);
+ const CBMType *lhs_type = c_eval_expr_type(ctx, left);
+ const CBMType *base = c_simplify_type(ctx, lhs_type, false);
if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
// Extract operator
for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
+ char *op = c_node_text(ctx, child);
if (op) {
- const char* op_name = cbm_arena_sprintf(ctx->arena, "operator%s", op);
- const CBMRegisteredFunc* m = c_lookup_member(ctx, type_qn, op_name);
+ const char *op_name =
+ cbm_arena_sprintf(ctx->arena, "operator%s", op);
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
+ c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator",
+ 0.90f);
}
}
break;
@@ -3463,22 +3792,24 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (ctx->cpp_mode && strcmp(kind, "assignment_expression") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", 4);
if (!ts_node_is_null(left)) {
- const CBMType* lhs_type = c_eval_expr_type(ctx, left);
- const CBMType* base = c_simplify_type(ctx, lhs_type, false);
+ const CBMType *lhs_type = c_eval_expr_type(ctx, left);
+ const CBMType *base = c_simplify_type(ctx, lhs_type, false);
if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
// Extract operator (+=, -=, *=, /=, etc.)
for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
TSNode child = ts_node_child(node, i);
if (!ts_node_is_named(child)) {
- char* op = c_node_text(ctx, child);
- if (op && strlen(op) >= 2 && op[strlen(op)-1] == '=') {
+ char *op = c_node_text(ctx, child);
+ if (op && strlen(op) >= 2 && op[strlen(op) - 1] == '=') {
// Compound assignment: +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=
- const char* op_name = cbm_arena_sprintf(ctx->arena, "operator%s", op);
- const CBMRegisteredFunc* m = c_lookup_member(ctx, type_qn, op_name);
+ const char *op_name =
+ cbm_arena_sprintf(ctx->arena, "operator%s", op);
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
+ c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator",
+ 0.90f);
}
}
break;
@@ -3493,13 +3824,13 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (ctx->cpp_mode && strcmp(kind, "subscript_expression") == 0) {
TSNode arg_node = ts_node_child_by_field_name(node, "argument", 8);
if (!ts_node_is_null(arg_node)) {
- const CBMType* arr_type = c_eval_expr_type(ctx, arg_node);
- const CBMType* base = c_simplify_type(ctx, arr_type, false);
+ const CBMType *arr_type = c_eval_expr_type(ctx, arg_node);
+ const CBMType *base = c_simplify_type(ctx, arr_type, false);
if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base) &&
base->kind != CBM_TYPE_POINTER && base->kind != CBM_TYPE_SLICE) {
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
- const CBMRegisteredFunc* m = c_lookup_member(ctx, type_qn, "operator[]");
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, "operator[]");
if (m) {
c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
}
@@ -3508,36 +3839,42 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
}
}
- // --- unary_expression/pointer_expression: operator* / operator++ / operator-- on custom types ---
- if (ctx->cpp_mode && (strcmp(kind, "unary_expression") == 0 ||
- strcmp(kind, "pointer_expression") == 0 ||
- strcmp(kind, "update_expression") == 0)) {
+ // --- unary_expression/pointer_expression: operator* / operator++ / operator-- on custom types
+ // ---
+ if (ctx->cpp_mode &&
+ (strcmp(kind, "unary_expression") == 0 || strcmp(kind, "pointer_expression") == 0 ||
+ strcmp(kind, "update_expression") == 0)) {
TSNode operand = ts_node_child_by_field_name(node, "argument", 8);
if (ts_node_is_null(operand))
operand = ts_node_child_by_field_name(node, "operand", 7);
if (!ts_node_is_null(operand)) {
- const CBMType* op_type = c_eval_expr_type(ctx, operand);
- const CBMType* base = c_simplify_type(ctx, op_type, false);
+ const CBMType *op_type = c_eval_expr_type(ctx, operand);
+ const CBMType *base = c_simplify_type(ctx, op_type, false);
if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base) &&
base->kind != CBM_TYPE_POINTER) {
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
// Determine which operator
- const char* op_name = NULL;
+ const char *op_name = NULL;
for (uint32_t ui = 0; ui < ts_node_child_count(node); ui++) {
TSNode ch = ts_node_child(node, ui);
if (!ts_node_is_named(ch)) {
- char* op = c_node_text(ctx, ch);
- if (!op) continue;
- if (strcmp(op, "*") == 0) op_name = "operator*";
- else if (strcmp(op, "++") == 0) op_name = "operator++";
- else if (strcmp(op, "--") == 0) op_name = "operator--";
- else if (strcmp(op, "!") == 0) op_name = "operator!";
+ char *op = c_node_text(ctx, ch);
+ if (!op)
+ continue;
+ if (strcmp(op, "*") == 0)
+ op_name = "operator*";
+ else if (strcmp(op, "++") == 0)
+ op_name = "operator++";
+ else if (strcmp(op, "--") == 0)
+ op_name = "operator--";
+ else if (strcmp(op, "!") == 0)
+ op_name = "operator!";
break;
}
}
if (op_name) {
- const CBMRegisteredFunc* m = c_lookup_member(ctx, type_qn, op_name);
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
if (m) {
c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
}
@@ -3549,7 +3886,7 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// --- Copy/move constructor: Foo a = expr; where expr has Foo type ---
if (ctx->cpp_mode && strcmp(kind, "declaration") == 0) {
- const CBMType* decl_type = c_parse_declaration_type(ctx, node);
+ const CBMType *decl_type = c_parse_declaration_type(ctx, node);
if (decl_type && decl_type->kind == CBM_TYPE_NAMED) {
uint32_t dnc = ts_node_named_child_count(node);
for (uint32_t di = 0; di < dnc; di++) {
@@ -3557,19 +3894,21 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
if (strcmp(ts_node_type(dchild), "init_declarator") == 0) {
TSNode val = ts_node_child_by_field_name(dchild, "value", 5);
if (!ts_node_is_null(val)) {
- const char* vk = ts_node_type(val);
+ const char *vk = ts_node_type(val);
// Skip if it's argument_list (already handled as constructor above)
// or initializer_list (also handled)
- if (strcmp(vk, "argument_list") != 0 && strcmp(vk, "initializer_list") != 0) {
- const CBMType* val_type = c_eval_expr_type(ctx, val);
- const CBMType* val_base = c_simplify_type(ctx, val_type, false);
+ if (strcmp(vk, "argument_list") != 0 &&
+ strcmp(vk, "initializer_list") != 0) {
+ const CBMType *val_type = c_eval_expr_type(ctx, val);
+ const CBMType *val_base = c_simplify_type(ctx, val_type, false);
// If assigning an object of the same type -> copy/move constructor
- const char* type_qn = type_to_qn(decl_type);
- const char* val_qn = type_to_qn(val_base);
+ const char *type_qn = type_to_qn(decl_type);
+ const char *val_qn = type_to_qn(val_base);
if (type_qn && val_qn && strcmp(type_qn, val_qn) == 0) {
- const char* short_name = strrchr(type_qn, '.');
+ const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
- const char* ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
+ const char *ctor_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
c_emit_resolved_call(ctx, ctor_qn, "lsp_copy_constructor", 0.85f);
}
}
@@ -3580,19 +3919,19 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
}
// --- Conversion operator: implicit bool/int conversion in conditions ---
- if (ctx->cpp_mode && (strcmp(kind, "if_statement") == 0 ||
- strcmp(kind, "while_statement") == 0 ||
- strcmp(kind, "do_statement") == 0)) {
+ if (ctx->cpp_mode &&
+ (strcmp(kind, "if_statement") == 0 || strcmp(kind, "while_statement") == 0 ||
+ strcmp(kind, "do_statement") == 0)) {
TSNode cond = ts_node_child_by_field_name(node, "condition", 9);
if (!ts_node_is_null(cond)) {
// If condition is a single expression of a custom type with operator bool
- const CBMType* cond_type = c_eval_expr_type(ctx, cond);
- const CBMType* base = c_simplify_type(ctx, cond_type, false);
+ const CBMType *cond_type = c_eval_expr_type(ctx, cond);
+ const CBMType *base = c_simplify_type(ctx, cond_type, false);
if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base) &&
base->kind != CBM_TYPE_POINTER) {
- const char* type_qn = type_to_qn(base);
+ const char *type_qn = type_to_qn(base);
if (type_qn) {
- const CBMRegisteredFunc* m = c_lookup_member(ctx, type_qn, "operator bool");
+ const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, "operator bool");
if (m) {
c_emit_resolved_call(ctx, m->qualified_name, "lsp_conversion", 0.85f);
}
@@ -3628,21 +3967,19 @@ static void c_resolve_calls_in_node(CLSPContext* ctx, TSNode node) {
// --- Designated initializer: {.field = value} ---
if (strcmp(kind, "initializer_pair") == 0 || strcmp(kind, "field_designator") == 0) {
// These appear inside initializer_list for aggregate init
- // We don't emit CALLS for field access, but we could track which struct is being initialized
- // This is primarily for completeness — no CALLS edge needed for field designators
+ // We don't emit CALLS for field access, but we could track which struct is being
+ // initialized This is primarily for completeness — no CALLS edge needed for field
+ // designators
}
recurse:;
// Push scope for blocks and control structures
- bool push_scope = (strcmp(kind, "compound_statement") == 0 ||
- strcmp(kind, "if_statement") == 0 ||
- strcmp(kind, "for_statement") == 0 ||
- strcmp(kind, "for_range_loop") == 0 ||
- strcmp(kind, "while_statement") == 0 ||
- strcmp(kind, "do_statement") == 0 ||
- strcmp(kind, "switch_statement") == 0 ||
- strcmp(kind, "catch_clause") == 0 ||
- strcmp(kind, "lambda_expression") == 0);
+ bool push_scope =
+ (strcmp(kind, "compound_statement") == 0 || strcmp(kind, "if_statement") == 0 ||
+ strcmp(kind, "for_statement") == 0 || strcmp(kind, "for_range_loop") == 0 ||
+ strcmp(kind, "while_statement") == 0 || strcmp(kind, "do_statement") == 0 ||
+ strcmp(kind, "switch_statement") == 0 || strcmp(kind, "catch_clause") == 0 ||
+ strcmp(kind, "lambda_expression") == 0);
if (push_scope) {
ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);
@@ -3664,13 +4001,15 @@ recurse:;
uint32_t lnc = ts_node_named_child_count(node);
for (uint32_t li = 0; li < lnc; li++) {
TSNode child = ts_node_named_child(node, li);
- if (ts_node_is_null(child)) continue;
+ if (ts_node_is_null(child))
+ continue;
if (strcmp(ts_node_type(child), "lambda_capture_specifier") == 0) {
uint32_t cnc = ts_node_named_child_count(child);
for (uint32_t ci = 0; ci < cnc; ci++) {
TSNode cap = ts_node_named_child(child, ci);
- if (ts_node_is_null(cap)) continue;
- const char* ck = ts_node_type(cap);
+ if (ts_node_is_null(cap))
+ continue;
+ const char *ck = ts_node_type(cap);
if (strcmp(ck, "lambda_capture_initializer") == 0) {
// Init-capture: name = value
// Try field-based access first (name field = 4 chars)
@@ -3682,8 +4021,8 @@ recurse:;
val_node = ts_node_named_child(cap, 1);
}
if (!ts_node_is_null(name_node) && !ts_node_is_null(val_node)) {
- char* cap_name = c_node_text(ctx, name_node);
- const CBMType* cap_type = c_eval_expr_type(ctx, val_node);
+ char *cap_name = c_node_text(ctx, name_node);
+ const CBMType *cap_type = c_eval_expr_type(ctx, val_node);
if (cap_name && !cbm_type_is_unknown(cap_type)) {
cbm_scope_bind(ctx->current_scope, cap_name, cap_type);
}
@@ -3716,19 +4055,20 @@ recurse:;
// Process function: set enclosing QN, bind params, walk body
// ============================================================================
-static void c_process_function(CLSPContext* ctx, TSNode func_node) {
+static void c_process_function(CLSPContext *ctx, TSNode func_node) {
TSNode decl = ts_node_child_by_field_name(func_node, "declarator", 10);
- if (ts_node_is_null(decl)) return;
+ if (ts_node_is_null(decl))
+ return;
// Extract function name from declarator chain
- char* func_name = NULL;
- const char* saved_class_qn = ctx->enclosing_class_qn;
+ char *func_name = NULL;
+ const char *saved_class_qn = ctx->enclosing_class_qn;
TSNode params_node = (TSNode){0};
// Navigate declarator to find name and parameters
TSNode cur = decl;
for (int depth = 0; depth < 10 && !ts_node_is_null(cur); depth++) {
- const char* dk = ts_node_type(cur);
+ const char *dk = ts_node_type(cur);
if (strcmp(dk, "function_declarator") == 0) {
TSNode fdecl = ts_node_child_by_field_name(cur, "declarator", 10);
@@ -3739,7 +4079,8 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
if (strcmp(dk, "pointer_declarator") == 0 || strcmp(dk, "reference_declarator") == 0) {
if (ts_node_named_child_count(cur) > 0)
cur = ts_node_named_child(cur, ts_node_named_child_count(cur) - 1);
- else break;
+ else
+ break;
continue;
}
if (strcmp(dk, "qualified_identifier") == 0 || strcmp(dk, "scoped_identifier") == 0) {
@@ -3747,17 +4088,19 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
// Check if this is a method (has Class:: prefix)
TSNode scope_node = ts_node_child_by_field_name(cur, "scope", 5);
if (!ts_node_is_null(scope_node)) {
- char* scope_text = c_node_text(ctx, scope_node);
+ char *scope_text = c_node_text(ctx, scope_node);
if (scope_text) {
- const char* scope_qn = c_build_qn(ctx, scope_text);
+ const char *scope_qn = c_build_qn(ctx, scope_text);
// Try as a type for enclosing class
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, scope_qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, scope_qn);
if (rt) {
ctx->enclosing_class_qn = scope_qn;
} else if (ctx->module_qn) {
- const char* fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, scope_qn);
+ const char *fqn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, scope_qn);
rt = cbm_registry_lookup_type(ctx->registry, fqn);
- if (rt) ctx->enclosing_class_qn = fqn;
+ if (rt)
+ ctx->enclosing_class_qn = fqn;
}
}
}
@@ -3779,10 +4122,11 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
break;
}
- if (!func_name || !func_name[0]) return;
+ if (!func_name || !func_name[0])
+ return;
// Build enclosing function QN
- const char* func_qn = c_build_qn(ctx, func_name);
+ const char *func_qn = c_build_qn(ctx, func_name);
if (ctx->module_qn && !strchr(func_qn, '.')) {
func_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, func_qn);
}
@@ -3792,11 +4136,11 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
// so pending template calls can be resolved at call sites.
if (ctx->in_template && ctx->template_param_count > 0) {
// Find the registered function and set type_param_names
- for (int ri = 0; ri < ((CBMTypeRegistry*)ctx->registry)->func_count; ri++) {
- CBMRegisteredFunc* rf = &((CBMTypeRegistry*)ctx->registry)->funcs[ri];
+ for (int ri = 0; ri < ((CBMTypeRegistry *)ctx->registry)->func_count; ri++) {
+ CBMRegisteredFunc *rf = &((CBMTypeRegistry *)ctx->registry)->funcs[ri];
if (strcmp(rf->qualified_name, func_qn) == 0 && !rf->type_param_names) {
- const char** tpn = (const char**)cbm_arena_alloc(ctx->arena,
- (ctx->template_param_count + 1) * sizeof(const char*));
+ const char **tpn = (const char **)cbm_arena_alloc(
+ ctx->arena, (ctx->template_param_count + 1) * sizeof(const char *));
for (int ti = 0; ti < ctx->template_param_count; ti++)
tpn[ti] = ctx->template_param_names[ti];
tpn[ctx->template_param_count] = NULL;
@@ -3807,14 +4151,14 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
}
// Push function scope
- CBMScope* saved_scope = ctx->current_scope;
+ CBMScope *saved_scope = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);
// Bind 'this' if in a method
if (ctx->enclosing_class_qn) {
- cbm_scope_bind(ctx->current_scope, "this",
- cbm_type_pointer(ctx->arena,
- cbm_type_named(ctx->arena, ctx->enclosing_class_qn)));
+ cbm_scope_bind(
+ ctx->current_scope, "this",
+ cbm_type_pointer(ctx->arena, cbm_type_named(ctx->arena, ctx->enclosing_class_qn)));
}
// Bind parameters and count defaults for min_params
@@ -3824,12 +4168,13 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
for (uint32_t i = 0; i < pnc; i++) {
TSNode param = ts_node_named_child(params_node, i);
if (!ts_node_is_null(param)) {
- const char* pk = ts_node_type(param);
+ const char *pk = ts_node_type(param);
if (strcmp(pk, "parameter_declaration") == 0 ||
strcmp(pk, "optional_parameter_declaration") == 0) {
total_params++;
TSNode dv = ts_node_child_by_field_name(param, "default_value", 13);
- if (!ts_node_is_null(dv)) defaulted_params++;
+ if (!ts_node_is_null(dv))
+ defaulted_params++;
}
c_process_statement(ctx, param);
}
@@ -3837,8 +4182,8 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
}
// Set min_params on the registered function (for default-arg overload matching)
if (total_params > 0 && defaulted_params > 0) {
- for (int ri = 0; ri < ((CBMTypeRegistry*)ctx->registry)->func_count; ri++) {
- CBMRegisteredFunc* rf = &((CBMTypeRegistry*)ctx->registry)->funcs[ri];
+ for (int ri = 0; ri < ((CBMTypeRegistry *)ctx->registry)->func_count; ri++) {
+ CBMRegisteredFunc *rf = &((CBMTypeRegistry *)ctx->registry)->funcs[ri];
if (strcmp(rf->qualified_name, func_qn) == 0 && rf->min_params < 0) {
rf->min_params = total_params - defaulted_params;
break;
@@ -3863,9 +4208,10 @@ static void c_process_function(CLSPContext* ctx, TSNode func_node) {
// Process a top-level or nested declaration within a namespace/class body,
// handling template_declaration wrapping.
-static void c_process_body_child(CLSPContext* ctx, TSNode child) {
- if (ts_node_is_null(child)) return;
- const char* ck = ts_node_type(child);
+static void c_process_body_child(CLSPContext *ctx, TSNode child) {
+ if (ts_node_is_null(child))
+ return;
+ const char *ck = ts_node_type(child);
if (strcmp(ck, "function_definition") == 0) {
c_process_function(ctx, child);
@@ -3880,7 +4226,7 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
uint32_t dnc = ts_node_named_child_count(child);
for (uint32_t di = 0; di < dnc; di++) {
TSNode dch = ts_node_named_child(child, di);
- const char* dk = ts_node_type(dch);
+ const char *dk = ts_node_type(dch);
if (strcmp(dk, "class_specifier") == 0 || strcmp(dk, "struct_specifier") == 0) {
c_process_class(ctx, dch);
has_class = true;
@@ -3891,8 +4237,7 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
TSNode func_decl_node = dch;
bool is_ref_ret = false;
bool is_ptr_ret = false;
- if (strcmp(dk, "reference_declarator") == 0 &&
- ts_node_named_child_count(dch) > 0) {
+ if (strcmp(dk, "reference_declarator") == 0 && ts_node_named_child_count(dch) > 0) {
TSNode inner = ts_node_named_child(dch, 0);
if (strcmp(ts_node_type(inner), "function_declarator") == 0) {
func_decl_node = inner;
@@ -3909,35 +4254,40 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
if (strcmp(ts_node_type(func_decl_node), "function_declarator") == 0) {
TSNode fn_name = ts_node_child_by_field_name(func_decl_node, "declarator", 10);
if (!ts_node_is_null(fn_name)) {
- char* fname = c_node_text(ctx, fn_name);
+ char *fname = c_node_text(ctx, fn_name);
if (fname && fname[0]) {
// Parse return type from declaration's type specifier
- const CBMType* ret_type = NULL;
+ const CBMType *ret_type = NULL;
for (uint32_t ri = 0; ri < dnc; ri++) {
TSNode rch = ts_node_named_child(child, ri);
- const char* rk = ts_node_type(rch);
+ const char *rk = ts_node_type(rch);
if (strcmp(rk, "function_declarator") != 0 &&
strcmp(rk, "identifier") != 0 &&
strcmp(rk, "pointer_declarator") != 0 &&
strcmp(rk, "reference_declarator") != 0) {
ret_type = c_parse_type_node(ctx, rch);
- if (!cbm_type_is_unknown(ret_type)) break;
+ if (!cbm_type_is_unknown(ret_type))
+ break;
}
}
if (ret_type && !cbm_type_is_unknown(ret_type)) {
- if (is_ref_ret) ret_type = cbm_type_reference(ctx->arena, ret_type);
- if (is_ptr_ret) ret_type = cbm_type_pointer(ctx->arena, ret_type);
- const char* func_qn = c_build_qn(ctx, fname);
+ if (is_ref_ret)
+ ret_type = cbm_type_reference(ctx->arena, ret_type);
+ if (is_ptr_ret)
+ ret_type = cbm_type_pointer(ctx->arena, ret_type);
+ const char *func_qn = c_build_qn(ctx, fname);
if (ctx->module_qn && !strchr(func_qn, '.'))
- func_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, func_qn);
+ func_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn,
+ func_qn);
// Use namespace if available
- if (ctx->current_namespace && !strstr(func_qn, ctx->current_namespace))
+ if (ctx->current_namespace &&
+ !strstr(func_qn, ctx->current_namespace))
func_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->current_namespace, fname);
+ ctx->current_namespace, fname);
// Only register if not already registered
if (!cbm_registry_lookup_func(ctx->registry, func_qn)) {
- const CBMType** rets = (const CBMType**)cbm_arena_alloc(
- ctx->arena, 2 * sizeof(const CBMType*));
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, 2 * sizeof(const CBMType *));
rets[0] = ret_type;
rets[1] = NULL;
CBMRegisteredFunc rf = {0};
@@ -3946,14 +4296,15 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
rf.signature = cbm_type_func(ctx->arena, NULL, NULL, rets);
// Copy template params if in template context
if (ctx->in_template && ctx->template_param_count > 0) {
- const char** tpn = (const char**)cbm_arena_alloc(
- ctx->arena, (ctx->template_param_count + 1) * sizeof(char*));
+ const char **tpn = (const char **)cbm_arena_alloc(
+ ctx->arena,
+ (ctx->template_param_count + 1) * sizeof(char *));
for (int tp = 0; tp < ctx->template_param_count; tp++)
tpn[tp] = ctx->template_param_names[tp];
tpn[ctx->template_param_count] = NULL;
rf.type_param_names = tpn;
}
- cbm_registry_add_func((CBMTypeRegistry*)ctx->registry, rf);
+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);
}
}
}
@@ -3972,8 +4323,8 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
} else if (strcmp(ck, "template_declaration") == 0) {
// Save template state, parse params for defaults, set flag
bool saved_template = ctx->in_template;
- const char** saved_tpn = ctx->template_param_names;
- const CBMType** saved_tpd = ctx->template_param_defaults;
+ const char **saved_tpn = ctx->template_param_names;
+ const CBMType **saved_tpd = ctx->template_param_defaults;
int saved_tpc = ctx->template_param_count;
ctx->in_template = true;
@@ -3994,17 +4345,18 @@ static void c_process_body_child(CLSPContext* ctx, TSNode child) {
}
}
-static void c_process_namespace(CLSPContext* ctx, TSNode ns_node) {
- const char* saved_ns = ctx->current_namespace;
+static void c_process_namespace(CLSPContext *ctx, TSNode ns_node) {
+ const char *saved_ns = ctx->current_namespace;
TSNode name_node = ts_node_child_by_field_name(ns_node, "name", 4);
if (!ts_node_is_null(name_node)) {
- char* ns_name = c_node_text(ctx, name_node);
+ char *ns_name = c_node_text(ctx, name_node);
if (ns_name) {
if (saved_ns) {
ctx->current_namespace = cbm_arena_sprintf(ctx->arena, "%s.%s", saved_ns, ns_name);
} else if (ctx->module_qn) {
- ctx->current_namespace = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, ns_name);
+ ctx->current_namespace =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, ns_name);
} else {
ctx->current_namespace = ns_name;
}
@@ -4030,20 +4382,21 @@ static void c_process_namespace(CLSPContext* ctx, TSNode ns_node) {
// Process class/struct: process method bodies
// ============================================================================
-static void c_process_class(CLSPContext* ctx, TSNode class_node) {
- const char* saved_class = ctx->enclosing_class_qn;
- const char** saved_tpn = ctx->template_param_names;
- const CBMType** saved_tpd = ctx->template_param_defaults;
+static void c_process_class(CLSPContext *ctx, TSNode class_node) {
+ const char *saved_class = ctx->enclosing_class_qn;
+ const char **saved_tpn = ctx->template_param_names;
+ const CBMType **saved_tpd = ctx->template_param_defaults;
int saved_tpc = ctx->template_param_count;
- char* class_name = NULL;
+ char *class_name = NULL;
TSNode name_node = ts_node_child_by_field_name(class_node, "name", 4);
if (!ts_node_is_null(name_node)) {
class_name = c_node_text(ctx, name_node);
if (class_name) {
- const char* class_qn;
+ const char *class_qn;
if (ctx->current_namespace) {
- class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, class_name);
+ class_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace, class_name);
} else if (ctx->module_qn) {
class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, class_name);
} else {
@@ -4053,16 +4406,17 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
// Store template param names on the registered type (for substitution)
if (ctx->in_template && ctx->template_param_names && ctx->template_param_count > 0) {
- CBMRegisteredType* rt = NULL;
- for (int ri = 0; ri < ((CBMTypeRegistry*)ctx->registry)->type_count; ri++) {
- if (strcmp(((CBMTypeRegistry*)ctx->registry)->types[ri].qualified_name, class_qn) == 0) {
- rt = &((CBMTypeRegistry*)ctx->registry)->types[ri];
+ CBMRegisteredType *rt = NULL;
+ for (int ri = 0; ri < ((CBMTypeRegistry *)ctx->registry)->type_count; ri++) {
+ if (strcmp(((CBMTypeRegistry *)ctx->registry)->types[ri].qualified_name,
+ class_qn) == 0) {
+ rt = &((CBMTypeRegistry *)ctx->registry)->types[ri];
break;
}
}
if (rt && !rt->type_param_names) {
- const char** tpn = (const char**)cbm_arena_alloc(ctx->arena,
- (ctx->template_param_count + 1) * sizeof(const char*));
+ const char **tpn = (const char **)cbm_arena_alloc(
+ ctx->arena, (ctx->template_param_count + 1) * sizeof(const char *));
for (int pi = 0; pi < ctx->template_param_count; pi++)
tpn[pi] = ctx->template_param_names[pi];
tpn[ctx->template_param_count] = NULL;
@@ -4080,17 +4434,21 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
uint32_t cnc = ts_node_named_child_count(class_node);
for (uint32_t ci = 0; ci < cnc; ci++) {
TSNode child = ts_node_named_child(class_node, ci);
- if (ts_node_is_null(child)) continue;
- const char* ck = ts_node_type(child);
- if (strcmp(ck, "base_class_clause") != 0) continue;
+ if (ts_node_is_null(child))
+ continue;
+ const char *ck = ts_node_type(child);
+ if (strcmp(ck, "base_class_clause") != 0)
+ continue;
// Iterate base specifiers
uint32_t bnc = ts_node_named_child_count(child);
for (uint32_t bi = 0; bi < bnc; bi++) {
TSNode base_spec = ts_node_named_child(child, bi);
- if (ts_node_is_null(base_spec)) continue;
+ if (ts_node_is_null(base_spec))
+ continue;
// Look for template_type as base: Base<Derived>
TSNode type_node = base_spec;
- if (strcmp(ts_node_type(base_spec), "access_specifier") == 0) continue;
+ if (strcmp(ts_node_type(base_spec), "access_specifier") == 0)
+ continue;
// The base type might be directly a template_type or wrapped
if (strcmp(ts_node_type(type_node), "template_type") != 0) {
// Try walking children for template_type
@@ -4104,31 +4462,34 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
break;
}
}
- if (!found) continue;
+ if (!found)
+ continue;
}
// type_node is template_type: check arguments for CRTP
TSNode targs = ts_node_child_by_field_name(type_node, "arguments", 9);
- if (ts_node_is_null(targs)) continue;
+ if (ts_node_is_null(targs))
+ continue;
// Check each template argument for CRTP pattern
uint32_t tanc = ts_node_named_child_count(targs);
for (uint32_t ti = 0; ti < tanc; ti++) {
TSNode ta = ts_node_named_child(targs, ti);
- if (ts_node_is_null(ta)) continue;
+ if (ts_node_is_null(ta))
+ continue;
TSNode ta_inner = ta;
// type_descriptor wraps the actual type
if (strcmp(ts_node_type(ta), "type_descriptor") == 0 &&
ts_node_named_child_count(ta) > 0) {
ta_inner = ts_node_named_child(ta, 0);
}
- char* arg_text = c_node_text(ctx, ta_inner);
+ char *arg_text = c_node_text(ctx, ta_inner);
if (arg_text && strcmp(arg_text, class_name) == 0) {
// CRTP detected! Map template param at position ti to derived class
// For now, bind using positional names (T0, T1, ...)
// Also check existing template params
if (ctx->template_param_names) {
for (int pi = 0; pi < ctx->template_param_count; pi++) {
- if (ctx->template_param_names[pi] &&
- ctx->template_param_defaults && !ctx->template_param_defaults[pi]) {
+ if (ctx->template_param_names[pi] && ctx->template_param_defaults &&
+ !ctx->template_param_defaults[pi]) {
// Bind unbound template param to derived class
// Only bind the first unbound one at position ti
if (pi == (int)ti) {
@@ -4153,49 +4514,54 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
// This allows template return type substitution for methods like T& value();
if (ctx->enclosing_class_qn) {
uint32_t bkn = 0;
- TSNode* bkids = cbm_lsp_collect_children(ctx->arena, body, &bkn);
+ 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);
+ 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 &&
strcmp(ck, "function_definition") != 0)
continue;
// Parse return type from type specifier
- const CBMType* ret_type = c_parse_declaration_type(ctx, child);
+ const CBMType *ret_type = c_parse_declaration_type(ctx, child);
// Walk declarator chain to find function_declarator + method name
uint32_t dnc = ts_node_named_child_count(child);
for (uint32_t di = 0; di < dnc; di++) {
TSNode decl = ts_node_named_child(child, di);
- // Navigate through reference_declarator, pointer_declarator to function_declarator
+ // Navigate through reference_declarator, pointer_declarator to
+ // function_declarator
TSNode cur = decl;
- const CBMType* actual_ret = ret_type;
+ const CBMType *actual_ret = ret_type;
for (int depth = 0; depth < 5 && !ts_node_is_null(cur); depth++) {
- const char* dk = ts_node_type(cur);
+ const char *dk = ts_node_type(cur);
if (strcmp(dk, "function_declarator") == 0) {
// Found method declaration — extract name
TSNode name_node = ts_node_child_by_field_name(cur, "declarator", 10);
- if (ts_node_is_null(name_node)) break;
- char* method_name = NULL;
- const char* nk = ts_node_type(name_node);
- if (strcmp(nk, "field_identifier") == 0 || strcmp(nk, "identifier") == 0) {
+ if (ts_node_is_null(name_node))
+ break;
+ char *method_name = NULL;
+ const char *nk = ts_node_type(name_node);
+ if (strcmp(nk, "field_identifier") == 0 ||
+ strcmp(nk, "identifier") == 0) {
method_name = c_node_text(ctx, name_node);
} else if (strcmp(nk, "destructor_name") == 0 ||
strcmp(nk, "operator_name") == 0) {
method_name = c_node_text(ctx, name_node);
}
- if (!method_name || !method_name[0]) break;
- const char* method_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->enclosing_class_qn, method_name);
+ if (!method_name || !method_name[0])
+ break;
+ const char *method_qn = cbm_arena_sprintf(
+ ctx->arena, "%s.%s", ctx->enclosing_class_qn, method_name);
// Check if already registered — if so, upgrade return type
// if pre-pass has a more specific type (e.g., TEMPLATE vs NAMED)
// Check both full QN and short QN (extract_defs may use shorter)
- const CBMRegisteredFunc* existing = cbm_registry_lookup_method(
+ const CBMRegisteredFunc *existing = cbm_registry_lookup_method(
ctx->registry, ctx->enclosing_class_qn, method_name);
if (!existing && ctx->module_qn) {
// Try without module prefix: "test.main.std.X" -> "std.X"
- const char* class_qn = ctx->enclosing_class_qn;
+ const char *class_qn = ctx->enclosing_class_qn;
size_t mod_len = strlen(ctx->module_qn);
if (strncmp(class_qn, ctx->module_qn, mod_len) == 0 &&
class_qn[mod_len] == '.') {
@@ -4207,7 +4573,8 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
// Upgrade: if existing return type is NAMED but we have
// TEMPLATE/TYPE_PARAM/POINTER(TYPE_PARAM), update in-place
bool should_upgrade = false;
- if (existing->signature && existing->signature->kind == CBM_TYPE_FUNC &&
+ if (existing->signature &&
+ existing->signature->kind == CBM_TYPE_FUNC &&
existing->signature->data.func.return_types &&
existing->signature->data.func.return_types[0]) {
int ek = existing->signature->data.func.return_types[0]->kind;
@@ -4220,18 +4587,19 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
}
if (should_upgrade) {
// Update existing entry's signature return type
- const CBMType** new_rets = (const CBMType**)cbm_arena_alloc(
- ctx->arena, 2 * sizeof(const CBMType*));
+ const CBMType **new_rets = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, 2 * sizeof(const CBMType *));
new_rets[0] = actual_ret;
new_rets[1] = NULL;
- CBMRegisteredFunc* mut = (CBMRegisteredFunc*)existing;
- mut->signature = cbm_type_func(ctx->arena, NULL, NULL, new_rets);
+ CBMRegisteredFunc *mut = (CBMRegisteredFunc *)existing;
+ mut->signature =
+ cbm_type_func(ctx->arena, NULL, NULL, new_rets);
}
break;
}
// Build return type with ref/ptr wrapping
- const CBMType** rets = (const CBMType**)cbm_arena_alloc(
- ctx->arena, 2 * sizeof(const CBMType*));
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, 2 * sizeof(const CBMType *));
rets[0] = actual_ret;
rets[1] = NULL;
CBMRegisteredFunc rf;
@@ -4241,16 +4609,16 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
rf.receiver_type = ctx->enclosing_class_qn;
rf.signature = cbm_type_func(ctx->arena, NULL, NULL, rets);
rf.min_params = -1;
- cbm_registry_add_func((CBMTypeRegistry*)ctx->registry, rf);
+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);
break;
} else if (strcmp(dk, "reference_declarator") == 0) {
actual_ret = cbm_type_reference(ctx->arena, actual_ret);
- cur = ts_node_named_child_count(cur) > 0 ?
- ts_node_named_child(cur, 0) : (TSNode){0};
+ cur = ts_node_named_child_count(cur) > 0 ? ts_node_named_child(cur, 0)
+ : (TSNode){0};
} else if (strcmp(dk, "pointer_declarator") == 0) {
actual_ret = cbm_type_pointer(ctx->arena, actual_ret);
- cur = ts_node_named_child_count(cur) > 0 ?
- ts_node_named_child(cur, 0) : (TSNode){0};
+ cur = ts_node_named_child_count(cur) > 0 ? ts_node_named_child(cur, 0)
+ : (TSNode){0};
} else {
break;
}
@@ -4260,10 +4628,11 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
}
uint32_t bkn = 0;
- TSNode* bkids = cbm_lsp_collect_children(ctx->arena, body, &bkn);
+ 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;
+ if (!ts_node_is_named(child))
+ continue;
c_process_body_child(ctx, child);
}
}
@@ -4281,26 +4650,24 @@ static void c_process_class(CLSPContext* ctx, TSNode class_node) {
// Process file: top-level walk
// ============================================================================
-__attribute__((no_sanitize("address")))
-void c_lsp_process_file(CLSPContext* ctx, TSNode root) {
- if (ts_node_is_null(root)) return;
+__attribute__((no_sanitize("address"))) void c_lsp_process_file(CLSPContext *ctx, TSNode root) {
+ if (ts_node_is_null(root))
+ return;
// 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 *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 < kn; i++) {
child = kids[i];
- const char* ck = ts_node_type(child);
+ const char *ck = ts_node_type(child);
- if (strcmp(ck, "using_declaration") == 0 ||
- strcmp(ck, "alias_declaration") == 0 ||
- strcmp(ck, "type_definition") == 0 ||
- strcmp(ck, "namespace_alias_definition") == 0) {
+ if (strcmp(ck, "using_declaration") == 0 || strcmp(ck, "alias_declaration") == 0 ||
+ strcmp(ck, "type_definition") == 0 || strcmp(ck, "namespace_alias_definition") == 0) {
c_process_statement(ctx, child);
} else if (strcmp(ck, "declaration") == 0) {
c_process_statement(ctx, child);
@@ -4310,9 +4677,8 @@ void c_lsp_process_file(CLSPContext* ctx, TSNode root) {
uint32_t tnc = ts_node_named_child_count(child);
for (uint32_t ti = 0; ti < tnc; ti++) {
inner = ts_node_named_child(child, ti);
- const char* ik = ts_node_type(inner);
- if (strcmp(ik, "alias_declaration") == 0 ||
- strcmp(ik, "type_definition") == 0) {
+ const char *ik = ts_node_type(inner);
+ if (strcmp(ik, "alias_declaration") == 0 || strcmp(ik, "type_definition") == 0) {
c_process_statement(ctx, inner);
}
}
@@ -4330,32 +4696,39 @@ void c_lsp_process_file(CLSPContext* ctx, TSNode root) {
// Parse C/C++ return type text into CBMType (for cross-file defs)
// ============================================================================
-static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, const char* module_qn) {
- if (!text || !text[0]) return cbm_type_unknown();
+static const CBMType *c_parse_return_type_text(CBMArena *a, const char *text,
+ const char *module_qn) {
+ if (!text || !text[0])
+ return cbm_type_unknown();
// Skip const/volatile qualifiers
- while (strncmp(text, "const ", 6) == 0) text += 6;
- while (strncmp(text, "volatile ", 9) == 0) text += 9;
+ while (strncmp(text, "const ", 6) == 0)
+ text += 6;
+ while (strncmp(text, "volatile ", 9) == 0)
+ text += 9;
// Pointer
size_t len = strlen(text);
if (len > 0 && text[len - 1] == '*') {
- char* inner = cbm_arena_strndup(a, text, len - 1);
+ char *inner = cbm_arena_strndup(a, text, len - 1);
// Trim trailing space
size_t ilen = strlen(inner);
- while (ilen > 0 && inner[ilen - 1] == ' ') inner[--ilen] = '\0';
+ while (ilen > 0 && inner[ilen - 1] == ' ')
+ inner[--ilen] = '\0';
return cbm_type_pointer(a, c_parse_return_type_text(a, inner, module_qn));
}
// Reference
if (len > 0 && text[len - 1] == '&') {
- char* inner = cbm_arena_strndup(a, text, len - 1);
+ char *inner = cbm_arena_strndup(a, text, len - 1);
size_t ilen = strlen(inner);
- while (ilen > 0 && inner[ilen - 1] == ' ') inner[--ilen] = '\0';
+ while (ilen > 0 && inner[ilen - 1] == ' ')
+ inner[--ilen] = '\0';
// Check for rvalue ref
if (ilen > 0 && inner[ilen - 1] == '&') {
inner[ilen - 1] = '\0';
- while (ilen > 1 && inner[ilen - 2] == ' ') inner[--ilen - 1] = '\0';
+ while (ilen > 1 && inner[ilen - 2] == ' ')
+ inner[--ilen - 1] = '\0';
return cbm_type_rvalue_ref(a, c_parse_return_type_text(a, inner, module_qn));
}
return cbm_type_reference(a, c_parse_return_type_text(a, inner, module_qn));
@@ -4363,10 +4736,11 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
// decltype(expr) — extract the type from the expression
if (strncmp(text, "decltype(", 9) == 0 && len > 10 && text[len - 1] == ')') {
- char* inner = cbm_arena_strndup(a, text + 9, len - 10);
+ char *inner = cbm_arena_strndup(a, text + 9, len - 10);
size_t ilen = strlen(inner);
// decltype(auto) — auto deduction, can't resolve statically
- if (strcmp(inner, "auto") == 0) return cbm_type_unknown();
+ if (strcmp(inner, "auto") == 0)
+ return cbm_type_unknown();
// decltype(TypeName()) — constructor call → type is TypeName
if (ilen >= 2 && inner[ilen - 1] == ')' && inner[ilen - 2] == '(') {
inner[ilen - 2] = '\0';
@@ -4377,13 +4751,14 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
}
// Builtins
- if (is_c_builtin_type(text)) return cbm_type_builtin(a, text);
+ if (is_c_builtin_type(text))
+ return cbm_type_builtin(a, text);
// Template type parameters: only T, U, V, K, W (common conventions) or T1-T9.
// Do NOT treat all single uppercase letters as type params — A, B, C, etc.
// are legitimate class names (especially in C++ code with short names).
- if (len == 1 && (text[0] == 'T' || text[0] == 'U' || text[0] == 'V' ||
- text[0] == 'K' || text[0] == 'W')) {
+ if (len == 1 &&
+ (text[0] == 'T' || text[0] == 'U' || text[0] == 'V' || text[0] == 'K' || text[0] == 'W')) {
return cbm_type_type_param(a, text);
}
if (len == 2 && text[0] == 'T' && text[1] >= '1' && text[1] <= '9') {
@@ -4392,14 +4767,15 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
// Template type: Name<Arg1, Arg2, ...>
{
- const char* angle = strchr(text, '<');
+ const char *angle = strchr(text, '<');
if (angle && len > 0 && text[len - 1] == '>') {
// Extract template name
size_t name_len = (size_t)(angle - text);
- char* tmpl_name = cbm_arena_strndup(a, text, name_len);
- while (name_len > 0 && tmpl_name[name_len - 1] == ' ') tmpl_name[--name_len] = '\0';
+ char *tmpl_name = cbm_arena_strndup(a, text, name_len);
+ while (name_len > 0 && tmpl_name[name_len - 1] == ' ')
+ tmpl_name[--name_len] = '\0';
// Replace :: with .
- for (char* p = tmpl_name; *p; p++) {
+ for (char *p = tmpl_name; *p; p++) {
if (p[0] == ':' && p[1] == ':') {
p[0] = '.';
memmove(p + 1, p + 2, strlen(p + 2) + 1);
@@ -4407,37 +4783,42 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
}
// Extract args between < and >
- const char* args_start = angle + 1;
+ const char *args_start = angle + 1;
size_t args_len = (size_t)((text + len - 1) - args_start);
- char* args_text = cbm_arena_strndup(a, args_start, args_len);
+ char *args_text = cbm_arena_strndup(a, args_start, args_len);
// Split by comma at nesting depth 0
- const CBMType* arg_types[16];
+ const CBMType *arg_types[16];
int arg_count = 0;
int depth = 0;
- const char* arg_begin = args_text;
- for (const char* p = args_text; ; p++) {
- if (*p == '<') depth++;
- else if (*p == '>') depth--;
+ const char *arg_begin = args_text;
+ for (const char *p = args_text;; p++) {
+ if (*p == '<')
+ depth++;
+ else if (*p == '>')
+ depth--;
if ((*p == ',' && depth == 0) || *p == '\0') {
if (arg_count < 16) {
size_t alen = (size_t)(p - arg_begin);
- char* arg = cbm_arena_strndup(a, arg_begin, alen);
+ char *arg = cbm_arena_strndup(a, arg_begin, alen);
// Trim whitespace
- while (*arg == ' ') arg++;
+ while (*arg == ' ')
+ arg++;
size_t al = strlen(arg);
- while (al > 0 && arg[al - 1] == ' ') arg[--al] = '\0';
+ while (al > 0 && arg[al - 1] == ' ')
+ arg[--al] = '\0';
if (arg[0]) {
arg_types[arg_count++] = c_parse_return_type_text(a, arg, module_qn);
}
}
- if (*p == '\0') break;
+ if (*p == '\0')
+ break;
arg_begin = p + 1;
}
}
// Qualify with module if unqualified
- const char* qname = tmpl_name;
+ const char *qname = tmpl_name;
if (!strchr(tmpl_name, '.') && module_qn && module_qn[0]) {
qname = cbm_arena_sprintf(a, "%s.%s", module_qn, tmpl_name);
}
@@ -4448,9 +4829,12 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
// Qualified name (has ::)
if (strstr(text, "::")) {
// Replace :: with .
- char* qn = cbm_arena_strdup(a, text);
- for (char* p = qn; *p; p++) {
- if (p[0] == ':' && p[1] == ':') { p[0] = '.'; memmove(p + 1, p + 2, strlen(p + 2) + 1); }
+ char *qn = cbm_arena_strdup(a, text);
+ for (char *p = qn; *p; p++) {
+ if (p[0] == ':' && p[1] == ':') {
+ p[0] = '.';
+ memmove(p + 1, p + 2, strlen(p + 2) + 1);
+ }
}
return cbm_type_named(a, qn);
}
@@ -4466,22 +4850,24 @@ static const CBMType* c_parse_return_type_text(CBMArena* a, const char* text, co
// Entry point: single-file LSP
// ============================================================================
-void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
- const char* source, int source_len, TSNode root, bool cpp_mode) {
+void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root, bool cpp_mode) {
CBMTypeRegistry reg;
cbm_registry_init(&reg, arena);
// Register stdlib
cbm_c_stdlib_register(&reg, arena);
- if (cpp_mode) cbm_cpp_stdlib_register(&reg, arena);
+ if (cpp_mode)
+ cbm_cpp_stdlib_register(&reg, arena);
- const char* module_qn = result->module_qn;
+ const char *module_qn = result->module_qn;
// Register file's own definitions
for (int i = 0; i < result->defs.count; i++) {
- CBMDefinition* d = &result->defs.items[i];
- if (!d->qualified_name || !d->name) continue;
+ CBMDefinition *d = &result->defs.items[i];
+ if (!d->qualified_name || !d->name)
+ continue;
if (d->label && (strcmp(d->label, "Class") == 0 || strcmp(d->label, "Type") == 0)) {
CBMRegisteredType rt;
@@ -4492,11 +4878,13 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
// Base classes
if (d->base_classes) {
int bc_count = 0;
- while (d->base_classes[bc_count]) bc_count++;
+ while (d->base_classes[bc_count])
+ bc_count++;
if (bc_count > 0) {
- const char** embedded = (const char**)cbm_arena_alloc(arena, (bc_count + 1) * sizeof(const char*));
+ const char **embedded = (const char **)cbm_arena_alloc(
+ arena, (bc_count + 1) * sizeof(const char *));
for (int j = 0; j < bc_count; j++) {
- const char* bc = d->base_classes[j];
+ const char *bc = d->base_classes[j];
// Check if already qualified
if (strchr(bc, '.') || strstr(bc, "::")) {
embedded[j] = bc;
@@ -4514,7 +4902,7 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
// Field definitions → populate field_names/field_types on parent type
if (d->label && strcmp(d->label, "Field") == 0 && d->parent_class && d->return_type) {
// Find or add the parent type in registry
- CBMRegisteredType* parent_rt = NULL;
+ CBMRegisteredType *parent_rt = NULL;
for (int ri = 0; ri < reg.type_count; ri++) {
if (strcmp(reg.types[ri].qualified_name, d->parent_class) == 0) {
parent_rt = &reg.types[ri];
@@ -4525,18 +4913,22 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
// Count existing fields
int existing = 0;
if (parent_rt->field_names) {
- while (parent_rt->field_names[existing]) existing++;
+ while (parent_rt->field_names[existing])
+ existing++;
}
// Add this field
- const char** new_fnames = (const char**)cbm_arena_alloc(arena, (existing + 2) * sizeof(const char*));
- const CBMType** new_ftypes = (const CBMType**)cbm_arena_alloc(arena, (existing + 2) * sizeof(const CBMType*));
+ const char **new_fnames =
+ (const char **)cbm_arena_alloc(arena, (existing + 2) * sizeof(const char *));
+ const CBMType **new_ftypes = (const CBMType **)cbm_arena_alloc(
+ arena, (existing + 2) * sizeof(const CBMType *));
if (new_fnames && new_ftypes) {
for (int j = 0; j < existing; j++) {
new_fnames[j] = parent_rt->field_names[j];
new_ftypes[j] = parent_rt->field_types ? parent_rt->field_types[j] : NULL;
}
new_fnames[existing] = d->name;
- new_ftypes[existing] = c_parse_return_type_text(arena, d->return_type, module_qn);
+ new_ftypes[existing] =
+ c_parse_return_type_text(arena, d->return_type, module_qn);
new_fnames[existing + 1] = NULL;
new_ftypes[existing + 1] = NULL;
parent_rt->field_names = new_fnames;
@@ -4554,31 +4946,37 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
// Build return type — prefer return_type (raw text) over return_types
// (cleaned by clean_type_name which strips template args like <Service>).
- const CBMType** ret_types = NULL;
+ const CBMType **ret_types = NULL;
if (d->return_type && d->return_type[0]) {
- ret_types = (const CBMType**)cbm_arena_alloc(arena, 2 * sizeof(const CBMType*));
+ ret_types = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
ret_types[0] = c_parse_return_type_text(arena, d->return_type, module_qn);
ret_types[1] = NULL;
} else if (d->return_types) {
int count = 0;
- while (d->return_types[count]) count++;
+ while (d->return_types[count])
+ count++;
if (count > 0) {
- ret_types = (const CBMType**)cbm_arena_alloc(arena, (count + 1) * sizeof(const CBMType*));
+ ret_types = (const CBMType **)cbm_arena_alloc(
+ arena, (count + 1) * sizeof(const CBMType *));
for (int j = 0; j < count; j++)
- ret_types[j] = c_parse_return_type_text(arena, d->return_types[j], module_qn);
+ ret_types[j] =
+ c_parse_return_type_text(arena, d->return_types[j], module_qn);
ret_types[count] = NULL;
}
}
// Build param types
- const CBMType** param_types_arr = NULL;
+ const CBMType **param_types_arr = NULL;
if (d->param_types) {
int count = 0;
- while (d->param_types[count]) count++;
+ while (d->param_types[count])
+ count++;
if (count > 0) {
- param_types_arr = (const CBMType**)cbm_arena_alloc(arena, (count + 1) * sizeof(const CBMType*));
+ param_types_arr = (const CBMType **)cbm_arena_alloc(
+ arena, (count + 1) * sizeof(const CBMType *));
for (int j = 0; j < count; j++)
- param_types_arr[j] = c_parse_return_type_text(arena, d->param_types[j], module_qn);
+ param_types_arr[j] =
+ c_parse_return_type_text(arena, d->param_types[j], module_qn);
param_types_arr[count] = NULL;
}
}
@@ -4594,7 +4992,7 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
memset(&auto_type, 0, sizeof(auto_type));
auto_type.qualified_name = d->parent_class;
// Extract short name
- const char* dot = strrchr(d->parent_class, '.');
+ const char *dot = strrchr(d->parent_class, '.');
auto_type.short_name = dot ? dot + 1 : d->parent_class;
cbm_registry_add_type(&reg, auto_type);
}
@@ -4620,11 +5018,12 @@ void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
* Reads field/return/embedded info from the def strings (def-driven —
* no per-file AST mutation), so the same defs always yield the same
* registry entries regardless of which file is being processed. */
-static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
- const char* module_qn, CBMLSPDef* defs, int def_count) {
+static void c_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const char *module_qn,
+ CBMLSPDef *defs, int def_count) {
for (int i = 0; i < def_count; i++) {
- CBMLSPDef* d = &defs[i];
- if (!d->qualified_name || !d->short_name) continue;
+ CBMLSPDef *d = &defs[i];
+ if (!d->qualified_name || !d->short_name)
+ continue;
if (d->label && (strcmp(d->label, "Class") == 0 || strcmp(d->label, "Type") == 0 ||
strcmp(d->label, "Interface") == 0)) {
@@ -4637,11 +5036,11 @@ static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
// Embedded/base types
if (d->embedded_types) {
// Parse "|"-separated list
- const char* src = d->embedded_types;
- const char* embeds[32];
+ const char *src = d->embedded_types;
+ const char *embeds[32];
int embed_count = 0;
while (*src && embed_count < 31) {
- const char* sep = strchr(src, '|');
+ const char *sep = strchr(src, '|');
if (sep) {
embeds[embed_count++] = cbm_arena_strndup(arena, src, sep - src);
src = sep + 1;
@@ -4651,8 +5050,10 @@ static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
}
}
if (embed_count > 0) {
- const char** arr = (const char**)cbm_arena_alloc(arena, (embed_count + 1) * sizeof(const char*));
- for (int j = 0; j < embed_count; j++) arr[j] = embeds[j];
+ const char **arr = (const char **)cbm_arena_alloc(
+ arena, (embed_count + 1) * sizeof(const char *));
+ for (int j = 0; j < embed_count; j++)
+ arr[j] = embeds[j];
arr[embed_count] = NULL;
rt.embedded_types = arr;
}
@@ -4660,29 +5061,35 @@ static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
// Field defs
if (d->field_defs) {
- const char* fsrc = d->field_defs;
- const char* fnames[64];
- const CBMType* ftypes[64];
+ const char *fsrc = d->field_defs;
+ const char *fnames[64];
+ const CBMType *ftypes[64];
int fcount = 0;
while (*fsrc && fcount < 63) {
- const char* sep = strchr(fsrc, '|');
- const char* end = sep ? sep : fsrc + strlen(fsrc);
- char* pair = cbm_arena_strndup(arena, fsrc, end - fsrc);
- char* colon = strchr(pair, ':');
+ const char *sep = strchr(fsrc, '|');
+ const char *end = sep ? sep : fsrc + strlen(fsrc);
+ char *pair = cbm_arena_strndup(arena, fsrc, end - fsrc);
+ char *colon = strchr(pair, ':');
if (colon) {
*colon = '\0';
fnames[fcount] = pair;
- ftypes[fcount] = c_parse_return_type_text(arena, colon + 1,
- d->def_module_qn ? d->def_module_qn : module_qn);
+ ftypes[fcount] = c_parse_return_type_text(
+ arena, colon + 1, d->def_module_qn ? d->def_module_qn : module_qn);
fcount++;
}
- if (!sep) break;
+ if (!sep)
+ break;
fsrc = sep + 1;
}
if (fcount > 0) {
- const char** fnarr = (const char**)cbm_arena_alloc(arena, (fcount + 1) * sizeof(const char*));
- const CBMType** ftarr = (const CBMType**)cbm_arena_alloc(arena, (fcount + 1) * sizeof(const CBMType*));
- for (int j = 0; j < fcount; j++) { fnarr[j] = fnames[j]; ftarr[j] = ftypes[j]; }
+ const char **fnarr =
+ (const char **)cbm_arena_alloc(arena, (fcount + 1) * sizeof(const char *));
+ const CBMType **ftarr = (const CBMType **)cbm_arena_alloc(
+ arena, (fcount + 1) * sizeof(const CBMType *));
+ for (int j = 0; j < fcount; j++) {
+ fnarr[j] = fnames[j];
+ ftarr[j] = ftypes[j];
+ }
fnarr[fcount] = NULL;
ftarr[fcount] = NULL;
rt.field_names = fnarr;
@@ -4700,30 +5107,34 @@ static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
rf.qualified_name = d->qualified_name; /* borrowed */
rf.short_name = d->short_name;
- const char* def_module = d->def_module_qn ? d->def_module_qn : module_qn;
+ const char *def_module = d->def_module_qn ? d->def_module_qn : module_qn;
// Return types
if (d->return_types) {
// Parse "|"-separated
- const char* rsrc = d->return_types;
- const CBMType* rets[16];
+ const char *rsrc = d->return_types;
+ const CBMType *rets[16];
int rcount = 0;
while (*rsrc && rcount < 15) {
- const char* sep = strchr(rsrc, '|');
- const char* end = sep ? sep : rsrc + strlen(rsrc);
- char* rt_text = cbm_arena_strndup(arena, rsrc, end - rsrc);
+ const char *sep = strchr(rsrc, '|');
+ const char *end = sep ? sep : rsrc + strlen(rsrc);
+ char *rt_text = cbm_arena_strndup(arena, rsrc, end - rsrc);
rets[rcount++] = c_parse_return_type_text(arena, rt_text, def_module);
- if (!sep) break;
+ if (!sep)
+ break;
rsrc = sep + 1;
}
if (rcount > 0) {
- const CBMType** rarr = (const CBMType**)cbm_arena_alloc(arena, (rcount + 1) * sizeof(const CBMType*));
- for (int j = 0; j < rcount; j++) rarr[j] = rets[j];
+ const CBMType **rarr = (const CBMType **)cbm_arena_alloc(
+ arena, (rcount + 1) * sizeof(const CBMType *));
+ for (int j = 0; j < rcount; j++)
+ rarr[j] = rets[j];
rarr[rcount] = NULL;
rf.signature = cbm_type_func(arena, NULL, NULL, rarr);
}
}
- if (!rf.signature) rf.signature = cbm_type_func(arena, NULL, NULL, NULL);
+ if (!rf.signature)
+ rf.signature = cbm_type_func(arena, NULL, NULL, NULL);
if (d->receiver_type) {
rf.receiver_type = d->receiver_type; /* borrowed */
@@ -4739,15 +5150,17 @@ static void c_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
* and all C-family defs. Shared READ-ONLY across resolve workers.
* Def-driven (no AST field collection) so produces identical entries
* to the per-file build — zero quality loss. */
-CBMTypeRegistry* cbm_c_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;
+CBMTypeRegistry *cbm_c_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_c_stdlib_register(reg, arena);
cbm_cpp_stdlib_register(reg, arena);
for (int i = 0; i < def_count; i++) {
- CBMLSPDef* d = &defs[i];
+ CBMLSPDef *d = &defs[i];
if (d->lang != CBM_LANG_C && d->lang != CBM_LANG_CPP && d->lang != CBM_LANG_CUDA) {
continue;
}
@@ -4757,29 +5170,28 @@ CBMTypeRegistry* cbm_c_build_cross_registry(CBMArena* arena, CBMLSPDef* defs, in
return reg;
}
-void cbm_run_c_lsp_cross_with_registry(
- CBMArena* arena,
- const char* source, int source_len,
- const char* module_qn,
- bool cpp_mode,
- CBMTypeRegistry* reg,
- const char** include_paths, const char** include_ns_qns, int include_count,
- TSTree* cached_tree,
- CBMResolvedCallArray* out) {
- if (!source || source_len == 0 || !out || !reg) return;
-
- TSParser* parser = NULL;
- TSTree* tree = cached_tree;
+void cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
+ const char *module_qn, bool cpp_mode, CBMTypeRegistry *reg,
+ const char **include_paths, const char **include_ns_qns,
+ int include_count, TSTree *cached_tree,
+ CBMResolvedCallArray *out) {
+ if (!source || source_len == 0 || !out || !reg)
+ return;
+
+ TSParser *parser = NULL;
+ TSTree *tree = cached_tree;
bool owns_tree = false;
if (!tree) {
parser = ts_parser_new();
- if (!parser) return;
- const TSLanguage* ts_lang = cpp_mode ? tree_sitter_cpp() : tree_sitter_c();
+ if (!parser)
+ return;
+ const TSLanguage *ts_lang = cpp_mode ? tree_sitter_cpp() : tree_sitter_c();
ts_parser_set_language(parser, ts_lang);
tree = ts_parser_parse_string(parser, NULL, source, source_len);
ts_parser_delete(parser);
owns_tree = true;
- if (!tree) return;
+ if (!tree)
+ return;
}
TSNode root = ts_tree_root_node(tree);
@@ -4795,42 +5207,40 @@ void cbm_run_c_lsp_cross_with_registry(
}
}
-void cbm_run_c_lsp_cross(
- CBMArena* arena,
- const char* source, int source_len,
- const char* module_qn,
- bool cpp_mode,
- CBMLSPDef* defs, int def_count,
- const char** include_paths, const char** include_ns_qns, int include_count,
- TSTree* cached_tree,
- CBMResolvedCallArray* out) {
+void cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn,
+ bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths,
+ const char **include_ns_qns, int include_count, TSTree *cached_tree,
+ CBMResolvedCallArray *out) {
- if (!source || source_len == 0 || !out) return;
+ if (!source || source_len == 0 || !out)
+ return;
CBMTypeRegistry reg;
cbm_registry_init(&reg, arena);
// Register stdlib
cbm_c_stdlib_register(&reg, arena);
- if (cpp_mode) cbm_cpp_stdlib_register(&reg, arena);
+ if (cpp_mode)
+ cbm_cpp_stdlib_register(&reg, arena);
// Register all defs (shared helper — def-driven)
c_register_lsp_defs(arena, &reg, module_qn, defs, def_count);
// Use cached tree if available, otherwise parse fresh
- TSParser* parser = NULL;
- TSTree* tree = cached_tree;
+ TSParser *parser = NULL;
+ TSTree *tree = cached_tree;
bool owns_tree = false;
if (!tree) {
parser = ts_parser_new();
- if (!parser) return;
- const TSLanguage* ts_lang = cpp_mode ?
- tree_sitter_cpp() : tree_sitter_c();
+ if (!parser)
+ return;
+ const TSLanguage *ts_lang = cpp_mode ? tree_sitter_cpp() : tree_sitter_c();
ts_parser_set_language(parser, ts_lang);
tree = ts_parser_parse_string(parser, NULL, source, source_len);
ts_parser_delete(parser);
owns_tree = true;
- if (!tree) return;
+ if (!tree)
+ return;
}
TSNode root = ts_tree_root_node(tree);
@@ -4857,18 +5267,17 @@ void cbm_run_c_lsp_cross(
// --- Batch cross-file LSP ---
-void cbm_batch_c_lsp_cross(
- CBMArena* arena,
- CBMBatchCLSPFile* files, int file_count,
- CBMResolvedCallArray* out)
-{
- if (!files || file_count <= 0 || !out) return;
+void cbm_batch_c_lsp_cross(CBMArena *arena, CBMBatchCLSPFile *files, int file_count,
+ CBMResolvedCallArray *out) {
+ if (!files || file_count <= 0 || !out)
+ return;
for (int f = 0; f < file_count; f++) {
- CBMBatchCLSPFile* file = &files[f];
+ CBMBatchCLSPFile *file = &files[f];
memset(&out[f], 0, sizeof(CBMResolvedCallArray));
- if (!file->source || file->source_len <= 0 || file->def_count <= 0) continue;
+ if (!file->source || file->source_len <= 0 || file->def_count <= 0)
+ continue;
// Per-file arena: registry + temp data freed after each file
CBMArena file_arena;
@@ -4878,29 +5287,24 @@ void cbm_batch_c_lsp_cross(
memset(&file_out, 0, sizeof(file_out));
// Delegate to existing per-file function
- cbm_run_c_lsp_cross(
- &file_arena,
- file->source, file->source_len,
- file->module_qn,
- file->cpp_mode,
- file->defs, file->def_count,
- file->include_paths, file->include_ns_qns, file->include_count,
- file->cached_tree,
- &file_out);
+ cbm_run_c_lsp_cross(&file_arena, file->source, file->source_len, file->module_qn,
+ file->cpp_mode, file->defs, file->def_count, file->include_paths,
+ file->include_ns_qns, file->include_count, file->cached_tree,
+ &file_out);
// Copy results to output arena (must outlive per-file arena)
if (file_out.count > 0) {
out[f].count = file_out.count;
- out[f].items = (CBMResolvedCall*)cbm_arena_alloc(arena,
- file_out.count * sizeof(CBMResolvedCall));
+ out[f].items =
+ (CBMResolvedCall *)cbm_arena_alloc(arena, file_out.count * sizeof(CBMResolvedCall));
for (int j = 0; j < file_out.count; j++) {
- CBMResolvedCall* src = &file_out.items[j];
- CBMResolvedCall* dst = &out[f].items[j];
+ CBMResolvedCall *src = &file_out.items[j];
+ CBMResolvedCall *dst = &out[f].items[j];
dst->caller_qn = src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn = src->callee_qn ? cbm_arena_strdup(arena, src->callee_qn) : NULL;
- dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
+ dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
- dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
}
}
diff --git a/internal/cbm/lsp/c_lsp.h b/internal/cbm/lsp/c_lsp.h
index c8a50fe00..1da23a5ba 100644
--- a/internal/cbm/lsp/c_lsp.h
+++ b/internal/cbm/lsp/c_lsp.h
@@ -5,160 +5,154 @@
#include "scope.h"
#include "type_registry.h"
#include "../cbm.h"
-#include "go_lsp.h" // for CBMLSPDef, CBMResolvedCallArray
+#include "go_lsp.h" // for CBMLSPDef, CBMResolvedCallArray
// CLSPContext holds state for C/C++ expression type evaluation within a file.
typedef struct {
- CBMArena* arena;
- const char* source;
+ CBMArena *arena;
+ const char *source;
int source_len;
- const CBMTypeRegistry* registry;
- CBMScope* current_scope;
+ const CBMTypeRegistry *registry;
+ CBMScope *current_scope;
// Include map: header_path -> namespace QN prefix
- const char** include_paths;
- const char** include_ns_qns;
+ const char **include_paths;
+ const char **include_ns_qns;
int include_count;
// Namespace state
- const char* current_namespace; // current namespace QN (e.g., "proj.ns1.ns2")
+ const char *current_namespace; // current namespace QN (e.g., "proj.ns1.ns2")
// Using namespace directives
- const char** using_namespaces;
+ const char **using_namespaces;
int using_ns_count;
int using_ns_cap;
// Using declarations: specific names imported into scope
- const char** using_decl_names;
- const char** using_decl_qns;
+ const char **using_decl_names;
+ const char **using_decl_qns;
int using_decl_count;
int using_decl_cap;
// Namespace aliases: short -> full QN
- const char** ns_alias_names;
- const char** ns_alias_qns;
+ const char **ns_alias_names;
+ const char **ns_alias_qns;
int ns_alias_count;
int ns_alias_cap;
// Current context
- const char* enclosing_func_qn;
- const char* enclosing_class_qn; // for implicit `this` resolution
- const char* module_qn;
+ const char *enclosing_func_qn;
+ const char *enclosing_class_qn; // for implicit `this` resolution
+ const char *module_qn;
// Output
- CBMResolvedCallArray* resolved_calls;
+ CBMResolvedCallArray *resolved_calls;
// Function pointer targets: var_name -> target function QN
- const char** fp_var_names;
- const char** fp_target_qns;
+ const char **fp_var_names;
+ const char **fp_target_qns;
int fp_count;
int fp_cap;
// Template parameter defaults for current template scope
- const char** template_param_names; // e.g., ["T", "U"]
- const CBMType** template_param_defaults; // e.g., [int_type, NULL]
+ const char **template_param_names; // e.g., ["T", "U"]
+ const CBMType **template_param_defaults; // e.g., [int_type, NULL]
int template_param_count;
// Pending template calls: member calls on TYPE_PARAM inside template functions.
// At call sites with known arg types, these are resolved retroactively.
struct {
- const char* func_qn; // enclosing template function
- const char* type_param; // e.g., "T"
- const char* method_name; // e.g., "draw"
+ const char *func_qn; // enclosing template function
+ const char *type_param; // e.g., "T"
+ const char *method_name; // e.g., "draw"
int arg_count;
} *pending_template_calls;
int pending_tc_count;
int pending_tc_cap;
// Flags
- bool cpp_mode; // C++ features enabled
- bool in_template; // currently inside template declaration
+ bool cpp_mode; // C++ features enabled
+ bool in_template; // currently inside template declaration
bool debug;
- int eval_depth; // recursion depth for c_eval_expr_type (crash guard)
- int eval_steps; // total expression eval calls for current file (hang guard)
+ int eval_depth; // recursion depth for c_eval_expr_type (crash guard)
+ int eval_steps; // total expression eval calls for current file (hang guard)
+ int walk_depth; // c_resolve_calls_in_node self-recursion (AST nesting)
} CLSPContext;
// --- API ---
-void c_lsp_init(CLSPContext* ctx, CBMArena* arena, const char* source, int source_len,
- const CBMTypeRegistry* registry, const char* module_qn, bool cpp_mode,
- CBMResolvedCallArray* out);
+void c_lsp_init(CLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn, bool cpp_mode,
+ CBMResolvedCallArray *out);
-void c_lsp_add_include(CLSPContext* ctx, const char* header_path, const char* ns_qn);
+void c_lsp_add_include(CLSPContext *ctx, const char *header_path, const char *ns_qn);
-void c_lsp_process_file(CLSPContext* ctx, TSNode root);
+void c_lsp_process_file(CLSPContext *ctx, TSNode root);
-const CBMType* c_eval_expr_type(CLSPContext* ctx, TSNode node);
-const CBMType* c_parse_type_node(CLSPContext* ctx, TSNode node);
-void c_process_statement(CLSPContext* ctx, TSNode node);
+const CBMType *c_eval_expr_type(CLSPContext *ctx, TSNode node);
+const CBMType *c_parse_type_node(CLSPContext *ctx, TSNode node);
+void c_process_statement(CLSPContext *ctx, TSNode node);
// Look up a member (method/field) on a type, traversing base classes.
-const CBMRegisteredFunc* c_lookup_member(CLSPContext* ctx, const char* type_qn, const char* member_name);
+const CBMRegisteredFunc *c_lookup_member(CLSPContext *ctx, const char *type_qn,
+ const char *member_name);
// Type simplification: unwrap refs, aliases, pointers (like clangd simplifyType).
-const CBMType* c_simplify_type(CLSPContext* ctx, const CBMType* t, bool unwrap_pointer);
+const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_pointer);
// --- Entry points ---
// Single-file LSP: build registry from file defs + stdlib, run resolution.
-void cbm_run_c_lsp(CBMArena* arena, CBMFileResult* result,
- const char* source, int source_len, TSNode root, bool cpp_mode);
+void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root, bool cpp_mode);
// Cross-file LSP: build registry from defs + stdlib, re-parse and resolve.
-void cbm_run_c_lsp_cross(
- CBMArena* arena,
- const char* source, int source_len,
- const char* module_qn,
- bool cpp_mode,
- CBMLSPDef* defs, int def_count,
- const char** include_paths, const char** include_ns_qns, int include_count,
- TSTree* cached_tree, // NULL = parse internally
- CBMResolvedCallArray* out);
+void cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn,
+ bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths,
+ const char **include_ns_qns, int include_count,
+ TSTree *cached_tree, // NULL = parse internally
+ CBMResolvedCallArray *out);
// Tier 2: build a project-wide C/C++/CUDA registry ONCE from all defs
// (filters by lang). Shared READ-ONLY across resolve workers. Def-driven
// (no AST field collection) → identical entries to the per-file build.
-CBMTypeRegistry* cbm_c_build_cross_registry(CBMArena* arena, CBMLSPDef* defs, int def_count);
+CBMTypeRegistry *cbm_c_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, int def_count);
// Cross-file LSP using a pre-built shared registry (Tier 2). Skips the
// per-file registry build; just parse + resolve.
-void cbm_run_c_lsp_cross_with_registry(
- CBMArena* arena,
- const char* source, int source_len,
- const char* module_qn,
- bool cpp_mode,
- CBMTypeRegistry* reg, // pre-built, finalized, READ-ONLY
- const char** include_paths, const char** include_ns_qns, int include_count,
- TSTree* cached_tree, // NULL = parse internally
- CBMResolvedCallArray* out);
+void cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
+ const char *module_qn, bool cpp_mode,
+ CBMTypeRegistry *reg, // pre-built, finalized, READ-ONLY
+ const char **include_paths, const char **include_ns_qns,
+ int include_count,
+ TSTree *cached_tree, // NULL = parse internally
+ CBMResolvedCallArray *out);
// Register C stdlib types and functions into a registry.
-void cbm_c_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena);
+void cbm_c_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
// Register C++ stdlib types and functions into a registry.
-void cbm_cpp_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena);
+void cbm_cpp_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
// --- Batch cross-file LSP ---
// Per-file input for batch C/C++ LSP processing.
typedef struct {
- const char* source;
+ const char *source;
int source_len;
- const char* module_qn;
+ const char *module_qn;
bool cpp_mode;
- TSTree* cached_tree; // from TSTree caching (NULL = parse internally)
- CBMLSPDef* defs; // combined file-local + cross-file defs
+ TSTree *cached_tree; // from TSTree caching (NULL = parse internally)
+ CBMLSPDef *defs; // combined file-local + cross-file defs
int def_count;
- const char** include_paths; // parallel arrays, include_count long
- const char** include_ns_qns;
+ const char **include_paths; // parallel arrays, include_count long
+ const char **include_ns_qns;
int include_count;
} CBMBatchCLSPFile;
// Process multiple C/C++ files' cross-file LSP in one CGo call.
// out must point to file_count pre-zeroed CBMResolvedCallArray structs.
-void cbm_batch_c_lsp_cross(
- CBMArena* arena,
- CBMBatchCLSPFile* files, int file_count,
- CBMResolvedCallArray* out);
+void cbm_batch_c_lsp_cross(CBMArena *arena, CBMBatchCLSPFile *files, int file_count,
+ CBMResolvedCallArray *out);
#endif // CBM_LSP_C_LSP_H
diff --git a/internal/cbm/lsp/java_lsp.c b/internal/cbm/lsp/java_lsp.c
index 48e8284ae..fd9bf22ff 100644
--- a/internal/cbm/lsp/java_lsp.c
+++ b/internal/cbm/lsp/java_lsp.c
@@ -42,6 +42,7 @@
#define JAVA_LSP_MAX_EVAL_DEPTH 32
#define JAVA_LSP_MAX_STMT_DEPTH 256
+#define JAVA_LSP_MAX_WALK_DEPTH 512
#define JAVA_LSP_MAX_INHERIT_HOPS 32
#define JAVA_LSP_MAX_OVERLOADS 64
#define JAVA_LSP_BUF 1024
@@ -2678,7 +2679,23 @@ static const CBMRegisteredFunc *lookup_method_for_call(JavaLSPContext *ctx, TSNo
/* Walk every node beneath `node`, calling resolve_method_call on each
* method_invocation / object_creation_expression and recursing into block
* children with proper scope handling. */
+static void java_resolve_calls_in_node_inner(JavaLSPContext *ctx, TSNode node);
+
+/* Depth-guarded entry: the AST walk recurses per nesting level and crashed
+ * with a stack overflow on pathologically nested real-world sources
+ * (elasticsearch, SIGSEGV in bind_lambda_args under hundreds of recursive
+ * java_resolve_calls_in_node frames). Past the cap the subtree is skipped —
+ * its calls stay unresolved, which is graceful degradation, not a crash. */
static void java_resolve_calls_in_node(JavaLSPContext *ctx, TSNode node) {
+ if (ctx->walk_depth >= JAVA_LSP_MAX_WALK_DEPTH) {
+ return;
+ }
+ ctx->walk_depth++;
+ java_resolve_calls_in_node_inner(ctx, node);
+ ctx->walk_depth--;
+}
+
+static void java_resolve_calls_in_node_inner(JavaLSPContext *ctx, TSNode node) {
if (ts_node_is_null(node))
return;
const char *kind = ts_node_type(node);
diff --git a/internal/cbm/lsp/java_lsp.h b/internal/cbm/lsp/java_lsp.h
index 6bae01932..f8b149494 100644
--- a/internal/cbm/lsp/java_lsp.h
+++ b/internal/cbm/lsp/java_lsp.h
@@ -33,12 +33,12 @@
#include "scope.h"
#include "type_registry.h"
#include "../cbm.h"
-#include "go_lsp.h" /* CBMLSPDef, CBMResolvedCallArray reused across languages */
+#include "go_lsp.h" /* CBMLSPDef, CBMResolvedCallArray reused across languages */
/* Java `use`-style import kinds. Mirrors PHP's enum with Java semantics. */
enum {
- CBM_JAVA_IMPORT_TYPE = 0, /* import com.foo.Bar; — type import */
- CBM_JAVA_IMPORT_STATIC = 1, /* import static com.foo.Bar.method; */
+ CBM_JAVA_IMPORT_TYPE = 0, /* import com.foo.Bar; — type import */
+ CBM_JAVA_IMPORT_STATIC = 1, /* import static com.foo.Bar.method; */
CBM_JAVA_IMPORT_ON_DEMAND = 2, /* import com.foo.*; — package on-demand */
CBM_JAVA_IMPORT_STATIC_OD = 3, /* import static com.foo.Bar.*; */
};
@@ -72,10 +72,10 @@ typedef struct {
int import_cap;
/* Current enclosing context. */
- const char *enclosing_method_qn; /* QN of the nearest method/ctor */
- const char *enclosing_class_qn; /* QN of the nearest class/interface/enum */
- const char *enclosing_super_qn; /* QN of the immediate superclass (NULL ⇒ Object) */
- const char *enclosing_class_short; /* short name of enclosing class — for "this" + ctor */
+ const char *enclosing_method_qn; /* QN of the nearest method/ctor */
+ const char *enclosing_class_qn; /* QN of the nearest class/interface/enum */
+ const char *enclosing_super_qn; /* QN of the immediate superclass (NULL ⇒ Object) */
+ const char *enclosing_class_short; /* short name of enclosing class — for "this" + ctor */
const char **enclosing_class_stack; /* nested-class stack (enclosing_class_qn at each depth) */
int enclosing_class_depth;
int enclosing_class_cap;
@@ -86,6 +86,7 @@ typedef struct {
/* Recursion guards. */
int eval_depth;
int statement_depth;
+ int walk_depth; /* java_resolve_calls_in_node self-recursion (AST nesting) */
/* Debug mode (CBM_LSP_DEBUG env). */
bool debug;
@@ -94,8 +95,8 @@ typedef struct {
/* ── Initialization / configuration ───────────────────────────────── */
void java_lsp_init(JavaLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
- const CBMTypeRegistry *registry, const char *package_name,
- const char *module_qn, CBMResolvedCallArray *out);
+ const CBMTypeRegistry *registry, const char *package_name, const char *module_qn,
+ CBMResolvedCallArray *out);
void java_lsp_add_import(JavaLSPContext *ctx, const char *local_name, const char *target_qn,
int kind);
@@ -128,7 +129,7 @@ const CBMRegisteredFunc *java_lookup_method(JavaLSPContext *ctx, const char *cla
/* Lookup a field on a class, walking the super-chain. Returns the field's
* type, or cbm_type_unknown() on miss. */
const CBMType *java_lookup_field_type(JavaLSPContext *ctx, const char *class_qn,
- const char *field_name);
+ const char *field_name);
/* ── Top-level entry points ───────────────────────────────────────── */
diff --git a/internal/cbm/lsp/ts_lsp.c b/internal/cbm/lsp/ts_lsp.c
index 048b3a459..286998a16 100644
--- a/internal/cbm/lsp/ts_lsp.c
+++ b/internal/cbm/lsp/ts_lsp.c
@@ -41,15 +41,15 @@ extern const TSLanguage *tree_sitter_javascript(void);
// ── Forward declarations ──────────────────────────────────────────────────────
-static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, const char* module_qn);
-static void process_node(TSLSPContext* ctx, TSNode node);
-static void process_function_body(TSLSPContext* ctx, TSNode body, const char* func_qn,
- const char* class_qn);
-static const CBMType* type_of_identifier(TSLSPContext* ctx, const char* name);
-static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv, const char* name);
-static const CBMRegisteredFunc* lookup_method(TSLSPContext* ctx, const CBMType* recv,
- const char* method_name);
-static char* node_text(TSLSPContext* ctx, TSNode node);
+static const CBMType *parse_ts_type_text(CBMArena *arena, const char *text, const char *module_qn);
+static void process_node(TSLSPContext *ctx, TSNode node);
+static void process_function_body(TSLSPContext *ctx, TSNode body, const char *func_qn,
+ const char *class_qn);
+static const CBMType *type_of_identifier(TSLSPContext *ctx, const char *name);
+static const CBMType *lookup_member_type(TSLSPContext *ctx, const CBMType *recv, const char *name);
+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
@@ -58,12 +58,14 @@ static char* node_text(TSLSPContext* ctx, TSNode node);
// 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) {
+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;
+ 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)) {
@@ -75,35 +77,39 @@ static TSNode* collect_children(CBMArena* arena, TSNode node, uint32_t* out_n) {
*out_n = kn;
return kids;
}
-static const CBMType* simplify_type(TSLSPContext* ctx, const CBMType* t);
-static const CBMType* unwrap_passthrough_template(const CBMType* t);
+static const CBMType *simplify_type(TSLSPContext *ctx, const CBMType *t);
+static const CBMType *unwrap_passthrough_template(const CBMType *t);
// ── Helpers ───────────────────────────────────────────────────────────────────
-static char* node_text(TSLSPContext* ctx, TSNode node) {
+static char *node_text(TSLSPContext *ctx, TSNode node) {
return cbm_node_text(ctx->arena, node, ctx->source);
}
-static bool node_kind_is(TSNode node, const char* kind) {
- if (ts_node_is_null(node)) return false;
+static bool node_kind_is(TSNode node, const char *kind) {
+ if (ts_node_is_null(node))
+ return false;
return strcmp(ts_node_type(node), kind) == 0;
}
// Find the first named child of `node` whose kind matches one of the listed kinds.
-static TSNode find_first_kind(TSNode node, const char* kind) {
- if (ts_node_is_null(node)) return node;
+static TSNode find_first_kind(TSNode node, const char *kind) {
+ if (ts_node_is_null(node))
+ return node;
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(node, i);
- if (!ts_node_is_null(c) && strcmp(ts_node_type(c), kind) == 0) return c;
+ if (!ts_node_is_null(c) && strcmp(ts_node_type(c), kind) == 0)
+ return c;
}
TSNode null_node = {0};
return null_node;
}
-static void ts_emit_resolved_call(TSLSPContext* ctx, const char* callee_qn,
- const char* strategy, float confidence) {
- if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn) return;
+static void ts_emit_resolved_call(TSLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence) {
+ if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
+ return;
CBMResolvedCall rc;
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
@@ -113,8 +119,9 @@ static void ts_emit_resolved_call(TSLSPContext* ctx, const char* callee_qn,
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
-static void ts_emit_unresolved_call(TSLSPContext* ctx, const char* expr_text, const char* reason) {
- if (!ctx || !ctx->resolved_calls || !ctx->enclosing_func_qn) return;
+static void ts_emit_unresolved_call(TSLSPContext *ctx, const char *expr_text, const char *reason) {
+ if (!ctx || !ctx->resolved_calls || !ctx->enclosing_func_qn)
+ return;
CBMResolvedCall rc;
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
@@ -130,70 +137,83 @@ static void ts_emit_unresolved_call(TSLSPContext* ctx, const char* expr_text, co
//
// Trims leading whitespace, leading ":" (TS type-annotation prefix produced by
// `cbm_node_text` on a `type_annotation` AST node), and trailing whitespace/`;`.
-static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, const char* module_qn) {
- if (!text || !text[0]) return cbm_type_unknown();
+static const CBMType *parse_ts_type_text(CBMArena *arena, const char *text, const char *module_qn) {
+ if (!text || !text[0])
+ return cbm_type_unknown();
// Strip leading whitespace, then a leading ':' (type annotation), then more whitespace.
- while (*text == ' ' || *text == '\t' || *text == '\n' || *text == '\r') text++;
- if (*text == ':') text++;
- while (*text == ' ' || *text == '\t' || *text == '\n' || *text == '\r') text++;
+ while (*text == ' ' || *text == '\t' || *text == '\n' || *text == '\r')
+ text++;
+ if (*text == ':')
+ text++;
+ while (*text == ' ' || *text == '\t' || *text == '\n' || *text == '\r')
+ text++;
size_t len = strlen(text);
- while (len > 0 && (text[len - 1] == ' ' || text[len - 1] == '\t' ||
- text[len - 1] == '\n' || text[len - 1] == '\r' ||
- text[len - 1] == ';' || text[len - 1] == ',')) len--;
- if (len == 0) return cbm_type_unknown();
+ while (len > 0 && (text[len - 1] == ' ' || text[len - 1] == '\t' || text[len - 1] == '\n' ||
+ text[len - 1] == '\r' || text[len - 1] == ';' || text[len - 1] == ','))
+ len--;
+ if (len == 0)
+ return cbm_type_unknown();
// Function type `(params) => returnType` (TS function type literal).
if (text[0] == '(') {
int depth = 0;
size_t close = (size_t)-1;
for (size_t i = 0; i < len; i++) {
- if (text[i] == '(') depth++;
+ if (text[i] == '(')
+ depth++;
else if (text[i] == ')') {
depth--;
- if (depth == 0) { close = i; break; }
+ if (depth == 0) {
+ close = i;
+ break;
+ }
}
}
- if (close == (size_t)-1) return cbm_type_unknown();
+ if (close == (size_t)-1)
+ return cbm_type_unknown();
size_t after = close + 1;
- while (after < len && (text[after] == ' ' || text[after] == '\t')) after++;
+ while (after < len && (text[after] == ' ' || text[after] == '\t'))
+ after++;
if (after + 2 <= len && text[after] == '=' && text[after + 1] == '>') {
// Parse return type.
- const char* ret_text = text + after + 2;
- const CBMType* ret = parse_ts_type_text(arena, ret_text, module_qn);
+ const char *ret_text = text + after + 2;
+ const CBMType *ret = parse_ts_type_text(arena, ret_text, module_qn);
// Parse params: split by top-level commas, each "name: type" or just "type".
- const char* fn_param_names[16] = {0};
- const CBMType* fn_param_types[16] = {0};
+ const char *fn_param_names[16] = {0};
+ const CBMType *fn_param_types[16] = {0};
int pc = 0;
- const char* params_text = text + 1;
+ const char *params_text = text + 1;
size_t params_len = close - 1;
if (params_len > 0) {
size_t start = 0;
int pdepth = 0;
for (size_t i = 0; i <= params_len && pc < 15; i++) {
char c = (i < params_len) ? params_text[i] : ',';
- if (c == '(' || c == '<' || c == '[') pdepth++;
- else if (c == ')' || c == '>' || c == ']') pdepth--;
+ if (c == '(' || c == '<' || c == '[')
+ pdepth++;
+ else if (c == ')' || c == '>' || c == ']')
+ pdepth--;
else if (c == ',' && pdepth == 0) {
if (i > start) {
- char* part = cbm_arena_strndup(arena, params_text + start,
- i - start);
- char* colon = strchr(part, ':');
+ char *part = cbm_arena_strndup(arena, params_text + start, i - start);
+ char *colon = strchr(part, ':');
if (colon) {
*colon = '\0';
- const char* nm = part;
- while (*nm == ' ' || *nm == '\t') nm++;
+ const char *nm = part;
+ while (*nm == ' ' || *nm == '\t')
+ nm++;
size_t nl = strlen(nm);
- while (nl > 0 && (nm[nl - 1] == ' ' || nm[nl - 1] == '?')) nl--;
+ while (nl > 0 && (nm[nl - 1] == ' ' || nm[nl - 1] == '?'))
+ nl--;
fn_param_names[pc] = cbm_arena_strndup(arena, nm, nl);
- fn_param_types[pc] = parse_ts_type_text(arena, colon + 1,
- module_qn);
+ fn_param_types[pc] =
+ parse_ts_type_text(arena, colon + 1, module_qn);
} else {
fn_param_names[pc] = cbm_arena_sprintf(arena, "_%d", pc);
- fn_param_types[pc] = parse_ts_type_text(arena, part,
- module_qn);
+ fn_param_types[pc] = parse_ts_type_text(arena, part, module_qn);
}
pc++;
}
@@ -203,7 +223,7 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
}
fn_param_names[pc] = NULL;
fn_param_types[pc] = NULL;
- const CBMType* rets[2] = {ret, NULL};
+ const CBMType *rets[2] = {ret, NULL};
return cbm_type_func(arena, fn_param_names, fn_param_types, rets);
}
// Parens without arrow → return UNKNOWN.
@@ -211,7 +231,8 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
}
// Object type literal `{...}` and other unhandled — return UNKNOWN.
- if (text[0] == '{') return cbm_type_unknown();
+ if (text[0] == '{')
+ return cbm_type_unknown();
// TS polymorphic `this` return type: emit a TYPE_PARAM("this") sentinel that
// ts_eval_expr_type / lookup_method substitute back to the actual receiver at
@@ -230,39 +251,41 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
size_t colon_pos = (size_t)-1;
for (size_t i = 0; i < len; i++) {
char c = text[i];
- if (c == '<' || c == '[' || c == '(') depth++;
- else if (c == '>' || c == ']' || c == ')') depth--;
- if (depth != 0) continue;
- if (ext_pos == (size_t)-1 && i > 0 && text[i] == ' ' &&
- i + 9 <= len && memcmp(text + i, " extends ", 9) == 0) {
+ if (c == '<' || c == '[' || c == '(')
+ depth++;
+ else if (c == '>' || c == ']' || c == ')')
+ depth--;
+ if (depth != 0)
+ continue;
+ if (ext_pos == (size_t)-1 && i > 0 && text[i] == ' ' && i + 9 <= len &&
+ memcmp(text + i, " extends ", 9) == 0) {
ext_pos = i;
i += 8;
continue;
}
- if (ext_pos != (size_t)-1 && q_pos == (size_t)-1 &&
- i + 3 <= len && text[i] == ' ' && text[i + 1] == '?' && text[i + 2] == ' ') {
+ if (ext_pos != (size_t)-1 && q_pos == (size_t)-1 && i + 3 <= len && text[i] == ' ' &&
+ text[i + 1] == '?' && text[i + 2] == ' ') {
q_pos = i;
i += 2;
continue;
}
- if (q_pos != (size_t)-1 && colon_pos == (size_t)-1 &&
- i + 3 <= len && text[i] == ' ' && text[i + 1] == ':' && text[i + 2] == ' ') {
+ if (q_pos != (size_t)-1 && colon_pos == (size_t)-1 && i + 3 <= len && text[i] == ' ' &&
+ text[i + 1] == ':' && text[i + 2] == ' ') {
colon_pos = i;
break;
}
}
if (ext_pos != (size_t)-1 && q_pos != (size_t)-1 && colon_pos != (size_t)-1) {
- char* check_text = cbm_arena_strndup(arena, text, ext_pos);
- char* extends_text = cbm_arena_strndup(arena, text + ext_pos + 9,
- q_pos - (ext_pos + 9));
- char* true_text = cbm_arena_strndup(arena, text + q_pos + 3,
- colon_pos - (q_pos + 3));
- char* false_text = cbm_arena_strndup(arena, text + colon_pos + 3,
- len - (colon_pos + 3));
- const CBMType* check = parse_ts_type_text(arena, check_text, module_qn);
- const CBMType* extends = parse_ts_type_text(arena, extends_text, module_qn);
- const CBMType* true_branch = parse_ts_type_text(arena, true_text, module_qn);
- const CBMType* false_branch = parse_ts_type_text(arena, false_text, module_qn);
+ char *check_text = cbm_arena_strndup(arena, text, ext_pos);
+ char *extends_text =
+ cbm_arena_strndup(arena, text + ext_pos + 9, q_pos - (ext_pos + 9));
+ char *true_text = cbm_arena_strndup(arena, text + q_pos + 3, colon_pos - (q_pos + 3));
+ char *false_text =
+ cbm_arena_strndup(arena, text + colon_pos + 3, len - (colon_pos + 3));
+ const CBMType *check = parse_ts_type_text(arena, check_text, module_qn);
+ const CBMType *extends = parse_ts_type_text(arena, extends_text, module_qn);
+ const CBMType *true_branch = parse_ts_type_text(arena, true_text, module_qn);
+ const CBMType *false_branch = parse_ts_type_text(arena, false_text, module_qn);
return cbm_type_conditional(arena, check, extends, true_branch, false_branch);
}
}
@@ -270,44 +293,50 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// `infer X` — emit CBM_TYPE_INFER. Only meaningful inside conditional `extends`
// patterns; emitted standalone here and matched later by eval_conditional.
if (len > 6 && memcmp(text, "infer ", 6) == 0) {
- const char* rest = text + 6;
- while (*rest == ' ' || *rest == '\t') rest++;
- const char* end = rest;
- while (*end && *end != ' ' && *end != '\t') end++;
- char* name = cbm_arena_strndup(arena, rest, (size_t)(end - rest));
+ const char *rest = text + 6;
+ while (*rest == ' ' || *rest == '\t')
+ rest++;
+ const char *end = rest;
+ while (*end && *end != ' ' && *end != '\t')
+ end++;
+ char *name = cbm_arena_strndup(arena, rest, (size_t)(end - rest));
return cbm_type_infer(arena, name);
}
// `keyof T` — emit CBM_TYPE_KEYOF for downstream evaluation.
if (len > 6 && memcmp(text, "keyof ", 6) == 0) {
- const char* rest = text + 6;
- while (*rest == ' ' || *rest == '\t') rest++;
- char* rest_term = cbm_arena_strdup(arena, rest);
- const CBMType* operand = parse_ts_type_text(arena, rest_term, module_qn);
+ const char *rest = text + 6;
+ while (*rest == ' ' || *rest == '\t')
+ rest++;
+ char *rest_term = cbm_arena_strdup(arena, rest);
+ const CBMType *operand = parse_ts_type_text(arena, rest_term, module_qn);
return cbm_type_keyof(arena, operand);
}
// `typeof X` in type position — emit CBM_TYPE_TYPEOF_QUERY.
if (len > 7 && memcmp(text, "typeof ", 7) == 0) {
- const char* rest = text + 7;
- while (*rest == ' ' || *rest == '\t') rest++;
+ const char *rest = text + 7;
+ while (*rest == ' ' || *rest == '\t')
+ rest++;
return cbm_type_typeof_query(arena, rest);
}
// Tuple `[T, U]` — first char `[`, balanced. Build TUPLE.
if (text[0] == '[' && len >= 2 && text[len - 1] == ']') {
- const char* inner_text = text + 1;
+ const char *inner_text = text + 1;
size_t inner_len = len - 2;
- const CBMType* elems[16] = {0};
+ const CBMType *elems[16] = {0};
int ec = 0;
size_t start = 0;
int depth = 0;
for (size_t i = 0; i <= inner_len && ec < 15; i++) {
char c = (i < inner_len) ? inner_text[i] : ',';
- if (c == '<' || c == '[') depth++;
- else if (c == '>' || c == ']') depth--;
+ if (c == '<' || c == '[')
+ depth++;
+ else if (c == '>' || c == ']')
+ depth--;
else if (c == ',' && depth == 0) {
- char* part = cbm_arena_strndup(arena, inner_text + start, i - start);
+ char *part = cbm_arena_strndup(arena, inner_text + start, i - start);
elems[ec++] = parse_ts_type_text(arena, part, module_qn);
start = i + 1;
}
@@ -319,23 +348,27 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// Top-level UNION ` | ` or INTERSECTION ` & ` — split at depth 0 (outside <>, []).
{
int depth = 0;
- const CBMType* members[16] = {0};
+ const CBMType *members[16] = {0};
int mc = 0;
size_t start = 0;
bool is_union = false;
bool is_inter = false;
for (size_t i = 0; i < len; i++) {
char c = text[i];
- if (c == '<' || c == '[') depth++;
- else if (c == '>' || c == ']') depth--;
- else if (depth == 0 && (c == '|' || c == '&') &&
- i > 0 && (text[i - 1] == ' ' || text[i - 1] == '\t')) {
+ if (c == '<' || c == '[')
+ depth++;
+ else if (c == '>' || c == ']')
+ depth--;
+ else if (depth == 0 && (c == '|' || c == '&') && i > 0 &&
+ (text[i - 1] == ' ' || text[i - 1] == '\t')) {
if (mc < 15) {
- char* part = cbm_arena_strndup(arena, text + start, i - start);
+ char *part = cbm_arena_strndup(arena, text + start, i - start);
members[mc++] = parse_ts_type_text(arena, part, module_qn);
}
- if (c == '|') is_union = true;
- else is_inter = true;
+ if (c == '|')
+ is_union = true;
+ else
+ is_inter = true;
start = i + 1;
}
}
@@ -345,7 +378,7 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// a union/intersection with >=16 members overflows the array
// (UBSan: index 16 out of bounds for 'const CBMType *[16]').
if (mc < 15) {
- char* part = cbm_arena_strndup(arena, text + start, len - start);
+ char *part = cbm_arena_strndup(arena, text + start, len - start);
members[mc++] = parse_ts_type_text(arena, part, module_qn);
}
members[mc] = NULL;
@@ -355,9 +388,9 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
}
// Builtins / predefined type keywords.
- static const char* const builtins[] = {
- "string", "number", "boolean", "bigint", "any", "unknown", "void", "never",
- "null", "undefined", "object", "symbol", NULL,
+ static const char *const builtins[] = {
+ "string", "number", "boolean", "bigint", "any", "unknown", "void",
+ "never", "null", "undefined", "object", "symbol", NULL,
};
for (int i = 0; builtins[i]; i++) {
size_t bl = strlen(builtins[i]);
@@ -368,9 +401,9 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// Trailing `[]` → Array<elem>. Strip and recurse.
if (len >= 2 && text[len - 1] == ']' && text[len - 2] == '[') {
- char* inner = cbm_arena_strndup(arena, text, len - 2);
- const CBMType* elem = parse_ts_type_text(arena, inner, module_qn);
- const CBMType* args[2] = {elem, NULL};
+ char *inner = cbm_arena_strndup(arena, text, len - 2);
+ const CBMType *elem = parse_ts_type_text(arena, inner, module_qn);
+ const CBMType *args[2] = {elem, NULL};
return cbm_type_template(arena, "Array", args, 1);
}
@@ -378,29 +411,35 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
if (len > 2 && text[len - 1] == '>') {
int depth = 0;
size_t open = (size_t)-1;
- for (size_t i = len; i-- > 0; ) {
+ for (size_t i = len; i-- > 0;) {
char c = text[i];
- if (c == '>') depth++;
+ if (c == '>')
+ depth++;
else if (c == '<') {
depth--;
- if (depth == 0) { open = i; break; }
+ if (depth == 0) {
+ open = i;
+ break;
+ }
}
}
if (open != (size_t)-1 && open > 0) {
- char* base = cbm_arena_strndup(arena, text, open);
- const char* args_text = text + open + 1;
+ char *base = cbm_arena_strndup(arena, text, open);
+ const char *args_text = text + open + 1;
size_t args_len = (len - 1) - (open + 1);
// Split args by top-level commas.
- const CBMType* args[16] = {0};
+ const CBMType *args[16] = {0};
int arg_count = 0;
size_t start = 0;
int adepth = 0;
for (size_t i = 0; i <= args_len && arg_count < 15; i++) {
char c = (i < args_len) ? args_text[i] : ',';
- if (c == '<') adepth++;
- else if (c == '>') adepth--;
+ if (c == '<')
+ adepth++;
+ else if (c == '>')
+ adepth--;
else if (c == ',' && adepth == 0) {
- char* part = cbm_arena_strndup(arena, args_text + start, i - start);
+ char *part = cbm_arena_strndup(arena, args_text + start, i - start);
args[arg_count++] = parse_ts_type_text(arena, part, module_qn);
start = i + 1;
}
@@ -410,25 +449,63 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// `Container<number>` becomes TEMPLATE("test.main.Container", [number]).
// Stdlib bases (Array, Promise, Map, Set, Object) stay bare so they match
// the stdlib registration.
- const char* qualified_base = base;
- static const char* const stdlib_names[] = {
- "Array", "Promise", "Map", "Set", "WeakMap", "WeakSet",
- "ReadonlyArray", "Iterable", "Iterator", "Generator",
- "AsyncIterable", "AsyncIterator", "AsyncGenerator",
- "Object", "String", "Number", "Boolean", "BigInt", "Symbol",
- "Function", "Date", "RegExp", "Error", "Partial", "Required",
- "Readonly", "Pick", "Omit", "Record", "Exclude", "Extract",
- "NonNullable", "Parameters", "ReturnType", "Awaited",
- "ThisType", "InstanceType", "ConstructorParameters",
- "Uppercase", "Lowercase", "Capitalize", "Uncapitalize",
- "NodeList", "HTMLCollection", NULL,
+ const char *qualified_base = base;
+ static const char *const stdlib_names[] = {
+ "Array",
+ "Promise",
+ "Map",
+ "Set",
+ "WeakMap",
+ "WeakSet",
+ "ReadonlyArray",
+ "Iterable",
+ "Iterator",
+ "Generator",
+ "AsyncIterable",
+ "AsyncIterator",
+ "AsyncGenerator",
+ "Object",
+ "String",
+ "Number",
+ "Boolean",
+ "BigInt",
+ "Symbol",
+ "Function",
+ "Date",
+ "RegExp",
+ "Error",
+ "Partial",
+ "Required",
+ "Readonly",
+ "Pick",
+ "Omit",
+ "Record",
+ "Exclude",
+ "Extract",
+ "NonNullable",
+ "Parameters",
+ "ReturnType",
+ "Awaited",
+ "ThisType",
+ "InstanceType",
+ "ConstructorParameters",
+ "Uppercase",
+ "Lowercase",
+ "Capitalize",
+ "Uncapitalize",
+ "NodeList",
+ "HTMLCollection",
+ NULL,
};
bool is_stdlib = false;
for (int sl = 0; stdlib_names[sl]; sl++) {
- if (strcmp(base, stdlib_names[sl]) == 0) { is_stdlib = true; break; }
+ if (strcmp(base, stdlib_names[sl]) == 0) {
+ is_stdlib = true;
+ break;
+ }
}
- if (!is_stdlib && module_qn && strchr(base, '.') == NULL &&
- base[0] >= 'A' && base[0] <= 'Z') {
+ if (!is_stdlib && module_qn && strchr(base, '.') == NULL && base[0] >= 'A' &&
+ base[0] <= 'Z') {
qualified_base = cbm_arena_sprintf(arena, "%s.%s", module_qn, base);
}
return cbm_type_template(arena, qualified_base, args, arg_count);
@@ -439,22 +516,57 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// will check both the QN as-given and module-qualified variants.
if (module_qn && strchr(text, '.') == NULL) {
// Stdlib names stay bare so they match the stdlib registration QNs.
- static const char* const bare_stdlib_names[] = {
- "Array", "Promise", "Map", "Set", "WeakMap", "WeakSet",
- "ReadonlyArray", "Iterable", "Iterator", "Generator",
- "AsyncIterable", "AsyncIterator", "AsyncGenerator",
- "Object", "String", "Number", "Boolean", "BigInt", "Symbol",
- "Function", "Date", "RegExp", "Error", "Math", "JSON",
+ static const char *const bare_stdlib_names[] = {
+ "Array",
+ "Promise",
+ "Map",
+ "Set",
+ "WeakMap",
+ "WeakSet",
+ "ReadonlyArray",
+ "Iterable",
+ "Iterator",
+ "Generator",
+ "AsyncIterable",
+ "AsyncIterator",
+ "AsyncGenerator",
+ "Object",
+ "String",
+ "Number",
+ "Boolean",
+ "BigInt",
+ "Symbol",
+ "Function",
+ "Date",
+ "RegExp",
+ "Error",
+ "Math",
+ "JSON",
"console",
// DOM essentials
- "Element", "HTMLElement", "Document", "Window", "Node",
- "EventTarget", "Event", "Response", "Request", "Headers",
- "URL", "URLSearchParams", "FormData", "Blob", "File",
- "NodeList", "HTMLCollection", "JSX",
+ "Element",
+ "HTMLElement",
+ "Document",
+ "Window",
+ "Node",
+ "EventTarget",
+ "Event",
+ "Response",
+ "Request",
+ "Headers",
+ "URL",
+ "URLSearchParams",
+ "FormData",
+ "Blob",
+ "File",
+ "NodeList",
+ "HTMLCollection",
+ "JSX",
NULL,
};
- char* terminated = cbm_arena_strndup(arena, text, len);
- if (!terminated) return cbm_type_unknown();
+ char *terminated = cbm_arena_strndup(arena, text, len);
+ if (!terminated)
+ return cbm_type_unknown();
for (int i = 0; bare_stdlib_names[i]; i++) {
if (strcmp(terminated, bare_stdlib_names[i]) == 0) {
return cbm_type_named(arena, terminated);
@@ -463,7 +575,7 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
// Bare uppercase identifier — qualify against the current module if it looks
// like a TypeIdent. Lower-case names are likely params/values, fall back.
if ((terminated[0] >= 'A' && terminated[0] <= 'Z')) {
- const char* qn = cbm_arena_sprintf(arena, "%s.%s", module_qn, terminated);
+ const char *qn = cbm_arena_sprintf(arena, "%s.%s", module_qn, terminated);
return cbm_type_named(arena, qn);
}
return cbm_type_named(arena, terminated);
@@ -472,15 +584,19 @@ static const CBMType* parse_ts_type_text(CBMArena* arena, const char* text, cons
}
// Return param-type CBMType array from a CBMDefinition's param_types text array.
-static const CBMType** parse_param_types_array(CBMArena* arena, const char** texts,
- const char* module_qn) {
- if (!texts) return NULL;
+static const CBMType **parse_param_types_array(CBMArena *arena, const char **texts,
+ const char *module_qn) {
+ if (!texts)
+ return NULL;
int count = 0;
- while (texts[count]) count++;
- if (count == 0) return NULL;
- const CBMType** arr = (const CBMType**)cbm_arena_alloc(arena,
- (size_t)(count + 1) * sizeof(const CBMType*));
- if (!arr) return NULL;
+ while (texts[count])
+ count++;
+ if (count == 0)
+ return NULL;
+ const CBMType **arr =
+ (const CBMType **)cbm_arena_alloc(arena, (size_t)(count + 1) * sizeof(const CBMType *));
+ if (!arr)
+ return NULL;
for (int i = 0; i < count; i++) {
arr[i] = parse_ts_type_text(arena, texts[i], module_qn);
}
@@ -522,52 +638,63 @@ static const CBMType** parse_param_types_array(CBMArena* arena, const char** tex
#define TS_RELATER_CACHE_SIZE 256
typedef struct {
- const CBMType* a;
- const CBMType* b;
- int8_t result; // -1 = unknown, 0 = false, 1 = true
+ const CBMType *a;
+ const CBMType *b;
+ int8_t result; // -1 = unknown, 0 = false, 1 = true
} TSRelaterCacheSlot;
-static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
- const CBMType* b, int depth,
- TSRelaterCacheSlot* cache);
+static int ts_is_assignable_inner(TSLSPContext *ctx, const CBMType *a, const CBMType *b, int depth,
+ TSRelaterCacheSlot *cache);
-static const CBMType* ts_relater_unwrap(const CBMType* t) {
- if (!t) return t;
- if (t->kind == CBM_TYPE_ALIAS) return cbm_type_resolve_alias(t);
+static const CBMType *ts_relater_unwrap(const CBMType *t) {
+ if (!t)
+ return t;
+ if (t->kind == CBM_TYPE_ALIAS)
+ return cbm_type_resolve_alias(t);
return t;
}
-static bool ts_builtin_compatible(const char* a, const char* b) {
- if (!a || !b) return false;
- if (strcmp(a, b) == 0) return true;
+static bool ts_builtin_compatible(const char *a, const char *b) {
+ if (!a || !b)
+ return false;
+ if (strcmp(a, b) == 0)
+ return true;
// `any` and `unknown` accept anything (handled by caller before this).
return false;
}
-static bool ts_literal_promotes_to_builtin(const CBMType* lit, const CBMType* bi) {
- if (!lit || lit->kind != CBM_TYPE_TS_LITERAL || !lit->data.literal_ts.tag) return false;
- if (!bi || bi->kind != CBM_TYPE_BUILTIN || !bi->data.builtin.name) return false;
+static bool ts_literal_promotes_to_builtin(const CBMType *lit, const CBMType *bi) {
+ if (!lit || lit->kind != CBM_TYPE_TS_LITERAL || !lit->data.literal_ts.tag)
+ return false;
+ if (!bi || bi->kind != CBM_TYPE_BUILTIN || !bi->data.builtin.name)
+ return false;
return strcmp(lit->data.literal_ts.tag, bi->data.builtin.name) == 0;
}
-static bool ts_class_extends(TSLSPContext* ctx, const char* sub_qn, const char* super_qn,
+static bool ts_class_extends(TSLSPContext *ctx, const char *sub_qn, const char *super_qn,
int depth) {
- if (!ctx || !sub_qn || !super_qn) return false;
- if (depth > TS_RELATER_MAX_DEPTH) return false;
- if (strcmp(sub_qn, super_qn) == 0) return true;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, sub_qn);
- if (!rt || !rt->embedded_types) return false;
+ if (!ctx || !sub_qn || !super_qn)
+ return false;
+ if (depth > TS_RELATER_MAX_DEPTH)
+ return false;
+ if (strcmp(sub_qn, super_qn) == 0)
+ return true;
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, sub_qn);
+ if (!rt || !rt->embedded_types)
+ return false;
for (int i = 0; rt->embedded_types[i]; i++) {
- if (ts_class_extends(ctx, rt->embedded_types[i], super_qn, depth + 1)) return true;
+ if (ts_class_extends(ctx, rt->embedded_types[i], super_qn, depth + 1))
+ return true;
}
return false;
}
-static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
- const CBMType* b, int depth,
- TSRelaterCacheSlot* cache) {
- if (depth > TS_RELATER_MAX_DEPTH) return 0;
- if (!a || !b) return 0;
+static int ts_is_assignable_inner(TSLSPContext *ctx, const CBMType *a, const CBMType *b, int depth,
+ TSRelaterCacheSlot *cache) {
+ if (depth > TS_RELATER_MAX_DEPTH)
+ return 0;
+ if (!a || !b)
+ return 0;
// Cache probe (pointer identity is sufficient — arena-stable within a resolver pass).
int slot = (int)((((uintptr_t)a >> 4) ^ ((uintptr_t)b >> 4)) & (TS_RELATER_CACHE_SIZE - 1));
@@ -577,16 +704,20 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
a = ts_relater_unwrap(a);
b = ts_relater_unwrap(b);
- if (!a || !b) return 0;
+ if (!a || !b)
+ return 0;
// any/unknown/never short-circuits.
if (b->kind == CBM_TYPE_BUILTIN && b->data.builtin.name) {
if (strcmp(b->data.builtin.name, "any") == 0 ||
- strcmp(b->data.builtin.name, "unknown") == 0) return 1;
+ strcmp(b->data.builtin.name, "unknown") == 0)
+ return 1;
}
if (a->kind == CBM_TYPE_BUILTIN && a->data.builtin.name) {
- if (strcmp(a->data.builtin.name, "any") == 0) return 1;
- if (strcmp(a->data.builtin.name, "never") == 0) return 1;
+ if (strcmp(a->data.builtin.name, "any") == 0)
+ return 1;
+ if (strcmp(a->data.builtin.name, "never") == 0)
+ return 1;
}
int result = 0;
@@ -595,8 +726,7 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
if (a->kind == CBM_TYPE_UNION && a->data.union_type.members) {
result = 1;
for (int i = 0; i < a->data.union_type.count; i++) {
- if (!ts_is_assignable_inner(ctx, a->data.union_type.members[i], b,
- depth + 1, cache)) {
+ if (!ts_is_assignable_inner(ctx, a->data.union_type.members[i], b, depth + 1, cache)) {
result = 0;
break;
}
@@ -606,8 +736,7 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
// Target unions: source assignable to any member.
if (b->kind == CBM_TYPE_UNION && b->data.union_type.members) {
for (int i = 0; i < b->data.union_type.count; i++) {
- if (ts_is_assignable_inner(ctx, a, b->data.union_type.members[i],
- depth + 1, cache)) {
+ if (ts_is_assignable_inner(ctx, a, b->data.union_type.members[i], depth + 1, cache)) {
result = 1;
break;
}
@@ -617,8 +746,7 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
// Source intersection: any member assignable to target.
if (a->kind == CBM_TYPE_INTERSECTION && a->data.union_type.members) {
for (int i = 0; i < a->data.union_type.count; i++) {
- if (ts_is_assignable_inner(ctx, a->data.union_type.members[i], b,
- depth + 1, cache)) {
+ if (ts_is_assignable_inner(ctx, a->data.union_type.members[i], b, depth + 1, cache)) {
result = 1;
break;
}
@@ -629,8 +757,7 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
if (b->kind == CBM_TYPE_INTERSECTION && b->data.union_type.members) {
result = 1;
for (int i = 0; i < b->data.union_type.count; i++) {
- if (!ts_is_assignable_inner(ctx, a, b->data.union_type.members[i],
- depth + 1, cache)) {
+ if (!ts_is_assignable_inner(ctx, a, b->data.union_type.members[i], depth + 1, cache)) {
result = 0;
break;
}
@@ -657,10 +784,16 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
// Same-kind cases.
switch (a->kind) {
case CBM_TYPE_NAMED: {
- const char* aqn = a->data.named.qualified_name;
- const char* bqn = b->data.named.qualified_name;
- if (!aqn || !bqn) { result = 0; break; }
- if (strcmp(aqn, bqn) == 0) { result = 1; break; }
+ const char *aqn = a->data.named.qualified_name;
+ const char *bqn = b->data.named.qualified_name;
+ if (!aqn || !bqn) {
+ result = 0;
+ break;
+ }
+ if (strcmp(aqn, bqn) == 0) {
+ result = 1;
+ break;
+ }
// class hierarchy: A extends B?
result = ts_class_extends(ctx, aqn, bqn, 0) ? 1 : 0;
break;
@@ -681,7 +814,10 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
case CBM_TYPE_TUPLE: {
int ac = a->data.tuple.count;
int bc = b->data.tuple.count;
- if (ac != bc) { result = 0; break; }
+ if (ac != bc) {
+ result = 0;
+ break;
+ }
result = 1;
for (int i = 0; i < ac; i++) {
if (!ts_is_assignable_inner(ctx, a->data.tuple.elems[i], b->data.tuple.elems[i],
@@ -693,17 +829,22 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
break;
}
case CBM_TYPE_TEMPLATE: {
- const char* an = a->data.template_type.template_name;
- const char* bn = b->data.template_type.template_name;
- if (!an || !bn || strcmp(an, bn) != 0) { result = 0; break; }
+ const char *an = a->data.template_type.template_name;
+ const char *bn = b->data.template_type.template_name;
+ if (!an || !bn || strcmp(an, bn) != 0) {
+ result = 0;
+ break;
+ }
int ac = a->data.template_type.arg_count;
int bcount = b->data.template_type.arg_count;
- if (ac != bcount) { result = 0; break; }
+ if (ac != bcount) {
+ result = 0;
+ break;
+ }
result = 1;
for (int i = 0; i < ac; i++) {
if (!ts_is_assignable_inner(ctx, a->data.template_type.template_args[i],
- b->data.template_type.template_args[i],
- depth + 1, cache)) {
+ b->data.template_type.template_args[i], depth + 1, cache)) {
result = 0;
break;
}
@@ -712,10 +853,10 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
}
case CBM_TYPE_FUNC: {
// Return covariance.
- const CBMType* aret = (a->data.func.return_types && a->data.func.return_types[0])
+ const CBMType *aret = (a->data.func.return_types && a->data.func.return_types[0])
? a->data.func.return_types[0]
: NULL;
- const CBMType* bret = (b->data.func.return_types && b->data.func.return_types[0])
+ const CBMType *bret = (b->data.func.return_types && b->data.func.return_types[0])
? b->data.func.return_types[0]
: NULL;
if (aret && bret && !ts_is_assignable_inner(ctx, aret, bret, depth + 1, cache)) {
@@ -724,14 +865,20 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
}
// Param contravariance + arity tolerance.
int ap = 0, bp = 0;
- if (a->data.func.param_types) while (a->data.func.param_types[ap]) ap++;
- if (b->data.func.param_types) while (b->data.func.param_types[bp]) bp++;
- if (ap > bp) { result = 0; break; } // source needs more params than target supplies
+ if (a->data.func.param_types)
+ while (a->data.func.param_types[ap])
+ ap++;
+ if (b->data.func.param_types)
+ while (b->data.func.param_types[bp])
+ bp++;
+ if (ap > bp) {
+ result = 0;
+ break;
+ } // source needs more params than target supplies
result = 1;
for (int i = 0; i < ap; i++) {
if (!ts_is_assignable_inner(ctx, b->data.func.param_types[i],
- a->data.func.param_types[i],
- depth + 1, cache)) {
+ a->data.func.param_types[i], depth + 1, cache)) {
result = 0;
break;
}
@@ -739,8 +886,8 @@ static int ts_is_assignable_inner(TSLSPContext* ctx, const CBMType* a,
break;
}
case CBM_TYPE_TYPE_PARAM: {
- const char* an = a->data.type_param.name;
- const char* bn = b->data.type_param.name;
+ const char *an = a->data.type_param.name;
+ const char *bn = b->data.type_param.name;
result = (an && bn && strcmp(an, bn) == 0) ? 1 : 0;
break;
}
@@ -757,8 +904,9 @@ done:
}
// Public entry point. Allocates a small per-call cache on the stack.
-static bool ts_is_assignable(TSLSPContext* ctx, const CBMType* a, const CBMType* b) {
- if (!ctx || !a || !b) return false;
+static bool ts_is_assignable(TSLSPContext *ctx, const CBMType *a, const CBMType *b) {
+ if (!ctx || !a || !b)
+ return false;
TSRelaterCacheSlot cache[TS_RELATER_CACHE_SIZE];
for (int i = 0; i < TS_RELATER_CACHE_SIZE; i++) {
cache[i].a = NULL;
@@ -775,22 +923,24 @@ static bool ts_is_assignable(TSLSPContext* ctx, const CBMType* a, const CBMType*
// table. Returns true on full match, false otherwise. Bindings table is OWNED by
// caller (typically stack-allocated).
typedef struct {
- const char* name;
- const CBMType* binding;
+ const char *name;
+ const CBMType *binding;
} TSInferBinding;
#define TS_INFER_MAX 8
-static bool match_with_infer(TSLSPContext* ctx, const CBMType* source,
- const CBMType* pattern, TSInferBinding* binds, int* bind_count,
- int depth) {
- if (depth > 16 || !source || !pattern) return false;
+static bool match_with_infer(TSLSPContext *ctx, const CBMType *source, const CBMType *pattern,
+ TSInferBinding *binds, int *bind_count, int depth) {
+ if (depth > 16 || !source || !pattern)
+ return false;
// Pattern is `infer X`: bind X to source.
if (pattern->kind == CBM_TYPE_INFER) {
- if (*bind_count >= TS_INFER_MAX) return false;
- const char* nm = pattern->data.infer.name;
- if (!nm) return false;
+ if (*bind_count >= TS_INFER_MAX)
+ return false;
+ const char *nm = pattern->data.infer.name;
+ if (!nm)
+ return false;
// Re-bind same name → require identical existing binding (else fail).
for (int i = 0; i < *bind_count; i++) {
if (binds[i].name && strcmp(binds[i].name, nm) == 0) {
@@ -812,46 +962,55 @@ static bool match_with_infer(TSLSPContext* ctx, const CBMType* source,
switch (pattern->kind) {
case CBM_TYPE_TEMPLATE: {
- const char* sn = source->data.template_type.template_name;
- const char* pn = pattern->data.template_type.template_name;
- if (!sn || !pn || strcmp(sn, pn) != 0) return false;
+ const char *sn = source->data.template_type.template_name;
+ const char *pn = pattern->data.template_type.template_name;
+ if (!sn || !pn || strcmp(sn, pn) != 0)
+ return false;
int sc = source->data.template_type.arg_count;
int pc = pattern->data.template_type.arg_count;
- if (sc != pc) return false;
+ if (sc != pc)
+ return false;
for (int i = 0; i < pc; i++) {
if (!match_with_infer(ctx, source->data.template_type.template_args[i],
- pattern->data.template_type.template_args[i],
- binds, bind_count, depth + 1)) return false;
+ pattern->data.template_type.template_args[i], binds, bind_count,
+ depth + 1))
+ return false;
}
return true;
}
case CBM_TYPE_TUPLE: {
int sc = source->data.tuple.count;
int pc = pattern->data.tuple.count;
- if (sc != pc) return false;
+ if (sc != pc)
+ return false;
for (int i = 0; i < pc; i++) {
- if (!match_with_infer(ctx, source->data.tuple.elems[i],
- pattern->data.tuple.elems[i],
- binds, bind_count, depth + 1)) return false;
+ if (!match_with_infer(ctx, source->data.tuple.elems[i], pattern->data.tuple.elems[i],
+ binds, bind_count, depth + 1))
+ return false;
}
return true;
}
case CBM_TYPE_FUNC: {
- const CBMType* sret = source->data.func.return_types ?
- source->data.func.return_types[0] : NULL;
- const CBMType* pret = pattern->data.func.return_types ?
- pattern->data.func.return_types[0] : NULL;
- if (sret && pret &&
- !match_with_infer(ctx, sret, pret, binds, bind_count, depth + 1)) return false;
+ const CBMType *sret =
+ source->data.func.return_types ? source->data.func.return_types[0] : NULL;
+ const CBMType *pret =
+ pattern->data.func.return_types ? pattern->data.func.return_types[0] : NULL;
+ if (sret && pret && !match_with_infer(ctx, sret, pret, binds, bind_count, depth + 1))
+ return false;
// Param-by-param match (positionally).
int sp = 0, pp = 0;
- if (source->data.func.param_types) while (source->data.func.param_types[sp]) sp++;
- if (pattern->data.func.param_types) while (pattern->data.func.param_types[pp]) pp++;
- if (sp != pp) return sp >= pp; // tolerate source having more params than pattern
+ if (source->data.func.param_types)
+ while (source->data.func.param_types[sp])
+ sp++;
+ if (pattern->data.func.param_types)
+ while (pattern->data.func.param_types[pp])
+ pp++;
+ if (sp != pp)
+ return sp >= pp; // tolerate source having more params than pattern
for (int i = 0; i < pp; i++) {
if (!match_with_infer(ctx, source->data.func.param_types[i],
- pattern->data.func.param_types[i],
- binds, bind_count, depth + 1)) return false;
+ pattern->data.func.param_types[i], binds, bind_count, depth + 1))
+ return false;
}
return true;
}
@@ -861,10 +1020,10 @@ static bool match_with_infer(TSLSPContext* ctx, const CBMType* source,
}
// Substitute `infer X` bindings into a type tree (recursive).
-static const CBMType* subst_infer_bindings(TSLSPContext* ctx, const CBMType* t,
- const TSInferBinding* binds, int bind_count,
- int depth) {
- if (!t || depth > 16 || bind_count == 0) return t;
+static const CBMType *subst_infer_bindings(TSLSPContext *ctx, const CBMType *t,
+ const TSInferBinding *binds, int bind_count, int depth) {
+ if (!t || depth > 16 || bind_count == 0)
+ return t;
// TYPE_PARAM matching the bound name → replace with binding's type.
if (t->kind == CBM_TYPE_TYPE_PARAM && t->data.type_param.name) {
for (int i = 0; i < bind_count; i++) {
@@ -878,9 +1037,9 @@ static const CBMType* subst_infer_bindings(TSLSPContext* ctx, const CBMType* t,
// names like `U` to `module.U` since it doesn't know about active infer binds).
// Match on the bare short name.
if (t->kind == CBM_TYPE_NAMED && t->data.named.qualified_name) {
- const char* qn = t->data.named.qualified_name;
- const char* dot = strrchr(qn, '.');
- const char* bare = dot ? dot + 1 : qn;
+ const char *qn = t->data.named.qualified_name;
+ const char *dot = strrchr(qn, '.');
+ const char *bare = dot ? dot + 1 : qn;
for (int i = 0; i < bind_count; i++) {
if (binds[i].name && strcmp(binds[i].name, bare) == 0) {
return binds[i].binding;
@@ -891,24 +1050,26 @@ static const CBMType* subst_infer_bindings(TSLSPContext* ctx, const CBMType* t,
if (t->kind == CBM_TYPE_TEMPLATE && t->data.template_type.template_args &&
t->data.template_type.arg_count > 0) {
int ac = t->data.template_type.arg_count;
- const CBMType** new_args = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(ac + 1) * sizeof(const CBMType*));
- if (!new_args) return t;
+ const CBMType **new_args = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(ac + 1) * sizeof(const CBMType *));
+ if (!new_args)
+ return t;
for (int i = 0; i < ac; i++) {
- new_args[i] = subst_infer_bindings(ctx, t->data.template_type.template_args[i],
- binds, bind_count, depth + 1);
+ new_args[i] = subst_infer_bindings(ctx, t->data.template_type.template_args[i], binds,
+ bind_count, depth + 1);
}
new_args[ac] = NULL;
return cbm_type_template(ctx->arena, t->data.template_type.template_name, new_args, ac);
}
if (t->kind == CBM_TYPE_TUPLE && t->data.tuple.count > 0) {
int n = t->data.tuple.count;
- const CBMType** new_elems = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(n + 1) * sizeof(const CBMType*));
- if (!new_elems) return t;
+ const CBMType **new_elems = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(n + 1) * sizeof(const CBMType *));
+ if (!new_elems)
+ return t;
for (int i = 0; i < n; i++) {
- new_elems[i] = subst_infer_bindings(ctx, t->data.tuple.elems[i],
- binds, bind_count, depth + 1);
+ new_elems[i] =
+ subst_infer_bindings(ctx, t->data.tuple.elems[i], binds, bind_count, depth + 1);
}
new_elems[n] = NULL;
return cbm_type_tuple(ctx->arena, new_elems, n);
@@ -917,28 +1078,34 @@ static const CBMType* subst_infer_bindings(TSLSPContext* ctx, const CBMType* t,
}
// Walk a type tree to detect any CBM_TYPE_INFER nodes.
-static bool contains_infer(const CBMType* t, int depth) {
- if (!t || depth > 32) return false;
- if (t->kind == CBM_TYPE_INFER) return true;
+static bool contains_infer(const CBMType *t, int depth) {
+ if (!t || depth > 32)
+ return false;
+ if (t->kind == CBM_TYPE_INFER)
+ return true;
if (t->kind == CBM_TYPE_TEMPLATE && t->data.template_type.template_args) {
for (int i = 0; i < t->data.template_type.arg_count; i++) {
- if (contains_infer(t->data.template_type.template_args[i], depth + 1)) return true;
+ if (contains_infer(t->data.template_type.template_args[i], depth + 1))
+ return true;
}
}
if (t->kind == CBM_TYPE_TUPLE && t->data.tuple.elems) {
for (int i = 0; i < t->data.tuple.count; i++) {
- if (contains_infer(t->data.tuple.elems[i], depth + 1)) return true;
+ if (contains_infer(t->data.tuple.elems[i], depth + 1))
+ return true;
}
}
if (t->kind == CBM_TYPE_FUNC) {
if (t->data.func.return_types) {
for (int i = 0; t->data.func.return_types[i]; i++) {
- if (contains_infer(t->data.func.return_types[i], depth + 1)) return true;
+ if (contains_infer(t->data.func.return_types[i], depth + 1))
+ return true;
}
}
if (t->data.func.param_types) {
for (int i = 0; t->data.func.param_types[i]; i++) {
- if (contains_infer(t->data.func.param_types[i], depth + 1)) return true;
+ if (contains_infer(t->data.func.param_types[i], depth + 1))
+ return true;
}
}
}
@@ -948,28 +1115,32 @@ static bool contains_infer(const CBMType* t, int depth) {
// Evaluate a CBM_TYPE_CONDITIONAL `T extends U ? X : Y`. With distribution: when T is
// a UNION, evaluate per member and union the results. Uses the partial relater for
// the extends check.
-static const CBMType* eval_conditional(TSLSPContext* ctx, const CBMType* t, int depth) {
- if (!t || t->kind != CBM_TYPE_CONDITIONAL || depth > 16) return t;
- const CBMType* check = t->data.conditional.check;
- const CBMType* extends = t->data.conditional.extends;
- const CBMType* tb = t->data.conditional.true_branch;
- const CBMType* fb = t->data.conditional.false_branch;
- if (!check || !extends) return t;
+static const CBMType *eval_conditional(TSLSPContext *ctx, const CBMType *t, int depth) {
+ if (!t || t->kind != CBM_TYPE_CONDITIONAL || depth > 16)
+ return t;
+ const CBMType *check = t->data.conditional.check;
+ const CBMType *extends = t->data.conditional.extends;
+ const CBMType *tb = t->data.conditional.true_branch;
+ const CBMType *fb = t->data.conditional.false_branch;
+ if (!check || !extends)
+ return t;
// Distribution: when check is a UNION, evaluate per member and union results.
if (check->kind == CBM_TYPE_UNION && check->data.union_type.members &&
check->data.union_type.count > 0) {
- const CBMType** results = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(check->data.union_type.count + 1) * sizeof(const CBMType*));
- if (!results) return t;
+ const CBMType **results = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(check->data.union_type.count + 1) * sizeof(const CBMType *));
+ if (!results)
+ return t;
int n = 0;
for (int i = 0; i < check->data.union_type.count; i++) {
- const CBMType* member = check->data.union_type.members[i];
- const CBMType* sub = cbm_type_conditional(ctx->arena, member, extends, tb, fb);
+ const CBMType *member = check->data.union_type.members[i];
+ const CBMType *sub = cbm_type_conditional(ctx->arena, member, extends, tb, fb);
results[n++] = eval_conditional(ctx, sub, depth + 1);
}
results[n] = NULL;
- if (n == 1) return results[0];
+ if (n == 1)
+ return results[0];
return cbm_type_union(ctx->arena, results, n);
}
@@ -991,46 +1162,55 @@ static const CBMType* eval_conditional(TSLSPContext* ctx, const CBMType* t, int
// Resolve a CBMType against the registry's alias chain when it's a NAMED type that's a
// pure alias (`type Foo = Bar`). Also evaluates inline conditional types.
-static const CBMType* simplify_type(TSLSPContext* ctx, const CBMType* t) {
- if (!t || !ctx || !ctx->registry) return t;
+static const CBMType *simplify_type(TSLSPContext *ctx, const CBMType *t) {
+ if (!t || !ctx || !ctx->registry)
+ return t;
if (t->kind == CBM_TYPE_CONDITIONAL) {
- const CBMType* evaluated = eval_conditional(ctx, t, 0);
- if (evaluated && evaluated != t) return simplify_type(ctx, evaluated);
+ const CBMType *evaluated = eval_conditional(ctx, t, 0);
+ if (evaluated && evaluated != t)
+ return simplify_type(ctx, evaluated);
return t;
}
- if (t->kind == CBM_TYPE_ALIAS) return cbm_type_resolve_alias(t);
- if (t->kind != CBM_TYPE_NAMED) return t;
+ if (t->kind == CBM_TYPE_ALIAS)
+ return cbm_type_resolve_alias(t);
+ if (t->kind != CBM_TYPE_NAMED)
+ return t;
for (int i = 0; i < 16; i++) {
- if (!t || t->kind != CBM_TYPE_NAMED) return t;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- t->data.named.qualified_name);
- if (!rt || !rt->alias_of) return t;
+ if (!t || t->kind != CBM_TYPE_NAMED)
+ return t;
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, t->data.named.qualified_name);
+ if (!rt || !rt->alias_of)
+ return t;
t = cbm_type_named(ctx->arena, rt->alias_of);
}
return t;
}
-static const CBMType* type_of_identifier(TSLSPContext* ctx, const char* name) {
- if (!ctx || !name) return cbm_type_unknown();
+static const CBMType *type_of_identifier(TSLSPContext *ctx, const char *name) {
+ if (!ctx || !name)
+ return cbm_type_unknown();
// Scope lookup (params, locals).
- const CBMType* t = cbm_scope_lookup(ctx->current_scope, name);
- if (t && !cbm_type_is_unknown(t)) return t;
+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
+ if (t && !cbm_type_is_unknown(t))
+ return t;
// Imports: bare identifier matching an import binding. Compute the full symbol QN
// and look it up in the registry. If it's a registered func, return its signature;
// if it's a registered type, return NAMED. Falls back to NAMED(module_qn) for
// namespace-style imports where no specific symbol matches.
for (int i = 0; i < ctx->import_count; i++) {
- const char* local = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
- const char* mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
- if (!local || !mqn || strcmp(local, name) != 0) continue;
+ const char *local = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ if (!local || !mqn || strcmp(local, name) != 0)
+ continue;
// Construct the full symbol QN: if mqn already ends in ".name" use it; else
// append ".name". This matches `resolve_type_with_imports`' convention.
size_t mqn_len = strlen(mqn);
size_t name_len = strlen(name);
- const char* full_qn;
+ const char *full_qn;
if (mqn_len > name_len + 1 && mqn[mqn_len - name_len - 1] == '.' &&
strcmp(mqn + mqn_len - name_len, name) == 0) {
full_qn = mqn;
@@ -1039,10 +1219,12 @@ static const CBMType* type_of_identifier(TSLSPContext* ctx, const char* name) {
}
// Try the symbol lookup precedence: registered func, then registered type.
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, full_qn);
- if (f && f->signature) return f->signature;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, full_qn);
- if (rt) return cbm_type_named(ctx->arena, full_qn);
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, full_qn);
+ if (f && f->signature)
+ return f->signature;
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, full_qn);
+ if (rt)
+ return cbm_type_named(ctx->arena, full_qn);
// No specific match — fall back to NAMED(module_qn), which is correct for
// namespace-style imports (`import * as foo from './foo'`).
@@ -1051,20 +1233,24 @@ static const CBMType* type_of_identifier(TSLSPContext* ctx, const char* name) {
// Module-local function or class.
if (ctx->module_qn) {
- const char* candidate = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name);
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, candidate);
- if (rt) return cbm_type_named(ctx->arena, candidate);
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, candidate);
- if (f && f->signature) return f->signature;
+ const char *candidate = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, candidate);
+ if (rt)
+ return cbm_type_named(ctx->arena, candidate);
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, candidate);
+ if (f && f->signature)
+ return f->signature;
}
// Global / stdlib bare-name lookup (Promise, Array, Map, Set, console, JSON, Object, ...).
// The TS stdlib registers these with QN equal to the bare name.
{
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, name);
- if (rt) return cbm_type_named(ctx->arena, name);
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, name);
- if (f && f->signature) return f->signature;
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, name);
+ if (rt)
+ return cbm_type_named(ctx->arena, name);
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, name);
+ if (f && f->signature)
+ return f->signature;
}
return cbm_type_unknown();
@@ -1072,30 +1258,58 @@ static const CBMType* type_of_identifier(TSLSPContext* ctx, const char* name) {
// Map BUILTIN type names to their wrapper class for method dispatch.
// `"x".split(...)` works because TS treats string primitives as having String prototype.
-static const char* builtin_wrapper_class(const char* builtin_name) {
- if (!builtin_name) return NULL;
- if (strcmp(builtin_name, "string") == 0) return "String";
- if (strcmp(builtin_name, "number") == 0) return "Number";
- if (strcmp(builtin_name, "boolean") == 0) return "Boolean";
- if (strcmp(builtin_name, "bigint") == 0) return "BigInt";
- if (strcmp(builtin_name, "symbol") == 0) return "Symbol";
+static const char *builtin_wrapper_class(const char *builtin_name) {
+ if (!builtin_name)
+ return NULL;
+ if (strcmp(builtin_name, "string") == 0)
+ return "String";
+ if (strcmp(builtin_name, "number") == 0)
+ return "Number";
+ if (strcmp(builtin_name, "boolean") == 0)
+ return "Boolean";
+ if (strcmp(builtin_name, "bigint") == 0)
+ return "BigInt";
+ if (strcmp(builtin_name, "symbol") == 0)
+ return "Symbol";
return NULL;
}
// Look up a property `name` on a receiver type. Returns the property type or UNKNOWN.
-static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
- const char* name) {
- if (!ctx || !recv || !name) return cbm_type_unknown();
- const CBMType* base = simplify_type(ctx, recv);
- if (!base) return cbm_type_unknown();
+static const CBMType *lookup_member_type_inner(TSLSPContext *ctx, const CBMType *recv,
+ const char *name);
+
+#define TS_LSP_MAX_MEMBER_DEPTH 64
+
+/* Depth-guarded entry: member lookup recurses through wrapper classes, union
+ * members and registered-type expansion; cyclic type graphs in real-world TS
+ * (microsoft/TypeScript reallyLargeFile.ts) recursed without bound — SIGBUS
+ * stack overflow under endless lookup_member_type frames. Past the cap the
+ * member resolves as unknown — graceful degradation, not a crash. */
+static const CBMType *lookup_member_type(TSLSPContext *ctx, const CBMType *recv, const char *name) {
+ if (!ctx || ctx->member_depth >= TS_LSP_MAX_MEMBER_DEPTH)
+ return cbm_type_unknown();
+ ctx->member_depth++;
+ const CBMType *r = lookup_member_type_inner(ctx, recv, name);
+ ctx->member_depth--;
+ return r;
+}
+
+static const CBMType *lookup_member_type_inner(TSLSPContext *ctx, const CBMType *recv,
+ const char *name) {
+ if (!ctx || !recv || !name)
+ return cbm_type_unknown();
+ const CBMType *base = simplify_type(ctx, recv);
+ if (!base)
+ return cbm_type_unknown();
base = unwrap_passthrough_template(base);
- if (!base) return cbm_type_unknown();
+ if (!base)
+ return cbm_type_unknown();
// BUILTIN primitives delegate to their wrapper class (e.g. string → String).
if (base->kind == CBM_TYPE_BUILTIN) {
- const char* wrap = builtin_wrapper_class(base->data.builtin.name);
+ const char *wrap = builtin_wrapper_class(base->data.builtin.name);
if (wrap) {
- const CBMType* wrapped = cbm_type_named(ctx->arena, wrap);
+ const CBMType *wrapped = cbm_type_named(ctx->arena, wrap);
return lookup_member_type(ctx, wrapped, name);
}
return cbm_type_unknown();
@@ -1104,8 +1318,8 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
if (base->kind == CBM_TYPE_TEMPLATE) {
// Look up on the template name (e.g., "Array", "Promise"); generic params are
// applied via cbm_type_substitute when we know the registered type's params.
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- base->data.template_type.template_name);
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, base->data.template_type.template_name);
if (rt) {
// Field?
if (rt->field_names && rt->field_types) {
@@ -1121,8 +1335,8 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
if (rt->method_qns && rt->method_names) {
for (int i = 0; rt->method_names[i]; i++) {
if (strcmp(rt->method_names[i], name) == 0) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry,
- rt->method_qns[i]);
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_func(ctx->registry, rt->method_qns[i]);
if (f && f->signature) {
return cbm_type_substitute(ctx->arena, f->signature,
rt->type_param_names,
@@ -1151,8 +1365,9 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
// first hit instead of building a union of results.)
if (base->data.union_type.members) {
for (int i = 0; i < base->data.union_type.count; i++) {
- const CBMType* m = lookup_member_type(ctx, base->data.union_type.members[i], name);
- if (!cbm_type_is_unknown(m)) return m;
+ const CBMType *m = lookup_member_type(ctx, base->data.union_type.members[i], name);
+ if (!cbm_type_is_unknown(m))
+ return m;
}
}
return cbm_type_unknown();
@@ -1161,34 +1376,40 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
if (base->kind == CBM_TYPE_INTERSECTION) {
if (base->data.union_type.members) {
for (int i = 0; i < base->data.union_type.count; i++) {
- const CBMType* m = lookup_member_type(ctx, base->data.union_type.members[i], name);
- if (!cbm_type_is_unknown(m)) return m;
+ const CBMType *m = lookup_member_type(ctx, base->data.union_type.members[i], name);
+ if (!cbm_type_is_unknown(m))
+ return m;
}
}
return cbm_type_unknown();
}
- if (base->kind != CBM_TYPE_NAMED) return cbm_type_unknown();
+ if (base->kind != CBM_TYPE_NAMED)
+ return cbm_type_unknown();
- const char* recv_qn = base->data.named.qualified_name;
- const CBMRegisteredType* rt = cbm_registry_resolve_alias(ctx->registry, recv_qn);
+ const char *recv_qn = base->data.named.qualified_name;
+ const CBMRegisteredType *rt = cbm_registry_resolve_alias(ctx->registry, recv_qn);
if (!rt) {
rt = cbm_registry_lookup_type(ctx->registry, recv_qn);
- if (!rt) return cbm_type_unknown();
+ if (!rt)
+ return cbm_type_unknown();
}
// Direct field lookup.
if (rt->field_names && rt->field_types) {
for (int i = 0; rt->field_names[i]; i++) {
- if (strcmp(rt->field_names[i], name) == 0) return rt->field_types[i];
+ if (strcmp(rt->field_names[i], name) == 0)
+ return rt->field_types[i];
}
}
// Method lookup → return the method's FUNC type.
if (rt->method_qns && rt->method_names) {
for (int i = 0; rt->method_names[i]; i++) {
if (strcmp(rt->method_names[i], name) == 0) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_func(ctx->registry, rt->method_qns[i]);
- if (f && f->signature) return f->signature;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_func(ctx->registry, rt->method_qns[i]);
+ if (f && f->signature)
+ return f->signature;
return cbm_type_unknown();
}
}
@@ -1196,9 +1417,10 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
// Walk extends/implements.
if (rt->embedded_types) {
for (int i = 0; rt->embedded_types[i]; i++) {
- const CBMType* parent = cbm_type_named(ctx->arena, rt->embedded_types[i]);
- const CBMType* m = lookup_member_type(ctx, parent, name);
- if (!cbm_type_is_unknown(m)) return m;
+ const CBMType *parent = cbm_type_named(ctx->arena, rt->embedded_types[i]);
+ const CBMType *m = lookup_member_type(ctx, parent, name);
+ if (!cbm_type_is_unknown(m))
+ return m;
}
}
return cbm_type_unknown();
@@ -1207,21 +1429,21 @@ static const CBMType* lookup_member_type(TSLSPContext* ctx, const CBMType* recv,
// TS utility types like Partial<T>, Readonly<T>, Required<T> are essentially
// transformations on T's properties — for call-edge resolution they pass through
// to T's own method/property surface. NonNullable<T> also unwraps to T.
-static const CBMType* unwrap_passthrough_template(const CBMType* t) {
- if (!t || t->kind != CBM_TYPE_TEMPLATE) return t;
- const char* name = t->data.template_type.template_name;
- if (!name || !t->data.template_type.template_args ||
- t->data.template_type.arg_count < 1) return t;
+static const CBMType *unwrap_passthrough_template(const CBMType *t) {
+ if (!t || t->kind != CBM_TYPE_TEMPLATE)
+ return t;
+ const char *name = t->data.template_type.template_name;
+ if (!name || !t->data.template_type.template_args || t->data.template_type.arg_count < 1)
+ return t;
// Single-arg utility types pass through to T's surface for method dispatch.
if (strcmp(name, "Partial") == 0 || strcmp(name, "Required") == 0 ||
strcmp(name, "Readonly") == 0 || strcmp(name, "NonNullable") == 0 ||
- strcmp(name, "Pick") == 0 || strcmp(name, "Omit") == 0 ||
- strcmp(name, "Awaited") == 0) {
+ strcmp(name, "Pick") == 0 || strcmp(name, "Omit") == 0 || strcmp(name, "Awaited") == 0) {
return t->data.template_type.template_args[0];
}
// ReturnType<F>: when F is FUNC, surface F's return type for method dispatch.
if (strcmp(name, "ReturnType") == 0) {
- const CBMType* f = t->data.template_type.template_args[0];
+ const CBMType *f = t->data.template_type.template_args[0];
if (f && f->kind == CBM_TYPE_FUNC && f->data.func.return_types &&
f->data.func.return_types[0]) {
return f->data.func.return_types[0];
@@ -1240,31 +1462,38 @@ static const CBMType* unwrap_passthrough_template(const CBMType* t) {
// Build a UNION of LITERAL string types representing keyof T, where T is a registered
// class/interface. Returns UNKNOWN if T has no fields or isn't registered.
-static const CBMType* eval_keyof(TSLSPContext* ctx, const CBMType* operand) {
- if (!ctx || !operand) return cbm_type_unknown();
- const CBMType* base = simplify_type(ctx, operand);
- if (!base || base->kind != CBM_TYPE_NAMED) return cbm_type_unknown();
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- base->data.named.qualified_name);
- if (!rt || !rt->field_names || !rt->field_names[0]) return cbm_type_unknown();
+static const CBMType *eval_keyof(TSLSPContext *ctx, const CBMType *operand) {
+ if (!ctx || !operand)
+ return cbm_type_unknown();
+ const CBMType *base = simplify_type(ctx, operand);
+ if (!base || base->kind != CBM_TYPE_NAMED)
+ return cbm_type_unknown();
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, base->data.named.qualified_name);
+ if (!rt || !rt->field_names || !rt->field_names[0])
+ return cbm_type_unknown();
int fc = 0;
- while (rt->field_names[fc]) fc++;
- const CBMType* members[64];
+ while (rt->field_names[fc])
+ fc++;
+ const CBMType *members[64];
int mc = 0;
for (int i = 0; i < fc && mc < 63; i++) {
members[mc++] = cbm_type_ts_literal(ctx->arena, "string", rt->field_names[i]);
}
members[mc] = NULL;
- if (mc == 0) return cbm_type_unknown();
- if (mc == 1) return members[0];
+ if (mc == 0)
+ return cbm_type_unknown();
+ if (mc == 1)
+ return members[0];
return cbm_type_union(ctx->arena, members, mc);
}
// Evaluate T[K]: when K is a string literal, look up that field on T. When K is a
// type parameter (or `keyof T` itself), return UNKNOWN — pragmatic v1.
-static const CBMType* eval_indexed_access(TSLSPContext* ctx, const CBMType* obj,
- const CBMType* key) {
- if (!ctx || !obj || !key) return cbm_type_unknown();
+static const CBMType *eval_indexed_access(TSLSPContext *ctx, const CBMType *obj,
+ const CBMType *key) {
+ if (!ctx || !obj || !key)
+ return cbm_type_unknown();
if (key->kind == CBM_TYPE_TS_LITERAL && key->data.literal_ts.value &&
key->data.literal_ts.tag && strcmp(key->data.literal_ts.tag, "string") == 0) {
return lookup_member_type(ctx, obj, key->data.literal_ts.value);
@@ -1273,35 +1502,39 @@ static const CBMType* eval_indexed_access(TSLSPContext* ctx, const CBMType* obj,
}
// Look up a method on a receiver type — returns the registered func.
-static const CBMRegisteredFunc* lookup_method(TSLSPContext* ctx, const CBMType* recv,
- const char* method_name) {
- if (!ctx || !recv || !method_name) return NULL;
- const CBMType* base = simplify_type(ctx, recv);
- if (!base) return NULL;
+static const CBMRegisteredFunc *lookup_method(TSLSPContext *ctx, const CBMType *recv,
+ const char *method_name) {
+ if (!ctx || !recv || !method_name)
+ return NULL;
+ const CBMType *base = simplify_type(ctx, recv);
+ if (!base)
+ return NULL;
base = unwrap_passthrough_template(base);
- if (!base) return NULL;
+ if (!base)
+ return NULL;
// BUILTIN primitives → look up via the wrapper class (string → String, etc.).
if (base->kind == CBM_TYPE_BUILTIN) {
- const char* wrap = builtin_wrapper_class(base->data.builtin.name);
+ const char *wrap = builtin_wrapper_class(base->data.builtin.name);
if (wrap) {
- const CBMType* wrapped = cbm_type_named(ctx->arena, wrap);
+ const CBMType *wrapped = cbm_type_named(ctx->arena, wrap);
return lookup_method(ctx, wrapped, method_name);
}
return NULL;
}
if (ctx->debug) {
- const char* base_qn = (base->kind == CBM_TYPE_NAMED) ? base->data.named.qualified_name :
- (base->kind == CBM_TYPE_TEMPLATE) ? base->data.template_type.template_name :
- "<other>";
+ const char *base_qn = (base->kind == CBM_TYPE_NAMED) ? base->data.named.qualified_name
+ : (base->kind == CBM_TYPE_TEMPLATE)
+ ? base->data.template_type.template_name
+ : "<other>";
fprintf(stderr, "[ts_lsp] lookup_method: recv_kind=%d recv_qn=%s method=%s\n",
(int)base->kind, base_qn ? base_qn : "(null)", method_name);
}
if (base->kind == CBM_TYPE_TEMPLATE) {
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- base->data.template_type.template_name);
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, base->data.template_type.template_name);
if (rt && rt->method_qns && rt->method_names) {
for (int i = 0; rt->method_names[i]; i++) {
if (strcmp(rt->method_names[i], method_name) == 0) {
@@ -1314,28 +1547,32 @@ static const CBMRegisteredFunc* lookup_method(TSLSPContext* ctx, const CBMType*
if (base->kind == CBM_TYPE_UNION || base->kind == CBM_TYPE_INTERSECTION) {
if (base->data.union_type.members) {
for (int i = 0; i < base->data.union_type.count; i++) {
- const CBMRegisteredFunc* f = lookup_method(ctx, base->data.union_type.members[i],
- method_name);
- if (f) return f;
+ const CBMRegisteredFunc *f =
+ lookup_method(ctx, base->data.union_type.members[i], method_name);
+ if (f)
+ return f;
}
}
return NULL;
}
- if (base->kind != CBM_TYPE_NAMED) return NULL;
- const char* recv_qn = base->data.named.qualified_name;
+ if (base->kind != CBM_TYPE_NAMED)
+ return NULL;
+ const char *recv_qn = base->data.named.qualified_name;
- const CBMRegisteredFunc* f = cbm_registry_lookup_method_aliased(ctx->registry, recv_qn,
- method_name);
- if (f) return f;
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_method_aliased(ctx->registry, recv_qn, method_name);
+ if (f)
+ return f;
// Walk extends/implements via the registered type.
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry, recv_qn);
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, recv_qn);
if (rt && rt->embedded_types) {
for (int i = 0; rt->embedded_types[i]; i++) {
- const CBMType* parent = cbm_type_named(ctx->arena, rt->embedded_types[i]);
- const CBMRegisteredFunc* pf = lookup_method(ctx, parent, method_name);
- if (pf) return pf;
+ const CBMType *parent = cbm_type_named(ctx->arena, rt->embedded_types[i]);
+ const CBMRegisteredFunc *pf = lookup_method(ctx, parent, method_name);
+ if (pf)
+ return pf;
}
}
return NULL;
@@ -1343,12 +1580,16 @@ 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(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];
+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++;
+ while (sig->data.func.return_types[count])
+ 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
@@ -1356,25 +1597,28 @@ static const CBMType* return_type_of(CBMArena* arena, const CBMType* sig) {
return cbm_type_tuple(arena, sig->data.func.return_types, count);
}
-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) return cbm_type_unknown();
+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)
+ return cbm_type_unknown();
ctx->eval_depth++;
- const CBMType* result = cbm_type_unknown();
- const char* kind = ts_node_type(node);
+ const CBMType *result = cbm_type_unknown();
+ const char *kind = ts_node_type(node);
if (strcmp(kind, "identifier") == 0 || strcmp(kind, "shorthand_property_identifier") == 0) {
- char* name = node_text(ctx, node);
- if (name) result = type_of_identifier(ctx, name);
+ char *name = node_text(ctx, node);
+ if (name)
+ result = type_of_identifier(ctx, name);
} else if (strcmp(kind, "this") == 0) {
if (ctx->enclosing_class_qn) {
result = cbm_type_named(ctx->arena, ctx->enclosing_class_qn);
}
} else if (strcmp(kind, "super") == 0) {
if (ctx->enclosing_class_qn) {
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- ctx->enclosing_class_qn);
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, ctx->enclosing_class_qn);
if (rt && rt->embedded_types && rt->embedded_types[0]) {
result = cbm_type_named(ctx->arena, rt->embedded_types[0]);
}
@@ -1386,43 +1630,42 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
// `expr!` — strip the assertion, type unchanged.
TSNode inner = ts_node_named_child(node, 0);
result = ts_eval_expr_type(ctx, inner);
- } else if (strcmp(kind, "as_expression") == 0 ||
- strcmp(kind, "satisfies_expression") == 0 ||
+ } else if (strcmp(kind, "as_expression") == 0 || strcmp(kind, "satisfies_expression") == 0 ||
strcmp(kind, "type_assertion") == 0) {
// `expr as T` / `<T>expr` / `expr satisfies T`: type-position field gives the type.
// For satisfies, we keep the asserted-type (TS narrows it but for resolution that's fine).
TSNode type_node = ts_node_child_by_field_name(node, "type", TS_LSP_FIELD_LEN("type"));
if (!ts_node_is_null(type_node)) {
- char* text = node_text(ctx, type_node);
+ char *text = node_text(ctx, type_node);
result = parse_ts_type_text(ctx->arena, text, ctx->module_qn);
} else {
// Last named child is the type for older grammars.
uint32_t nc = ts_node_named_child_count(node);
if (nc >= 2) {
TSNode tn = ts_node_named_child(node, nc - 1);
- char* text = node_text(ctx, tn);
+ char *text = node_text(ctx, tn);
result = parse_ts_type_text(ctx->arena, text, ctx->module_qn);
}
}
} else if (strcmp(kind, "member_expression") == 0 ||
strcmp(kind, "subscript_expression") == 0) {
TSNode obj = ts_node_child_by_field_name(node, "object", TS_LSP_FIELD_LEN("object"));
- TSNode prop = ts_node_child_by_field_name(node, "property",
- TS_LSP_FIELD_LEN("property"));
+ TSNode prop = ts_node_child_by_field_name(node, "property", TS_LSP_FIELD_LEN("property"));
if (!ts_node_is_null(obj) && !ts_node_is_null(prop)) {
- const CBMType* recv = ts_eval_expr_type(ctx, obj);
- char* pname = node_text(ctx, prop);
- if (pname) result = lookup_member_type(ctx, recv, pname);
+ const CBMType *recv = ts_eval_expr_type(ctx, obj);
+ char *pname = node_text(ctx, prop);
+ if (pname)
+ result = lookup_member_type(ctx, recv, pname);
}
} else if (strcmp(kind, "new_expression") == 0) {
- TSNode ctor = ts_node_child_by_field_name(node, "constructor",
- TS_LSP_FIELD_LEN("constructor"));
+ TSNode ctor =
+ ts_node_child_by_field_name(node, "constructor", TS_LSP_FIELD_LEN("constructor"));
if (!ts_node_is_null(ctor)) {
- char* cname = node_text(ctx, ctor);
+ char *cname = node_text(ctx, ctor);
if (cname) {
// Bare class name → qualify against module.
if (strchr(cname, '.') == NULL && ctx->module_qn) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
result = cbm_type_named(ctx->arena, qn);
} else {
result = cbm_type_named(ctx->arena, cname);
@@ -1432,7 +1675,7 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
} else if (strcmp(kind, "call_expression") == 0) {
TSNode fn = ts_node_child_by_field_name(node, "function", TS_LSP_FIELD_LEN("function"));
if (!ts_node_is_null(fn)) {
- const CBMType* fn_type = ts_eval_expr_type(ctx, fn);
+ const CBMType *fn_type = ts_eval_expr_type(ctx, fn);
if (ctx->debug) {
fprintf(stderr, "[ts_lsp] eval call_expression: fn_kind=%s fn_type_kind=%d\n",
ts_node_type(fn), fn_type ? (int)fn_type->kind : -1);
@@ -1444,15 +1687,15 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
// `this` (TYPE_PARAM "this"), substitute the actual receiver type
// from the call site (fn is a member_expression — its `object` is
// the receiver). Powers fluent-builder patterns.
- if (result && result->kind == CBM_TYPE_TYPE_PARAM &&
- result->data.type_param.name &&
+ if (result && result->kind == CBM_TYPE_TYPE_PARAM && result->data.type_param.name &&
strcmp(result->data.type_param.name, "this") == 0 &&
strcmp(ts_node_type(fn), "member_expression") == 0) {
- TSNode obj = ts_node_child_by_field_name(fn, "object",
- TS_LSP_FIELD_LEN("object"));
+ TSNode obj =
+ ts_node_child_by_field_name(fn, "object", TS_LSP_FIELD_LEN("object"));
if (!ts_node_is_null(obj)) {
- const CBMType* recv = ts_eval_expr_type(ctx, obj);
- if (recv && !cbm_type_is_unknown(recv)) result = recv;
+ const CBMType *recv = ts_eval_expr_type(ctx, obj);
+ if (recv && !cbm_type_is_unknown(recv))
+ result = recv;
}
}
@@ -1466,19 +1709,23 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
TS_LSP_FIELD_LEN("arguments"));
if (!ts_node_is_null(args)) {
// Build a list of inferred type-param names + arg types.
- const char* inf_names[8] = {0};
- const CBMType* inf_args[8] = {0};
+ const char *inf_names[8] = {0};
+ const CBMType *inf_args[8] = {0};
int ic = 0;
uint32_t pc = 0;
- while (fn_type->data.func.param_types[pc]) pc++;
+ while (fn_type->data.func.param_types[pc])
+ pc++;
uint32_t argc = ts_node_named_child_count(args);
for (uint32_t i = 0; i < pc && i < argc && ic < 7; i++) {
- const CBMType* pt = fn_type->data.func.param_types[i];
- if (!pt || pt->kind != CBM_TYPE_TYPE_PARAM) continue;
+ const CBMType *pt = fn_type->data.func.param_types[i];
+ if (!pt || pt->kind != CBM_TYPE_TYPE_PARAM)
+ continue;
TSNode arg = ts_node_named_child(args, i);
- if (ts_node_is_null(arg)) continue;
- const CBMType* at = ts_eval_expr_type(ctx, arg);
- if (cbm_type_is_unknown(at)) continue;
+ if (ts_node_is_null(arg))
+ continue;
+ const CBMType *at = ts_eval_expr_type(ctx, arg);
+ if (cbm_type_is_unknown(at))
+ continue;
inf_names[ic] = pt->data.type_param.name;
inf_args[ic] = at;
ic++;
@@ -1486,16 +1733,18 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
if (ic > 0) {
inf_names[ic] = NULL;
inf_args[ic] = NULL;
- const CBMType* sub = cbm_type_substitute(ctx->arena, result,
- inf_names, inf_args);
- if (sub && !cbm_type_is_unknown(sub)) result = sub;
+ const CBMType *sub =
+ cbm_type_substitute(ctx->arena, result, inf_names, inf_args);
+ if (sub && !cbm_type_is_unknown(sub))
+ result = sub;
}
}
}
if (ctx->debug) {
- const char* res_qn = (result && result->kind == CBM_TYPE_NAMED) ?
- result->data.named.qualified_name : "<other>";
+ const char *res_qn = (result && result->kind == CBM_TYPE_NAMED)
+ ? result->data.named.qualified_name
+ : "<other>";
fprintf(stderr, "[ts_lsp] returns kind=%d qn=%s\n",
result ? (int)result->kind : -1, res_qn ? res_qn : "(null)");
}
@@ -1503,12 +1752,11 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
}
} else if (strcmp(kind, "await_expression") == 0) {
TSNode inner = ts_node_named_child(node, 0);
- const CBMType* t = ts_eval_expr_type(ctx, inner);
+ const CBMType *t = ts_eval_expr_type(ctx, inner);
// Promise<T> → T.
if (t && t->kind == CBM_TYPE_TEMPLATE && t->data.template_type.template_name &&
strcmp(t->data.template_type.template_name, "Promise") == 0 &&
- t->data.template_type.arg_count >= 1 &&
- t->data.template_type.template_args) {
+ t->data.template_type.arg_count >= 1 && t->data.template_type.template_args) {
result = t->data.template_type.template_args[0];
} else {
result = t;
@@ -1525,36 +1773,38 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
result = cbm_type_builtin(ctx->arena, "undefined");
} else if (strcmp(kind, "array") == 0) {
// Use first element's type as Array<T> argument.
- const CBMType* elem = cbm_type_unknown();
+ const CBMType *elem = cbm_type_unknown();
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(node, i);
if (!ts_node_is_null(c)) {
elem = ts_eval_expr_type(ctx, c);
- if (!cbm_type_is_unknown(elem)) break;
+ if (!cbm_type_is_unknown(elem))
+ break;
}
}
- const CBMType* args[2] = {elem, NULL};
+ const CBMType *args[2] = {elem, NULL};
result = cbm_type_template(ctx->arena, "Array", args, 1);
} else if (strcmp(kind, "object") == 0) {
// Object literal — capture string-keyed property types.
uint32_t nc = ts_node_named_child_count(node);
- const char* names[32] = {0};
- const CBMType* types[32] = {0};
+ const char *names[32] = {0};
+ const CBMType *types[32] = {0};
int count = 0;
for (uint32_t i = 0; i < nc && count < 31; i++) {
TSNode c = ts_node_named_child(node, i);
- if (ts_node_is_null(c)) continue;
- const char* ck = ts_node_type(c);
+ if (ts_node_is_null(c))
+ continue;
+ const char *ck = ts_node_type(c);
if (strcmp(ck, "pair") == 0) {
TSNode key = ts_node_child_by_field_name(c, "key", TS_LSP_FIELD_LEN("key"));
TSNode val = ts_node_child_by_field_name(c, "value", TS_LSP_FIELD_LEN("value"));
if (!ts_node_is_null(key) && !ts_node_is_null(val)) {
- char* k = node_text(ctx, key);
+ char *k = node_text(ctx, key);
if (k) {
// Strip surrounding quotes if string key.
size_t kl = strlen(k);
- if (kl >= 2 && (k[0] == '"' || k[0] == '\'') && k[kl-1] == k[0]) {
+ if (kl >= 2 && (k[0] == '"' || k[0] == '\'') && k[kl - 1] == k[0]) {
k[kl - 1] = '\0';
k++;
}
@@ -1564,7 +1814,7 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
}
}
} else if (strcmp(ck, "shorthand_property_identifier") == 0) {
- char* k = node_text(ctx, c);
+ char *k = node_text(ctx, c);
if (k) {
names[count] = k;
types[count] = type_of_identifier(ctx, k);
@@ -1576,17 +1826,20 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
types[count] = NULL;
result = cbm_type_object_lit(ctx->arena, names, types, NULL, NULL);
} else if (strcmp(kind, "ternary_expression") == 0) {
- TSNode cons = ts_node_child_by_field_name(node, "consequence",
- TS_LSP_FIELD_LEN("consequence"));
- TSNode alt = ts_node_child_by_field_name(node, "alternative",
- TS_LSP_FIELD_LEN("alternative"));
- const CBMType* a = ts_eval_expr_type(ctx, cons);
- const CBMType* b = ts_eval_expr_type(ctx, alt);
- if (cbm_type_is_unknown(a)) result = b;
- else if (cbm_type_is_unknown(b)) result = a;
- else if (a == b) result = a;
+ TSNode cons =
+ ts_node_child_by_field_name(node, "consequence", TS_LSP_FIELD_LEN("consequence"));
+ TSNode alt =
+ ts_node_child_by_field_name(node, "alternative", TS_LSP_FIELD_LEN("alternative"));
+ const CBMType *a = ts_eval_expr_type(ctx, cons);
+ const CBMType *b = ts_eval_expr_type(ctx, alt);
+ if (cbm_type_is_unknown(a))
+ result = b;
+ else if (cbm_type_is_unknown(b))
+ result = a;
+ else if (a == b)
+ result = a;
else {
- const CBMType* members[3] = {a, b, NULL};
+ const CBMType *members[3] = {a, b, NULL};
result = cbm_type_union(ctx->arena, members, 2);
}
} else if (strcmp(kind, "binary_expression") == 0) {
@@ -1594,8 +1847,8 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
TSNode left = ts_node_child_by_field_name(node, "left", TS_LSP_FIELD_LEN("left"));
TSNode right = ts_node_child_by_field_name(node, "right", TS_LSP_FIELD_LEN("right"));
if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
- const CBMType* l = ts_eval_expr_type(ctx, left);
- const CBMType* r = ts_eval_expr_type(ctx, right);
+ const CBMType *l = ts_eval_expr_type(ctx, left);
+ const CBMType *r = ts_eval_expr_type(ctx, right);
if ((l && l->kind == CBM_TYPE_BUILTIN && l->data.builtin.name &&
strcmp(l->data.builtin.name, "string") == 0) ||
(r && r->kind == CBM_TYPE_BUILTIN && r->data.builtin.name &&
@@ -1617,50 +1870,51 @@ const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node) {
// Naming convention: ctx->import_module_qns[i] is the imported module's QN (e.g.
// "test.conn"); to get the full type QN, we append the local-binding name. Falls back
// to the original type if no match.
-static const CBMType* resolve_type_with_imports(TSLSPContext* ctx, const CBMType* t) {
- if (!t || !ctx) return t;
+static const CBMType *resolve_type_with_imports(TSLSPContext *ctx, const CBMType *t) {
+ if (!t || !ctx)
+ return t;
if (t->kind == CBM_TYPE_NAMED && t->data.named.qualified_name) {
- const char* qn = t->data.named.qualified_name;
- const char* dot = strrchr(qn, '.');
- const char* bare = dot ? dot + 1 : qn;
+ const char *qn = t->data.named.qualified_name;
+ const char *dot = strrchr(qn, '.');
+ const char *bare = dot ? dot + 1 : qn;
// TS semantics: locally-declared types shadow ambient/stdlib types with the
// same name. parse_ts_type_text leaves stdlib names bare to match the stdlib
// registration QN; if the local module has a type with the same short name
// (e.g. test files declaring their own `Response`/`File`/etc.), prefer that.
if (!dot && ctx->module_qn) {
- const char* local_qn = cbm_arena_sprintf(ctx->arena, "%s.%s",
- ctx->module_qn, bare);
- const CBMRegisteredType* local_rt = cbm_registry_lookup_type(ctx->registry,
- local_qn);
- if (local_rt) return cbm_type_named(ctx->arena, local_qn);
+ const char *local_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, bare);
+ const CBMRegisteredType *local_rt = cbm_registry_lookup_type(ctx->registry, local_qn);
+ if (local_rt)
+ return cbm_type_named(ctx->arena, local_qn);
}
for (int i = 0; i < ctx->import_count; i++) {
- const char* lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
- const char* mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
- if (!lname || !mqn) continue;
- if (strcmp(lname, bare) != 0) continue;
+ const char *lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ if (!lname || !mqn)
+ continue;
+ if (strcmp(lname, bare) != 0)
+ continue;
// Heuristic: if mqn already ends in ".bare" use as-is; otherwise append.
size_t mqn_len = strlen(mqn);
size_t bare_len = strlen(bare);
- if (mqn_len > bare_len + 1 &&
- mqn[mqn_len - bare_len - 1] == '.' &&
+ if (mqn_len > bare_len + 1 && mqn[mqn_len - bare_len - 1] == '.' &&
strcmp(mqn + mqn_len - bare_len, bare) == 0) {
return cbm_type_named(ctx->arena, mqn);
}
- return cbm_type_named(ctx->arena,
- cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, bare));
+ return cbm_type_named(ctx->arena, cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, bare));
}
return t;
}
if (t->kind == CBM_TYPE_TEMPLATE && t->data.template_type.template_args &&
t->data.template_type.arg_count > 0) {
int ac = t->data.template_type.arg_count;
- const CBMType** new_args = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(ac + 1) * sizeof(const CBMType*));
- if (!new_args) return t;
+ const CBMType **new_args = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(ac + 1) * sizeof(const CBMType *));
+ if (!new_args)
+ return t;
for (int i = 0; i < ac; i++) {
new_args[i] = resolve_type_with_imports(ctx, t->data.template_type.template_args[i]);
}
@@ -1668,68 +1922,78 @@ static const CBMType* resolve_type_with_imports(TSLSPContext* ctx, const CBMType
return cbm_type_template(ctx->arena, t->data.template_type.template_name, new_args, ac);
}
if (t->kind == CBM_TYPE_UNION || t->kind == CBM_TYPE_INTERSECTION) {
- if (!t->data.union_type.members || t->data.union_type.count == 0) return t;
+ if (!t->data.union_type.members || t->data.union_type.count == 0)
+ return t;
int mc = t->data.union_type.count;
- const CBMType** new_members = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(mc + 1) * sizeof(const CBMType*));
- if (!new_members) return t;
+ const CBMType **new_members = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(mc + 1) * sizeof(const CBMType *));
+ if (!new_members)
+ return t;
for (int i = 0; i < mc; i++) {
new_members[i] = resolve_type_with_imports(ctx, t->data.union_type.members[i]);
}
new_members[mc] = NULL;
- return t->kind == CBM_TYPE_UNION
- ? cbm_type_union(ctx->arena, new_members, mc)
- : cbm_type_intersection(ctx->arena, new_members, mc);
+ return t->kind == CBM_TYPE_UNION ? cbm_type_union(ctx->arena, new_members, mc)
+ : cbm_type_intersection(ctx->arena, new_members, mc);
}
return t;
}
-const CBMType* ts_parse_type_node(TSLSPContext* ctx, TSNode node) {
- if (!ctx || ts_node_is_null(node)) return cbm_type_unknown();
- char* text = node_text(ctx, node);
- const CBMType* parsed = parse_ts_type_text(ctx->arena, text, ctx->module_qn);
+const CBMType *ts_parse_type_node(TSLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return cbm_type_unknown();
+ char *text = node_text(ctx, node);
+ const CBMType *parsed = parse_ts_type_text(ctx->arena, text, ctx->module_qn);
return resolve_type_with_imports(ctx, parsed);
}
// ── Statement processing ──────────────────────────────────────────────────────
// Bind a variable_declarator: `let x: T = init` / `const x = init` / `var x = ...`.
-static void bind_variable_declarator(TSLSPContext* ctx, TSNode decl) {
+static void bind_variable_declarator(TSLSPContext *ctx, TSNode decl) {
TSNode name = ts_node_child_by_field_name(decl, "name", TS_LSP_FIELD_LEN("name"));
TSNode tann = ts_node_child_by_field_name(decl, "type", TS_LSP_FIELD_LEN("type"));
TSNode value = ts_node_child_by_field_name(decl, "value", TS_LSP_FIELD_LEN("value"));
- if (ts_node_is_null(name)) return;
+ if (ts_node_is_null(name))
+ return;
- const CBMType* declared = NULL;
+ const CBMType *declared = NULL;
if (!ts_node_is_null(tann)) {
// type_annotation contains the actual type as a named child.
TSNode tch = ts_node_named_child(tann, 0);
- if (!ts_node_is_null(tch)) declared = ts_parse_type_node(ctx, tch);
+ if (!ts_node_is_null(tch))
+ declared = ts_parse_type_node(ctx, tch);
}
- const CBMType* inferred = ts_node_is_null(value) ? cbm_type_unknown() : ts_eval_expr_type(ctx, value);
- const CBMType* bound = (declared && !cbm_type_is_unknown(declared)) ? declared : inferred;
+ const CBMType *inferred =
+ ts_node_is_null(value) ? cbm_type_unknown() : ts_eval_expr_type(ctx, value);
+ const CBMType *bound = (declared && !cbm_type_is_unknown(declared)) ? declared : inferred;
if (node_kind_is(name, "identifier")) {
- char* nm = node_text(ctx, name);
- if (nm) cbm_scope_bind(ctx->current_scope, nm, bound);
+ char *nm = node_text(ctx, name);
+ if (nm)
+ cbm_scope_bind(ctx->current_scope, nm, bound);
} else if (node_kind_is(name, "object_pattern")) {
// Destructure object: `const { a, b } = obj` — bind a and b to obj.a and obj.b types.
uint32_t nc = ts_node_named_child_count(name);
for (uint32_t i = 0; i < nc; i++) {
TSNode pn = ts_node_named_child(name, i);
- if (ts_node_is_null(pn)) continue;
- const char* pk = ts_node_type(pn);
+ if (ts_node_is_null(pn))
+ continue;
+ const char *pk = ts_node_type(pn);
if (strcmp(pk, "shorthand_property_identifier_pattern") == 0) {
- char* pnm = node_text(ctx, pn);
- if (pnm) cbm_scope_bind(ctx->current_scope, pnm, lookup_member_type(ctx, bound, pnm));
+ char *pnm = node_text(ctx, pn);
+ if (pnm)
+ cbm_scope_bind(ctx->current_scope, pnm, lookup_member_type(ctx, bound, pnm));
} else if (strcmp(pk, "pair_pattern") == 0) {
TSNode key = ts_node_child_by_field_name(pn, "key", TS_LSP_FIELD_LEN("key"));
TSNode val = ts_node_child_by_field_name(pn, "value", TS_LSP_FIELD_LEN("value"));
- if (!ts_node_is_null(key) && !ts_node_is_null(val) && node_kind_is(val, "identifier")) {
- char* knm = node_text(ctx, key);
- char* vnm = node_text(ctx, val);
+ if (!ts_node_is_null(key) && !ts_node_is_null(val) &&
+ node_kind_is(val, "identifier")) {
+ char *knm = node_text(ctx, key);
+ char *vnm = node_text(ctx, val);
if (knm && vnm) {
- cbm_scope_bind(ctx->current_scope, vnm, lookup_member_type(ctx, bound, knm));
+ cbm_scope_bind(ctx->current_scope, vnm,
+ lookup_member_type(ctx, bound, knm));
}
}
}
@@ -1739,11 +2003,14 @@ static void bind_variable_declarator(TSLSPContext* ctx, TSNode decl) {
uint32_t nc = ts_node_named_child_count(name);
for (uint32_t i = 0; i < nc; i++) {
TSNode pn = ts_node_named_child(name, i);
- if (ts_node_is_null(pn) || !node_kind_is(pn, "identifier")) continue;
- char* pnm = node_text(ctx, pn);
- if (!pnm) continue;
- const CBMType* et = cbm_type_unknown();
- if (bound && bound->kind == CBM_TYPE_TEMPLATE && bound->data.template_type.template_args &&
+ if (ts_node_is_null(pn) || !node_kind_is(pn, "identifier"))
+ continue;
+ char *pnm = node_text(ctx, pn);
+ if (!pnm)
+ continue;
+ const CBMType *et = cbm_type_unknown();
+ if (bound && bound->kind == CBM_TYPE_TEMPLATE &&
+ bound->data.template_type.template_args &&
bound->data.template_type.arg_count >= 1) {
et = bound->data.template_type.template_args[0];
} else if (bound && bound->kind == CBM_TYPE_TUPLE && bound->data.tuple.elems &&
@@ -1757,12 +2024,11 @@ static void bind_variable_declarator(TSLSPContext* ctx, TSNode decl) {
// Bind a single TS parameter into the current scope. Robust against grammar field-name
// variations: tries `pattern`, `name`, then falls back to first named child of the param.
-static void bind_parameter(TSLSPContext* ctx, TSNode param) {
- const char* pk = ts_node_type(param);
- if (strcmp(pk, "required_parameter") != 0 &&
- strcmp(pk, "optional_parameter") != 0 &&
- strcmp(pk, "tuple_parameter") != 0 &&
- strcmp(pk, "optional_tuple_parameter") != 0) return;
+static void bind_parameter(TSLSPContext *ctx, TSNode param) {
+ const char *pk = ts_node_type(param);
+ if (strcmp(pk, "required_parameter") != 0 && strcmp(pk, "optional_parameter") != 0 &&
+ strcmp(pk, "tuple_parameter") != 0 && strcmp(pk, "optional_tuple_parameter") != 0)
+ return;
// Find pattern: try field "pattern", then "name", then first non-type named child.
TSNode pattern = ts_node_child_by_field_name(param, "pattern", TS_LSP_FIELD_LEN("pattern"));
@@ -1773,15 +2039,19 @@ static void bind_parameter(TSLSPContext* ctx, TSNode param) {
uint32_t nc = ts_node_named_child_count(param);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(param, i);
- if (ts_node_is_null(c)) continue;
- const char* k = ts_node_type(c);
- if (strcmp(k, "type_annotation") == 0) continue;
- if (strcmp(k, "decorator") == 0) continue;
+ if (ts_node_is_null(c))
+ continue;
+ const char *k = ts_node_type(c);
+ if (strcmp(k, "type_annotation") == 0)
+ continue;
+ if (strcmp(k, "decorator") == 0)
+ continue;
pattern = c;
break;
}
}
- if (ts_node_is_null(pattern)) return;
+ if (ts_node_is_null(pattern))
+ return;
// Find the type annotation: prefer field "type", fall back to descending into a child
// of kind "type_annotation".
@@ -1797,39 +2067,43 @@ static void bind_parameter(TSLSPContext* ctx, TSNode param) {
}
}
- const CBMType* t = cbm_type_unknown();
+ const CBMType *t = cbm_type_unknown();
if (!ts_node_is_null(tann)) {
// The tree may give us either the type_annotation node or its inner type node.
TSNode tch = (strcmp(ts_node_type(tann), "type_annotation") == 0)
? ts_node_named_child(tann, 0)
: tann;
if (!ts_node_is_null(tch)) {
- const char* tk = ts_node_type(tch);
+ const char *tk = ts_node_type(tch);
// Inline object type `{ a: T; b: U }` — walk members and build OBJECT_LIT
// directly via AST. Falling back to text-parsing the node would yield UNKNOWN.
if (strcmp(tk, "object_type") == 0) {
- const char* p_names[32] = {0};
- const CBMType* p_types[32] = {0};
+ const char *p_names[32] = {0};
+ const CBMType *p_types[32] = {0};
int pcount = 0;
uint32_t omc = ts_node_named_child_count(tch);
for (uint32_t oi = 0; oi < omc && pcount < 31; oi++) {
TSNode m = ts_node_named_child(tch, oi);
- if (ts_node_is_null(m)) continue;
- const char* mk = ts_node_type(m);
+ if (ts_node_is_null(m))
+ continue;
+ const char *mk = ts_node_type(m);
if (strcmp(mk, "property_signature") == 0) {
- TSNode pname = ts_node_child_by_field_name(m, "name",
- TS_LSP_FIELD_LEN("name"));
- TSNode ptype = ts_node_child_by_field_name(m, "type",
- TS_LSP_FIELD_LEN("type"));
- if (ts_node_is_null(pname)) continue;
- char* pnm_text = node_text(ctx, pname);
- if (!pnm_text) continue;
- const CBMType* pt = cbm_type_unknown();
+ TSNode pname =
+ ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
+ TSNode ptype =
+ ts_node_child_by_field_name(m, "type", TS_LSP_FIELD_LEN("type"));
+ if (ts_node_is_null(pname))
+ continue;
+ char *pnm_text = node_text(ctx, pname);
+ if (!pnm_text)
+ continue;
+ const CBMType *pt = cbm_type_unknown();
if (!ts_node_is_null(ptype)) {
TSNode ptch = (strcmp(ts_node_type(ptype), "type_annotation") == 0)
? ts_node_named_child(ptype, 0)
: ptype;
- if (!ts_node_is_null(ptch)) pt = ts_parse_type_node(ctx, ptch);
+ if (!ts_node_is_null(ptch))
+ pt = ts_parse_type_node(ctx, ptch);
}
p_names[pcount] = pnm_text;
p_types[pcount] = pt;
@@ -1846,25 +2120,26 @@ static void bind_parameter(TSLSPContext* ctx, TSNode param) {
}
if (node_kind_is(pattern, "identifier")) {
- char* nm = node_text(ctx, pattern);
- if (nm) cbm_scope_bind(ctx->current_scope, nm, t);
+ char *nm = node_text(ctx, pattern);
+ if (nm)
+ cbm_scope_bind(ctx->current_scope, nm, t);
} else if (node_kind_is(pattern, "object_pattern")) {
uint32_t nc = ts_node_named_child_count(pattern);
for (uint32_t i = 0; i < nc; i++) {
TSNode p = ts_node_named_child(pattern, i);
if (node_kind_is(p, "shorthand_property_identifier_pattern")) {
- char* pnm = node_text(ctx, p);
- if (pnm) cbm_scope_bind(ctx->current_scope, pnm, lookup_member_type(ctx, t, pnm));
+ char *pnm = node_text(ctx, p);
+ if (pnm)
+ cbm_scope_bind(ctx->current_scope, pnm, lookup_member_type(ctx, t, pnm));
} else if (node_kind_is(p, "pair_pattern")) {
TSNode key = ts_node_child_by_field_name(p, "key", TS_LSP_FIELD_LEN("key"));
TSNode val = ts_node_child_by_field_name(p, "value", TS_LSP_FIELD_LEN("value"));
if (!ts_node_is_null(key) && !ts_node_is_null(val) &&
node_kind_is(val, "identifier")) {
- char* knm = node_text(ctx, key);
- char* vnm = node_text(ctx, val);
+ char *knm = node_text(ctx, key);
+ char *vnm = node_text(ctx, val);
if (knm && vnm) {
- cbm_scope_bind(ctx->current_scope, vnm,
- lookup_member_type(ctx, t, knm));
+ cbm_scope_bind(ctx->current_scope, vnm, lookup_member_type(ctx, t, knm));
}
}
}
@@ -1873,10 +2148,12 @@ static void bind_parameter(TSLSPContext* ctx, TSNode param) {
uint32_t nc = ts_node_named_child_count(pattern);
for (uint32_t i = 0; i < nc; i++) {
TSNode p = ts_node_named_child(pattern, i);
- if (!node_kind_is(p, "identifier")) continue;
- char* pnm = node_text(ctx, p);
- if (!pnm) continue;
- const CBMType* et = cbm_type_unknown();
+ if (!node_kind_is(p, "identifier"))
+ continue;
+ char *pnm = node_text(ctx, p);
+ if (!pnm)
+ continue;
+ const CBMType *et = cbm_type_unknown();
if (t && t->kind == CBM_TYPE_TEMPLATE && t->data.template_type.template_args &&
t->data.template_type.arg_count >= 1) {
et = t->data.template_type.template_args[0];
@@ -1886,22 +2163,24 @@ static void bind_parameter(TSLSPContext* ctx, TSNode param) {
}
}
-void ts_process_statement(TSLSPContext* ctx, TSNode node) {
- if (!ctx || ts_node_is_null(node)) return;
- const char* kind = ts_node_type(node);
+void ts_process_statement(TSLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
if (strcmp(kind, "lexical_declaration") == 0 || strcmp(kind, "variable_declaration") == 0) {
uint32_t nc = ts_node_named_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(node, i);
- if (node_kind_is(c, "variable_declarator")) bind_variable_declarator(ctx, c);
+ if (node_kind_is(c, "variable_declarator"))
+ bind_variable_declarator(ctx, c);
}
} else if (strcmp(kind, "for_in_statement") == 0 || strcmp(kind, "for_of_statement") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", TS_LSP_FIELD_LEN("left"));
TSNode right = ts_node_child_by_field_name(node, "right", TS_LSP_FIELD_LEN("right"));
if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
- const CBMType* iter = ts_eval_expr_type(ctx, right);
- const CBMType* elem = cbm_type_unknown();
+ const CBMType *iter = ts_eval_expr_type(ctx, right);
+ const CBMType *elem = cbm_type_unknown();
if (iter && iter->kind == CBM_TYPE_TEMPLATE && iter->data.template_type.template_args &&
iter->data.template_type.arg_count >= 1) {
elem = iter->data.template_type.template_args[0];
@@ -1913,13 +2192,15 @@ void ts_process_statement(TSLSPContext* ctx, TSNode node) {
if (node_kind_is(v, "variable_declarator")) {
TSNode nm = ts_node_child_by_field_name(v, "name", TS_LSP_FIELD_LEN("name"));
if (node_kind_is(nm, "identifier")) {
- char* s = node_text(ctx, nm);
- if (s) cbm_scope_bind(ctx->current_scope, s, elem);
+ char *s = node_text(ctx, nm);
+ if (s)
+ cbm_scope_bind(ctx->current_scope, s, elem);
}
}
} else if (node_kind_is(left, "identifier")) {
- char* s = node_text(ctx, left);
- if (s) cbm_scope_bind(ctx->current_scope, s, elem);
+ char *s = node_text(ctx, left);
+ if (s)
+ cbm_scope_bind(ctx->current_scope, s, elem);
}
}
}
@@ -1927,43 +2208,46 @@ void ts_process_statement(TSLSPContext* ctx, TSNode node) {
// ── Call resolution + tree walk ───────────────────────────────────────────────
-static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
+static void resolve_call_at(TSLSPContext *ctx, TSNode call_node) {
TSNode fn = ts_node_child_by_field_name(call_node, "function", TS_LSP_FIELD_LEN("function"));
- if (ts_node_is_null(fn)) return;
+ if (ts_node_is_null(fn))
+ return;
// Argument count.
int arg_count = 0;
- TSNode args = ts_node_child_by_field_name(call_node, "arguments", TS_LSP_FIELD_LEN("arguments"));
- if (!ts_node_is_null(args)) arg_count = (int)ts_node_named_child_count(args);
+ TSNode args =
+ ts_node_child_by_field_name(call_node, "arguments", TS_LSP_FIELD_LEN("arguments"));
+ if (!ts_node_is_null(args))
+ arg_count = (int)ts_node_named_child_count(args);
- const char* fk = ts_node_type(fn);
+ const char *fk = ts_node_type(fn);
// member_expression: obj.method(...)
if (strcmp(fk, "member_expression") == 0) {
TSNode obj = ts_node_child_by_field_name(fn, "object", TS_LSP_FIELD_LEN("object"));
TSNode prop = ts_node_child_by_field_name(fn, "property", TS_LSP_FIELD_LEN("property"));
if (!ts_node_is_null(obj) && !ts_node_is_null(prop)) {
- char* mname = node_text(ctx, prop);
+ char *mname = node_text(ctx, prop);
if (mname) {
// Identifier as namespace import: `name.fn()` or `mod.fn()`.
if (node_kind_is(obj, "identifier")) {
- char* on = node_text(ctx, obj);
+ char *on = node_text(ctx, obj);
if (on) {
for (int i = 0; i < ctx->import_count; i++) {
- const char* lname = ctx->import_local_names ?
- ctx->import_local_names[i] : NULL;
- const char* mqn = ctx->import_module_qns ?
- ctx->import_module_qns[i] : NULL;
+ const char *lname =
+ ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *mqn =
+ ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
if (lname && mqn && strcmp(lname, on) == 0) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol_by_args(
+ const CBMRegisteredFunc *f = cbm_registry_lookup_symbol_by_args(
ctx->registry, mqn, mname, arg_count);
if (f) {
ts_emit_resolved_call(ctx, f->qualified_name,
- "lsp_ts_namespace", 0.95f);
+ "lsp_ts_namespace", 0.95f);
return;
}
- ts_emit_unresolved_call(ctx,
- cbm_arena_sprintf(ctx->arena, "%s.%s", on, mname),
+ ts_emit_unresolved_call(
+ ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", on, mname),
"module_symbol_not_in_registry");
return;
}
@@ -1971,29 +2255,28 @@ static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
}
}
// Type-based dispatch.
- const CBMType* recv = ts_eval_expr_type(ctx, obj);
- const CBMRegisteredFunc* f = lookup_method(ctx, recv, mname);
+ const CBMType *recv = ts_eval_expr_type(ctx, obj);
+ const CBMRegisteredFunc *f = lookup_method(ctx, recv, mname);
// Overload resolution by arg types: when receiver is NAMED and the
// registry has multiple overloads (same receiver+name), eval each
// arg's type and let cbm_registry_lookup_method_by_types score them.
// Falls back to the first match if scoring fails.
if (f && recv) {
- const CBMType* base = simplify_type(ctx, recv);
+ const CBMType *base = simplify_type(ctx, recv);
base = base ? unwrap_passthrough_template(base) : NULL;
- if (base && base->kind == CBM_TYPE_NAMED &&
- base->data.named.qualified_name && arg_count > 0) {
- const CBMType* arg_types[16] = {0};
+ if (base && base->kind == CBM_TYPE_NAMED && base->data.named.qualified_name &&
+ arg_count > 0) {
+ const CBMType *arg_types[16] = {0};
int n = arg_count > 16 ? 16 : arg_count;
for (int i = 0; i < n; i++) {
TSNode arg = ts_node_named_child(args, (uint32_t)i);
arg_types[i] = ts_eval_expr_type(ctx, arg);
}
- const CBMRegisteredFunc* better =
- cbm_registry_lookup_method_by_types(ctx->registry,
- base->data.named.qualified_name,
- mname, arg_types, n);
- if (better) f = better;
+ const CBMRegisteredFunc *better = cbm_registry_lookup_method_by_types(
+ ctx->registry, base->data.named.qualified_name, mname, arg_types, n);
+ if (better)
+ f = better;
}
}
@@ -2009,11 +2292,12 @@ static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
// identifier: free function call.
if (strcmp(fk, "identifier") == 0) {
- char* name = node_text(ctx, fn);
- if (!name) return;
+ char *name = node_text(ctx, fn);
+ if (!name)
+ return;
// Eval arg types up-front for type-aware overload resolution.
- const CBMType* arg_types[16] = {0};
+ const CBMType *arg_types[16] = {0};
int typed_arg_n = 0;
if (!ts_node_is_null(args) && arg_count > 0) {
typed_arg_n = arg_count > 16 ? 16 : arg_count;
@@ -2025,14 +2309,14 @@ static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
// Module-local function: prefer by-types when args are typed.
if (ctx->module_qn) {
- const CBMRegisteredFunc* f = NULL;
+ const CBMRegisteredFunc *f = NULL;
if (typed_arg_n > 0) {
- f = cbm_registry_lookup_symbol_by_types(ctx->registry, ctx->module_qn,
- name, arg_types, typed_arg_n);
+ f = cbm_registry_lookup_symbol_by_types(ctx->registry, ctx->module_qn, name,
+ arg_types, typed_arg_n);
}
if (!f) {
- f = cbm_registry_lookup_symbol_by_args(ctx->registry, ctx->module_qn,
- name, arg_count);
+ f = cbm_registry_lookup_symbol_by_args(ctx->registry, ctx->module_qn, name,
+ arg_count);
}
if (f) {
ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_local", 0.95f);
@@ -2041,17 +2325,17 @@ static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
}
// Imported default/named function.
for (int i = 0; i < ctx->import_count; i++) {
- const char* lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
- const char* mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ const char *lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
if (lname && mqn && strcmp(lname, name) == 0) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol_by_args(
- ctx->registry, mqn, name, arg_count);
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol_by_args(ctx->registry, mqn, name, arg_count);
if (f) {
ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_import", 0.95f);
return;
}
// Fall through to qualified_name fallback.
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, name);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, name);
ts_emit_unresolved_call(ctx, qn, "import_symbol_not_in_registry");
return;
}
@@ -2064,65 +2348,65 @@ static void resolve_call_at(TSLSPContext* ctx, TSNode call_node) {
// contextually typed by the enclosing call (e.g. `arr.map(x => x.length)` — `x` should
// be bound to `arr`'s element type via Array<T>.map's `(x: T) => U` signature). The
// caller passes `expected` = the FUNC type the callback must conform to.
-static void process_callback_arrow(TSLSPContext* ctx, TSNode arrow, const CBMType* expected) {
- if (ts_node_is_null(arrow) || !expected || expected->kind != CBM_TYPE_FUNC) return;
+static void process_callback_arrow(TSLSPContext *ctx, TSNode arrow, const CBMType *expected) {
+ if (ts_node_is_null(arrow) || !expected || expected->kind != CBM_TYPE_FUNC)
+ return;
- CBMScope* saved = ctx->current_scope;
+ CBMScope *saved = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, saved);
// Tree-sitter typescript shapes for arrow functions:
// `(x, y) => body` → parameters: formal_parameters
// `x => body` → parameter: identifier (singular field)
- TSNode params = ts_node_child_by_field_name(arrow, "parameters",
- TS_LSP_FIELD_LEN("parameters"));
- TSNode bare_param = ts_node_child_by_field_name(arrow, "parameter",
- TS_LSP_FIELD_LEN("parameter"));
+ TSNode params =
+ ts_node_child_by_field_name(arrow, "parameters", TS_LSP_FIELD_LEN("parameters"));
+ TSNode bare_param =
+ ts_node_child_by_field_name(arrow, "parameter", TS_LSP_FIELD_LEN("parameter"));
int idx = 0;
if (!ts_node_is_null(bare_param)) {
// Single bare param: `x => ...`.
- const char* pk = ts_node_type(bare_param);
+ const char *pk = ts_node_type(bare_param);
if (strcmp(pk, "identifier") == 0) {
- char* nm = node_text(ctx, bare_param);
- const CBMType* pt = (expected->data.func.param_types &&
- expected->data.func.param_types[0])
- ? expected->data.func.param_types[0]
- : cbm_type_unknown();
- if (nm) cbm_scope_bind(ctx->current_scope, nm, pt);
+ char *nm = node_text(ctx, bare_param);
+ const CBMType *pt =
+ (expected->data.func.param_types && expected->data.func.param_types[0])
+ ? expected->data.func.param_types[0]
+ : cbm_type_unknown();
+ if (nm)
+ cbm_scope_bind(ctx->current_scope, nm, pt);
}
} else if (!ts_node_is_null(params)) {
uint32_t pc = ts_node_named_child_count(params);
for (uint32_t i = 0; i < pc; i++) {
TSNode p = ts_node_named_child(params, i);
- if (ts_node_is_null(p)) continue;
- const char* pk = ts_node_type(p);
- const char* pname = NULL;
- const CBMType* expected_pt = (expected->data.func.param_types &&
- expected->data.func.param_types[idx])
- ? expected->data.func.param_types[idx]
- : NULL;
+ if (ts_node_is_null(p))
+ continue;
+ const char *pk = ts_node_type(p);
+ const char *pname = NULL;
+ const CBMType *expected_pt =
+ (expected->data.func.param_types && expected->data.func.param_types[idx])
+ ? expected->data.func.param_types[idx]
+ : NULL;
if (strcmp(pk, "identifier") == 0) {
pname = node_text(ctx, p);
} else {
// required_parameter / optional_parameter — extract pattern.
- TSNode pp = ts_node_child_by_field_name(p, "pattern",
- TS_LSP_FIELD_LEN("pattern"));
+ TSNode pp = ts_node_child_by_field_name(p, "pattern", TS_LSP_FIELD_LEN("pattern"));
if (ts_node_is_null(pp)) {
- pp = ts_node_child_by_field_name(p, "name",
- TS_LSP_FIELD_LEN("name"));
+ pp = ts_node_child_by_field_name(p, "name", TS_LSP_FIELD_LEN("name"));
}
if (!ts_node_is_null(pp) && strcmp(ts_node_type(pp), "identifier") == 0) {
pname = node_text(ctx, pp);
}
// If the param has its own annotation, use that. Otherwise use expected.
- TSNode tann = ts_node_child_by_field_name(p, "type",
- TS_LSP_FIELD_LEN("type"));
+ TSNode tann = ts_node_child_by_field_name(p, "type", TS_LSP_FIELD_LEN("type"));
if (!ts_node_is_null(tann)) {
TSNode tch = (strcmp(ts_node_type(tann), "type_annotation") == 0)
? ts_node_named_child(tann, 0)
: tann;
if (!ts_node_is_null(tch)) {
- const CBMType* annotated = ts_parse_type_node(ctx, tch);
+ const CBMType *annotated = ts_parse_type_node(ctx, tch);
if (!cbm_type_is_unknown(annotated)) {
expected_pt = annotated;
}
@@ -2160,36 +2444,36 @@ static void process_callback_arrow(TSLSPContext* ctx, TSNode arrow, const CBMTyp
// On success: writes the narrowed variable name and target type, plus whether the
// match polarity is `==` (true → consequence) or `!=` (true → alternative).
// Returns true if narrowing applies.
-static bool extract_narrowing(TSLSPContext* ctx, TSNode condition,
- const char** out_var, const CBMType** out_type,
- bool* out_inverted) {
+static bool extract_narrowing(TSLSPContext *ctx, TSNode condition, const char **out_var,
+ const CBMType **out_type, bool *out_inverted) {
*out_var = NULL;
*out_type = NULL;
*out_inverted = false;
- if (ts_node_is_null(condition)) return false;
+ if (ts_node_is_null(condition))
+ return false;
// Strip outer parens if any.
while (!ts_node_is_null(condition) &&
strcmp(ts_node_type(condition), "parenthesized_expression") == 0) {
condition = ts_node_named_child(condition, 0);
}
- if (ts_node_is_null(condition)) return false;
- const char* k = ts_node_type(condition);
+ if (ts_node_is_null(condition))
+ return false;
+ const char *k = ts_node_type(condition);
// `x instanceof Foo`: binary_expression with operator "instanceof".
if (strcmp(k, "binary_expression") == 0) {
- TSNode op = ts_node_child_by_field_name(condition, "operator",
- TS_LSP_FIELD_LEN("operator"));
- char* opt = ts_node_is_null(op) ? NULL : node_text(ctx, op);
+ TSNode op =
+ ts_node_child_by_field_name(condition, "operator", TS_LSP_FIELD_LEN("operator"));
+ char *opt = ts_node_is_null(op) ? NULL : node_text(ctx, op);
TSNode left = ts_node_child_by_field_name(condition, "left", TS_LSP_FIELD_LEN("left"));
TSNode right = ts_node_child_by_field_name(condition, "right", TS_LSP_FIELD_LEN("right"));
- if (opt && strcmp(opt, "instanceof") == 0 &&
- !ts_node_is_null(left) && !ts_node_is_null(right) &&
- strcmp(ts_node_type(left), "identifier") == 0 &&
+ if (opt && strcmp(opt, "instanceof") == 0 && !ts_node_is_null(left) &&
+ !ts_node_is_null(right) && strcmp(ts_node_type(left), "identifier") == 0 &&
strcmp(ts_node_type(right), "identifier") == 0) {
*out_var = node_text(ctx, left);
- char* class_name = node_text(ctx, right);
+ char *class_name = node_text(ctx, right);
if (class_name) {
*out_type = parse_ts_type_text(ctx->arena, class_name, ctx->module_qn);
*out_type = resolve_type_with_imports(ctx, *out_type);
@@ -2198,29 +2482,28 @@ static bool extract_narrowing(TSLSPContext* ctx, TSNode condition,
}
// `typeof x === 'string'` / `typeof x !== 'number'`
- if (opt && (strcmp(opt, "===") == 0 || strcmp(opt, "==") == 0 ||
- strcmp(opt, "!==") == 0 || strcmp(opt, "!=") == 0) &&
+ if (opt &&
+ (strcmp(opt, "===") == 0 || strcmp(opt, "==") == 0 || strcmp(opt, "!==") == 0 ||
+ strcmp(opt, "!=") == 0) &&
!ts_node_is_null(left) && !ts_node_is_null(right)) {
bool inverted = (strcmp(opt, "!==") == 0 || strcmp(opt, "!=") == 0);
// typeof x === 'string'
if (strcmp(ts_node_type(left), "unary_expression") == 0) {
- TSNode op2 = ts_node_child_by_field_name(left, "operator",
- TS_LSP_FIELD_LEN("operator"));
- char* opt2 = ts_node_is_null(op2) ? NULL : node_text(ctx, op2);
- TSNode arg = ts_node_child_by_field_name(left, "argument",
- TS_LSP_FIELD_LEN("argument"));
- if (opt2 && strcmp(opt2, "typeof") == 0 &&
- !ts_node_is_null(arg) &&
+ TSNode op2 =
+ ts_node_child_by_field_name(left, "operator", TS_LSP_FIELD_LEN("operator"));
+ char *opt2 = ts_node_is_null(op2) ? NULL : node_text(ctx, op2);
+ TSNode arg =
+ ts_node_child_by_field_name(left, "argument", TS_LSP_FIELD_LEN("argument"));
+ if (opt2 && strcmp(opt2, "typeof") == 0 && !ts_node_is_null(arg) &&
strcmp(ts_node_type(arg), "identifier") == 0 &&
strcmp(ts_node_type(right), "string") == 0) {
*out_var = node_text(ctx, arg);
- char* lit = node_text(ctx, right);
+ char *lit = node_text(ctx, right);
if (lit) {
// Strip surrounding quotes.
size_t ll = strlen(lit);
- if (ll >= 2 && (lit[0] == '"' || lit[0] == '\'') &&
- lit[ll - 1] == lit[0]) {
+ if (ll >= 2 && (lit[0] == '"' || lit[0] == '\'') && lit[ll - 1] == lit[0]) {
lit[ll - 1] = '\0';
lit++;
}
@@ -2239,58 +2522,72 @@ static bool extract_narrowing(TSLSPContext* ctx, TSNode condition,
// Look up a union member that satisfies a discriminant: when narrowed via `x.kind ===
// 'foo'`, find the member of x's type whose `kind` property is the literal 'foo'.
// Returns NULL if no match. Pragmatic v1: only handles `member_expression === string`.
-static const CBMType* narrow_discriminated_union(TSLSPContext* ctx, TSNode condition,
- const char** out_var) {
+static const CBMType *narrow_discriminated_union(TSLSPContext *ctx, TSNode condition,
+ const char **out_var) {
*out_var = NULL;
- if (ts_node_is_null(condition)) return NULL;
+ if (ts_node_is_null(condition))
+ return NULL;
while (!ts_node_is_null(condition) &&
strcmp(ts_node_type(condition), "parenthesized_expression") == 0) {
condition = ts_node_named_child(condition, 0);
}
- if (ts_node_is_null(condition)) return NULL;
- if (strcmp(ts_node_type(condition), "binary_expression") != 0) return NULL;
+ if (ts_node_is_null(condition))
+ return NULL;
+ if (strcmp(ts_node_type(condition), "binary_expression") != 0)
+ return NULL;
- TSNode op = ts_node_child_by_field_name(condition, "operator",
- TS_LSP_FIELD_LEN("operator"));
- char* opt = ts_node_is_null(op) ? NULL : node_text(ctx, op);
- if (!opt || (strcmp(opt, "===") != 0 && strcmp(opt, "==") != 0)) return NULL;
+ TSNode op = ts_node_child_by_field_name(condition, "operator", TS_LSP_FIELD_LEN("operator"));
+ char *opt = ts_node_is_null(op) ? NULL : node_text(ctx, op);
+ if (!opt || (strcmp(opt, "===") != 0 && strcmp(opt, "==") != 0))
+ return NULL;
TSNode left = ts_node_child_by_field_name(condition, "left", TS_LSP_FIELD_LEN("left"));
TSNode right = ts_node_child_by_field_name(condition, "right", TS_LSP_FIELD_LEN("right"));
- if (ts_node_is_null(left) || ts_node_is_null(right)) return NULL;
+ if (ts_node_is_null(left) || ts_node_is_null(right))
+ return NULL;
// left = `x.kind`, right = string literal.
if (strcmp(ts_node_type(left), "member_expression") != 0 ||
- strcmp(ts_node_type(right), "string") != 0) return NULL;
+ strcmp(ts_node_type(right), "string") != 0)
+ return NULL;
TSNode obj = ts_node_child_by_field_name(left, "object", TS_LSP_FIELD_LEN("object"));
TSNode prop = ts_node_child_by_field_name(left, "property", TS_LSP_FIELD_LEN("property"));
- if (ts_node_is_null(obj) || strcmp(ts_node_type(obj), "identifier") != 0) return NULL;
- if (ts_node_is_null(prop)) return NULL;
- char* var_name = node_text(ctx, obj);
- char* prop_name = node_text(ctx, prop);
- char* lit = node_text(ctx, right);
- if (!var_name || !prop_name || !lit) return NULL;
+ if (ts_node_is_null(obj) || strcmp(ts_node_type(obj), "identifier") != 0)
+ return NULL;
+ if (ts_node_is_null(prop))
+ return NULL;
+ char *var_name = node_text(ctx, obj);
+ char *prop_name = node_text(ctx, prop);
+ char *lit = node_text(ctx, right);
+ if (!var_name || !prop_name || !lit)
+ return NULL;
size_t ll = strlen(lit);
if (ll >= 2 && (lit[0] == '"' || lit[0] == '\'') && lit[ll - 1] == lit[0]) {
lit[ll - 1] = '\0';
lit++;
}
- const CBMType* var_type = cbm_scope_lookup(ctx->current_scope, var_name);
- if (!var_type || var_type->kind != CBM_TYPE_UNION) return NULL;
- if (!var_type->data.union_type.members) return NULL;
+ const CBMType *var_type = cbm_scope_lookup(ctx->current_scope, var_name);
+ if (!var_type || var_type->kind != CBM_TYPE_UNION)
+ return NULL;
+ if (!var_type->data.union_type.members)
+ return NULL;
for (int i = 0; i < var_type->data.union_type.count; i++) {
- const CBMType* m = var_type->data.union_type.members[i];
- if (!m || m->kind != CBM_TYPE_NAMED) continue;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(ctx->registry,
- m->data.named.qualified_name);
- if (!rt || !rt->field_names || !rt->field_types) continue;
+ const CBMType *m = var_type->data.union_type.members[i];
+ if (!m || m->kind != CBM_TYPE_NAMED)
+ continue;
+ const CBMRegisteredType *rt =
+ cbm_registry_lookup_type(ctx->registry, m->data.named.qualified_name);
+ if (!rt || !rt->field_names || !rt->field_types)
+ continue;
for (int j = 0; rt->field_names[j]; j++) {
- if (strcmp(rt->field_names[j], prop_name) != 0) continue;
- const CBMType* ft = rt->field_types[j];
- if (!ft) continue;
+ if (strcmp(rt->field_names[j], prop_name) != 0)
+ continue;
+ const CBMType *ft = rt->field_types[j];
+ if (!ft)
+ continue;
// Discriminant fields are typically string-literal types (`'circle'`) or
// the BUILTIN("string") fallback. For BUILTIN fallback we can't narrow
// precisely, so skip unless the parsed text matches our literal.
@@ -2302,7 +2599,7 @@ static const CBMType* narrow_discriminated_union(TSLSPContext* ctx, TSNode condi
// Some interfaces declare `kind: 'circle'` as NAMED("'circle'") via
// text fall-through; handle that too.
if (ft->kind == CBM_TYPE_NAMED && ft->data.named.qualified_name) {
- const char* qn = ft->data.named.qualified_name;
+ const char *qn = ft->data.named.qualified_name;
size_t qnl = strlen(qn);
if (qnl >= 2 && (qn[0] == '\'' || qn[0] == '"') && qn[qnl - 1] == qn[0]) {
if (strncmp(qn + 1, lit, qnl - 2) == 0 && strlen(lit) == qnl - 2) {
@@ -2319,28 +2616,33 @@ static const CBMType* narrow_discriminated_union(TSLSPContext* ctx, TSNode condi
// Resolve a JSX element opening — emits a resolved call edge for component invocations.
// `<Foo prop={x}/>` and `<Foo>...</Foo>` both invoke the component as a function.
// Lowercase first letter is treated as a JSX intrinsic (HTML element) and ignored.
-static void resolve_jsx_element(TSLSPContext* ctx, TSNode element_node) {
- if (!ctx->jsx_mode) return;
+static void resolve_jsx_element(TSLSPContext *ctx, TSNode element_node) {
+ if (!ctx->jsx_mode)
+ return;
// The element's first named child is the opening element (or self-closing).
- const char* kind = ts_node_type(element_node);
+ const char *kind = ts_node_type(element_node);
TSNode tag = element_node;
if (strcmp(kind, "jsx_element") == 0) {
TSNode opening = ts_node_named_child(element_node, 0);
- if (!ts_node_is_null(opening)) tag = opening;
+ if (!ts_node_is_null(opening))
+ tag = opening;
}
// Get the name from the opening / self_closing element. Field is "name".
TSNode name_node = ts_node_child_by_field_name(tag, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name_node)) return;
- char* tag_name = node_text(ctx, name_node);
- if (!tag_name || !tag_name[0]) return;
+ if (ts_node_is_null(name_node))
+ return;
+ char *tag_name = node_text(ctx, name_node);
+ if (!tag_name || !tag_name[0])
+ return;
// Lowercase first → intrinsic (HTML element). Skip emission.
- if (tag_name[0] >= 'a' && tag_name[0] <= 'z') return;
+ if (tag_name[0] >= 'a' && tag_name[0] <= 'z')
+ return;
// Resolve as a free-function/component call.
if (ctx->module_qn) {
- const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry,
- ctx->module_qn, tag_name);
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, tag_name);
if (f) {
ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_jsx", 0.95f);
return;
@@ -2348,10 +2650,10 @@ static void resolve_jsx_element(TSLSPContext* ctx, TSNode element_node) {
}
// Try imports.
for (int i = 0; i < ctx->import_count; i++) {
- const char* lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
- const char* mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ const char *lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
if (lname && mqn && strcmp(lname, tag_name) == 0) {
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, tag_name);
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, tag_name);
ts_emit_resolved_call(ctx, qn, "lsp_ts_jsx_import", 0.85f);
return;
}
@@ -2359,9 +2661,10 @@ static void resolve_jsx_element(TSLSPContext* ctx, TSNode element_node) {
ts_emit_unresolved_call(ctx, tag_name, "jsx_component_not_in_registry");
}
-static void process_node(TSLSPContext* ctx, TSNode node) {
- if (!ctx || ts_node_is_null(node)) return;
- const char* kind = ts_node_type(node);
+static void process_node(TSLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
// Scope-affecting statements bind first, then we recurse.
ts_process_statement(ctx, node);
@@ -2375,15 +2678,19 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// Handle arg processing manually for this path to avoid double-walking via
// default recurse below.
do {
- TSNode fn_node = ts_node_child_by_field_name(node, "function",
- TS_LSP_FIELD_LEN("function"));
- if (ts_node_is_null(fn_node)) break;
- const CBMType* fn_type = ts_eval_expr_type(ctx, fn_node);
- if (!fn_type || fn_type->kind != CBM_TYPE_FUNC) break;
- if (!fn_type->data.func.param_types) break;
- TSNode args = ts_node_child_by_field_name(node, "arguments",
- TS_LSP_FIELD_LEN("arguments"));
- if (ts_node_is_null(args)) break;
+ TSNode fn_node =
+ ts_node_child_by_field_name(node, "function", TS_LSP_FIELD_LEN("function"));
+ if (ts_node_is_null(fn_node))
+ break;
+ const CBMType *fn_type = ts_eval_expr_type(ctx, fn_node);
+ if (!fn_type || fn_type->kind != CBM_TYPE_FUNC)
+ break;
+ if (!fn_type->data.func.param_types)
+ break;
+ TSNode args =
+ ts_node_child_by_field_name(node, "arguments", TS_LSP_FIELD_LEN("arguments"));
+ if (ts_node_is_null(args))
+ break;
// Process the function child for nested call resolution.
process_node(ctx, fn_node);
@@ -2395,31 +2702,31 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// 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++;
+ 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 =
+ if (ts_node_is_null(arg))
+ continue;
+ const char *ak = ts_node_type(arg);
+ 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) &&
+ if ((strcmp(ak, "arrow_function") == 0 || strcmp(ak, "function_expression") == 0) &&
expected && expected->kind == CBM_TYPE_FUNC) {
process_callback_arrow(ctx, arg, expected);
} else {
process_node(ctx, arg);
}
}
- return; // Skip default recurse since we processed children manually.
+ return; // Skip default recurse since we processed children manually.
} while (0);
}
// JSX element resolution (TSX / JSX modes).
if (ctx->jsx_mode &&
- (strcmp(kind, "jsx_element") == 0 ||
- strcmp(kind, "jsx_self_closing_element") == 0)) {
+ (strcmp(kind, "jsx_element") == 0 || strcmp(kind, "jsx_self_closing_element") == 0)) {
resolve_jsx_element(ctx, node);
}
@@ -2429,12 +2736,13 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
TSNode value = ts_node_child_by_field_name(node, "value", TS_LSP_FIELD_LEN("value"));
TSNode body = ts_node_child_by_field_name(node, "body", TS_LSP_FIELD_LEN("body"));
// Walk the value expression so any nested calls resolve.
- if (!ts_node_is_null(value)) process_node(ctx, value);
+ if (!ts_node_is_null(value))
+ process_node(ctx, value);
// Identify discriminant: switch on `x.kind` member_expression.
- const char* disc_var = NULL;
- const char* disc_prop = NULL;
- const CBMType* var_union = NULL;
+ const char *disc_var = NULL;
+ const char *disc_prop = NULL;
+ const CBMType *var_union = NULL;
if (!ts_node_is_null(value)) {
// Strip parens.
TSNode v = value;
@@ -2444,15 +2752,16 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
}
if (!ts_node_is_null(v) && strcmp(ts_node_type(v), "member_expression") == 0) {
TSNode obj = ts_node_child_by_field_name(v, "object", TS_LSP_FIELD_LEN("object"));
- TSNode prop = ts_node_child_by_field_name(v, "property",
- TS_LSP_FIELD_LEN("property"));
+ TSNode prop =
+ ts_node_child_by_field_name(v, "property", TS_LSP_FIELD_LEN("property"));
if (!ts_node_is_null(obj) && !ts_node_is_null(prop) &&
strcmp(ts_node_type(obj), "identifier") == 0) {
disc_var = node_text(ctx, obj);
disc_prop = node_text(ctx, prop);
if (disc_var) {
- const CBMType* t = cbm_scope_lookup(ctx->current_scope, disc_var);
- if (t && t->kind == CBM_TYPE_UNION) var_union = t;
+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, disc_var);
+ if (t && t->kind == CBM_TYPE_UNION)
+ var_union = t;
}
}
}
@@ -2463,21 +2772,22 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
uint32_t bnc = ts_node_named_child_count(body);
for (uint32_t i = 0; i < bnc; i++) {
TSNode case_node = ts_node_named_child(body, i);
- if (ts_node_is_null(case_node)) continue;
- const char* ck = ts_node_type(case_node);
+ if (ts_node_is_null(case_node))
+ continue;
+ const char *ck = ts_node_type(case_node);
if (strcmp(ck, "switch_case") != 0 && strcmp(ck, "switch_default") != 0) {
process_node(ctx, case_node);
continue;
}
// Find this case's literal value.
- const CBMType* narrowed = NULL;
+ const CBMType *narrowed = NULL;
if (var_union && disc_prop && strcmp(ck, "switch_case") == 0) {
- TSNode case_value = ts_node_child_by_field_name(case_node, "value",
- TS_LSP_FIELD_LEN("value"));
+ TSNode case_value =
+ ts_node_child_by_field_name(case_node, "value", TS_LSP_FIELD_LEN("value"));
if (!ts_node_is_null(case_value) &&
strcmp(ts_node_type(case_value), "string") == 0) {
- char* lit = node_text(ctx, case_value);
+ char *lit = node_text(ctx, case_value);
if (lit) {
size_t ll = strlen(lit);
if (ll >= 2 && (lit[0] == '"' || lit[0] == '\'') &&
@@ -2487,22 +2797,28 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
}
// Match member with matching discriminant field literal.
for (int mi = 0; mi < var_union->data.union_type.count; mi++) {
- const CBMType* m = var_union->data.union_type.members[mi];
- if (!m || m->kind != CBM_TYPE_NAMED) continue;
- const CBMRegisteredType* rt = cbm_registry_lookup_type(
+ const CBMType *m = var_union->data.union_type.members[mi];
+ if (!m || m->kind != CBM_TYPE_NAMED)
+ continue;
+ const CBMRegisteredType *rt = cbm_registry_lookup_type(
ctx->registry, m->data.named.qualified_name);
- if (!rt || !rt->field_names || !rt->field_types) continue;
+ if (!rt || !rt->field_names || !rt->field_types)
+ continue;
for (int fj = 0; rt->field_names[fj]; fj++) {
- if (strcmp(rt->field_names[fj], disc_prop) != 0) continue;
- const CBMType* ft = rt->field_types[fj];
- if (!ft) continue;
- if (ft->kind == CBM_TYPE_TS_LITERAL && ft->data.literal_ts.value &&
+ if (strcmp(rt->field_names[fj], disc_prop) != 0)
+ continue;
+ const CBMType *ft = rt->field_types[fj];
+ if (!ft)
+ continue;
+ if (ft->kind == CBM_TYPE_TS_LITERAL &&
+ ft->data.literal_ts.value &&
strcmp(ft->data.literal_ts.value, lit) == 0) {
narrowed = m;
break;
}
- if (ft->kind == CBM_TYPE_NAMED && ft->data.named.qualified_name) {
- const char* qn = ft->data.named.qualified_name;
+ if (ft->kind == CBM_TYPE_NAMED &&
+ ft->data.named.qualified_name) {
+ const char *qn = ft->data.named.qualified_name;
size_t qnl = strlen(qn);
if (qnl >= 2 && (qn[0] == '\'' || qn[0] == '"') &&
qn[qnl - 1] == qn[0] &&
@@ -2513,14 +2829,15 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
}
}
}
- if (narrowed) break;
+ if (narrowed)
+ break;
}
}
}
}
// Walk case body with narrowed scope if applicable.
- CBMScope* saved = ctx->current_scope;
+ CBMScope *saved = ctx->current_scope;
if (narrowed && disc_var) {
ctx->current_scope = cbm_scope_push(ctx->arena, saved);
cbm_scope_bind(ctx->current_scope, disc_var, narrowed);
@@ -2541,26 +2858,27 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// (discriminated union). Narrowed binding is pushed into a child scope for the
// matching branch; the other branch sees the original type.
if (strcmp(kind, "if_statement") == 0) {
- TSNode condition = ts_node_child_by_field_name(node, "condition",
- TS_LSP_FIELD_LEN("condition"));
- TSNode consequence = ts_node_child_by_field_name(node, "consequence",
- TS_LSP_FIELD_LEN("consequence"));
- TSNode alt = ts_node_child_by_field_name(node, "alternative",
- TS_LSP_FIELD_LEN("alternative"));
+ TSNode condition =
+ ts_node_child_by_field_name(node, "condition", TS_LSP_FIELD_LEN("condition"));
+ TSNode consequence =
+ ts_node_child_by_field_name(node, "consequence", TS_LSP_FIELD_LEN("consequence"));
+ TSNode alt =
+ ts_node_child_by_field_name(node, "alternative", TS_LSP_FIELD_LEN("alternative"));
// Walk the condition itself so any nested calls there resolve too.
- if (!ts_node_is_null(condition)) process_node(ctx, condition);
+ if (!ts_node_is_null(condition))
+ process_node(ctx, condition);
// 1. Try simple narrowing (instanceof, typeof).
- const char* nv = NULL;
- const CBMType* nt = NULL;
+ const char *nv = NULL;
+ const CBMType *nt = NULL;
bool inverted = false;
bool ok = extract_narrowing(ctx, condition, &nv, &nt, &inverted);
// 2. Try discriminated-union narrowing if simple narrowing didn't apply.
if (!ok) {
- const char* dv = NULL;
- const CBMType* dt = narrow_discriminated_union(ctx, condition, &dv);
+ const char *dv = NULL;
+ const CBMType *dt = narrow_discriminated_union(ctx, condition, &dv);
if (dv && dt) {
nv = dv;
nt = dt;
@@ -2572,7 +2890,7 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// Walk consequence with narrowed binding (for the truthy branch unless inverted).
if (!ts_node_is_null(consequence)) {
if (ok && nv && nt && !inverted) {
- CBMScope* saved = ctx->current_scope;
+ CBMScope *saved = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, saved);
cbm_scope_bind(ctx->current_scope, nv, nt);
process_node(ctx, consequence);
@@ -2586,7 +2904,7 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
// narrowing inverse is harder — skip).
if (!ts_node_is_null(alt)) {
if (ok && nv && nt && inverted) {
- CBMScope* saved = ctx->current_scope;
+ CBMScope *saved = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, saved);
cbm_scope_bind(ctx->current_scope, nv, nt);
process_node(ctx, alt);
@@ -2596,24 +2914,23 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
}
}
- return; // Skip default recurse.
+ return; // Skip default recurse.
}
// Function-introducing nodes get their own scope + enclosing_func_qn handling.
- if (strcmp(kind, "function_declaration") == 0 ||
- strcmp(kind, "method_definition") == 0 ||
- strcmp(kind, "function_expression") == 0 ||
- strcmp(kind, "arrow_function") == 0 ||
+ if (strcmp(kind, "function_declaration") == 0 || strcmp(kind, "method_definition") == 0 ||
+ strcmp(kind, "function_expression") == 0 || strcmp(kind, "arrow_function") == 0 ||
strcmp(kind, "method_signature") == 0) {
// Nested functions just get a fresh scope; top-level / class-method walks own
// their enclosing_func_qn via process_function_body.
- CBMScope* saved = ctx->current_scope;
+ CBMScope *saved = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, saved);
- TSNode params = ts_node_child_by_field_name(node, "parameters",
- TS_LSP_FIELD_LEN("parameters"));
+ TSNode params =
+ ts_node_child_by_field_name(node, "parameters", TS_LSP_FIELD_LEN("parameters"));
if (!ts_node_is_null(params)) {
uint32_t nc = ts_node_named_child_count(params);
- for (uint32_t i = 0; i < nc; i++) bind_parameter(ctx, ts_node_named_child(params, i));
+ for (uint32_t i = 0; i < nc; i++)
+ bind_parameter(ctx, ts_node_named_child(params, i));
}
TSNode body = ts_node_child_by_field_name(node, "body", TS_LSP_FIELD_LEN("body"));
if (!ts_node_is_null(body)) {
@@ -2631,24 +2948,28 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
if (strcmp(kind, "class_declaration") == 0) {
// Find the class name to set enclosing_class_qn for methods.
TSNode name = ts_node_child_by_field_name(node, "name", TS_LSP_FIELD_LEN("name"));
- const char* class_qn = NULL;
+ const char *class_qn = NULL;
if (!ts_node_is_null(name) && ctx->module_qn) {
- char* cn = node_text(ctx, name);
- if (cn) class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cn);
+ char *cn = node_text(ctx, name);
+ if (cn)
+ class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cn);
}
TSNode body = ts_node_child_by_field_name(node, "body", TS_LSP_FIELD_LEN("body"));
if (!ts_node_is_null(body) && class_qn) {
uint32_t nc = ts_node_named_child_count(body);
for (uint32_t i = 0; i < nc; i++) {
TSNode m = ts_node_named_child(body, i);
- if (!node_kind_is(m, "method_definition")) continue;
+ if (!node_kind_is(m, "method_definition"))
+ continue;
TSNode mname = ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(mname)) continue;
- char* mn = node_text(ctx, mname);
- if (!mn) continue;
- const char* mqn = strcmp(mn, "constructor") == 0
- ? cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mn)
- : cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mn);
+ if (ts_node_is_null(mname))
+ continue;
+ char *mn = node_text(ctx, mname);
+ if (!mn)
+ continue;
+ const char *mqn = strcmp(mn, "constructor") == 0
+ ? cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mn)
+ : cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mn);
process_function_body(ctx, m, mqn, class_qn);
}
}
@@ -2668,12 +2989,13 @@ static void process_node(TSLSPContext* ctx, TSNode node) {
}
}
-static void process_function_body(TSLSPContext* ctx, TSNode func_node, const char* func_qn,
- const char* class_qn) {
- if (ts_node_is_null(func_node)) return;
- CBMScope* saved_scope = ctx->current_scope;
- const char* saved_func = ctx->enclosing_func_qn;
- const char* saved_class = ctx->enclosing_class_qn;
+static void process_function_body(TSLSPContext *ctx, TSNode func_node, const char *func_qn,
+ const char *class_qn) {
+ if (ts_node_is_null(func_node))
+ return;
+ CBMScope *saved_scope = ctx->current_scope;
+ const char *saved_func = ctx->enclosing_func_qn;
+ const char *saved_class = ctx->enclosing_class_qn;
ctx->current_scope = cbm_scope_push(ctx->arena, saved_scope);
ctx->enclosing_func_qn = func_qn;
@@ -2684,27 +3006,30 @@ static void process_function_body(TSLSPContext* ctx, TSNode func_node, const cha
cbm_scope_bind(ctx->current_scope, "this", cbm_type_named(ctx->arena, class_qn));
}
- TSNode params = ts_node_child_by_field_name(func_node, "parameters",
- TS_LSP_FIELD_LEN("parameters"));
+ TSNode params =
+ ts_node_child_by_field_name(func_node, "parameters", TS_LSP_FIELD_LEN("parameters"));
if (!ts_node_is_null(params)) {
uint32_t nc = ts_node_named_child_count(params);
- for (uint32_t i = 0; i < nc; i++) bind_parameter(ctx, ts_node_named_child(params, i));
+ for (uint32_t i = 0; i < nc; i++)
+ bind_parameter(ctx, ts_node_named_child(params, i));
// JSDoc / signature-derived param-type fallback: if bind_parameter left a
// param bound to UNKNOWN (no inline TS annotation), use the registered func's
// signature param_types[i] (which apply_jsdoc_signatures may have populated).
if (func_qn) {
- const CBMRegisteredFunc* rf = cbm_registry_lookup_func(ctx->registry, func_qn);
+ const CBMRegisteredFunc *rf = cbm_registry_lookup_func(ctx->registry, func_qn);
if (rf && rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
- rf->signature->data.func.param_names &&
- rf->signature->data.func.param_types) {
+ rf->signature->data.func.param_names && rf->signature->data.func.param_types) {
for (int i = 0; rf->signature->data.func.param_names[i] &&
- rf->signature->data.func.param_types[i]; i++) {
- const char* pname = rf->signature->data.func.param_names[i];
- const CBMType* ptype = rf->signature->data.func.param_types[i];
- if (cbm_type_is_unknown(ptype)) continue;
- const CBMType* existing = cbm_scope_lookup(ctx->current_scope, pname);
- if (existing && !cbm_type_is_unknown(existing)) continue;
+ rf->signature->data.func.param_types[i];
+ i++) {
+ const char *pname = rf->signature->data.func.param_names[i];
+ const CBMType *ptype = rf->signature->data.func.param_types[i];
+ if (cbm_type_is_unknown(ptype))
+ continue;
+ const CBMType *existing = cbm_scope_lookup(ctx->current_scope, pname);
+ if (existing && !cbm_type_is_unknown(existing))
+ continue;
cbm_scope_bind(ctx->current_scope, pname, ptype);
}
}
@@ -2734,21 +3059,22 @@ static void process_function_body(TSLSPContext* ctx, TSNode func_node, const cha
ctx->current_scope = saved_scope;
}
-void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
- if (!ctx || ts_node_is_null(root)) return;
- if (ctx->dts_mode) return;
+void ts_lsp_process_file(TSLSPContext *ctx, TSNode root) {
+ if (!ctx || ts_node_is_null(root))
+ return;
+ if (ctx->dts_mode)
+ return;
// 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);
+ TSNode *kids = collect_children(ctx->arena, root, &kn);
// Pass 1: bind module-level declarations into root scope.
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) {
+ const char *kind = ts_node_type(child);
+ if (strcmp(kind, "lexical_declaration") == 0 || strcmp(kind, "variable_declaration") == 0) {
ts_process_statement(ctx, child);
}
}
@@ -2756,14 +3082,16 @@ void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
// Pass 2: process functions, methods, and class bodies.
for (uint32_t i = 0; i < kn; i++) {
TSNode child = kids[i];
- const char* kind = ts_node_type(child);
+ const char *kind = ts_node_type(child);
if (strcmp(kind, "function_declaration") == 0) {
TSNode name = ts_node_child_by_field_name(child, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name) || !ctx->module_qn) continue;
- char* fn = node_text(ctx, name);
- if (!fn) continue;
- const char* fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
+ if (ts_node_is_null(name) || !ctx->module_qn)
+ continue;
+ char *fn = node_text(ctx, name);
+ if (!fn)
+ continue;
+ const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
process_function_body(ctx, child, fqn, NULL);
} else if (strcmp(kind, "class_declaration") == 0) {
process_node(ctx, child);
@@ -2772,15 +3100,18 @@ void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
uint32_t enc = ts_node_named_child_count(child);
for (uint32_t j = 0; j < enc; j++) {
TSNode inner = ts_node_named_child(child, j);
- if (ts_node_is_null(inner)) continue;
- const char* ik = ts_node_type(inner);
+ if (ts_node_is_null(inner))
+ continue;
+ const char *ik = ts_node_type(inner);
if (strcmp(ik, "function_declaration") == 0) {
- TSNode name = ts_node_child_by_field_name(inner, "name",
- TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name) || !ctx->module_qn) continue;
- char* fn = node_text(ctx, name);
- if (!fn) continue;
- const char* fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
+ TSNode name =
+ ts_node_child_by_field_name(inner, "name", TS_LSP_FIELD_LEN("name"));
+ if (ts_node_is_null(name) || !ctx->module_qn)
+ continue;
+ char *fn = node_text(ctx, name);
+ if (!fn)
+ continue;
+ const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
process_function_body(ctx, inner, fqn, NULL);
} else if (strcmp(ik, "class_declaration") == 0) {
process_node(ctx, inner);
@@ -2793,11 +3124,11 @@ void ts_lsp_process_file(TSLSPContext* ctx, TSNode root) {
// ── Initialization ────────────────────────────────────────────────────────────
-void ts_lsp_init(TSLSPContext* ctx, CBMArena* arena, const char* source, int source_len,
- const CBMTypeRegistry* registry, const char* module_qn,
- bool js_mode, bool jsx_mode, bool dts_mode,
- CBMResolvedCallArray* out) {
- if (!ctx) return;
+void ts_lsp_init(TSLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn, bool js_mode,
+ bool jsx_mode, bool dts_mode, CBMResolvedCallArray *out) {
+ if (!ctx)
+ return;
memset(ctx, 0, sizeof(TSLSPContext));
ctx->arena = arena;
ctx->source = source;
@@ -2810,18 +3141,20 @@ void ts_lsp_init(TSLSPContext* ctx, CBMArena* arena, const char* source, int sou
ctx->dts_mode = dts_mode;
ctx->current_scope = arena ? cbm_scope_push(arena, NULL) : NULL;
- const char* debug_env = getenv("CBM_LSP_DEBUG");
+ const char *debug_env = getenv("CBM_LSP_DEBUG");
ctx->debug = (debug_env && debug_env[0]);
}
-void ts_lsp_add_import(TSLSPContext* ctx, const char* local_name, const char* module_qn) {
- if (!ctx || !ctx->arena || !local_name || !module_qn) return;
+void ts_lsp_add_import(TSLSPContext *ctx, const char *local_name, const char *module_qn) {
+ if (!ctx || !ctx->arena || !local_name || !module_qn)
+ return;
int new_count = ctx->import_count + 1;
- const char** names = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)new_count * sizeof(const char*));
- const char** qns = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)new_count * sizeof(const char*));
- if (!names || !qns) return;
+ const char **names =
+ (const char **)cbm_arena_alloc(ctx->arena, (size_t)new_count * sizeof(const char *));
+ const char **qns =
+ (const char **)cbm_arena_alloc(ctx->arena, (size_t)new_count * sizeof(const char *));
+ if (!names || !qns)
+ return;
for (int i = 0; i < ctx->import_count; i++) {
names[i] = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
qns[i] = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
@@ -2835,25 +3168,29 @@ void ts_lsp_add_import(TSLSPContext* ctx, const char* local_name, const char* mo
// ── Stdlib seeds (Phase 5 will replace with generator) ────────────────────────
-static const CBMType* tt_builtin(CBMArena* a, const char* n) { return cbm_type_builtin(a, n); }
-static const CBMType* tt_param(CBMArena* a, const char* n) { return cbm_type_type_param(a, n); }
+static const CBMType *tt_builtin(CBMArena *a, const char *n) {
+ return cbm_type_builtin(a, n);
+}
+static const CBMType *tt_param(CBMArena *a, const char *n) {
+ return cbm_type_type_param(a, n);
+}
-static void ts_reg_method(CBMTypeRegistry* reg, CBMArena* arena, const char* recv_qn,
- const char* name, const CBMType* ret_type) {
+static void ts_reg_method(CBMTypeRegistry *reg, CBMArena *arena, const char *recv_qn,
+ const char *name, const CBMType *ret_type) {
CBMRegisteredFunc rf;
memset(&rf, 0, sizeof(rf));
rf.qualified_name = cbm_arena_sprintf(arena, "%s.%s", recv_qn, name);
rf.short_name = cbm_arena_strdup(arena, name);
rf.receiver_type = cbm_arena_strdup(arena, recv_qn);
rf.min_params = -1;
- const CBMType* rets[2] = {ret_type ? ret_type : cbm_type_unknown(), NULL};
+ const CBMType *rets[2] = {ret_type ? ret_type : cbm_type_unknown(), NULL};
rf.signature = cbm_type_func(arena, NULL, NULL, rets);
cbm_registry_add_func(reg, rf);
}
-static void reg_type_with_methods(CBMTypeRegistry* reg, CBMArena* arena, const char* qn,
- const char* short_name, const char** type_params,
- const char** method_names, const CBMType** method_returns) {
+static void reg_type_with_methods(CBMTypeRegistry *reg, CBMArena *arena, const char *qn,
+ const char *short_name, const char **type_params,
+ const char **method_names, const CBMType **method_returns) {
CBMRegisteredType rt;
memset(&rt, 0, sizeof(rt));
rt.qualified_name = cbm_arena_strdup(arena, qn);
@@ -2861,11 +3198,12 @@ static void reg_type_with_methods(CBMTypeRegistry* reg, CBMArena* arena, const c
rt.type_param_names = type_params;
if (method_names) {
int count = 0;
- while (method_names[count]) count++;
- const char** mqns = (const char**)cbm_arena_alloc(arena,
- (size_t)(count + 1) * sizeof(const char*));
- const char** mnames_copy = (const char**)cbm_arena_alloc(arena,
- (size_t)(count + 1) * sizeof(const char*));
+ while (method_names[count])
+ count++;
+ const char **mqns =
+ (const char **)cbm_arena_alloc(arena, (size_t)(count + 1) * sizeof(const char *));
+ const char **mnames_copy =
+ (const char **)cbm_arena_alloc(arena, (size_t)(count + 1) * sizeof(const char *));
if (mqns && mnames_copy) {
for (int i = 0; i < count; i++) {
mnames_copy[i] = cbm_arena_strdup(arena, method_names[i]);
@@ -2886,54 +3224,56 @@ static void reg_type_with_methods(CBMTypeRegistry* reg, CBMArena* arena, const c
}
}
-void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
- if (!reg || !arena) return;
+void cbm_ts_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena) {
+ if (!reg || !arena)
+ return;
- const CBMType* t_string = tt_builtin(arena, "string");
- const CBMType* t_number = tt_builtin(arena, "number");
- const CBMType* t_boolean = tt_builtin(arena, "boolean");
- const CBMType* t_void = tt_builtin(arena, "void");
- const CBMType* t_unknown = cbm_type_unknown();
+ const CBMType *t_string = tt_builtin(arena, "string");
+ const CBMType *t_number = tt_builtin(arena, "number");
+ const CBMType *t_boolean = tt_builtin(arena, "boolean");
+ const CBMType *t_void = tt_builtin(arena, "void");
+ const CBMType *t_unknown = cbm_type_unknown();
// Array<T>: minimal method surface for v1.
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const CBMType* tparam_U = tt_param(arena, "U");
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- static const char* methods[] = {
- "push", "pop", "shift", "unshift", "slice", "splice", "concat", "join",
- "indexOf", "includes", "forEach", "map", "filter", "find", "findIndex",
- "reduce", "some", "every", "sort", "reverse", "at", "flat", "flatMap", NULL,
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const CBMType *tparam_U = tt_param(arena, "U");
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ static const char *methods[] = {
+ "push", "pop", "shift", "unshift", "slice", "splice", "concat", "join",
+ "indexOf", "includes", "forEach", "map", "filter", "find", "findIndex", "reduce",
+ "some", "every", "sort", "reverse", "at", "flat", "flatMap", NULL,
};
- const CBMType* returns[24];
- const CBMType* t_T = tparam_T;
- const CBMType* t_arr_T_args[2] = {t_T, NULL};
- const CBMType* t_arr_T = cbm_type_template(arena, "Array", t_arr_T_args, 1);
- returns[0] = t_number; // push
- returns[1] = t_T; // pop
- returns[2] = t_T; // shift
- returns[3] = t_number; // unshift
- returns[4] = t_arr_T; // slice
- returns[5] = t_arr_T; // splice
- returns[6] = t_arr_T; // concat
- returns[7] = t_string; // join
- returns[8] = t_number; // indexOf
- returns[9] = t_boolean; // includes
- returns[10] = t_void; // forEach
- returns[11] = cbm_type_template(arena, "Array",
- (const CBMType*[]){tparam_U, NULL}, 1); // map<U>
- returns[12] = t_arr_T; // filter
- returns[13] = t_T; // find
- returns[14] = t_number; // findIndex
- returns[15] = tparam_U; // reduce<U>
- returns[16] = t_boolean; // some
- returns[17] = t_boolean; // every
- returns[18] = t_arr_T; // sort
- returns[19] = t_arr_T; // reverse
- returns[20] = t_T; // at
- returns[21] = t_arr_T; // flat
- returns[22] = t_arr_T; // flatMap
+ const CBMType *returns[24];
+ const CBMType *t_T = tparam_T;
+ const CBMType *t_arr_T_args[2] = {t_T, NULL};
+ const CBMType *t_arr_T = cbm_type_template(arena, "Array", t_arr_T_args, 1);
+ returns[0] = t_number; // push
+ returns[1] = t_T; // pop
+ returns[2] = t_T; // shift
+ returns[3] = t_number; // unshift
+ returns[4] = t_arr_T; // slice
+ returns[5] = t_arr_T; // splice
+ returns[6] = t_arr_T; // concat
+ returns[7] = t_string; // join
+ returns[8] = t_number; // indexOf
+ returns[9] = t_boolean; // includes
+ returns[10] = t_void; // forEach
+ returns[11] =
+ cbm_type_template(arena, "Array", (const CBMType *[]){tparam_U, NULL}, 1); // map<U>
+ returns[12] = t_arr_T; // filter
+ returns[13] = t_T; // find
+ returns[14] = t_number; // findIndex
+ returns[15] = tparam_U; // reduce<U>
+ returns[16] = t_boolean; // some
+ returns[17] = t_boolean; // every
+ returns[18] = t_arr_T; // sort
+ returns[19] = t_arr_T; // reverse
+ returns[20] = t_T; // at
+ returns[21] = t_arr_T; // flat
+ returns[22] = t_arr_T; // flatMap
returns[23] = NULL;
reg_type_with_methods(reg, arena, "Array", "Array", tparams, methods, returns);
@@ -2942,36 +3282,41 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// contextual typing can bind the callback's first param to T inside the
// closure body. We rebuild rf.signature carrying through the existing return
// type. This unlocks `arr.map(x => x.length)`-style resolution.
- const char* p_names[] = {"callback", NULL};
- struct { const char* method; const CBMType* ret; const CBMType* cb_param0; const CBMType* cb_ret; } cb_specs[] = {
- {"forEach", t_void, t_T, t_void},
- {"map", returns[11], t_T, tparam_U},
- {"filter", t_arr_T, t_T, t_boolean},
- {"find", t_T, t_T, t_boolean},
- {"findIndex", t_number, t_T, t_boolean},
- {"some", t_boolean, t_T, t_boolean},
- {"every", t_boolean, t_T, t_boolean},
- {"flatMap", t_arr_T, t_T, tparam_U},
- {"sort", t_arr_T, t_T, t_number},
- {"reduce", tparam_U, t_T, tparam_U},
+ const char *p_names[] = {"callback", NULL};
+ struct {
+ const char *method;
+ const CBMType *ret;
+ const CBMType *cb_param0;
+ const CBMType *cb_ret;
+ } cb_specs[] = {
+ {"forEach", t_void, t_T, t_void},
+ {"map", returns[11], t_T, tparam_U},
+ {"filter", t_arr_T, t_T, t_boolean},
+ {"find", t_T, t_T, t_boolean},
+ {"findIndex", t_number, t_T, t_boolean},
+ {"some", t_boolean, t_T, t_boolean},
+ {"every", t_boolean, t_T, t_boolean},
+ {"flatMap", t_arr_T, t_T, tparam_U},
+ {"sort", t_arr_T, t_T, t_number},
+ {"reduce", tparam_U, t_T, tparam_U},
{NULL, NULL, NULL, NULL},
};
for (int ci = 0; cb_specs[ci].method; ci++) {
// Build callback FUNC type: (x: T) => returnType
- const CBMType* cb_param_types[2] = {cb_specs[ci].cb_param0, NULL};
- const CBMType* cb_returns[2] = {cb_specs[ci].cb_ret, NULL};
- const char* cb_param_names[2] = {"x", NULL};
- const CBMType* cb_func = cbm_type_func(arena, cb_param_names, cb_param_types,
- cb_returns);
+ const CBMType *cb_param_types[2] = {cb_specs[ci].cb_param0, NULL};
+ const CBMType *cb_returns[2] = {cb_specs[ci].cb_ret, NULL};
+ const char *cb_param_names[2] = {"x", NULL};
+ const CBMType *cb_func =
+ cbm_type_func(arena, cb_param_names, cb_param_types, cb_returns);
// Rebuild Array.<method>'s signature with this callback as param 0.
- const CBMType* outer_param_types[2] = {cb_func, NULL};
- const CBMType* outer_returns[2] = {cb_specs[ci].ret, NULL};
- const CBMType* new_sig = cbm_type_func(arena, p_names, outer_param_types,
- outer_returns);
+ const CBMType *outer_param_types[2] = {cb_func, NULL};
+ const CBMType *outer_returns[2] = {cb_specs[ci].ret, NULL};
+ const CBMType *new_sig =
+ cbm_type_func(arena, p_names, outer_param_types, outer_returns);
// Find Array.<method> in the registry and patch its signature.
- char* qn = cbm_arena_sprintf(arena, "Array.%s", cb_specs[ci].method);
+ char *qn = cbm_arena_sprintf(arena, "Array.%s", cb_specs[ci].method);
for (int fi = 0; fi < reg->func_count; fi++) {
if (reg->funcs[fi].qualified_name &&
strcmp(reg->funcs[fi].qualified_name, qn) == 0) {
@@ -2984,13 +3329,14 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// Promise<T>
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- static const char* methods[] = {"then", "catch", "finally", NULL};
- const CBMType* returns[4];
- const CBMType* t_promise_T_args[2] = {tparam_T, NULL};
- const CBMType* t_promise_T = cbm_type_template(arena, "Promise", t_promise_T_args, 1);
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ static const char *methods[] = {"then", "catch", "finally", NULL};
+ const CBMType *returns[4];
+ const CBMType *t_promise_T_args[2] = {tparam_T, NULL};
+ const CBMType *t_promise_T = cbm_type_template(arena, "Promise", t_promise_T_args, 1);
returns[0] = t_promise_T;
returns[1] = t_promise_T;
returns[2] = t_promise_T;
@@ -3000,93 +3346,111 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// Map<K,V>
{
- const char** tparams = (const char**)cbm_arena_alloc(arena, 3 * sizeof(const char*));
- tparams[0] = "K"; tparams[1] = "V"; tparams[2] = NULL;
- static const char* methods[] = {"get", "set", "has", "delete", "clear", "forEach", NULL};
- const CBMType* returns[7] = {
- tt_param(arena, "V"), cbm_type_template(arena, "Map",
- (const CBMType*[]){tt_param(arena, "K"), tt_param(arena, "V"), NULL}, 2),
- t_boolean, t_boolean, t_void, t_void, NULL,
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 3 * sizeof(const char *));
+ tparams[0] = "K";
+ tparams[1] = "V";
+ tparams[2] = NULL;
+ static const char *methods[] = {"get", "set", "has", "delete", "clear", "forEach", NULL};
+ const CBMType *returns[7] = {
+ tt_param(arena, "V"),
+ cbm_type_template(arena, "Map",
+ (const CBMType *[]){tt_param(arena, "K"), tt_param(arena, "V"), NULL},
+ 2),
+ t_boolean,
+ t_boolean,
+ t_void,
+ t_void,
+ NULL,
};
reg_type_with_methods(reg, arena, "Map", "Map", tparams, methods, returns);
}
// Set<T>
{
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- static const char* methods[] = {"add", "has", "delete", "clear", "forEach", NULL};
- const CBMType* returns[6] = {
- cbm_type_template(arena, "Set",
- (const CBMType*[]){tt_param(arena, "T"), NULL}, 1),
- t_boolean, t_boolean, t_void, t_void, NULL,
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ static const char *methods[] = {"add", "has", "delete", "clear", "forEach", NULL};
+ const CBMType *returns[6] = {
+ cbm_type_template(arena, "Set", (const CBMType *[]){tt_param(arena, "T"), NULL}, 1),
+ t_boolean,
+ t_boolean,
+ t_void,
+ t_void,
+ NULL,
};
reg_type_with_methods(reg, arena, "Set", "Set", tparams, methods, returns);
}
// Iterator<T> / Iterable<T>
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- // IteratorResult<T> is loose — we fold it to T-or-undefined via the iterator method's return.
- static const char* iter_methods[] = {"next", "return", "throw", NULL};
- const CBMType* iter_returns[4] = {tparam_T, tparam_T, tparam_T, NULL};
- reg_type_with_methods(reg, arena, "Iterator", "Iterator", tparams,
- iter_methods, iter_returns);
-
- const CBMType* iter_t = cbm_type_template(arena, "Iterator",
- (const CBMType*[]){tparam_T, NULL}, 1);
- static const char* iterable_methods[] = {NULL}; // [Symbol.iterator] not modeled by name
- const CBMType* iterable_returns[1] = {NULL};
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ // IteratorResult<T> is loose — we fold it to T-or-undefined via the iterator method's
+ // return.
+ static const char *iter_methods[] = {"next", "return", "throw", NULL};
+ const CBMType *iter_returns[4] = {tparam_T, tparam_T, tparam_T, NULL};
+ reg_type_with_methods(reg, arena, "Iterator", "Iterator", tparams, iter_methods,
+ iter_returns);
+
+ const CBMType *iter_t =
+ cbm_type_template(arena, "Iterator", (const CBMType *[]){tparam_T, NULL}, 1);
+ static const char *iterable_methods[] = {NULL}; // [Symbol.iterator] not modeled by name
+ const CBMType *iterable_returns[1] = {NULL};
(void)iter_t;
- reg_type_with_methods(reg, arena, "Iterable", "Iterable", tparams,
- iterable_methods, iterable_returns);
+ reg_type_with_methods(reg, arena, "Iterable", "Iterable", tparams, iterable_methods,
+ iterable_returns);
}
// AsyncIterator<T> / AsyncIterable<T> — methods return Promise<T>
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- const CBMType* prom_T = cbm_type_template(arena, "Promise",
- (const CBMType*[]){tparam_T, NULL}, 1);
- static const char* methods[] = {"next", "return", "throw", NULL};
- const CBMType* returns[4] = {prom_T, prom_T, prom_T, NULL};
- reg_type_with_methods(reg, arena, "AsyncIterator", "AsyncIterator", tparams,
- methods, returns);
- reg_type_with_methods(reg, arena, "AsyncIterable", "AsyncIterable", tparams,
- methods, returns);
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ const CBMType *prom_T =
+ cbm_type_template(arena, "Promise", (const CBMType *[]){tparam_T, NULL}, 1);
+ static const char *methods[] = {"next", "return", "throw", NULL};
+ const CBMType *returns[4] = {prom_T, prom_T, prom_T, NULL};
+ reg_type_with_methods(reg, arena, "AsyncIterator", "AsyncIterator", tparams, methods,
+ returns);
+ reg_type_with_methods(reg, arena, "AsyncIterable", "AsyncIterable", tparams, methods,
+ returns);
}
// Generator<T> — extends Iterator<T> with yield-based methods.
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const char** tparams = (const char**)cbm_arena_alloc(arena, 2 * sizeof(const char*));
- tparams[0] = "T"; tparams[1] = NULL;
- static const char* methods[] = {"next", "return", "throw", NULL};
- const CBMType* returns[4] = {tparam_T, tparam_T, tparam_T, NULL};
- reg_type_with_methods(reg, arena, "Generator", "Generator", tparams,
- methods, returns);
- reg_type_with_methods(reg, arena, "AsyncGenerator", "AsyncGenerator", tparams,
- methods, returns);
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const char **tparams = (const char **)cbm_arena_alloc(arena, 2 * sizeof(const char *));
+ tparams[0] = "T";
+ tparams[1] = NULL;
+ static const char *methods[] = {"next", "return", "throw", NULL};
+ const CBMType *returns[4] = {tparam_T, tparam_T, tparam_T, NULL};
+ reg_type_with_methods(reg, arena, "Generator", "Generator", tparams, methods, returns);
+ reg_type_with_methods(reg, arena, "AsyncGenerator", "AsyncGenerator", tparams, methods,
+ returns);
}
// String prototype methods (most common).
{
- static const char* methods[] = {
- "charAt", "charCodeAt", "concat", "includes", "indexOf", "lastIndexOf",
- "padStart", "padEnd", "repeat", "replace", "slice", "split", "startsWith",
- "endsWith", "substring", "toLowerCase", "toUpperCase", "trim", "trimStart",
- "trimEnd", "match", "matchAll", "normalize", "at", NULL,
+ static const char *methods[] = {
+ "charAt", "charCodeAt", "concat", "includes", "indexOf",
+ "lastIndexOf", "padStart", "padEnd", "repeat", "replace",
+ "slice", "split", "startsWith", "endsWith", "substring",
+ "toLowerCase", "toUpperCase", "trim", "trimStart", "trimEnd",
+ "match", "matchAll", "normalize", "at", NULL,
};
// Simplified: most string methods return string or boolean — fold to string for v1.
- int mc = 0; while (methods[mc]) mc++;
- const CBMType** returns = (const CBMType**)cbm_arena_alloc(arena,
- (size_t)(mc + 1) * sizeof(const CBMType*));
+ int mc = 0;
+ while (methods[mc])
+ mc++;
+ const CBMType **returns =
+ (const CBMType **)cbm_arena_alloc(arena, (size_t)(mc + 1) * sizeof(const CBMType *));
for (int i = 0; i < mc; i++) {
// booleans: includes, startsWith, endsWith
- const char* m = methods[i];
+ const char *m = methods[i];
if (strcmp(m, "includes") == 0 || strcmp(m, "startsWith") == 0 ||
strcmp(m, "endsWith") == 0) {
returns[i] = t_boolean;
@@ -3094,8 +3458,8 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
strcmp(m, "charCodeAt") == 0) {
returns[i] = t_number;
} else if (strcmp(m, "split") == 0) {
- returns[i] = cbm_type_template(arena, "Array",
- (const CBMType*[]){t_string, NULL}, 1);
+ returns[i] =
+ cbm_type_template(arena, "Array", (const CBMType *[]){t_string, NULL}, 1);
} else {
returns[i] = t_string;
}
@@ -3106,61 +3470,68 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// console — used so frequently that resolving `console.log` directly is high value.
{
- static const char* methods[] = {"log", "error", "warn", "info", "debug", NULL};
- const CBMType* returns[6] = {t_void, t_void, t_void, t_void, t_void, NULL};
+ static const char *methods[] = {"log", "error", "warn", "info", "debug", NULL};
+ const CBMType *returns[6] = {t_void, t_void, t_void, t_void, t_void, NULL};
reg_type_with_methods(reg, arena, "console", "console", NULL, methods, returns);
}
// JSON namespace.
{
- static const char* methods[] = {"parse", "stringify", NULL};
- const CBMType* returns[3] = {t_unknown, t_string, NULL};
+ static const char *methods[] = {"parse", "stringify", NULL};
+ const CBMType *returns[3] = {t_unknown, t_string, NULL};
reg_type_with_methods(reg, arena, "JSON", "JSON", NULL, methods, returns);
}
// Object — constructor namespace methods that are commonly chained.
{
- static const char* methods[] = {"keys", "values", "entries", "assign", "freeze",
+ static const char *methods[] = {"keys", "values", "entries", "assign", "freeze",
"isFrozen", "create", "getPrototypeOf", NULL};
- const CBMType* returns[9] = {
- cbm_type_template(arena, "Array", (const CBMType*[]){t_string, NULL}, 1),
- cbm_type_template(arena, "Array", (const CBMType*[]){t_unknown, NULL}, 1),
- cbm_type_template(arena, "Array", (const CBMType*[]){t_unknown, NULL}, 1),
- t_unknown, t_unknown, t_boolean, t_unknown, t_unknown, NULL,
+ const CBMType *returns[9] = {
+ cbm_type_template(arena, "Array", (const CBMType *[]){t_string, NULL}, 1),
+ cbm_type_template(arena, "Array", (const CBMType *[]){t_unknown, NULL}, 1),
+ cbm_type_template(arena, "Array", (const CBMType *[]){t_unknown, NULL}, 1),
+ t_unknown,
+ t_unknown,
+ t_boolean,
+ t_unknown,
+ t_unknown,
+ NULL,
};
reg_type_with_methods(reg, arena, "Object", "Object", NULL, methods, returns);
}
// Number wrapper class (so `(42).toString()` and similar resolve).
{
- static const char* methods[] = {
+ static const char *methods[] = {
"toString", "toFixed", "toExponential", "toPrecision", "valueOf", NULL,
};
- const CBMType* returns[6] = {t_string, t_string, t_string, t_string, t_number, NULL};
+ const CBMType *returns[6] = {t_string, t_string, t_string, t_string, t_number, NULL};
reg_type_with_methods(reg, arena, "Number", "Number", NULL, methods, returns);
}
// Boolean wrapper class.
{
- static const char* methods[] = {"toString", "valueOf", NULL};
- const CBMType* returns[3] = {t_string, t_boolean, NULL};
+ static const char *methods[] = {"toString", "valueOf", NULL};
+ const CBMType *returns[3] = {t_string, t_boolean, NULL};
reg_type_with_methods(reg, arena, "Boolean", "Boolean", NULL, methods, returns);
}
// Date wrapper class — common date operations.
{
- static const char* methods[] = {
- "toISOString", "toString", "toJSON", "toDateString", "toTimeString",
- "getTime", "valueOf", "getFullYear", "getMonth", "getDate", "getDay",
- "getHours", "getMinutes", "getSeconds", "getMilliseconds",
- "setFullYear", "setMonth", "setDate", "setHours", "setMinutes",
- "setSeconds", NULL,
+ static const char *methods[] = {
+ "toISOString", "toString", "toJSON", "toDateString", "toTimeString",
+ "getTime", "valueOf", "getFullYear", "getMonth", "getDate",
+ "getDay", "getHours", "getMinutes", "getSeconds", "getMilliseconds",
+ "setFullYear", "setMonth", "setDate", "setHours", "setMinutes",
+ "setSeconds", NULL,
};
- int mc = 0; while (methods[mc]) mc++;
- const CBMType** returns = (const CBMType**)cbm_arena_alloc(arena,
- (size_t)(mc + 1) * sizeof(const CBMType*));
+ int mc = 0;
+ while (methods[mc])
+ mc++;
+ const CBMType **returns =
+ (const CBMType **)cbm_arena_alloc(arena, (size_t)(mc + 1) * sizeof(const CBMType *));
for (int i = 0; i < mc; i++) {
- const char* m = methods[i];
+ const char *m = methods[i];
if (strcmp(m, "toISOString") == 0 || strcmp(m, "toString") == 0 ||
strcmp(m, "toJSON") == 0 || strcmp(m, "toDateString") == 0 ||
strcmp(m, "toTimeString") == 0) {
@@ -3175,29 +3546,32 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// RegExp wrapper class.
{
- static const char* methods[] = {"test", "exec", "toString", "compile", NULL};
- const CBMType* returns[5] = {t_boolean, t_unknown, t_string, t_unknown, NULL};
+ static const char *methods[] = {"test", "exec", "toString", "compile", NULL};
+ const CBMType *returns[5] = {t_boolean, t_unknown, t_string, t_unknown, NULL};
reg_type_with_methods(reg, arena, "RegExp", "RegExp", NULL, methods, returns);
}
// Error class — used heavily in `throw new Error(...)` and catch handlers.
{
- static const char* methods[] = {"toString", NULL};
- const CBMType* returns[2] = {t_string, NULL};
+ static const char *methods[] = {"toString", NULL};
+ const CBMType *returns[2] = {t_string, NULL};
reg_type_with_methods(reg, arena, "Error", "Error", NULL, methods, returns);
}
// Math namespace — static math operations.
{
- static const char* methods[] = {
- "floor", "ceil", "round", "trunc", "abs", "sqrt", "cbrt", "pow",
- "exp", "log", "log2", "log10", "sin", "cos", "tan", "asin", "acos", "atan",
- "atan2", "min", "max", "random", "hypot", "sign", NULL,
+ static const char *methods[] = {
+ "floor", "ceil", "round", "trunc", "abs", "sqrt", "cbrt", "pow", "exp",
+ "log", "log2", "log10", "sin", "cos", "tan", "asin", "acos", "atan",
+ "atan2", "min", "max", "random", "hypot", "sign", NULL,
};
- int mc = 0; while (methods[mc]) mc++;
- const CBMType** returns = (const CBMType**)cbm_arena_alloc(arena,
- (size_t)(mc + 1) * sizeof(const CBMType*));
- for (int i = 0; i < mc; i++) returns[i] = t_number;
+ int mc = 0;
+ while (methods[mc])
+ mc++;
+ const CBMType **returns =
+ (const CBMType **)cbm_arena_alloc(arena, (size_t)(mc + 1) * sizeof(const CBMType *));
+ for (int i = 0; i < mc; i++)
+ returns[i] = t_number;
returns[mc] = NULL;
reg_type_with_methods(reg, arena, "Math", "Math", NULL, methods, returns);
}
@@ -3210,14 +3584,13 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// Array.isArray(x): boolean
// Array.of(...items): Array<T>
{
- const CBMType* tparam_T = tt_param(arena, "T");
- const CBMType* t_T = tparam_T;
- const CBMType* prom_T = cbm_type_template(arena, "Promise",
- (const CBMType*[]){t_T, NULL}, 1);
- const CBMType* arr_T = cbm_type_template(arena, "Array",
- (const CBMType*[]){t_T, NULL}, 1);
- const CBMType* prom_arr_T = cbm_type_template(arena, "Promise",
- (const CBMType*[]){arr_T, NULL}, 1);
+ const CBMType *tparam_T = tt_param(arena, "T");
+ const CBMType *t_T = tparam_T;
+ const CBMType *prom_T =
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_T, NULL}, 1);
+ const CBMType *arr_T = cbm_type_template(arena, "Array", (const CBMType *[]){t_T, NULL}, 1);
+ const CBMType *prom_arr_T =
+ cbm_type_template(arena, "Promise", (const CBMType *[]){arr_T, NULL}, 1);
ts_reg_method(reg, arena, "Promise", "resolve", prom_T);
ts_reg_method(reg, arena, "Promise", "all", prom_arr_T);
ts_reg_method(reg, arena, "Promise", "reject", prom_T);
@@ -3235,123 +3608,182 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// be Phase 5 (generator).
{
// EventTarget base
- static const char* et_methods[] = {
- "addEventListener", "removeEventListener", "dispatchEvent", NULL,
+ static const char *et_methods[] = {
+ "addEventListener",
+ "removeEventListener",
+ "dispatchEvent",
+ NULL,
};
- const CBMType* et_returns[4] = {t_void, t_void, t_boolean, NULL};
- reg_type_with_methods(reg, arena, "EventTarget", "EventTarget", NULL,
- et_methods, et_returns);
+ const CBMType *et_returns[4] = {t_void, t_void, t_boolean, NULL};
+ reg_type_with_methods(reg, arena, "EventTarget", "EventTarget", NULL, et_methods,
+ et_returns);
// Node
- static const char* node_methods[] = {
- "appendChild", "removeChild", "replaceChild", "cloneNode", "contains",
- "hasChildNodes", "addEventListener", "removeEventListener",
- "dispatchEvent", NULL,
+ static const char *node_methods[] = {
+ "appendChild", "removeChild", "replaceChild", "cloneNode", "contains",
+ "hasChildNodes", "addEventListener", "removeEventListener", "dispatchEvent", NULL,
};
- const CBMType* node_t = cbm_type_named(arena, "Node");
- const CBMType* node_returns[10] = {
- node_t, node_t, node_t, node_t, t_boolean, t_boolean,
- t_void, t_void, t_boolean, NULL,
+ const CBMType *node_t = cbm_type_named(arena, "Node");
+ const CBMType *node_returns[10] = {
+ node_t, node_t, node_t, node_t, t_boolean, t_boolean, t_void, t_void, t_boolean, NULL,
};
reg_type_with_methods(reg, arena, "Node", "Node", NULL, node_methods, node_returns);
// Element
- static const char* el_methods[] = {
- "getAttribute", "setAttribute", "removeAttribute", "hasAttribute",
- "querySelector", "querySelectorAll", "closest", "matches",
- "appendChild", "removeChild", "replaceChild",
- "addEventListener", "removeEventListener", "dispatchEvent",
- "getBoundingClientRect", "scrollIntoView",
- "focus", "blur", "click", "remove", NULL,
+ static const char *el_methods[] = {
+ "getAttribute",
+ "setAttribute",
+ "removeAttribute",
+ "hasAttribute",
+ "querySelector",
+ "querySelectorAll",
+ "closest",
+ "matches",
+ "appendChild",
+ "removeChild",
+ "replaceChild",
+ "addEventListener",
+ "removeEventListener",
+ "dispatchEvent",
+ "getBoundingClientRect",
+ "scrollIntoView",
+ "focus",
+ "blur",
+ "click",
+ "remove",
+ NULL,
};
- const CBMType* el_t = cbm_type_named(arena, "Element");
- const CBMType* nodelist_t = cbm_type_template(arena, "NodeList",
- (const CBMType*[]){el_t, NULL}, 1);
- const CBMType* el_returns[21] = {
- t_string, t_void, t_void, t_boolean,
- el_t, nodelist_t, el_t, t_boolean,
- el_t, el_t, el_t,
- t_void, t_void, t_boolean,
- t_unknown, t_void,
- t_void, t_void, t_void, t_void, NULL,
+ const CBMType *el_t = cbm_type_named(arena, "Element");
+ const CBMType *nodelist_t =
+ cbm_type_template(arena, "NodeList", (const CBMType *[]){el_t, NULL}, 1);
+ const CBMType *el_returns[21] = {
+ t_string, t_void, t_void, t_boolean, el_t, nodelist_t, el_t,
+ t_boolean, el_t, el_t, el_t, t_void, t_void, t_boolean,
+ t_unknown, t_void, t_void, t_void, t_void, t_void, NULL,
};
reg_type_with_methods(reg, arena, "Element", "Element", NULL, el_methods, el_returns);
// HTMLElement (extends Element)
- static const char* html_methods[] = {
- "getAttribute", "setAttribute", "querySelector", "querySelectorAll",
- "closest", "addEventListener", "removeEventListener",
- "click", "focus", "blur", "remove", NULL,
+ static const char *html_methods[] = {
+ "getAttribute",
+ "setAttribute",
+ "querySelector",
+ "querySelectorAll",
+ "closest",
+ "addEventListener",
+ "removeEventListener",
+ "click",
+ "focus",
+ "blur",
+ "remove",
+ NULL,
};
- const CBMType* html_t = cbm_type_named(arena, "HTMLElement");
- const CBMType* html_returns[12] = {
- t_string, t_void, html_t,
- cbm_type_template(arena, "NodeList", (const CBMType*[]){html_t, NULL}, 1),
- html_t, t_void, t_void, t_void, t_void, t_void, t_void, NULL,
+ const CBMType *html_t = cbm_type_named(arena, "HTMLElement");
+ const CBMType *html_returns[12] = {
+ t_string, t_void,
+ html_t, cbm_type_template(arena, "NodeList", (const CBMType *[]){html_t, NULL}, 1),
+ html_t, t_void,
+ t_void, t_void,
+ t_void, t_void,
+ t_void, NULL,
};
- reg_type_with_methods(reg, arena, "HTMLElement", "HTMLElement", NULL,
- html_methods, html_returns);
+ reg_type_with_methods(reg, arena, "HTMLElement", "HTMLElement", NULL, html_methods,
+ html_returns);
// Document
- static const char* doc_methods[] = {
- "getElementById", "querySelector", "querySelectorAll", "getElementsByClassName",
- "getElementsByTagName", "createElement", "createTextNode", "createDocumentFragment",
- "addEventListener", "removeEventListener", NULL,
+ static const char *doc_methods[] = {
+ "getElementById",
+ "querySelector",
+ "querySelectorAll",
+ "getElementsByClassName",
+ "getElementsByTagName",
+ "createElement",
+ "createTextNode",
+ "createDocumentFragment",
+ "addEventListener",
+ "removeEventListener",
+ NULL,
};
- const CBMType* doc_returns[11] = {
- html_t, html_t,
- cbm_type_template(arena, "NodeList", (const CBMType*[]){html_t, NULL}, 1),
- cbm_type_template(arena, "HTMLCollection", (const CBMType*[]){html_t, NULL}, 1),
- cbm_type_template(arena, "HTMLCollection", (const CBMType*[]){html_t, NULL}, 1),
- html_t, node_t, node_t,
- t_void, t_void, NULL,
+ const CBMType *doc_returns[11] = {
+ html_t,
+ html_t,
+ cbm_type_template(arena, "NodeList", (const CBMType *[]){html_t, NULL}, 1),
+ cbm_type_template(arena, "HTMLCollection", (const CBMType *[]){html_t, NULL}, 1),
+ cbm_type_template(arena, "HTMLCollection", (const CBMType *[]){html_t, NULL}, 1),
+ html_t,
+ node_t,
+ node_t,
+ t_void,
+ t_void,
+ NULL,
};
- reg_type_with_methods(reg, arena, "Document", "Document", NULL, doc_methods,
- doc_returns);
+ reg_type_with_methods(reg, arena, "Document", "Document", NULL, doc_methods, doc_returns);
// Event
- static const char* event_methods[] = {
- "preventDefault", "stopPropagation", "stopImmediatePropagation",
- "composedPath", NULL,
+ static const char *event_methods[] = {
+ "preventDefault", "stopPropagation", "stopImmediatePropagation", "composedPath", NULL,
};
- const CBMType* event_returns[5] = {
- t_void, t_void, t_void,
- cbm_type_template(arena, "Array", (const CBMType*[]){et_methods[0] ? cbm_type_named(arena, "EventTarget") : t_unknown, NULL}, 1),
+ const CBMType *event_returns[5] = {
+ t_void,
+ t_void,
+ t_void,
+ cbm_type_template(
+ arena, "Array",
+ (const CBMType *[]){
+ et_methods[0] ? cbm_type_named(arena, "EventTarget") : t_unknown, NULL},
+ 1),
NULL,
};
- reg_type_with_methods(reg, arena, "Event", "Event", NULL, event_methods,
- event_returns);
+ reg_type_with_methods(reg, arena, "Event", "Event", NULL, event_methods, event_returns);
// Response (fetch API)
- static const char* resp_methods[] = {
+ static const char *resp_methods[] = {
"json", "text", "blob", "arrayBuffer", "formData", "clone", NULL,
};
- const CBMType* resp_returns[7] = {
- cbm_type_template(arena, "Promise", (const CBMType*[]){t_unknown, NULL}, 1),
- cbm_type_template(arena, "Promise", (const CBMType*[]){t_string, NULL}, 1),
- cbm_type_template(arena, "Promise", (const CBMType*[]){t_unknown, NULL}, 1),
- cbm_type_template(arena, "Promise", (const CBMType*[]){t_unknown, NULL}, 1),
- cbm_type_template(arena, "Promise", (const CBMType*[]){t_unknown, NULL}, 1),
+ const CBMType *resp_returns[7] = {
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_unknown, NULL}, 1),
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_string, NULL}, 1),
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_unknown, NULL}, 1),
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_unknown, NULL}, 1),
+ cbm_type_template(arena, "Promise", (const CBMType *[]){t_unknown, NULL}, 1),
cbm_type_named(arena, "Response"),
NULL,
};
- reg_type_with_methods(reg, arena, "Response", "Response", NULL, resp_methods,
- resp_returns);
+ reg_type_with_methods(reg, arena, "Response", "Response", NULL, resp_methods, resp_returns);
// Window
- static const char* win_methods[] = {
- "addEventListener", "removeEventListener", "alert", "confirm", "prompt",
- "fetch", "setTimeout", "clearTimeout", "setInterval", "clearInterval",
- "requestAnimationFrame", "cancelAnimationFrame", NULL,
+ static const char *win_methods[] = {
+ "addEventListener",
+ "removeEventListener",
+ "alert",
+ "confirm",
+ "prompt",
+ "fetch",
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "requestAnimationFrame",
+ "cancelAnimationFrame",
+ NULL,
};
- const CBMType* win_returns[13] = {
- t_void, t_void, t_void, t_boolean, t_string,
+ const CBMType *win_returns[13] = {
+ t_void,
+ t_void,
+ t_void,
+ t_boolean,
+ t_string,
cbm_type_template(arena, "Promise",
- (const CBMType*[]){cbm_type_named(arena, "Response"), NULL}, 1),
- t_number, t_void, t_number, t_void, t_number, t_void, NULL,
+ (const CBMType *[]){cbm_type_named(arena, "Response"), NULL}, 1),
+ t_number,
+ t_void,
+ t_number,
+ t_void,
+ t_number,
+ t_void,
+ NULL,
};
- reg_type_with_methods(reg, arena, "Window", "Window", NULL, win_methods,
- win_returns);
+ reg_type_with_methods(reg, arena, "Window", "Window", NULL, win_methods, win_returns);
}
}
@@ -3359,11 +3791,12 @@ void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) {
// Build a registry from result->defs: register Class/Interface as types; Function/Method
// as funcs. Walks AST briefly for class fields/extends.
-static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileResult* result,
- const char* module_qn) {
+static void register_file_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMFileResult *result,
+ const char *module_qn) {
for (int i = 0; i < result->defs.count; i++) {
- CBMDefinition* d = &result->defs.items[i];
- if (!d->qualified_name || !d->name || !d->label) continue;
+ CBMDefinition *d = &result->defs.items[i];
+ if (!d->qualified_name || !d->name || !d->label)
+ continue;
if (strcmp(d->label, "Class") == 0 || strcmp(d->label, "Interface") == 0) {
CBMRegisteredType rt;
@@ -3374,18 +3807,20 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
// base_classes → embedded_types (extends/implements).
if (d->base_classes) {
int bc = 0;
- while (d->base_classes[bc]) bc++;
+ while (d->base_classes[bc])
+ bc++;
if (bc > 0) {
- const char** emb = (const char**)cbm_arena_alloc(arena,
- (size_t)(bc + 1) * sizeof(const char*));
+ const char **emb = (const char **)cbm_arena_alloc(
+ arena, (size_t)(bc + 1) * sizeof(const char *));
if (emb) {
for (int j = 0; j < bc; j++) {
- const char* b = d->base_classes[j];
+ const char *b = d->base_classes[j];
// For TS, extract_defs returns base text like "extends Animal"
// or "extends Foo<Bar>" (raw class_heritage node text). Strip
// the keyword and pull the first identifier.
if (b) {
- while (*b == ' ' || *b == '\t' || *b == '\n') b++;
+ while (*b == ' ' || *b == '\t' || *b == '\n')
+ b++;
if (strncmp(b, "extends", 7) == 0 &&
(b[7] == ' ' || b[7] == '\t')) {
b += 7;
@@ -3394,19 +3829,20 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
(b[10] == ' ' || b[10] == '\t')) {
b += 10;
}
- while (*b == ' ' || *b == '\t' || *b == '\n') b++;
+ while (*b == ' ' || *b == '\t' || *b == '\n')
+ b++;
size_t bl = 0;
- while (b[bl] && b[bl] != ' ' && b[bl] != ',' &&
- b[bl] != '<' && b[bl] != '(' && b[bl] != '\n' &&
- b[bl] != '\t') bl++;
+ while (b[bl] && b[bl] != ' ' && b[bl] != ',' && b[bl] != '<' &&
+ b[bl] != '(' && b[bl] != '\n' && b[bl] != '\t')
+ bl++;
if (bl == 0) {
emb[j] = NULL;
continue;
}
- char* base_name = cbm_arena_strndup(arena, b, bl);
+ char *base_name = cbm_arena_strndup(arena, b, bl);
if (strchr(base_name, '.') == NULL) {
- emb[j] = cbm_arena_sprintf(arena, "%s.%s",
- module_qn, base_name);
+ emb[j] =
+ cbm_arena_sprintf(arena, "%s.%s", module_qn, base_name);
} else {
emb[j] = base_name;
}
@@ -3434,19 +3870,20 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
// at the first '<' (so `Promise<number>` becomes `Promise`, losing the
// generic args). The raw text preserves generics; parse_ts_type_text strips
// the leading `:` annotation prefix.
- const CBMType** rets = NULL;
+ const CBMType **rets = NULL;
if (d->return_type && d->return_type[0]) {
- rets = (const CBMType**)cbm_arena_alloc(arena, 2 * sizeof(const CBMType*));
+ rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
if (rets) {
rets[0] = parse_ts_type_text(arena, d->return_type, module_qn);
rets[1] = NULL;
}
} else if (d->return_types) {
int n = 0;
- while (d->return_types[n]) n++;
+ while (d->return_types[n])
+ n++;
if (n > 0) {
- rets = (const CBMType**)cbm_arena_alloc(arena,
- (size_t)(n + 1) * sizeof(const CBMType*));
+ rets = (const CBMType **)cbm_arena_alloc(arena, (size_t)(n + 1) *
+ sizeof(const CBMType *));
if (rets) {
for (int j = 0; j < n; j++) {
rets[j] = parse_ts_type_text(arena, d->return_types[j], module_qn);
@@ -3455,24 +3892,24 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
}
}
}
- const CBMType** params_t = parse_param_types_array(arena, d->param_types, module_qn);
+ const CBMType **params_t = parse_param_types_array(arena, d->param_types, module_qn);
rf.signature = cbm_type_func(arena, d->param_names, params_t, rets);
// Methods: deduce receiver from QN ("module.Class.method" → receiver "module.Class").
if (strcmp(d->label, "Method") == 0) {
- const char* dot = strrchr(d->qualified_name, '.');
+ const char *dot = strrchr(d->qualified_name, '.');
if (dot && dot != d->qualified_name) {
- char* recv = cbm_arena_strndup(arena, d->qualified_name,
+ char *recv = cbm_arena_strndup(arena, d->qualified_name,
(size_t)(dot - d->qualified_name));
rf.receiver_type = recv;
// Ensure the receiver type is registered (auto-create if missing).
- const CBMRegisteredType* existing = cbm_registry_lookup_type(reg, recv);
+ const CBMRegisteredType *existing = cbm_registry_lookup_type(reg, recv);
if (!existing) {
CBMRegisteredType auto_rt;
memset(&auto_rt, 0, sizeof(auto_rt));
auto_rt.qualified_name = recv;
- const char* short_name = strrchr(recv, '.');
+ const char *short_name = strrchr(recv, '.');
auto_rt.short_name = short_name ? short_name + 1 : recv;
cbm_registry_add_type(reg, auto_rt);
}
@@ -3486,27 +3923,30 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
// Second pass: attach method_names / method_qns to each registered type from
// the registered methods. Lets dispatch find them via lookup_member_type.
for (int ti = 0; ti < reg->type_count; ti++) {
- CBMRegisteredType* rt = &reg->types[ti];
- if (!rt->qualified_name) continue;
+ CBMRegisteredType *rt = &reg->types[ti];
+ if (!rt->qualified_name)
+ continue;
// Count methods first.
int mcount = 0;
for (int fi = 0; fi < reg->func_count; fi++) {
- const CBMRegisteredFunc* f = &reg->funcs[fi];
+ const CBMRegisteredFunc *f = &reg->funcs[fi];
if (f->receiver_type && strcmp(f->receiver_type, rt->qualified_name) == 0) {
mcount++;
}
}
- if (mcount == 0) continue;
+ if (mcount == 0)
+ continue;
- const char** mnames = (const char**)cbm_arena_alloc(arena,
- (size_t)(mcount + 1) * sizeof(const char*));
- const char** mqns = (const char**)cbm_arena_alloc(arena,
- (size_t)(mcount + 1) * sizeof(const char*));
- if (!mnames || !mqns) continue;
+ const char **mnames =
+ (const char **)cbm_arena_alloc(arena, (size_t)(mcount + 1) * sizeof(const char *));
+ const char **mqns =
+ (const char **)cbm_arena_alloc(arena, (size_t)(mcount + 1) * sizeof(const char *));
+ if (!mnames || !mqns)
+ continue;
int idx = 0;
for (int fi = 0; fi < reg->func_count && idx < mcount; fi++) {
- const CBMRegisteredFunc* f = &reg->funcs[fi];
+ const CBMRegisteredFunc *f = &reg->funcs[fi];
if (f->receiver_type && strcmp(f->receiver_type, rt->qualified_name) == 0) {
mnames[idx] = f->short_name;
mqns[idx] = f->qualified_name;
@@ -3522,8 +3962,9 @@ static void register_file_defs(CBMArena* arena, CBMTypeRegistry* reg, CBMFileRes
// Find the first `return EXPR` inside a body and evaluate EXPR's type. Returns
// UNKNOWN if the body has no return or every return is unresolvable.
-static const CBMType* infer_return_type_from_body(TSLSPContext* ctx, TSNode body) {
- if (ts_node_is_null(body)) return cbm_type_unknown();
+static const CBMType *infer_return_type_from_body(TSLSPContext *ctx, TSNode body) {
+ if (ts_node_is_null(body))
+ return cbm_type_unknown();
// Iterative DFS using a small fixed-size stack to avoid C-stack blowup on big bodies.
enum { STACK_CAP = 256 };
@@ -3532,23 +3973,26 @@ static const CBMType* infer_return_type_from_body(TSLSPContext* ctx, TSNode body
stack[top++] = body;
while (top > 0) {
TSNode n = stack[--top];
- if (ts_node_is_null(n)) continue;
- const char* k = ts_node_type(n);
+ if (ts_node_is_null(n))
+ continue;
+ const char *k = ts_node_type(n);
if (strcmp(k, "return_statement") == 0) {
// The first named child is the return expression (if any).
uint32_t rnc = ts_node_named_child_count(n);
- if (rnc == 0) continue;
+ if (rnc == 0)
+ continue;
TSNode expr = ts_node_named_child(n, 0);
- if (ts_node_is_null(expr)) continue;
- const CBMType* t = ts_eval_expr_type(ctx, expr);
- if (t && !cbm_type_is_unknown(t)) return t;
+ if (ts_node_is_null(expr))
+ continue;
+ const CBMType *t = ts_eval_expr_type(ctx, expr);
+ if (t && !cbm_type_is_unknown(t))
+ return t;
continue;
}
// Don't recurse into nested function bodies — their returns belong to them.
- if (strcmp(k, "function_declaration") == 0 ||
- strcmp(k, "function_expression") == 0 ||
- strcmp(k, "arrow_function") == 0 ||
- strcmp(k, "method_definition") == 0) continue;
+ if (strcmp(k, "function_declaration") == 0 || strcmp(k, "function_expression") == 0 ||
+ strcmp(k, "arrow_function") == 0 || strcmp(k, "method_definition") == 0)
+ continue;
uint32_t cnt = ts_node_child_count(n);
for (uint32_t i = 0; i < cnt && top < STACK_CAP; i++) {
@@ -3565,19 +4009,22 @@ static const CBMType* infer_return_type_from_body(TSLSPContext* ctx, TSNode body
//
// Called after `register_file_defs` so the func entries already exist; we only mutate
// in place.
-static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
- if (ts_node_is_null(root) || !reg || !ctx->module_qn) return;
+static void rebuild_signatures_from_ast(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
+ if (ts_node_is_null(root) || !reg || !ctx->module_qn)
+ return;
enum { STACK_CAP = 256 };
TSNode stack[STACK_CAP];
int top = 0;
uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc && top < STACK_CAP; i++) stack[top++] = ts_node_child(root, i);
+ for (uint32_t i = 0; i < nc && top < STACK_CAP; i++)
+ stack[top++] = ts_node_child(root, i);
while (top > 0) {
TSNode n = stack[--top];
- if (ts_node_is_null(n)) continue;
- const char* k = ts_node_type(n);
+ if (ts_node_is_null(n))
+ continue;
+ const char *k = ts_node_type(n);
// Recurse into export_statement and class bodies.
if (strcmp(k, "export_statement") == 0 || strcmp(k, "class_body") == 0) {
@@ -3589,21 +4036,25 @@ static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeR
}
if (strcmp(k, "class_declaration") == 0) {
TSNode body = ts_node_child_by_field_name(n, "body", TS_LSP_FIELD_LEN("body"));
- if (!ts_node_is_null(body) && top < STACK_CAP) stack[top++] = body;
+ if (!ts_node_is_null(body) && top < STACK_CAP)
+ stack[top++] = body;
continue;
}
bool is_func = (strcmp(k, "function_declaration") == 0);
bool is_method = (strcmp(k, "method_definition") == 0);
- if (!is_func && !is_method) continue;
+ if (!is_func && !is_method)
+ continue;
TSNode name_node = ts_node_child_by_field_name(n, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name_node)) continue;
- char* fname = node_text(ctx, name_node);
- if (!fname) continue;
+ if (ts_node_is_null(name_node))
+ continue;
+ char *fname = node_text(ctx, name_node);
+ if (!fname)
+ continue;
// Resolve this declaration's FQN to find its registered func.
- const char* fqn = NULL;
+ const char *fqn = NULL;
if (is_func) {
fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
} else {
@@ -3613,45 +4064,47 @@ static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeR
strcmp(ts_node_type(parent), "class_declaration") != 0) {
parent = ts_node_parent(parent);
}
- if (ts_node_is_null(parent)) continue;
- TSNode cn = ts_node_child_by_field_name(parent, "name",
- TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(cn)) continue;
- char* cname = node_text(ctx, cn);
- if (!cname) continue;
+ if (ts_node_is_null(parent))
+ continue;
+ TSNode cn = ts_node_child_by_field_name(parent, "name", TS_LSP_FIELD_LEN("name"));
+ if (ts_node_is_null(cn))
+ continue;
+ char *cname = node_text(ctx, cn);
+ if (!cname)
+ continue;
fqn = cbm_arena_sprintf(ctx->arena, "%s.%s.%s", ctx->module_qn, cname, fname);
}
// Rebuild parameters from AST.
- TSNode params = ts_node_child_by_field_name(n, "parameters",
- TS_LSP_FIELD_LEN("parameters"));
- const char* p_names[32] = {0};
- const CBMType* p_types[32] = {0};
+ TSNode params =
+ ts_node_child_by_field_name(n, "parameters", TS_LSP_FIELD_LEN("parameters"));
+ const char *p_names[32] = {0};
+ const CBMType *p_types[32] = {0};
int pc = 0;
if (!ts_node_is_null(params)) {
uint32_t pnc = ts_node_named_child_count(params);
for (uint32_t i = 0; i < pnc && pc < 31; i++) {
TSNode p = ts_node_named_child(params, i);
- if (ts_node_is_null(p)) continue;
- const char* pk = ts_node_type(p);
- if (strcmp(pk, "required_parameter") != 0 &&
- strcmp(pk, "optional_parameter") != 0) continue;
+ if (ts_node_is_null(p))
+ continue;
+ const char *pk = ts_node_type(p);
+ if (strcmp(pk, "required_parameter") != 0 && strcmp(pk, "optional_parameter") != 0)
+ continue;
// Param name.
- TSNode pat = ts_node_child_by_field_name(p, "pattern",
- TS_LSP_FIELD_LEN("pattern"));
+ TSNode pat = ts_node_child_by_field_name(p, "pattern", TS_LSP_FIELD_LEN("pattern"));
if (ts_node_is_null(pat)) {
- pat = ts_node_child_by_field_name(p, "name",
- TS_LSP_FIELD_LEN("name"));
+ pat = ts_node_child_by_field_name(p, "name", TS_LSP_FIELD_LEN("name"));
}
- if (ts_node_is_null(pat) || strcmp(ts_node_type(pat), "identifier") != 0) continue;
- char* pn = node_text(ctx, pat);
- if (!pn) continue;
+ if (ts_node_is_null(pat) || strcmp(ts_node_type(pat), "identifier") != 0)
+ continue;
+ char *pn = node_text(ctx, pat);
+ if (!pn)
+ continue;
// Param type.
- const CBMType* pt = cbm_type_unknown();
- TSNode tann = ts_node_child_by_field_name(p, "type",
- TS_LSP_FIELD_LEN("type"));
+ const CBMType *pt = cbm_type_unknown();
+ TSNode tann = ts_node_child_by_field_name(p, "type", TS_LSP_FIELD_LEN("type"));
if (ts_node_is_null(tann)) {
// Fall back to kind-based search.
uint32_t pcnt = ts_node_named_child_count(p);
@@ -3668,7 +4121,8 @@ static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeR
TSNode tch = (strcmp(ts_node_type(tann), "type_annotation") == 0)
? ts_node_named_child(tann, 0)
: tann;
- if (!ts_node_is_null(tch)) pt = ts_parse_type_node(ctx, tch);
+ if (!ts_node_is_null(tch))
+ pt = ts_parse_type_node(ctx, tch);
}
p_names[pc] = pn;
@@ -3680,31 +4134,33 @@ static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeR
p_types[pc] = NULL;
// Rebuild return type from AST.
- const CBMType* ret = cbm_type_unknown();
- TSNode rt_node = ts_node_child_by_field_name(n, "return_type",
- TS_LSP_FIELD_LEN("return_type"));
+ const CBMType *ret = cbm_type_unknown();
+ TSNode rt_node =
+ ts_node_child_by_field_name(n, "return_type", TS_LSP_FIELD_LEN("return_type"));
if (!ts_node_is_null(rt_node)) {
TSNode tch = (strcmp(ts_node_type(rt_node), "type_annotation") == 0)
? ts_node_named_child(rt_node, 0)
: rt_node;
- if (!ts_node_is_null(tch)) ret = ts_parse_type_node(ctx, tch);
+ if (!ts_node_is_null(tch))
+ ret = ts_parse_type_node(ctx, tch);
}
// Build new signature and patch in registry.
- const CBMType* rets[2] = {ret, NULL};
- const CBMType* new_sig = cbm_type_func(ctx->arena, p_names, p_types, rets);
+ const CBMType *rets[2] = {ret, NULL};
+ const CBMType *new_sig = cbm_type_func(ctx->arena, p_names, p_types, rets);
for (int fi = 0; fi < reg->func_count; fi++) {
- if (!reg->funcs[fi].qualified_name) continue;
- if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0) continue;
+ if (!reg->funcs[fi].qualified_name)
+ continue;
+ if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0)
+ continue;
// Preserve the ret type if AST gave UNKNOWN but the existing reg sig had one.
if (cbm_type_is_unknown(ret) && reg->funcs[fi].signature &&
reg->funcs[fi].signature->kind == CBM_TYPE_FUNC &&
reg->funcs[fi].signature->data.func.return_types &&
reg->funcs[fi].signature->data.func.return_types[0] &&
- !cbm_type_is_unknown(
- reg->funcs[fi].signature->data.func.return_types[0])) {
- const CBMType* preserved[2] = {
- reg->funcs[fi].signature->data.func.return_types[0], NULL};
+ !cbm_type_is_unknown(reg->funcs[fi].signature->data.func.return_types[0])) {
+ const CBMType *preserved[2] = {reg->funcs[fi].signature->data.func.return_types[0],
+ NULL};
new_sig = cbm_type_func(ctx->arena, p_names, p_types, preserved);
}
reg->funcs[fi].signature = new_sig;
@@ -3716,20 +4172,23 @@ static void rebuild_signatures_from_ast(TSLSPContext* ctx, TSNode root, CBMTypeR
// Convert NAMED references to TYPE_PARAM for any function whose declaration has a
// `type_parameters` block. Without this, generic functions like `function id<T>(x: T): T`
// register T as NAMED("module.T") instead of TYPE_PARAM("T"), defeating substitution.
-static void convert_signature_type_params(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
- if (ts_node_is_null(root) || !reg || !ctx->module_qn) return;
+static void convert_signature_type_params(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
+ if (ts_node_is_null(root) || !reg || !ctx->module_qn)
+ return;
// Walk: function_declaration, class_declaration { method_definition }, plus exported.
enum { STACK_CAP = 256 };
TSNode stack[STACK_CAP];
int top = 0;
uint32_t nc = ts_node_child_count(root);
- for (uint32_t i = 0; i < nc && top < STACK_CAP; i++) stack[top++] = ts_node_child(root, i);
+ for (uint32_t i = 0; i < nc && top < STACK_CAP; i++)
+ stack[top++] = ts_node_child(root, i);
while (top > 0) {
TSNode n = stack[--top];
- if (ts_node_is_null(n)) continue;
- const char* k = ts_node_type(n);
+ if (ts_node_is_null(n))
+ continue;
+ const char *k = ts_node_type(n);
// Recurse into export_statement and class_body.
if (strcmp(k, "export_statement") == 0 || strcmp(k, "class_body") == 0) {
@@ -3741,54 +4200,62 @@ static void convert_signature_type_params(TSLSPContext* ctx, TSNode root, CBMTyp
}
if (strcmp(k, "class_declaration") == 0) {
TSNode body = ts_node_child_by_field_name(n, "body", TS_LSP_FIELD_LEN("body"));
- if (!ts_node_is_null(body) && top < STACK_CAP) stack[top++] = body;
+ if (!ts_node_is_null(body) && top < STACK_CAP)
+ stack[top++] = body;
continue;
}
bool is_func = (strcmp(k, "function_declaration") == 0);
bool is_method = (strcmp(k, "method_definition") == 0);
- if (!is_func && !is_method) continue;
+ if (!is_func && !is_method)
+ continue;
- TSNode tparams = ts_node_child_by_field_name(n, "type_parameters",
- TS_LSP_FIELD_LEN("type_parameters"));
- if (ts_node_is_null(tparams)) continue;
+ TSNode tparams =
+ ts_node_child_by_field_name(n, "type_parameters", TS_LSP_FIELD_LEN("type_parameters"));
+ if (ts_node_is_null(tparams))
+ continue;
// Collect type param names.
- const char* names[16] = {0};
- const CBMType* args[16] = {0};
+ const char *names[16] = {0};
+ const CBMType *args[16] = {0};
int tpc = 0;
uint32_t tnc = ts_node_named_child_count(tparams);
for (uint32_t i = 0; i < tnc && tpc < 15; i++) {
TSNode tp = ts_node_named_child(tparams, i);
- if (ts_node_is_null(tp)) continue;
+ if (ts_node_is_null(tp))
+ continue;
// type_parameter has child name (type_identifier or identifier).
- TSNode tname = ts_node_child_by_field_name(tp, "name",
- TS_LSP_FIELD_LEN("name"));
+ TSNode tname = ts_node_child_by_field_name(tp, "name", TS_LSP_FIELD_LEN("name"));
if (ts_node_is_null(tname)) {
// First named child fallback.
if (ts_node_named_child_count(tp) > 0) {
tname = ts_node_named_child(tp, 0);
}
}
- if (ts_node_is_null(tname)) continue;
- char* nm = node_text(ctx, tname);
- if (!nm) continue;
+ if (ts_node_is_null(tname))
+ continue;
+ char *nm = node_text(ctx, tname);
+ if (!nm)
+ continue;
names[tpc] = nm;
args[tpc] = cbm_type_type_param(ctx->arena, nm);
tpc++;
}
names[tpc] = NULL;
args[tpc] = NULL;
- if (tpc == 0) continue;
+ if (tpc == 0)
+ continue;
// Resolve the function's QN.
TSNode name_node = ts_node_child_by_field_name(n, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name_node)) continue;
- char* fname = node_text(ctx, name_node);
- if (!fname) continue;
+ if (ts_node_is_null(name_node))
+ continue;
+ char *fname = node_text(ctx, name_node);
+ if (!fname)
+ continue;
// For methods, the receiver class must be in QN. For free functions, just module.
- const char* fqn = NULL;
+ const char *fqn = NULL;
if (is_func) {
fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
} else {
@@ -3798,28 +4265,35 @@ static void convert_signature_type_params(TSLSPContext* ctx, TSNode root, CBMTyp
strcmp(ts_node_type(parent), "class_declaration") != 0) {
parent = ts_node_parent(parent);
}
- if (ts_node_is_null(parent)) continue;
- TSNode cn = ts_node_child_by_field_name(parent, "name",
- TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(cn)) continue;
- char* cname = node_text(ctx, cn);
- if (!cname) continue;
+ if (ts_node_is_null(parent))
+ continue;
+ TSNode cn = ts_node_child_by_field_name(parent, "name", TS_LSP_FIELD_LEN("name"));
+ if (ts_node_is_null(cn))
+ continue;
+ char *cname = node_text(ctx, cn);
+ if (!cname)
+ continue;
fqn = cbm_arena_sprintf(ctx->arena, "%s.%s.%s", ctx->module_qn, cname, fname);
}
// Patch the registered func's signature: rewrite NAMED → TYPE_PARAM.
for (int fi = 0; fi < reg->func_count; fi++) {
- if (!reg->funcs[fi].qualified_name) continue;
- if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0) continue;
- const CBMType* old_sig = reg->funcs[fi].signature;
- if (!old_sig) break;
- const CBMType* new_sig = cbm_type_substitute(ctx->arena, old_sig, names, args);
- if (new_sig) reg->funcs[fi].signature = new_sig;
+ if (!reg->funcs[fi].qualified_name)
+ continue;
+ if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0)
+ continue;
+ const CBMType *old_sig = reg->funcs[fi].signature;
+ if (!old_sig)
+ break;
+ const CBMType *new_sig = cbm_type_substitute(ctx->arena, old_sig, names, args);
+ if (new_sig)
+ reg->funcs[fi].signature = new_sig;
// Also store the type_param_names for later overload-by-types use.
- const char** stored = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)(tpc + 1) * sizeof(const char*));
+ const char **stored = (const char **)cbm_arena_alloc(
+ ctx->arena, (size_t)(tpc + 1) * sizeof(const char *));
if (stored) {
- for (int ti = 0; ti < tpc; ti++) stored[ti] = names[ti];
+ for (int ti = 0; ti < tpc; ti++)
+ stored[ti] = names[ti];
stored[tpc] = NULL;
reg->funcs[fi].type_param_names = stored;
}
@@ -3839,49 +4313,60 @@ static void convert_signature_type_params(TSLSPContext* ctx, TSNode root, CBMTyp
// Skips: nested braces in the type, complex JSDoc syntax (callback definitions,
// @typedef, etc.). Falls back gracefully on UNKNOWN.
typedef struct {
- const char* name;
- const CBMType* type;
+ const char *name;
+ const CBMType *type;
} JSDocParam;
-static void parse_jsdoc_block(TSLSPContext* ctx, const char* text, size_t len,
- JSDocParam* out_params, int* out_param_count, int max_params,
- const CBMType** out_return) {
+static void parse_jsdoc_block(TSLSPContext *ctx, const char *text, size_t len,
+ JSDocParam *out_params, int *out_param_count, int max_params,
+ const CBMType **out_return) {
*out_return = NULL;
*out_param_count = 0;
- if (!text || len == 0) return;
+ if (!text || len == 0)
+ return;
- const char* end = text + len;
- const char* p = text;
+ const char *end = text + len;
+ const char *p = text;
while (p < end) {
// Find next `@` that introduces a tag.
- while (p < end && *p != '@') p++;
- if (p >= end) return;
+ while (p < end && *p != '@')
+ p++;
+ if (p >= end)
+ return;
p++; // skip @
// Match "param" or "returns"/"return".
- const char* tag_start = p;
- while (p < end && (*p >= 'a' && *p <= 'z')) p++;
+ const char *tag_start = p;
+ while (p < end && (*p >= 'a' && *p <= 'z'))
+ p++;
size_t tag_len = (size_t)(p - tag_start);
bool is_param = (tag_len == 5 && memcmp(tag_start, "param", 5) == 0);
bool is_return = ((tag_len == 7 && memcmp(tag_start, "returns", 7) == 0) ||
(tag_len == 6 && memcmp(tag_start, "return", 6) == 0));
- if (!is_param && !is_return) continue;
+ if (!is_param && !is_return)
+ continue;
// Skip whitespace.
- while (p < end && (*p == ' ' || *p == '\t')) p++;
- if (p >= end || *p != '{') continue;
+ while (p < end && (*p == ' ' || *p == '\t'))
+ p++;
+ if (p >= end || *p != '{')
+ continue;
p++; // skip {
- const char* type_start = p;
+ const char *type_start = p;
int depth = 1;
while (p < end && depth > 0) {
- if (*p == '{') depth++;
- else if (*p == '}') depth--;
- if (depth > 0) p++;
+ if (*p == '{')
+ depth++;
+ else if (*p == '}')
+ depth--;
+ if (depth > 0)
+ p++;
}
- if (p >= end || *p != '}') continue;
+ if (p >= end || *p != '}')
+ continue;
size_t type_len = (size_t)(p - type_start);
- char* type_text = cbm_arena_strndup(ctx->arena, type_start, type_len);
- const CBMType* parsed = parse_ts_type_text(ctx->arena, type_text, ctx->module_qn);
+ char *type_text = cbm_arena_strndup(ctx->arena, type_start, type_len);
+ const CBMType *parsed = parse_ts_type_text(ctx->arena, type_text, ctx->module_qn);
p++; // skip }
if (is_return) {
@@ -3890,14 +4375,17 @@ static void parse_jsdoc_block(TSLSPContext* ctx, const char* text, size_t len,
}
// Param: skip whitespace then read name.
- while (p < end && (*p == ' ' || *p == '\t')) p++;
- const char* name_start = p;
+ while (p < end && (*p == ' ' || *p == '\t'))
+ p++;
+ const char *name_start = p;
while (p < end && ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
- (*p >= '0' && *p <= '9') || *p == '_' || *p == '$' || *p == '.')) p++;
+ (*p >= '0' && *p <= '9') || *p == '_' || *p == '$' || *p == '.'))
+ p++;
size_t name_len = (size_t)(p - name_start);
- if (name_len == 0) continue;
+ if (name_len == 0)
+ continue;
if (*out_param_count < max_params) {
- char* nm = cbm_arena_strndup(ctx->arena, name_start, name_len);
+ char *nm = cbm_arena_strndup(ctx->arena, name_start, name_len);
out_params[*out_param_count].name = nm;
out_params[*out_param_count].type = parsed;
(*out_param_count)++;
@@ -3907,14 +4395,16 @@ static void parse_jsdoc_block(TSLSPContext* ctx, const char* text, size_t len,
// For each function_declaration in `js_mode` with a JSDoc-style comment immediately
// before it, parse the comment and patch the registered func's signature.
-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;
+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 kn = 0;
- TSNode* kids = collect_children(ctx->arena, root, &kn);
+ 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;
+ if (strcmp(ts_node_type(n), "function_declaration") != 0)
+ continue;
// Find the immediate preceding comment sibling (skip whitespace nodes which
// tree-sitter doesn't expose as named children, but unnamed children may include
@@ -3922,49 +4412,63 @@ static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegist
TSNode prev = {0};
for (int j = (int)i - 1; j >= 0; j--) {
TSNode candidate = kids[j];
- const char* ck = ts_node_type(candidate);
- if (strcmp(ck, "comment") == 0) { prev = candidate; break; }
+ const char *ck = ts_node_type(candidate);
+ if (strcmp(ck, "comment") == 0) {
+ prev = candidate;
+ break;
+ }
// Anything else: stop — JSDoc must be immediately preceding.
- if (ts_node_is_named(candidate)) break;
+ if (ts_node_is_named(candidate))
+ break;
}
- if (ts_node_is_null(prev)) continue;
+ if (ts_node_is_null(prev))
+ continue;
// Get comment text and check JSDoc shape (`/** ... */`).
- char* ctext = node_text(ctx, prev);
- if (!ctext) continue;
+ char *ctext = node_text(ctx, prev);
+ if (!ctext)
+ continue;
size_t clen = strlen(ctext);
- if (clen < 4 || ctext[0] != '/' || ctext[1] != '*' || ctext[2] != '*') continue;
+ if (clen < 4 || ctext[0] != '/' || ctext[1] != '*' || ctext[2] != '*')
+ continue;
JSDocParam params[16];
int pcount = 0;
- const CBMType* ret = NULL;
+ const CBMType *ret = NULL;
parse_jsdoc_block(ctx, ctext + 3, clen - 3, params, &pcount, 16, &ret);
// Resolve the function's QN and patch the registered signature.
TSNode name_node = ts_node_child_by_field_name(n, "name", TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(name_node)) continue;
- char* fname = node_text(ctx, name_node);
- if (!fname) continue;
- const char* fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
+ if (ts_node_is_null(name_node))
+ continue;
+ char *fname = node_text(ctx, name_node);
+ if (!fname)
+ continue;
+ const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
for (int fi = 0; fi < reg->func_count; fi++) {
- if (!reg->funcs[fi].qualified_name) continue;
- if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0) continue;
- const CBMType* old_sig = reg->funcs[fi].signature;
- const CBMType** rets = NULL;
+ if (!reg->funcs[fi].qualified_name)
+ continue;
+ if (strcmp(reg->funcs[fi].qualified_name, fqn) != 0)
+ continue;
+ const CBMType *old_sig = reg->funcs[fi].signature;
+ const CBMType **rets = NULL;
if (ret && !cbm_type_is_unknown(ret)) {
- rets = (const CBMType**)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType*));
- if (rets) { rets[0] = ret; rets[1] = NULL; }
+ rets = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
+ if (rets) {
+ rets[0] = ret;
+ rets[1] = NULL;
+ }
} else if (old_sig && old_sig->kind == CBM_TYPE_FUNC) {
rets = old_sig->data.func.return_types;
}
- const CBMType** params_arr = NULL;
- const char** param_names_arr = NULL;
+ const CBMType **params_arr = NULL;
+ const char **param_names_arr = NULL;
if (pcount > 0) {
- params_arr = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(pcount + 1) * sizeof(const CBMType*));
- param_names_arr = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)(pcount + 1) * sizeof(const char*));
+ params_arr = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(pcount + 1) * sizeof(const CBMType *));
+ param_names_arr = (const char **)cbm_arena_alloc(
+ ctx->arena, (size_t)(pcount + 1) * sizeof(const char *));
if (params_arr && param_names_arr) {
for (int j = 0; j < pcount; j++) {
params_arr[j] = params[j].type;
@@ -3977,8 +4481,7 @@ static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegist
params_arr = old_sig->data.func.param_types;
param_names_arr = old_sig->data.func.param_names;
}
- reg->funcs[fi].signature = cbm_type_func(ctx->arena, param_names_arr,
- params_arr, rets);
+ reg->funcs[fi].signature = cbm_type_func(ctx->arena, param_names_arr, params_arr, rets);
break;
}
}
@@ -3987,37 +4490,41 @@ static void apply_jsdoc_signatures(TSLSPContext* ctx, TSNode root, CBMTypeRegist
// For each function_declaration whose registered signature has no return type, infer
// it from the body and rebuild the signature. This mirrors typescript-go's
// 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;
+static void infer_implicit_returns(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
+ if (ts_node_is_null(root) || !reg || !ctx->module_qn)
+ return;
uint32_t kn = 0;
- TSNode* kids = collect_children(ctx->arena, root, &kn);
+ TSNode *kids = collect_children(ctx->arena, root, &kn);
for (uint32_t i = 0; i < kn; i++) {
TSNode n = kids[i];
- const char* k = ts_node_type(n);
+ const char *k = ts_node_type(n);
TSNode decl = n;
if (strcmp(k, "export_statement") == 0) {
- TSNode d = ts_node_child_by_field_name(n, "declaration",
- TS_LSP_FIELD_LEN("declaration"));
+ TSNode d =
+ ts_node_child_by_field_name(n, "declaration", TS_LSP_FIELD_LEN("declaration"));
if (!ts_node_is_null(d)) {
decl = d;
k = ts_node_type(decl);
}
}
- if (strcmp(k, "function_declaration") != 0) continue;
+ if (strcmp(k, "function_declaration") != 0)
+ continue;
- TSNode name_node = ts_node_child_by_field_name(decl, "name",
- TS_LSP_FIELD_LEN("name"));
+ TSNode name_node = ts_node_child_by_field_name(decl, "name", TS_LSP_FIELD_LEN("name"));
TSNode body = ts_node_child_by_field_name(decl, "body", TS_LSP_FIELD_LEN("body"));
- if (ts_node_is_null(name_node) || ts_node_is_null(body)) continue;
+ if (ts_node_is_null(name_node) || ts_node_is_null(body))
+ continue;
- char* fname = node_text(ctx, name_node);
- if (!fname) continue;
- const char* fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
- const CBMRegisteredFunc* existing = cbm_registry_lookup_func(reg, fqn);
- if (!existing) continue;
+ char *fname = node_text(ctx, name_node);
+ if (!fname)
+ continue;
+ const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fname);
+ const CBMRegisteredFunc *existing = cbm_registry_lookup_func(reg, fqn);
+ if (!existing)
+ continue;
// Only infer when the existing signature lacks an explicit return type.
if (existing->signature && existing->signature->kind == CBM_TYPE_FUNC &&
existing->signature->data.func.return_types &&
@@ -4026,18 +4533,19 @@ static void infer_implicit_returns(TSLSPContext* ctx, TSNode root, CBMTypeRegist
continue;
}
- const CBMType* inferred = infer_return_type_from_body(ctx, body);
- if (cbm_type_is_unknown(inferred)) continue;
+ const CBMType *inferred = infer_return_type_from_body(ctx, body);
+ if (cbm_type_is_unknown(inferred))
+ continue;
// Build a new FUNC signature carrying over params from the existing one (if any).
- const char** param_names = NULL;
- const CBMType** param_types = NULL;
+ const char **param_names = NULL;
+ const CBMType **param_types = NULL;
if (existing->signature && existing->signature->kind == CBM_TYPE_FUNC) {
param_names = existing->signature->data.func.param_names;
param_types = existing->signature->data.func.param_types;
}
- const CBMType* rets[2] = {inferred, NULL};
- const CBMType* new_sig = cbm_type_func(ctx->arena, param_names, param_types, rets);
+ const CBMType *rets[2] = {inferred, NULL};
+ const CBMType *new_sig = cbm_type_func(ctx->arena, param_names, param_types, rets);
// Patch the registered func in place.
for (int fi = 0; fi < reg->func_count; fi++) {
@@ -4053,19 +4561,20 @@ static void infer_implicit_returns(TSLSPContext* ctx, TSNode root, CBMTypeRegist
// AST sweep: walk class/interface bodies to collect field names+types and refine
// embedded_types / type_param_names.
-static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* reg) {
- if (ts_node_is_null(root) || !reg) return;
+static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
+ if (ts_node_is_null(root) || !reg)
+ return;
uint32_t kn = 0;
- TSNode* kids = collect_children(ctx->arena, root, &kn);
+ TSNode *kids = collect_children(ctx->arena, root, &kn);
for (uint32_t i = 0; i < kn; i++) {
TSNode n = kids[i];
- const char* k = ts_node_type(n);
+ const char *k = ts_node_type(n);
TSNode decl = n;
if (strcmp(k, "export_statement") == 0) {
// Look for declaration field.
- TSNode d = ts_node_child_by_field_name(n, "declaration",
- TS_LSP_FIELD_LEN("declaration"));
+ TSNode d =
+ ts_node_child_by_field_name(n, "declaration", TS_LSP_FIELD_LEN("declaration"));
if (!ts_node_is_null(d)) {
decl = d;
k = ts_node_type(decl);
@@ -4075,13 +4584,15 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
if (strcmp(k, "type_alias_declaration") == 0) {
TSNode name = ts_node_child_by_field_name(decl, "name", TS_LSP_FIELD_LEN("name"));
TSNode val = ts_node_child_by_field_name(decl, "value", TS_LSP_FIELD_LEN("value"));
- if (ts_node_is_null(name) || ts_node_is_null(val) || !ctx->module_qn) continue;
- char* nm = node_text(ctx, name);
- if (!nm) continue;
- const char* qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, nm);
+ if (ts_node_is_null(name) || ts_node_is_null(val) || !ctx->module_qn)
+ continue;
+ char *nm = node_text(ctx, name);
+ if (!nm)
+ continue;
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, nm);
// alias_of: resolved to QN if it's a NAMED text we can qualify.
- char* val_text = node_text(ctx, val);
- const char* alias_qn = NULL;
+ char *val_text = node_text(ctx, val);
+ const char *alias_qn = NULL;
if (val_text && val_text[0] && strchr(val_text, ' ') == NULL &&
strchr(val_text, '|') == NULL && strchr(val_text, '&') == NULL) {
if (strchr(val_text, '.') == NULL && val_text[0] >= 'A' && val_text[0] <= 'Z') {
@@ -4095,7 +4606,8 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
for (int ti = 0; ti < reg->type_count; ti++) {
if (reg->types[ti].qualified_name &&
strcmp(reg->types[ti].qualified_name, qn) == 0) {
- if (alias_qn) reg->types[ti].alias_of = alias_qn;
+ if (alias_qn)
+ reg->types[ti].alias_of = alias_qn;
found = true;
break;
}
@@ -4115,16 +4627,17 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
continue;
}
- TSNode name_node = ts_node_child_by_field_name(decl, "name",
- TS_LSP_FIELD_LEN("name"));
+ TSNode name_node = ts_node_child_by_field_name(decl, "name", TS_LSP_FIELD_LEN("name"));
TSNode body = ts_node_child_by_field_name(decl, "body", TS_LSP_FIELD_LEN("body"));
- if (ts_node_is_null(name_node) || ts_node_is_null(body) || !ctx->module_qn) continue;
- char* cname = node_text(ctx, name_node);
- if (!cname) continue;
- const char* class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
+ if (ts_node_is_null(name_node) || ts_node_is_null(body) || !ctx->module_qn)
+ continue;
+ char *cname = node_text(ctx, name_node);
+ if (!cname)
+ continue;
+ const char *class_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, cname);
// Find the registered type and augment with fields.
- CBMRegisteredType* rt = NULL;
+ CBMRegisteredType *rt = NULL;
for (int ti = 0; ti < reg->type_count; ti++) {
if (reg->types[ti].qualified_name &&
strcmp(reg->types[ti].qualified_name, class_qn) == 0) {
@@ -4132,23 +4645,25 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
break;
}
}
- if (!rt) continue;
+ if (!rt)
+ continue;
- const char* field_names[64] = {0};
- const CBMType* field_types[64] = {0};
+ const char *field_names[64] = {0};
+ const CBMType *field_types[64] = {0};
int field_count = 0;
// Interface method signatures we need to register as separate funcs.
- const char* iface_method_names[64] = {0};
- const char* iface_method_qns[64] = {0};
- const CBMType* iface_method_sigs[64] = {0};
+ const char *iface_method_names[64] = {0};
+ const char *iface_method_qns[64] = {0};
+ const CBMType *iface_method_sigs[64] = {0};
int iface_method_count = 0;
bool is_interface = (strcmp(k, "interface_declaration") == 0);
uint32_t bnc = ts_node_named_child_count(body);
for (uint32_t bi = 0; bi < bnc && field_count < 63; bi++) {
TSNode m = ts_node_named_child(body, bi);
- if (ts_node_is_null(m)) continue;
- const char* mk = ts_node_type(m);
+ if (ts_node_is_null(m))
+ continue;
+ const char *mk = ts_node_type(m);
// public_field_definition: TS class fields.
// property_signature: interface fields. Interface fields can be either
@@ -4157,13 +4672,16 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
strcmp(mk, "property_signature") == 0) {
TSNode fname = ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
TSNode ftype = ts_node_child_by_field_name(m, "type", TS_LSP_FIELD_LEN("type"));
- if (ts_node_is_null(fname)) continue;
- char* fnm = node_text(ctx, fname);
- if (!fnm) continue;
- const CBMType* ft = cbm_type_unknown();
+ if (ts_node_is_null(fname))
+ continue;
+ char *fnm = node_text(ctx, fname);
+ if (!fnm)
+ continue;
+ const CBMType *ft = cbm_type_unknown();
if (!ts_node_is_null(ftype)) {
TSNode tch = ts_node_named_child(ftype, 0);
- if (!ts_node_is_null(tch)) ft = ts_parse_type_node(ctx, tch);
+ if (!ts_node_is_null(tch))
+ ft = ts_parse_type_node(ctx, tch);
}
field_names[field_count] = fnm;
field_types[field_count] = ft;
@@ -4174,27 +4692,30 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
// Interface method signature: `methodName(params): ReturnType;`
// Or class method declaration in `.d.ts` ambient mode.
if (is_interface && (strcmp(mk, "method_signature") == 0)) {
- if (iface_method_count >= 63) continue;
- TSNode mname = ts_node_child_by_field_name(m, "name",
- TS_LSP_FIELD_LEN("name"));
- if (ts_node_is_null(mname)) continue;
- char* mnm = node_text(ctx, mname);
- if (!mnm) continue;
+ if (iface_method_count >= 63)
+ continue;
+ TSNode mname = ts_node_child_by_field_name(m, "name", TS_LSP_FIELD_LEN("name"));
+ if (ts_node_is_null(mname))
+ continue;
+ char *mnm = node_text(ctx, mname);
+ if (!mnm)
+ continue;
// Return type via field "return_type" — it's a type_annotation node.
- const CBMType* ret = cbm_type_unknown();
- TSNode rt_node = ts_node_child_by_field_name(m, "return_type",
- TS_LSP_FIELD_LEN("return_type"));
+ const CBMType *ret = cbm_type_unknown();
+ TSNode rt_node =
+ ts_node_child_by_field_name(m, "return_type", TS_LSP_FIELD_LEN("return_type"));
if (!ts_node_is_null(rt_node)) {
TSNode tch = (strcmp(ts_node_type(rt_node), "type_annotation") == 0)
? ts_node_named_child(rt_node, 0)
: rt_node;
- if (!ts_node_is_null(tch)) ret = ts_parse_type_node(ctx, tch);
+ if (!ts_node_is_null(tch))
+ ret = ts_parse_type_node(ctx, tch);
}
- const CBMType* rets[2] = {ret, NULL};
- const CBMType* sig = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ const CBMType *rets[2] = {ret, NULL};
+ const CBMType *sig = cbm_type_func(ctx->arena, NULL, NULL, rets);
- const char* mqn = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mnm);
+ const char *mqn = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mnm);
iface_method_names[iface_method_count] = mnm;
iface_method_qns[iface_method_count] = mqn;
iface_method_sigs[iface_method_count] = sig;
@@ -4212,10 +4733,10 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
}
}
if (field_count > 0) {
- const char** fn_arr = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)(field_count + 1) * sizeof(const char*));
- const CBMType** ft_arr = (const CBMType**)cbm_arena_alloc(ctx->arena,
- (size_t)(field_count + 1) * sizeof(const CBMType*));
+ const char **fn_arr = (const char **)cbm_arena_alloc(
+ ctx->arena, (size_t)(field_count + 1) * sizeof(const char *));
+ const CBMType **ft_arr = (const CBMType **)cbm_arena_alloc(
+ ctx->arena, (size_t)(field_count + 1) * sizeof(const CBMType *));
if (fn_arr && ft_arr) {
for (int j = 0; j < field_count; j++) {
fn_arr[j] = field_names[j];
@@ -4230,10 +4751,10 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
// Attach interface method names/qns to the registered type.
if (iface_method_count > 0) {
- const char** mn_arr = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)(iface_method_count + 1) * sizeof(const char*));
- const char** mq_arr = (const char**)cbm_arena_alloc(ctx->arena,
- (size_t)(iface_method_count + 1) * sizeof(const char*));
+ const char **mn_arr = (const char **)cbm_arena_alloc(
+ ctx->arena, (size_t)(iface_method_count + 1) * sizeof(const char *));
+ const char **mq_arr = (const char **)cbm_arena_alloc(
+ ctx->arena, (size_t)(iface_method_count + 1) * sizeof(const char *));
if (mn_arr && mq_arr) {
for (int j = 0; j < iface_method_count; j++) {
mn_arr[j] = iface_method_names[j];
@@ -4244,21 +4765,22 @@ static void ast_sweep_shapes(TSLSPContext* ctx, TSNode root, CBMTypeRegistry* re
rt->method_names = mn_arr;
rt->method_qns = mq_arr;
}
- (void)iface_method_sigs; // sigs already attached via cbm_registry_add_func
+ (void)iface_method_sigs; // sigs already attached via cbm_registry_add_func
}
}
}
-void cbm_run_ts_lsp(CBMArena* arena, CBMFileResult* result,
- const char* source, int source_len, TSNode root,
- bool js_mode, bool jsx_mode, bool dts_mode) {
- if (!arena || !result || !source || ts_node_is_null(root)) return;
+void cbm_run_ts_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root, bool js_mode, bool jsx_mode, bool dts_mode) {
+ if (!arena || !result || !source || ts_node_is_null(root))
+ return;
// Diagnostic / benchmarking knob: setting `CBM_LSP_DISABLED=1` skips the resolver.
// This is used by the baseline-vs-LSP comparison tests to measure how many calls
// the LSP-augmented path adds over plain tree-sitter extraction.
- const char* disabled = getenv("CBM_LSP_DISABLED");
- if (disabled && disabled[0] && disabled[0] != '0') return;
+ const char *disabled = getenv("CBM_LSP_DISABLED");
+ if (disabled && disabled[0] && disabled[0] != '0')
+ return;
CBMTypeRegistry reg;
cbm_registry_init(&reg, arena);
@@ -4266,14 +4788,14 @@ void cbm_run_ts_lsp(CBMArena* arena, CBMFileResult* result,
register_file_defs(arena, &reg, result, result->module_qn);
TSLSPContext ctx;
- ts_lsp_init(&ctx, arena, source, source_len, &reg, result->module_qn,
- js_mode, jsx_mode, dts_mode, &result->resolved_calls);
+ ts_lsp_init(&ctx, arena, source, source_len, &reg, result->module_qn, js_mode, jsx_mode,
+ dts_mode, &result->resolved_calls);
// Add imports early so type-resolution passes can rewrite NAMED references that
// refer to imported symbols. ts_parse_type_node consults these via
// resolve_type_with_imports.
for (int i = 0; i < result->imports.count; i++) {
- const CBMImport* imp = &result->imports.items[i];
+ const CBMImport *imp = &result->imports.items[i];
if (imp->local_name && imp->module_path) {
ts_lsp_add_import(&ctx, imp->local_name, imp->module_path);
}
@@ -4294,11 +4816,12 @@ void cbm_run_ts_lsp(CBMArena* arena, CBMFileResult* result,
* 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) {
+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;
+ 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;
@@ -4308,16 +4831,19 @@ static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
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*));
+ 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++) {
+ 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;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4327,26 +4853,29 @@ static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
}
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*));
+ 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++) {
+ 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;
+ 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);
+ ft_arr[idx] =
+ parse_ts_type_text(arena, colon + 1, d->def_module_qn);
idx++;
}
- if (*s == '\0') break;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4359,28 +4888,31 @@ static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
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*));
+ 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++) {
+ 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));
+ 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;
+ 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];
+ CBMRegisteredType *rt_just = &reg->types[reg->type_count - 1];
rt_just->method_names = mn_arr;
rt_just->method_qns = mqn_arr;
}
@@ -4394,17 +4926,20 @@ static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
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*));
+ 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++) {
+ 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));
+ 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;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4424,14 +4959,16 @@ static void ts_register_lsp_defs(CBMArena* arena, CBMTypeRegistry* reg,
* (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;
+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];
+ CBMLSPDef *d = &defs[i];
if (d->lang != CBM_LANG_JAVASCRIPT && d->lang != CBM_LANG_TYPESCRIPT &&
d->lang != CBM_LANG_TSX) {
continue;
@@ -4449,17 +4986,14 @@ CBMTypeRegistry* cbm_ts_build_cross_registry(CBMArena* arena, CBMLSPDef* defs, i
* `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;
+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. */
@@ -4467,40 +5001,43 @@ void cbm_run_ts_lsp_cross_with_registry(CBMArena* arena,
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 : "";
+ 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;
+ 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());
+ 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;
+ 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);
+ 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);
+ 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]);
@@ -4515,18 +5052,17 @@ void cbm_run_ts_lsp_cross_with_registry(CBMArena* arena,
ts_lsp_process_file(&ctx, root);
- if (owns_tree) ts_tree_delete(tree);
+ 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,
- bool js_mode, bool jsx_mode, bool dts_mode,
- CBMLSPDef* defs, int def_count,
- const char** import_names, const char** import_qns, int import_count,
- TSTree* cached_tree,
- CBMResolvedCallArray* out) {
- if (!arena || !out) return;
+void cbm_run_ts_lsp_cross(CBMArena *arena, const char *source, int source_len,
+ const char *module_qn, bool js_mode, bool jsx_mode, bool dts_mode,
+ CBMLSPDef *defs, int def_count, const char **import_names,
+ const char **import_qns, int import_count, TSTree *cached_tree,
+ CBMResolvedCallArray *out) {
+ if (!arena || !out)
+ return;
CBMTypeRegistry reg;
cbm_registry_init(&reg, arena);
@@ -4534,8 +5070,9 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
// Register cross-file defs.
for (int i = 0; i < def_count; i++) {
- const CBMLSPDef* d = &defs[i];
- if (!d->qualified_name || !d->short_name || !d->label) continue;
+ 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;
@@ -4546,16 +5083,19 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
// Embedded types (extends list) — pipe-separated.
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*));
+ 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++) {
+ 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;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4566,26 +5106,29 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
// Field defs (interface members, "name:type|name:type").
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*));
+ 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++) {
+ 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;
+ 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);
+ ft_arr[idx] =
+ parse_ts_type_text(arena, colon + 1, d->def_module_qn);
idx++;
}
- if (*s == '\0') break;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4599,21 +5142,24 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
// Method names from method_names_str.
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*));
+ 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++) {
+ 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));
+ 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;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4621,7 +5167,7 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
mqn_arr[idx] = NULL;
// Find the type we just inserted and attach.
if (reg.type_count > 0) {
- CBMRegisteredType* rt_just = &reg.types[reg.type_count - 1];
+ CBMRegisteredType *rt_just = &reg.types[reg.type_count - 1];
rt_just->method_names = mn_arr;
rt_just->method_qns = mqn_arr;
}
@@ -4636,17 +5182,20 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
// Return types from pipe-separated return_types text.
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*));
+ 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++) {
+ 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));
+ 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;
+ if (*s == '\0')
+ break;
start = s + 1;
}
}
@@ -4662,25 +5211,28 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
}
// Use cached tree if available; otherwise parse internally and own it.
- TSTree* tree = cached_tree;
+ 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());
+ 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;
+ 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);
+ if (owns_tree)
+ ts_tree_delete(tree);
return;
}
@@ -4691,8 +5243,7 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
cbm_registry_finalize(&reg);
TSLSPContext ctx;
- ts_lsp_init(&ctx, arena, source, source_len, &reg, module_qn,
- js_mode, jsx_mode, dts_mode, out);
+ ts_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, js_mode, jsx_mode, dts_mode, out);
// Add imports early so type passes can resolve imported types.
for (int i = 0; i < import_count; i++) {
@@ -4709,25 +5260,24 @@ void cbm_run_ts_lsp_cross(CBMArena* arena,
ts_lsp_process_file(&ctx, root);
- if (owns_tree) ts_tree_delete(tree);
+ if (owns_tree)
+ ts_tree_delete(tree);
}
// ── Batch cross-file (Phase 3) ────────────────────────────────────────────────
-void cbm_batch_ts_lsp_cross(CBMArena* arena,
- CBMBatchTSLSPFile* files, int file_count,
- CBMResolvedCallArray* out) {
- if (!arena || !files || !out || file_count <= 0) return;
+void cbm_batch_ts_lsp_cross(CBMArena *arena, CBMBatchTSLSPFile *files, int file_count,
+ CBMResolvedCallArray *out) {
+ if (!arena || !files || !out || file_count <= 0)
+ return;
// Project-scope merging happens implicitly: every file's CBMLSPDef set already
// includes both same-file and cross-file defs (built by the caller). The plan §17
// finding #4 fix ensures the *caller* (pass_calls.c) merges interface declarations
// by QN before passing them in.
for (int i = 0; i < file_count; i++) {
- CBMBatchTSLSPFile* f = &files[i];
- cbm_run_ts_lsp_cross(arena, f->source, f->source_len, f->module_qn,
- f->js_mode, f->jsx_mode, f->dts_mode,
- f->defs, f->def_count,
- f->import_names, f->import_qns, f->import_count,
- f->cached_tree, &out[i]);
+ CBMBatchTSLSPFile *f = &files[i];
+ cbm_run_ts_lsp_cross(arena, f->source, f->source_len, f->module_qn, f->js_mode, f->jsx_mode,
+ f->dts_mode, f->defs, f->def_count, f->import_names, f->import_qns,
+ f->import_count, f->cached_tree, &out[i]);
}
}
diff --git a/internal/cbm/lsp/ts_lsp.h b/internal/cbm/lsp/ts_lsp.h
index 61831d65c..154d38ee7 100644
--- a/internal/cbm/lsp/ts_lsp.h
+++ b/internal/cbm/lsp/ts_lsp.h
@@ -5,7 +5,7 @@
#include "scope.h"
#include "type_registry.h"
#include "../cbm.h"
-#include "go_lsp.h" // for CBMLSPDef, CBMResolvedCallArray (shared cross-language)
+#include "go_lsp.h" // for CBMLSPDef, CBMResolvedCallArray (shared cross-language)
// TSLSPContext holds state for TypeScript / JavaScript / JSX / TSX expression type
// evaluation within a single file. One context per cbm_run_ts_lsp invocation.
@@ -21,136 +21,130 @@
// Modes are independent: a `.tsx` file sets jsx_mode=true with js_mode=false; a `.jsx` file
// sets both true.
typedef struct {
- CBMArena* arena;
- const char* source;
+ CBMArena *arena;
+ const char *source;
int source_len;
- const CBMTypeRegistry* registry;
- CBMScope* current_scope;
+ const CBMTypeRegistry *registry;
+ CBMScope *current_scope;
// Import map: local_name -> module QN (resolved or opaque).
// Parallel arrays of length import_count.
- const char** import_local_names;
- const char** import_module_qns;
+ const char **import_local_names;
+ const char **import_module_qns;
int import_count;
// File / surrounding context.
- const char* module_qn; // QN of this file's module
- const char* enclosing_func_qn; // current function being walked, NULL at module scope
- const char* enclosing_class_qn; // current class for `this` resolution
+ const char *module_qn; // QN of this file's module
+ const char *enclosing_func_qn; // current function being walked, NULL at module scope
+ const char *enclosing_class_qn; // current class for `this` resolution
// Output: resolved calls accumulate here.
- CBMResolvedCallArray* resolved_calls;
+ CBMResolvedCallArray *resolved_calls;
// Type-parameter scope (innermost generic function/class).
// type_param_constraints may be NULL or shorter — entries default to "any".
- const char** type_param_names;
- const CBMType** type_param_constraints;
+ const char **type_param_names;
+ const CBMType **type_param_constraints;
int type_param_count;
// Mode flags — see comment above.
bool js_mode;
bool jsx_mode;
bool dts_mode;
- bool strict; // tsconfig "strict": true → fewer implicit-any fallbacks
- bool debug; // CBM_LSP_DEBUG env
+ bool strict; // tsconfig "strict": true → fewer implicit-any fallbacks
+ bool debug; // CBM_LSP_DEBUG env
// Recursion guard for ts_eval_expr_type (mirrors c_lsp).
int eval_depth;
+ // 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;
// --- Initialization ---
// Initialise a TSLSPContext for processing one file. Mode flags select dialect.
-void ts_lsp_init(TSLSPContext* ctx, CBMArena* arena, const char* source, int source_len,
- const CBMTypeRegistry* registry, const char* module_qn,
- bool js_mode, bool jsx_mode, bool dts_mode,
- CBMResolvedCallArray* out);
+void ts_lsp_init(TSLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn, bool js_mode,
+ bool jsx_mode, bool dts_mode, CBMResolvedCallArray *out);
// Register an import: local binding name → module QN (or unresolved module specifier).
-void ts_lsp_add_import(TSLSPContext* ctx, const char* local_name, const char* module_qn);
+void ts_lsp_add_import(TSLSPContext *ctx, const char *local_name, const char *module_qn);
// Walk the entire file: bind module-level declarations, then process every function /
// method body. Safe on any tree-sitter root; emits zero calls in dts_mode.
-void ts_lsp_process_file(TSLSPContext* ctx, TSNode root);
+void ts_lsp_process_file(TSLSPContext *ctx, TSNode root);
// --- Internals exposed for tests and stdlib data ---
// Evaluate the type of a TS/JS expression node. Returns cbm_type_unknown() on miss.
-const CBMType* ts_eval_expr_type(TSLSPContext* ctx, TSNode node);
+const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node);
// Parse a TS/JS type-position AST node into a CBMType.
-const CBMType* ts_parse_type_node(TSLSPContext* ctx, TSNode node);
+const CBMType *ts_parse_type_node(TSLSPContext *ctx, TSNode node);
// Process a single statement node, binding any variables it declares into ctx->current_scope.
-void ts_process_statement(TSLSPContext* ctx, TSNode node);
+void ts_process_statement(TSLSPContext *ctx, TSNode node);
// --- Entry points ---
// Single-file LSP. Builds a registry from result->defs + the TS stdlib subset, runs
// resolution, and writes resolved calls into result->resolved_calls.
-void cbm_run_ts_lsp(CBMArena* arena, CBMFileResult* result,
- const char* source, int source_len, TSNode root,
- bool js_mode, bool jsx_mode, bool dts_mode);
+void cbm_run_ts_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root, bool js_mode, bool jsx_mode, bool dts_mode);
// Cross-file LSP. Caller passes in cross-file definitions (CBMLSPDef list) and the
// resolved import → module-QN map. Re-parses source if cached_tree is NULL.
-void cbm_run_ts_lsp_cross(CBMArena* arena,
- const char* source, int source_len,
- const char* module_qn,
- bool js_mode, bool jsx_mode, bool dts_mode,
- CBMLSPDef* defs, int def_count,
- const char** import_names, const char** import_qns, int import_count,
- TSTree* cached_tree,
- CBMResolvedCallArray* out);
+void cbm_run_ts_lsp_cross(CBMArena *arena, const char *source, int source_len,
+ const char *module_qn, bool js_mode, bool jsx_mode, bool dts_mode,
+ CBMLSPDef *defs, int def_count, const char **import_names,
+ const char **import_qns, int import_count, 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);
+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);
+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.
-void cbm_ts_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena);
+void cbm_ts_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
// --- Batch cross-file LSP ---
// Per-file input for batch TS LSP processing.
typedef struct {
- const char* source;
+ const char *source;
int source_len;
- const char* module_qn;
+ const char *module_qn;
bool js_mode;
bool jsx_mode;
bool dts_mode;
- TSTree* cached_tree; // from TSTree caching (NULL = parse internally)
- CBMLSPDef* defs; // combined file-local + cross-file defs
+ TSTree *cached_tree; // from TSTree caching (NULL = parse internally)
+ CBMLSPDef *defs; // combined file-local + cross-file defs
int def_count;
- const char** import_names; // parallel arrays, import_count long
- const char** import_qns;
+ const char **import_names; // parallel arrays, import_count long
+ const char **import_qns;
int import_count;
} CBMBatchTSLSPFile;
// Process multiple TS/JS files' cross-file LSP in one CGo call.
// out must point to file_count pre-zeroed CBMResolvedCallArray structs.
// Project-scope declaration merging happens here (per plan §17 finding #4).
-void cbm_batch_ts_lsp_cross(CBMArena* arena,
- CBMBatchTSLSPFile* files, int file_count,
- CBMResolvedCallArray* out);
+void cbm_batch_ts_lsp_cross(CBMArena *arena, CBMBatchTSLSPFile *files, int file_count,
+ CBMResolvedCallArray *out);
#endif // CBM_LSP_TS_LSP_H
diff --git a/tests/test_stack_overflow.c b/tests/test_stack_overflow.c
index 75749c799..b4bc7e79d 100644
--- a/tests/test_stack_overflow.c
+++ b/tests/test_stack_overflow.c
@@ -389,6 +389,117 @@ TEST(cpp_large_templated_header_no_crash_issue424) {
PASS();
}
+/* ═══════════════════════════════════════════════════════════════════
+ * LSP resolve recursion guards (perf-sweep crashes, 2026-06-10)
+ *
+ * Indexing real OSS crashed in the LSP RESOLVE walks (distinct from the
+ * extraction-walk caps above): elasticsearch → SIGSEGV under deep recursive
+ * java_resolve_calls_in_node frames (bind_lambda_args), bitcoin → SIGSEGV
+ * under deep c_resolve_calls_in_node frames (cbm_type_substitute via
+ * c_adl_resolve), microsoft/TypeScript → SIGBUS under an unbounded
+ * lookup_member_type cycle. The walks now carry depth guards; these
+ * reproductions fork a child so a regression cannot kill the test runner
+ * (the TS cyclic-type shape is only reachable with a real cross-file
+ * registry, so that one is verified at the real-repo tier; the synthetic
+ * cyclic fixture here guards the in-file path).
+ * ═══════════════════════════════════════════════════════════════════ */
+
+#if !defined(_WIN32)
+#include <sys/wait.h>
+#include <unistd.h>
+#endif
+
+/* Run cbm_extract_file in a forked child; true if the child died by signal.
+ * Mirrors tests/test_lang_contract.c. On Windows run in-process (a genuine
+ * crash there aborts the runner — hard, visible failure). */
+static bool so_extract_crashes(const char *content, CBMLanguage lang, const char *relpath) {
+#if defined(_WIN32)
+ CBMFileResult *r =
+ cbm_extract_file(content, (int)strlen(content), lang, "so", relpath, 0, NULL, NULL);
+ if (r) {
+ cbm_free_result(r);
+ }
+ return false;
+#else
+ fflush(NULL);
+ pid_t pid = fork();
+ if (pid < 0) {
+ return false;
+ }
+ if (pid == 0) {
+ CBMFileResult *r =
+ cbm_extract_file(content, (int)strlen(content), lang, "so", relpath, 0, NULL, NULL);
+ if (r) {
+ cbm_free_result(r);
+ }
+ _exit(0);
+ }
+ int status = 0;
+ (void)waitpid(pid, &status, 0);
+ return WIFSIGNALED(status);
+#endif
+}
+
+TEST(lsp_java_deep_nesting_no_crash) {
+ /* Deeply nested call expressions — the same shape as the elasticsearch
+ * crash (fast SIGSEGV under recursive java_resolve_calls_in_node frames;
+ * pre-guard prod probe: rc=139 in under a second at this depth). Nested
+ * BLOCKS are deliberately not used: java block processing is minutes-slow
+ * at depth >=3000 (separate adversarial-input pathology, documented in
+ * the perf-sweep report). */
+ const int DEPTH = 30000;
+ size_t sz = (size_t)DEPTH * 3 + 256;
+ char *src = malloc(sz);
+ ASSERT_NOT_NULL(src);
+ char *p = src;
+ p += snprintf(p, sz, "class X { static int f(int a) { return a; } static int g() { return ");
+ for (int i = 0; i < DEPTH; i++) {
+ *p++ = 'f';
+ *p++ = '(';
+ }
+ *p++ = '1';
+ memset(p, ')', DEPTH);
+ p += DEPTH;
+ snprintf(p, sz - (size_t)(p - src), "; } }\n");
+ ASSERT_FALSE(so_extract_crashes(src, CBM_LANG_JAVA, "X.java"));
+ free(src);
+ PASS();
+}
+
+TEST(lsp_cpp_deep_expression_no_crash) {
+ /* See lsp_java_deep_nesting_no_crash on the depth choice. */
+ const int DEPTH = 30000;
+ size_t sz = (size_t)DEPTH * 3 + 256;
+ char *src = malloc(sz);
+ ASSERT_NOT_NULL(src);
+ char *p = src;
+ p += snprintf(p, sz, "int f(int x) { return x; }\nint g() { return ");
+ for (int i = 0; i < DEPTH; i++) {
+ *p++ = 'f';
+ *p++ = '(';
+ }
+ *p++ = '1';
+ memset(p, ')', DEPTH);
+ p += DEPTH;
+ snprintf(p, sz - (size_t)(p - src), "; }\n");
+ ASSERT_FALSE(so_extract_crashes(src, CBM_LANG_CPP, "deep.cpp"));
+ free(src);
+ PASS();
+}
+
+TEST(lsp_ts_cyclic_types_no_crash) {
+ const char *src = "type A = B | null;\n"
+ "type B = A | number;\n"
+ "interface C extends D { c: number; }\n"
+ "interface D extends C { d: number; }\n"
+ "declare const a: A;\n"
+ "declare const c: C;\n"
+ "function useIt(p: C) { return p.missing_member; }\n"
+ "const y = c.also_missing;\n";
+ ASSERT_FALSE(so_extract_crashes(src, CBM_LANG_TYPESCRIPT, "cycle.ts"));
+ PASS();
+}
+
/* ═══════════════════════════════════════════════════════════════════
* Suite registration
* ═══════════════════════════════════════════════════════════════════ */
@@ -398,6 +509,9 @@ SUITE(stack_overflow) {
RUN_TEST(ts_allocator_bound_to_mimalloc_issue424);
RUN_TEST(cpp_large_templated_header_no_crash_issue424);
+ RUN_TEST(lsp_java_deep_nesting_no_crash);
+ RUN_TEST(lsp_cpp_deep_expression_no_crash);
+ RUN_TEST(lsp_ts_cyclic_types_no_crash);
RUN_TEST(js_calls_exceed_512);
RUN_TEST(python_calls_exceed_512);