diff --git a/internal/cbm/lsp/generated/rust_stdlib_data.c b/internal/cbm/lsp/generated/rust_stdlib_data.c index c35309da4e..697011de98 100644 --- a/internal/cbm/lsp/generated/rust_stdlib_data.c +++ b/internal/cbm/lsp/generated/rust_stdlib_data.c @@ -1801,8 +1801,4 @@ void cbm_rust_stdlib_register(CBMTypeRegistry* reg, CBMArena* arena) { /* Common-crate seeds (serde/tokio/anyhow/clap/regex/log/futures/ * parking_lot/once_cell/chrono/uuid/reqwest/rayon). */ cbm_rust_crates_register(reg, arena); - - /* Finalise: build hash buckets so per-file lookups are O(1) - * instead of O(n) over the ~2.5k registered entries. */ - cbm_registry_finalize(reg); } diff --git a/internal/cbm/lsp/rust_lsp.c b/internal/cbm/lsp/rust_lsp.c index be040f7f8f..4d08172202 100644 --- a/internal/cbm/lsp/rust_lsp.c +++ b/internal/cbm/lsp/rust_lsp.c @@ -28,8 +28,10 @@ #include "rust_lsp.h" #include "lsp_work.h" #include "rust_cargo.h" +#include "../../../src/foundation/mem_core.h" #include "../helpers.h" #include +#include #include #include #include @@ -413,21 +415,22 @@ static const char *rust_lookup_prelude(const char *name) { typedef struct { CBMIdxMemo unique; CBMIdxMemo ambiguous; + const char **qns; + int qn_count; } RustTraitNameIndex; -static void rust_trait_name_index_add(RustTraitNameIndex *index, CBMArena *arena, - const CBMTypeRegistry *reg, const char *key, int type_index) { - if (!index || !arena || !reg || !key || !key[0] || type_index < 0 || - type_index >= reg->type_count) { +static void rust_trait_name_index_add(RustTraitNameIndex *index, CBMArena *arena, const char *key, + int32_t qn_id) { + if (!index || !arena || !key || !key[0] || qn_id < 0 || qn_id >= index->qn_count) { return; } int32_t previous = cbm_idxmemo_get(&index->unique, key); if (previous < 0) { - cbm_idxmemo_put_if_absent(&index->unique, arena, key, type_index); + cbm_idxmemo_put_if_absent(&index->unique, arena, key, qn_id); return; } - const char *previous_qn = reg->types[previous].qualified_name; - const char *current_qn = reg->types[type_index].qualified_name; + const char *previous_qn = index->qns[previous]; + const char *current_qn = index->qns[qn_id]; if (previous_qn && current_qn && strcmp(previous_qn, current_qn) != 0) { cbm_idxmemo_put_if_absent(&index->ambiguous, arena, key, 1); } @@ -439,39 +442,56 @@ static void rust_trait_name_index_build(RustTraitNameIndex *index, CBMArena *are if (!arena || !reg) { return; } - for (int i = 0; i < reg->type_count; i++) { - const CBMRegisteredType *type = ®->types[i]; - if (!type->is_interface || !type->qualified_name) { - continue; + int total_traits = 0; + for (const CBMTypeRegistry *link = reg; link; link = link->fallback) { + for (int i = 0; i < link->type_count; i++) { + if (link->types[i].is_interface && link->types[i].qualified_name) { + total_traits++; + } } - const char *suffix = type->qualified_name; - for (;;) { - rust_trait_name_index_add(index, arena, reg, suffix, i); - const char *dot = strchr(suffix, '.'); - if (!dot || !dot[1]) { - break; + } + if (total_traits == 0) { + return; + } + index->qns = (const char **)cbm_arena_alloc(arena, (size_t)total_traits * sizeof(*index->qns)); + if (!index->qns) { + return; + } + for (const CBMTypeRegistry *link = reg; link; link = link->fallback) { + for (int i = 0; i < link->type_count; i++) { + const CBMRegisteredType *type = &link->types[i]; + if (!type->is_interface || !type->qualified_name) { + continue; + } + int32_t qn_id = index->qn_count++; + index->qns[qn_id] = type->qualified_name; + const char *suffix = type->qualified_name; + for (;;) { + rust_trait_name_index_add(index, arena, suffix, qn_id); + const char *dot = strchr(suffix, '.'); + if (!dot || !dot[1]) { + break; + } + suffix = dot + 1; } - suffix = dot + 1; } } } -static const char *rust_trait_name_index_lookup(const RustTraitNameIndex *index, - const CBMTypeRegistry *reg, const char *key) { - if (!index || !reg || !key || cbm_idxmemo_get(&index->ambiguous, key) >= 0) { +static const char *rust_trait_name_index_lookup(const RustTraitNameIndex *index, const char *key) { + if (!index || !key || cbm_idxmemo_get(&index->ambiguous, key) >= 0) { return NULL; } - int32_t type_index = cbm_idxmemo_get(&index->unique, key); - if (type_index < 0 || type_index >= reg->type_count) { + int32_t qn_id = cbm_idxmemo_get(&index->unique, key); + if (qn_id < 0 || qn_id >= index->qn_count) { return NULL; } - return reg->types[type_index].qualified_name; + return index->qns[qn_id]; } -static const char *rust_canonical_impl_trait(CBMArena *arena, const CBMTypeRegistry *reg, - const RustTraitNameIndex *index, const char *raw_trait, - const char *def_module_qn) { - if (!arena || !reg || !index || !raw_trait || !raw_trait[0]) { +static const char *rust_canonical_impl_trait(CBMArena *arena, const RustTraitNameIndex *index, + const char *raw_trait, const char *def_module_qn) { + if (!arena || !index || !raw_trait || !raw_trait[0]) { return NULL; } while (isspace((unsigned char)*raw_trait)) { @@ -496,13 +516,13 @@ static const char *rust_canonical_impl_trait(CBMArena *arena, const CBMTypeRegis if (def_module_qn && relative[0] && strncmp(relative, "crate.", 6) != 0 && strncmp(relative, "super.", 6) != 0) { const char *local = cbm_arena_sprintf(arena, "%s.%s", def_module_qn, relative); - const char *local_qn = rust_trait_name_index_lookup(index, reg, local); + const char *local_qn = rust_trait_name_index_lookup(index, local); if (local_qn) { return local_qn; } } - const char *exact = rust_trait_name_index_lookup(index, reg, normalized); + const char *exact = rust_trait_name_index_lookup(index, normalized); if (exact) { return exact; } @@ -511,7 +531,7 @@ static const char *rust_canonical_impl_trait(CBMArena *arena, const CBMTypeRegis * the canonical QN must actually be registered in this registry. */ if (!strchr(normalized, '.')) { const char *prelude = rust_lookup_prelude(normalized); - const char *prelude_qn = rust_trait_name_index_lookup(index, reg, prelude); + const char *prelude_qn = rust_trait_name_index_lookup(index, prelude); if (prelude_qn) { return prelude_qn; } @@ -527,7 +547,7 @@ static const char *rust_canonical_impl_trait(CBMArena *arena, const CBMTypeRegis suffix += 6; } } - return rust_trait_name_index_lookup(index, reg, suffix); + return rust_trait_name_index_lookup(index, suffix); } static void rust_registered_type_add_embedded(CBMArena *arena, CBMRegisteredType *type, @@ -2525,35 +2545,41 @@ static const CBMRegisteredFunc *rust_registry_lookup_trait_impl_method(const CBM if (!reg || !receiver_qn || !method_name) { return NULL; } + const CBMRegisteredFunc *best = NULL; + const CBMTypeRegistry *best_reg = NULL; int best_index = -1; const char *matched_trait = NULL; - CBMMethodIter it; - cbm_registry_methods(reg, receiver_qn, method_name, &it); - for (int index; (index = cbm_method_iter_next(&it)) >= 0;) { - const CBMRegisteredFunc *candidate = ®->funcs[index]; - if ((candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) == 0 || !candidate->impl_trait_qn) { - continue; - } - if (trait_qn && strcmp(candidate->impl_trait_qn, trait_qn) != 0) { - continue; - } - if (!trait_qn && matched_trait && strcmp(matched_trait, candidate->impl_trait_qn) != 0) { - if (out_ambiguous) { - *out_ambiguous = true; + /* Walk each link directly rather than cbm_registry_methods_chain: Rust + * inherent and trait-impl methods intentionally share a source-level QN, + * so QN-based shadowing would hide a distinct trait impl in fallback. */ + for (const CBMTypeRegistry *link = reg; link; link = link->fallback) { + CBMMethodIter it; + cbm_registry_methods(link, receiver_qn, method_name, &it); + for (int index; (index = cbm_method_iter_next(&it)) >= 0;) { + const CBMRegisteredFunc *candidate = &link->funcs[index]; + if ((candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) == 0 || + !candidate->impl_trait_qn) { + continue; + } + if (trait_qn && strcmp(candidate->impl_trait_qn, trait_qn) != 0) { + continue; + } + if (!trait_qn && matched_trait && + strcmp(matched_trait, candidate->impl_trait_qn) != 0) { + if (out_ambiguous) { + *out_ambiguous = true; + } + return NULL; + } + matched_trait = candidate->impl_trait_qn; + if (!best || (link == best_reg && index < best_index)) { + best = candidate; + best_reg = link; + best_index = index; } - return NULL; - } - matched_trait = candidate->impl_trait_qn; - if (best_index < 0 || index < best_index) { - best_index = index; } } - if (best_index >= 0) { - return ®->funcs[best_index]; - } - return reg->fallback ? rust_registry_lookup_trait_impl_method( - reg->fallback, receiver_qn, trait_qn, method_name, out_ambiguous) - : NULL; + return best; } static const CBMRegisteredFunc *rust_lookup_method_depth(RustLSPContext *ctx, const char *type_qn, @@ -2623,35 +2649,37 @@ static const CBMRegisteredFunc *rust_lookup_method_in_trait(RustLSPContext *ctx, bool allow_abstract) { if (!ctx || !trait_qn || !method_name) return NULL; - const CBMTypeRegistry *reg = ctx->registry; - int best_default = -1; - int best_any = -1; - CBMMethodIter it; - cbm_registry_methods(reg, trait_qn, method_name, &it); - for (int index; (index = cbm_method_iter_next(&it)) >= 0;) { - const CBMRegisteredFunc *candidate = ®->funcs[index]; - if (candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) { - continue; - } - if (best_any < 0 || index < best_any) { - best_any = index; + const CBMRegisteredFunc *best_default = NULL; + const CBMTypeRegistry *best_default_reg = NULL; + int best_default_idx = -1; + const CBMRegisteredFunc *best_any = NULL; + const CBMTypeRegistry *best_any_reg = NULL; + int best_any_idx = -1; + for (const CBMTypeRegistry *link = ctx->registry; link; link = link->fallback) { + CBMMethodIter it; + cbm_registry_methods(link, trait_qn, method_name, &it); + for (int index; (index = cbm_method_iter_next(&it)) >= 0;) { + const CBMRegisteredFunc *candidate = &link->funcs[index]; + if (candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) { + continue; + } + if (!best_any || (link == best_any_reg && index < best_any_idx)) { + best_any = candidate; + best_any_reg = link; + best_any_idx = index; + } + if ((candidate->flags & CBM_FUNC_FLAG_RUST_ABSTRACT) == 0 && + (!best_default || (link == best_default_reg && index < best_default_idx))) { + best_default = candidate; + best_default_reg = link; + best_default_idx = index; + } } - if ((candidate->flags & CBM_FUNC_FLAG_RUST_ABSTRACT) == 0 && - (best_default < 0 || index < best_default)) { - best_default = index; + if (best_default) { + return best_default; } } - int selected = best_default >= 0 ? best_default : (allow_abstract ? best_any : -1); - if (selected >= 0) { - return ®->funcs[selected]; - } - if (reg->fallback) { - RustLSPContext fallback_ctx = *ctx; - fallback_ctx.registry = reg->fallback; - fallback_ctx.use_rows = (CBMNameRows){0}; /* the copy must not grow ctx's chains */ - return rust_lookup_method_in_trait(&fallback_ctx, trait_qn, method_name, allow_abstract); - } - return NULL; + return allow_abstract ? best_any : NULL; } /* Resolve an ordinary method call with Rust precedence: inherent first, @@ -2804,9 +2832,9 @@ static const CBMRegisteredFunc *rust_find_sole_trait_impl(RustLSPContext *ctx, c const char *tdot = strrchr(trait_qn, '.'); const char *tbare = tdot ? tdot + 1 : trait_qn; CBMTypeEmbedIter eit; - cbm_registry_types_by_embedded_bare(reg, tbare, &eit); + cbm_registry_types_by_embedded_bare_chain(reg, tbare, &eit); for (int ti; n < 2 && (ti = cbm_type_embed_iter_next(&eit)) >= 0;) { - const CBMRegisteredType *t = ®->types[ti]; + const CBMRegisteredType *t = &eit.reg->types[ti]; if (!t->embedded_types || !t->qualified_name) continue; bool impls = false; @@ -4066,15 +4094,16 @@ static void rust_inject_syn_call(RustLSPContext *ctx, const char *callee_qn) { const char *short_name = dot ? dot + 1 : callee_qn; if (!short_name || !short_name[0]) return; + CBMArena *call_arena = ctx->syn_calls_arena ? ctx->syn_calls_arena : ctx->arena; CBMCall call = {0}; - call.callee_name = cbm_arena_strdup(ctx->arena, short_name); - call.enclosing_func_qn = ctx->enclosing_func_qn; + call.callee_name = cbm_arena_strdup(call_arena, short_name); + call.enclosing_func_qn = cbm_arena_strdup(call_arena, ctx->enclosing_func_qn); if (ctx->emit_site_end_byte > ctx->emit_site_start_byte) { call.site_start_byte = ctx->emit_site_start_byte; call.site_end_byte = ctx->emit_site_end_byte; call.requires_lsp_resolution = true; } - cbm_calls_push(ctx->syn_calls, ctx->arena, call); + cbm_calls_push(ctx->syn_calls, call_arena, call); } /* The generic call extractor intentionally filters Rust built-in macro names @@ -4210,9 +4239,9 @@ static const char *rust_resolve_callable_value(RustLSPContext *ctx, TSNode value const CBMRegisteredFunc *unique = NULL; int matches = 0; CBMFreeFuncIter iter; - cbm_registry_free_funcs_by_short_name(ctx->registry, tail, &iter); + cbm_registry_free_funcs_by_short_name_chain(ctx->registry, tail, &iter); for (int index; matches < 2 && (index = cbm_free_func_iter_next(&iter)) >= 0;) { - const CBMRegisteredFunc *candidate = &ctx->registry->funcs[index]; + const CBMRegisteredFunc *candidate = &iter.reg->funcs[index]; if (!candidate->receiver_type && candidate->qualified_name && rust_qn_has_suffix(candidate->qualified_name, resolved)) { unique = candidate; @@ -4584,9 +4613,9 @@ static void rust_resolve_call_expression_inner(RustLSPContext *ctx, TSNode node) /* Iterate only free funcs whose short_name == tail via the index; * the receiver/short_name/needle re-checks below are unchanged. */ CBMFreeFuncIter ffit; - cbm_registry_free_funcs_by_short_name(ctx->registry, tail, &ffit); + cbm_registry_free_funcs_by_short_name_chain(ctx->registry, tail, &ffit); for (int i; mem_matches < 2 && (i = cbm_free_func_iter_next(&ffit)) >= 0;) { - const CBMRegisteredFunc *f = &ctx->registry->funcs[i]; + const CBMRegisteredFunc *f = &ffit.reg->funcs[i]; if (!f->short_name || !f->qualified_name) continue; if (f->receiver_type) @@ -4626,9 +4655,9 @@ static void rust_resolve_call_expression_inner(RustLSPContext *ctx, TSNode node) /* Iterate only free funcs whose short_name == tail via the index; the * receiver/short_name/crate-prefix re-checks below are unchanged. */ CBMFreeFuncIter ffit; - cbm_registry_free_funcs_by_short_name(ctx->registry, tail, &ffit); + cbm_registry_free_funcs_by_short_name_chain(ctx->registry, tail, &ffit); for (int i; matches < 2 && (i = cbm_free_func_iter_next(&ffit)) >= 0;) { - const CBMRegisteredFunc *f = &ctx->registry->funcs[i]; + const CBMRegisteredFunc *f = &ffit.reg->funcs[i]; if (!f->short_name || !f->qualified_name) continue; if (f->receiver_type) @@ -5600,13 +5629,239 @@ static const char *rust_method_key(RustFirstRows *rows, const char *receiver, co return cbm_arena_sprintf(&rows->arena, "%s\x1f%s", receiver, name); } +/* The Rust stdlib + crate seed (276 types, 1,753 functions) registered ONCE per + * process into a finalized, sealed registry that every per-file and cross-file + * registry chains to as its fallback — the overlay contract of type_registry.h: + * lookups and chain iterators reach it, refinements copy into the head, nothing + * mutates it. Threads racing the first build each build a copy and the first to + * publish wins; the others free theirs — no thread waits. Returns NULL on + * allocation failure so callers fall back to registering into their own arena. */ +typedef struct { + CBMArena arena; + CBMTypeRegistry reg; +} rust_stdlib_holder_t; + +static _Atomic(rust_stdlib_holder_t *) g_rust_stdlib_shared; + +#ifdef CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_rust_stdlib_builds; + +uint64_t cbm_rust_stdlib_test_build_count(void) { + return atomic_load_explicit(&g_rust_stdlib_builds, memory_order_relaxed); +} +#endif + +static const CBMTypeRegistry *rust_stdlib_shared(void) { + rust_stdlib_holder_t *ready = atomic_load_explicit(&g_rust_stdlib_shared, memory_order_acquire); + if (ready) + return &ready->reg; + rust_stdlib_holder_t *built = cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*built)); + if (!built) + return NULL; + cbm_arena_init(&built->arena); + if (built->arena.nblocks == 0) { + cbm_free(CBM_MEM_CLASS_OTHER, built); + return NULL; + } + cbm_registry_init(&built->reg, &built->arena); +#ifdef CBM_ENABLE_TEST_SEAMS + atomic_fetch_add_explicit(&g_rust_stdlib_builds, 1, memory_order_relaxed); +#endif + cbm_rust_stdlib_register(&built->reg, &built->arena); + cbm_registry_finalize(&built->reg); + built->reg.read_only = true; + rust_stdlib_holder_t *expected = NULL; + if (atomic_compare_exchange_strong_explicit(&g_rust_stdlib_shared, &expected, built, + memory_order_acq_rel, memory_order_acquire)) { + return &built->reg; + } + cbm_arena_destroy(&built->arena); + cbm_free(CBM_MEM_CLASS_OTHER, built); + return &expected->reg; +} + +static void rust_registry_with_stdlib(CBMTypeRegistry *reg, CBMArena *arena) { + const CBMTypeRegistry *shared = rust_stdlib_shared(); + if (shared) { + reg->fallback = shared; + } else { +#ifdef CBM_ENABLE_TEST_SEAMS + atomic_fetch_add_explicit(&g_rust_stdlib_builds, 1, memory_order_relaxed); +#endif + cbm_rust_stdlib_register(reg, arena); + } +} + +/* Return a writable CBMRegisteredType for `type_qn` in `reg` (never mutating + * `reg->fallback`). If `type_qn` is already in `reg`, return it; if it exists in + * `reg->fallback`, copy-on-write into `reg` (preserving stdlib metadata such as + * `embedded_types`); otherwise auto-register a new stub type. Updates `type_idx`. + * + * `cbm_registry_type_for_update` is not reused here because: (1) `reg` is not + * yet finalized during construction, so `lookup_type_self` would linearly scan + * `reg->types` and leave `type_idx` stale; (2) it returns NULL on miss instead + * of auto-stubbing external types; and (3) Rust only appends `embedded_types` + * via a fresh arena array and never mutates `field_types`. */ +static CBMRegisteredType *rust_ensure_mutable_type(CBMArena *arena, CBMArena *idx_arena, + CBMTypeRegistry *reg, CBMIdxMemo *type_idx, + const char *type_qn, bool dup_strings) { + if (!arena || !idx_arena || !reg || !type_idx || !type_qn) { + return NULL; + } + int32_t type_index = cbm_idxmemo_get(type_idx, type_qn); + if (type_index >= 0 && type_index < reg->type_count) { + return ®->types[type_index]; + } + const CBMRegisteredType *base = + reg->fallback ? cbm_registry_lookup_type(reg->fallback, type_qn) : NULL; + CBMRegisteredType copy; + if (base) { + copy = *base; + } else { + memset(©, 0, sizeof(copy)); + copy.qualified_name = dup_strings ? cbm_arena_strdup(arena, type_qn) : type_qn; + if (!copy.qualified_name) { + return NULL; + } + const char *dot = strrchr(type_qn, '.'); + copy.short_name = + dot ? (dup_strings ? cbm_arena_strdup(arena, dot + 1) : dot + 1) : copy.qualified_name; + } + int before = reg->type_count; + cbm_registry_add_type(reg, copy); + if (reg->type_count != before + 1) { + return NULL; + } + cbm_idxmemo_put_if_absent(type_idx, idx_arena, reg->types[before].qualified_name, before); + return ®->types[before]; +} + +/* True when `ptr` points inside one of `arena`'s live blocks. Keeps static + * literal `strategy`/`reason` pointers zero-copy when copying calls out of a + * scratch arena while still duplicating scratch-owned strings (e.g. + * `lsp_callable_alias` / `lsp_callable_value_reference` reasons). */ +static bool rust_arena_owns_ptr(const CBMArena *arena, const void *ptr) { + if (!arena || !ptr) { + return false; + } + uintptr_t p = (uintptr_t)ptr; + for (int i = 0; i < arena->nblocks; i++) { + uintptr_t lo = (uintptr_t)arena->blocks[i]; + uintptr_t hi = lo + arena->block_sizes[i]; + if (p >= lo && p < hi) { + return true; + } + } + return false; +} + +static const char *rust_copy_if_owned(CBMArena *dst_arena, const CBMArena *src_arena, + const char *s) { + if (!s) { + return NULL; + } + if (!src_arena || rust_arena_owns_ptr(src_arena, s)) { + return cbm_arena_strdup(dst_arena, s); + } + return s; +} + +/* Copy `caller_qn` once per enclosing function (4-entry stack MRU handles + * consecutive calls in a function plus nested functions/closures). */ +static const char *rust_copy_caller_qn(CBMArena *dst_arena, const char *caller_qn, + const char **cache_src, const char **cache_dst, + int *cache_n) { + if (!caller_qn) { + return NULL; + } + for (int i = 0; i < *cache_n; i++) { + if (cache_src[i] == caller_qn || strcmp(cache_src[i], caller_qn) == 0) { + return cache_dst[i]; + } + } + const char *dup = cbm_arena_strdup(dst_arena, caller_qn); + if (!dup) { + return NULL; + } + int slot = *cache_n < 4 ? (*cache_n)++ : 3; + for (int i = slot; i > 0; i--) { + cache_src[i] = cache_src[i - 1]; + cache_dst[i] = cache_dst[i - 1]; + } + cache_src[0] = caller_qn; + cache_dst[0] = dup; + return dup; +} + +/* Copy resolved calls from a per-file scratch arena (`src_arena`) into the + * caller's longer-lived arena. Static literal `strategy`/`reason` strings stay + * zero-copy, `caller_qn` is copied once per function, and `dst->items` is + * exact-sized when `dst` starts empty. */ +static void rust_copy_resolved_calls(CBMArena *arena, const CBMArena *src_arena, + const CBMResolvedCallArray *src, CBMResolvedCallArray *dst) { + if (!arena || !src || !dst || src->count <= 0) { + return; + } + const char *caller_src[4] = {0}; + const char *caller_dst[4] = {0}; + int caller_n = 0; + if (!dst->items && dst->count == 0) { + CBMResolvedCall *items = + (CBMResolvedCall *)cbm_arena_alloc(arena, (size_t)src->count * sizeof(CBMResolvedCall)); + if (!items) { + return; + } + dst->items = items; + dst->cap = src->count; + dst->count = src->count; + for (int j = 0; j < src->count; j++) { + const CBMResolvedCall *s = &src->items[j]; + CBMResolvedCall *d = &dst->items[j]; + memset(d, 0, sizeof(*d)); + d->caller_qn = + rust_copy_caller_qn(arena, s->caller_qn, caller_src, caller_dst, &caller_n); + d->callee_qn = s->callee_qn ? cbm_arena_strdup(arena, s->callee_qn) : NULL; + d->strategy = rust_copy_if_owned(arena, src_arena, s->strategy); + d->confidence = s->confidence; + d->reason = rust_copy_if_owned(arena, src_arena, s->reason); + d->kind = s->kind; + d->site_start_byte = s->site_start_byte; + d->site_end_byte = s->site_end_byte; + d->source_origin = s->source_origin; + d->callee_sig = s->callee_sig ? cbm_arena_strdup(arena, s->callee_sig) : NULL; + } + return; + } + for (int j = 0; j < src->count; j++) { + const CBMResolvedCall *s = &src->items[j]; + CBMResolvedCall copy = { + .caller_qn = + rust_copy_caller_qn(arena, s->caller_qn, caller_src, caller_dst, &caller_n), + .callee_qn = s->callee_qn ? cbm_arena_strdup(arena, s->callee_qn) : NULL, + .strategy = rust_copy_if_owned(arena, src_arena, s->strategy), + .confidence = s->confidence, + .reason = rust_copy_if_owned(arena, src_arena, s->reason), + .kind = s->kind, + .site_start_byte = s->site_start_byte, + .site_end_byte = s->site_end_byte, + .source_origin = s->source_origin, + .callee_sig = s->callee_sig ? cbm_arena_strdup(arena, s->callee_sig) : NULL, + }; + cbm_resolvedcall_push(dst, arena, copy); + } +} + /* Build the registry from the per-file `result->defs`, `result->impl_traits`, - * and a Rust prelude seed. */ -void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFileResult *result, - const char *module_qn, TSNode root, const char *source) { + * and the shared sealed Rust prelude seed. Temporary build tables (`type_idx`, + * `trait_names`, tail memo, normalized trait keys) live in `build_scratch`. */ +static void rust_build_local_registry_with_scratch(CBMArena *arena, CBMArena *build_scratch, + CBMTypeRegistry *reg, CBMFileResult *result, + const char *module_qn, TSNode root, + const char *source) { cbm_registry_init(reg, arena); - cbm_rust_stdlib_register(reg, arena); + rust_registry_with_stdlib(reg, arena); + reg->tail_arena = build_scratch; /* Phase A1: register all type containers first. Trait provenance on a * later method can then be canonicalized without declaration-order or @@ -5614,7 +5869,7 @@ void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFil CBMIdxMemo type_idx = {0}; for (int i = 0; i < reg->type_count; i++) { if (reg->types[i].qualified_name) { - cbm_idxmemo_put_if_absent(&type_idx, arena, reg->types[i].qualified_name, i); + cbm_idxmemo_put_if_absent(&type_idx, build_scratch, reg->types[i].qualified_name, i); } } for (int i = 0; i < result->defs.count; i++) { @@ -5628,10 +5883,10 @@ void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFil rt.short_name = d->name; rt.is_interface = (strcmp(d->label, "Interface") == 0 || strcmp(d->label, "Trait") == 0); cbm_registry_add_type(reg, rt); - cbm_idxmemo_put_if_absent(&type_idx, arena, rt.qualified_name, reg->type_count - 1); + cbm_idxmemo_put_if_absent(&type_idx, build_scratch, rt.qualified_name, reg->type_count - 1); } RustTraitNameIndex trait_names; - rust_trait_name_index_build(&trait_names, arena, reg); + rust_trait_name_index_build(&trait_names, build_scratch, reg); /* Phase A2: register every Function/Method definition. */ for (int i = 0; i < result->defs.count; i++) { @@ -5650,8 +5905,8 @@ void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFil } if (d->impl_trait) { rf.flags |= CBM_FUNC_FLAG_RUST_TRAIT_IMPL; - rf.impl_trait_qn = - rust_canonical_impl_trait(arena, reg, &trait_names, d->impl_trait, module_qn); + rf.impl_trait_qn = rust_canonical_impl_trait(build_scratch, &trait_names, + d->impl_trait, module_qn); } /* Build FUNC sig from return_types / param_types. */ @@ -5700,14 +5955,16 @@ void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFil if (strcmp(d->label, "Method") == 0 && d->parent_class) { rf.receiver_type = d->parent_class; - if (cbm_idxmemo_get(&type_idx, rf.receiver_type) < 0) { + if (cbm_idxmemo_get(&type_idx, rf.receiver_type) < 0 && + (!reg->fallback || + !cbm_registry_lookup_type(reg->fallback, rf.receiver_type))) { CBMRegisteredType auto_t; memset(&auto_t, 0, sizeof(auto_t)); auto_t.qualified_name = rf.receiver_type; const char *dot = strrchr(rf.receiver_type, '.'); auto_t.short_name = dot ? cbm_arena_strdup(arena, dot + 1) : rf.receiver_type; cbm_registry_add_type(reg, auto_t); - cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, + cbm_idxmemo_put_if_absent(&type_idx, build_scratch, auto_t.qualified_name, reg->type_count - 1); } } @@ -6187,28 +6444,34 @@ void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFil ? it->struct_qn : cbm_arena_sprintf(arena, "%s.%s", module_qn, it->struct_name); const char *trait_qn = - rust_canonical_impl_trait(arena, reg, &trait_names, it->trait_name, module_qn); + rust_canonical_impl_trait(build_scratch, &trait_names, it->trait_name, module_qn); if (!trait_qn) { continue; } - - CBMRegisteredType *rt = NULL; - int32_t type_index = cbm_idxmemo_get(&type_idx, recv_qn); - if (type_index >= 0) { - rt = ®->types[type_index]; - } - if (!rt) { - CBMRegisteredType auto_t; - memset(&auto_t, 0, sizeof(auto_t)); - auto_t.qualified_name = recv_qn; - const char *dot = strrchr(recv_qn, '.'); - auto_t.short_name = dot ? dot + 1 : recv_qn; - cbm_registry_add_type(reg, auto_t); - rt = ®->types[reg->type_count - 1]; - cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, reg->type_count - 1); + CBMRegisteredType *rt = + rust_ensure_mutable_type(arena, build_scratch, reg, &type_idx, recv_qn, false); + if (rt) { + rust_registered_type_add_embedded(arena, rt, trait_qn); } - rust_registered_type_add_embedded(arena, rt, trait_qn); } + + reg->tail_arena = NULL; + memset(®->func_tail, 0, sizeof(reg->func_tail)); + memset(®->type_tail, 0, sizeof(reg->type_tail)); +} + +void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFileResult *result, + const char *module_qn, TSNode root, const char *source) { + if (!reg) { + return; + } + CBMArena build_scratch; + cbm_arena_init_lazy(&build_scratch, RUST_FIRST_ROWS_BLOCK); + CBMTypeRegistry local_reg; + rust_build_local_registry_with_scratch(arena, &build_scratch, &local_reg, result, module_qn, + root, source); + cbm_arena_destroy(&build_scratch); + *reg = local_reg; } void cbm_run_rust_lsp_with_manifest(CBMArena *arena, CBMFileResult *result, const char *source, @@ -6218,18 +6481,27 @@ void cbm_run_rust_lsp_with_manifest(CBMArena *arena, CBMFileResult *result, cons return; const char *module_qn = result->module_qn ? result->module_qn : "rust"; + /* Run local registry construction, hash indexing, and the AST walk in a + * per-call scratch arena so only emitted resolved calls and synthetic + * calls are retained in the caller's longer-lived result arena. */ + CBMArena work_arena; + cbm_arena_init(&work_arena); + CBMTypeRegistry reg; - cbm_rust_build_local_registry(arena, ®, result, module_qn, root, source); - /* Finalize after all per-file adds so lookups during the walk - * use the hash buckets. */ + cbm_rust_build_local_registry(&work_arena, ®, result, module_qn, root, source); cbm_registry_finalize(®); + reg.read_only = true; + + CBMResolvedCallArray local_resolved; + memset(&local_resolved, 0, sizeof(local_resolved)); RustLSPContext ctx; - rust_lsp_init(&ctx, arena, source, source_len, ®, module_qn, &result->resolved_calls); + rust_lsp_init(&ctx, &work_arena, source, source_len, ®, module_qn, &local_resolved); ctx.cargo_manifest = manifest; /* Let the resolver inject synthetic syntactic calls for operator/macro * desugaring so those recovered calls reach the CALLS-edge pipeline. */ ctx.syn_calls = &result->calls; + ctx.syn_calls_arena = arena; rust_collect_uses(&ctx, root); /* Bridge any extracted CBMImports the unified extractor saw. */ @@ -6241,6 +6513,8 @@ void cbm_run_rust_lsp_with_manifest(CBMArena *arena, CBMFileResult *result, cons } rust_lsp_process_file(&ctx, root); + rust_copy_resolved_calls(arena, &work_arena, &local_resolved, &result->resolved_calls); + cbm_arena_destroy(&work_arena); } void cbm_run_rust_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len, @@ -6260,11 +6534,16 @@ extern const TSLanguage *tree_sitter_rust(void); * `module_qn` is ONLY the fallback used to qualify a def's return type when that def * carries no def_module_qn; pass NULL for the shared build (all_defs always carry * def_module_qn — verified: 0 NULL across the C + Rust kernel corpora). */ -static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, - CBMRustLSPDef *defs, int def_count, - const char *module_qn) { +static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, CBMRustLSPDef *defs, + int def_count, const char *module_qn) { cbm_registry_init(reg, arena); - cbm_rust_stdlib_register(reg, arena); + rust_registry_with_stdlib(reg, arena); + + /* Temporary build tables (`type_idx`, `trait_names`, normalized trait keys, + * split return-type scratch) live in a lazy scratch arena destroyed before + * finalize so the shared cross-file arena retains only registry payload. */ + CBMArena build_scratch; + cbm_arena_init_lazy(&build_scratch, RUST_FIRST_ROWS_BLOCK); /* qn → (type index + 1), FIRST occurrence wins (mirrors the linear scans * this map replaces). Both in-loop registry probes below — the receiver @@ -6280,7 +6559,7 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, for (int ti = 0; ti < reg->type_count; ti++) { const char *qn = reg->types[ti].qualified_name; if (qn) { - cbm_idxmemo_put_if_absent(&type_idx, arena, qn, ti); + cbm_idxmemo_put_if_absent(&type_idx, &build_scratch, qn, ti); } } @@ -6300,11 +6579,12 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, rt.is_interface = d->is_interface || strcmp(d->label, "Trait") == 0 || strcmp(d->label, "Interface") == 0; cbm_registry_add_type(reg, rt); - cbm_idxmemo_put_if_absent(&type_idx, arena, rt.qualified_name, reg->type_count - 1); + cbm_idxmemo_put_if_absent(&type_idx, &build_scratch, rt.qualified_name, + reg->type_count - 1); } RustTraitNameIndex trait_names; - rust_trait_name_index_build(&trait_names, arena, reg); + rust_trait_name_index_build(&trait_names, &build_scratch, reg); /* Materialize independent impl relations first, including empty impls. */ for (int i = 0; i < def_count; i++) { @@ -6314,22 +6594,15 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, } const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn; const char *trait_qn = - rust_canonical_impl_trait(arena, reg, &trait_names, d->trait_qn, def_mod); + rust_canonical_impl_trait(&build_scratch, &trait_names, d->trait_qn, def_mod); if (!trait_qn) { continue; } - int32_t type_index = cbm_idxmemo_get(&type_idx, d->receiver_type); - if (type_index < 0) { - CBMRegisteredType auto_t; - memset(&auto_t, 0, sizeof(auto_t)); - auto_t.qualified_name = cbm_arena_strdup(arena, d->receiver_type); - const char *dot = strrchr(d->receiver_type, '.'); - auto_t.short_name = dot ? cbm_arena_strdup(arena, dot + 1) : auto_t.qualified_name; - cbm_registry_add_type(reg, auto_t); - type_index = reg->type_count - 1; - cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, type_index); + CBMRegisteredType *rt = + rust_ensure_mutable_type(arena, &build_scratch, reg, &type_idx, d->receiver_type, true); + if (rt) { + rust_registered_type_add_embedded(arena, rt, trait_qn); } - rust_registered_type_add_embedded(arena, ®->types[type_index], trait_qn); } for (int i = 0; i < def_count; i++) { @@ -6350,7 +6623,7 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, if (d->trait_qn && d->trait_qn[0]) { rf.flags |= CBM_FUNC_FLAG_RUST_TRAIT_IMPL; rf.impl_trait_qn = - rust_canonical_impl_trait(arena, reg, &trait_names, d->trait_qn, def_mod); + rust_canonical_impl_trait(&build_scratch, &trait_names, d->trait_qn, def_mod); } /* Build sig from return_types text. */ @@ -6364,21 +6637,24 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, ret_types = (const CBMType **)cbm_arena_alloc(arena, (count + 1) * sizeof(const CBMType *)); int idx = 0; - char *buf = cbm_arena_strdup(arena, d->return_types); - char *start = buf; - for (char *p = buf;; p++) { - if (*p == '|' || *p == '\0') { - char save = *p; - *p = '\0'; - if (start[0]) { - ret_types[idx++] = rust_parse_return_type_text(arena, start, def_mod); + char *buf = cbm_arena_strdup(&build_scratch, d->return_types); + if (buf && ret_types) { + char *start = buf; + for (char *p = buf;; p++) { + if (*p == '|' || *p == '\0') { + char save = *p; + *p = '\0'; + if (start[0]) { + ret_types[idx++] = + rust_parse_return_type_text(arena, start, def_mod); + } + if (save == '\0') + break; + start = p + 1; } - if (save == '\0') - break; - start = p + 1; } + ret_types[idx] = NULL; } - ret_types[idx] = NULL; } RustSignatureParamParserContext parser_ctx = {.module_qn = def_mod}; const CBMType **param_types = cbm_type_materialize_signature_params( @@ -6388,14 +6664,16 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) { rf.receiver_type = cbm_arena_strdup(arena, d->receiver_type); - if (cbm_idxmemo_get(&type_idx, rf.receiver_type) < 0) { + if (rf.receiver_type && cbm_idxmemo_get(&type_idx, rf.receiver_type) < 0 && + (!reg->fallback || + !cbm_registry_lookup_type(reg->fallback, rf.receiver_type))) { CBMRegisteredType auto_t; memset(&auto_t, 0, sizeof(auto_t)); auto_t.qualified_name = rf.receiver_type; const char *dot = strrchr(d->receiver_type, '.'); auto_t.short_name = dot ? cbm_arena_strdup(arena, dot + 1) : rf.receiver_type; cbm_registry_add_type(reg, auto_t); - cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, + cbm_idxmemo_put_if_absent(&type_idx, &build_scratch, auto_t.qualified_name, reg->type_count - 1); } } @@ -6406,11 +6684,8 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, * backwards-compatible direct CBMRustLSPDef callers. Production * extraction additionally emits an independent relation record. */ if (rf.receiver_type && rf.impl_trait_qn) { - CBMRegisteredType *rt = NULL; - int32_t tix = cbm_idxmemo_get(&type_idx, rf.receiver_type); - if (tix >= 0) { - rt = ®->types[tix]; - } + CBMRegisteredType *rt = rust_ensure_mutable_type(arena, &build_scratch, reg, + &type_idx, rf.receiver_type, true); if (rt) { rust_registered_type_add_embedded(arena, rt, rf.impl_trait_qn); } @@ -6418,8 +6693,9 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena, } } - /* Finalise the cross-file registry now that all defs are added. - * (type_idx is arena-owned — freed with the registry's arena.) */ + cbm_arena_destroy(&build_scratch); + + /* Finalise the cross-file registry now that all defs are added. */ cbm_registry_finalize(reg); } @@ -6458,12 +6734,23 @@ CBMTypeRegistry *cbm_rust_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, CBMTypeRegistry *reg = (CBMTypeRegistry *)cbm_arena_alloc(arena, sizeof(*reg)); if (!reg) return NULL; + CBMArena convert_scratch; + cbm_arena_init_lazy(&convert_scratch, RUST_FIRST_ROWS_BLOCK); + int rust_count = 0; + for (int i = 0; i < def_count; i++) { + if (defs[i].lang == CBM_LANG_RUST) { + rust_count++; + } + } CBMRustLSPDef *rdefs = NULL; int n = 0; - if (def_count > 0) { - rdefs = (CBMRustLSPDef *)cbm_arena_alloc(arena, (size_t)def_count * sizeof(CBMRustLSPDef)); - if (!rdefs) + if (rust_count > 0) { + rdefs = (CBMRustLSPDef *)cbm_arena_alloc(&convert_scratch, + (size_t)rust_count * sizeof(CBMRustLSPDef)); + if (!rdefs) { + cbm_arena_destroy(&convert_scratch); return NULL; + } for (int i = 0; i < def_count; i++) { if (defs[i].lang != CBM_LANG_RUST) { continue; @@ -6487,6 +6774,7 @@ CBMTypeRegistry *cbm_rust_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, } } rust_populate_cross_registry(reg, arena, n > 0 ? rdefs : NULL, n, /*module_qn=*/NULL); + cbm_arena_destroy(&convert_scratch); reg->read_only = true; /* seal: shared Tier-2 registry is read-only during resolve */ return reg; } @@ -6557,6 +6845,7 @@ void cbm_run_rust_lsp_cross_with_manifest(CBMArena *arena, const char *source, i /* Build registry from cross-file defs + stdlib (per-file). */ CBMTypeRegistry reg; rust_populate_cross_registry(®, arena, defs, def_count, module_qn); + reg.read_only = true; rust_resolve_against_registry(arena, source, source_len, module_qn, ®, import_names, import_qns, import_count, root, manifest, out, synthetic_calls); @@ -6601,24 +6890,7 @@ void cbm_batch_rust_lsp_cross(CBMArena *arena, CBMBatchRustLSPFile *files, int f file->defs, file->def_count, file->import_names, file->import_qns, file->import_count, file->cached_tree, &file_out); - if (file_out.count > 0) { - out[f].count = file_out.count; - 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]; - memset(dst, 0, sizeof(*dst)); - 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->confidence = src->confidence; - dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL; - dst->kind = src->kind; - dst->site_start_byte = src->site_start_byte; - dst->site_end_byte = src->site_end_byte; - } - } + rust_copy_resolved_calls(arena, &file_arena, &file_out, &out[f]); cbm_arena_destroy(&file_arena); } diff --git a/internal/cbm/lsp/rust_lsp.h b/internal/cbm/lsp/rust_lsp.h index 7dd80dcedd..2605c59310 100644 --- a/internal/cbm/lsp/rust_lsp.h +++ b/internal/cbm/lsp/rust_lsp.h @@ -184,6 +184,9 @@ typedef struct { * callers provide a separate output array and merge it into the owning * file result with explicit arena-aware copying. */ CBMCallArray *syn_calls; + /* Arena owning `syn_calls` when `ctx->arena` is a shorter-lived scratch + * arena (NULL falls back to `ctx->arena`). */ + CBMArena *syn_calls_arena; /* While >0, rust_emit_resolved_call also injects a matching synthetic * CBMCall into `syn_calls` so the recovered call becomes an edge. Set @@ -380,4 +383,10 @@ typedef struct { void cbm_batch_rust_lsp_cross(CBMArena *arena, CBMBatchRustLSPFile *files, int file_count, CBMResolvedCallArray *out); +#ifdef CBM_ENABLE_TEST_SEAMS +/* Monotonic count of Rust stdlib seed builds in this process (shared-cache + * builds plus any OOM fallback). Tests assert zero delta after first publish. */ +uint64_t cbm_rust_stdlib_test_build_count(void); +#endif + #endif /* CBM_LSP_RUST_LSP_H */ diff --git a/tests/test_rust_lsp.c b/tests/test_rust_lsp.c index e5ab4cef39..e44a643044 100644 --- a/tests/test_rust_lsp.c +++ b/tests/test_rust_lsp.c @@ -18,6 +18,7 @@ * `suite_rust_lsp` at the bottom; test_main.c registers it via RUN_SUITE. */ #include "test_framework.h" +#include "foundation/arena.h" #include "cbm.h" #include "lsp/rust_lsp.h" #include "pipeline/lsp_resolve.h" @@ -6282,6 +6283,455 @@ TEST(rustlsp_partial_registry_hash_lookup_correctness) { cbm_free_result(r); PASS(); } +TEST(rustlsp_stdlib_register_defers_finalize) { + CBMArena arena; + cbm_arena_init(&arena); + CBMTypeRegistry reg; + cbm_registry_init(®, &arena); + + cbm_rust_stdlib_register(®, &arena); + ASSERT_GT(reg.type_count, 0); + ASSERT_GT(reg.func_count, 0); + + /* Stdlib seeding must not prematurely build hash tables into reg->arena; + * callers finalize into their own arena after adding local/project defs. */ + ASSERT_NULL(reg.func_qn_buckets); + ASSERT_NULL(reg.type_qn_buckets); + ASSERT_NULL(reg.method_buckets); + ASSERT_NULL(reg.type_embed_buckets); + ASSERT_NULL(reg.type_short_buckets); + ASSERT_NULL(reg.ffunc_short_buckets); + + cbm_arena_destroy(&arena); + PASS(); +} + +TEST(rustlsp_per_file_work_arena_and_shared_stdlib) { + const char *src = "struct S { v: std::vec::Vec }\n" + "impl S {\n" + " fn make() -> S { S { v: Vec::new() } }\n" + " fn count(&self) -> usize { self.v.len() }\n" + "}\n" + "fn run() {\n" + " let s = S::make();\n" + " let _ = s.count();\n" + "}\n"; + + CBMFileResult *r = extract_rust(src); + ASSERT_NOT_NULL(r); + ASSERT_NOT_NULL(r->cached_tree); + TSNode root = ts_tree_root_node(r->cached_tree); + + /* Measure standalone stdlib registration and hash-table footprint. */ + CBMArena std_arena; + CBMArena std_idx_arena; + cbm_arena_init(&std_arena); + cbm_arena_init(&std_idx_arena); + CBMTypeRegistry std_reg; + cbm_registry_init(&std_reg, &std_arena); + cbm_rust_stdlib_register(&std_reg, &std_arena); + size_t std_bytes = cbm_arena_total(&std_arena); + cbm_registry_finalize_into(&std_reg, &std_idx_arena); + size_t std_idx_bytes = cbm_arena_total(&std_idx_arena); + ASSERT_GT(std_bytes, (size_t)0); + ASSERT_GT(std_idx_bytes, (size_t)0); + + /* Local registry must chain to the process-shared sealed stdlib instead of + * copying stdlib types/funcs or retaining build-time scratch structures. */ + CBMArena build_arena; + cbm_arena_init(&build_arena); + CBMTypeRegistry reg; + cbm_rust_build_local_registry(&build_arena, ®, r, r->module_qn, root, src); + size_t build_bytes = cbm_arena_total(&build_arena); + ASSERT_NOT_NULL(reg.fallback); + ASSERT_TRUE(reg.fallback->read_only); + ASSERT_LT(reg.type_count, std_reg.type_count); + ASSERT_LT(reg.func_count, std_reg.func_count); + ASSERT_LT(build_bytes, std_bytes); + ASSERT_NULL(reg.func_qn_buckets); + ASSERT_NULL(reg.type_qn_buckets); + ASSERT_NULL(reg.tail_arena); + + /* Per-file Rust LSP runs registry build, finalize, and AST walk inside a + * per-call work arena; only emitted calls are copied into run_arena. */ + CBMArena run_arena; + cbm_arena_init(&run_arena); + memset(&r->resolved_calls, 0, sizeof(r->resolved_calls)); + cbm_run_rust_lsp(&run_arena, r, src, (int)strlen(src), root); + size_t run_bytes = cbm_arena_total(&run_arena); + + ASSERT_GTE(require_resolved(r, "run", "S.make"), 0); + ASSERT_GTE(require_resolved(r, "run", "S.count"), 0); + ASSERT_GTE(require_resolved(r, "make", "Vec.new"), 0); + ASSERT_GTE(require_resolved(r, "count", "Vec.len"), 0); + ASSERT_LT(run_bytes, build_bytes); + ASSERT_LT(run_bytes, std_idx_bytes); + + cbm_free_result(r); + cbm_arena_destroy(&run_arena); + cbm_arena_destroy(&build_arena); + cbm_arena_destroy(&std_idx_arena); + cbm_arena_destroy(&std_arena); + PASS(); +} + +TEST(rustlsp_shared_stdlib_cow_isolates_foreign_trait_impls) { + /* Attaching a project trait impl to a stdlib type with existing metadata + * (`std.path.PathBuf` carries `DerefTarget:std.path.Path`) must copy-on-write + * into the head registry, preserve the stdlib DerefTarget, and leave the + * shared sealed fallback completely untouched for subsequent builds. */ + CBMLSPDef defs[] = { + { + .qualified_name = "test.a.CustomExt", + .short_name = "CustomExt", + .label = "Trait", + .def_module_qn = "test.a", + .lang = CBM_LANG_RUST, + .is_interface = true, + }, + { + .qualified_name = "test.a.CustomExt.tag", + .short_name = "tag", + .label = "Method", + .receiver_type = "test.a.CustomExt", + .def_module_qn = "test.a", + .return_types = "usize", + .lang = CBM_LANG_RUST, + .is_abstract = true, + }, + { + .qualified_name = "std.path.PathBuf.tag", + .short_name = "tag", + .label = "Method", + .receiver_type = "std.path.PathBuf", + .def_module_qn = "test.a", + .return_types = "usize", + .trait_qn = "test.a.CustomExt", + .lang = CBM_LANG_RUST, + }, + { + .receiver_type = "std.path.PathBuf", + .def_module_qn = "test.a", + .trait_qn = "test.a.CustomExt", + .lang = CBM_LANG_RUST, + .is_rust_impl_relation = true, + }, + }; + + CBMArena arena_a; + cbm_arena_init(&arena_a); + CBMTypeRegistry *reg_a = + cbm_rust_build_cross_registry(&arena_a, defs, (int)(sizeof(defs) / sizeof(defs[0]))); + ASSERT_NOT_NULL(reg_a); + ASSERT_NOT_NULL(reg_a->fallback); + ASSERT_TRUE(reg_a->fallback->read_only); + + const CBMRegisteredType *pb_head = cbm_registry_lookup_type(reg_a, "std.path.PathBuf"); + const CBMRegisteredType *pb_base = + cbm_registry_lookup_type(reg_a->fallback, "std.path.PathBuf"); + ASSERT_NOT_NULL(pb_head); + ASSERT_NOT_NULL(pb_base); + ASSERT_NEQ(pb_head, pb_base); + + bool head_has_deref = false; + bool head_has_custom = false; + for (int i = 0; pb_head->embedded_types && pb_head->embedded_types[i]; i++) { + if (strcmp(pb_head->embedded_types[i], "DerefTarget:std.path.Path") == 0) { + head_has_deref = true; + } + if (strcmp(pb_head->embedded_types[i], "test.a.CustomExt") == 0) { + head_has_custom = true; + } + } + ASSERT_TRUE(head_has_deref); + ASSERT_TRUE(head_has_custom); + + bool base_has_custom = false; + for (int i = 0; pb_base->embedded_types && pb_base->embedded_types[i]; i++) { + if (strcmp(pb_base->embedded_types[i], "test.a.CustomExt") == 0) { + base_has_custom = true; + } + } + ASSERT_FALSE(base_has_custom); + + /* Both the local trait method and Deref-promoted std.path.Path method resolve. */ + const char *src_a = "fn run(p: std::path::PathBuf) {\n" + " let _ = p.tag();\n" + " let _ = p.file_name();\n" + "}\n"; + CBMResolvedCallArray out_a = {0}; + cbm_run_rust_lsp_cross_with_registry(&arena_a, src_a, (int)strlen(src_a), "test.a", reg_a, NULL, + NULL, 0, NULL, NULL, &out_a, NULL); + bool resolved_tag = false; + bool resolved_file_name = false; + for (int i = 0; i < out_a.count; i++) { + if (out_a.items[i].callee_qn && + strcmp(out_a.items[i].callee_qn, "std.path.PathBuf.tag") == 0) { + resolved_tag = true; + } + if (out_a.items[i].callee_qn && + strcmp(out_a.items[i].callee_qn, "std.path.Path.file_name") == 0) { + resolved_file_name = true; + } + } + ASSERT_TRUE(resolved_tag); + ASSERT_TRUE(resolved_file_name); + + /* A second independent registry must see the unmutated stdlib PathBuf. */ + CBMArena arena_b; + cbm_arena_init(&arena_b); + CBMTypeRegistry *reg_b = cbm_rust_build_cross_registry(&arena_b, NULL, 0); + ASSERT_NOT_NULL(reg_b); + ASSERT_EQ(reg_b->fallback, reg_a->fallback); + const CBMRegisteredType *pb_b = cbm_registry_lookup_type(reg_b, "std.path.PathBuf"); + ASSERT_EQ(pb_b, pb_base); + + cbm_arena_destroy(&arena_b); + cbm_arena_destroy(&arena_a); + PASS(); +} + +TEST(rustlsp_per_file_work_arena_preserves_synthetic_calls) { + /* Macro-hidden calls inject synthetic CBMCalls into result->calls while + * resolved calls are copied into result->resolved_calls. Every string and + * entry in both arrays must live in the caller's arena after work_arena + * is destroyed inside cbm_run_rust_lsp. */ + const char *src = "struct Counter;\n" + "impl Counter {\n" + " fn value(&self) -> usize { 42 }\n" + "}\n" + "fn report(c: &Counter) -> String {\n" + " format!(\"{}\", c.value())\n" + "}\n"; + + CBMFileResult *r = extract_rust(src); + ASSERT_NOT_NULL(r); + ASSERT_NOT_NULL(r->cached_tree); + TSNode root = ts_tree_root_node(r->cached_tree); + + CBMArena run_arena; + cbm_arena_init(&run_arena); + memset(&r->calls, 0, sizeof(r->calls)); + memset(&r->resolved_calls, 0, sizeof(r->resolved_calls)); + + cbm_run_rust_lsp(&run_arena, r, src, (int)strlen(src), root); + + ASSERT_GTE(require_resolved(r, "report", "Counter.value"), 0); + bool found_syn_value = false; + for (int i = 0; i < r->calls.count; i++) { + ASSERT_NOT_NULL(r->calls.items[i].callee_name); + ASSERT_NOT_NULL(r->calls.items[i].enclosing_func_qn); + if (strcmp(r->calls.items[i].callee_name, "value") == 0 && + strstr(r->calls.items[i].enclosing_func_qn, "report") != NULL) { + found_syn_value = true; + } + } + ASSERT_TRUE(found_syn_value); + + /* Touch every copied string field of every resolved call to verify no + * pointers dangle into the destroyed work_arena under ASan. */ + for (int i = 0; i < r->resolved_calls.count; i++) { + const CBMResolvedCall *rc = &r->resolved_calls.items[i]; + ASSERT_NOT_NULL(rc->caller_qn); + ASSERT_NOT_NULL(rc->callee_qn); + ASSERT_NOT_NULL(rc->strategy); + ASSERT_GT(strlen(rc->caller_qn), (size_t)0); + ASSERT_GT(strlen(rc->callee_qn), (size_t)0); + ASSERT_GT(strlen(rc->strategy), (size_t)0); + if (rc->reason) { + ASSERT_GT(strlen(rc->reason), (size_t)0); + } + } + + cbm_free_result(r); + cbm_arena_destroy(&run_arena); + PASS(); +} + +TEST(rustlsp_shared_stdlib_builds_once_across_files) { + /* Contract: once the shared sealed Rust stdlib is published on first use, + * subsequent files trigger zero additional stdlib builds, and each per-file + * registry holds only that file's own types and functions. */ + struct { + const char *src; + int expected_types; + int expected_funcs; + const char *caller; + const char *callee; + } files[5] = { + { + "struct A;\n" + "impl A { fn step(&self) {} }\n" + "fn f0(a: &A) { a.step(); }\n", + 1, + 2, + "f0", + "A.step", + }, + { + "struct B; struct B2;\n" + "impl B { fn make() -> B { B } fn use_b(&self) {} }\n" + "fn f1() { let b = B::make(); b.use_b(); }\n", + 2, + 3, + "f1", + "B.use_b", + }, + { + "trait T { fn ping(&self); }\n" + "struct C;\n" + "impl T for C { fn ping(&self) {} }\n" + "fn f2(c: &C) { c.ping(); }\n", + 2, + 3, + "f2", + "C.ping", + }, + { + "fn helper() -> usize { 1 }\n" + "fn f3() { let _ = helper(); }\n", + 0, + 2, + "f3", + "helper", + }, + { + "struct D { v: std::vec::Vec }\n" + "impl D {\n" + " fn new() -> D { D { v: Vec::new() } }\n" + " fn len(&self) -> usize { self.v.len() }\n" + "}\n" + "fn f4() { let d = D::new(); let _ = d.len(); }\n", + 1, + 3, + "f4", + "D.len", + }, + }; + + const CBMTypeRegistry *first_fallback = NULL; + uint64_t builds_after_first = 0; + + for (int i = 0; i < 5; i++) { + CBMFileResult *r = extract_rust(files[i].src); + ASSERT_NOT_NULL(r); + ASSERT_NOT_NULL(r->cached_tree); + TSNode root = ts_tree_root_node(r->cached_tree); + + CBMArena build_arena; + cbm_arena_init(&build_arena); + CBMTypeRegistry reg; + cbm_rust_build_local_registry(&build_arena, ®, r, r->module_qn, root, files[i].src); + + ASSERT_NOT_NULL(reg.fallback); + ASSERT_TRUE(reg.fallback->read_only); + if (i == 0) { + first_fallback = reg.fallback; + } else { + ASSERT_EQ(reg.fallback, first_fallback); + } + + /* Per-file registry must contain only this file's own definitions. */ + ASSERT_EQ(reg.type_count, files[i].expected_types); + ASSERT_EQ(reg.func_count, files[i].expected_funcs); + ASSERT_EQ(reg.type_count + reg.func_count, + files[i].expected_types + files[i].expected_funcs); + + CBMArena run_arena; + cbm_arena_init(&run_arena); + memset(&r->resolved_calls, 0, sizeof(r->resolved_calls)); + cbm_run_rust_lsp(&run_arena, r, files[i].src, (int)strlen(files[i].src), root); + ASSERT_GTE(require_resolved(r, files[i].caller, files[i].callee), 0); + + if (i == 0) { + builds_after_first = cbm_rust_stdlib_test_build_count(); + ASSERT_GTE(builds_after_first, (uint64_t)1); + } else { + ASSERT_EQ(cbm_rust_stdlib_test_build_count() - builds_after_first, (uint64_t)0); + } + + cbm_free_result(r); + cbm_arena_destroy(&run_arena); + cbm_arena_destroy(&build_arena); + } + PASS(); +} + +TEST(rustlsp_copy_resolved_calls_dedups_caller_and_preserves_arena_reason) { + /* Copying resolved calls out of work_arena must: + * - duplicate caller_qn once per function (shared pointer across calls); + * - keep static literal strategy pointers zero-copy; + * - duplicate scratch-arena-owned reasons (callable alias / value ref) + * so no pointers dangle after work_arena is destroyed. */ + const char *src = "fn h1() {}\n" + "fn h2() {}\n" + "fn apply(_f: fn()) {}\n" + "fn driver() {\n" + " h1();\n" + " h2();\n" + " let alias_fn = h1;\n" + " alias_fn();\n" + " apply(h2);\n" + "}\n"; + + CBMFileResult *r = extract_rust(src); + ASSERT_NOT_NULL(r); + ASSERT_NOT_NULL(r->cached_tree); + TSNode root = ts_tree_root_node(r->cached_tree); + + CBMArena run_arena; + cbm_arena_init(&run_arena); + memset(&r->resolved_calls, 0, sizeof(r->resolved_calls)); + cbm_run_rust_lsp(&run_arena, r, src, (int)strlen(src), root); + + const char *driver_caller_ptr = NULL; + const char *direct_strategy_ptr = NULL; + int driver_calls = 0; + int direct_calls = 0; + bool saw_alias_reason = false; + bool saw_ref_reason = false; + + for (int i = 0; i < r->resolved_calls.count; i++) { + const CBMResolvedCall *rc = &r->resolved_calls.items[i]; + ASSERT_NOT_NULL(rc->caller_qn); + ASSERT_NOT_NULL(rc->callee_qn); + ASSERT_NOT_NULL(rc->strategy); + if (strstr(rc->caller_qn, "driver")) { + driver_calls++; + if (!driver_caller_ptr) { + driver_caller_ptr = rc->caller_qn; + } else { + ASSERT_EQ(rc->caller_qn, driver_caller_ptr); + } + } + if (strcmp(rc->strategy, "lsp_direct") == 0) { + direct_calls++; + if (!direct_strategy_ptr) { + direct_strategy_ptr = rc->strategy; + } else { + ASSERT_EQ(rc->strategy, direct_strategy_ptr); + } + } + if (strcmp(rc->strategy, "lsp_callable_alias") == 0 && rc->reason && + strcmp(rc->reason, "alias_fn") == 0) { + saw_alias_reason = true; + } + if (strcmp(rc->strategy, "lsp_callable_value_reference") == 0 && rc->reason && + strcmp(rc->reason, "h2") == 0) { + saw_ref_reason = true; + } + } + + ASSERT_GTE(driver_calls, 5); + ASSERT_GTE(direct_calls, 3); + ASSERT_TRUE(saw_alias_reason); + ASSERT_TRUE(saw_ref_reason); + + cbm_free_result(r); + cbm_arena_destroy(&run_arena); + PASS(); +} + /* GAT lifetime stripping. */ TEST(rustlsp_partial_gat_lifetime_stripped) { /* Without stripping, the type-text parser produced `Self.Item<'a>` @@ -7369,6 +7819,12 @@ void suite_rust_lsp(void) { /* PARTIAL: registry hash, GAT, HRTB, Cargo.toml, Chalk-lite, HM */ RUN_TEST(rustlsp_partial_registry_hash_lookup_correctness); + RUN_TEST(rustlsp_stdlib_register_defers_finalize); + RUN_TEST(rustlsp_per_file_work_arena_and_shared_stdlib); + RUN_TEST(rustlsp_shared_stdlib_cow_isolates_foreign_trait_impls); + RUN_TEST(rustlsp_per_file_work_arena_preserves_synthetic_calls); + RUN_TEST(rustlsp_shared_stdlib_builds_once_across_files); + RUN_TEST(rustlsp_copy_resolved_calls_dedups_caller_and_preserves_arena_reason); RUN_TEST(rustlsp_partial_gat_lifetime_stripped); RUN_TEST(rustlsp_partial_hrtb_stripped); RUN_TEST(rustlsp_partial_cargo_parses_simple);