From 5830c55c509df33313acd163b4293c56b1e2908c Mon Sep 17 00:00:00 2001 From: Wei-Lun Li Date: Sat, 14 Nov 2026 12:08:43 +0900 Subject: [PATCH 01/25] fix(extract): read a CRLF line splice in C-family strings as LF does (#1546) tree-sitter-c and the grammars built on it (cpp, cuda, objc, glsl, hlsl, ispc, slang) read a backslash line splice inside a string literal as an escape_sequence, `\` plus one character. In a CRLF file that character is the CR, the LF then ends the literal, and the rest of the function, often the rest of the file, falls into one ERROR region. In the issue's file the two functions after the literal are missing and Middle spans to the end of the file. Before parsing those languages, rewrite each `\` CR LF as space `\` LF in extract_parse_bytes, next to the PHP inline-HTML mask (#2000). The rewrite keeps the length and the line break, so offsets and line numbers still refer to the file on disk, and the buffer is copied only when a splice is found. Signed-off-by: Wei-Lun Li --- internal/cbm/cbm.c | 46 +++++++++++++- tests/test_extraction.c | 137 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 3 deletions(-) diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index 18b6c57ea..64df76d5d 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -3319,15 +3319,55 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage return r; } +/* The grammars built on tree-sitter-c: same set as cbm_conditional_block_types + * minus C#, which has no backslash line splices. */ +static bool c_splice_lang(CBMLanguage language) { + return language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA || + language == CBM_LANG_OBJC || language == CBM_LANG_GLSL || language == CBM_LANG_HLSL || + language == CBM_LANG_ISPC || language == CBM_LANG_SLANG; +} + +/* #1546: these grammars read a backslash line splice inside a string literal + * as an escape_sequence, `\` plus one character. With CRLF line endings that + * character is the CR, the LF then ends the literal, and the rest of the + * function, often the rest of the file, becomes one ERROR region. + * Each `\` CR LF becomes space `\` LF: the same length, the line break in the + * same place, so offsets and line numbers still refer to the file on disk and + * the next line is byte-identical. Copied only when a splice is found. */ +static const char *c_mask_crlf_splices(CBMArena *a, const char *source, int source_len) { + char *out = NULL; + for (int i = 0; i + PAIR_LEN < source_len; i++) { + if (source[i] != '\\' || source[i + SKIP_ONE] != '\r' || source[i + PAIR_LEN] != '\n') { + continue; + } + if (!out) { + out = (char *)cbm_arena_alloc(a, (size_t)source_len + SKIP_ONE); + if (!out) { + return source; + } + memcpy(out, source, (size_t)source_len); + out[source_len] = '\0'; + } + out[i] = ' '; + out[i + SKIP_ONE] = '\\'; + i += PAIR_LEN; + } + return out ? out : source; +} + /* The bytes the grammar parses. PHP that leaves PHP mode (`?> markup defs.count; i++) { + if (r->defs.items[i].name && strcmp(r->defs.items[i].name, name) == 0) { + return &r->defs.items[i]; + } + } + return NULL; +} + +/* The reporter's file, byte for byte. */ +TEST(extract_cpp_crlf_string_splice_keeps_later_functions_issue1546) { + CBMFileResult *r = extract("void Head()\r\n" + "{\r\n" + " int h = 0;\r\n" + "}\r\n" + "\r\n" + "void Middle()\r\n" + "{\r\n" + " const wchar_t* s = L\"line 0\\r\\n\\\r\n" + "line 1\\r\\n\";\r\n" + "}\r\n" + "\r\n" + "void TrailerOne()\r\n" + "{\r\n" + " int a = 1;\r\n" + "}\r\n" + "\r\n" + "void TrailerTwo()\r\n" + "{\r\n" + " int b = 2;\r\n" + "}\r\n", + CBM_LANG_CPP, "t", "repro.cpp"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + ASSERT_FALSE(r->parse_incomplete); + const CBMDefinition *middle = splice_def(r, "Middle"); + const CBMDefinition *one = splice_def(r, "TrailerOne"); + const CBMDefinition *two = splice_def(r, "TrailerTwo"); + ASSERT_NOT_NULL(middle); + ASSERT_NOT_NULL(one); + ASSERT_NOT_NULL(two); + ASSERT_EQ((int)middle->start_line, 6); + ASSERT_EQ((int)middle->end_line, 10); + ASSERT_EQ((int)one->start_line, 12); + ASSERT_EQ((int)two->start_line, 17); + cbm_free_result(r); + PASS(); +} + +/* Every grammar built on tree-sitter-c has the same escape rule. */ +TEST(extract_c_family_crlf_string_splice_parses_clean_issue1546) { + static const CBMLanguage langs[] = {CBM_LANG_C, CBM_LANG_CPP, CBM_LANG_CUDA, + CBM_LANG_OBJC, CBM_LANG_GLSL, CBM_LANG_HLSL, + CBM_LANG_ISPC, CBM_LANG_SLANG}; + const char *src = "void Head()\r\n" + "{\r\n" + " int h = 0;\r\n" + "}\r\n" + "\r\n" + "void Middle()\r\n" + "{\r\n" + " const char *s = \"line 0\\\r\n" + "line 1\";\r\n" + "}\r\n" + "\r\n" + "void TrailerOne()\r\n" + "{\r\n" + " int a = 1;\r\n" + "}\r\n"; + for (size_t i = 0; i < sizeof(langs) / sizeof(langs[0]); i++) { + CBMFileResult *r = extract(src, langs[i], "t", "splice.c"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->parse_incomplete); + const CBMDefinition *middle = splice_def(r, "Middle"); + const CBMDefinition *tail = splice_def(r, "TrailerOne"); + ASSERT_NOT_NULL(middle); + ASSERT_NOT_NULL(tail); + ASSERT_EQ((int)middle->end_line, 10); + ASSERT_EQ((int)tail->start_line, 12); + cbm_free_result(r); + } + PASS(); +} + +/* Splices in a macro and a line comment, which the grammar already read with + * CRLF, still do; the preprocessed second pass sees the rewritten bytes too. */ +TEST(extract_c_crlf_splices_in_macro_comment_and_string_issue1546) { + CBMFileResult *r = extract("#define LOG2(a, b) \\\r\n" + " do { log_it(a); \\\r\n" + " log_it(b); } while (0)\r\n" + "\r\n" + "// a comment that ends with a splice \\\r\n" + " and goes on here\r\n" + "\r\n" + "static const char *usage = \"usage: tool\\n\\\r\n" + " -h help\\n\";\r\n" + "\r\n" + "int helper(int x)\r\n" + "{\r\n" + " return x + 1;\r\n" + "}\r\n" + "\r\n" + "int main(void)\r\n" + "{\r\n" + " LOG2(\"a\", \"b\");\r\n" + " return helper(2);\r\n" + "}\r\n", + CBM_LANG_C, "t", "mix.c"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->parse_incomplete); + ASSERT(has_def(r, "Macro", "LOG2")); + const CBMDefinition *usage = splice_def(r, "usage"); + const CBMDefinition *helper = splice_def(r, "helper"); + ASSERT_NOT_NULL(usage); + ASSERT_NOT_NULL(helper); + ASSERT_EQ((int)usage->end_line, 9); + ASSERT_EQ((int)helper->start_line, 11); + ASSERT_EQ((int)helper->end_line, 14); + for (int i = 0; i < r->calls.count; i++) { + const CBMCall *c = &r->calls.items[i]; + if (c->callee_name && strcmp(c->callee_name, "helper") == 0) { + ASSERT_NOT_NULL(c->enclosing_func_qn); + ASSERT_NOT_NULL(strstr(c->enclosing_func_qn, "main")); + } + } + ASSERT(has_call(r, "log_it")); + cbm_free_result(r); + PASS(); +} + /* #1735: the #1071 check's cost. cbm_subtract_macro_invocation_regions asked * "is this region a macro call?" before "is it inside a function?", and the * first question walked the source from byte 0 for every region: regions x @@ -15745,6 +15879,9 @@ SUITE(extraction) { RUN_TEST(extract_cpp_macros_issue375); RUN_TEST(extract_cpp_functionlike_macro_type_arg_no_false_parse_partial_issue1071); RUN_TEST(extract_cpp_real_in_body_error_still_flagged_issue1071); + RUN_TEST(extract_cpp_crlf_string_splice_keeps_later_functions_issue1546); + RUN_TEST(extract_c_family_crlf_string_splice_parses_clean_issue1546); + RUN_TEST(extract_c_crlf_splices_in_macro_comment_and_string_issue1546); RUN_TEST(macro_check_reads_no_source_for_regions_outside_functions_issue1735); RUN_TEST(macro_check_locates_lines_with_one_table_issue1735); RUN_TEST(extract_gdscript_issue186); From 8efb059fe8d40797eb91000439bda05802a99a1b Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Sat, 14 Nov 2026 14:16:50 +0100 Subject: [PATCH 02/25] fix(lsp): read a CRLF line splice in the C/C++ cross-file pass too (#1546) The per-file extract now parses C-family files with each backslash CR LF rewritten as space backslash LF, but the cross-file C/C++ LSP pass parses the file a second time from the original bytes: the parallel driver from its retained copy, the sequential driver from a fresh read. Both end in c_lsp_cross_with_registry_run or c_lsp_cross_run, which parsed those bytes as they came, so after a CRLF string splice the rest of the file was one ERROR region again for that pass, and a call only that pass resolves was lost. Export the mask as cbm_c_mask_crlf_splices (declared in cbm.h next to the PHP inline-HTML mask) and apply it at the top of both cross bodies, before the test-owner check, the way cbm_run_php_lsp_cross_with_bindings does for #2000. The owner digest then sees the same bytes the extract hashed. The copy comes from the call's arena and is made only when a splice is found. A 66-file C++ repo (parallel driver) with the reporter's string splice, followed by a call through a struct declared in another header: LF 208 edges; CRLF 207 before (after_one -> ops.run, lsp_field_access, missing) and 208 after, byte-identical to LF. The 3-file version (sequential driver): 28, 27, 28, also identical to LF. redis 4f20cb48: the LF graph (40,941 nodes, 141,136 edges) and the CRLF graph (40,940 nodes, 141,144 edges) are unchanged. Tests: a pipeline test through both drivers with the shared C/C++ registry (the parallel harness can now opt into it, like the C# one), and a c_lsp test through the per-file, shared-registry and batch entries, each with an LF control. Both fail without the two calls; removing either call alone fails the test that covers its body. Signed-off-by: Martin Vogel --- internal/cbm/cbm.c | 10 +++- internal/cbm/cbm.h | 5 ++ internal/cbm/lsp/c_lsp.c | 7 +++ tests/test_c_lsp.c | 84 +++++++++++++++++++++++++++ tests/test_parallel.c | 120 ++++++++++++++++++++++++++++++++++++++- 5 files changed, 221 insertions(+), 5 deletions(-) diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index 64df76d5d..dd266b7ee 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -3333,8 +3333,12 @@ static bool c_splice_lang(CBMLanguage language) { * function, often the rest of the file, becomes one ERROR region. * Each `\` CR LF becomes space `\` LF: the same length, the line break in the * same place, so offsets and line numbers still refer to the file on disk and - * the next line is byte-identical. Copied only when a splice is found. */ -static const char *c_mask_crlf_splices(CBMArena *a, const char *source, int source_len) { + * the next line is byte-identical. Copied only when a splice is found. The + * cross-file C/C++ LSP pass reads the file again and applies it too. */ +const char *cbm_c_mask_crlf_splices(CBMArena *a, const char *source, int source_len) { + if (!a || !source) { + return source; + } char *out = NULL; for (int i = 0; i + PAIR_LEN < source_len; i++) { if (source[i] != '\\' || source[i + SKIP_ONE] != '\r' || source[i + PAIR_LEN] != '\n') { @@ -3366,7 +3370,7 @@ static const char *extract_parse_bytes(CBMArena *a, CBMLanguage language, const return cbm_php_mask_inline_html(a, source, source_len); } if (c_splice_lang(language)) { - return c_mask_crlf_splices(a, source, source_len); + return cbm_c_mask_crlf_splices(a, source, source_len); } return source; } diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 9c29cbabb..3f88a626c 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -1429,6 +1429,11 @@ void cbm_extract_dbt(CBMExtractCtx *ctx); // parse past `?>` (#2000). Same length and line breaks as the input; returns // `source` itself when nothing needs rewriting. Defined in php_inline_html.c. const char *cbm_php_mask_inline_html(CBMArena *arena, const char *source, int source_len); +// C-family source with each `\` CR LF line splice rewritten as space `\` LF so +// the grammars built on tree-sitter-c read it as they read the LF splice +// (#1546). Same length and line breaks as the input; returns `source` itself +// when there is no such splice. Defined in cbm.c. +const char *cbm_c_mask_crlf_splices(CBMArena *arena, const char *source, int source_len); void cbm_extract_imports(CBMExtractCtx *ctx); void cbm_extract_usages(CBMExtractCtx *ctx); void cbm_extract_semantic(CBMExtractCtx *ctx); diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.c index f0e5861f1..07d335a63 100644 --- a/internal/cbm/lsp/c_lsp.c +++ b/internal/cbm/lsp/c_lsp.c @@ -7228,6 +7228,10 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i const CBMFileResult *test_owners, CBMLSPStatus *status) { *status = CBM_LSP_COMPLETE; + /* The retained or re-read source is the file on disk; read it the way the + * per-file extract did (#1546), so the owner digest, the cached tree and + * node text agree. */ + source = cbm_c_mask_crlf_splices(arena, source, source_len); if ((test_owners && test_owners->has_test_definition_owners && source_origin != CBM_SOURCE_ORIGIN_RAW) || !cbm_test_definition_owners_match(test_owners, source, source_len, cpp_mode, @@ -7319,6 +7323,9 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len, CBMSourceOrigin source_origin, const CBMFileResult *test_owners, CBMLSPStatus *status) { *status = CBM_LSP_COMPLETE; + /* Same bytes as the per-file extract (#1546); see + * c_lsp_cross_with_registry_run. */ + source = cbm_c_mask_crlf_splices(arena, source, source_len); if ((test_owners && test_owners->has_test_definition_owners && source_origin != CBM_SOURCE_ORIGIN_RAW) || !cbm_test_definition_owners_match(test_owners, source, source_len, cpp_mode, diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.c index fc7bf2f1e..16c1b0ca9 100644 --- a/tests/test_c_lsp.c +++ b/tests/test_c_lsp.c @@ -16903,6 +16903,89 @@ TEST(clsp_issue1527_cross_file_memo_failures_propagate) { PASS(); } +/* #1546: the cross entry points get the file as it is on disk and must read a + * `\` CR LF string splice the way the per-file extract does. Read raw, the CR + * ends the escape, the LF ends the literal, and run() falls into the ERROR + * region with its call. LF is the control; per-file, shared-registry and + * batch entry each. */ +TEST(clsp_issue1546_cross_entry_points_read_crlf_string_splice) { + static const char *const srcs[2] = {"struct S { int m() { return 1; } };\n" + "void Middle()\n" + "{\n" + " const wchar_t* s = L\"line 0\\r\\n\\\n" + "line 1\\r\\n\";\n" + "}\n" + "\n" + "void run() { S s; s.m(); }\n", + "struct S { int m() { return 1; } };\r\n" + "void Middle()\r\n" + "{\r\n" + " const wchar_t* s = L\"line 0\\r\\n\\\r\n" + "line 1\\r\\n\";\r\n" + "}\r\n" + "\r\n" + "void run() { S s; s.m(); }\r\n"}; + CBMLSPDef defs[] = { + {.qualified_name = "test.S", .short_name = "S", .label = "Class", .lang = CBM_LANG_CPP}, + {.qualified_name = "test.S.m", + .short_name = "m", + .label = "Method", + .receiver_type = "test.S", + .return_types = "int", + .lang = CBM_LANG_CPP}, + }; + bool resolved[2][3] = {{false}}; + for (int e = 0; e < 2; e++) { + const char *src = srcs[e]; + int len = (int)strlen(src); + for (int mode = 0; mode < 3; mode++) { + CBMArena a; + cbm_arena_init(&a); + CBMTypeRegistry reg; + cbm_registry_init(®, &a); + reg.fallback = cbm_c_build_cross_registry(&a, defs, 2); + CBMResolvedCallArray out = {0}; + CBMBatchCLSPFile file = {.source = src, + .source_len = len, + .module_qn = "test", + .cpp_mode = true, + .defs = defs, + .def_count = 2}; + if (mode == 0) { + (void)cbm_run_c_lsp_cross(&a, src, len, "test", true, defs, 2, NULL, NULL, 0, NULL, + &out); + } else if (mode == 1) { + (void)cbm_run_c_lsp_cross_with_registry(&a, src, len, "test", true, ®, NULL, + NULL, 0, NULL, &out); + } else { + (void)cbm_batch_c_lsp_cross(&a, &file, 1, &out); + } + for (int i = 0; i < out.count; i++) { + const CBMResolvedCall *rc = &out.items[i]; + if (rc->caller_qn && strcmp(rc->caller_qn, "test.run") == 0 && rc->callee_qn && + strcmp(rc->callee_qn, "test.S.m") == 0) { + resolved[e][mode] = true; + } + } + cbm_arena_destroy(&a); + } + } + for (int e = 0; e < 2; e++) { + for (int mode = 0; mode < 3; mode++) { + if (!resolved[e][mode]) { + printf(" CRLF splice diagnostic: %s entry %d did not resolve run -> S.m\n", + e ? "CRLF" : "LF", mode); + } + } + } + for (int e = 0; e < 2; e++) { + for (int mode = 0; mode < 3; mode++) { + ASSERT_TRUE(resolved[e][mode]); + } + } + PASS(); +} + /* A chain's LENGTH is not nesting depth (#1527 follow-up). An operator chain * `a + a + ... + a` and a receiver chain `b.a().a()...` are evaluated link by * link, so neither consumes the evaluator's depth guard: the file keeps its @@ -17083,6 +17166,7 @@ SUITE(c_lsp) { RUN_TEST(clsp_issue1527_preprocessed_depth_failure_is_reported); RUN_TEST(registry_issue1527_index_preserves_registration_order); RUN_TEST(clsp_issue1527_cross_file_memo_failures_propagate); + RUN_TEST(clsp_issue1546_cross_entry_points_read_crlf_string_splice); RUN_TEST(clsp_issue1527_long_binary_chain_is_not_nesting); RUN_TEST(clsp_issue1527_long_receiver_chain_is_not_nesting); RUN_TEST(clsp_c_reassigned_function_pointer_calls_join_exact_occurrences); diff --git a/tests/test_parallel.c b/tests/test_parallel.c index 59c8b9130..829e35777 100644 --- a/tests/test_parallel.c +++ b/tests/test_parallel.c @@ -307,6 +307,8 @@ static bool g_harness_spill = false; static int64_t g_harness_parked = -1; /* Opt-in: hand cbm_parallel_resolve the production Tier-2 C# registry. */ static bool g_harness_cs_registry = false; +/* Opt-in: the same for the Tier-2 C/C++ registry. */ +static bool g_harness_c_registry = false; static cbm_gbuf_t *run_parallel_with_extract_opts_and_mutator( const char *project, const char *repo_path, cbm_file_info_t *files, int file_count, @@ -385,10 +387,14 @@ static cbm_gbuf_t *run_parallel_with_extract_opts_and_mutator( if (g_harness_cs_registry && all_defs) { harness_registries.cs = cbm_cs_build_cross_registry(&cross_arena, all_defs, def_count); } + if (g_harness_c_registry && all_defs) { + harness_registries.c = cbm_c_build_cross_registry(&cross_arena, all_defs, def_count); + } cbm_parallel_resolve(&ctx, files, file_count, result_cache, &shared_ids, worker_count, all_defs, def_count, def_modules, module_def_index, - g_harness_cs_registry ? &harness_registries - : NULL /* tests use per-file path */); + g_harness_cs_registry || g_harness_c_registry + ? &harness_registries + : NULL /* tests use per-file path */); cbm_gbuf_set_next_id(gbuf, atomic_load(&shared_ids)); cbm_pxc_free_module_def_index(module_def_index); @@ -4879,6 +4885,115 @@ TEST(parallel_cross_file_reread_preserves_unretained_edges) { PASS(); } +/* #1546: the per-file extract parses a C-family file with each `\` CR LF line + * splice rewritten as space `\` LF. The cross-file C/C++ LSP pass reads the + * file again (the parallel driver from its retained copy, the sequential one + * from disk) and must read it the same way. o->run() after the string splice + * is a call only that pass resolves: the struct is declared in another file. + * LF is the control; with CRLF the cross pass used to see the rest of main.cpp + * as one ERROR region and lose the edge in both drivers. */ +static const char *const crlf_splice_files[][2] = { + {"other.h", "#ifndef OTHER_H\n" + "#define OTHER_H\n" + "struct ops { int (*run)(int); };\n" + "struct ops *get_ops(void);\n" + "#endif\n"}, + {"other.cpp", "#include \"other.h\"\n" + "static int run_impl(int x) { return x; }\n" + "static struct ops the_ops = { run_impl };\n" + "struct ops *get_ops(void)\n" + "{\n" + " return &the_ops;\n" + "}\n"}, + {"main.cpp", "#include \"other.h\"\n" + "void Middle(void)\n" + "{\n" + " const wchar_t* s = L\"line 0\\r\\n\\\n" + "line 1\\r\\n\";\n" + "}\n" + "\n" + "int after_one(void)\n" + "{\n" + " struct ops *o = get_ops();\n" + " return o->run(3);\n" + "}\n"}, +}; + +static int write_with_line_endings(const char *path, const char *lf_text, bool crlf) { + char *text = malloc(strlen(lf_text) * 2 + 1); + if (!text) { + return -1; + } + size_t n = 0; + for (const char *p = lf_text; *p; p++) { + if (crlf && *p == '\n') { + text[n++] = '\r'; + } + text[n++] = *p; + } + text[n] = '\0'; + int rc = th_write_file(path, text); + free(text); + return rc; +} + +static bool crlf_splice_has_lsp_edge(const cbm_gbuf_t *gbuf) { + const cbm_gbuf_edge_t *edge = + gbuf ? find_call_edge_to_target_fragment(gbuf, "main.after_one", "ops.run") : NULL; + return edge && edge->properties_json && + strstr(edge->properties_json, "\"strategy\":\"lsp") != NULL; +} + +TEST(cross_file_cpp_lsp_after_crlf_string_splice_issue1546) { + enum { CRLF_SPLICE_FILES = 3 }; + bool seq_edge[2] = {false}; + bool par_edge[2] = {false}; + for (int crlf = 0; crlf < 2; crlf++) { + char tmpdir[256]; + snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_crlf_XXXXXX"); + if (!cbm_mkdtemp(tmpdir)) { + FAIL("mkdtemp failed"); + } + char paths[CRLF_SPLICE_FILES][512]; + cbm_file_info_t files[CRLF_SPLICE_FILES] = {0}; + bool written = true; + for (int i = 0; i < CRLF_SPLICE_FILES; i++) { + snprintf(paths[i], sizeof(paths[i]), "%s/%s", tmpdir, crlf_splice_files[i][0]); + written = written && + write_with_line_endings(paths[i], crlf_splice_files[i][1], crlf != 0) == 0; + files[i].path = paths[i]; + files[i].rel_path = (char *)crlf_splice_files[i][0]; + files[i].language = CBM_LANG_CPP; + } + if (!written) { + th_rmtree(tmpdir); + FAIL("failed to write the CRLF splice fixture"); + } + /* Both drivers resolve C/C++ against the shared Tier-2 registry, as + * production does; tests/test_c_lsp.c covers the per-file entry. */ + cbm_gbuf_t *seq = + run_sequential_with_lsp_cross("cbm_crlf", tmpdir, files, CRLF_SPLICE_FILES); + g_harness_c_registry = true; + cbm_gbuf_t *par = run_parallel("cbm_crlf", tmpdir, files, CRLF_SPLICE_FILES, 2); + g_harness_c_registry = false; + seq_edge[crlf] = crlf_splice_has_lsp_edge(seq); + par_edge[crlf] = crlf_splice_has_lsp_edge(par); + if (!seq_edge[crlf] || !par_edge[crlf]) { + printf(" CRLF splice diagnostic (%s): sequential=%s parallel=%s\n", + crlf ? "CRLF" : "LF", seq_edge[crlf] ? "present" : "absent", + par_edge[crlf] ? "present" : "absent"); + } + cbm_gbuf_free(seq); + cbm_gbuf_free(par); + th_rmtree(tmpdir); + } + ASSERT_TRUE(seq_edge[0]); + ASSERT_TRUE(par_edge[0]); + ASSERT_TRUE(seq_edge[1]); + ASSERT_TRUE(par_edge[1]); + PASS(); +} + /* issue #294: gRPC service-name extraction must (a) preserve the canonical * proto service name (FooServiceClient → FooService, not Foo) and (b) only * match real stub/client types — ordinary receiver vars must NOT produce @@ -6138,6 +6253,7 @@ SUITE(parallel) { RUN_TEST(parallel_python_lsp_override_cross_file_emits_lsp_strategy_edges); RUN_TEST(parallel_go_cross_package_field_chain_resolves); RUN_TEST(parallel_cross_file_reread_preserves_unretained_edges); + RUN_TEST(cross_file_cpp_lsp_after_crlf_string_splice_issue1546); RUN_TEST(parallel_java_kotlin_lsp_override_cross_file_emits_lsp_strategy_edges); RUN_TEST(parallel_rust_external_target_contract); RUN_TEST(parallel_java_external_target_contract); From 0fe3601243e2ee7864c9085e55bc3030e28d1d28 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Tue, 17 Nov 2026 22:11:33 +0100 Subject: [PATCH 03/25] C/C++: resolve #include against the indexed repository root The C/C++/CUDA preprocessed pass handed the file's repository-relative path to simplecpp, which looked quoted #include names up relative to the process working directory, so the graph depended on the directory the indexer was started from. Include lookup is now resolved against the indexed repository root instead of the process working directory. Before simplecpp runs, every #include and __has_include of the file, and of each header it reaches, is resolved in the including file's directory within the repository root and stored in simplecpp's FileDataCache under the key its own lookup computes, so simplecpp opens no file itself. Headers are read through cbm_fopen, with the rules discovery applies to what belongs to the tree. Angle-bracket names and computed #include lines resolve to nothing, as before. The pipeline passes its repository root to cbm_extract_file_ex_with_tests; without one, no header resolves. When the run that follows includes stops at #error (or at another directive that makes simplecpp discard the expansion), the file keeps its expansion without includes. The expanded buffer holds only the file's own tokens. A header's macros still shape them, but its body is indexed as its own file, with its own lines: calls, usages and writes inside an included header are no longer attributed to the includer, and the includer's lines keep their numbers. Fixes #2993 Signed-off-by: Martin Vogel --- internal/cbm/cbm.c | 98 ++++++++- internal/cbm/cbm.h | 8 +- internal/cbm/preprocessor.cpp | 350 ++++++++++++++++++++++++++++-- internal/cbm/preprocessor.h | 28 ++- src/pipeline/pass_calls.c | 12 +- src/pipeline/pass_definitions.c | 8 +- src/pipeline/pass_parallel.c | 2 +- src/pipeline/pass_semantic.c | 2 +- src/pipeline/pass_usages.c | 3 +- tests/test_pipeline.c | 297 +++++++++++++++++++++++++ tests/test_pipeline_conventions.c | 4 +- tests/test_test_conventions.c | 2 +- 12 files changed, 757 insertions(+), 57 deletions(-) diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index 18b6c57ea..b70c37bf2 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -28,6 +28,7 @@ #include "cpp_branch_views.h" #include "foundation/compat.h" #include "foundation/compat_fs.h" // cbm_fopen — crash-supervisor per-file marker write +#include "foundation/limits.h" // cbm_max_file_bytes — headers read by the #include lookup #include "foundation/hash_table.h" // CBMHashTable — crash-supervisor quarantine set #include "foundation/str_util.h" // cbm_json_escape — variants file_path #include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState @@ -3779,14 +3780,83 @@ static void cbm_swift_type_imports(CBMFileResult *result, CBMLanguage language) } } -static CBMFileResult *extract_file_ex_body(const char *source, int source_len, CBMLanguage language, - const char *project, const char *rel_path, - int64_t timeout_micros, const char **extra_defines, - const char **include_paths, - const CBMMacroTable *macro_table, - const CBMReturnTypeTable *return_type_table, - CBMArena *scratch, - const cbm_test_declarations_t *test_declarations) { +/* ── #include lookup of the preprocessed pass (#2993) ────────────── + * Quoted #include names of the C-family second pass resolve against the + * indexed repository root: preprocessor.cpp hands over a normalised, + * root-relative name, and the header is read only when it is part of the tree + * the way discovery sees the tree -- every component below the root a + * directory or a regular file, none a symlink or junction (discovery skips + * those), within the per-file size cap. Paths are UTF-8, opened through + * cbm_fopen. Nothing here depends on the process working directory. */ +typedef struct { + const char *root; +} cbm_include_tree_t; + +/* True when every component of `path` after its first `root_len` bytes is a + * directory, the last one a regular file; *size receives that file's size. */ +static bool include_path_in_tree(char *path, size_t root_len, int64_t *size) { + cbm_path_info_t info = {0}; + char *component = path + root_len; + for (;;) { + char *slash = strchr(component, '/'); + if (slash) { + *slash = '\0'; + } + int rc = cbm_path_info_utf8(path, &info); + if (slash) { + *slash = '/'; + } + if (rc != CBM_PATH_INFO_OK || info.is_symlink || + (slash ? !info.is_directory : !info.is_regular)) { + return false; + } + if (!slash) { + *size = info.size; + return true; + } + component = slash + 1; + } +} + +static char *include_tree_read(const void *userdata, const char *rel_path, size_t *out_len) { + const cbm_include_tree_t *tree = (const cbm_include_tree_t *)userdata; + size_t root_len = strlen(tree->root); + bool sep = root_len > 0 && tree->root[root_len - 1] != '/' && tree->root[root_len - 1] != '\\'; + char path[CBM_SZ_4K]; + int written = snprintf(path, sizeof(path), "%s%s%s", tree->root, sep ? "/" : "", rel_path); + if (!rel_path[0] || written < 0 || (size_t)written >= sizeof(path)) { + return NULL; + } + int64_t size = 0; + if (!include_path_in_tree(path, root_len + (sep ? 1 : 0), &size) || size < 0 || + size > (int64_t)cbm_max_file_bytes()) { + return NULL; + } + FILE *f = cbm_fopen(path, "rb"); + if (!f) { + return NULL; + } + char *data = (char *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)size + 1); + size_t got = data && size > 0 ? fread(data, 1, (size_t)size, f) : 0; + (void)fclose(f); + if (data) { + data[got] = '\0'; + *out_len = got; + } + return data; +} + +static void include_tree_release(const void *userdata, char *data) { + (void)userdata; + cbm_free(CBM_MEM_CLASS_EXTRACT, data); +} + +static CBMFileResult *extract_file_ex_body( + const char *source, int source_len, CBMLanguage language, const char *project, + const char *rel_path, int64_t timeout_micros, const char **extra_defines, + const char **include_paths, const CBMMacroTable *macro_table, + const CBMReturnTypeTable *return_type_table, CBMArena *scratch, + const cbm_test_declarations_t *test_declarations, const char *repo_root) { // Allocate result on heap (arena inside for all string data) CBMFileResult *result = cbm_result_alloc(); if (!result) { @@ -4179,8 +4249,11 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C char export_cands[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX]; int export_cand_count = cbm_export_macro_candidates(source, source_len, export_cands, CBM_EXPORT_MACRO_MAX); + cbm_include_tree_t include_tree = {repo_root}; + CBMIncludeReader include_reader = {include_tree_read, include_tree_release, &include_tree}; CBMPreprocessedSource *preprocessed = cbm_preprocess_with_map( - source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C); + source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C, + repo_root && repo_root[0] ? &include_reader : NULL); if (preprocessed && preprocessed->source) { char *expanded = preprocessed->source; int expanded_len = (int)strlen(expanded); @@ -4849,14 +4922,15 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua const CBMReturnTypeTable *return_type_table) { return cbm_extract_file_ex_with_tests(source, source_len, language, project, rel_path, timeout_micros, extra_defines, include_paths, macro_table, - return_type_table, NULL); + return_type_table, NULL, NULL); } CBMFileResult *cbm_extract_file_ex_with_tests( const char *source, int source_len, CBMLanguage language, const char *project, const char *rel_path, int64_t timeout_micros, const char **extra_defines, const char **include_paths, const CBMMacroTable *macro_table, - const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations) { + const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations, + const char *repo_root) { CBMArena scratch; if (tl_scratch_live && tl_scratch_slot) { scratch = *tl_scratch_slot; @@ -4867,7 +4941,7 @@ CBMFileResult *cbm_extract_file_ex_with_tests( } CBMFileResult *result = extract_file_ex_body( source, source_len, language, project, rel_path, timeout_micros, extra_defines, - include_paths, macro_table, return_type_table, &scratch, test_declarations); + include_paths, macro_table, return_type_table, &scratch, test_declarations, repo_root); /* Even early parse/quarantine exits publish conservative Python metadata. * No tree is reparsed, and existing best-effort extraction flags stay intact. */ if (result && language == CBM_LANG_PYTHON && diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index de1cc03f9..c536cc050 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -1282,12 +1282,16 @@ CBMFileResult *cbm_extract_file_ex( /* Additive immutable-snapshot entry point. NULL preserves legacy behavior. * Snapshot must outlive this call; returned data is independently result-owned. * A non-OK result status is an explicit configured-mapping failure, not a - * successful empty inventory. error_msg may be NULL on diagnostic OOM. */ + * successful empty inventory. error_msg may be NULL on diagnostic OOM. + * repo_root: the indexed repository root rel_path is relative to. The C-family + * preprocessed pass resolves quoted #include names against it (preprocessor.h); + * NULL resolves none. Never the process working directory. */ CBMFileResult *cbm_extract_file_ex_with_tests( const char *source, int source_len, CBMLanguage language, const char *project, const char *rel_path, int64_t timeout_micros, const char **extra_defines, const char **include_paths, const CBMMacroTable *macro_table, - const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations); + const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations, + const char *repo_root); // Free all memory associated with a result. void cbm_free_result(CBMFileResult *result); diff --git a/internal/cbm/preprocessor.cpp b/internal/cbm/preprocessor.cpp index 43ab183d0..87e69be87 100644 --- a/internal/cbm/preprocessor.cpp +++ b/internal/cbm/preprocessor.cpp @@ -5,13 +5,257 @@ #include "preprocessor.h" #include "vendored/simplecpp/simplecpp.h" +#include +#include #include #include +#include #include #include #include #include +// ── #include lookup against the indexed repository root (#2993) ──────────── +// simplecpp looks a quoted header up as `dirPath(includer) + name` and opens it +// relative to the process working directory, so the expansion depended on the +// directory the indexer was started from. Here every #include and +// __has_include of the file, and of each header it reaches, is resolved before +// simplecpp runs: a quoted name in the including file's directory within the +// repository root, read through the caller's CBMIncludeReader; an angle-bracket +// name resolves to nothing, as no include directories are configured. The +// result is stored in simplecpp's FileDataCache under the exact key its own +// lookup (FileDataCache::get) computes, so simplecpp opens no file itself and +// the expansion is a function of the indexed tree alone. +namespace { + +// A computed `#include MACRO` line names its header only after macro expansion, +// which no lookup made ahead of simplecpp can see. Its directive is renamed to +// one simplecpp does not know, and an unknown directive includes nothing. +const char kUnresolvedIncludeDirective[] = "cbm_unresolved_include"; + +// True when `key`, the normalised name an include resolves to, names a file +// within the indexed repository root: the name was written relative to the +// including file, and every component of the normalised result names an entry +// of the tree. The rule is the same on every platform, so one tree resolves the +// same way everywhere. +bool names_tree_file(const std::string &header, const std::string &key) { + if (header.empty() || header[0] == '/' || header[0] == '\\' || + (header.size() >= 2U && header[1] == ':')) { + return false; + } + if (key.empty() || key[0] == '/' || key.find(':') != std::string::npos || + key.find('\\') != std::string::npos || key.find('\0') != std::string::npos) { + return false; + } + std::string::size_type start = 0; + for (;;) { + const std::string::size_type end = key.find('/', start); + const std::string part = + key.substr(start, end == std::string::npos ? std::string::npos : end - start); + if (part == "..") { + return false; + } + if (end == std::string::npos) { + return true; + } + start = end + 1U; + } +} + +// The first non-comment token after `tok` on the same line, or nullptr. +simplecpp::Token *next_on_line(simplecpp::Token *tok) { + simplecpp::Token *next = tok->next; + while (next && next->comment) { + next = next->next; + } + return sameline(tok, next) ? next : nullptr; +} + +class IncludeTree { + public: + IncludeTree(const CBMIncludeReader *reader, std::vector &files, + simplecpp::FileDataCache &cache) + : reader_(reader), files_(files), cache_(cache) {} + + // Resolve everything the main file reaches. Every file name its own + // tokens registered (itself, and names from its #line directives) is the + // main file's; every later one belongs to a header. + void add_main_file(simplecpp::TokenList &tokens) { + first_header_file_ = static_cast(files_.size()); + prepare(tokens); + while (!pending_.empty()) { + Pending next = std::move(pending_.front()); + pending_.pop_front(); + prepare(next.tokens); + cache_.insert(simplecpp::FileData{next.key, std::move(next.tokens)}); + } + } + + // Tokens whose file index is at or above this came from a header. + unsigned int first_header_file() const { + return first_header_file_; + } + + private: + struct Pending { + std::string key; + simplecpp::TokenList tokens; + }; + + // Rewrite one file's __has_include tests and computed includes, and + // resolve the headers its #include lines name. + void prepare(simplecpp::TokenList &tokens) { + for (simplecpp::Token *tok = tokens.front(); tok; tok = tok->next) { + if (tok->str() == HAS_INCLUDE) { + rewrite_has_include(tokens, tok); + } else if (tok->op == '#' && !sameline(tok->previousSkipComments(), tok)) { + simplecpp::Token *directive = next_on_line(tok); + if (directive && directive->str() == INCLUDE) { + resolve_include(directive); + } + } + } + } + + // `#include "name"` / `#include ` as simplecpp's preprocess reads it: + // the first non-comment token after the directive, quotes or brackets + // stripped. + void resolve_include(simplecpp::Token *directive) { + const simplecpp::Token *operand = next_on_line(directive); + if (!operand) { + return; // no header name: simplecpp reports it and opens nothing + } + if (operand->name) { + directive->setstr(kUnresolvedIncludeDirective); + return; + } + const std::string &spelled = operand->str(); + if (spelled.size() <= 2U) { + return; // no header name: simplecpp reports it and opens nothing + } + (void)lookup(file_of(directive), spelled.substr(1U, spelled.size() - 2U), + spelled[0] == '<'); + } + + // `__has_include ( name )` (or without the parentheses) as simplecpp's #if + // evaluation reads it becomes the literal 1 or 0 of the same lookup. The + // operand of `defined` / `#ifdef` / `#ifndef` stays as it is. A form that + // does not close on its line keeps its operand, and its #if still fails to + // evaluate, as it did before. + void rewrite_has_include(simplecpp::TokenList &tokens, simplecpp::Token *tok) { + const simplecpp::Token *before = tok->previousSkipComments(); + if (before && before->op == '(' && sameline(before, tok)) { + before = before->previousSkipComments(); + } + if (before && sameline(before, tok) && + (before->str() == DEFINED || before->str() == IFDEF || before->str() == IFNDEF)) { + return; + } + simplecpp::Token *operand = next_on_line(tok); + const bool par = operand && operand->op == '('; + if (par) { + operand = next_on_line(operand); + } + bool found = false; + simplecpp::Token *last = operand; + if (operand && operand->op == '<') { + while (last && last->op != '>') { + last = next_on_line(last); + } + } else if (operand && operand->str().size() > 2U && operand->str()[0] == '"') { + const std::string &spelled = operand->str(); + found = lookup(file_of(tok), spelled.substr(1U, spelled.size() - 2U), false); + } + if (last && par) { + last = next_on_line(last); + if (last && last->op != ')') { + last = nullptr; + } + } + tok->setstr(found ? "1" : "0"); + if (!last) { + return; + } + while (tok->next != last) { + tokens.deleteToken(tok->next); + } + tokens.deleteToken(last); + } + + const std::string &file_of(const simplecpp::Token *tok) const { + static const std::string none; + return tok->location.fileIndex < files_.size() ? files_[tok->location.fileIndex] : none; + } + + // Key the name the way simplecpp's FileDataCache::get does and make sure + // the cache holds that key, so get() finds it instead of opening a file. + // True when the name resolved to a file of the indexed tree. + bool lookup(const std::string &sourcefile, const std::string &header, bool system) { + if (simplecpp::isAbsolutePath(header)) { + return load(simplecpp::simplifyPath(header), false); + } + if (system) { + return false; // no include directories: get() opens nothing + } + const std::string key = simplecpp::simplifyPath(dirPath(sourcefile) + header); + return load(key, names_tree_file(header, key)); + } + + // Cache `key` once: its tokens when the tree holds it, an empty token list + // otherwise (the include then adds nothing). The main file never resolves + // as a header: its tokens are the expansion itself. + bool load(const std::string &key, bool in_tree) { + const std::map::const_iterator seen = loaded_.find(key); + if (seen != loaded_.end()) { + return seen->second; + } + std::string text; + const bool found = in_tree && !names_main_file(key) && read(key, &text); + loaded_[key] = found; + if (!found) { + cache_.insert(simplecpp::FileData{key, simplecpp::TokenList(files_)}); + return false; + } + std::istringstream istr(text); + pending_.push_back(Pending{key, simplecpp::TokenList(istr, files_, key)}); + return true; + } + + bool names_main_file(const std::string &key) const { + for (unsigned int i = 0; i < first_header_file_ && i < files_.size(); i++) { + if (files_[i] == key) { + return true; + } + } + return false; + } + + bool read(const std::string &key, std::string *out) const { + if (!reader_ || !reader_->read) { + return false; + } + size_t len = 0; + char *data = reader_->read(reader_->userdata, key.c_str(), &len); + if (!data) { + return false; + } + out->assign(data, len); + if (reader_->release) { + reader_->release(reader_->userdata, data); + } + return true; + } + + const CBMIncludeReader *reader_; + std::vector &files_; + simplecpp::FileDataCache &cache_; + std::map loaded_; + std::deque pending_; + unsigned int first_header_file_ = 0; +}; + +} // namespace + extern "C" { static bool has_preprocessor_work(const char *source, int source_len) { @@ -407,11 +651,23 @@ static bool tokens_source_adjacent(const simplecpp::Token *prev, const simplecpp // scopes, C-LSP class scopes) minted a second node for the same definition, the // QN dedup (strcmp) missing it. A gap that held whitespace or a comment is still // one space, as before. -static std::string stringify_source_spacing(const simplecpp::TokenList &tokens) { +// +// Tokens of an included header's body (file index at or above +// first_header_file) are left out: the header is indexed as its own file, and +// its calls, usages and writes are its own, never the includer's. What the +// header defines still shapes the main file's tokens, since macro expansions +// carry the location of their use. With no header body in the buffer, the main +// file's lines keep their own numbers, as they do when nothing is included. +static std::string stringify_source_spacing(const simplecpp::TokenList &tokens, + unsigned int first_header_file) { std::ostringstream ret; simplecpp::Location loc; loc.line = 1; + const simplecpp::Token *prev = nullptr; for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) { + if (tok->location.fileIndex >= first_header_file) { + continue; + } if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) { ret << "\n#line " << tok->location.line << " \"" << tokens.file(tok->location) << "\"\n"; @@ -421,16 +677,76 @@ static std::string stringify_source_spacing(const simplecpp::TokenList &tokens) ret << '\n'; loc.line++; } - const simplecpp::Token *prev = tok->previous; if (prev && prev->location.sameline(tok->location) && !tokens_source_adjacent(prev, tok)) { ret << ' '; } ret << tok->str(); loc.adjust(tok->str()); + prev = tok; } return ret.str(); } +// simplecpp drops the whole expansion when it stops at #error, or at a +// directive it cannot read or evaluate: the output list is cleared and an +// ERROR or SYNTAX_ERROR is reported. +static bool expansion_discarded(const simplecpp::TokenList &output, + const simplecpp::OutputList &outputs) { + if (!output.empty()) { + return false; + } + for (simplecpp::OutputList::const_iterator it = outputs.begin(); it != outputs.end(); ++it) { + if (it->type == simplecpp::Output::ERROR || it->type == simplecpp::Output::SYNTAX_ERROR) { + return true; + } + } + return false; +} + +// One simplecpp run over the file. Every header its #include and +// __has_include lines reach is resolved through `reader` first (none when it +// is NULL). Returns false when simplecpp discarded the expansion. +static bool preprocess_file(const std::string &src, const std::string &main_name, + const simplecpp::DUI &dui, const CBMIncludeReader *reader, + std::string *expanded) { + std::vector files; + files.push_back(main_name); + std::istringstream istr(src); + simplecpp::TokenList rawtokens(istr, files, files[0]); + simplecpp::FileDataCache cache; + IncludeTree tree(reader, files, cache); + tree.add_main_file(rawtokens); + simplecpp::TokenList output(files); + simplecpp::OutputList outputs; + simplecpp::preprocess(output, rawtokens, files, cache, dui, &outputs); + const bool kept = !expansion_discarded(output, outputs); + *expanded = stringify_source_spacing(output, tree.first_header_file()); + simplecpp::cleanup(cache); + return kept; +} + +// The file's expansion with its includes followed. When what an include +// brought in stops simplecpp (an #error reached inside a header, a header +// directive it cannot evaluate, a failure while reading one), the file keeps +// its expansion without includes instead of losing it. +static std::string preprocess_with_fallback(const std::string &src, const std::string &main_name, + const simplecpp::DUI &dui, + const CBMIncludeReader *reader) { + std::string expanded; + if (reader) { + try { + if (preprocess_file(src, main_name, dui, reader, &expanded)) { + return expanded; + } + } catch (...) { + // fall through to the expansion without includes + } + expanded.clear(); + } + (void)preprocess_file(src, main_name, dui, nullptr, &expanded); + return expanded; +} + static bool build_line_map(const std::string &expanded, const std::string &main_file, uint32_t *original_line_by_expanded_line, uint8_t *belongs_to_main_file) { @@ -472,7 +788,9 @@ static bool build_line_map(const std::string &expanded, const std::string &main_ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_len, const char *filename, const char **extra_defines, - const char **include_paths, int cpp_mode) { + const char **include_paths, int cpp_mode, + const CBMIncludeReader *reader) { + (void)include_paths; // lookups resolve through `reader` only (preprocessor.h) // Run the second pass when there are directives to evaluate OR when the file // carries export-macro-shaped identifiers to predefine empty (#1989) — a UE // plugin header with only `#pragma once` + `#include` lines still needs it. @@ -509,27 +827,11 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le dui.defines.push_back(std::string(export_cands[i]) + "="); } } - if (include_paths) { - for (int i = 0; include_paths[i]; i++) - dui.includePaths.push_back(include_paths[i]); - } dui.std = cpp_mode ? "c++17" : "c11"; - std::string src(source, source_len); - std::istringstream istr(src); - std::vector files; - files.push_back(filename ? filename : ""); - - simplecpp::TokenList rawtokens(istr, files, files[0]); - simplecpp::TokenList output(files); - simplecpp::FileDataCache filedata = simplecpp::load(rawtokens, files, dui); - - simplecpp::preprocess(output, rawtokens, files, filedata, dui); - - std::string result = stringify_source_spacing(output); - - // Clean up loaded file data - simplecpp::cleanup(filedata); + const std::string src(source, source_len); + const std::string main_name(filename ? filename : ""); + std::string result = preprocess_with_fallback(src, main_name, dui, reader); CBMPreprocessedSource *pp = (CBMPreprocessedSource *)calloc(1, sizeof(*pp)); if (!pp) { @@ -546,7 +848,7 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le return NULL; } memcpy(pp->source, result.c_str(), result.size() + 1); - if (!build_line_map(result, files[0], pp->original_line_by_expanded_line, + if (!build_line_map(result, main_name, pp->original_line_by_expanded_line, pp->belongs_to_main_file)) { cbm_preprocessed_source_free(pp); return NULL; @@ -561,7 +863,7 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le char *cbm_preprocess(const char *source, int source_len, const char *filename, const char **extra_defines, const char **include_paths, int cpp_mode) { CBMPreprocessedSource *pp = cbm_preprocess_with_map(source, source_len, filename, extra_defines, - include_paths, cpp_mode); + include_paths, cpp_mode, NULL); if (!pp) { return NULL; } diff --git a/internal/cbm/preprocessor.h b/internal/cbm/preprocessor.h index 1b108b335..84104fb98 100644 --- a/internal/cbm/preprocessor.h +++ b/internal/cbm/preprocessor.h @@ -24,26 +24,48 @@ typedef struct { int expanded_line_count; } CBMPreprocessedSource; +/* Supplies the files of the indexed repository to the #include lookup of the + * preprocessed pass. rel_path is relative to the repository root, '/'-separated + * and normalised. read returns a buffer of *out_len bytes, handed back to + * release once consumed, or NULL when the repository holds no such file. */ +typedef struct { + char *(*read)(const void *userdata, const char *rel_path, size_t *out_len); + void (*release)(const void *userdata, char *data); + const void *userdata; +} CBMIncludeReader; + // Collect conventional export-macro-shaped identifiers (ALL_CAPS ending in // _API/_EXPORT/_IMPORT/_DLLEXPORT/_DEPRECATED) from the source, up to max_out // unique names. Returns the number of names stored in out. int cbm_export_macro_candidates(const char *source, int source_len, char (*out)[CBM_EXPORT_MACRO_NAME_MAX], int max_out); -// Preprocess C/C++ source: expand macros, evaluate #ifdef, resolve #include. +// Preprocess C/C++ source: expand macros, evaluate #ifdef. #include is not +// followed (no include reader): every included header contributes nothing. // Returns malloc-allocated expanded source, or NULL if no expansion needed/on failure. // extra_defines: NULL-terminated array of "NAME=VALUE" strings (can be NULL). -// include_paths: NULL-terminated array of directory paths for #include resolution (can be NULL). +// include_paths: kept for API compatibility; not consulted (see cbm_preprocess_with_map). // The returned string must be freed with cbm_preprocess_free(). char *cbm_preprocess(const char *source, int source_len, const char *filename, const char **extra_defines, const char **include_paths, int cpp_mode); // Preprocess and return source plus expanded-line -> original-line ownership map. +// filename is the file's path relative to the indexed repository root. Quoted +// #include and __has_include names resolve through `reader` only, in the +// including file's directory within the repository root; a NULL reader +// resolves nothing. Angle-bracket names and computed #include lines resolve to +// nothing, and include_paths is not consulted, so the expansion is a function +// of the indexed tree alone. The expanded buffer holds the main file's own +// tokens only: what an included header defines (macros, #if state) shapes it, +// but the header's body is not part of it; the header is indexed as its own +// file. When the run that follows includes ends in #error (or another stop that +// discards the expansion), the file falls back to its expansion without includes. // Returns NULL if no expansion is needed or preprocessing fails. // Free with cbm_preprocessed_source_free(). CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_len, const char *filename, const char **extra_defines, - const char **include_paths, int cpp_mode); + const char **include_paths, int cpp_mode, + const CBMIncludeReader *reader); // Free preprocessed source returned by cbm_preprocess. void cbm_preprocess_free(char *expanded); diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.c index 4430e9d44..14b6fe9a5 100644 --- a/src/pipeline/pass_calls.c +++ b/src/pipeline/pass_calls.c @@ -1545,12 +1545,12 @@ static CBMFileResult *calls_get_or_extract(cbm_pipeline_ctx_t *ctx, int idx, } return NULL; } - CBMFileResult *r = - cbm_pipeline_test_force_extract_null(ctx, fi->language) - ? NULL - : cbm_extract_file_ex_with_tests( - src, slen, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, - NULL, NULL, ctx->macro_table, ctx->return_type_table, ctx->test_declarations); + CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language) + ? NULL + : cbm_extract_file_ex_with_tests( + src, slen, fi->language, ctx->project_name, fi->rel_path, + CBM_EXTRACT_BUDGET, NULL, NULL, ctx->macro_table, + ctx->return_type_table, ctx->test_declarations, ctx->repo_path); free(src); (void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r); if (r) { diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c index 11f851fbf..e67406019 100644 --- a/src/pipeline/pass_definitions.c +++ b/src/pipeline/pass_definitions.c @@ -1101,10 +1101,10 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t : lang == CBM_LANG_OBJECTSCRIPT_EXPORT ? cbm_pipeline_extract_objectscript_export(source, source_len, ctx->project_name, rel, ctx->macro_table, NULL) - : cbm_extract_file_ex_with_tests(source, source_len, lang, ctx->project_name, rel, - CBM_EXTRACT_BUDGET, NULL, - NULL /* no extra defines or include paths */, - ctx->macro_table, NULL, ctx->test_declarations); + : cbm_extract_file_ex_with_tests( + source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL, + NULL /* no extra defines or include paths */, ctx->macro_table, NULL, + ctx->test_declarations, ctx->repo_path); free(source); if (!cbm_pipeline_test_extraction_ok(ctx, lang, result)) { diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c index 71b5b684f..9066b971f 100644 --- a/src/pipeline/pass_parallel.c +++ b/src/pipeline/pass_parallel.c @@ -1370,7 +1370,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) { : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ec->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, ec->macro_table, ec->return_type_table, - ec->pctx->test_declarations); + ec->pctx->test_declarations, ec->repo_path); uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS; diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c index 9ad910852..50b9ddf40 100644 --- a/src/pipeline/pass_semantic.c +++ b/src/pipeline/pass_semantic.c @@ -699,7 +699,7 @@ static CBMFileResult *sem_get_or_extract(cbm_pipeline_ctx_t *ctx, int file_idx, ? NULL : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, NULL, - NULL, ctx->test_declarations); + NULL, ctx->test_declarations, ctx->repo_path); cbm_free(CBM_MEM_CLASS_SEMANTIC, source); (void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r); if (r) { diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.c index 7a643ce05..628f9d163 100644 --- a/src/pipeline/pass_usages.c +++ b/src/pipeline/pass_usages.c @@ -481,7 +481,8 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil ? NULL : cbm_extract_file_ex_with_tests( source, source_len, files[i].language, ctx->project_name, rel, - CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations); + CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations, + ctx->repo_path); free(source); if (!cbm_pipeline_test_extraction_ok(ctx, files[i].language, result)) { cbm_free_result(result); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index ff4e6d0d6..bb2d90f23 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -34950,7 +34950,304 @@ TEST(pipeline_inc_c_family_fragments) { th_rmtree(tmp); PASS(); } + +/* ── C/C++ #include lookup against the indexed repository root (#2993) ── */ + +#ifdef _WIN32 +#include +#define inc_root_chdir _chdir +#define inc_root_getcwd _getcwd +#else +#define inc_root_chdir chdir +#define inc_root_getcwd getcwd +#endif + +/* Index `root` into `db` with the process working directory set to `cwd`, and + * restore the working directory afterwards. */ +static int inc_root_index_from(const char *root, const char *db, const char *cwd) { + char saved[CBM_SZ_4K]; + if (!inc_root_getcwd(saved, sizeof(saved)) || inc_root_chdir(cwd) != 0) { + return -1; + } + int rc = -1; + cbm_pipeline_t *p = cbm_pipeline_new(root, db, CBM_MODE_FULL); + if (p) { + (void)cbm_pipeline_set_project_name(p, "incroot"); + cbm_pipeline_set_persistence(p, false); + rc = cbm_pipeline_run(p); + cbm_pipeline_free(p); + } + if (inc_root_chdir(saved) != 0) { + rc = -1; + } + return rc; +} + +/* One FNV-1a digest over every node and edge row of the graph, in sorted + * order: two graphs with the same digest and row count are the same graph. */ +static uint64_t inc_root_graph_digest(const char *db_path, int *rows) { + static const char *const queries[] = { + "SELECT label||'|'||qualified_name||'|'||file_path||'|'||start_line||'|'||end_line||'|'||" + "properties FROM nodes ORDER BY 1", + "SELECT e.type||'|'||s.qualified_name||'|'||t.qualified_name||'|'||e.properties FROM edges " + "e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id ORDER BY 1", + }; + uint64_t h = 1469598103934665603ULL; + *rows = 0; + sqlite3 *db = NULL; + if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK) { + for (size_t q = 0; q < sizeof(queries) / sizeof(queries[0]); q++) { + sqlite3_stmt *stmt = NULL; + if (sqlite3_prepare_v2(db, queries[q], -1, &stmt, NULL) == SQLITE_OK) { + while (sqlite3_step(stmt) == SQLITE_ROW) { + const unsigned char *row = sqlite3_column_text(stmt, 0); + for (const unsigned char *c = row ? row : (const unsigned char *)""; *c; c++) { + h = (h ^ *c) * 1099511628211ULL; + } + h = (h ^ 0xffU) * 1099511628211ULL; + (*rows)++; + } + } + sqlite3_finalize(stmt); + } + } + sqlite3_close(db); + return h; +} + +/* CALLS edges from the function named `from` to the Function named `to`. */ +static int inc_root_calls(const char *db, const char *from, const char *to) { + char sql[512]; + snprintf(sql, sizeof(sql), + "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON " + "t.id=e.target_id WHERE e.type='CALLS' AND s.name='%s' AND t.name='%s' AND " + "t.label='Function'", + from, to); + return k8s_inc_count(db, sql); +} + +/* #2993: the graph depended on the directory the indexer was started from: + * a quoted #include was looked up relative to the process working directory. + * The lookup now resolves against the indexed repository root. The same + * fixture, indexed from an empty directory, from a directory holding a + * different lib/m.h, and from the repository root, gives one graph, in which + * the macro of the repository's own lib/m.h expands to a call that resolves + * to its in-tree target. */ +TEST(pipeline_c_include_lookup_uses_repo_root) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s/cbm_incroot_XXXXXX", cbm_tmpdir()); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + char root[512]; + char empty[512]; + char other[512]; + snprintf(root, sizeof(root), "%s/repo", tmp); + snprintf(empty, sizeof(empty), "%s/empty", tmp); + snprintf(other, sizeof(other), "%s/other", tmp); + write_temp_file(root, "lib/a.c", + "#define A_C_LOCAL 1\n" + "#include \"m.h\"\n" + "\n" + "void caller(int v) {\n" + " DO_WORK(v);\n" + "}\n"); + write_temp_file(root, "lib/m.h", + "#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n"); + write_temp_file(root, "lib/t.c", + "void real_target(int x) { (void)x; }\n" + "void other_target(int x) { (void)x; }\n"); + write_temp_file(other, "lib/m.h", + "#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n"); + ASSERT(cbm_mkdir_p(empty, 0755)); + + const char *cwds[] = {empty, other, root}; + enum { RUNS = sizeof(cwds) / sizeof(cwds[0]) }; + int rc[RUNS]; + int rows[RUNS]; + int real[RUNS]; + int stray[RUNS]; + uint64_t digest[RUNS]; + for (int i = 0; i < RUNS; i++) { + char db[512]; + snprintf(db, sizeof(db), "%s/graph%d.db", tmp, i); + rc[i] = inc_root_index_from(root, db, cwds[i]); + digest[i] = inc_root_graph_digest(db, &rows[i]); + real[i] = inc_root_calls(db, "caller", "real_target"); + stray[i] = inc_root_calls(db, "caller", "other_target"); + } + th_rmtree(tmp); + for (int i = 0; i < RUNS; i++) { + ASSERT_EQ(rc[i], 0); + ASSERT_GT(rows[i], 0); + ASSERT_EQ(real[i], 1); + ASSERT_EQ(stray[i], 0); + ASSERT_EQ(rows[i], rows[0]); + ASSERT(digest[i] == digest[0]); + } + PASS(); +} + +/* #2993: simplecpp discards a file's whole expansion when it stops at #error. + * An #error reached inside an included header must not cost the file its + * expansion: the file keeps its expansion without includes, so the call its + * own macro expands to survives. Indexed from the repository root, where the + * header is found whichever way the lookup is made. */ +TEST(pipeline_c_include_error_keeps_expansion_without_includes) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s/cbm_incerr_XXXXXX", cbm_tmpdir()); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + char root[512]; + snprintf(root, sizeof(root), "%s/repo", tmp); + write_temp_file(root, "cfg.h", + "#ifndef CFG_H\n" + "#define CFG_H\n" + "#ifndef CFG_CONFIGURED\n" + "#error \"configure first\"\n" + "#endif\n" + "#endif\n"); + write_temp_file(root, "z.c", + "#include \"cfg.h\"\n" + "#define RUN_STEP(x) step_target(x)\n" + "\n" + "int z_entry(int v) {\n" + " RUN_STEP(v);\n" + " return v;\n" + "}\n"); + write_temp_file(root, "steps.c", "void step_target(int x) { (void)x; }\n"); + char db[512]; + snprintf(db, sizeof(db), "%s/graph.db", tmp); + int rc = inc_root_index_from(root, db, root); + int step_calls = inc_root_calls(db, "z_entry", "step_target"); + th_rmtree(tmp); + ASSERT_EQ(rc, 0); + ASSERT_EQ(step_calls, 1); + PASS(); +} + +/* #2993: an included header's body is the header's own -- indexed as its own + * file, with its own lines. The includer's expansion holds only the + * includer's tokens (the header's macros still shape them), so a call or a + * write inside a header's inline function is never one of the includer's + * edges, and no edge of the includer carries a line past the includer's last + * line. Indexed from the repository root, where the header is found whichever + * way the lookup is made. */ +TEST(pipeline_c_header_body_stays_with_the_header) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s/cbm_inchdr_XXXXXX", cbm_tmpdir()); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + char root[512]; + snprintf(root, sizeof(root), "%s/repo", tmp); + char header[2048]; + int used = snprintf(header, sizeof(header), "#ifndef OPS_H\n#define OPS_H\n"); + for (int i = 0; i < 24; i++) { + used += snprintf(header + used, sizeof(header) - (size_t)used, "/* line %d */\n", i); + } + snprintf(header + used, sizeof(header) - (size_t)used, + "extern int header_counter;\n" + "static inline int ops_inline(int v) {\n" + " header_counter = v;\n" + " return header_only_callee(v);\n" + "}\n" + "#endif\n"); + write_temp_file(root, "ops.h", header); + /* user.c is 6 lines long. */ + write_temp_file(root, "user.c", + "#include \"ops.h\"\n" + "#define USER_FLAG 1\n" + "\n" + "int user_fn(int v) {\n" + " return main_only_callee(v);\n" + "}\n"); + write_temp_file(root, "callees.c", + "int header_counter;\n" + "int header_only_callee(int v) { return v; }\n" + "int main_only_callee(int v) { return v; }\n"); + char db[512]; + snprintf(db, sizeof(db), "%s/graph.db", tmp); + int rc = inc_root_index_from(root, db, root); + int from_user = k8s_inc_count( + db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON " + "t.id=e.target_id WHERE e.type IN ('CALLS','USAGE','WRITES') AND " + "s.file_path='user.c' AND t.name IN ('header_only_callee','header_counter')"); + int past_end = k8s_inc_count( + db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id WHERE e.type IN " + "('CALLS','USAGE') AND s.file_path='user.c' AND " + "CAST(json_extract(e.properties,'$.line') AS INTEGER) > 6"); + int own_call = k8s_inc_count( + db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON " + "t.id=e.target_id WHERE e.type='CALLS' AND s.file_path='ops.h' AND " + "t.name='header_only_callee'"); + int user_call = inc_root_calls(db, "user_fn", "main_only_callee"); + th_rmtree(tmp); + ASSERT_EQ(rc, 0); + ASSERT_EQ(from_user, 0); + ASSERT_EQ(past_end, 0); + ASSERT_GT(own_call, 0); + ASSERT_EQ(user_call, 1); + PASS(); +} + +/* #2993: only a name that denotes a file of the indexed tree resolves. Each + * of the three includes of lib/a.c names a header that is not part of the + * indexed tree (the third is reached through a symbolic link, which discovery + * does not index either), so none of the three macros expands, wherever the + * indexer runs; here it runs from the repository root. */ +TEST(pipeline_c_include_lookup_stays_in_repo_root) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s/cbm_incside_XXXXXX", cbm_tmpdir()); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + char root[512]; + snprintf(root, sizeof(root), "%s/repo", tmp); + write_temp_file(tmp, "m_side.h", "#define SIDE_M(x) m_target(x)\n"); + write_temp_file(tmp, "n_side.h", "#define SIDE_N(x) n_target(x)\n"); + write_temp_file(tmp, "l_side.h", "#define SIDE_L(x) l_target(x)\n"); + char source[2048]; + snprintf(source, sizeof(source), + "#define A_LOCAL 1\n" + "#include \"../../m_side.h\"\n" + "#include \"%s/n_side.h\"\n" + "#include \"l_side.h\"\n" + "\n" + "void caller(int v) {\n" + " SIDE_M(v);\n" + " SIDE_N(v);\n" + " SIDE_L(v);\n" + "}\n", + tmp); + write_temp_file(root, "lib/a.c", source); + write_temp_file(root, "lib/t.c", + "void m_target(int x) { (void)x; }\n" + "void n_target(int x) { (void)x; }\n" + "void l_target(int x) { (void)x; }\n"); +#ifndef _WIN32 + char link_target[512]; + char link_path[512]; + snprintf(link_target, sizeof(link_target), "%s/l_side.h", tmp); + snprintf(link_path, sizeof(link_path), "%s/lib/l_side.h", root); + ASSERT_EQ(symlink(link_target, link_path), 0); +#endif + char db[512]; + snprintf(db, sizeof(db), "%s/graph.db", tmp); + int rc = inc_root_index_from(root, db, root); + static const char *const targets[] = {"m_target", "n_target", "l_target"}; + int wrong = 0; + for (size_t i = 0; i < sizeof(targets) / sizeof(targets[0]); i++) { + int n = inc_root_calls(db, "caller", targets[i]); + if (n != 0) { + printf(" caller -> %s: %d\n", targets[i], n); + wrong++; + } + } + th_rmtree(tmp); + ASSERT_EQ(rc, 0); + ASSERT_EQ(wrong, 0); + PASS(); +} + SUITE(pipeline) { + RUN_TEST(pipeline_c_include_lookup_uses_repo_root); + RUN_TEST(pipeline_c_include_error_keeps_expansion_without_includes); + RUN_TEST(pipeline_c_header_body_stays_with_the_header); + RUN_TEST(pipeline_c_include_lookup_stays_in_repo_root); RUN_TEST(pipeline_inc_c_family_fragments); RUN_TEST(pipeline_python_module_callers_sequential); RUN_TEST(pipeline_python_module_callers_parallel); diff --git a/tests/test_pipeline_conventions.c b/tests/test_pipeline_conventions.c index ff8d73653..c2ee451a0 100644 --- a/tests/test_pipeline_conventions.c +++ b/tests/test_pipeline_conventions.c @@ -537,12 +537,12 @@ static pc_spill_witness_t pc_collect_spill_witness(pc_fixture_t *f) { decl = cbm_test_declarations_parse(pc_config0, strlen(pc_config0), false); if (!decl) goto done; cache[0] = cbm_extract_file_ex_with_tests(plain, (int)strlen(plain), CBM_LANG_C, - PC_PROJECT, "contributor.c", 0, NULL, NULL, NULL, NULL, decl); + PC_PROJECT, "contributor.c", 0, NULL, NULL, NULL, NULL, decl, NULL); if (!cache[0] || cache[0]->test_declarations_status != CBM_TEST_EXTRACT_OK || cache[0]->defs.count < 1) goto done; cbm_result_compact(cache[0]); cache[1] = cbm_extract_file_ex_with_tests(owner, (int)strlen(owner), CBM_LANG_C, - PC_PROJECT, "parked.c", 0, NULL, NULL, NULL, NULL, decl); + PC_PROJECT, "parked.c", 0, NULL, NULL, NULL, NULL, decl, NULL); if (!pc_result_case(cache[1], "CHECK_parked", PC_PROJECT ".parked.CHECK_parked")) goto done; cbm_result_compact(cache[1]); ctx.test_declarations = decl; diff --git a/tests/test_test_conventions.c b/tests/test_test_conventions.c index 79862da18..b289053da 100644 --- a/tests/test_test_conventions.c +++ b/tests/test_test_conventions.c @@ -33,7 +33,7 @@ static cbm_test_declarations_t *tc_config(const char *records, const char *prese static CBMFileResult *tc_extract(const char *source, CBMLanguage language, const char *path, const cbm_test_declarations_t *config) { return cbm_extract_file_ex_with_tests(source, (int)strlen(source), language, - "convproj", path, 0, NULL, NULL, NULL, NULL, config); + "convproj", path, 0, NULL, NULL, NULL, NULL, config, NULL); } static CBMFileResult *tc_legacy(const char *source, CBMLanguage language, const char *path) { From beba7f8c0c5879c6d46a0eb5d9125427e3df6099 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 04:05:30 +0100 Subject: [PATCH 04/25] C/C++: re-extract a header's includers in an incremental refresh A C-family file's preprocessed pass reads the repository files its quoted #include lines name, so its graph changes with their bytes even when its own bytes do not. An incremental refresh after an edit to a header alone re-extracted only the header, and its includers kept their old expansion. - The #include lookup resolves only to files the index run covers (its discovery, through CBMIncludeScope and the pipeline context's indexed_files), so every file an expansion depends on is in the run's manifest. - Each file's lsp_surface row records the files its lookup read (included_files; transitive, since the headers a header includes are on the includer's own list). It is not part of surface_sha. - The closure planner adds every stored file whose record names a changed or deleted file to the delta as a changed file, which then goes through the same surface comparison. One pass over the stored rows. - CBM_INDEX_FORMAT_VERSION 6 -> 7: an index written before records no included files, so it is rebuilt once. - The graph and content digests cover the new column; a database without it keeps its previous digest stream. Tests: pipeline_c_header_edit_refreshes_includers_incrementally (a header edit reaches a direct and a transitive includer; the refresh equals a fresh full index) and index_format_v6_included_files_rebuild. Refs #2993 Signed-off-by: Martin Vogel --- internal/cbm/cbm.c | 101 ++++++++++++++-------------- internal/cbm/cbm.h | 23 +++++-- internal/cbm/preprocessor.cpp | 82 ++++++++++++++++++---- internal/cbm/preprocessor.h | 5 ++ internal/cbm/result_compact.c | 1 + scripts/memory-core-baseline.txt | 2 +- src/pipeline/lsp_surface.c | 50 ++++++++++++-- src/pipeline/pass_calls.c | 3 +- src/pipeline/pass_definitions.c | 3 +- src/pipeline/pass_parallel.c | 3 +- src/pipeline/pass_semantic.c | 3 +- src/pipeline/pass_usages.c | 3 +- src/pipeline/pipeline.c | 29 ++++++++ src/pipeline/pipeline_incremental.c | 101 +++++++++++++++++++++++++++- src/pipeline/pipeline_internal.h | 11 +++ src/store/store.c | 17 +++-- src/store/store.h | 12 +++- src/store/store_content_digest.c | 29 +++++--- src/store/store_graph_digest.c | 47 ++++++++++--- tests/test_index_format.c | 84 +++++++++++++++++++++++ tests/test_pipeline.c | 95 ++++++++++++++++++++++++++ 21 files changed, 598 insertions(+), 106 deletions(-) diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index b70c37bf2..2f16e9774 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -3782,60 +3782,34 @@ static void cbm_swift_type_imports(CBMFileResult *result, CBMLanguage language) /* ── #include lookup of the preprocessed pass (#2993) ────────────── * Quoted #include names of the C-family second pass resolve against the - * indexed repository root: preprocessor.cpp hands over a normalised, - * root-relative name, and the header is read only when it is part of the tree - * the way discovery sees the tree -- every component below the root a - * directory or a regular file, none a symlink or junction (discovery skips - * those), within the per-file size cap. Paths are UTF-8, opened through - * cbm_fopen. Nothing here depends on the process working directory. */ -typedef struct { - const char *root; -} cbm_include_tree_t; - -/* True when every component of `path` after its first `root_len` bytes is a - * directory, the last one a regular file; *size receives that file's size. */ -static bool include_path_in_tree(char *path, size_t root_len, int64_t *size) { - cbm_path_info_t info = {0}; - char *component = path + root_len; - for (;;) { - char *slash = strchr(component, '/'); - if (slash) { - *slash = '\0'; - } - int rc = cbm_path_info_utf8(path, &info); - if (slash) { - *slash = '/'; - } - if (rc != CBM_PATH_INFO_OK || info.is_symlink || - (slash ? !info.is_directory : !info.is_regular)) { - return false; - } - if (!slash) { - *size = info.size; - return true; - } - component = slash + 1; - } -} - + * indexed repository: preprocessor.cpp hands over a normalised, root-relative + * name, and the header is read only when it is one of the files the index run + * covers (CBMIncludeScope.is_indexed; discovery has already applied its rules: + * no symlinks or junctions, ignore files, skipped directories), within the + * per-file size cap. Every file the expansion depends on is therefore in the + * run's manifest. Paths are UTF-8, opened through cbm_fopen. */ static char *include_tree_read(const void *userdata, const char *rel_path, size_t *out_len) { - const cbm_include_tree_t *tree = (const cbm_include_tree_t *)userdata; - size_t root_len = strlen(tree->root); - bool sep = root_len > 0 && tree->root[root_len - 1] != '/' && tree->root[root_len - 1] != '\\'; - char path[CBM_SZ_4K]; - int written = snprintf(path, sizeof(path), "%s%s%s", tree->root, sep ? "/" : "", rel_path); - if (!rel_path[0] || written < 0 || (size_t)written >= sizeof(path)) { + const CBMIncludeScope *scope = (const CBMIncludeScope *)userdata; + if (!rel_path[0] || !scope->is_indexed || !scope->is_indexed(scope->userdata, rel_path)) { return NULL; } - int64_t size = 0; - if (!include_path_in_tree(path, root_len + (sep ? 1 : 0), &size) || size < 0 || - size > (int64_t)cbm_max_file_bytes()) { + size_t root_len = strlen(scope->root); + bool sep = + root_len > 0 && scope->root[root_len - 1] != '/' && scope->root[root_len - 1] != '\\'; + char path[CBM_SZ_4K]; + int written = snprintf(path, sizeof(path), "%s%s%s", scope->root, sep ? "/" : "", rel_path); + if (written < 0 || (size_t)written >= sizeof(path)) { return NULL; } FILE *f = cbm_fopen(path, "rb"); if (!f) { return NULL; } + long size = fseek(f, 0, SEEK_END) == 0 ? ftell(f) : -1; + if (size < 0 || size > cbm_max_file_bytes() || fseek(f, 0, SEEK_SET) != 0) { + (void)fclose(f); + return NULL; + } char *data = (char *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)size + 1); size_t got = data && size > 0 ? fread(data, 1, (size_t)size, f) : 0; (void)fclose(f); @@ -3851,12 +3825,36 @@ static void include_tree_release(const void *userdata, char *data) { cbm_free(CBM_MEM_CLASS_EXTRACT, data); } +/* result->included_files from what the preprocessed pass's lookup read. An + * allocation failure marks the result as failed: a missing list would let an + * incremental refresh skip this file after one of its headers changed. */ +static void record_included_files(CBMArena *a, CBMFileResult *result, + const CBMPreprocessedSource *pp) { + if (!pp || pp->included_count <= 0) { + return; + } + const char **list = + (const char **)cbm_arena_alloc(a, ((size_t)pp->included_count + 1) * sizeof(char *)); + for (int i = 0; list && i < pp->included_count; i++) { + list[i] = cbm_arena_strdup(a, pp->included_files[i]); + if (!list[i]) { + list = NULL; + } + } + if (!list) { + result->has_error = true; + return; + } + list[pp->included_count] = NULL; + result->included_files = list; +} + static CBMFileResult *extract_file_ex_body( const char *source, int source_len, CBMLanguage language, const char *project, const char *rel_path, int64_t timeout_micros, const char **extra_defines, const char **include_paths, const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table, CBMArena *scratch, - const cbm_test_declarations_t *test_declarations, const char *repo_root) { + const cbm_test_declarations_t *test_declarations, const CBMIncludeScope *include_scope) { // Allocate result on heap (arena inside for all string data) CBMFileResult *result = cbm_result_alloc(); if (!result) { @@ -4249,11 +4247,12 @@ static CBMFileResult *extract_file_ex_body( char export_cands[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX]; int export_cand_count = cbm_export_macro_candidates(source, source_len, export_cands, CBM_EXPORT_MACRO_MAX); - cbm_include_tree_t include_tree = {repo_root}; - CBMIncludeReader include_reader = {include_tree_read, include_tree_release, &include_tree}; + CBMIncludeReader include_reader = {include_tree_read, include_tree_release, include_scope}; + bool include_lookup = include_scope && include_scope->root && include_scope->root[0]; CBMPreprocessedSource *preprocessed = cbm_preprocess_with_map( source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C, - repo_root && repo_root[0] ? &include_reader : NULL); + include_lookup ? &include_reader : NULL); + record_included_files(a, result, preprocessed); if (preprocessed && preprocessed->source) { char *expanded = preprocessed->source; int expanded_len = (int)strlen(expanded); @@ -4930,7 +4929,7 @@ CBMFileResult *cbm_extract_file_ex_with_tests( const char *rel_path, int64_t timeout_micros, const char **extra_defines, const char **include_paths, const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations, - const char *repo_root) { + const CBMIncludeScope *include_scope) { CBMArena scratch; if (tl_scratch_live && tl_scratch_slot) { scratch = *tl_scratch_slot; @@ -4941,7 +4940,7 @@ CBMFileResult *cbm_extract_file_ex_with_tests( } CBMFileResult *result = extract_file_ex_body( source, source_len, language, project, rel_path, timeout_micros, extra_defines, - include_paths, macro_table, return_type_table, &scratch, test_declarations, repo_root); + include_paths, macro_table, return_type_table, &scratch, test_declarations, include_scope); /* Even early parse/quarantine exits publish conservative Python metadata. * No tree is reparsed, and existing best-effort extraction flags stay intact. */ if (result && language == CBM_LANG_PYTHON && diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index c536cc050..f684297ed 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -931,6 +931,11 @@ typedef struct CBMFileResult { const char **constants; // NULL-terminated (NULL if none) const char **global_vars; // NULL-terminated (NULL if none) const char **macros; // NULL-terminated, C/C++ only (NULL if none) + /* C, C++, CUDA: the repository files the preprocessed pass's #include + * lookup read (repository-relative, sorted, NULL-terminated; NULL if none). + * The file's graph depends on their bytes as well as its own, so an + * incremental refresh re-extracts the file when one of them changes. */ + const char **included_files; bool has_error; const char *error_msg; @@ -1279,19 +1284,29 @@ CBMFileResult *cbm_extract_file_ex( const CBMReturnTypeTable *return_type_table // OS return types, or NULL ); +/* The indexed repository as the C-family preprocessed pass's #include lookup + * sees it (#2993): `root` is the directory rel_path is relative to, and a + * quoted include resolves only to a file is_indexed() accepts -- one of the + * files the index run covers -- so the expansion is a function of the indexed + * tree alone, never of the process working directory. */ +typedef struct { + const char *root; + bool (*is_indexed)(const void *userdata, const char *rel_path); + const void *userdata; +} CBMIncludeScope; + /* Additive immutable-snapshot entry point. NULL preserves legacy behavior. * Snapshot must outlive this call; returned data is independently result-owned. * A non-OK result status is an explicit configured-mapping failure, not a * successful empty inventory. error_msg may be NULL on diagnostic OOM. - * repo_root: the indexed repository root rel_path is relative to. The C-family - * preprocessed pass resolves quoted #include names against it (preprocessor.h); - * NULL resolves none. Never the process working directory. */ + * include_scope: where quoted #include names resolve (preprocessor.h); NULL + * resolves none. */ CBMFileResult *cbm_extract_file_ex_with_tests( const char *source, int source_len, CBMLanguage language, const char *project, const char *rel_path, int64_t timeout_micros, const char **extra_defines, const char **include_paths, const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations, - const char *repo_root); + const CBMIncludeScope *include_scope); // Free all memory associated with a result. void cbm_free_result(CBMFileResult *result); diff --git a/internal/cbm/preprocessor.cpp b/internal/cbm/preprocessor.cpp index 87e69be87..95c964b36 100644 --- a/internal/cbm/preprocessor.cpp +++ b/internal/cbm/preprocessor.cpp @@ -96,6 +96,16 @@ class IncludeTree { return first_header_file_; } + // The repository files the lookup read, sorted (the map's order). + void read_files(std::vector *out) const { + for (std::map::const_iterator it = loaded_.begin(); it != loaded_.end(); + ++it) { + if (it->second) { + out->push_back(it->first); + } + } + } + private: struct Pending { std::string key; @@ -705,22 +715,35 @@ static bool expansion_discarded(const simplecpp::TokenList &output, // One simplecpp run over the file. Every header its #include and // __has_include lines reach is resolved through `reader` first (none when it -// is NULL). Returns false when simplecpp discarded the expansion. +// is NULL); `read` (may be NULL) receives the repository files the lookup +// read, also when the run fails. Returns false when simplecpp discarded the +// expansion. static bool preprocess_file(const std::string &src, const std::string &main_name, const simplecpp::DUI &dui, const CBMIncludeReader *reader, - std::string *expanded) { + std::string *expanded, std::vector *read) { std::vector files; files.push_back(main_name); std::istringstream istr(src); simplecpp::TokenList rawtokens(istr, files, files[0]); simplecpp::FileDataCache cache; IncludeTree tree(reader, files, cache); - tree.add_main_file(rawtokens); - simplecpp::TokenList output(files); - simplecpp::OutputList outputs; - simplecpp::preprocess(output, rawtokens, files, cache, dui, &outputs); - const bool kept = !expansion_discarded(output, outputs); - *expanded = stringify_source_spacing(output, tree.first_header_file()); + bool kept = false; + try { + tree.add_main_file(rawtokens); + simplecpp::TokenList output(files); + simplecpp::OutputList outputs; + simplecpp::preprocess(output, rawtokens, files, cache, dui, &outputs); + kept = !expansion_discarded(output, outputs); + *expanded = stringify_source_spacing(output, tree.first_header_file()); + } catch (...) { + if (read) { + tree.read_files(read); + } + throw; + } + if (read) { + tree.read_files(read); + } simplecpp::cleanup(cache); return kept; } @@ -728,14 +751,16 @@ static bool preprocess_file(const std::string &src, const std::string &main_name // The file's expansion with its includes followed. When what an include // brought in stops simplecpp (an #error reached inside a header, a header // directive it cannot evaluate, a failure while reading one), the file keeps -// its expansion without includes instead of losing it. +// its expansion without includes instead of losing it. `read` receives the +// repository files the include-following run read. static std::string preprocess_with_fallback(const std::string &src, const std::string &main_name, const simplecpp::DUI &dui, - const CBMIncludeReader *reader) { + const CBMIncludeReader *reader, + std::vector *read) { std::string expanded; if (reader) { try { - if (preprocess_file(src, main_name, dui, reader, &expanded)) { + if (preprocess_file(src, main_name, dui, reader, &expanded, read)) { return expanded; } } catch (...) { @@ -743,10 +768,32 @@ static std::string preprocess_with_fallback(const std::string &src, const std::s } expanded.clear(); } - (void)preprocess_file(src, main_name, dui, nullptr, &expanded); + (void)preprocess_file(src, main_name, dui, nullptr, &expanded, nullptr); return expanded; } +// A malloc'd copy of `read` for CBMPreprocessedSource.included_files; false on +// allocation failure (everything copied so far is released by the caller). +static bool copy_included_files(const std::vector &read, CBMPreprocessedSource *pp) { + if (read.empty()) { + return true; + } + pp->included_files = (char **)calloc(read.size(), sizeof(char *)); + if (!pp->included_files) { + return false; + } + for (size_t i = 0; i < read.size(); i++) { + char *copy = (char *)malloc(read[i].size() + 1); + if (!copy) { + return false; + } + memcpy(copy, read[i].c_str(), read[i].size() + 1); + pp->included_files[i] = copy; + pp->included_count = (int)i + 1; + } + return true; +} + static bool build_line_map(const std::string &expanded, const std::string &main_file, uint32_t *original_line_by_expanded_line, uint8_t *belongs_to_main_file) { @@ -831,12 +878,17 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le const std::string src(source, source_len); const std::string main_name(filename ? filename : ""); - std::string result = preprocess_with_fallback(src, main_name, dui, reader); + std::vector read; + std::string result = preprocess_with_fallback(src, main_name, dui, reader, &read); CBMPreprocessedSource *pp = (CBMPreprocessedSource *)calloc(1, sizeof(*pp)); if (!pp) { return NULL; } + if (!copy_included_files(read, pp)) { + cbm_preprocessed_source_free(pp); + return NULL; + } int line_count = count_expanded_lines(result); pp->source = (char *)malloc(result.size() + 1); pp->original_line_by_expanded_line = @@ -884,6 +936,10 @@ void cbm_preprocessed_source_free(CBMPreprocessedSource *pp) { free(pp->source); free(pp->original_line_by_expanded_line); free(pp->belongs_to_main_file); + for (int i = 0; i < pp->included_count; i++) { + free(pp->included_files[i]); + } + free(pp->included_files); free(pp); } diff --git a/internal/cbm/preprocessor.h b/internal/cbm/preprocessor.h index 84104fb98..bd0135873 100644 --- a/internal/cbm/preprocessor.h +++ b/internal/cbm/preprocessor.h @@ -22,6 +22,11 @@ typedef struct { uint32_t *original_line_by_expanded_line; // 1-based; 0 means directive/unmapped. uint8_t *belongs_to_main_file; // 1-based; true only for the original input file. int expanded_line_count; + /* The repository files the #include lookup read (repository-relative, + * sorted, each once), whether or not the run that followed includes kept + * its expansion: the expansion depends on their bytes either way. */ + char **included_files; + int included_count; } CBMPreprocessedSource; /* Supplies the files of the indexed repository to the #include lookup of the diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index b8b70da46..d3d942101 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -461,6 +461,7 @@ static void cr_walk(cr_ctx_t *c, CBMFileResult *r) { cr_list(c, &r->constants); cr_list(c, &r->global_vars); cr_list(c, &r->macros); + cr_list(c, &r->included_files); cr_str(c, &r->error_msg); cr_str(c, &r->error_ranges); cr_str(c, &r->module_doc); diff --git a/scripts/memory-core-baseline.txt b/scripts/memory-core-baseline.txt index 23f4744af..a21ce4111 100644 --- a/scripts/memory-core-baseline.txt +++ b/scripts/memory-core-baseline.txt @@ -55,7 +55,7 @@ src/mcp/mcp.c 765 src/pipeline/artifact.c 38 src/pipeline/fqn.c 23 src/pipeline/lsp_resolve.h 4 -src/pipeline/lsp_surface.c 5 +src/pipeline/lsp_surface.c 4 src/pipeline/pass_calls.c 22 src/pipeline/pass_compile_commands.c 17 src/pipeline/pass_configlink.c 3 diff --git a/src/pipeline/lsp_surface.c b/src/pipeline/lsp_surface.c index 20b16e5e3..24916e754 100644 --- a/src/pipeline/lsp_surface.c +++ b/src/pipeline/lsp_surface.c @@ -519,6 +519,42 @@ typedef struct { _Atomic bool failed; } surface_job_t; +/* Row strings are released with cbm_store_free_lsp_surfaces (free), so they + * come from the C heap: one place allocates them. */ +static char *surface_row_alloc(size_t n) { + return malloc(n); +} + +static char *surface_row_strdup(const char *s) { + size_t n = strlen(s); + char *copy = surface_row_alloc(n + 1); + if (copy) { + memcpy(copy, s, n + 1); + } + return copy; +} + +/* CBMFileResult.included_files, one file per line ("" when none). */ +static char *surface_row_included_files(const CBMFileResult *fr) { + size_t len = 0; + for (const char *const *f = fr->included_files; f && *f; f++) { + len += strlen(*f) + 1; + } + char *out = surface_row_alloc(len + 1); + if (!out) { + return NULL; + } + size_t at = 0; + for (const char *const *f = fr->included_files; f && *f; f++) { + size_t n = strlen(*f); + memcpy(out + at, *f, n); + at += n; + out[at++] = '\n'; + } + out[at] = '\0'; + return out; +} + static void surface_row_build(int i, void *arg) { surface_job_t *job = (surface_job_t *)arg; if (atomic_load_explicit(&job->failed, memory_order_relaxed)) { @@ -539,8 +575,11 @@ static void surface_row_build(int i, void *arg) { char *json = surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path, job->all_defs ? job->all_defs + start : NULL, end - start, &json_len); + char *included = surface_row_included_files(fr); cbm_pipeline_result_release(fr, loaded); - if (!json) { + if (!json || !included) { + free(json); + free(included); atomic_store_explicit(&job->failed, true, memory_order_relaxed); return; } @@ -548,12 +587,13 @@ static void surface_row_build(int i, void *arg) { cbm_sha256_hex(json, json_len, sha); cbm_lsp_surface_row_t *r = &job->rows[i]; r->defs_json = json; /* set first: it marks the row present for the compaction */ - r->project = strdup(job->project); - r->rel_path = strdup(job->files[i].rel_path); - r->surface_sha = strdup(sha); + r->project = surface_row_strdup(job->project); + r->rel_path = surface_row_strdup(job->files[i].rel_path); + r->surface_sha = surface_row_strdup(sha); r->ref_bloom = NULL; r->ref_bloom_len = 0; - r->config_ctx = strdup(""); + r->config_ctx = surface_row_strdup(""); + r->included_files = included; if (!r->project || !r->rel_path || !r->surface_sha || !r->config_ctx) { atomic_store_explicit(&job->failed, true, memory_order_relaxed); } diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.c index ac24ed378..16e04e85d 100644 --- a/src/pipeline/pass_calls.c +++ b/src/pipeline/pass_calls.c @@ -1545,12 +1545,13 @@ static CBMFileResult *calls_get_or_extract(cbm_pipeline_ctx_t *ctx, int idx, } return NULL; } + CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx); CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language) ? NULL : cbm_extract_file_ex_with_tests( src, slen, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, ctx->macro_table, - ctx->return_type_table, ctx->test_declarations, ctx->repo_path); + ctx->return_type_table, ctx->test_declarations, &include_scope); free(src); (void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r); if (r) { diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c index 3c29d1291..c18c9fcd1 100644 --- a/src/pipeline/pass_definitions.c +++ b/src/pipeline/pass_definitions.c @@ -1098,6 +1098,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t /* Studio Export XML is transformed to one cacheable aggregate so later * passes see the same calls/usages/semantic carriers as native UDL. */ + CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx); CBMFileResult *result = cbm_pipeline_test_force_extract_null(ctx, lang) ? NULL : lang == CBM_LANG_OBJECTSCRIPT_EXPORT @@ -1106,7 +1107,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t : cbm_extract_file_ex_with_tests( source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL, NULL /* no extra defines or include paths */, ctx->macro_table, NULL, - ctx->test_declarations, ctx->repo_path); + ctx->test_declarations, &include_scope); free(source); if (!cbm_pipeline_test_extraction_ok(ctx, lang, result)) { diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c index 7d8d8c85f..700ce270a 100644 --- a/src/pipeline/pass_parallel.c +++ b/src/pipeline/pass_parallel.c @@ -1361,6 +1361,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) { /* Export XML uses the same cache slot as every physical file, so its * generated classes are composed before entering the common registry * and resolution lifecycle. */ + CBMIncludeScope include_scope = cbm_pipeline_include_scope(ec->pctx); CBMFileResult *result = cbm_pipeline_test_force_extract_null(ec->pctx, fi->language) ? NULL : fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT @@ -1370,7 +1371,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) { : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ec->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, ec->macro_table, ec->return_type_table, - ec->pctx->test_declarations, ec->repo_path); + ec->pctx->test_declarations, &include_scope); uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS; diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c index 50b9ddf40..fdcbb9a0c 100644 --- a/src/pipeline/pass_semantic.c +++ b/src/pipeline/pass_semantic.c @@ -694,12 +694,13 @@ static CBMFileResult *sem_get_or_extract(cbm_pipeline_ctx_t *ctx, int file_idx, } return NULL; } + CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx); CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language) ? NULL : cbm_extract_file_ex_with_tests(source, source_len, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, NULL, - NULL, ctx->test_declarations, ctx->repo_path); + NULL, ctx->test_declarations, &include_scope); cbm_free(CBM_MEM_CLASS_SEMANTIC, source); (void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r); if (r) { diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.c index 628f9d163..588f0831f 100644 --- a/src/pipeline/pass_usages.c +++ b/src/pipeline/pass_usages.c @@ -477,12 +477,13 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil errors++; continue; } + CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx); result = cbm_pipeline_test_force_extract_null(ctx, files[i].language) ? NULL : cbm_extract_file_ex_with_tests( source, source_len, files[i].language, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations, - ctx->repo_path); + &include_scope); free(source); if (!cbm_pipeline_test_extraction_ok(ctx, files[i].language, result)) { cbm_free_result(result); diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index bae038f5d..5458de1a2 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -1007,6 +1007,27 @@ bool cbm_pipeline_set_project_name(cbm_pipeline_t *p, const char *name) { return true; } +CBMHashTable *cbm_pipeline_indexed_files_new(const cbm_file_info_t *files, int file_count) { + CBMHashTable *set = cbm_ht_create((uint32_t)((size_t)file_count * PAIR_LEN + CBM_SZ_64)); + for (int i = 0; set && i < file_count; i++) { + cbm_ht_set(set, files[i].rel_path, (void *)&files[i]); + } + return set; +} + +static bool pipeline_file_is_indexed(const void *userdata, const char *rel_path) { + return userdata && cbm_ht_get((const CBMHashTable *)userdata, rel_path) != NULL; +} + +CBMIncludeScope cbm_pipeline_include_scope(const cbm_pipeline_ctx_t *ctx) { + CBMIncludeScope scope = { + .root = ctx ? ctx->repo_path : NULL, + .is_indexed = pipeline_file_is_indexed, + .userdata = ctx ? ctx->indexed_files : NULL, + }; + return scope; +} + void cbm_pipeline_set_lsp_surfaces(cbm_pipeline_t *p, cbm_lsp_surface_row_t *rows, int count) { if (!p) { cbm_store_free_lsp_surfaces(rows, count); @@ -4386,6 +4407,7 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) { struct timespec t0; cbm_clock_gettime(CLOCK_MONOTONIC, &t0); cbm_path_alias_collection_t *path_aliases = NULL; + CBMHashTable *indexed_files = NULL; cbm_file_hash_t *baseline_manifest = NULL; int baseline_count = 0; char **requested_excluded_dirs = NULL; @@ -4551,11 +4573,17 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) { * when no usable configs are found — non-TS projects pay nothing. */ path_aliases = cbm_load_path_aliases_excluded(p->repo_path, p->excluded_dirs, p->excluded_count); + indexed_files = cbm_pipeline_indexed_files_new(files, file_count); + if (!indexed_files) { + rc = CBM_NOT_FOUND; + goto cleanup; + } /* Build shared context for pass functions */ cbm_pipeline_ctx_t ctx = { .project_name = p->project_name, .repo_path = p->repo_path, + .indexed_files = indexed_files, .gbuf = p->gbuf, .registry = p->registry, .cancelled = p->cancelled, @@ -4601,6 +4629,7 @@ cleanup: cbm_registry_free(p->registry); p->registry = NULL; cbm_path_alias_collection_free(path_aliases); + cbm_ht_free(indexed_files); /* keys borrowed from files */ if (restore_requested_discovery) { cbm_discover_free_excluded(p->excluded_dirs, p->excluded_count); cbm_discover_free_ignored(p->ignored_files, p->ignored_count); diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c index 40a425ea6..8c99f10b2 100644 --- a/src/pipeline/pipeline_incremental.c +++ b/src/pipeline/pipeline_incremental.c @@ -2361,6 +2361,7 @@ static void *rehydrate_worker(void *arg) { * correctness stays trivially reasoned. Returns heap rows via out. */ static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project, cbm_file_info_t *probe_files, int probe_count, + const CBMHashTable *indexed_files, cbm_lsp_surface_row_t **out_rows, int *out_count) { *out_rows = NULL; *out_count = 0; @@ -2376,6 +2377,7 @@ static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project, cbm_pipeline_ctx_t probe_ctx = { .project_name = project, .repo_path = cbm_pipeline_repo_path(p), + .indexed_files = indexed_files, .gbuf = probe_gbuf, .registry = NULL, .cancelled = cbm_pipeline_cancelled_ptr(p), @@ -3019,6 +3021,85 @@ static bool closure_metadata_current(bool metadata_current, const cbm_file_hash_ return current && old_count == new_count; } +/* Does `list` (one repository path per line, as lsp_surface.included_files + * stores it) name a file of `delta`? Every listed file must have been tracked + * by the previous generation: a file it did not hash cannot be proven + * unchanged, which *untracked reports. */ +static bool closure_list_names_delta(const char *list, const CBMHashTable *delta, + const CBMHashTable *stored_by_path, bool *untracked) { + bool hit = false; + char name[CBM_SZ_4K]; + for (const char *at = list; at && *at;) { + const char *end = strchr(at, '\n'); + size_t n = end ? (size_t)(end - at) : strlen(at); + if (n > 0) { + if (n >= sizeof(name)) { + *untracked = true; + return hit; + } + memcpy(name, at, n); + name[n] = '\0'; + if (!cbm_ht_get(stored_by_path, name)) { + *untracked = true; + } + if (cbm_ht_get(delta, name)) { + hit = true; + } + } + at = end ? end + 1 : at + n; + } + return hit; +} + +/* The includers of a changed or deleted file (#2993). A C-family file's + * preprocessed pass reads the repository files its #include lines name, so + * its graph changes with their bytes even when its own bytes do not. Every + * stored surface row lists the files its file's lookup read, transitively + * (the headers a header includes are on the includer's own list), so one pass + * over the rows finds every includer. Each joins the delta as a changed file + * and goes through the same surface comparison as the others. `paths` holds + * the changed files, then the deleted ones; the includers are inserted after + * the changed files. Linear in the total length of the lists. Returns a + * decline reason, or NULL. */ +static const char *closure_add_includers(const cbm_lsp_surface_row_t *rows, int row_count, + const CBMHashTable *stored_by_path, + const CBMHashTable *files_by_path, char **paths, + int *n_changed, int n_deleted) { + int changed = *n_changed; + CBMHashTable *delta = + cbm_ht_create((uint32_t)((size_t)(changed + n_deleted) * PAIR_LEN + CBM_SZ_64)); + char **found = (char **)cbm_alloc(CBM_MEM_CLASS_OTHER, + (size_t)(row_count > 0 ? row_count : 1) * sizeof(char *)); + const char *why = !delta || !found ? "alloc" : NULL; + for (int i = 0; !why && i < changed + n_deleted; i++) { + cbm_ht_set(delta, paths[i], paths[i]); + } + int found_count = 0; + for (int i = 0; !why && i < row_count; i++) { + bool untracked = false; + bool hit = + closure_list_names_delta(rows[i].included_files, delta, stored_by_path, &untracked); + if (untracked) { + why = "include_untracked"; + } else if (hit && !cbm_ht_get(delta, rows[i].rel_path)) { + if (!cbm_ht_get(files_by_path, rows[i].rel_path)) { + why = "includer_not_discovered"; + } else { + found[found_count++] = (char *)rows[i].rel_path; + } + } + } + if (!why && found_count > 0) { + memmove(paths + changed + found_count, paths + changed, (size_t)n_deleted * sizeof(char *)); + memcpy(paths + changed, found, (size_t)found_count * sizeof(char *)); + *n_changed = changed + found_count; + cbm_log_info("incremental.closure_includers", "includers", itoa_buf(found_count)); + } + cbm_free(CBM_MEM_CLASS_OTHER, found); + cbm_ht_free(delta); /* keys borrowed */ + return why; +} + /* Decide whether this manifest delta is closure-repairable, and if so build * the plan. Returns 1 with *plan filled, or 0 (decline → FULL) with the * reason logged. Every early exit declines; nothing here mutates state. */ @@ -3202,6 +3283,12 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p for (int i = 0; i < plan->stored_count; i++) { cbm_ht_set(rows_by_path, plan->stored_rows[i].rel_path, &plan->stored_rows[i]); } + decline = closure_add_includers(plan->stored_rows, plan->stored_count, stored_by_path, + files_by_path, changed_paths, &n_changed, n_deleted); + if (decline) { + cbm_ht_free(rows_by_path); + goto done; + } probe_files = (cbm_file_info_t *)calloc((size_t)(n_changed ? n_changed : 1), sizeof(cbm_file_info_t)); @@ -3220,7 +3307,7 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p probe_files[i] = *info; } int probe_rc = n_changed > 0 ? closure_probe_surfaces(p, project, probe_files, n_changed, - &probe_rows, &probe_count) + files_by_path, &probe_rows, &probe_count) : 0; if (probe_rc != 0) { cbm_ht_free(rows_by_path); @@ -3566,6 +3653,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char cbm_gbuf_t *gbuf = NULL; cbm_registry_t *registry = NULL; cbm_path_alias_collection_t *path_aliases = NULL; + CBMHashTable *indexed_files = NULL; CBMHashTable *stale_surface_set = NULL; closure_resolve_t cr = {0}; bool cr_arena_live = false; @@ -3778,6 +3866,11 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char cbm_log_error("delta.err", "phase", "doc_link_scopes"); goto out; } + indexed_files = cbm_pipeline_indexed_files_new(files, file_count); + if (!indexed_files) { + cbm_log_error("delta.err", "phase", "indexed_files"); + goto out; + } /* The purge already removed the closure and deleted files, so every File * row left in the stage is a file the passes will not see. A failed read * is a delta-route failure: the maps would silently diverge from a full @@ -3791,6 +3884,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char cbm_pipeline_ctx_t ctx = { .project_name = project, .repo_path = cbm_pipeline_repo_path(p), + .indexed_files = indexed_files, .gbuf = gbuf, .registry = registry, .cancelled = cbm_pipeline_cancelled_ptr(p), @@ -4133,6 +4227,7 @@ out: cbm_registry_free(registry); } cbm_path_alias_collection_free(path_aliases); + cbm_ht_free(indexed_files); /* keys borrowed from files */ if (gbuf) { cbm_gbuf_free(gbuf); } @@ -4546,10 +4641,12 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil cbm_path_alias_collection_t *path_aliases = cbm_load_path_aliases_excluded(cbm_pipeline_repo_path(p), excluded_dirs, excluded_count); + CBMHashTable *indexed_files = cbm_pipeline_indexed_files_new(files, file_count); cbm_pipeline_ctx_t ctx = { .project_name = project, .repo_path = cbm_pipeline_repo_path(p), + .indexed_files = indexed_files, .gbuf = existing, .registry = registry, .cancelled = cbm_pipeline_cancelled_ptr(p), @@ -4637,6 +4734,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil free(changed_files); cbm_registry_free(registry); cbm_path_alias_collection_free(path_aliases); + cbm_ht_free(indexed_files); /* keys borrowed from files */ incr_free_edge_capture(&edge_cap); cbm_store_free_coverage(old_cov, old_cov_count); free_mode_skipped(mode_skipped, mode_skipped_count); @@ -4736,6 +4834,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil free(changed_files); cbm_registry_free(registry); cbm_path_alias_collection_free(path_aliases); + cbm_ht_free(indexed_files); /* keys borrowed from files */ /* Re-link inbound cross-file edges that the purge orphaned. Runs after * re-resolution AND post-passes so the freshly re-created target nodes diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h index 475f233a2..373d2e5da 100644 --- a/src/pipeline/pipeline_internal.h +++ b/src/pipeline/pipeline_internal.h @@ -458,6 +458,10 @@ typedef struct cbm_tf_release { typedef struct { const char *project_name; /* borrowed from pipeline */ const char *repo_path; /* borrowed from pipeline */ + /* The rel_path of every file of the run's whole discovery (keys borrowed + * from its file list), also when a pass is handed only some of them: the + * files a C-family #include may resolve to (#2993). NULL: none resolves. */ + const CBMHashTable *indexed_files; /* An incremental run: the unchanged files whose earlier run declared * image builds (docker build ...), read again by the shell pass, as * those edges are recomputed whole. Borrowed; NULL in a full run. */ @@ -577,6 +581,13 @@ typedef struct { int tf_release_cap; } cbm_pipeline_ctx_t; +/* The set for cbm_pipeline_ctx_t.indexed_files: every rel_path of `files` + * (keys borrowed; free with cbm_ht_free). NULL on allocation failure. */ +CBMHashTable *cbm_pipeline_indexed_files_new(const cbm_file_info_t *files, int file_count); +/* The #include scope of a pass's C-family extraction: the run's repository + * root and its indexed files. */ +CBMIncludeScope cbm_pipeline_include_scope(const cbm_pipeline_ctx_t *ctx); + /* Origin-aware LSP returns only success/failure. Never retain partial output * when its configured owner proof cannot be applied to current source. */ static inline void cbm_pipeline_test_owner_error(CBMFileResult *result) { diff --git a/src/store/store.c b/src/store/store.c index c76fd3625..6b3cf5c35 100644 --- a/src/store/store.c +++ b/src/store/store.c @@ -428,6 +428,7 @@ static int init_schema(cbm_store_t *s) { " defs_json TEXT NOT NULL," " ref_bloom BLOB," " config_ctx TEXT NOT NULL DEFAULT ''," + " included_files TEXT NOT NULL DEFAULT ''," " PRIMARY KEY (project, rel_path)" ");" /* Best-effort indexing-coverage signal (#963). One row per file the @@ -6551,11 +6552,11 @@ int cbm_store_upsert_file_hash_batch(cbm_store_t *s, const cbm_file_hash_t *hash static int upsert_lsp_surface_row(cbm_store_t *s, const cbm_lsp_surface_row_t *row) { const char *sql = - "INSERT INTO lsp_surface (project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx)" - " VALUES (?1, ?2, ?3, ?4, ?5, ?6)" + "INSERT INTO lsp_surface (project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx," + " included_files) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)" " ON CONFLICT(project, rel_path) DO UPDATE SET surface_sha = excluded.surface_sha," " defs_json = excluded.defs_json, ref_bloom = excluded.ref_bloom," - " config_ctx = excluded.config_ctx"; + " config_ctx = excluded.config_ctx, included_files = excluded.included_files"; sqlite3_stmt *stmt = NULL; if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) { store_set_error_sqlite(s, "lsp_surface upsert prepare"); @@ -6571,6 +6572,7 @@ static int upsert_lsp_surface_row(cbm_store_t *s, const cbm_lsp_surface_row_t *r sqlite3_bind_null(stmt, ST_COL_5); } bind_text(stmt, ST_COL_6, row->config_ctx ? row->config_ctx : ""); + bind_text(stmt, ST_COL_7, row->included_files ? row->included_files : ""); int rc = sqlite3_step(stmt); sqlite3_finalize(stmt); if (rc != SQLITE_DONE) { @@ -6606,8 +6608,8 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf int *count) { *out = NULL; *count = 0; - const char *sql = "SELECT project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx" - " FROM lsp_surface WHERE project = ?1 ORDER BY rel_path"; + const char *sql = "SELECT project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx," + " included_files FROM lsp_surface WHERE project = ?1 ORDER BY rel_path"; sqlite3_stmt *stmt = NULL; if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) { store_set_error_sqlite(s, "lsp_surface get prepare"); @@ -6644,11 +6646,13 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf const void *bloom = sqlite3_column_blob(stmt, ST_COL_4); int bloom_len = sqlite3_column_bytes(stmt, ST_COL_4); const char *cfg = (const char *)sqlite3_column_text(stmt, ST_COL_5); + const char *inc = (const char *)sqlite3_column_text(stmt, ST_COL_6); r->project = strdup(proj ? proj : ""); r->rel_path = strdup(rel ? rel : ""); r->surface_sha = strdup(sha ? sha : ""); r->defs_json = strdup(defs ? defs : "[]"); r->config_ctx = strdup(cfg ? cfg : ""); + r->included_files = strdup(inc ? inc : ""); if (bloom && bloom_len > 0) { void *copy = malloc((size_t)bloom_len); if (copy) { @@ -6658,7 +6662,7 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf } } if (!r->project || !r->rel_path || !r->surface_sha || !r->defs_json || !r->config_ctx || - (bloom && bloom_len > 0 && !r->ref_bloom)) { + !r->included_files || (bloom && bloom_len > 0 && !r->ref_bloom)) { n++; /* count the partial row so the free below releases it */ oom = true; break; @@ -6707,6 +6711,7 @@ void cbm_store_free_lsp_surfaces(cbm_lsp_surface_row_t *rows, int count) { free((void *)rows[i].defs_json); free((void *)rows[i].ref_bloom); free((void *)rows[i].config_ctx); + free((void *)rows[i].included_files); } free(rows); } diff --git a/src/store/store.h b/src/store/store.h index c94add8ed..694712a59 100644 --- a/src/store/store.h +++ b/src/store/store.h @@ -39,8 +39,11 @@ typedef struct cbm_store_read_scope cbm_store_read_scope_t; * 6 #2360: File nodes record their declared package clause (`package` * property); an incremental run reads it back to build the namespace * map and the Scala top-level index for the files it does not - * re-extract. */ -#define CBM_INDEX_FORMAT_VERSION 6 + * re-extract. + * 7 #2993: lsp_surface rows record the repository files a C-family file's + * #include lookup read (`included_files`); an incremental run + * re-extracts the file when one of them changes. */ +#define CBM_INDEX_FORMAT_VERSION 7 #define CBM_STORE_CANCELLED (-3) #define CBM_STORE_SCAN_LIMIT (-4) #define CBM_STORE_CALLBACK_ERR (-5) @@ -113,6 +116,11 @@ typedef struct { const void *ref_bloom; /* referenced-identifier bloom blob (may be NULL) */ int ref_bloom_len; const char *config_ctx; /* governing-config context hash ("" = none) */ + /* The repository files the file's C-family #include lookup read + * (CBMFileResult.included_files): sorted, one per line, "" = none. Not part + * of the surface: an incremental run re-extracts the file when one of + * them changes. */ + const char *included_files; } cbm_lsp_surface_row_t; /* The definition variants that lie in a file (graph_buffer.c "Definition diff --git a/src/store/store_content_digest.c b/src/store/store_content_digest.c index ff15aa33e..6f1705382 100644 --- a/src/store/store_content_digest.c +++ b/src/store/store_content_digest.c @@ -42,8 +42,8 @@ static const sc_query_t sc_queries[] = { "(SELECT 1 FROM main.nodes n WHERE n.id=e.target_id));"}, {"file_hashes", "SELECT rel_path,sha256,size FROM main.file_hashes WHERE project=?1 " "ORDER BY 1,2,3;"}, - {"lsp_surface", "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM " - "main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5;"}, + {"lsp_surface", "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx,included_files " + "FROM main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5,6;"}, {"index_coverage", "SELECT rel_path,kind,detail FROM main.index_coverage WHERE project=?1 " "ORDER BY 1,2,3;"}, {"index_coverage_meta", @@ -87,6 +87,22 @@ static void sc_frame(cbm_sha256_ctx *ctx, unsigned char tag, const void *bytes, } } +/* Read-only legacy databases retain their existing content digest: a table + * that gained a column is read with its earlier query when the column is + * absent. NULL for tables without an earlier shape. */ +static const char *sc_legacy_query(const char *name) { + if (strcmp(name, "index_coverage_meta") == 0) { + return "SELECT index_mode,recording_status,ignored_files_stored," + "ignored_files_total,coverage_version,hash_records_complete FROM " + "main.index_coverage_meta WHERE project=?1;"; + } + if (strcmp(name, "lsp_surface") == 0) { + return "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM " + "main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5;"; + } + return NULL; +} + static bool sc_table(sqlite3 *db, const sc_query_t *q, const char *project, cbm_sha256_ctx *ctx) { sqlite3_stmt *st = NULL; if (sqlite3_prepare_v2(db, q->sql, -1, &st, NULL) != SQLITE_OK) { @@ -105,13 +121,8 @@ static bool sc_table(sqlite3 *db, const sc_query_t *q, const char *project, cbm_ sqlite3_step(schema) == SQLITE_DONE; return sqlite3_finalize(schema) == SQLITE_OK && absent; } - /* Read-only legacy databases retain their existing content digest. */ - if (strcmp(q->name, "index_coverage_meta") != 0 || - sqlite3_prepare_v2(db, - "SELECT index_mode,recording_status,ignored_files_stored," - "ignored_files_total,coverage_version,hash_records_complete FROM " - "main.index_coverage_meta WHERE project=?1;", - SC_SQL_TEXT_LENGTH, &st, NULL) != SQLITE_OK) { + const char *legacy = sc_legacy_query(q->name); + if (!legacy || sqlite3_prepare_v2(db, legacy, SC_SQL_TEXT_LENGTH, &st, NULL) != SQLITE_OK) { sqlite3_finalize(st); return false; } diff --git a/src/store/store_graph_digest.c b/src/store/store_graph_digest.c index 6748f25a0..967b66b77 100644 --- a/src/store/store_graph_digest.c +++ b/src/store/store_graph_digest.c @@ -18,6 +18,7 @@ enum { GD_ALLOW_BLOB = 1 << GD_BLOB, GD_TABLE_COUNT = 10, GD_MAX_COLUMNS = 10, + GD_LSP_SURFACE = 5, GD_COVERAGE_META = 7, GD_STORE_META = 8, GD_UNRESOLVED_CANDIDATES = 9, @@ -78,8 +79,9 @@ static const gd_column_t gd_project_summaries[] = {{"project", GD_T, 0, 1}, {"created_at", GD_T, 0, 0}, {"updated_at", GD_T, 0, 0}}; static const gd_column_t gd_lsp_surface[] = { - {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0}, - {"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0}, {"config_ctx", GD_T, 0, 0}}; + {"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0}, + {"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0}, {"config_ctx", GD_T, 0, 0}, + {"included_files", GD_T, 0, 0}}; static const gd_column_t gd_index_coverage[] = {{"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"kind", GD_T, 0, 3}, @@ -119,7 +121,7 @@ static const gd_table_t gd_tables[GD_TABLE_COUNT] = { "PRAGMA main.table_xinfo('project_summaries');", "SELECT project,summary,source_hash,created_at,updated_at FROM main.project_summaries " "ORDER BY CAST(project AS BLOB) ASC;"}, - {"lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface), + {"lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface) - 1, "PRAGMA main.table_xinfo('lsp_surface');", "SELECT project,rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM main.lsp_surface " "ORDER BY CAST(project AS BLOB) ASC,CAST(rel_path AS BLOB) ASC;"}, @@ -150,6 +152,14 @@ static const gd_table_t gd_coverage_meta_current = { "ignored_files_total,coverage_version,hash_records_complete,unresolved_calls_complete " "FROM main.index_coverage_meta ORDER BY CAST(project AS BLOB) ASC;"}; +/* The same for lsp_surface: index format 7 records the files each C-family + * file's #include lookup read (`included_files`). */ +static const gd_table_t gd_lsp_surface_current = { + "lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface), + "PRAGMA main.table_xinfo('lsp_surface');", + "SELECT project,rel_path,surface_sha,defs_json,ref_bloom,config_ctx,included_files " + "FROM main.lsp_surface ORDER BY CAST(project AS BLOB) ASC,CAST(rel_path AS BLOB) ASC;"}; + #undef GD_B #undef GD_N #undef GD_T @@ -168,11 +178,28 @@ typedef struct { bool have_uid; bool have_counter; bool have_unresolved_completeness; + bool have_included_files; } gd_context_t; static const gd_table_t *gd_table(const gd_context_t *g, int index) { - return index == GD_COVERAGE_META && g->have_unresolved_completeness ? &gd_coverage_meta_current - : &gd_tables[index]; + if (index == GD_COVERAGE_META && g->have_unresolved_completeness) { + return &gd_coverage_meta_current; + } + if (index == GD_LSP_SURFACE && g->have_included_files) { + return &gd_lsp_surface_current; + } + return &gd_tables[index]; +} + +/* The newest schema a table may have, when it has a legacy one too. */ +static const gd_table_t *gd_current_table(const gd_table_t *table) { + if (table == &gd_tables[GD_COVERAGE_META]) { + return &gd_coverage_meta_current; + } + if (table == &gd_tables[GD_LSP_SURFACE]) { + return &gd_lsp_surface_current; + } + return NULL; } typedef struct { @@ -460,9 +487,8 @@ static bool gd_column_schema(gd_context_t *g, const gd_column_t *expected) { static bool gd_columns(gd_context_t *g, const gd_table_t *table) { bool seen[GD_MAX_COLUMNS] = {false}; - bool coverage_meta = table == &gd_tables[GD_COVERAGE_META]; - int allowed_columns = - coverage_meta ? gd_coverage_meta_current.column_count : table->column_count; + const gd_table_t *current = gd_current_table(table); + int allowed_columns = current ? current->column_count : table->column_count; if (!gd_prepare(g, table->column_query)) { return false; } @@ -498,9 +524,12 @@ static bool gd_columns(gd_context_t *g, const gd_table_t *table) { return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA); } } - if (coverage_meta) { + if (table == &gd_tables[GD_COVERAGE_META]) { g->have_unresolved_completeness = seen[table->column_count]; } + if (table == &gd_tables[GD_LSP_SURFACE]) { + g->have_included_files = seen[table->column_count]; + } return gd_finalize(g); } diff --git a/tests/test_index_format.c b/tests/test_index_format.c index b94467b01..842e25b8a 100644 --- a/tests/test_index_format.c +++ b/tests/test_index_format.c @@ -568,6 +568,89 @@ TEST(index_format_v5_scala_packages_rebuild) { PASS(); } +/* Format 6 recorded no included files on its lsp_surface rows (#2993). An + * incremental refresh re-extracts the includers of a changed header from that + * record, so a format-6 index refreshed in place would keep an includer's + * edges stale after an edit to its header alone. */ +static const RFile k_include_files[] = { + {"lib/m.h", "#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n"}, + {"lib/a.c", + "#define A_LOCAL 1\n#include \"m.h\"\n\nvoid caller(int v) {\n DO_WORK(v);\n}\n"}, + {"lib/t.c", "void real_target(int x) { (void)x; }\nvoid other_target(int x) { (void)x; }\n"}, +}; + +/* CALLS edges from the function `caller` to the Function `target`. */ +static int include_caller_calls(cbm_store_t *s, const char *target) { + char sql[512]; + snprintf(sql, sizeof(sql), + "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON " + "t.id=e.target_id WHERE e.type='CALLS' AND s.name='caller' AND t.name='%s' AND " + "t.label='Function'", + target); + sqlite3_stmt *st = NULL; + if (sqlite3_prepare_v2(cbm_store_get_db(s), sql, -1, &st, NULL) != SQLITE_OK) { + return -1; + } + int count = sqlite3_step(st) == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1; + sqlite3_finalize(st); + return count; +} + +static int include_rows_recorded(cbm_store_t *s) { + sqlite3_stmt *st = NULL; + if (sqlite3_prepare_v2(cbm_store_get_db(s), + "SELECT COUNT(*) FROM lsp_surface WHERE included_files <> ''", -1, &st, + NULL) != SQLITE_OK) { + return -1; + } + int count = sqlite3_step(st) == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1; + sqlite3_finalize(st); + return count; +} + +TEST(index_format_v6_included_files_rebuild) { + RProj lp; + cbm_store_t *q0 = rh_index_files(&lp, k_include_files, 3); + ASSERT_NOT_NULL(q0); + ASSERT_EQ(include_caller_calls(q0, "real_target"), 1); + ASSERT_EQ(include_rows_recorded(q0), 1); + cbm_store_close(q0); + + /* The old shape: no row records the files its lookup read. */ + cbm_store_t *w = cbm_store_open_path(lp.dbpath); + ASSERT_NOT_NULL(w); + ASSERT_EQ(sqlite3_exec(cbm_store_get_db(w), "UPDATE lsp_surface SET included_files = ''", NULL, + NULL, NULL), + SQLITE_OK); + ASSERT_EQ(cbm_store_set_format_version(w, 6), CBM_STORE_OK); + cbm_store_close(w); + + /* Only the header changes. */ + char path[700]; + snprintf(path, sizeof(path), "%s/lib/m.h", lp.tmpdir); + FILE *fp = fopen(path, "wb"); + ASSERT_NOT_NULL(fp); + fputs("#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n", fp); + fclose(fp); + + char *resp = index_capture(&lp); + ASSERT_NOT_NULL(resp); + free(resp); + cbm_store_t *r = cbm_store_open_path(lp.dbpath); + ASSERT_NOT_NULL(r); + ASSERT_EQ(include_caller_calls(r, "other_target"), 1); + ASSERT_EQ(include_caller_calls(r, "real_target"), 0); + if (!strstr(g_log_buf, "format_change_reindex")) { + FAIL("a format-6 index was not routed through the full-reindex path"); + } + ASSERT_EQ(include_rows_recorded(r), 1); + int format = -1; + ASSERT_EQ(cbm_store_get_format_version(r, &format), CBM_STORE_OK); + ASSERT_EQ(format, CBM_INDEX_FORMAT_VERSION); + rh_cleanup(&lp, r); + PASS(); +} + SUITE(index_format) { RUN_TEST(index_format_siblings_distinct_and_searchable); RUN_TEST(index_format_legacy_index_rebuilds_and_repairs); @@ -575,4 +658,5 @@ SUITE(index_format) { RUN_TEST(index_format_swift_collisions_and_stale_calls_rebuild); RUN_TEST(index_format_v2_images_rebuild_without_invented_host); RUN_TEST(index_format_v5_scala_packages_rebuild); + RUN_TEST(index_format_v6_included_files_rebuild); } diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 191a3bcba..43a429057 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -35714,7 +35714,102 @@ TEST(pipeline_c_include_lookup_stays_in_repo_root) { PASS(); } +/* #2993: a C file's graph depends on the in-tree headers its includes read, + * so an edit to a header alone changes its includers' graphs. lib/a.c + * includes lib/m.h directly, lib/b.c through lib/mid.h; only lib/m.h's macro + * changes. The incremental refresh (closure repair) must re-extract both + * includers and give the graph a fresh full index gives. 60 filler files take + * the fixture past MIN_FILES_FOR_PARALLEL, so the fresh full index resolves + * calls on the same parallel path as the repair: the sequential path writes + * the same CALLS properties in another key order. */ +TEST(pipeline_c_header_edit_refreshes_includers_incrementally) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s/cbm_incedit_XXXXXX", cbm_tmpdir()); + ASSERT_NOT_NULL(cbm_mkdtemp(tmp)); + char root[512]; + snprintf(root, sizeof(root), "%s/repo", tmp); + write_temp_file(root, "lib/m.h", + "#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n"); + write_temp_file(root, "lib/mid.h", "#ifndef MID_H\n#define MID_H\n#include \"m.h\"\n#endif\n"); + write_temp_file(root, "lib/a.c", + "#define A_LOCAL 1\n" + "#include \"m.h\"\n" + "\n" + "void caller_a(int v) {\n" + " DO_WORK(v);\n" + "}\n"); + write_temp_file(root, "lib/b.c", + "#define B_LOCAL 1\n" + "#include \"mid.h\"\n" + "\n" + "void caller_b(int v) {\n" + " DO_WORK(v);\n" + "}\n"); + write_temp_file(root, "lib/t.c", + "void real_target(int x) { (void)x; }\n" + "void other_target(int x) { (void)x; }\n"); + write_temp_file(root, "lib/u.c", "int unrelated(void) { return 1; }\n"); + for (int i = 0; i < 60; i++) { + char name[64]; + char body[96]; + snprintf(name, sizeof(name), "fill/fill_%02d.c", i); + snprintf(body, sizeof(body), "int fill_%02d(void) { return %d; }\n", i, i); + write_temp_file(root, name, body); + } + char db[512]; + char fresh_db[512]; + snprintf(db, sizeof(db), "%s/graph.db", tmp); + snprintf(fresh_db, sizeof(fresh_db), "%s/fresh.db", tmp); + int rc_full = inc_root_index_from(root, db, root); + int before_a = inc_root_calls(db, "caller_a", "real_target"); + + write_temp_file(root, "lib/m.h", + "#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n"); + cbm_pipeline_incremental_test_reset_faults(); + int rc_incr = inc_root_index_from(root, db, root); + cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route(); + int rc_fresh = inc_root_index_from(root, fresh_db, root); + + int incr_rows = 0; + int fresh_rows = 0; + uint64_t incr_digest = inc_root_graph_digest(db, &incr_rows); + uint64_t fresh_digest = inc_root_graph_digest(fresh_db, &fresh_rows); + unsigned char incr_content[32] = {0}; + unsigned char fresh_content[32] = {1}; + cbm_store_t *incr_store = cbm_store_open_path(db); + cbm_store_t *fresh_store = cbm_store_open_path(fresh_db); + bool contents_read = + incr_store && fresh_store && + cbm_store_graph_content_digest(incr_store, "incroot", incr_content) == CBM_STORE_OK && + cbm_store_graph_content_digest(fresh_store, "incroot", fresh_content) == CBM_STORE_OK; + cbm_store_close(incr_store); + cbm_store_close(fresh_store); + static const char *const callers[] = {"caller_a", "caller_b"}; + int wrong = 0; + for (size_t i = 0; i < sizeof(callers) / sizeof(callers[0]); i++) { + int now = inc_root_calls(db, callers[i], "other_target"); + int stale = inc_root_calls(db, callers[i], "real_target"); + if (now != 1 || stale != 0) { + printf(" %s: other_target %d, real_target %d\n", callers[i], now, stale); + wrong++; + } + } + th_rmtree(tmp); + ASSERT_EQ(rc_full, 0); + ASSERT_EQ(before_a, 1); + ASSERT_EQ(rc_incr, 0); + ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(rc_fresh, 0); + ASSERT_EQ(wrong, 0); + ASSERT_EQ(incr_rows, fresh_rows); + ASSERT(incr_digest == fresh_digest); + ASSERT(contents_read); + ASSERT(memcmp(incr_content, fresh_content, sizeof(incr_content)) == 0); + PASS(); +} + SUITE(pipeline) { + RUN_TEST(pipeline_c_header_edit_refreshes_includers_incrementally); RUN_TEST(pipeline_c_include_lookup_uses_repo_root); RUN_TEST(pipeline_c_include_error_keeps_expansion_without_includes); RUN_TEST(pipeline_c_header_body_stays_with_the_header); From fc263770fc71dc06f70bffa7c16e0ce50719c4ba Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 04:19:57 +0100 Subject: [PATCH 05/25] feat(lsp): resolve declared types once, in the scope that wrote them A definition's declared types travel to other files as source text, and the Go and Python cross registrars qualified that text against the defining module only: a type the defining file imported from a third file became `.`, a name nobody registered, and every call through it was lost. A shared step (src/pipeline/type_scope.{h,c}) resolves every type name a definition's return, parameter and field texts write once, in the scope of the file that wrote it: the file's own module, then what its imports bind (the LSP import map). A name gets an identity only when that scope gives exactly one answer and the answer is a project definition of a type label the engine registers. One description row per language (Go, Python): - An import that names no project definition is no answer (`Self` from typing, `logging.Logger`), and neither is a path a package re-exports: the step cannot prove one through the engine's export fold. - Go imports bind packages: a bare name never resolves through one, and an own-module name is left to the engine, so a type parameter cannot take an identity. - Python looks a name up in the def's own scopes first: a def inside a function gets none, and so does a name its enclosing class body declares, a PEP 695 type parameter of the file (new extraction field CBMDefinition.type_params), a name the module binds more than once (its ordered namespace facts: an import and a TypeVar, two imports), and any name of a module with a star import or a parse error. Identities ride on CBMLSPDef.type_scope ("spelling=QN|..."), are stored in the LSP surface row ("ty", codec version 5) for the routes that do not re-extract a file, and are left out of the surface hash and the Python namespace comparison: a body edit stays a one-file repair. An identity also depends on other files' type definitions; the closure planner declines when a changed file gains a type definition, or when a type some stored identity names changes or leaves its file (cbm_lsp_surface_identity_decline), so the depth-1 closure stays exact. The Go and Python registrars read identities through a per-def index (cbm_type_scope_index / cbm_type_scope_find: one hash probe per lookup), and the per-file selection follows them to the declaring modules, walking each module once. Every loop the step adds has a counted-work growth test. Signed-off-by: Martin Vogel --- Makefile.cbm | 3 +- internal/cbm/cbm.h | 6 + internal/cbm/extract_defs.c | 53 ++ internal/cbm/lsp/go_lsp.c | 62 +- internal/cbm/lsp/go_lsp.h | 5 + internal/cbm/lsp/py_lsp.c | 31 +- internal/cbm/lsp/type_rep.c | 98 +++ internal/cbm/lsp/type_rep.h | 19 + internal/cbm/result_compact.c | 1 + src/pipeline/lsp_surface.c | 302 ++++++- src/pipeline/lsp_surface.h | 28 +- src/pipeline/pass_lsp_cross.c | 179 +++- src/pipeline/pass_lsp_cross.h | 6 + src/pipeline/pipeline.c | 2 +- src/pipeline/pipeline_incremental.c | 63 +- src/pipeline/pipeline_internal.h | 10 + src/pipeline/type_scope.c | 676 +++++++++++++++ src/pipeline/type_scope.h | 130 +++ tests/test_main.c | 4 + tests/test_pipeline.c | 28 +- tests/test_type_scope.c | 1212 +++++++++++++++++++++++++++ 21 files changed, 2828 insertions(+), 90 deletions(-) create mode 100644 src/pipeline/type_scope.c create mode 100644 src/pipeline/type_scope.h create mode 100644 tests/test_type_scope.c diff --git a/Makefile.cbm b/Makefile.cbm index 66cccffe2..8e19fcac0 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -532,6 +532,7 @@ PIPELINE_SRCS = \ src/pipeline/pass_calls.c \ src/pipeline/pass_spawns.c \ src/pipeline/pass_lsp_cross.c \ + src/pipeline/type_scope.c \ src/pipeline/pass_usages.c \ src/pipeline/pass_semantic.c \ src/pipeline/pass_tests.c \ @@ -870,7 +871,7 @@ TEST_DISCOVER_SRCS = \ TEST_GRAPH_BUFFER_SRCS = tests/test_graph_buffer.c -TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c +TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c TEST_WATCHER_SRCS = tests/test_watcher.c tests/test_svn_state.c diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index de1cc03f9..8a4f9005a 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -328,6 +328,12 @@ typedef struct { * for a defined type `type A B` (its method set is its own) and in every * other language. Tail field: zero-init stays valid. */ const char *alias_target; + /* Python only: the names a PEP 695 type parameter list declares + * (`def f[T, *Ts, **P]`, `class C[T]`), '|'-joined. The cross-file type + * step keeps them from taking a real type's identity (type_scope.h); never + * written to the graph. NULL when none and in every other language. Tail + * field: zero-init stays valid. */ + const char *type_params; } CBMDefinition; /* extra_props key of a generated member, one the compiler writes and the diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 585f93db4..75885e076 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -6939,6 +6939,50 @@ static bool make_rule_sets_variable(TSNode rule, const char *src) { (strchr("+?!", src[p]) && p + SKIP_ONE < end && src[p + SKIP_ONE] == '=')); } +/* Python: the names a PEP 695 type parameter list declares on a function or + * class definition (`def f[T, *Ts, **P]`, `class C[T: Base]`), '|'-joined, or + * NULL. Each parameter is a `type` whose first identifier is its name. */ +static TSNode py_type_param_ident(TSNode param) { + while (!ts_node_is_null(param) && strcmp(ts_node_type(param), "identifier") != 0) { + param = ts_node_named_child_count(param) ? ts_node_named_child(param, 0) : (TSNode){0}; + } + return param; +} + +static const char *py_type_param_names(CBMArena *a, TSNode node, const char *source) { + if (strcmp(ts_node_type(node), "decorated_definition") == 0) { + node = ts_node_child_by_field_name(node, TS_FIELD("definition")); + } + TSNode list = ts_node_is_null(node) + ? node + : ts_node_child_by_field_name(node, TS_FIELD("type_parameters")); + uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list); + size_t total = 0; /* every name plus one separator or the terminator */ + for (uint32_t i = 0; i < n; i++) { + TSNode id = py_type_param_ident(ts_node_named_child(list, i)); + total += ts_node_is_null(id) ? 0 : ts_node_end_byte(id) - ts_node_start_byte(id) + 1; + } + char *out = total ? (char *)cbm_arena_alloc(a, total) : NULL; + if (!out) { + return NULL; + } + size_t at = 0; + for (uint32_t i = 0; i < n; i++) { + TSNode id = py_type_param_ident(ts_node_named_child(list, i)); + if (ts_node_is_null(id)) { + continue; + } + if (at) { + out[at++] = '|'; + } + size_t len = ts_node_end_byte(id) - ts_node_start_byte(id); + memcpy(out + at, source + ts_node_start_byte(id), len); + at += len; + } + out[at] = '\0'; + return at ? out : NULL; +} + /* Make: a rule names several targets (`up down: deps`), each a goal * `make ` runs. The rule's definition carries the first target; * every further one gets a definition of its own over the same rule span -- @@ -7250,6 +7294,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec // Decorators + route extraction from decorator AST def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec); extract_route_from_decorators(a, node, ctx->source, spec, &def.route_path, &def.route_method); + if (ctx->language == CBM_LANG_PYTHON) { + def.type_params = py_type_param_names(a, node, ctx->source); + } // Rust: cfg-gated twins (#[cfg(windows)] fn f / #[cfg(not(windows))] fn f) // keep the plain QN: they are variants of ONE definition, and the graph @@ -8973,6 +9020,9 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s } def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec); def.docstring = extract_docstring(ctx, node, name); + if (ctx->language == CBM_LANG_PYTHON) { + def.type_params = py_type_param_names(a, node, ctx->source); + } cbm_defs_push(&ctx->result->defs, a, def); @@ -9497,6 +9547,9 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node, def.decorators = extract_decorators(a, child, ctx->source, ctx->language, spec); extract_route_from_decorators(a, child, ctx->source, spec, &def.route_path, &def.route_method); + if (ctx->language == CBM_LANG_PYTHON) { + def.type_params = py_type_param_names(a, child, ctx->source); + } const char *client_path = NULL; const char *client_method = NULL; /* Retrofit services must be interfaces; Pippo and Rapidoid put the path in diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 6e4aa81a1..76f6f7770 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -2171,18 +2171,23 @@ void go_lsp_process_file(GoLSPContext *ctx, TSNode root) { // --- Helper: parse Go return type text into CBMType --- -const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const char *module_qn) { +/* scope_ix: the defining def's resolved type identities (CBMLSPDef.type_scope, + * indexed), NULL when it has none. A named type the scope knows is that + * identity; any other named type keeps the module qualification. */ +static const CBMType *go_parse_type_text_scoped(CBMArena *a, const char *text, + const char *module_qn, + const cbm_type_scope_index_t *scope_ix) { if (!text || !text[0]) return cbm_type_unknown(); // Pointer: *Foo if (text[0] == '*') { - return cbm_type_pointer(a, cbm_parse_return_type_text(a, text + 1, module_qn)); + return cbm_type_pointer(a, go_parse_type_text_scoped(a, text + 1, module_qn, scope_ix)); } // Slice: []Foo if (text[0] == '[' && text[1] == ']') { - return cbm_type_slice(a, cbm_parse_return_type_text(a, text + 2, module_qn)); + return cbm_type_slice(a, go_parse_type_text_scoped(a, text + 2, module_qn, scope_ix)); } // Builtin types @@ -2195,19 +2200,30 @@ const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const c return cbm_type_builtin(a, text); } + // Named type the defining file's scope resolved (`pkg.T` through its import). + const char *scoped = cbm_type_scope_find(scope_ix, text, strlen(text)); + if (scoped) { + return cbm_type_named(a, scoped); + } + // Named type: assume local to module return cbm_type_named(a, cbm_arena_sprintf(a, "%s.%s", module_qn, text)); } +const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const char *module_qn) { + return go_parse_type_text_scoped(a, text, module_qn, NULL); +} + typedef struct { const char *module_qn; + const cbm_type_scope_index_t *scope_ix; /* the def's resolved type identities, or NULL */ } CBMGoLSPSignatureParserContext; static const CBMType *cbm_go_lsp_parse_signature_param_text(CBMArena *arena, const char *text, void *parser_ctx) { const CBMGoLSPSignatureParserContext *ctx = (const CBMGoLSPSignatureParserContext *)parser_ctx; const char *module_qn = ctx && ctx->module_qn ? ctx->module_qn : ""; - return cbm_parse_return_type_text(arena, text, module_qn); + return go_parse_type_text_scoped(arena, text, module_qn, ctx ? ctx->scope_ix : NULL); } // --- Shared Go stdlib registry --- @@ -2682,8 +2698,10 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, // --- Cross-file LSP: parse source, build registry from defs, run LSP --- -// Helper: split "|"-separated string into array of CBMType*. -static const CBMType **split_pipe_types(CBMArena *a, const char *text, const char *module_qn) { +// Helper: split "|"-separated string into array of CBMType*. scope_ix: the +// defining def's resolved type identities (go_parse_type_text_scoped). +static const CBMType **split_pipe_types(CBMArena *a, const char *text, const char *module_qn, + const cbm_type_scope_index_t *scope_ix) { if (!text || !text[0]) return NULL; @@ -2708,7 +2726,7 @@ static const CBMType **split_pipe_types(CBMArena *a, const char *text, const cha char save = *p; *p = '\0'; if (start[0]) { - arr[idx++] = cbm_parse_return_type_text(a, start, module_qn); + arr[idx++] = go_parse_type_text_scoped(a, start, module_qn, scope_ix); } if (save == '\0') break; @@ -2780,7 +2798,8 @@ static const char *go_alias_target_qn(CBMArena *arena, const char *target, /* Parse "name:type|name:type" into NULL-terminated name/type arrays. False when * nothing parsed (or on allocation failure): the type keeps no field info. */ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char *def_module_qn, - const char ***names_out, const CBMType ***types_out) { + const cbm_type_scope_index_t *scope_ix, const char ***names_out, + const CBMType ***types_out) { // Count fields int count = 1; @@ -2815,7 +2834,7 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char if (colon && idx < count) { *colon = '\0'; names[idx] = cbm_arena_strdup(arena, start); - types[idx] = cbm_parse_return_type_text(arena, colon + 1, def_module_qn); + types[idx] = go_parse_type_text_scoped(arena, colon + 1, def_module_qn, scope_ix); idx++; } if (save == '\0') @@ -2831,12 +2850,13 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char } static void parse_field_defs_into_type(CBMArena *arena, CBMTypeRegistry *reg, const char *type_qn, - const char *field_defs, const char *def_module_qn) { + const char *field_defs, const char *def_module_qn, + const cbm_type_scope_index_t *scope_ix) { if (!field_defs || !field_defs[0] || !type_qn) return; const char **names = NULL; const CBMType **types = NULL; - if (parse_field_defs(arena, field_defs, def_module_qn, &names, &types)) { + if (parse_field_defs(arena, field_defs, def_module_qn, scope_ix, &names, &types)) { // Find the registered type and update field info for (int ti = 0; ti < reg->type_count; ti++) { if (reg->types[ti].qualified_name && @@ -3364,6 +3384,8 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, continue; const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn; + /* The def's declared-type identities, indexed once for its texts. */ + const cbm_type_scope_index_t *scope_ix = cbm_type_scope_index(arena, d->type_scope); // Every type-like container (Type/Class/Struct/Interface/Enum/Trait). // Struct included so Go structs (now labelled "Struct") register as types. @@ -3385,7 +3407,8 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // Populate struct field types from field_defs if (d->field_defs && d->field_defs[0]) { - parse_field_defs_into_type(arena, ®, rt.qualified_name, d->field_defs, def_mod); + parse_field_defs_into_type(arena, ®, rt.qualified_name, d->field_defs, def_mod, + scope_ix); } } @@ -3397,8 +3420,8 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, rf.short_name = d->short_name; // borrowed // Build FUNC type from return_types text - const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod); - CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod}; + const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod, scope_ix); + CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod, scope_ix}; const CBMType **param_types = cbm_type_materialize_signature_params( arena, d->signature_param_types, d->signature_param_count, cbm_go_lsp_parse_signature_param_text, ¶m_parser_ctx); @@ -3666,6 +3689,8 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * (set by cbm_pxc_collect_all_defs). There is no caller module to * fall back to — this registry is project-wide, not per-file. */ const char *def_mod = d->def_module_qn ? d->def_module_qn : ""; + /* The def's declared-type identities, indexed once for its texts. */ + const cbm_type_scope_index_t *scope_ix = cbm_type_scope_index(arena, d->type_scope); // Every type-like container (Type/Class/Struct/Interface/Enum/Trait). // Struct included so Go structs (now labelled "Struct") register as types. @@ -3687,13 +3712,14 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i const char **names = NULL; const CBMType **types = NULL; uintptr_t at = (uintptr_t)cbm_ht_get(first_type, rt.qualified_name); - if (parse_field_defs(arena, d->field_defs, def_mod, &names, &types) && at) { + if (parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &names, &types) && + at) { reg->types[at - 1].field_names = names; reg->types[at - 1].field_types = types; } } else { parse_field_defs_into_type(arena, reg, rt.qualified_name, d->field_defs, - def_mod); + def_mod, scope_ix); } } } @@ -3703,8 +3729,8 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i memset(&rf, 0, sizeof(rf)); rf.qualified_name = d->qualified_name; /* borrowed */ rf.short_name = d->short_name; - const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod); - CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod}; + const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod, scope_ix); + CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod, scope_ix}; const CBMType **param_types = cbm_type_materialize_signature_params( arena, d->signature_param_types, d->signature_param_count, cbm_go_lsp_parse_signature_param_text, ¶m_parser_ctx); diff --git a/internal/cbm/lsp/go_lsp.h b/internal/cbm/lsp/go_lsp.h index 6724f186a..fc612cfef 100644 --- a/internal/cbm/lsp/go_lsp.h +++ b/internal/cbm/lsp/go_lsp.h @@ -111,6 +111,11 @@ typedef struct { * by the registrar against def_module_qn like return_types. NULL = not an * identity alias. */ const char *alias_target; + /* Identities of the type names this def's declared types write, resolved + * once in the scope of the file that wrote them (src/pipeline/type_scope.h): + * "spelling=QN|spelling=QN". Read with cbm_type_scope_find (type_rep.h). + * NULL = no name needs one; the engine then qualifies as before. */ + const char *type_scope; } CBMLSPDef; // Parse source, build registry from defs + stdlib, run LSP. diff --git a/internal/cbm/lsp/py_lsp.c b/internal/cbm/lsp/py_lsp.c index 8e745c23f..5f348cb72 100644 --- a/internal/cbm/lsp/py_lsp.c +++ b/internal/cbm/lsp/py_lsp.c @@ -4420,6 +4420,12 @@ static const char **py_split_subscript_args(CBMArena *arena, const char *s, int return out; } +/* The resolved type identities of the cross-file def whose annotations are + * being parsed (CBMLSPDef.type_scope, resolved once in the scope of the module + * that wrote them, indexed). Bound by py_register_lsp_defs around one def's + * texts only; NULL for every parse of the walked file's own source. */ +static _Thread_local const cbm_type_scope_index_t *g_py_type_scope; + static const CBMType *py_parse_type_text_qn(CBMArena *arena, const char *ann, const char *module_qn) { if (!ann || !ann[0]) @@ -4575,6 +4581,11 @@ static const CBMType *py_parse_type_text_qn(CBMArena *arena, const char *ann, return cbm_type_builtin(arena, ann); } } + // A name the defining module's scope resolved (its import, or its own class). + const char *scoped = cbm_type_scope_find(g_py_type_scope, ann, strlen(ann)); + if (scoped) { + return cbm_type_named(arena, scoped); + } // Bare unqualified name: qualify with module_qn if it doesn't already // contain a dot. Skips obvious typing-module names so `Optional` / // `Self` / etc. don't end up qualified to the consumer's module. @@ -6453,9 +6464,20 @@ static bool py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe rf.short_name = d->short_name; py_register_func_decorators(&rf, d->decorators); - // Build FUNC type from "|"-separated return types. - const char **ret_strs = py_split_pipe(arena, d->return_types); + /* this def's annotations only */ + g_py_type_scope = cbm_type_scope_index(arena, d->type_scope); + // Build FUNC type from "|"-separated return types. A def whose + // annotations carry resolved identities is one annotation, parsed + // as the per-file registrar parses it (`T | None` is a union). + const char **ret_strs = g_py_type_scope ? NULL : py_split_pipe(arena, d->return_types); const CBMType **ret_types = NULL; + if (g_py_type_scope && d->return_types && d->return_types[0]) { + ret_types = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *)); + if (ret_types) { + ret_types[0] = py_parse_type_text_qn(arena, d->return_types, NULL); + ret_types[1] = NULL; + } + } if (ret_strs) { int n = 0; while (ret_strs[n]) @@ -6473,12 +6495,15 @@ static bool py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe /* Fallback definitions can be mixed-language. Only authoritative * Python metadata opts into package scope normalization. */ if (d->lang == CBM_LANG_PYTHON && - !py_symbol_scope(arena, d->def_module_qn, "register", &symbol_scope)) + !py_symbol_scope(arena, d->def_module_qn, "register", &symbol_scope)) { + g_py_type_scope = NULL; return false; + } PySignatureParamParserContext parser_ctx = {.module_qn = symbol_scope}; const CBMType **param_types = cbm_type_materialize_signature_params( arena, d->signature_param_types, d->signature_param_count, py_signature_param_type_adapter, &parser_ctx); + g_py_type_scope = NULL; rf.signature = cbm_type_func(arena, NULL, param_types, ret_types); if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) { diff --git a/internal/cbm/lsp/type_rep.c b/internal/cbm/lsp/type_rep.c index afc5b0d52..6e10980a1 100644 --- a/internal/cbm/lsp/type_rep.c +++ b/internal/cbm/lsp/type_rep.c @@ -1,4 +1,5 @@ #include "type_rep.h" +#include #include #include @@ -963,3 +964,100 @@ const CBMType *cbm_type_substitute(CBMArena *a, const CBMType *t, const char **t return t; } } + +/* ── Declared-type identities of one definition ─────────────────── */ + +typedef struct { + const char *name; /* spelling, NUL-terminated copy */ + size_t len; + const char *qn; /* NUL-terminated copy */ +} cbm_type_scope_entry_t; + +struct cbm_type_scope_index { + cbm_type_scope_entry_t *slots; /* open addressing, power-of-two size */ + uint32_t mask; +}; + +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_type_scope_index_work; +uint64_t cbm_type_scope_index_test_work(void) { + return atomic_load_explicit(&g_type_scope_index_work, memory_order_relaxed); +} +#define TYPE_SCOPE_INDEX_WORK(n) \ + atomic_fetch_add_explicit(&g_type_scope_index_work, (uint64_t)(n), memory_order_relaxed) +#else +#define TYPE_SCOPE_INDEX_WORK(n) ((void)0) +#endif + +static uint32_t type_scope_hash(const char *s, size_t len) { + uint32_t h = 2166136261u; + for (size_t i = 0; i < len; i++) { + h = (h ^ (unsigned char)s[i]) * 16777619u; + } + return h; +} + +const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope) { + if (!a || !scope || !scope[0]) { + return NULL; + } + size_t n = strlen(scope); + TYPE_SCOPE_INDEX_WORK(n); + uint32_t entries = 1; + for (size_t i = 0; i < n; i++) { + entries += scope[i] == '|'; + } + uint32_t size = 4; + while (size < entries * 2) { + size *= 2; + } + char *copy = cbm_arena_strndup(a, scope, n); + cbm_type_scope_index_t *ix = (cbm_type_scope_index_t *)cbm_arena_alloc(a, sizeof(*ix)); + cbm_type_scope_entry_t *slots = + (cbm_type_scope_entry_t *)cbm_arena_alloc(a, (size_t)size * sizeof(*slots)); + if (!copy || !ix || !slots) { + return NULL; + } + memset(slots, 0, (size_t)size * sizeof(*slots)); + ix->slots = slots; + ix->mask = size - 1; + for (char *p = copy; p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *eq = strchr(p, '='); + if (eq && eq > p && eq[1]) { + *eq = '\0'; + size_t len = (size_t)(eq - p); + uint32_t at = type_scope_hash(p, len) & ix->mask; + while (slots[at].name && + !(slots[at].len == len && memcmp(slots[at].name, p, len) == 0)) { + TYPE_SCOPE_INDEX_WORK(1); + at = (at + 1) & ix->mask; + } + if (!slots[at].name) { /* the first entry of a spelling stands */ + slots[at] = (cbm_type_scope_entry_t){.name = p, .len = len, .qn = eq + 1}; + } + } + p = bar ? bar + 1 : NULL; + } + return ix; +} + +const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *name, + size_t name_len) { + if (!ix || !name || name_len == 0) { + return NULL; + } + TYPE_SCOPE_INDEX_WORK(name_len); + uint32_t at = type_scope_hash(name, name_len) & ix->mask; + while (ix->slots[at].name) { + TYPE_SCOPE_INDEX_WORK(1); + if (ix->slots[at].len == name_len && memcmp(ix->slots[at].name, name, name_len) == 0) { + return ix->slots[at].qn; + } + at = (at + 1) & ix->mask; + } + return NULL; +} diff --git a/internal/cbm/lsp/type_rep.h b/internal/cbm/lsp/type_rep.h index a32e7812a..db2b8b6d6 100644 --- a/internal/cbm/lsp/type_rep.h +++ b/internal/cbm/lsp/type_rep.h @@ -235,4 +235,23 @@ const CBMType* cbm_type_resolve_alias(const CBMType* t); const CBMType* cbm_type_substitute(CBMArena* a, const CBMType* t, const char** type_params, const CBMType** type_args); +// The identities of the type names one definition's declared types write +// ("spelling=QN|spelling=QN", CBMLSPDef.type_scope, resolved once in the scope +// of the file that wrote it by the pipeline's type-scope step), indexed once +// per definition so each lookup is a hash probe. NULL for a NULL or empty +// scope (or on allocation failure: the engine then qualifies as before). +typedef struct cbm_type_scope_index cbm_type_scope_index_t; +const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope); + +// The identity of one spelling exactly as the type text writes it (name_len +// bytes): the QN (owned by the index's arena), or NULL when the def has none +// for it (the engine then qualifies as before). NULL index = none. +const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *name, + size_t name_len); + +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +// Work counter for the growth tests: bytes hashed and slots probed. +uint64_t cbm_type_scope_index_test_work(void); +#endif + #endif // CBM_LSP_TYPE_REP_H diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index b8b70da46..9866c79ff 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -282,6 +282,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) { cr_str(c, &d->decl_namespace); cr_str(c, &d->variant_key); cr_str(c, &d->alias_target); + cr_str(c, &d->type_params); } static void cr_walk_call(cr_ctx_t *c, CBMCall *call) { diff --git a/src/pipeline/lsp_surface.c b/src/pipeline/lsp_surface.c index 20b16e5e3..5d1bd5599 100644 --- a/src/pipeline/lsp_surface.c +++ b/src/pipeline/lsp_surface.c @@ -32,15 +32,24 @@ #include "foundation/log.h" #include "foundation/mem_core.h" #include "foundation/sha256.h" -#include "pipeline/doc_links.h" /* cbm_doclinks_storable_scope */ +#include "pipeline/doc_links.h" /* cbm_doclinks_storable_scope */ +#include "pipeline/type_scope.h" /* the type labels identities may name */ #include "pipeline/worker_pool.h" #include "yyjson/yyjson.h" /* 3: Go defs carry their parsed result list `|`-joined in "ret" (F-G8 D1); * a version-2 surface holds the raw result text and must be re-extracted. * 4: Go identity aliases carry their target in "al" (#2033); a version-3 - * surface has no alias targets and must be re-extracted. */ -enum { SURFACE_CODEC_VERSION = 4 }; + * surface has no alias targets and must be re-extracted. + * 5: defs carry their declared types' identities in "ty" (type_scope.h); a + * version-4 surface has none, and a dependent re-resolved against it would + * lose the calls a full index makes through them. The surface hash and the + * Python namespace comparison leave "ty" out: they judge the identities' + * inputs (the def's type texts, the file's imports in "dl" / "py"), which + * the planner's probe computes exactly as a full index does; the outputs + * also depend on other files' type definitions, which the planner gates + * itself (closure_identity_decline, pipeline_incremental.c). */ +enum { SURFACE_CODEC_VERSION = 5 }; /* Labels the incremental name registry serves that pxc_map_label does NOT * carry into the CBMLSPDef set. Their (name, qn, label) triple must still @@ -328,6 +337,72 @@ int cbm_lsp_surface_python_namespace_from_json(CBMArena *arena, const char *json return status; } +/* Two objects equal member by member, in order, leaving out the members named + * `skip` (NULL skips none). */ +static bool surface_obj_equal_except(yyjson_val *a, yyjson_val *b, const char *skip) { + if (!yyjson_is_obj(a) || !yyjson_is_obj(b)) { + return yyjson_equals(a, b); + } + yyjson_obj_iter ia = yyjson_obj_iter_with(a); + yyjson_obj_iter ib = yyjson_obj_iter_with(b); + for (;;) { + yyjson_val *ka = yyjson_obj_iter_next(&ia); + while (ka && skip && yyjson_equals_str(ka, skip)) { + ka = yyjson_obj_iter_next(&ia); + } + yyjson_val *kb = yyjson_obj_iter_next(&ib); + while (kb && skip && yyjson_equals_str(kb, skip)) { + kb = yyjson_obj_iter_next(&ib); + } + if (!ka || !kb) { + return !ka && !kb; + } + if (!yyjson_equals(ka, kb) || + !yyjson_equals(yyjson_obj_iter_get_val(ka), yyjson_obj_iter_get_val(kb))) { + return false; + } + } +} + +/* Two surface rows equal but for their declared-type identities ("ty" in + * each "lsp" def), which the comparisons leave out (SURFACE_CODEC_VERSION). */ +static bool surface_rows_equal_without_identities(yyjson_val *a, yyjson_val *b) { + if (!yyjson_is_obj(a) || !yyjson_is_obj(b)) { + return yyjson_equals(a, b); + } + yyjson_obj_iter ia = yyjson_obj_iter_with(a); + yyjson_obj_iter ib = yyjson_obj_iter_with(b); + for (;;) { + yyjson_val *ka = yyjson_obj_iter_next(&ia); + yyjson_val *kb = yyjson_obj_iter_next(&ib); + if (!ka || !kb) { + return !ka && !kb; + } + if (!yyjson_equals(ka, kb)) { + return false; + } + yyjson_val *va = yyjson_obj_iter_get_val(ka); + yyjson_val *vb = yyjson_obj_iter_get_val(kb); + if (!yyjson_equals_str(ka, "lsp") || !yyjson_is_arr(va) || !yyjson_is_arr(vb)) { + if (!yyjson_equals(va, vb)) { + return false; + } + continue; + } + if (yyjson_arr_size(va) != yyjson_arr_size(vb)) { + return false; + } + yyjson_arr_iter da = yyjson_arr_iter_with(va); + yyjson_arr_iter db = yyjson_arr_iter_with(vb); + for (yyjson_val *x = yyjson_arr_iter_next(&da), *y = yyjson_arr_iter_next(&db); x && y; + x = yyjson_arr_iter_next(&da), y = yyjson_arr_iter_next(&db)) { + if (!surface_obj_equal_except(x, y, "ty")) { + return false; + } + } + } +} + int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) { if (!old_json) { return -1; @@ -349,9 +424,12 @@ int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) { : 0; int result = -1; if (old_state >= 0 && new_state >= 0) { - result = (old_state == 0 && new_state == 0) ? 0 - : (old_state != new_state || !new_json || strcmp(old_json, new_json) != 0) ? 1 - : 0; + result = (old_state == 0 && new_state == 0) ? 0 + : (old_state != new_state || !new_doc || + !surface_rows_equal_without_identities(yyjson_doc_get_root(old_doc), + yyjson_doc_get_root(new_doc))) + ? 1 + : 0; } cbm_arena_destroy(&scratch); yyjson_doc_free(old_doc); @@ -359,12 +437,185 @@ int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) { return result; } +/* ── Declared-type identities across a repair ─────────────────────── */ + +static bool surface_type_label(int lang, const char *label) { + const cbm_type_scope_lang_t *row = + lang >= 0 && lang < (int)CBM_LANG_COUNT ? cbm_type_scope_lang((CBMLanguage)lang) : NULL; + for (const char *const *l = row && label ? row->labels : NULL; l && *l; l++) { + if (strcmp(*l, label) == 0) { + return true; + } + } + return false; +} + +/* Hash one row's type definitions: QN -> its def object (both borrowed from + * the returned doc, which the caller frees). A row that does not parse + * returns NULL; the planner has validated every row it passes. */ +static yyjson_doc *surface_row_types(const char *json, CBMHashTable *types, uint64_t *work) { + yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL; + yyjson_val *lsp = doc ? yyjson_obj_get(yyjson_doc_get_root(doc), "lsp") : NULL; + if (!yyjson_is_arr(lsp)) { + return doc; + } + yyjson_arr_iter it = yyjson_arr_iter_with(lsp); + for (yyjson_val *d = yyjson_arr_iter_next(&it); d; d = yyjson_arr_iter_next(&it)) { + if (work) { + (*work)++; + } + const char *qn = yyjson_get_str(yyjson_obj_get(d, "qn")); + if (qn && + surface_type_label(yyjson_get_int(yyjson_obj_get(d, "lg")), + yyjson_get_str(yyjson_obj_get(d, "lb"))) && + !cbm_ht_get(types, qn)) { + cbm_ht_set(types, qn, d); + } + } + return doc; +} + +typedef struct { + const CBMHashTable *other; /* the row's types on the other side */ + CBMHashTable *gone; /* QNs whose type definition changed or left (owned keys) */ + bool appeared; +} surface_type_cmp_t; + +static void surface_type_appeared(const char *qn, void *val, void *ud) { + (void)val; + surface_type_cmp_t *c = (surface_type_cmp_t *)ud; + if (!cbm_ht_get(c->other, qn)) { + c->appeared = true; + } +} + +static void surface_type_changed(const char *qn, void *val, void *ud) { + surface_type_cmp_t *c = (surface_type_cmp_t *)ud; + yyjson_val *now = (yyjson_val *)cbm_ht_get(c->other, qn); + if ((now && surface_obj_equal_except((yyjson_val *)val, now, "ty")) || + cbm_ht_get(c->gone, qn)) { + return; + } + char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, strlen(qn) + 1); + if (key) { + memcpy(key, qn, strlen(qn) + 1); + cbm_ht_set(c->gone, key, key); + } +} + +static void surface_free_key(const char *key, void *val, void *ud) { + (void)val; + (void)ud; + cbm_free(CBM_MEM_CLASS_OTHER, (void *)key); +} + +/* True when one of the identities stored in `ty` ("spelling=QN|...") names a + * QN of `gone`. */ +static bool surface_names_gone(const char *ty, const CBMHashTable *gone, char **buf, size_t *cap, + uint64_t *work) { + for (const char *p = ty; p && *p;) { + const char *eq = strchr(p, '='); + if (!eq) { + return false; + } + const char *bar = strchr(eq, '|'); + size_t len = bar ? (size_t)(bar - eq - 1) : strlen(eq + 1); + if (work) { + *work += (uint64_t)(len + (size_t)(eq - p) + 1); + } + if (len + 1 > *cap) { + size_t grown_cap = (len + 1) * 2; + char *grown = cbm_realloc(CBM_MEM_CLASS_OTHER, *buf, grown_cap); + if (!grown) { + return true; /* cannot tell: decline */ + } + *buf = grown; + *cap = grown_cap; + } + memcpy(*buf, eq + 1, len); + (*buf)[len] = '\0'; + if (cbm_ht_get(gone, *buf)) { + return true; + } + p = bar ? bar + 1 : eq + 1 + len; + } + return false; +} + +const char *cbm_lsp_surface_identity_decline(const char *const *old_rows, + const char *const *new_rows, int changed_count, + const cbm_lsp_surface_row_t *stored, int stored_count, + uint64_t *work) { + const char *decline = NULL; + CBMHashTable *gone = cbm_ht_create(CBM_SZ_64); + if (!gone) { + return "alloc"; + } + for (int i = 0; i < changed_count && !decline; i++) { + CBMHashTable *before = cbm_ht_create(CBM_SZ_64); + CBMHashTable *after = cbm_ht_create(CBM_SZ_64); + yyjson_doc *old_doc = before ? surface_row_types(old_rows[i], before, work) : NULL; + yyjson_doc *new_doc = + after && new_rows[i] ? surface_row_types(new_rows[i], after, work) : NULL; + if (!before || !after) { + decline = "alloc"; + } else if (!old_doc || (new_rows[i] && !new_doc)) { + decline = "surface_row_unreadable"; + } else { + surface_type_cmp_t appear = {.other = before}; + cbm_ht_foreach(after, surface_type_appeared, &appear); + surface_type_cmp_t change = {.other = after, .gone = gone}; + cbm_ht_foreach(before, surface_type_changed, &change); + if (appear.appeared) { + decline = "declared_types_changed"; + } + } + yyjson_doc_free(old_doc); + yyjson_doc_free(new_doc); + cbm_ht_free(before); + cbm_ht_free(after); + } + /* A changed or departed type matters only when an identity names it: + * read the stored identities (only rows that hold one are parsed). */ + char *buf = NULL; + size_t cap = 0; + for (int r = 0; r < stored_count && !decline && cbm_ht_count(gone) > 0; r++) { + const char *json = stored[r].defs_json; + if (work && json) { + *work += (uint64_t)strlen(json); + } + if (!json || !strstr(json, "\"ty\":")) { + continue; + } + yyjson_doc *doc = yyjson_read(json, strlen(json), 0); + yyjson_val *lsp = doc ? yyjson_obj_get(yyjson_doc_get_root(doc), "lsp") : NULL; + if (!doc) { + decline = "surface_row_unreadable"; + } + yyjson_arr_iter it = yyjson_arr_iter_with(lsp); + for (yyjson_val *d = lsp ? yyjson_arr_iter_next(&it) : NULL; d && !decline; + d = yyjson_arr_iter_next(&it)) { + const char *ty = yyjson_get_str(yyjson_obj_get(d, "ty")); + if (ty && surface_names_gone(ty, gone, &buf, &cap, work)) { + decline = "identity_target_changed"; + } + } + yyjson_doc_free(doc); + } + cbm_free(CBM_MEM_CLASS_OTHER, buf); + cbm_ht_foreach(gone, surface_free_key, NULL); + cbm_ht_free(gone); + return decline; +} + /* Serialize one file's surface: its slice of all_defs plus the registry-only - * symbols from its raw extraction defs. Returns a malloc'd JSON string and its - * length. */ + * symbols from its raw extraction defs. Returns the JSON string (malloc'd, or + * from `alc` when given) and its length. With identities, each def's + * declared-type identities ("ty") are written as well: the stored row carries + * them, the hashed bytes do not. */ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage language, const char *rel_path, const CBMLSPDef *defs, int def_count, - size_t *out_len) { + bool identities, const yyjson_alc *alc, size_t *out_len) { yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL); if (!doc) { return NULL; @@ -400,6 +651,11 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu yyjson_mut_obj_add_bool(doc, o, "ab", d->is_abstract); add_str_array_or_null(doc, o, "dec", d->decorators, -1); add_str_or_null(doc, o, "al", d->alias_target); + /* Stored for the routes that resolve against this row without + * re-extracting it; never hashed (see SURFACE_CODEC_VERSION). */ + if (identities && d->type_scope) { + yyjson_mut_obj_add_str(doc, o, "ty", d->type_scope); + } yyjson_mut_arr_add_val(lsp, o); } yyjson_mut_obj_add_val(doc, root, "lsp", lsp); @@ -498,7 +754,7 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu } /* Names, types and strings come from source text, which need not be UTF-8: * one such byte must not cost the repository every surface row. */ - char *json = cbm_json_write_text(doc, NULL, out_len); + char *json = cbm_json_write_text(doc, alc, out_len); yyjson_mut_doc_free(doc); return json; } @@ -535,17 +791,34 @@ static void surface_row_build(int i, void *arg) { } int start = job->def_starts ? job->def_starts[i] : 0; int end = job->def_starts ? job->def_starts[i + 1] : 0; + const CBMLSPDef *slice = job->all_defs ? job->all_defs + start : NULL; + bool identities = false; + for (int d = 0; slice && d < end - start && !identities; d++) { + identities = slice[d].type_scope != NULL; + } size_t json_len = 0; + /* The hash covers the row without identities; a row that has some is + * written a second time with them, for storage (the hashed text is then + * a memory-core buffer, released here). */ char *json = - surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path, - job->all_defs ? job->all_defs + start : NULL, end - start, &json_len); + surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path, slice, end - start, + false, identities ? cbm_json_writer_allocator() : NULL, &json_len); + char sha[CBM_SHA256_HEX_LEN + 1]; + if (json) { + cbm_sha256_hex(json, json_len, sha); + } + if (json && identities) { + size_t stored_len = 0; + char *stored = surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path, + slice, end - start, true, NULL, &stored_len); + cbm_free(CBM_MEM_CLASS_OTHER, json); + json = stored; + } cbm_pipeline_result_release(fr, loaded); if (!json) { atomic_store_explicit(&job->failed, true, memory_order_relaxed); return; } - char sha[CBM_SHA256_HEX_LEN + 1]; - cbm_sha256_hex(json, json_len, sha); cbm_lsp_surface_row_t *r = &job->rows[i]; r->defs_json = json; /* set first: it marks the row present for the compaction */ r->project = strdup(job->project); @@ -749,6 +1022,7 @@ int cbm_lsp_surface_defs_from_json(CBMArena *arena, const char *defs_json, CBMLS int dec_count = 0; d->decorators = arena_str_array(arena, yyjson_obj_get(o, "dec"), true, &dec_count); d->alias_target = arena_str_or_null(arena, yyjson_obj_get(o, "al")); + d->type_scope = arena_str_or_null(arena, yyjson_obj_get(o, "ty")); if (!d->qualified_name || !d->short_name || !d->label) { /* A def the writer could not have produced: qn/sn/label are * unconditionally present in build_lsp_def output. Corrupt row. */ diff --git a/src/pipeline/lsp_surface.h b/src/pipeline/lsp_surface.h index 1a73b3427..937e1430b 100644 --- a/src/pipeline/lsp_surface.h +++ b/src/pipeline/lsp_surface.h @@ -15,8 +15,11 @@ * events and unknown effects; other languages carry an explicit null. * Field order and array order are fixed by the writer, so byte equality of the * serialization is surface equality; the sha256 of these bytes is the - * stored surface_sha. Rows written by a different codec version fail the - * "v" check on load and route the run to a full rebuild. + * stored surface_sha. A def's declared-type identities ("ty", type_scope.h) + * are stored in the row but are not part of the hashed bytes nor of the + * Python comparison: they are not file content (see + * cbm_lsp_surface_identity_decline). Rows written by a different codec + * version fail the "v" check on load and route the run to a full rebuild. */ #ifndef CBM_PIPELINE_LSP_SURFACE_H #define CBM_PIPELINE_LSP_SURFACE_H @@ -68,6 +71,27 @@ int cbm_lsp_surface_python_namespace_from_json(CBMArena *arena, const char *json */ int cbm_lsp_surface_python_change(const char *old_json, const char *new_json); +/* Whether a closure repair keeps every stored declared-type identity valid. + * An identity depends on the writing file's own content, which the surface + * hash covers, and on which project definitions are types of the label its + * language row allows; a repair cannot recompute the second for files it does + * not re-extract, so the planner declines when it changes: + * - "declared_types_changed": a changed file now has a type definition (a + * QN of a type label of its language's row) it did not have; + * - "identity_target_changed": a type definition some stored identity names + * left a changed or deleted file, or its definition changed (an alias + * that became a defined type, another label, other fields or embedded + * types): the files resolving through that identity are not the type's + * dependents in the graph. + * old_rows/new_rows: the stored and the fresh row of each changed file whose + * surface changed (new NULL for a deleted file); stored: the whole previous + * generation. Returns NULL when the repair keeps them, else the reason. *work + * (may be NULL) counts the defs and identity entries examined. */ +const char *cbm_lsp_surface_identity_decline(const char *const *old_rows, + const char *const *new_rows, int changed_count, + const cbm_lsp_surface_row_t *stored, int stored_count, + uint64_t *work); + #if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS /* Bracket each file callback, including skipped/error rows. Install only with * no surface build running; clear after the observed build returns. */ diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index eae590326..14323fc33 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -21,6 +21,7 @@ #include "resolve_stats.h" #include "pipeline/pipeline_internal.h" #include "pipeline/lsp_resolve.h" +#include "pipeline/type_scope.h" #include "callable_sig.h" #include "lsp/go_lsp.h" #include "lsp/c_lsp.h" @@ -1290,15 +1291,21 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are .project_name = project_name, .rel = files[fi].rel_path, .lang = files[fi].language}; - if (ctx && ctx->registry && pxc_lang_resolves_base_qns(files[fi].language)) { - bs.reg = ctx->registry; - bs.gbuf = ctx->gbuf; + /* The declared-type scope step (type_scope.h) reads the same map. */ + const cbm_type_scope_lang_t *scope_lang = + ctx && ctx->registry ? cbm_type_scope_lang(files[fi].language) : NULL; + bool resolve_bases = ctx && ctx->registry && pxc_lang_resolves_base_qns(files[fi].language); + if (resolve_bases || scope_lang) { /* Bases and field annotations resolve through annotation-only * imports too: `if TYPE_CHECKING:` exists for them (#1277). */ cbm_pxc_build_import_map_ex(ctx->gbuf, project_name, files[fi].rel_path, files[fi].language, fr, true, &bs.imp_keys, &bs.imp_vals, &bs.imp_count); } + if (resolve_bases) { + bs.reg = ctx->registry; + bs.gbuf = ctx->gbuf; + } for (int di = 0; di < fr->defs.count; di++) { if (pxc_build_lsp_def(arena, &fr->defs.items[di], def_modules[fi], namespace_name, files[fi].language, &defs[idx], bs.reg ? &bs : NULL) == 0) { @@ -1315,7 +1322,6 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are idx += pxc_build_py_namespace_records(arena, fr, def_modules[fi], &defs[idx]); } } - cbm_pxc_free_import_map(bs.imp_keys, bs.imp_vals, bs.imp_count); /* NULL-safe */ if (files[fi].language == CBM_LANG_GO) { pxc_fold_struct_fields(arena, fr, defs, file_start, idx, "Struct"); } else if (files[fi].language == CBM_LANG_C || files[fi].language == CBM_LANG_CPP) { @@ -1332,6 +1338,28 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are } } } + /* Every declared type this file wrote, resolved once in this file's + * scope; the identities travel with the defs (and their surface). */ + if (scope_lang) { + cbm_type_scope_t scope = {.reg = ctx->registry, + .module_qn = def_modules[fi], + .imp_keys = bs.imp_keys, + .imp_vals = bs.imp_vals, + .imp_count = bs.imp_count}; + if (scope_lang->lexical_scopes) { + /* The file's own scopes: its definitions and the module's + * ordered namespace facts. */ + scope.file_defs = fr->defs.items; + scope.file_def_count = fr->defs.count; + scope.module_facts = &fr->py_namespace; + } + cbm_type_scope_file_t *ts_file = cbm_type_scope_file_begin(scope_lang, &scope); + for (int di = file_start; ts_file && di < idx; di++) { + cbm_type_scope_attach(ts_file, arena, &defs[di]); + } + cbm_type_scope_file_end(ts_file); + } + cbm_pxc_free_import_map(bs.imp_keys, bs.imp_vals, bs.imp_count); /* NULL-safe */ if (fr_loaded) { cbm_free_result(fr); } @@ -3059,53 +3087,140 @@ static const pxc_module_entry_t *pxc_py_spec_entry(const CBMModuleDefIndex *idx, return NULL; } +/* The index entry of the module that declares the definition `qn`: its + * nearest proper module prefix (a Python package through its __init__), or + * NULL. */ +static const pxc_module_entry_t *pxc_module_of_qn(const CBMModuleDefIndex *idx, const char *qn, + size_t len, CBMLanguage lang) { + char key[CBM_SZ_1K]; + if (len + sizeof(".__init__") > sizeof(key)) { + return NULL; + } + memcpy(key, qn, len); + key[len] = '\0'; + for (;;) { + char *dot = strrchr(key, '.'); + if (!dot) { + return NULL; + } + *dot = '\0'; + const pxc_module_entry_t *e = (const pxc_module_entry_t *)cbm_ht_get(idx->ht, key); + if (!e && lang == CBM_LANG_PYTHON) { + e = pxc_py_module_entry(idx, key, strlen(key)); + } + if (e) { + return e; + } + } +} + +/* A def the selection reaches through: a Python namespace record, or a def + * whose declared types carry identities (type_scope.h). */ +static bool pxc_def_reaches(const CBMLSPDef *d) { + return pxc_is_py_reexport_record(d) || d->type_scope; +} + +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_pxc_reach_work; +uint64_t cbm_pxc_test_reach_work(void) { + return atomic_load_explicit(&g_pxc_reach_work, memory_order_relaxed); +} +#define PXC_REACH_WORK(n) \ + atomic_fetch_add_explicit(&g_pxc_reach_work, (uint64_t)(n), memory_order_relaxed) +#else +#define PXC_REACH_WORK(n) ((void)0) +#endif + +/* Select every def of module entry `e` the caller can use and queue the ones + * that reach further (each def is queued at most once). Module entries + * partition the defs (one def_module_qn each), so an entry is known by its + * first def: each entry is walked once, however many defs point at it. */ +static void pxc_mark_reached_entry(const pxc_module_entry_t *e, bool *selected, + const CBMLSPDef *all_defs, CBMLanguage caller_lang, bool *queued, + bool *entry_done, int *work, int *n, int *total) { + if (!e || e->count <= 0 || entry_done[e->indices[0]]) { + return; + } + entry_done[e->indices[0]] = true; + PXC_REACH_WORK(e->count); + for (int j = 0; j < e->count; j++) { + int di = e->indices[j]; + const CBMLSPDef *d = &all_defs[di]; + if (!pxc_def_lang_matches(caller_lang, d->lang) || + (caller_lang == CBM_LANG_PYTHON && d->lang != CBM_LANG_PYTHON)) { + continue; + } + if (!selected[di]) { + selected[di] = true; + (*total)++; + } + if (!queued[di] && pxc_def_reaches(d)) { + queued[di] = true; + work[(*n)++] = di; + } + } +} + /* A per-file selection holds the defs of the caller's own and imported - * modules. A Python package that re-exports a name keeps only the record; - * the definition lives in the module the record points at, possibly through - * further re-exports. Select those modules' defs too, following every - * selected record once (a worklist over def indices: linear in the defs it - * reaches), so the per-file LSP can fold the chain as the shared registry - * does. */ -static void pxc_mark_reexport_targets(const CBMModuleDefIndex *idx, bool *selected, - const CBMLSPDef *all_defs, int *total) { + * modules. Two kinds of selected def point further: + * - A Python package that re-exports a name keeps only the record; the + * definition lives in the module the record points at, possibly through + * further re-exports. + * - A def's declared-type identity names a type in a module the caller + * neither owns nor imports (the return type the callee's file imported). + * Select those modules' defs too, following every reaching def once and + * walking every module entry once (a worklist over def indices: linear in the + * defs it reaches and the identities they hold), so the per-file LSP sees what + * the shared registry holds for a full index. */ +static void pxc_mark_reached_targets(const CBMModuleDefIndex *idx, bool *selected, + const CBMLSPDef *all_defs, CBMLanguage caller_lang, + int *total) { int cap = idx->def_count; int *work = (int *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(int)); bool *queued = (bool *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(bool)); - if (!work || !queued) { + bool *entry_done = (bool *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(bool)); + if (!work || !queued || !entry_done) { cbm_free(CBM_MEM_CLASS_EXTRACT, work); cbm_free(CBM_MEM_CLASS_EXTRACT, queued); + cbm_free(CBM_MEM_CLASS_EXTRACT, entry_done); return; } int n = 0; for (int i = 0; i < cap; i++) { - if (selected[i] && pxc_is_py_reexport_record(&all_defs[i])) { + if (selected[i] && pxc_def_reaches(&all_defs[i])) { queued[i] = true; work[n++] = i; } } for (int w = 0; w < n; w++) { const CBMLSPDef *r = &all_defs[work[w]]; - bool star = strcmp(r->label, "PyStarImport") == 0; - const pxc_module_entry_t *e = - r->def_module_qn ? pxc_py_spec_entry(idx, r->def_module_qn, r->receiver_type, - star ? NULL : r->method_names_str) - : NULL; - for (int j = 0; e && j < e->count; j++) { - int di = e->indices[j]; - if (di < 0 || di >= cap || all_defs[di].lang != CBM_LANG_PYTHON) - continue; - if (!selected[di]) { - selected[di] = true; - (*total)++; - } - if (!queued[di] && pxc_is_py_reexport_record(&all_defs[di])) { - queued[di] = true; - work[n++] = di; + /* The modules this def points at: one for a record, one per identity. */ + if (caller_lang == CBM_LANG_PYTHON && pxc_is_py_reexport_record(r)) { + bool star = strcmp(r->label, "PyStarImport") == 0; + const pxc_module_entry_t *e = + r->def_module_qn ? pxc_py_spec_entry(idx, r->def_module_qn, r->receiver_type, + star ? NULL : r->method_names_str) + : NULL; + pxc_mark_reached_entry(e, selected, all_defs, caller_lang, queued, entry_done, work, &n, + total); + } + for (const char *p = r->type_scope; p && *p;) { + const char *eq = strchr(p, '='); + if (!eq) { + break; } + const char *bar = strchr(eq, '|'); + size_t qn_len = bar ? (size_t)(bar - eq - 1) : strlen(eq + 1); + PXC_REACH_WORK(1); + const pxc_module_entry_t *e = pxc_module_of_qn(idx, eq + 1, qn_len, caller_lang); + pxc_mark_reached_entry(e, selected, all_defs, caller_lang, queued, entry_done, work, &n, + total); + p = bar ? bar + 1 : eq + 1 + qn_len; } } cbm_free(CBM_MEM_CLASS_EXTRACT, work); cbm_free(CBM_MEM_CLASS_EXTRACT, queued); + cbm_free(CBM_MEM_CLASS_EXTRACT, entry_done); } CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef *all_defs, @@ -3140,8 +3255,8 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef pxc_module_entry_t *e = (pxc_module_entry_t *)cbm_ht_get(idx->namespace_ht, namespace_key); total += pxc_mark_entry_defs(selected, e, all_defs, caller_lang); } - if (caller_lang == CBM_LANG_PYTHON) { - pxc_mark_reexport_targets(idx, selected, all_defs, &total); + if (caller_lang == CBM_LANG_PYTHON || cbm_type_scope_lang(caller_lang)) { + pxc_mark_reached_targets(idx, selected, all_defs, caller_lang, &total); } if (total == 0) { diff --git a/src/pipeline/pass_lsp_cross.h b/src/pipeline/pass_lsp_cross.h index 51964bc41..9459ea903 100644 --- a/src/pipeline/pass_lsp_cross.h +++ b/src/pipeline/pass_lsp_cross.h @@ -134,6 +134,12 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef const char *own_module, const char *const *imp_qns, int imp_count, int *out_count, bool *out_success); +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +/* Work counter for the growth tests: module-entry defs walked and identities + * followed by the per-file selection's worklist. Test builds only. */ +uint64_t cbm_pxc_test_reach_work(void); +#endif + /* ── Tier 2 full: pre-built per-language cross-LSP registries ───── * * Each non-NULL registry is built ONCE in pipeline.c (in a dedicated diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index bae038f5d..2b32c9ba1 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2608,7 +2608,7 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c census_len(def->client_route_path) + census_len(def->impl_trait) + census_len(def->http_base_url) + census_list(def->extra_props) + census_len(def->decl_namespace) + census_len(def->variant_key) + - census_len(def->alias_target); + census_len(def->alias_target) + census_len(def->type_params); } for (int c = 0; c < r->calls.count; c++) { const CBMCall *call = &r->calls.items[c]; diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c index 40a425ea6..92b7cc804 100644 --- a/src/pipeline/pipeline_incremental.c +++ b/src/pipeline/pipeline_incremental.c @@ -71,10 +71,33 @@ cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void) { return (cbm_incremental_route_t)atomic_load(&g_incr_test_last_route); } +/* The last closure plan's counters (an accepted plan) or decline reason. */ +static atomic_int g_incr_test_plan_files = -1; +static atomic_int g_incr_test_plan_surface_changed = -1; +static atomic_int g_incr_test_plan_dependents = -1; +static _Atomic(const char *) g_incr_test_plan_decline = NULL; + +cbm_incremental_closure_plan_t cbm_pipeline_incremental_test_last_closure_plan(void) { + return (cbm_incremental_closure_plan_t){.files = atomic_load(&g_incr_test_plan_files), + .surface_changed = + atomic_load(&g_incr_test_plan_surface_changed), + .dependents = atomic_load(&g_incr_test_plan_dependents), + .decline = atomic_load(&g_incr_test_plan_decline)}; +} + +static void incr_test_note_plan(int files, int surface_changed, int dependents, + const char *decline) { + atomic_store(&g_incr_test_plan_files, files); + atomic_store(&g_incr_test_plan_surface_changed, surface_changed); + atomic_store(&g_incr_test_plan_dependents, dependents); + atomic_store(&g_incr_test_plan_decline, decline); +} + void cbm_pipeline_incremental_test_reset_faults(void) { atomic_store(&g_incr_test_fail_result_cache_alloc, false); atomic_store(&g_incr_test_force_legacy_partial, false); atomic_store(&g_incr_test_last_route, CBM_INCREMENTAL_ROUTE_NONE); + incr_test_note_plan(-1, -1, -1, NULL); cbm_pipeline_persist_test_reset_faults(); } @@ -1470,7 +1493,11 @@ static void free_incremental_result_cache(CBMFileResult **cache, int count) { * recomputed; a surface change pulls in exactly the files with edges into * it. Per-file extraction is a pure function of file content, so an * unchanged dependent can never be surface-changed in turn — the closure is - * structurally depth-1 and needs no fixpoint. Every uncertain case declines + * structurally depth-1 and needs no fixpoint. The one part of a stored row + * that is not file content, its declared-type identities (type_scope.h), is + * kept out of the hash and stays valid because the plan declines whenever the + * type definitions they depend on change (cbm_lsp_surface_identity_decline). + * Every uncertain case declines * to a FULL rebuild: new files, added definition names (yesterday's graph * cannot know tomorrow's referencers), virtual/config manifest entries, * missing or unreadable surface rows, dependents outside discovery, or a @@ -3235,9 +3262,13 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p * query. Python changes require a full rebuild; other surface changes and * deletions seed the dependent query. */ int n_surface_changed = 0; - /* dep_targets, then the body-edited files (body_targets) in the same block */ - const char **dep_targets = - (const char **)calloc((size_t)(n_changed + n_deleted + n_changed), sizeof(char *)); + /* dep_targets, then the body-edited files (body_targets), then the stored + * and fresh rows of every surface-changed or deleted file for the + * declared-type identity gate (identity_old / identity_new; fresh NULL + * for a deleted file), in the same block */ + int identity_cap = n_changed + n_deleted + 1; + const char **dep_targets = (const char **)calloc( + (size_t)(n_changed + n_deleted + n_changed + 2 * identity_cap), sizeof(char *)); if (!dep_targets) { cbm_ht_free(rows_by_path); decline = "alloc"; @@ -3245,6 +3276,9 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p } body_targets = dep_targets + n_changed + n_deleted; int dep_target_count = 0; + const char **identity_old = body_targets + n_changed; + const char **identity_new = identity_old + identity_cap; + int identity_count = 0; /* The first file that declines the closure stops both loops; the one exit * below releases dep_targets and the row index for every reason. */ const char *why = NULL; @@ -3281,6 +3315,8 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p } else { n_surface_changed++; dep_targets[dep_target_count++] = changed_paths[i]; + identity_old[identity_count] = stored_row->defs_json; + identity_new[identity_count++] = fresh_row->defs_json; } } bool gone_scope_changed = false; /* a deleted file takes its declarations along */ @@ -3294,8 +3330,19 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p if (gone && !doc_scope_repairable(gone->defs_json, NULL, removed_names)) { gone_scope_changed = true; } + if (gone) { + identity_old[identity_count] = gone->defs_json; + identity_new[identity_count++] = NULL; + } } cbm_ht_free(rows_by_path); + /* Declared-type identities (type_scope.h) are not file content: a repair + * keeps them only while the project's type definitions they depend on + * stay as they were. */ + if (!why && identity_count > 0) { + why = cbm_lsp_surface_identity_decline(identity_old, identity_new, identity_count, + plan->stored_rows, plan->stored_count, NULL); + } /* A body edit keeps a file's names but moves its lines: a document that * bound a reference by lines (`file#L3-L9`, :lines:) would keep a stale @@ -3308,7 +3355,7 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p (body_target_count > 0 && cbm_store_get_dependent_files(store, project, body_targets, body_target_count, &line_docs, &line_doc_count) != CBM_STORE_OK)); - free(dep_targets); /* body_targets with it */ + free(dep_targets); /* body_targets and the identity rows with it */ body_targets = NULL; if (why) { decline = why; @@ -3403,6 +3450,9 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p cbm_log_info("incremental.closure_plan_done", "closure", itoa_buf(plan->count), "doc_link_dependents", itoa_buf(n_row_dependents), "elapsed_ms", itoa_buf((int)elapsed_ms(t))); +#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API + incr_test_note_plan(plan->count, n_surface_changed, dependent_count, NULL); +#endif done: cbm_path_alias_collection_free(plan_aliases); @@ -3420,6 +3470,9 @@ done: if (decline) { cbm_log_info("incremental.closure_decline", "reason", decline, "elapsed_ms", itoa_buf((int)elapsed_ms(t))); +#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API + incr_test_note_plan(-1, -1, -1, decline); +#endif cbm_store_free_lsp_surfaces(plan->stored_rows, plan->stored_count); int fatal_rc = plan->fatal_rc; cbm_store_free_doc_links(plan->doc_rows, plan->doc_row_count); diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h index 475f233a2..029b1b8b4 100644 --- a/src/pipeline/pipeline_internal.h +++ b/src/pipeline/pipeline_internal.h @@ -2081,6 +2081,16 @@ void cbm_pipeline_incremental_test_after_stage_created_once(cbm_pipeline_test_ho void *userdata); cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void); void cbm_pipeline_incremental_test_reset_faults(void); +/* The last closure plan: an accepted plan's re-parse set size, surface-changed + * files and dependents (decline NULL), or a declined plan's reason (counters + * -1). All -1 / NULL after a reset and when no plan ran. */ +typedef struct { + int files; + int surface_changed; + int dependents; + const char *decline; +} cbm_incremental_closure_plan_t; +cbm_incremental_closure_plan_t cbm_pipeline_incremental_test_last_closure_plan(void); /* Shared persistence-hook plumbing. Tests use the incremental facade above so * one reset covers route, extraction, and publication faults. */ diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c new file mode 100644 index 000000000..cc5f7d724 --- /dev/null +++ b/src/pipeline/type_scope.c @@ -0,0 +1,676 @@ +/* + * type_scope.c — declared types resolved once, in the scope that wrote them. + * See type_scope.h for the contract. + * + * Cost: per file, one hash of its import map, one hash of its own definitions + * (rows with lexical scopes) and one memo of the spellings it writes; per + * definition, one scan of its type texts and one walk up its enclosing defs + * that stops at the first one already walked. Every lookup is an exact hash + * probe (no scan, no short-name candidate list), so the step is linear in the + * bytes of declared type text and of the file's definition names. + */ +#include "pipeline/type_scope.h" + +#include "foundation/constants.h" + +#include +#include +#include +#include +#include + +/* ── Language descriptions ────────────────────────────────────────── */ + +/* Go: every type-like declaration has a method set (a Go alias carries its + * target through alias_target, which the registrar follows). */ +static const char *const go_labels[] = {"Struct", "Interface", "Type", "Class", "Enum", NULL}; +/* Python: what py_register_lsp_defs registers as a type. */ +static const char *const py_labels[] = {"Class", "Interface", "Protocol", "Type", NULL}; + +static const cbm_type_scope_lang_t type_scope_langs[] = { + {.lang = CBM_LANG_GO, + .labels = go_labels, + .engine_qualifies_own_module = true, + .imports_bind_modules = true, + .return_types = true, + .param_types = true, + .field_types = true}, + {.lang = CBM_LANG_PYTHON, + .quoted_names = true, + .labels = py_labels, + .engine_qualifies_own_module = false, + .lexical_scopes = true, + .return_types = true, + .param_types = true}, +}; + +const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang) { + for (size_t i = 0; i < sizeof(type_scope_langs) / sizeof(type_scope_langs[0]); i++) { + if (type_scope_langs[i].lang == lang) { + return &type_scope_langs[i]; + } + } + return NULL; +} + +/* ── Work counter (test builds) ───────────────────────────────────── */ + +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_type_scope_work; + +uint64_t cbm_type_scope_test_work(void) { + return atomic_load_explicit(&g_type_scope_work, memory_order_relaxed); +} + +#define TYPE_SCOPE_WORK(n) \ + atomic_fetch_add_explicit(&g_type_scope_work, (uint64_t)(n), memory_order_relaxed) +#else +#define TYPE_SCOPE_WORK(n) ((void)0) +#endif + +/* ── Per-file state ───────────────────────────────────────────────── */ + +/* Distinct, never-dereferenced values: "two imports bind this local to + * different targets", a memoized miss, and the two nesting verdicts. */ +static char g_ambiguous_mark; +static char g_miss_mark; +static char g_nest_open_mark; +static char g_nest_local_mark; +static char g_bound_once_mark; +static char g_bound_many_mark; +#define TYPE_SCOPE_BOUND_ONCE ((void *)&g_bound_once_mark) +#define TYPE_SCOPE_BOUND_MANY ((void *)&g_bound_many_mark) +#define TYPE_SCOPE_AMBIGUOUS ((void *)&g_ambiguous_mark) +#define TYPE_SCOPE_MISS ((void *)&g_miss_mark) +#define TYPE_SCOPE_NEST_OPEN ((void *)&g_nest_open_mark) /* module or class bodies only */ +#define TYPE_SCOPE_NEST_LOCAL ((void *)&g_nest_local_mark) /* inside a function */ + +struct cbm_type_scope_file { + const cbm_type_scope_lang_t *lang; + cbm_type_scope_t scope; + size_t scope_len; /* the module's symbol scope (a package without __init__) */ + CBMHashTable *imports; /* local -> import QN, or TYPE_SCOPE_AMBIGUOUS */ + CBMHashTable *memo; /* spelling -> QN, or TYPE_SCOPE_MISS */ + CBMHashTable *seen; /* spelling -> serial of the last def that wrote it */ + /* lexical scopes only */ + CBMHashTable *defs; /* file def QN -> index + 1 into scope.file_defs */ + CBMHashTable *tparams; /* every type parameter name the file declares */ + CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */ + CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */ + bool closed; /* the module's bindings cannot be listed: no identity */ + uintptr_t serial; /* the def being attached, from 1 */ + const char *enclosing_class; /* the def's immediately enclosing class, or NULL */ + CBMArena keys; /* memo keys and candidate strings */ +}; + +static bool type_scope_function_label(const char *label) { + return label && (strcmp(label, "Function") == 0 || strcmp(label, "Method") == 0); +} + +/* Count the module-level bindings of every name from the ordered namespace + * facts; a star import, a parse error or an incomplete record closes the + * file. */ +static bool type_scope_index_module_facts(cbm_type_scope_file_t *f) { + const CBMPyNamespaceFacts *facts = f->scope.module_facts; + f->bindings = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(facts ? facts->count + 1 : 1)); + if (!f->bindings) { + return false; + } + if (!facts || facts->status != CBM_PY_NS_COMPLETE) { + f->closed = true; + return true; + } + for (int i = 0; i < facts->count && !f->closed; i++) { + const CBMPyNamespaceFact *fact = &facts->items[i]; + TYPE_SCOPE_WORK(1); + switch (fact->kind) { + case CBM_PY_NS_IMPORT_STAR: + f->closed = true; /* binds names nobody listed */ + break; + case CBM_PY_NS_UNKNOWN: + /* An effect or a compound statement: the import map and the + * engine read past those as well. A parse error leaves the file's + * bindings unknown. */ + f->closed = fact->reason == CBM_PY_NS_REASON_PARSE; + break; + case CBM_PY_NS_OWN_DEF: + case CBM_PY_NS_IMPORT_MODULE: + case CBM_PY_NS_IMPORT_NAME: + case CBM_PY_NS_SHADOW: + case CBM_PY_NS_DELETE: + if (fact->local_name && fact->local_name[0]) { + bool again = cbm_ht_get(f->bindings, fact->local_name) != NULL; + /* keys borrow the facts, which outlive the file state */ + cbm_ht_set(f->bindings, fact->local_name, + again ? TYPE_SCOPE_BOUND_MANY : TYPE_SCOPE_BOUND_ONCE); + } + break; + default: + break; /* __all__ facts bind no name */ + } + } + return true; +} + +/* True when the module binds this head more than once. */ +static bool type_scope_rebound(const cbm_type_scope_file_t *f, const char *head) { + TYPE_SCOPE_WORK(1); + return f->bindings && cbm_ht_get(f->bindings, head) == TYPE_SCOPE_BOUND_MANY; +} + +/* Hash the file's own definitions and its type parameter names. */ +static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { + int n = f->scope.file_def_count; + f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); + f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); + f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); + if (!f->defs || !f->tparams || !f->nesting || !type_scope_index_module_facts(f)) { + return false; + } + for (int i = 0; i < n; i++) { + const CBMDefinition *d = &f->scope.file_defs[i]; + if (d->qualified_name && !cbm_ht_get(f->defs, d->qualified_name)) { + TYPE_SCOPE_WORK(1); + cbm_ht_set(f->defs, d->qualified_name, (void *)(uintptr_t)(i + 1)); + } + for (const char *p = d->type_params; p && *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL; + TYPE_SCOPE_WORK(len + 1); + if (name && !cbm_ht_get(f->tparams, name)) { + cbm_ht_set(f->tparams, name, name); + } + p = bar ? bar + 1 : p + len; + } + } + return true; +} + +cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang, + const cbm_type_scope_t *scope) { + if (!lang || !scope || !scope->reg || !scope->module_qn) { + return NULL; + } + cbm_type_scope_file_t *f = cbm_calloc(CBM_MEM_CLASS_EXTRACT, sizeof(*f)); + if (!f) { + return NULL; + } + f->lang = lang; + f->scope = *scope; + f->scope_len = cbm_fqn_symbol_scope_len(scope->module_qn); + f->imports = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(scope->imp_count + 1)); + f->memo = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32); + f->seen = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32); + cbm_arena_init_lazy(&f->keys, CBM_SZ_4K); + if (!f->imports || !f->memo || !f->seen || + (lang->lexical_scopes && !type_scope_index_file_defs(f))) { + cbm_type_scope_file_end(f); + return NULL; + } + for (int i = 0; i < scope->imp_count; i++) { + const char *key = scope->imp_keys ? scope->imp_keys[i] : NULL; + const char *val = scope->imp_vals ? scope->imp_vals[i] : NULL; + if (!key || !val || !key[0]) { + continue; + } + TYPE_SCOPE_WORK(1); + void *prev = cbm_ht_get(f->imports, key); + if (!prev) { + cbm_ht_set(f->imports, key, (void *)val); + } else if (prev != TYPE_SCOPE_AMBIGUOUS && strcmp((const char *)prev, val) != 0) { + cbm_ht_set(f->imports, key, TYPE_SCOPE_AMBIGUOUS); + } + } + return f; +} + +void cbm_type_scope_file_end(cbm_type_scope_file_t *file) { + if (!file) { + return; + } + cbm_ht_free(file->imports); /* NULL-safe */ + cbm_ht_free(file->memo); + cbm_ht_free(file->seen); + cbm_ht_free(file->defs); + cbm_ht_free(file->tparams); + cbm_ht_free(file->nesting); + cbm_ht_free(file->bindings); + cbm_arena_destroy(&file->keys); + cbm_free(CBM_MEM_CLASS_EXTRACT, file); +} + +/* ── Resolution ───────────────────────────────────────────────────── */ + +/* `qn` when it names a project definition of an allowed label, else NULL. */ +static const char *type_scope_target(const cbm_type_scope_file_t *f, const char *qn) { + TYPE_SCOPE_WORK(1); + const char *label = cbm_registry_label_of(f->scope.reg, qn); + if (!label) { + return NULL; + } + for (const char *const *l = f->lang->labels; *l; l++) { + if (strcmp(*l, label) == 0) { + return qn; + } + } + return NULL; +} + +/* The candidate QN for `dotted` through the import that binds its head, or + * NULL. *bound reports whether an import binds the head at all (then the + * file's own module does not decide the name). An import names a project + * definition or nothing: a path that names no definition (a module outside + * the project, a name a package re-exports) is no answer. */ +static const char *type_scope_via_import(cbm_type_scope_file_t *f, const char *dotted, + size_t head_len, bool *bound, bool *ambiguous) { + *bound = false; + *ambiguous = false; + const char *dot = dotted[head_len] == '.' ? dotted + head_len : NULL; + if (!dot && f->lang->imports_bind_modules) { + return NULL; /* a bare name never resolves through a package import */ + } + char head[CBM_SZ_256]; + if (head_len == 0 || head_len >= sizeof(head)) { + return NULL; + } + memcpy(head, dotted, head_len); + head[head_len] = '\0'; + TYPE_SCOPE_WORK(1); + void *v = cbm_ht_get(f->imports, head); + if (!v) { + return NULL; + } + *bound = true; + if (v == TYPE_SCOPE_AMBIGUOUS) { + *ambiguous = true; + return NULL; + } + const char *val = (const char *)v; + if (dot) { + /* `pkg.T`: the import binds the module, the rest names inside it. */ + const char *qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, dot + 1); + return qn ? type_scope_target(f, qn) : NULL; + } + /* A bare name: the import binds the type itself, or (a module-valued + * binding, Python's `from m import T` whose edge names the module) the + * type of that name inside it. Both existing and differing is no answer. */ + const char *direct = type_scope_target(f, val); + const char *member_qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, head); + const char *member = member_qn ? type_scope_target(f, member_qn) : NULL; + if (direct && member && strcmp(direct, member) != 0) { + *ambiguous = true; + return NULL; + } + return direct ? direct : member; +} + +/* The memo / seen key of a spelling: the spelling itself, NUL-terminated in a + * caller buffer (a name too long for it has no identity). */ +static bool type_scope_key(const char *spelling, size_t len, char *buf, size_t bufsz) { + if (len == 0 || len >= bufsz) { + return false; + } + memcpy(buf, spelling, len); + buf[len] = '\0'; + return true; +} + +static size_t type_scope_head_len(const char *spelling, size_t len) { + const char *dot = memchr(spelling, '.', len); + return dot ? (size_t)(dot - spelling) : len; +} + +const char *cbm_type_scope_resolve(cbm_type_scope_file_t *f, const char *spelling, size_t len) { + char probe[CBM_SZ_512]; + if (!f || !spelling || !type_scope_key(spelling, len, probe, sizeof(probe))) { + return NULL; + } + TYPE_SCOPE_WORK(1); + void *memo = cbm_ht_get(f->memo, probe); + if (memo) { + return memo == TYPE_SCOPE_MISS ? NULL : (const char *)memo; + } + char *key = cbm_arena_strndup(&f->keys, spelling, len); + if (!key) { + return NULL; + } + const char *result = NULL; + const char *dotted = key; /* `T` or `pkg.T`, NUL-terminated */ + size_t head_len = type_scope_head_len(dotted, len); + if (f->bindings) { + /* A head the module binds more than once has no one answer. */ + char head[CBM_SZ_256]; + if (!type_scope_key(dotted, head_len, head, sizeof(head)) || type_scope_rebound(f, head)) { + cbm_ht_set(f->memo, key, TYPE_SCOPE_MISS); + return NULL; + } + } + bool bound = false; + bool ambiguous = false; + const char *via_import = type_scope_via_import(f, dotted, head_len, &bound, &ambiguous); + /* A Python package's names live under the package, not its __init__. */ + const char *mod = f->scope.module_qn; + int scope_len = (int)f->scope_len; + const char *own_qn = cbm_arena_sprintf(&f->keys, "%.*s.%s", scope_len, mod, dotted); + const char *own = own_qn ? type_scope_target(f, own_qn) : NULL; + if (bound && !ambiguous) { + /* The import decides, unless the own module binds the head as well + * (any definition of that name: a class, a function, a TypeVar + * variable): two bindings of one name, whose winner is source order. */ + const char *head_qn = + cbm_arena_sprintf(&f->keys, "%.*s.%.*s", scope_len, mod, (int)head_len, dotted); + TYPE_SCOPE_WORK(1); + bool own_binds = head_qn && cbm_registry_exists(f->scope.reg, head_qn); + bool same = via_import && own && strcmp(own, via_import) == 0; + result = own_binds && !same ? NULL : via_import; + } else if (!bound) { + result = own; + } + cbm_ht_set(f->memo, key, result ? (void *)result : TYPE_SCOPE_MISS); + return result; +} + +/* ── The def's own enclosing scopes (lexical rows) ───────────────── */ + +/* Whether the definition `qn` lies inside a function. inside(q) is true when + * q's parent is a function, false when the parent is the module, and + * inside(parent) when the parent is a class of this file; a parent QN this + * file does not define is no proof of a module or class body, so it counts as + * inside (no identity). The walk stops at the first ancestor already judged, + * and every class it passes is judged on the way, so each definition of the + * file is walked through once. */ +static bool type_scope_function_local(cbm_type_scope_file_t *f, const char *qn) { + const char **passed = NULL; /* classes walked through, not yet judged */ + int count = 0; + int cap = 0; + bool inside = true; + const char *cur = qn; + for (;;) { + const char *dot = strrchr(cur, '.'); + size_t parent_len = dot ? (size_t)(dot - cur) : 0; + if (parent_len <= f->scope_len) { + inside = false; /* cur is a module-level definition */ + break; + } + char *parent = cbm_arena_strndup(&f->keys, cur, parent_len); + TYPE_SCOPE_WORK(parent_len + 1); + if (!parent) { + break; + } + void *known = cbm_ht_get(f->nesting, parent); + if (known) { + inside = known == TYPE_SCOPE_NEST_LOCAL; + break; + } + uintptr_t at = (uintptr_t)cbm_ht_get(f->defs, parent); + if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) { + break; /* inside a function, or under a parent this file lacks */ + } + if (count == cap) { + int grown_cap = cap ? cap * 2 : 8; + const char **grown = + (const char **)cbm_arena_alloc(&f->keys, (size_t)grown_cap * sizeof(*grown)); + if (!grown) { + break; + } + if (count) { + memcpy(grown, passed, (size_t)count * sizeof(*grown)); + } + passed = grown; + cap = grown_cap; + } + passed[count++] = parent; /* a class: inside(cur) == inside(parent) */ + cur = parent; + } + for (int i = 0; i < count; i++) { + cbm_ht_set(f->nesting, passed[i], inside ? TYPE_SCOPE_NEST_LOCAL : TYPE_SCOPE_NEST_OPEN); + } + return inside; +} + +/* The def's immediately enclosing class: its parent QN when that is a + * non-function definition of this file, else NULL. */ +static const char *type_scope_enclosing_class(cbm_type_scope_file_t *f, const char *qn) { + const char *dot = strrchr(qn, '.'); + size_t parent_len = dot ? (size_t)(dot - qn) : 0; + if (parent_len <= f->scope_len) { + return NULL; + } + char *parent = cbm_arena_strndup(&f->keys, qn, parent_len); + TYPE_SCOPE_WORK(parent_len + 1); + uintptr_t at = parent ? (uintptr_t)cbm_ht_get(f->defs, parent) : 0; + if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) { + return NULL; + } + return parent; +} + +/* True when the def's own scopes bind the head of this spelling before the + * module does: a type parameter the file declares, or a name the enclosing + * class body declares. */ +static bool type_scope_shadowed(cbm_type_scope_file_t *f, const char *name, size_t len) { + size_t head_len = type_scope_head_len(name, len); + char head[CBM_SZ_256]; + if (!type_scope_key(name, head_len, head, sizeof(head))) { + return true; + } + TYPE_SCOPE_WORK(1); + if (cbm_ht_get(f->tparams, head)) { + return true; + } + if (!f->enclosing_class) { + return false; + } + const char *member = cbm_arena_sprintf(&f->keys, "%s.%s", f->enclosing_class, head); + TYPE_SCOPE_WORK(1); + return !member || cbm_ht_get(f->defs, member) != NULL; +} + +/* ── Reduction of a type text to the names it writes ──────────────── */ + +static bool type_scope_ident_start(unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c >= 0x80; +} + +static bool type_scope_ident_char(unsigned char c) { + return type_scope_ident_start(c) || (c >= '0' && c <= '9'); +} + +typedef void (*type_scope_name_fn)(const char *name, size_t len, void *ud); + +/* Call fn for every type name the text writes: a run of identifier + * characters joined by `.`. A quoted run is a literal (skipped) unless + * quoted_names; a name that is only a member access (one `.` before it) or a + * label (one `:` after it: a property, a named parameter) is not a type + * name. */ +static void type_scope_names(const cbm_type_scope_lang_t *lang, const char *text, + type_scope_name_fn fn, void *ud) { + size_t n = text ? strlen(text) : 0; + TYPE_SCOPE_WORK(n); + size_t i = 0; + while (i < n) { + unsigned char c = (unsigned char)text[i]; + if ((c == '"' || c == '\'' || c == '`') && !lang->quoted_names) { + size_t close = i + 1; + while (close < n && text[close] != (char)c) { + close++; + } + i = close < n ? close + 1 : n; + continue; + } + if (!type_scope_ident_start(c)) { + i++; + continue; + } + size_t start = i; + while (i < n && type_scope_ident_char((unsigned char)text[i])) { + i++; + } + for (;;) { + if (i + 1 < n && text[i] == '.' && type_scope_ident_start((unsigned char)text[i + 1])) { + i++; + } else { + break; + } + while (i < n && type_scope_ident_char((unsigned char)text[i])) { + i++; + } + } + bool member = start > 0 && text[start - 1] == '.' && (start < 2 || text[start - 2] != '.'); + size_t after = i; + while (after < n && text[after] == ' ') { + after++; + } + bool label = after < n && text[after] == ':' && (after + 1 >= n || text[after + 1] != ':'); + if (!member && !label) { + fn(text + start, i - start, ud); + } + } +} + +/* ── Attaching identities to a definition ─────────────────────────── */ + +typedef struct { + cbm_type_scope_file_t *file; + char *buf; /* "spelling=QN|..." being built (heap) */ + size_t len; + size_t cap; + bool failed; +} type_scope_build_t; + +/* True when the current def already wrote this spelling (one hash probe; the + * seen table remembers, per spelling, the last def that wrote it). */ +static bool type_scope_seen(cbm_type_scope_file_t *f, const char *name, size_t len) { + char probe[CBM_SZ_512]; + if (!type_scope_key(name, len, probe, sizeof(probe))) { + return true; /* too long to key: never an identity */ + } + TYPE_SCOPE_WORK(1); + void *last = cbm_ht_get(f->seen, probe); + if (last == (void *)f->serial) { + return true; + } + const char *key = last ? cbm_ht_get_key(f->seen, probe) : cbm_arena_strdup(&f->keys, probe); + if (key) { + cbm_ht_set(f->seen, key, (void *)f->serial); + } + return false; +} + +static bool type_scope_append(type_scope_build_t *b, const char *s, size_t n) { + if (b->len + n + 1 > b->cap) { + size_t cap = b->cap ? b->cap * 2 : 128; + while (cap < b->len + n + 1) { + cap *= 2; + } + char *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, b->buf, cap); + if (!grown) { + b->failed = true; + return false; + } + b->buf = grown; + b->cap = cap; + } + memcpy(b->buf + b->len, s, n); + b->len += n; + b->buf[b->len] = '\0'; + return true; +} + +static void type_scope_on_name(const char *name, size_t len, void *ud) { + type_scope_build_t *b = (type_scope_build_t *)ud; + if (b->failed || type_scope_seen(b->file, name, len)) { + return; + } + if (b->file->lang->lexical_scopes && type_scope_shadowed(b->file, name, len)) { + return; + } + const char *qn = cbm_type_scope_resolve(b->file, name, len); + if (!qn) { + return; + } + if (b->file->lang->engine_qualifies_own_module) { + /* The engine already qualifies this spelling to exactly this QN. */ + const char *mod = b->file->scope.module_qn; + size_t ml = strlen(mod); + if (strncmp(qn, mod, ml) == 0 && qn[ml] == '.' && strlen(qn + ml + 1) == len && + memcmp(qn + ml + 1, name, len) == 0) { + return; + } + } + if ((b->len && !type_scope_append(b, "|", 1)) || !type_scope_append(b, name, len) || + !type_scope_append(b, "=", 1) || !type_scope_append(b, qn, strlen(qn))) { + return; + } +} + +/* Each '|'-separated piece of `text`; with after_colon, only the part after + * the first ':' of each piece (field_defs' "name:type"). */ +static void type_scope_scan_pieces(type_scope_build_t *b, const char *text, bool after_colon) { + if (!text || !text[0]) { + return; + } + size_t n = strlen(text); + char *copy = cbm_arena_strndup(&b->file->keys, text, n); + if (!copy) { + return; + } + char *piece = copy; + for (size_t i = 0; i <= n; i++) { + if (copy[i] != '|' && copy[i] != '\0') { + continue; + } + copy[i] = '\0'; + const char *t = piece; + if (after_colon) { + const char *colon = strchr(piece, ':'); + t = colon ? colon + 1 : NULL; + } + if (t && t[0]) { + type_scope_names(b->file->lang, t, type_scope_on_name, b); + } + piece = copy + i + 1; + } +} + +void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def) { + if (!file || !arena || !def) { + return; + } + const cbm_type_scope_lang_t *lang = file->lang; + file->serial++; + file->enclosing_class = NULL; + if (lang->lexical_scopes) { + /* A module whose bindings cannot be listed (a star import, an effect + * binding unknown names), and a def inside a function (it sees locals + * the step cannot list): neither gets one. */ + if (file->closed || !def->qualified_name || + type_scope_function_local(file, def->qualified_name)) { + return; + } + file->enclosing_class = type_scope_enclosing_class(file, def->qualified_name); + } + type_scope_build_t b = {.file = file}; + if (lang->return_types) { + type_scope_scan_pieces(&b, def->return_types, false); + } + if (lang->param_types && def->signature_param_types) { + for (int i = 0; i < def->signature_param_count; i++) { + const char *t = def->signature_param_types[i]; + if (t && strcmp(t, "?") != 0) { + type_scope_names(lang, t, type_scope_on_name, &b); + } + } + } + if (lang->field_types) { + type_scope_scan_pieces(&b, def->field_defs, true); + } + if (lang->embedded_types) { + type_scope_scan_pieces(&b, def->embedded_types, false); + } + if (b.len > 0 && !b.failed) { + def->type_scope = cbm_arena_strndup(arena, b.buf, b.len); + } + cbm_free(CBM_MEM_CLASS_EXTRACT, b.buf); +} diff --git a/src/pipeline/type_scope.h b/src/pipeline/type_scope.h new file mode 100644 index 000000000..2235a0f55 --- /dev/null +++ b/src/pipeline/type_scope.h @@ -0,0 +1,130 @@ +/* + * type_scope.h — declared types resolved once, in the scope that wrote them. + * + * A definition's declared types (its return type, parameter types, field + * types) travel to other files as source text inside CBMLSPDef. Each engine + * used to qualify that text against the defining MODULE only, so a type the + * defining file imported from a third file became `.`, + * a name nobody registered, and every call through it was lost. + * + * This step resolves every type name such a text mentions ONCE, in the scope + * of the file that wrote it: the file's own module, then what its imports + * bind. A name gets an identity only when that scope gives exactly one answer + * and that answer is a project definition of a type label the consuming + * engine registers. A name that is not found, is ambiguous, is shadowed by a + * scope the step cannot see into, or is bound to anything outside the project + * keeps no identity, and the engine keeps doing what it did before. There is + * no project-wide name match here. + * + * The result is stored with the definition (CBMLSPDef.type_scope, persisted in + * the file's LSP surface) as "spelling=QN|spelling=QN", the spelling exactly + * as the type text writes it. Only identities the engine cannot derive itself + * are stored: where the engine already qualifies a bare name to + * `.`, a name the file's own module declares is left out. + * The engines read an identity through cbm_type_scope_find (lsp/type_rep.h) + * wherever they would otherwise qualify a type name against the module. + * + * An identity depends on two inputs: the writing file's own content (its type + * texts, its imports, its module) and which project definitions are types. + * The surface hash covers the first and leaves the identities themselves out; + * the incremental planner declines a repair whenever the second changes + * (pipeline_incremental.c, closure_identity_decline). + * + * What is language-specific is a description (cbm_type_scope_lang_t): which + * definition labels an identity may name, how the language's imports and + * scopes bind names, and which CBMLSPDef fields carry raw type text for that + * language. A further language plugs in by adding its row. + */ +#ifndef CBM_PIPELINE_TYPE_SCOPE_H +#define CBM_PIPELINE_TYPE_SCOPE_H + +#include "cbm.h" +#include "foundation/arena.h" +#include "foundation/hash_table.h" +#include "lsp/go_lsp.h" /* CBMLSPDef */ +#include "pipeline/pipeline.h" + +#include +#include + +/* How one language writes type names, and what its engine consumes. */ +typedef struct { + CBMLanguage lang; + /* A name inside quotes is a type name (Python forward references); in + * every other language a quoted run is a literal and is skipped. */ + bool quoted_names; + /* Labels of the definitions an identity may name: the type kinds the + * engine registers and can look members up on. NULL-terminated. */ + const char *const *labels; + /* The engine qualifies a bare name against the defining module itself + * (Go), so an own-module identity need not be stored. Python's cross + * registrar keeps the bare spelling: it is stored there. */ + bool engine_qualifies_own_module; + /* An import binds a module only (Go: a package), so only a qualified + * `pkg.T` resolves through it and a bare name never does. Without it + * (Python) `from m import T` binds the type itself. */ + bool imports_bind_modules; + /* Python: an annotation is evaluated in the def's enclosing scopes before + * the module. A def nested in a function sees that function's locals, + * which the step cannot list, so it gets no identity; a name the + * immediately enclosing class body declares and a PEP 695 type parameter + * of the file get none, and neither does a name the module binds more + * than once (cbm_type_scope_t.module_facts). */ + bool lexical_scopes; + /* Which CBMLSPDef texts hold raw type spellings for this language. */ + bool return_types; + bool param_types; + bool field_types; /* "name:type|name:type" in field_defs */ + bool embedded_types; /* "|"-joined raw spellings in embedded_types */ +} cbm_type_scope_lang_t; + +/* The description for `lang`, or NULL when no engine consumes identities. */ +const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang); + +/* One file's scope: the project's names, the file's module, what the file's + * imports bind (local name -> import QN, the LSP import map), and for a row + * with lexical_scopes the file's own definitions. */ +typedef struct { + const cbm_registry_t *reg; + const char *module_qn; + const char *const *imp_keys; + const char *const *imp_vals; + int imp_count; + /* lexical_scopes only: the file's extraction definitions, in any order + * (their QNs, labels and type_params); NULL with def_count 0 = none. */ + const CBMDefinition *file_defs; + int file_def_count; + /* lexical_scopes only: the module's ordered namespace facts. Without a + * complete record, with a star import or with a parse error the file gets + * no identity; a name the module binds twice (two imports, an import and + * a definition, a later assignment) gets none. */ + const CBMPyNamespaceFacts *module_facts; +} cbm_type_scope_t; + +/* Per-file working state: the import map by key, the file's own scopes, and + * a memo of the spellings already resolved. Build once per file, free after + * the file's defs. */ +typedef struct cbm_type_scope_file cbm_type_scope_file_t; + +cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang, + const cbm_type_scope_t *scope); +void cbm_type_scope_file_end(cbm_type_scope_file_t *file); + +/* The identity of one spelling (`T`, `pkg.T`) in the file's module and import + * scope, or NULL (the def's own enclosing scopes are applied by the attach). + * The returned QN is owned by the file state (valid until file_end). Never a + * short-name guess. */ +const char *cbm_type_scope_resolve(cbm_type_scope_file_t *file, const char *spelling, size_t len); + +/* Set def->type_scope from the def's type texts (per the description), or + * leave it NULL when no name the def writes needs an identity. The string is + * allocated in `arena`. */ +void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def); + +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +/* Work counter for the growth tests: one per byte of type text scanned, per + * hash probe and per enclosing-scope step. Test builds only. */ +uint64_t cbm_type_scope_test_work(void); +#endif + +#endif /* CBM_PIPELINE_TYPE_SCOPE_H */ diff --git a/tests/test_main.c b/tests/test_main.c index 189ad8e93..e93c5f95a 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1860,6 +1860,7 @@ extern void suite_activation_transaction(void); extern void suite_system_info(void); extern void suite_worker_pool(void); extern void suite_parallel(void); +extern void suite_type_scope(void); extern void suite_call_reference_language_complex_contract(void); extern void suite_repro_call_scope_usages(void); extern void suite_repro_call_argument_usages(void); @@ -2748,6 +2749,9 @@ int main(int argc, char **argv) { /* Parallel pipeline */ RUN_SELECTED_SUITE(parallel); + /* Declared types resolved in the scope that wrote them */ + RUN_SELECTED_SUITE(type_scope); + /* Promoted lexical-resolution regression contracts. */ RUN_SELECTED_SUITE(repro_lexical_binding_precision); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 124a1514d..5dd886dcb 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -32548,7 +32548,7 @@ TEST(pipeline_python_namespace_change_admission) { } int body = -9, signature = -9, alias = -9, order = -9; int empty = -9, literal = -9, unknown = -9, deletion = -9, transition = -9; - const char *non_python = "{\"v\":4,\"lang\":0,\"lsp\":[],\"reg\":[],\"py\":null}"; + const char *non_python = "{\"v\":5,\"lang\":0,\"lsp\":[],\"reg\":[],\"py\":null}"; if (complete) { body = cbm_lsp_surface_python_change(json[0], json[1]); signature = cbm_lsp_surface_python_change(json[0], json[2]); @@ -32679,24 +32679,24 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) { * it re-extracts in full. */ const char *bad[] = { "{\"v\":1,\"lsp\":[]}", - "{\"v\":4,\"lang\":1,\"lsp\":[]}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":null}", - "{\"v\":4,\"lang\":1.0,\"lsp\":[],\"py\":null}", - "{\"v\":4,\"v\":4,\"lang\":0,\"lsp\":[],\"py\":null}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[]}", + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":null}", + "{\"v\":5,\"lang\":1.0,\"lsp\":[],\"py\":null}", + "{\"v\":5,\"v\":5,\"lang\":0,\"lsp\":[],\"py\":null}", + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":3,\"failure\":2,\"events\":[]}}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\\u0000suffix\",\"status\":2," "\"failure\":0,\"events\":[]}}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[" "{\"k\":999,\"d\":0,\"s\":0,\"r\":0,\"f\":0,\"l\":0," "\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}", - "{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[" "{\"k\":8,\"d\":0,\"s\":1,\"r\":0,\"f\":0,\"l\":4294967296," "\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}", @@ -32716,7 +32716,7 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) { cbm_arena_destroy(&arena); } const char *unknown = - "{\"v\":4,\"lang\":1,\"lsp\":[],\"reg\":[],\"py\":{\"v\":2,\"lang\":1," + "{\"v\":5,\"lang\":1,\"lsp\":[],\"reg\":[],\"py\":{\"v\":2,\"lang\":1," "\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[" "{\"k\":7,\"d\":0,\"s\":0,\"r\":7,\"f\":0,\"l\":0," "\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}"; @@ -32744,7 +32744,7 @@ TEST(pipeline_lsp_surface_large_object_array_decode) { const size_t capacity = (size_t)count * 192 + 64; char *json = malloc(capacity); ASSERT_NOT_NULL(json); - size_t used = (size_t)snprintf(json, capacity, "{\"v\":4,\"lang\":0,\"py\":null,\"lsp\":["); + size_t used = (size_t)snprintf(json, capacity, "{\"v\":5,\"lang\":0,\"py\":null,\"lsp\":["); for (int i = 0; i < count; i++) { int n = snprintf(json + used, capacity - used, "%s{\"qn\":\"pkg.f%d\",\"sn\":\"f%d\",\"lb\":\"Function\"," @@ -32837,7 +32837,7 @@ TEST(pipeline_lsp_surface_persisted_and_body_edit_invariant) { /* The row is the versioned codec envelope (codec version 4) with * the def present. */ snprintf(json_probe, sizeof(json_probe), "%.20s", row_a->defs_json); - ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":4") != NULL); + ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":5") != NULL); ASSERT_TRUE(strstr(row_a->defs_json, "surface_probe") != NULL); } else if (round == 1) { ASSERT_STR_EQ(row_a->surface_sha, sha_baseline); diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c new file mode 100644 index 000000000..b7922b41a --- /dev/null +++ b/tests/test_type_scope.c @@ -0,0 +1,1212 @@ +/* + * test_type_scope.c — declared types resolved once, in the scope that wrote + * them (src/pipeline/type_scope.h). + * + * Unit tests pin the shared step's answers against a hand-built registry: an + * identity is stored only when the declaring file's scope gives exactly one + * answer and that answer is a project type. Growth tests count the work of + * every loop the step adds at two sizes. Pipeline tests index small fixtures + * per engine (a caller, a file declaring a function or field whose type it + * imports, the file defining that type, and a same-named decoy) with one + * worker and with four, above the parallel threshold; the shapes the review + * of the first cut found false edges in get no edge; and every incremental + * route gives the full index's graph. + */ +#include "test_framework.h" +#include "test_helpers.h" + +#include "foundation/compat.h" +#include "foundation/compat_fs.h" +#include "foundation/arena.h" +#include "lsp/type_rep.h" +#include "pipeline/lsp_surface.h" +#include "pipeline/pass_lsp_cross.h" +#include "pipeline/pipeline.h" +#include "pipeline/pipeline_internal.h" /* incremental route seam */ +#include "pipeline/type_scope.h" +#include "sqlite3.h" +#include "store/store.h" + +#include +#include +#include + +/* ── Unit: the shared step ─────────────────────────────────────────── */ + +typedef struct { + cbm_registry_t *reg; + CBMArena arena; +} ts_unit_t; + +static void ts_unit_begin(ts_unit_t *u) { + u->reg = cbm_registry_new(); + cbm_arena_init(&u->arena); + cbm_registry_add(u->reg, "Store", "p.a.Store", "Class", false); + cbm_registry_add(u->reg, "Store", "p.b.Store", "Class", false); + cbm_registry_add(u->reg, "Result", "p.c.Result", "Variable", false); + cbm_registry_add(u->reg, "make", "p.c.make", "Function", false); + cbm_registry_add(u->reg, "Local", "p.app.Local", "Class", false); +} + +static void ts_unit_end(ts_unit_t *u) { + cbm_registry_free(u->reg); + cbm_arena_destroy(&u->arena); +} + +/* A Python module's namespace facts: each name bound once by an import. */ +typedef struct { + CBMPyNamespaceFact items[16]; + CBMPyNamespaceFacts facts; +} ts_facts_t; + +static const CBMPyNamespaceFacts *ts_facts(ts_facts_t *f, const char *const *bound, int n) { + memset(f, 0, sizeof(*f)); + for (int i = 0; i < n && i < 16; i++) { + f->items[i] = (CBMPyNamespaceFact){.kind = CBM_PY_NS_IMPORT_NAME, .local_name = bound[i]}; + } + f->facts = (CBMPyNamespaceFacts){.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = f->items, + .count = n < 16 ? n : 16, + .cap = 16}; + return &f->facts; +} + +typedef struct { + CBMLanguage lang; + const char *def_qn; /* default p.app.f */ + const char *ret; + const char *const *keys; + const char *const *vals; + int n; + const CBMDefinition *file_defs; + int file_def_count; + const CBMPyNamespaceFacts *facts; /* Python; NULL = one complete empty record */ +} ts_attach_t; + +/* The type_scope one def gets in module p.app. */ +static const char *ts_unit_attach_with(ts_unit_t *u, const ts_attach_t *in) { + ts_facts_t empty; + cbm_type_scope_t scope = {.reg = u->reg, + .module_qn = "p.app", + .imp_keys = in->keys, + .imp_vals = in->vals, + .imp_count = in->n, + .file_defs = in->file_defs, + .file_def_count = in->file_def_count, + .module_facts = in->facts ? in->facts : ts_facts(&empty, NULL, 0)}; + cbm_type_scope_file_t *f = cbm_type_scope_file_begin(cbm_type_scope_lang(in->lang), &scope); + if (!f) { + return ""; + } + CBMLSPDef def = {0}; + def.qualified_name = in->def_qn ? in->def_qn : "p.app.f"; + def.short_name = "f"; + def.label = "Function"; + def.return_types = in->ret; + def.lang = in->lang; + cbm_type_scope_attach(f, &u->arena, &def); + cbm_type_scope_file_end(f); + return def.type_scope; +} + +static const char *ts_unit_attach(ts_unit_t *u, CBMLanguage lang, const char *ret, + const char *const *keys, const char *const *vals, int n) { + ts_attach_t in = {.lang = lang, .ret = ret, .keys = keys, .vals = vals, .n = n}; + return ts_unit_attach_with(u, &in); +} + +TEST(type_scope_import_binding_is_the_identity) { + ts_unit_t u; + ts_unit_begin(&u); + /* `from p.a import Store`-shaped (a module-valued binding) and a direct + * one; the same-named Store of the other module is never chosen. */ + const char *keys[] = {"Store"}; + const char *mod_vals[] = {"p.a"}; + const char *direct_vals[] = {"p.b.Store"}; + ts_facts_t facts; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Optional[Store]", + .keys = keys, + .vals = mod_vals, + .n = 1, + .facts = ts_facts(&facts, keys, 1)}; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Store=p.a.Store"); + in.vals = direct_vals; + in.ret = "list[Store]"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Store=p.b.Store"); + /* The own module declares Store as well: two bindings of one name. */ + cbm_registry_add(u.reg, "Store", "p.app.Store", "Class", false); + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +TEST(type_scope_dotted_spelling_through_its_head) { + ts_unit_t u; + ts_unit_begin(&u); + const char *keys[] = {"a"}; + const char *vals[] = {"p.a"}; + /* Go `*a.Store`, `[]a.Store`, a map value: one identity for `a.Store`. */ + const char *got = + ts_unit_attach(&u, CBM_LANG_GO, "*a.Store|[]a.Store|map[string]a.Store", keys, vals, 1); + ASSERT_STR_EQ(got, "a.Store=p.a.Store"); + /* A name the head's module does not declare: nothing. */ + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "*a.Missing", keys, vals, 1)); + ts_unit_end(&u); + PASS(); +} + +TEST(type_scope_stores_nothing_without_one_answer) { + ts_unit_t u; + ts_unit_begin(&u); + ts_facts_t facts; + /* Two imports bind Store to different targets: ambiguous. */ + const char *keys2[] = {"Store", "Store"}; + const char *vals2[] = {"p.a.Store", "p.b.Store"}; + const char *one[] = {"Store"}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Store", + .keys = keys2, + .vals = vals2, + .n = 2, + .facts = ts_facts(&facts, one, 1)}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* Not found anywhere in scope. */ + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_PYTHON, "Nowhere", NULL, NULL, 0)); + /* Bound, but to something no members are looked up on: a variable and a + * function. */ + const char *rk[] = {"Result", "make"}; + const char *rv[] = {"p.c.Result", "p.c.make"}; + ts_attach_t bound = {.lang = CBM_LANG_PYTHON, + .ret = "Result[make]", + .keys = rk, + .vals = rv, + .n = 2, + .facts = ts_facts(&facts, rk, 2)}; + ASSERT_NULL(ts_unit_attach_with(&u, &bound)); + ts_unit_end(&u); + PASS(); +} + +/* Finding 6: an import that names no project definition (the standard + * library, a third-party package) is no identity, and the engine keeps its + * own handling of the spelling (`Self`). */ +TEST(type_scope_names_outside_the_project_get_none) { + ts_unit_t u; + ts_unit_begin(&u); + ts_facts_t facts; + const char *keys[] = {"Self", "logging", "pathlib"}; + /* What the import map makes of them: project-prefixed paths no node has. */ + const char *vals[] = {"p.typing.Self", "p.logging", "p.pathlib"}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Self", + .keys = keys, + .vals = vals, + .n = 3, + .facts = ts_facts(&facts, keys, 3)}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "logging.Logger"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "pathlib.Path"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +/* Go imports bind packages: a bare name never resolves through one, so a + * type parameter (never dotted) named like an import cannot take a type of + * that package; and an own-module name is left to the engine. */ +TEST(type_scope_go_bare_names_and_own_module) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "T", "p.tpkg.T", "Struct", false); + const char *keys[] = {"T"}; + const char *vals[] = {"p.tpkg"}; + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "T", keys, vals, 1)); + ASSERT_STR_EQ(ts_unit_attach(&u, CBM_LANG_GO, "*T.T", keys, vals, 1), "T.T=p.tpkg.T"); + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "*Local", NULL, NULL, 0)); + ts_unit_end(&u); + PASS(); +} + +/* Python's cross registrar keeps bare spellings, so an own-module identity + * is stored (a forward reference in quotes too). */ +TEST(type_scope_python_own_module) { + ts_unit_t u; + ts_unit_begin(&u); + ASSERT_STR_EQ(ts_unit_attach(&u, CBM_LANG_PYTHON, "Optional[\"Local\"]", NULL, NULL, 0), + "Local=p.app.Local"); + ts_unit_end(&u); + PASS(); +} + +/* Finding 3: a method's annotation is looked up in its class body first. A + * name the enclosing class declares (a nested class, a class attribute) gets + * no identity, and a def inside a function none at all. */ +TEST(type_scope_python_enclosing_scopes) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "Config", "p.app.Config", "Class", false); + cbm_registry_add(u.reg, "Config", "p.app.Model.Config", "Class", false); + cbm_registry_add(u.reg, "Alias", "p.app.Alias", "Class", false); + const CBMDefinition defs[] = { + {.qualified_name = "p.app.Config", .label = "Class"}, + {.qualified_name = "p.app.Alias", .label = "Class"}, + {.qualified_name = "p.app.Model", .label = "Class"}, + {.qualified_name = "p.app.Model.Config", .label = "Class"}, + {.qualified_name = "p.app.Model.Alias", .label = "Variable"}, + {.qualified_name = "p.app.Model.cfg", .label = "Method"}, + {.qualified_name = "p.app.Model.alias", .label = "Method"}, + {.qualified_name = "p.app.Model.Config.owner", .label = "Method"}, + {.qualified_name = "p.app.outer", .label = "Function"}, + {.qualified_name = "p.app.outer.inner", .label = "Function"}, + {.qualified_name = "p.app.top", .label = "Function"}, + }; + int n = (int)(sizeof(defs) / sizeof(defs[0])); + ts_attach_t in = { + .lang = CBM_LANG_PYTHON, .file_defs = defs, .file_def_count = n, .ret = "Config"}; + in.def_qn = "p.app.Model.cfg"; /* Model.Config */ + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.Model.alias"; + in.ret = "Alias"; /* the class attribute Model.Alias */ + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.outer.inner"; /* inside a function: its locals */ + in.ret = "Config"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* The module scope answers where nothing encloses the name. */ + in.def_qn = "p.app.top"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Config=p.app.Config"); + in.def_qn = "p.app.Model.Config.owner"; /* its class declares no `Alias` */ + in.ret = "Alias"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Alias=p.app.Alias"); + ts_unit_end(&u); + PASS(); +} + +/* Type parameters: a PEP 695 parameter of the file (`def f[T]`, + * `class C[T]`) and a TypeVar the module assigns over an import never take a + * real type's identity. */ +TEST(type_scope_python_type_parameters) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "T", "p.app.T", "Class", false); + cbm_registry_add(u.reg, "Item", "p.a.Item", "Class", false); + const CBMDefinition defs[] = { + {.qualified_name = "p.app.T", .label = "Class"}, + {.qualified_name = "p.app.wrap", .label = "Function", .type_params = "T"}, + {.qualified_name = "p.app.Box", .label = "Class", .type_params = "K|T"}, + {.qualified_name = "p.app.Box.get", .label = "Method"}, + }; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .file_defs = defs, + .file_def_count = 4, + .def_qn = "p.app.wrap", + .ret = "T"}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.Box.get"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* `from p.a import Item` then `Item = TypeVar("Item")`: bound twice. */ + CBMPyNamespaceFact twice[] = { + {.kind = CBM_PY_NS_IMPORT_NAME, .local_name = "Item"}, + {.kind = CBM_PY_NS_SHADOW, .local_name = "Item", .reason = CBM_PY_NS_REASON_VALUE}}; + CBMPyNamespaceFacts facts = {.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = twice, + .count = 2, + .cap = 2}; + const char *keys[] = {"Item"}; + const char *vals[] = {"p.a.Item"}; + ts_attach_t tv = {.lang = CBM_LANG_PYTHON, + .ret = "Item", + .keys = keys, + .vals = vals, + .n = 1, + .facts = &facts}; + ASSERT_NULL(ts_unit_attach_with(&u, &tv)); + facts.count = 1; /* the import alone decides */ + ASSERT_STR_EQ(ts_unit_attach_with(&u, &tv), "Item=p.a.Item"); + ts_unit_end(&u); + PASS(); +} + +/* A module whose bindings cannot be listed gets no identity: a star import, + * a parse error, an incomplete record. */ +TEST(type_scope_python_unlisted_bindings_get_none) { + ts_unit_t u; + ts_unit_begin(&u); + CBMPyNamespaceFact star[] = {{.kind = CBM_PY_NS_IMPORT_STAR, .module_name = "p.c"}}; + CBMPyNamespaceFacts facts = {.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = star, + .count = 1, + .cap = 1}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, .ret = "Local", .facts = &facts}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + CBMPyNamespaceFact parse[] = {{.kind = CBM_PY_NS_UNKNOWN, .reason = CBM_PY_NS_REASON_PARSE}}; + facts.items = parse; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* An effect (a call) does not hide bindings from the step. */ + parse[0].reason = CBM_PY_NS_REASON_EFFECT; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Local=p.app.Local"); + facts.status = CBM_PY_NS_INCOMPLETE; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +/* ── Growth: counted work at two sizes ─────────────────────────────── */ + +static bool ts_linear(uint64_t small, uint64_t large) { + /* Twice the input: close to twice the work (names grow by a digit). */ + return small > 0 && large * 10 >= small * 18 && large * 10 <= small * 23; +} + +/* `defs` defs in one file, each writing its own `a.T` (no memo hit), or + * one def writing `defs` distinct names. */ +static uint64_t ts_step_work(int defs, bool one_def) { + ts_unit_t u; + ts_unit_begin(&u); + char qn[64]; + for (int i = 0; i < defs; i++) { + snprintf(qn, sizeof(qn), "p.a.T%d", i); + cbm_registry_add(u.reg, qn + 4, qn, "Struct", false); + } + const char *keys[] = {"a"}; + const char *vals[] = {"p.a"}; + cbm_type_scope_t scope = { + .reg = u.reg, .module_qn = "p.app", .imp_keys = keys, .imp_vals = vals, .imp_count = 1}; + cbm_type_scope_file_t *f = cbm_type_scope_file_begin(cbm_type_scope_lang(CBM_LANG_GO), &scope); + char *all = (char *)calloc((size_t)defs, 16); + size_t at = 0; + uint64_t before = cbm_type_scope_test_work(); + for (int i = 0; i < defs; i++) { + char text[32]; + snprintf(text, sizeof(text), "*a.T%d", i); + if (one_def) { + at += (size_t)snprintf(all + at, 16, "%s%s", at ? "|" : "", text); + continue; + } + CBMLSPDef def = {.qualified_name = "p.app.f", .short_name = "f", .label = "Function"}; + def.return_types = text; + def.lang = CBM_LANG_GO; + cbm_type_scope_attach(f, &u.arena, &def); + } + if (one_def) { + CBMLSPDef def = {.qualified_name = "p.app.f", .short_name = "f", .label = "Function"}; + def.return_types = all; + def.lang = CBM_LANG_GO; + cbm_type_scope_attach(f, &u.arena, &def); + } + uint64_t work = cbm_type_scope_test_work() - before; + free(all); + cbm_type_scope_file_end(f); + ts_unit_end(&u); + return work; +} + +TEST(type_scope_step_work_grows_linearly) { + uint64_t defs_small = ts_step_work(1000, false); + uint64_t defs_large = ts_step_work(2000, false); + uint64_t names_small = ts_step_work(1000, true); + uint64_t names_large = ts_step_work(2000, true); + printf(" step work: defs 1000=%llu 2000=%llu, names in one def 1000=%llu 2000=%llu\n", + (unsigned long long)defs_small, (unsigned long long)defs_large, + (unsigned long long)names_small, (unsigned long long)names_large); + ASSERT_TRUE(ts_linear(defs_small, defs_large)); + ASSERT_TRUE(ts_linear(names_small, names_large)); + PASS(); +} + +/* The engines' lookup: one def with k identities, k lookups. */ +static uint64_t ts_lookup_work(int k) { + CBMArena a; + cbm_arena_init(&a); + size_t cap = (size_t)k * 40 + 1; + char *scope = (char *)calloc(cap, 1); + size_t at = 0; + for (int i = 0; i < k; i++) { + at += (size_t)snprintf(scope + at, cap - at, "%sa.T%d=p.a.T%d", at ? "|" : "", i, i); + } + uint64_t before = cbm_type_scope_index_test_work(); + const cbm_type_scope_index_t *ix = cbm_type_scope_index(&a, scope); + int found = 0; + for (int i = 0; i < k; i++) { + char name[32]; + int n = snprintf(name, sizeof(name), "a.T%d", i); + found += cbm_type_scope_find(ix, name, (size_t)n) != NULL; + } + uint64_t work = cbm_type_scope_index_test_work() - before; + free(scope); + cbm_arena_destroy(&a); + return found == k ? work : 0; +} + +TEST(type_scope_lookup_work_grows_linearly) { + uint64_t small = ts_lookup_work(1000); + uint64_t large = ts_lookup_work(2000); + printf(" lookup work: 1000 identities=%llu 2000=%llu\n", (unsigned long long)small, + (unsigned long long)large); + ASSERT_TRUE(ts_linear(small, large)); + PASS(); +} + +/* The per-file selection's worklist. A chain (module i's def names module + * i-1's type) and a fan (n modules' defs all name one module of n defs): the + * fan walked that module once per identity before. */ +static uint64_t ts_reach_work(int n, bool fan) { + CBMArena a; + cbm_arena_init(&a); + int count = fan ? 2 * n : n; + CBMLSPDef *defs = (CBMLSPDef *)calloc((size_t)count, sizeof(CBMLSPDef)); + for (int i = 0; i < count; i++) { + CBMLSPDef *d = &defs[i]; + bool hub = fan && i >= n; /* the fan's target module, n defs */ + int mod = hub ? n : i; + d->def_module_qn = cbm_arena_sprintf(&a, "p.m%d", mod); + d->qualified_name = cbm_arena_sprintf(&a, "p.m%d.T%d", mod, i); + d->short_name = "T"; + d->label = hub || !fan ? "Struct" : "Function"; + d->lang = CBM_LANG_GO; + if (!hub && (fan || i > 0)) { + int target = fan ? n : i - 1; + int target_def = fan ? n : i - 1; + d->type_scope = cbm_arena_sprintf(&a, "x.T=p.m%d.T%d", target, target_def); + } + } + CBMModuleDefIndex *idx = cbm_pxc_build_module_def_index(defs, count); + char own[32]; + snprintf(own, sizeof(own), "p.m%d", fan ? 0 : n - 1); + /* The fan's caller imports every holder module. */ + const char **imps = (const char **)calloc((size_t)n, sizeof(char *)); + for (int i = 0; i < n; i++) { + imps[i] = cbm_arena_sprintf(&a, "p.m%d", i); + } + uint64_t before = cbm_pxc_test_reach_work(); + int out = 0; + bool ok = false; + CBMLSPDef *sel = cbm_pxc_filter_defs_for_file(idx, defs, CBM_LANG_GO, NULL, own, + fan ? imps : NULL, fan ? n : 0, &out, &ok); + uint64_t work = cbm_pxc_test_reach_work() - before; + free(sel); + free(imps); + cbm_pxc_free_module_def_index(idx); + free(defs); + cbm_arena_destroy(&a); + return ok && out == count ? work : 0; +} + +TEST(type_scope_reach_work_grows_linearly) { + uint64_t chain_small = ts_reach_work(1000, false); + uint64_t chain_large = ts_reach_work(2000, false); + uint64_t fan_small = ts_reach_work(1000, true); + uint64_t fan_large = ts_reach_work(2000, true); + printf(" reach work: chain 1000=%llu 2000=%llu, fan 1000=%llu 2000=%llu\n", + (unsigned long long)chain_small, (unsigned long long)chain_large, + (unsigned long long)fan_small, (unsigned long long)fan_large); + ASSERT_TRUE(ts_linear(chain_small, chain_large)); + ASSERT_TRUE(ts_linear(fan_small, fan_large)); + PASS(); +} + +/* The planner's identity gate over n stored rows, each holding one identity, + * after a change of the type one of them names. */ +static uint64_t ts_decline_work(int n, const char **reason) { + cbm_lsp_surface_row_t *rows = (cbm_lsp_surface_row_t *)calloc((size_t)n, sizeof(*rows)); + for (int i = 0; i < n; i++) { + char *json = (char *)malloc(256); + snprintf(json, 256, + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.f%d.New\",\"sn\":\"New\",\"lb\":" + "\"Function\",\"lg\":%d,\"ty\":\"store.T%d=p.store.T%d\"}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, i, (int)CBM_LANG_GO, i, i); + rows[i].defs_json = json; + } + char before_row[256]; + snprintf(before_row, sizeof(before_row), + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\"," + "\"lg\":%d,\"al\":\"Impl\"}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO); + char after_row[256]; + snprintf(after_row, sizeof(after_row), + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\"," + "\"lg\":%d,\"al\":null}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO); + const char *old_rows[] = {before_row}; + const char *new_rows[] = {after_row}; + uint64_t work = 0; + *reason = cbm_lsp_surface_identity_decline(old_rows, new_rows, 1, rows, n, &work); + for (int i = 0; i < n; i++) { + free((void *)rows[i].defs_json); + } + free(rows); + return work; +} + +TEST(type_scope_identity_gate_work_grows_linearly) { + const char *small_reason = NULL; + const char *large_reason = NULL; + uint64_t small = ts_decline_work(1000, &small_reason); + uint64_t large = ts_decline_work(2000, &large_reason); + printf(" identity gate work: 1000 rows=%llu 2000=%llu (%s)\n", (unsigned long long)small, + (unsigned long long)large, large_reason ? large_reason : "kept"); + ASSERT_STR_EQ(small_reason, "identity_target_changed"); + ASSERT_STR_EQ(large_reason, "identity_target_changed"); + ASSERT_TRUE(ts_linear(small, large)); + PASS(); +} + +/* ── Pipeline fixtures ─────────────────────────────────────────────── */ + +/* CALLS edges from a node named `src` to the node whose QN ends in + * `tgt_qn_tail` whose properties contain `fragment` (NULL = any). */ +static int ts_calls_to(cbm_store_t *s, const char *project, const char *src, + const char *tgt_qn_tail, const char *fragment) { + cbm_edge_t *edges = NULL; + int count = 0; + if (cbm_store_find_edges_by_type(s, project, "CALLS", &edges, &count) != CBM_STORE_OK) { + return -1; + } + int matches = 0; + size_t tail = strlen(tgt_qn_tail); + for (int i = 0; i < count; i++) { + cbm_node_t a = {0}; + cbm_node_t b = {0}; + bool ok = cbm_store_find_node_by_id(s, edges[i].source_id, &a) == CBM_STORE_OK && + cbm_store_find_node_by_id(s, edges[i].target_id, &b) == CBM_STORE_OK; + size_t qn_len = ok && b.qualified_name ? strlen(b.qualified_name) : 0; + if (ok && a.name && strcmp(a.name, src) == 0 && qn_len >= tail && + strcmp(b.qualified_name + qn_len - tail, tgt_qn_tail) == 0 && + (qn_len == tail || b.qualified_name[qn_len - tail - 1] == '.') && + (!fragment || (edges[i].properties_json && strstr(edges[i].properties_json, fragment)))) { + matches++; + } + cbm_node_free_fields(&a); + cbm_node_free_fields(&b); + } + if (edges) { + cbm_store_free_edges(edges, count); + } + return matches; +} + +#define TS_LSP "\"strategy\":\"lsp_" + +typedef struct { + const char *rel; + const char *content; +} ts_file_t; + +static void ts_write(const char *tmp, const ts_file_t *files) { + for (int i = 0; files && files[i].rel; i++) { + th_write_file(TH_PATH(tmp, files[i].rel), files[i].content); + } +} + +/* Filler files that put a fixture above the parallel threshold. */ +static void ts_pad(const char *tmp, CBMLanguage lang, int count) { + for (int i = 0; i < count; i++) { + char rel[64]; + char body[128]; + if (lang == CBM_LANG_GO) { + snprintf(rel, sizeof(rel), "fill/f%d.go", i); + snprintf(body, sizeof(body), "package fill\n\nfunc F%d() int { return %d }\n", i, i); + } else { + snprintf(rel, sizeof(rel), "fill/f%d.py", i); + snprintf(body, sizeof(body), "def f%d():\n return %d\n", i, i); + } + th_write_file(TH_PATH(tmp, rel), body); + } +} + +enum { TS_PAD_FILES = 52 }; /* above the parallel threshold (50 files) */ + +/* Full index of `tmp` with CBM_WORKERS=workers into tmp/. */ +static cbm_store_t *ts_index_workers(const char *tmp, const char *db_name, int workers, + char *project, size_t project_size) { + char *saved = NULL; + const char *old = getenv("CBM_WORKERS"); + saved = old ? strdup(old) : NULL; + char w[16]; + snprintf(w, sizeof(w), "%d", workers); + cbm_setenv("CBM_WORKERS", w, 1); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/%s", tmp, db_name); + cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL); + int rc = p ? cbm_pipeline_run(p) : -1; + if (p) { + snprintf(project, project_size, "%s", cbm_pipeline_project_name(p)); + } + cbm_pipeline_free(p); + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + return rc == 0 ? cbm_store_open_path(db_path) : NULL; +} + +/* One fixture indexed with one worker and with four (both above the parallel + * threshold); `check` returns 0 when the graph is right. */ +typedef int (*ts_check_fn)(cbm_store_t *s, const char *project, const char *label); + +static int ts_twins(const char *name, const ts_file_t *files, CBMLanguage pad_lang, + ts_check_fn check) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_%s_XXXXXX", name); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + ts_write(tmp, files); + ts_pad(tmp, pad_lang, TS_PAD_FILES); + int bad = 0; + for (int run = 0; run < 2 && !bad; run++) { + int workers = run == 0 ? 1 : 4; + char project[256] = {0}; + cbm_store_t *s = ts_index_workers(tmp, run == 0 ? "seq.db" : "par.db", workers, project, + sizeof(project)); + if (!s) { + bad = 1; + break; + } + bad = check(s, project, run == 0 ? "1 worker" : "4 workers"); + cbm_store_close(s); + } + th_rmtree(tmp); + ASSERT_EQ(bad, 0); + PASS(); +} + +/* Go: app calls fixture.New() (returns *store.Store) and reads + * fixture.NewHolder().S (a field of type *store.Store); fixture.go imports + * store. decoy/ declares a same-named Store with the same method. */ +static const ts_file_t go_scope_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"decoy/store.go", "package decoy\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store { return &store.Store{} }\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n\n" + "func Field() string {\n\th := fixture.NewHolder()\n\treturn h.S.Get(\"y\")\n}\n"}, + {NULL, NULL}}; + +static int go_scope_check(cbm_store_t *s, const char *project, const char *label) { + int ret_hit = ts_calls_to(s, project, "Run", "store.Store.Get", TS_LSP); + int ret_decoy = ts_calls_to(s, project, "Run", "decoy.Store.Get", NULL); + int field_hit = ts_calls_to(s, project, "Field", "store.Store.Get", TS_LSP); + int field_decoy = ts_calls_to(s, project, "Field", "decoy.Store.Get", NULL); + printf(" go (%s): return=%d decoy=%d field=%d decoy=%d\n", label, ret_hit, ret_decoy, + field_hit, field_decoy); + return !(ret_hit == 1 && ret_decoy == 0 && field_hit == 1 && field_decoy == 0); +} + +TEST(type_scope_go_return_and_field_types) { + return ts_twins("go", go_scope_files, CBM_LANG_GO, go_scope_check); +} + +/* Go: a type parameter named like an import (`import T "…/tpkg"`, then + * `func Wrap[T any](x T) T`) is the parameter inside Wrap, not tpkg's T. */ +static const ts_file_t go_tparam_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"tpkg/t.go", "package tpkg\n\ntype T struct{ n int }\n\nfunc (t T) M() string { return \"t\" }\n"}, + {"other/x.go", "package other\n\ntype X struct{ n int }\n\nfunc (x X) M() string { return \"x\" }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport T \"example.com/demo/tpkg\"\n\n" + "var Keep T.T\n\nfunc Wrap[T any](x T) T { return x }\n"}, + {"app/app.go", "package app\n\nimport (\n\t\"example.com/demo/fixture\"\n" + "\t\"example.com/demo/other\"\n)\n\n" + "func Run() string { return fixture.Wrap(other.X{}).M() }\n"}, + {NULL, NULL}}; + +static int go_tparam_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "Run", "tpkg.T.M", NULL); + printf(" go type parameter (%s): edge to tpkg.T.M=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_go_type_parameter_is_no_import) { + return ts_twins("gotp", go_tparam_files, CBM_LANG_GO, go_tparam_check); +} + +/* Python: app.py calls fixture.make() (-> Store, imported by fixture.py from + * pkg.store) and fixture.local() (-> Local, fixture.py's own class). decoy.py + * declares a same-named Store with the same method. */ +static const ts_file_t py_scope_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/store.py", "class Store:\n def get(self, k):\n return k\n"}, + {"pkg/decoy.py", "class Store:\n def get(self, k):\n return k\n"}, + {"pkg/fixture.py", "from pkg.store import Store\n\n\n" + "class Local:\n def ping(self):\n return 1\n\n\n" + "def make() -> Store:\n return Store()\n\n\n" + "def local() -> Local:\n return Local()\n"}, + {"pkg/app.py", "from pkg.fixture import make, local\n\n\n" + "def run():\n s = make()\n return s.get(\"x\")\n\n\n" + "def own():\n v = local()\n return v.ping()\n"}, + {NULL, NULL}}; + +static int py_scope_check(cbm_store_t *s, const char *project, const char *label) { + int ret_hit = ts_calls_to(s, project, "run", "pkg.store.Store.get", TS_LSP); + int ret_decoy = ts_calls_to(s, project, "run", "pkg.decoy.Store.get", NULL); + int own_hit = ts_calls_to(s, project, "own", "pkg.fixture.Local.ping", TS_LSP); + printf(" python (%s): return=%d decoy=%d own=%d\n", label, ret_hit, ret_decoy, own_hit); + return !(ret_hit == 1 && ret_decoy == 0 && own_hit == 1); +} + +TEST(type_scope_python_return_types) { + return ts_twins("py", py_scope_files, CBM_LANG_PYTHON, py_scope_check); +} + +/* Finding 3: `def cfg(self) -> Config` in a class with a nested `Config` + * names Model.Config, never the module-level Config. */ +static const ts_file_t py_nested_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/mod.py", "class Config:\n def load(self):\n return 1\n\n\n" + "class Model:\n" + " class Config:\n def load(self):\n return 2\n\n" + " def cfg(self) -> Config:\n return Model.Config()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run():\n m = Model()\n return m.cfg().load()\n"}, + {NULL, NULL}}; + +static int py_nested_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" python nested class (%s): edge to module-level Config.load=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_python_nested_class_is_not_the_module_class) { + return ts_twins("pynest", py_nested_files, CBM_LANG_PYTHON, py_nested_check); +} + +/* Finding 6: `-> Self` chains across files keep main's edges; `Self` comes + * from typing, which the project does not define. A decoy declares the same + * method names. */ +static const ts_file_t py_self_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/builder.py", "from typing import Self\n\n\n" + "class Builder:\n" + " def a(self) -> Self:\n return self\n\n" + " def b(self) -> Self:\n return self\n\n" + " def done(self) -> int:\n return 1\n"}, + {"pkg/app.py", "from pkg.builder import Builder\n\n\n" + "def run():\n x = Builder()\n return x.a().b().done()\n"}, + {"pkg/decoy.py", "class Other:\n" + " def a(self):\n return self\n\n" + " def b(self):\n return self\n\n" + " def done(self):\n return 2\n"}, + {NULL, NULL}}; + +static int py_self_check(cbm_store_t *s, const char *project, const char *label) { + int a = ts_calls_to(s, project, "run", "pkg.builder.Builder.a", NULL); + int b = ts_calls_to(s, project, "run", "pkg.builder.Builder.b", NULL); + int done = ts_calls_to(s, project, "run", "pkg.builder.Builder.done", NULL); + int decoy = ts_calls_to(s, project, "run", "pkg.decoy.Other.done", NULL) + + ts_calls_to(s, project, "run", "pkg.decoy.Other.b", NULL); + printf(" python Self chain (%s): a=%d b=%d done=%d decoy=%d\n", label, a, b, done, decoy); + return !(a == 1 && b == 1 && done == 1 && decoy == 0); +} + +TEST(type_scope_python_self_chain_keeps_its_edges) { + return ts_twins("pyself", py_self_files, CBM_LANG_PYTHON, py_self_check); +} + +/* Type parameters: `def wrap[Item](x: Item) -> Item` in a file that also + * imports a class Item; the caller passes an Other. */ +static const ts_file_t py_tparam_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/item.py", "class Item:\n def save(self):\n return 1\n"}, + {"pkg/other.py", "class Other:\n def save(self):\n return 2\n"}, + {"pkg/box.py", "from pkg.item import Item\n\n\n" + "def touch(i: Item) -> None:\n i.save()\n\n\n" + "def wrap[Item](x: Item) -> Item:\n return x\n"}, + {"pkg/app.py", "from pkg.box import wrap\nfrom pkg.other import Other\n\n\n" + "def go():\n o = wrap(Other())\n return o.save()\n"}, + {NULL, NULL}}; + +static int py_tparam_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "go", "pkg.item.Item.save", NULL); + printf(" python type parameter (%s): edge to pkg.item.Item.save=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_python_type_parameter_is_no_import) { + return ts_twins("pytp", py_tparam_files, CBM_LANG_PYTHON, py_tparam_check); +} + +/* ── Full index versus every incremental route ───────────────────── */ + +static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, + size_t *len) { + sqlite3_stmt *st = NULL; + if (sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) { + return; + } + sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT); + while (sqlite3_step(st) == SQLITE_ROW) { + const char *row = (const char *)sqlite3_column_text(st, 0); + size_t n = row ? strlen(row) : 0; + char *grown = (char *)realloc(*buf, *len + n + 2); + if (!grown) { + break; + } + *buf = grown; + memcpy(*buf + *len, row ? row : "", n); + *len += n; + (*buf)[(*len)++] = '\n'; + (*buf)[*len] = '\0'; + } + sqlite3_finalize(st); +} + +/* Every node (label, QN) and edge (type, source QN, target QN, properties) + * of the project, sorted: equal listings are equal graphs. A call's `args` + * are left out: on main already the closure route renders them differently + * from a full index (quote style, key order), whatever the resolver did. */ +static char *ts_listing(const char *db_path, const char *project) { + sqlite3 *db = NULL; + if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + sqlite3_close(db); + return NULL; + } + char *buf = (char *)calloc(1, 1); + size_t len = 0; + ts_listing_append(db, + "SELECT label||'|'||qualified_name FROM nodes WHERE project=?1 ORDER BY 1", + project, &buf, &len); + ts_listing_append(db, + "SELECT e.type||'|'||s.qualified_name||'|'||t.qualified_name||'|'||" + "CASE WHEN json_valid(e.properties) THEN json_remove(e.properties, '$.args') " + "ELSE coalesce(e.properties, '') END FROM edges e " + "JOIN nodes s ON s.id=e.source_id " + "JOIN nodes t ON t.id=e.target_id WHERE e.project=?1 ORDER BY 1", + project, &buf, &len); + sqlite3_close(db); + return buf; +} + +/* Print the lines one listing has and the other lacks (a failing case). */ +static void ts_listing_diff(const char *a, const char *b, const char *tag) { + for (const char *line = a; line && *line;) { + const char *nl = strchr(line, '\n'); + size_t n = nl ? (size_t)(nl - line) : strlen(line); + bool found = false; + for (const char *p = b; p && *p && !found;) { + const char *pnl = strchr(p, '\n'); + size_t pn = pnl ? (size_t)(pnl - p) : strlen(p); + found = pn == n && memcmp(p, line, n) == 0; + p = pnl ? pnl + 1 : p + pn; + } + if (!found) { + printf(" only %s: %.*s\n", tag, (int)n, line); + } + line = nl ? nl + 1 : line + n; + } +} + +typedef struct { + cbm_incremental_route_t route; + cbm_incremental_closure_plan_t plan; + bool same_graph; +} ts_incr_result_t; + +/* Index `files` (plus `pad` Go or Python fillers), apply `edits`, index again + * incrementally into the same database, then index the edited tree afresh; + * the two graphs must be equal whatever route the incremental run took. */ +static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_lang, int pad, + const ts_file_t *edits, const char *tag) { + ts_incr_result_t r = {.route = CBM_INCREMENTAL_ROUTE_NONE}; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_incr_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + return r; + } + ts_write(tmp, files); + ts_pad(tmp, pad_lang, pad); + char db[512]; + snprintf(db, sizeof(db), "%s/incr.db", tmp); + cbm_pipeline_t *base = cbm_pipeline_new(tmp, db, CBM_MODE_FULL); + char project[256] = {0}; + if (base && cbm_pipeline_run(base) == 0) { + snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(base)); + } + cbm_pipeline_free(base); + + ts_write(tmp, edits); + cbm_pipeline_incremental_test_reset_faults(); + cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL); + int rc = incr ? cbm_pipeline_run(incr) : -1; + r.route = cbm_pipeline_incremental_test_last_route(); + r.plan = cbm_pipeline_incremental_test_last_closure_plan(); + cbm_pipeline_free(incr); + + char full_db[512]; + snprintf(full_db, sizeof(full_db), "%s/full.db", tmp); + cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL); + int full_rc = full ? cbm_pipeline_run(full) : -1; + cbm_pipeline_free(full); + + char *repaired = rc == 0 && project[0] ? ts_listing(db, project) : NULL; + char *fresh = full_rc == 0 && project[0] ? ts_listing(full_db, project) : NULL; + r.same_graph = repaired && fresh && strcmp(repaired, fresh) == 0; + printf(" incremental %s: route=%d plan files=%d surface_changed=%d dependents=%d " + "decline=%s same_graph=%d\n", + tag, (int)r.route, r.plan.files, r.plan.surface_changed, r.plan.dependents, + r.plan.decline ? r.plan.decline : "-", (int)r.same_graph); + if (!r.same_graph && repaired && fresh) { + ts_listing_diff(repaired, fresh, "incremental"); + ts_listing_diff(fresh, repaired, "full"); + } + free(repaired); + free(fresh); + th_rmtree(tmp); + return r; +} + +/* Only the caller is re-parsed (a closure of one file: the per-file Go + * registrar): fixture.go's identities come back from its stored row. */ +TEST(type_scope_incremental_caller_edit_per_file_go) { + const ts_file_t edit[] = { + {"app/app.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\tv := s.Get(\"x\")\n\treturn v\n}\n\n" + "func Field() string {\n\th := fixture.NewHolder()\n\treturn h.S.Get(\"y\")\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(go_scope_files, CBM_LANG_GO, 0, edit, "go caller edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 9: a body edit of the file that holds the identities, with twelve + * dependents in a 40-file tree (the review's go-incr), stays a one-file + * repair as on main: the probe and the stored row hash the same bytes. */ +static const ts_file_t go_incr_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store { return &store.Store{} }\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {"app0/app.go", "package app0\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app1/app.go", "package app1\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app2/app.go", "package app2\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app3/app.go", "package app3\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app4/app.go", "package app4\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app5/app.go", "package app5\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app6/app.go", "package app6\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app7/app.go", "package app7\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app8/app.go", "package app8\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app9/app.go", "package app9\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app10/app.go", "package app10\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app11/app.go", "package app11\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {NULL, NULL}}; + +TEST(type_scope_incremental_body_edit_stays_one_file) { + const ts_file_t edit[] = { + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store {\n\ts := &store.Store{}\n\treturn s\n}\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(go_incr_files, CBM_LANG_GO, 25, edit, "go body edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_EQ(r.plan.surface_changed, 0); + ASSERT_EQ(r.plan.dependents, 0); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 7, Go: the type an identity names changes in its declaring file + * while every name stays (an alias that becomes a defined type, a type that + * becomes a variable), and a caller two imports away resolved through it. + * The methods live in other files of the package, so the caller is no + * dependent of the edited file. The doc-link scope records an exported + * type's kind and alias target, so main already declines these; the graph + * must still be the full index's. */ +static const ts_file_t go_alias_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "type T = Impl\n"}, + {"store/b2.go", "package store\n\nfunc (i Impl) M() string { return \"impl\" }\n"}, + {"store/b3.go", "package store\n\nfunc (i Impl2) M() string { return \"impl2\" }\n"}, + {"decoy/d.go", "package decoy\n\ntype T struct{ n int }\n\nfunc (t T) M() string { return \"d\" }\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "func Make() store.T { return store.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().M() }\n"}, + {NULL, NULL}}; + +/* The change the doc-link scope does not see (it records an exported type's + * name, kind, alias target and field names, never a field's type): the + * struct an identity names gets another field type. The caller resolved + * `fixture.Get().S.Get()` through fixture.go's identity `model.Holder` and + * Holder's field; it has no edge into model/b.go. */ +TEST(type_scope_incremental_named_type_field_change_matches_full) { + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\ntype Other struct{ n int }\n"}, + {"store/m1.go", "package store\n\nfunc (s *Store) Get() string { return \"s\" }\n"}, + {"store/m2.go", "package store\n\nfunc (o *Other) Get() string { return \"o\" }\n"}, + {"model/b.go", "package model\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/model\"\n\n" + "func Get() model.Holder { return model.Holder{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Get().S.Get() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"model/b.go", "package model\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Other\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go named type field change"); + ASSERT_TRUE(r.same_graph); + ASSERT_STR_EQ(r.plan.decline, "identity_target_changed"); + PASS(); +} + +TEST(type_scope_incremental_type_shape_changes_match_full) { + const ts_file_t to_defined[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "type T Impl\n"}, + {NULL, NULL}}; + ts_incr_result_t r = + ts_incremental(go_alias_files, CBM_LANG_GO, 0, to_defined, "go alias->defined type"); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_FORCED_FULL); + const ts_file_t to_var[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "var T = Impl{}\n"}, + {NULL, NULL}}; + r = ts_incremental(go_alias_files, CBM_LANG_GO, 0, to_var, "go type->var"); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_FORCED_FULL); + PASS(); +} + +/* The gate is narrow: a signature change of another definition in the + * declaring file stays a repair. */ +TEST(type_scope_incremental_other_def_edit_stays_a_repair) { + const ts_file_t edit[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype T = Impl\n\n" + "func Helper(n int) int { return n }\n"}, + {NULL, NULL}}; + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype T = Impl\n\n" + "func Helper() int { return 1 }\n"}, + {"store/b2.go", "package store\n\nfunc (i Impl) M() string { return \"impl\" }\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "func Make() store.T { return store.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().M() }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go other def edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Python: a caller's body edit re-resolves that file alone with the per-file + * Python registrar, reading fixture.py's identities from its stored row; a + * body edit of fixture.py itself stays a one-file repair too. */ +TEST(type_scope_incremental_python_body_edits) { + const ts_file_t caller[] = { + {"pkg/app.py", "from pkg.fixture import make, local\n\n\n" + "def run():\n s = make()\n v = s.get(\"x\")\n return v\n\n\n" + "def own():\n v = local()\n return v.ping()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(py_scope_files, CBM_LANG_PYTHON, 0, caller, "py caller"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + const ts_file_t declaring[] = { + {"pkg/fixture.py", "from pkg.store import Store\n\n\n" + "class Local:\n def ping(self):\n return 1\n\n\n" + "def make() -> Store:\n s = Store()\n return s\n\n\n" + "def local() -> Local:\n return Local()\n"}, + {NULL, NULL}}; + r = ts_incremental(py_scope_files, CBM_LANG_PYTHON, 0, declaring, "py declaring body"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_EQ(r.plan.surface_changed, 0); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 7, Python: the declaring module's name changes from an alias to a + * class (and a class to a function), a caller two imports away. */ +TEST(type_scope_incremental_python_declaring_change_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/b.py", "class Impl:\n def m(self):\n return 1\n\n\nT = Impl\n"}, + {"pkg/a.py", "from pkg.b import T\n\n\ndef make() -> T:\n return T()\n"}, + {"pkg/c.py", "from pkg.a import make\n\n\ndef run():\n return make().m()\n"}, + {NULL, NULL}}; + const ts_file_t to_class[] = { + {"pkg/b.py", "class Impl:\n def m(self):\n return 1\n\n\n" + "class T:\n def m(self):\n return 2\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_PYTHON, 0, to_class, "py alias->class"); + ASSERT_TRUE(r.same_graph); + const ts_file_t start_class[] = { + {"pkg/__init__.py", ""}, + {"pkg/b.py", "class T:\n def m(self):\n return 1\n"}, + {"pkg/a.py", "from pkg.b import T\n\n\ndef make() -> T:\n return T()\n"}, + {"pkg/c.py", "from pkg.a import make\n\n\ndef run():\n return make().m()\n"}, + {NULL, NULL}}; + const ts_file_t to_function[] = { + {"pkg/b.py", "def T():\n return 1\n\n\ndef m():\n return 2\n"}, {NULL, NULL}}; + r = ts_incremental(start_class, CBM_LANG_PYTHON, 0, to_function, "py class->function"); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +SUITE(type_scope) { + RUN_TEST(type_scope_import_binding_is_the_identity); + RUN_TEST(type_scope_dotted_spelling_through_its_head); + RUN_TEST(type_scope_stores_nothing_without_one_answer); + RUN_TEST(type_scope_names_outside_the_project_get_none); + RUN_TEST(type_scope_go_bare_names_and_own_module); + RUN_TEST(type_scope_python_own_module); + RUN_TEST(type_scope_python_enclosing_scopes); + RUN_TEST(type_scope_python_type_parameters); + RUN_TEST(type_scope_python_unlisted_bindings_get_none); + RUN_TEST(type_scope_step_work_grows_linearly); + RUN_TEST(type_scope_lookup_work_grows_linearly); + RUN_TEST(type_scope_reach_work_grows_linearly); + RUN_TEST(type_scope_identity_gate_work_grows_linearly); + RUN_TEST(type_scope_go_return_and_field_types); + RUN_TEST(type_scope_go_type_parameter_is_no_import); + RUN_TEST(type_scope_python_return_types); + RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); + RUN_TEST(type_scope_python_self_chain_keeps_its_edges); + RUN_TEST(type_scope_python_type_parameter_is_no_import); + RUN_TEST(type_scope_incremental_caller_edit_per_file_go); + RUN_TEST(type_scope_incremental_body_edit_stays_one_file); + RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); + RUN_TEST(type_scope_incremental_type_shape_changes_match_full); + RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); + RUN_TEST(type_scope_incremental_python_body_edits); + RUN_TEST(type_scope_incremental_python_declaring_change_matches_full); +} From bdc27776ebbdba5d3bbe4a6856e2eb90f974ebe5 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 01:14:09 +0100 Subject: [PATCH 06/25] fix(lsp): Go struct fields on their own registry entry Both Go registrars attached a struct's fields to the FIRST registry entry of its qualified name: a receiver placeholder when a method of the struct was registered first. A type lookup after finalize answers with the LAST entry of that name, so the fields were never seen and every field chain through such a struct died (helm's `r.cfg.Releases.DeployedAll`). The fields are now parsed onto the struct's own entry, the placeholder keeping them too for the first-registered readers. Go module QNs are directories: a package and its external test package (`foo`, `foo_test`), or build-tagged variants, can declare two structs of one QN, and which entry a lookup answers with depends on file order. Such a QN keeps no fields in either registrar, as before this change, where its fields were never visible. Signed-off-by: Martin Vogel --- internal/cbm/lsp/go_lsp.c | 110 +++++++++++++++------------ tests/test_type_scope.c | 151 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 214 insertions(+), 47 deletions(-) diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 76f6f7770..49aaabaf1 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -935,13 +935,13 @@ const CBMType *go_eval_builtin_call(GoLSPContext *ctx, const char *name, TSNode // --- Import-alias re-qualification ------------------------------------ // -// parse_field_defs_into_type qualifies struct field type texts as -// ".". When the author wrote the text through an import -// alias ("Svc:svc.Svc" in module test.main), that yields a QN -// ("test.main.svc.Svc") that exists nowhere in the project-wide registry — -// the real QN is ".Svc" and only the calling file's import map -// can say so. On an exact-QN miss this rewrites the alias segment through -// the file's imports; returns NULL when no alias segment is involved. +// parse_field_defs qualifies a struct field type text the defining file's +// scope did not resolve (no identity in the def's type_scope) as +// ".". Written through an import alias ("Svc:svc.Svc" in +// module test.main), that yields a QN ("test.main.svc.Svc") that exists +// nowhere in the project-wide registry. On an exact-QN miss this rewrites the +// alias segment through the calling file's imports; returns NULL when no alias +// segment is involved. static const char *go_requalify_via_imports(GoLSPContext *ctx, const char *type_qn) { if (!ctx || !type_qn || !type_qn[0] || ctx->import_count <= 0) @@ -2849,24 +2849,32 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char return idx > 0; } -static void parse_field_defs_into_type(CBMArena *arena, CBMTypeRegistry *reg, const char *type_qn, - const char *field_defs, const char *def_module_qn, - const cbm_type_scope_index_t *scope_ix) { - if (!field_defs || !field_defs[0] || !type_qn) - return; - const char **names = NULL; - const CBMType **types = NULL; - if (parse_field_defs(arena, field_defs, def_module_qn, scope_ix, &names, &types)) { - // Find the registered type and update field info - for (int ti = 0; ti < reg->type_count; ti++) { - if (reg->types[ti].qualified_name && - strcmp(reg->types[ti].qualified_name, type_qn) == 0) { - reg->types[ti].field_names = names; - reg->types[ti].field_types = types; - break; - } +/* Go module QNs are directories, so a package and its external test package + * (`foo` and `foo_test`), or build-tagged variants, can declare two types of + * one QN. A type lookup answers with one entry of a name, which one depends on + * file order; what is keyed by such a QN (its fields, its embedded types) is + * therefore registered for neither. Returns the QNs two or more type + * definitions share (owned keys borrowed from defs; free with cbm_ht_free), or + * NULL on allocation failure (then nothing counts as shared). */ +static char g_go_qn_once_mark; +static char g_go_qn_shared_mark; + +static CBMHashTable *go_shared_type_qns(const CBMLSPDef *defs, int def_count) { + CBMHashTable *seen = cbm_ht_create((uint32_t)(def_count / 4 + 64)); + for (int i = 0; seen && i < def_count; i++) { + const CBMLSPDef *d = &defs[i]; + if (!d->qualified_name || !d->label || d->lang != CBM_LANG_GO || + !cbm_label_is_type_like(d->label)) { + continue; } + void *prev = cbm_ht_get(seen, d->qualified_name); + cbm_ht_set(seen, d->qualified_name, prev ? &g_go_qn_shared_mark : &g_go_qn_once_mark); } + return seen; +} + +static bool go_type_qn_shared(const CBMHashTable *shared, const char *qn) { + return shared && qn && cbm_ht_get(shared, qn) == &g_go_qn_shared_mark; } // --- Phase 1c: Extract type parameters from generic function declarations --- @@ -3378,6 +3386,7 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // caller's arena which outlives this call, so cbm_arena_strdup is // wasted work. On kubernetes (~110k defs × 11k files × 5 strdups // ~= 6B mallocs) this alone saves ~90s of resolve wall time. + CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); for (int i = 0; i < def_count; i++) { CBMLSPDef *d = &defs[i]; if (!d->qualified_name || !d->short_name || !d->label) @@ -3403,13 +3412,17 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, } rt.alias_of = go_alias_target_qn(arena, d->alias_target, def_mod); - cbm_registry_add_type(®, rt); - - // Populate struct field types from field_defs - if (d->field_defs && d->field_defs[0]) { - parse_field_defs_into_type(arena, ®, rt.qualified_name, d->field_defs, def_mod, - scope_ix); + // Struct field types from field_defs, on this def's own entry: a + // type lookup answers with the last entry of a name, so fields on + // an earlier receiver placeholder were never seen. A QN two type + // definitions share keeps none (go_shared_type_qns). + if (d->field_defs && d->field_defs[0] && + !go_type_qn_shared(shared_qns, d->qualified_name)) { + (void)parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &rt.field_names, + &rt.field_types); } + + cbm_registry_add_type(®, rt); } // Function/Method @@ -3444,6 +3457,7 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, cbm_registry_add_func(®, rf); } } + cbm_ht_free(shared_qns); /* NULL-safe */ // 3. Phase 1b: Scan AST for struct definitions to populate embedded_types { @@ -3661,11 +3675,12 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * not finalized until the end, so its own lookup scans every type, and the * receiver check below plus the field-definition lookup made the build * O(types x (methods + structs)) -- 4.4 s single-threaded on the Go corpus, - * the scaling lane's parse_field_defs_into_type x2.9 (waste sanitizer, - * 2026-09-17). First-match semantics are kept exactly: a receiver's - * placeholder type added before its struct still receives the fields. - * NULL on allocation failure: the linear paths below run as before. */ + * the scaling lane's field-definition lookup x2.9 (waste sanitizer, + * 2026-09-17). A receiver's placeholder type added before its struct + * receives the struct's fields as well as the struct's own entry. + * NULL on allocation failure: the receiver check scans the registry. */ CBMHashTable *first_type = cbm_ht_create((uint32_t)(def_count / 4 + 1024)); + CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); int noted_types = 0; #define GO_NOTE_NEW_TYPES() \ do { \ @@ -3705,22 +3720,22 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i rt.method_names = split_pipe_strings(arena, d->method_names_str); } rt.alias_of = go_alias_target_qn(arena, d->alias_target, def_mod); + /* Fields on this def's own entry, which a lookup after finalize + * answers with (the last entry of a name). The first entry -- a + * receiver placeholder when a method came earlier -- keeps them + * too, for the first-registered readers. A QN two type + * definitions share keeps none (go_shared_type_qns). */ + if (d->field_defs && d->field_defs[0] && + !go_type_qn_shared(shared_qns, d->qualified_name)) { + (void)parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &rt.field_names, + &rt.field_types); + } cbm_registry_add_type(reg, rt); GO_NOTE_NEW_TYPES(); - if (d->field_defs && d->field_defs[0]) { - if (first_type) { - const char **names = NULL; - const CBMType **types = NULL; - uintptr_t at = (uintptr_t)cbm_ht_get(first_type, rt.qualified_name); - if (parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &names, &types) && - at) { - reg->types[at - 1].field_names = names; - reg->types[at - 1].field_types = types; - } - } else { - parse_field_defs_into_type(arena, reg, rt.qualified_name, d->field_defs, - def_mod, scope_ix); - } + uintptr_t at = first_type ? (uintptr_t)cbm_ht_get(first_type, rt.qualified_name) : 0; + if (rt.field_names && at && (int)at - 1 != reg->type_count - 1) { + reg->types[at - 1].field_names = rt.field_names; + reg->types[at - 1].field_types = rt.field_types; } } @@ -3754,6 +3769,7 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i } #undef GO_NOTE_NEW_TYPES cbm_ht_free(first_type); + cbm_ht_free(shared_qns); /* NULL-safe */ cbm_registry_finalize(reg); reg->read_only = true; /* seal: shared Tier-2 registry is read-only during resolve */ diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index b7922b41a..7e3071650 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -840,6 +840,153 @@ TEST(type_scope_python_type_parameter_is_no_import) { return ts_twins("pytp", py_tparam_files, CBM_LANG_PYTHON, py_tparam_check); } +/* ── Go registrars: fields ────────────────────────────────────────── */ + +/* Resolve `source` (module test.main or `module_qn`) against `defs` with the + * per-file registrar or the shared one; the number of resolved calls to + * `callee`. */ +static int ts_go_registry_hits(bool shared, const char *source, const char *module_qn, + CBMLSPDef *defs, int def_count, const char **imp_names, + const char **imp_qns, int imp_count, const char *callee) { + CBMArena arena; + cbm_arena_init(&arena); + CBMResolvedCallArray out = {0}; + if (shared) { + CBMTypeRegistry *reg = cbm_go_build_cross_registry(&arena, defs, def_count); + if (reg) { + cbm_run_go_lsp_cross_with_registry(&arena, source, (int)strlen(source), module_qn, + NULL, reg, imp_names, imp_qns, imp_count, NULL, + &out); + } + } else { + cbm_run_go_lsp_cross(&arena, source, (int)strlen(source), module_qn, NULL, defs, + def_count, imp_names, imp_qns, imp_count, NULL, &out); + } + int hits = 0; + for (int i = 0; i < out.count; i++) { + if (out.items[i].callee_qn && strcmp(out.items[i].callee_qn, callee) == 0) { + hits++; + } + } + cbm_arena_destroy(&arena); + return hits; +} + +/* A method of Configuration registered before the struct makes a receiver + * placeholder first; after finalize a type lookup answers with the last + * entry of that name, so the struct's fields must sit on its own entry. They + * sat on the placeholder, and every field chain through such a struct died + * (helm's `cfg.Releases.Get`). The field type also comes through an identity + * (`store.Storage`). */ +static int go_registry_field_case(bool shared) { + const char *source = "package main\n\n" + "import \"p/cfg\"\n\n" + "func run(c *cfg.Configuration) string {\n" + "\treturn c.Releases.Get(\"x\")\n}\n"; + CBMLSPDef defs[] = { + {.qualified_name = "test.main.run", + .short_name = "run", + .label = "Function", + .def_module_qn = "test.main", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.cfg.Configuration.hook", + .short_name = "hook", + .label = "Method", + .def_module_qn = "p.cfg", + .receiver_type = "p.cfg.Configuration", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.cfg.Configuration", + .short_name = "Configuration", + .label = "Struct", + .def_module_qn = "p.cfg", + .field_defs = "Releases:*store.Storage", + .type_scope = "store.Storage=p.store.Storage", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.store.Storage", + .short_name = "Storage", + .label = "Struct", + .def_module_qn = "p.store", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.store.Storage.Get", + .short_name = "Get", + .label = "Method", + .def_module_qn = "p.store", + .receiver_type = "p.store.Storage", + .return_types = "string", + .lang = CBM_LANG_GO}, + }; + const char *imp_names[] = {"cfg"}; + const char *imp_qns[] = {"p.cfg"}; + int hits = ts_go_registry_hits(shared, source, "test.main", defs, 5, imp_names, imp_qns, 1, + "p.store.Storage.Get"); + printf(" go registry (%s): run -> Storage.Get resolved %d\n", shared ? "shared" : "per-file", + hits); + ASSERT_EQ(hits, 1); + PASS(); +} + +TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file) { + return go_registry_field_case(false); +} + +TEST(type_scope_go_fields_survive_an_earlier_receiver_shared) { + return go_registry_field_case(true); +} + +/* `package svc` and `package svc_test` in one directory both declare a + * struct S (one QN): which S a lookup answers with depends on file order, so + * neither's fields are registered, and the answer is the same in both + * orders. */ +static int go_shared_qn_case(bool shared) { + const char *source = "package svc_test\n\n" + "func run(s *S) string { return s.X.Get() }\n"; + CBMLSPDef real_s = {.qualified_name = "p.svc.S", + .short_name = "S", + .label = "Struct", + .def_module_qn = "p.svc", + .field_defs = "X:*real.Store", + .type_scope = "real.Store=p.real.Store", + .lang = CBM_LANG_GO}; + CBMLSPDef fake_s = real_s; + fake_s.field_defs = "X:*fake.Store"; + fake_s.type_scope = "fake.Store=p.fake.Store"; + CBMLSPDef rest[] = { + {.qualified_name = "p.real.Store", .short_name = "Store", .label = "Struct", + .def_module_qn = "p.real", .lang = CBM_LANG_GO}, + {.qualified_name = "p.real.Store.Get", .short_name = "Get", .label = "Method", + .def_module_qn = "p.real", .receiver_type = "p.real.Store", .return_types = "string", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.fake.Store", .short_name = "Store", .label = "Struct", + .def_module_qn = "p.fake", .lang = CBM_LANG_GO}, + {.qualified_name = "p.fake.Store.Get", .short_name = "Get", .label = "Method", + .def_module_qn = "p.fake", .receiver_type = "p.fake.Store", .return_types = "string", + .lang = CBM_LANG_GO}, + }; + int hits[2][2]; + for (int order = 0; order < 2; order++) { + CBMLSPDef defs[6]; + defs[0] = order ? fake_s : real_s; + defs[1] = order ? real_s : fake_s; + memcpy(defs + 2, rest, sizeof(rest)); + hits[order][0] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.real.Store.Get"); + hits[order][1] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.fake.Store.Get"); + } + printf(" go shared QN (%s): order A real=%d fake=%d, order B real=%d fake=%d\n", + shared ? "shared" : "per-file", hits[0][0], hits[0][1], hits[1][0], hits[1][1]); + ASSERT_EQ(hits[0][0] + hits[0][1] + hits[1][0] + hits[1][1], 0); + PASS(); +} + +TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file) { + return go_shared_qn_case(false); +} + +TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared) { + return go_shared_qn_case(true); +} + /* ── Full index versus every incremental route ───────────────────── */ static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, @@ -1202,6 +1349,10 @@ SUITE(type_scope) { RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); + RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); + RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_shared); + RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file); + RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); RUN_TEST(type_scope_incremental_body_edit_stays_one_file); RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); From dfa846771fdd28fd0d93fcad2dae9677da59fcc7 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 01:14:29 +0100 Subject: [PATCH 07/25] feat(lsp): bind Go closure parameters wherever the literal stands The Go walker recursed into a func literal's body as plain children of the enclosing scope; its declared parameters were bound only when the literal was evaluated as an expression (an argument, an assignment). A literal in a composite literal's field value, a test table's `run: func(reg *httpmock.Registry) { reg.Register(...) }`, left `reg` untyped and every call through it unresolved. The walker now walks every func literal it reaches with its parameters bound, through the same helper the evaluator uses. Signed-off-by: Martin Vogel --- internal/cbm/lsp/go_lsp.c | 83 ++++++++++++++++++++++----------------- tests/test_type_scope.c | 30 ++++++++++++++ 2 files changed, 77 insertions(+), 36 deletions(-) diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 49aaabaf1..1656daa26 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -346,6 +346,45 @@ static void go_unify_type(const CBMType *param_type, const CBMType *arg_type, // --- go_eval_expr_type: recursive expression type evaluator --- +/* Walk a closure's body in a child scope (inheriting every outer binding) + * with its declared parameters bound: `func(reg *httpmock.Registry) { + * reg.Register(...) }` types `reg` wherever the literal stands (an + * argument, an assignment, a composite literal's field value). */ +static void go_walk_func_literal(GoLSPContext *ctx, TSNode node) { + TSNode body = ts_node_child_by_field_name(node, "body", 4); + if (ts_node_is_null(body)) { + return; + } + CBMScope *saved = ctx->current_scope; + ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); + TSNode params = ts_node_child_by_field_name(node, "parameters", 10); + if (!ts_node_is_null(params)) { + uint32_t nc = ts_node_child_count(params); + for (uint32_t i = 0; i < nc; i++) { + TSNode param = ts_node_child(params, i); + if (ts_node_is_null(param) || !ts_node_is_named(param) || + strcmp(ts_node_type(param), "parameter_declaration") != 0) { + continue; + } + TSNode type_node = ts_node_child_by_field_name(param, "type", 4); + const CBMType *pt = go_parse_type_node(ctx, type_node); + uint32_t pnc = ts_node_child_count(param); + for (uint32_t j = 0; j < pnc; j++) { + TSNode ch = ts_node_child(param, j); + if (!ts_node_is_null(ch) && ts_node_is_named(ch) && + strcmp(ts_node_type(ch), "identifier") == 0) { + char *pname = lsp_node_text(ctx, ch); + if (pname && strcmp(pname, "_") != 0) { + cbm_scope_bind(ctx->current_scope, pname, pt); + } + } + } + } + } + resolve_calls_in_node(ctx, body); + ctx->current_scope = saved; +} + const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (ts_node_is_null(node)) return cbm_type_unknown(); @@ -805,42 +844,7 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { // --- Func literal (closure) --- if (strcmp(kind, "func_literal") == 0) { // Process the closure body to resolve calls with captured scope - TSNode body = ts_node_child_by_field_name(node, "body", 4); - if (!ts_node_is_null(body)) { - // Push child scope (inherits all outer bindings via parent chain) - CBMScope *saved = ctx->current_scope; - ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); - - // Bind closure parameters - TSNode params = ts_node_child_by_field_name(node, "parameters", 10); - if (!ts_node_is_null(params)) { - uint32_t nc = ts_node_child_count(params); - for (uint32_t i = 0; i < nc; i++) { - TSNode param = ts_node_child(params, i); - if (ts_node_is_null(param) || !ts_node_is_named(param)) - continue; - if (strcmp(ts_node_type(param), "parameter_declaration") != 0) - continue; - TSNode type_node = ts_node_child_by_field_name(param, "type", 4); - const CBMType *pt = go_parse_type_node(ctx, type_node); - uint32_t pnc = ts_node_child_count(param); - for (uint32_t j = 0; j < pnc; j++) { - TSNode ch = ts_node_child(param, j); - if (!ts_node_is_null(ch) && ts_node_is_named(ch) && - strcmp(ts_node_type(ch), "identifier") == 0) { - char *pname = lsp_node_text(ctx, ch); - if (pname && strcmp(pname, "_") != 0) - cbm_scope_bind(ctx->current_scope, pname, pt); - } - } - } - } - - // Walk closure body to resolve calls - resolve_calls_in_node(ctx, body); - - ctx->current_scope = saved; - } + go_walk_func_literal(ctx, node); // Build full FUNC type with param/return types from AST const CBMType *pt_arr[16]; @@ -1529,6 +1533,13 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { return; const char *kind = ts_node_type(node); + /* A closure the walk reaches is walked with its parameters bound, not + * as plain children in the enclosing scope. */ + if (strcmp(kind, "func_literal") == 0) { + go_walk_func_literal(ctx, node); + return; + } + // Process statements to build scope go_process_statement(ctx, node); diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 7e3071650..e03b09d8a 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -987,6 +987,35 @@ TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared) { return go_shared_qn_case(true); } +/* ── Go: closure parameters ───────────────────────────────────────── */ + +/* A closure parameter is typed wherever the literal stands, here as a + * composite literal's field value (a test table), not only where the literal + * is evaluated. decoy/ declares the same Store with the same method. */ +static const ts_file_t go_closure_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"decoy/store.go", "package decoy\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/store\"\n\n" + "type stub struct {\n\trun func(s *store.Store) string\n}\n\n" + "func Closure() string {\n" + "\ttt := []stub{{run: func(s *store.Store) string { return s.Get(\"x\") }}}\n" + "\treturn tt[0].run(nil)\n}\n"}, + {NULL, NULL}}; + +static int go_closure_check(cbm_store_t *s, const char *project, const char *label) { + int closure = ts_calls_to(s, project, "Closure", "store.Store.Get", TS_LSP); + int decoy = ts_calls_to(s, project, "Closure", "decoy.Store.Get", NULL); + printf(" go closure (%s): closure=%d decoy=%d\n", label, closure, decoy); + return !(closure == 1 && decoy == 0); +} + +TEST(type_scope_go_closure_parameters_in_composite_literals) { + return ts_twins("goclos", go_closure_files, CBM_LANG_GO, go_closure_check); +} + /* ── Full index versus every incremental route ───────────────────── */ static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, @@ -1353,6 +1382,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_shared); RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file); RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared); + RUN_TEST(type_scope_go_closure_parameters_in_composite_literals); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); RUN_TEST(type_scope_incremental_body_edit_stays_one_file); RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); From dc81846a8e55708fca3e95f3d539d8280b4917b0 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 04:21:33 +0100 Subject: [PATCH 08/25] feat(lsp): type Go package-level values across files `pkg.Default.Get()` and a bare `Default.Get()` of another file of the package stayed untyped: Variable definitions carried no type, and the Go registrars ignored them. A package-level `var`/`const` now records the type its declaration or its single initializer spells (`T`, `T{}`, `&T{}`, `new(T)`, a const block's implicit repetition; nothing inferred) in CBMDefinition.value_type. The pipeline hands it to the cross-file LSP as the Variable's type, the Go registrars register the value under . with CBM_FUNC_FLAG_VALUE, and `pkg.V` / `V` evaluate to that type. The type is not written to the graph: no Variable node of any language carries one today. A value is never a call target, on every route: the walker's callable lookups and the fast resolve of unresolved calls both skip it, so a call through a function-typed value keeps main's edge and strategy. A directory holds both `package foo` and `package foo_test`, and their package-level names share one directory QN. A value whose QN another definition also has (a value of another type or identity, a function of the other package) is registered for neither, so the answer never depends on file order; values of one QN that spell the same type with the same identities (build variants of one declaration) give one answer and stay. The struct rule of the earlier commit becomes the same kind of rule: a struct QN whose definitions all spell the same fields with the same identities keeps them. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 7 ++ internal/cbm/extract_defs.c | 61 ++++++++++ internal/cbm/lsp/go_lsp.c | 193 +++++++++++++++++++++++++----- internal/cbm/lsp/type_registry.h | 4 + internal/cbm/result_compact.c | 1 + src/pipeline/pass_lsp_cross.c | 5 + src/pipeline/pipeline.c | 3 +- tests/test_type_scope.c | 195 +++++++++++++++++++++++++++++++ 8 files changed, 438 insertions(+), 31 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 8a4f9005a..8b4fe71fe 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -334,6 +334,13 @@ typedef struct { * written to the graph. NULL when none and in every other language. Tail * field: zero-init stays valid. */ const char *type_params; + /* Go only: the type a package-level `var`/`const` declares, or the type + * its single initializer spells (`T{}` is T, `&T{}` and `new(T)` are *T, + * a const block's bare spec repeats the previous one's). It reaches the + * cross-file LSP as the Variable's type (go_lsp.c, package-level values) + * and is never written to the graph. NULL for anything else and in every + * other language. Tail field: zero-init stays valid. */ + const char *value_type; } CBMDefinition; /* extra_props key of a generated member, one the compiler writes and the diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 75885e076..70c561555 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -11067,6 +11067,53 @@ static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) { } } +/* Go: the type a package-level `var`/`const` spec declares, else the type + * its single initializer spells: `T{...}` is T, `&T{...}` is *T, `new(T)` is + * *T. NULL for anything else (a call's result, an arithmetic expression): + * nothing is inferred. */ +static const char *go_value_type_text(CBMArena *a, TSNode spec, const char *source) { + TSNode type = ts_node_child_by_field_name(spec, TS_FIELD("type")); + if (!ts_node_is_null(type)) { + return cbm_node_text(a, type, source); + } + TSNode value = ts_node_child_by_field_name(spec, TS_FIELD("value")); + if (!ts_node_is_null(value) && strcmp(ts_node_type(value), "expression_list") == 0) { + value = ts_node_named_child_count(value) == 1 ? ts_node_named_child(value, 0) : (TSNode){0}; + } + if (ts_node_is_null(value)) { + return NULL; + } + bool pointer = false; + if (strcmp(ts_node_type(value), "unary_expression") == 0) { + TSNode op = ts_node_child_by_field_name(value, TS_FIELD("operator")); + const char *ot = ts_node_is_null(op) ? NULL : cbm_node_text(a, op, source); + if (!ot || strcmp(ot, "&") != 0) { + return NULL; + } + value = ts_node_child_by_field_name(value, TS_FIELD("operand")); + pointer = true; + if (ts_node_is_null(value)) { + return NULL; + } + } + const char *vk = ts_node_type(value); + const char *text = NULL; + if (strcmp(vk, "composite_literal") == 0) { + TSNode t = ts_node_child_by_field_name(value, TS_FIELD("type")); + text = ts_node_is_null(t) ? NULL : cbm_node_text(a, t, source); + } else if (!pointer && strcmp(vk, "call_expression") == 0) { + TSNode fn = ts_node_child_by_field_name(value, TS_FIELD("function")); + TSNode args = ts_node_child_by_field_name(value, TS_FIELD("arguments")); + const char *fname = ts_node_is_null(fn) ? NULL : cbm_node_text(a, fn, source); + if (fname && strcmp(fname, "new") == 0 && !ts_node_is_null(args) && + ts_node_named_child_count(args) == 1) { + text = cbm_node_text(a, ts_node_named_child(args, 0), source); + pointer = true; + } + } + return text && pointer ? cbm_arena_sprintf(a, "*%s", text) : text; +} + static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a, const char *kind) { (void)kind; @@ -11095,13 +11142,27 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a } case CBM_LANG_GO: { uint32_t n = ts_node_named_child_count(node); + /* In a const block a spec with neither type nor value repeats the + * previous spec's (`A Kind = iota; B; C`). */ + const char *repeated = NULL; for (uint32_t i = 0; i < n; i++) { TSNode child = ts_node_named_child(node, i); const char *ck = ts_node_type(child); if (strcmp(ck, "var_spec") == 0 || strcmp(ck, "const_spec") == 0) { + bool bare = strcmp(ck, "const_spec") == 0 && + ts_node_is_null(ts_node_child_by_field_name(child, TS_FIELD("type"))) && + ts_node_is_null(ts_node_child_by_field_name(child, TS_FIELD("value"))); + const char *vtype = bare ? repeated : go_value_type_text(a, child, ctx->source); + repeated = vtype; TSNode vname = ts_node_child_by_field_name(child, TS_FIELD("name")); if (!ts_node_is_null(vname)) { + int before = ctx->result->defs.count; push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child); + /* The value's type reaches other files (pkg.V.Method()), + * never the graph (CBMDefinition.value_type). */ + if (vtype && ctx->result->defs.count == before + 1) { + ctx->result->defs.items[before].value_type = vtype; + } } } } diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 1656daa26..451ceeaaa 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -385,6 +385,35 @@ static void go_walk_func_literal(GoLSPContext *ctx, TSNode node) { ctx->current_scope = saved; } +/* The type a package-level symbol has as an expression: a value's declared + * type (CBM_FUNC_FLAG_VALUE: the signature's single result), a function's + * own signature. NULL when unknown. */ +static const CBMType *go_symbol_type(const CBMRegisteredFunc *f) { + if (!f || !f->signature) { + return NULL; + } + if ((f->flags & CBM_FUNC_FLAG_VALUE) == 0) { + return f->signature; + } + const CBMType **rets = + f->signature->kind == CBM_TYPE_FUNC ? f->signature->data.func.return_types : NULL; + return rets && rets[0] ? rets[0] : NULL; +} + +/* A package-level symbol a call can target: a function, never a value. */ +static const CBMRegisteredFunc *go_lookup_callable(const CBMTypeRegistry *reg, + const char *package_qn, const char *name) { + const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(reg, package_qn, name); + return f && (f->flags & CBM_FUNC_FLAG_VALUE) ? NULL : f; +} + +/* The same rule for a lookup by full QN (the fast resolve path). */ +static const CBMRegisteredFunc *go_lookup_func_callable(const CBMTypeRegistry *reg, + const char *qn) { + const CBMRegisteredFunc *f = cbm_registry_lookup_func(reg, qn); + return f && (f->flags & CBM_FUNC_FLAG_VALUE) ? NULL : f; +} + const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (ts_node_is_null(node)) return cbm_type_unknown(); @@ -402,11 +431,11 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (cbm_scope_contains(ctx->current_scope, name)) return t ? t : cbm_type_unknown(); - // Check if it's a package-level function - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); - if (f && f->signature) - return f->signature; + // A package-level function or value (of any file of the package) + const CBMType *st = + go_symbol_type(cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name)); + if (st) + return st; // Check if it's a builtin type (for type conversions like string(x), int(x)) const CBMType *bt = resolve_builtin_type(ctx, name); @@ -439,11 +468,11 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (pkg_name) { const char *pkg_qn = resolve_import(ctx, pkg_name); if (pkg_qn) { - // Look up pkg.Symbol as a function or type - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name); - if (f && f->signature) - return f->signature; + // Look up pkg.Symbol as a function, a value or a type + const CBMType *st = go_symbol_type( + cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name)); + if (st) + return st; // Check if it's a type char *type_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", pkg_qn, field_name); const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); @@ -1097,8 +1126,7 @@ static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node) { if (cbm_scope_contains(ctx->current_scope, name)) { return cbm_scope_lookup_callable(ctx->current_scope, name); } - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); + const CBMRegisteredFunc *f = go_lookup_callable(ctx->registry, ctx->package_qn, name); return f ? f->qualified_name : NULL; } @@ -1115,8 +1143,7 @@ static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node) { char *local = lsp_node_text(ctx, operand); const char *package_qn = local ? resolve_import(ctx, local) : NULL; if (package_qn) { - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, package_qn, member); + const CBMRegisteredFunc *f = go_lookup_callable(ctx->registry, package_qn, member); return f ? f->qualified_name : NULL; } } @@ -1570,7 +1597,7 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { const char *pkg_qn = resolve_import(ctx, pkg_name); if (pkg_qn && field_name) { const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name); + go_lookup_callable(ctx->registry, pkg_qn, field_name); if (f) { emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, node); @@ -1766,7 +1793,7 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { } // Package-local function const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); + go_lookup_callable(ctx->registry, ctx->package_qn, name); if (f) { emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, node); } else { @@ -2748,6 +2775,100 @@ static const CBMType **split_pipe_types(CBMArena *a, const char *text, const cha return idx > 0 ? arr : NULL; } +/* The mark of a QN in the tables below (go_shared_type_qns, + * go_value_qn_counts) whose definitions give different answers; any other + * value is the QN's first definition. */ +static char g_go_qn_shared_mark; + +static bool go_type_qn_shared(const CBMHashTable *shared, const char *qn) { + return shared && qn && cbm_ht_get(shared, qn) == &g_go_qn_shared_mark; +} + +static bool go_same_text(const char *a, const char *b) { + return (!a || !a[0]) ? (!b || !b[0]) : (b && strcmp(a, b) == 0); +} + +/* The QN a package-level value registers under: ., or NULL + * for a def that is no typed value. */ +static const char *go_value_qn(CBMArena *a, const CBMLSPDef *d, const char *def_mod) { + if (!d->label || strcmp(d->label, "Variable") != 0 || !d->short_name || !d->return_types || + !d->return_types[0] || strchr(d->return_types, '|') || !def_mod || !def_mod[0]) { + return NULL; + } + return cbm_arena_sprintf(a, "%s.%s", def_mod, d->short_name); +} + +/* Every Go def QN and every value QN, marked shared when two defs that give + * different answers have it. A directory holds both `package foo` and + * `package foo_test`, and their package-level names live under one directory + * QN: a value whose QN another definition also has (a value of another type + * or identity, a function, a type of the other package) is registered for + * neither, so no answer depends on file order. Two values of one QN that + * spell the same type with the same identities (build variants of one + * declaration) give one answer and stay. NULL on allocation failure (then no + * value is registered). */ +static CBMHashTable *go_value_qn_counts(CBMArena *a, const CBMLSPDef *defs, int def_count, + const char *fallback_mod) { + CBMHashTable *seen = cbm_ht_create((uint32_t)(def_count / 4 + 64)); + for (int i = 0; seen && i < def_count; i++) { + const CBMLSPDef *d = &defs[i]; + if (!d->qualified_name || d->lang != CBM_LANG_GO) { + continue; + } + const char *def_mod = d->def_module_qn ? d->def_module_qn : fallback_mod; + const char *value_qn = go_value_qn(a, d, def_mod); + const char *keys[2] = {d->qualified_name, + value_qn && strcmp(value_qn, d->qualified_name) != 0 ? value_qn + : NULL}; + for (int k = 0; k < 2; k++) { + if (!keys[k]) { + continue; + } + void *prev = cbm_ht_get(seen, keys[k]); + if (!prev) { + cbm_ht_set(seen, keys[k], (void *)d); /* the first definition */ + continue; + } + const CBMLSPDef *first = (const CBMLSPDef *)prev; + bool same_value = prev != &g_go_qn_shared_mark && value_qn && + go_value_qn(a, first, first->def_module_qn ? first->def_module_qn + : fallback_mod) && + go_same_text(first->return_types, d->return_types) && + go_same_text(first->type_scope, d->type_scope); + if (!same_value) { + cbm_ht_set(seen, keys[k], &g_go_qn_shared_mark); + } + } + } + return seen; +} + +/* A package-level value (a Go `var`/`const` Variable def whose declaration or + * initializer spells its type): registered under . with + * CBM_FUNC_FLAG_VALUE and that type as the signature's single result, so + * `pkg.V.Method()` and a bare `V.Method()` of another file are typed. A + * value is never a call target (go_lookup_callable, go_lookup_func_callable), + * and a QN another definition shares registers no value (go_value_qn_counts). */ +static void go_register_value(CBMTypeRegistry *reg, CBMArena *a, const CBMLSPDef *d, + const char *def_mod, const cbm_type_scope_index_t *scope_ix, + const CBMHashTable *value_qns) { + const char *qn = go_value_qn(a, d, def_mod); + if (!qn || !value_qns || go_type_qn_shared(value_qns, qn)) { + return; + } + const CBMType **ret = split_pipe_types(a, d->return_types, def_mod, scope_ix); + if (!ret || !ret[0] || cbm_type_is_unknown(ret[0])) { + return; + } + CBMRegisteredFunc rf; + memset(&rf, 0, sizeof(rf)); + rf.qualified_name = qn; + rf.short_name = d->short_name; + rf.signature = cbm_type_func(a, NULL, NULL, ret); + rf.flags = CBM_FUNC_FLAG_VALUE; + cbm_registry_add_func(reg, rf); +} + // Helper: split "|"-separated string into array of const char*. static const char **split_pipe_strings(CBMArena *a, const char *text) { if (!text || !text[0]) @@ -2864,12 +2985,12 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char * (`foo` and `foo_test`), or build-tagged variants, can declare two types of * one QN. A type lookup answers with one entry of a name, which one depends on * file order; what is keyed by such a QN (its fields, its embedded types) is - * therefore registered for neither. Returns the QNs two or more type - * definitions share (owned keys borrowed from defs; free with cbm_ht_free), or - * NULL on allocation failure (then nothing counts as shared). */ -static char g_go_qn_once_mark; -static char g_go_qn_shared_mark; - + * therefore registered for neither, unless every definition of the QN spells + * the same fields and embedded types with the same identities (build variants + * of one struct): then every order gives one answer. Returns the QNs whose + * definitions differ (marked shared; keys borrowed from defs; free with + * cbm_ht_free), or NULL on allocation failure (then nothing counts as + * shared). */ static CBMHashTable *go_shared_type_qns(const CBMLSPDef *defs, int def_count) { CBMHashTable *seen = cbm_ht_create((uint32_t)(def_count / 4 + 64)); for (int i = 0; seen && i < def_count; i++) { @@ -2879,15 +3000,21 @@ static CBMHashTable *go_shared_type_qns(const CBMLSPDef *defs, int def_count) { continue; } void *prev = cbm_ht_get(seen, d->qualified_name); - cbm_ht_set(seen, d->qualified_name, prev ? &g_go_qn_shared_mark : &g_go_qn_once_mark); + if (!prev) { + cbm_ht_set(seen, d->qualified_name, (void *)d); /* the first definition */ + continue; + } + const CBMLSPDef *first = (const CBMLSPDef *)prev; + if (prev != &g_go_qn_shared_mark && + (!go_same_text(first->field_defs, d->field_defs) || + !go_same_text(first->embedded_types, d->embedded_types) || + !go_same_text(first->type_scope, d->type_scope))) { + cbm_ht_set(seen, d->qualified_name, &g_go_qn_shared_mark); + } } return seen; } -static bool go_type_qn_shared(const CBMHashTable *shared, const char *qn) { - return shared && qn && cbm_ht_get(shared, qn) == &g_go_qn_shared_mark; -} - // --- Phase 1c: Extract type parameters from generic function declarations --- // Helper: parse a tree-sitter type AST node with type param awareness. @@ -3398,6 +3525,7 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // wasted work. On kubernetes (~110k defs × 11k files × 5 strdups // ~= 6B mallocs) this alone saves ~90s of resolve wall time. CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); + CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, module_qn); for (int i = 0; i < def_count; i++) { CBMLSPDef *d = &defs[i]; if (!d->qualified_name || !d->short_name || !d->label) @@ -3467,8 +3595,10 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, cbm_registry_add_func(®, rf); } + go_register_value(®, arena, d, def_mod, scope_ix, value_qns); } cbm_ht_free(shared_qns); /* NULL-safe */ + cbm_ht_free(value_qns); // 3. Phase 1b: Scan AST for struct definitions to populate embedded_types { @@ -3692,6 +3822,7 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * NULL on allocation failure: the receiver check scans the registry. */ CBMHashTable *first_type = cbm_ht_create((uint32_t)(def_count / 4 + 1024)); CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); + CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, ""); int noted_types = 0; #define GO_NOTE_NEW_TYPES() \ do { \ @@ -3777,10 +3908,12 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i } cbm_registry_add_func(reg, rf); } + go_register_value(reg, arena, d, def_mod, scope_ix, value_qns); } #undef GO_NOTE_NEW_TYPES cbm_ht_free(first_type); cbm_ht_free(shared_qns); /* NULL-safe */ + cbm_ht_free(value_qns); cbm_registry_finalize(reg); reg->read_only = true; /* seal: shared Tier-2 registry is read-only during resolve */ @@ -3881,7 +4014,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * * but the global registry has. (method_not_found with NAMED * receiver, or any other case where callee_qn looks like a * full QN). Direct lookup. */ - const CBMRegisteredFunc *f = cbm_registry_lookup_func(reg, uc->callee_qn); + const CBMRegisteredFunc *f = go_lookup_func_callable(reg, uc->callee_qn); /* Case 2: callee_qn is "local_pkg_alias.suffix" — the alias * needs translating through the file's import map to get the @@ -3901,7 +4034,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * char fq[1024]; int n = snprintf(fq, sizeof(fq), "%s.%s", import_qns[j], suffix); if (n > 0 && n < (int)sizeof(fq)) { - f = cbm_registry_lookup_func(reg, fq); + f = go_lookup_func_callable(reg, fq); } break; } @@ -3915,7 +4048,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * * an exact package-local lookup rather than a project-wide short-name * guess. */ if (!f && !strchr(uc->callee_qn, '.') && result->module_qn) { - f = cbm_registry_lookup_symbol(reg, result->module_qn, uc->callee_qn); + f = go_lookup_callable(reg, result->module_qn, uc->callee_qn); } if (!f) diff --git a/internal/cbm/lsp/type_registry.h b/internal/cbm/lsp/type_registry.h index c979833d0..68caae8ae 100644 --- a/internal/cbm/lsp/type_registry.h +++ b/internal/cbm/lsp/type_registry.h @@ -24,6 +24,10 @@ typedef enum { * Ordinary call resolution keeps its historical language-specific choice, * but a function value cannot name one materialized definition exactly. */ CBM_FUNC_FLAG_AMBIGUOUS_BINDING = 1 << 10, + /* Go only: a package-level value (`var`/`const`), registered so `pkg.V` + * and a bare `V` of another file have its declared type: the signature's + * single result. Never a call target. */ + CBM_FUNC_FLAG_VALUE = 1 << 11, } CBMFuncFlags; // Registered function/method with full type signature. diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index 9866c79ff..2cc6def62 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -283,6 +283,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) { cr_str(c, &d->variant_key); cr_str(c, &d->alias_target); cr_str(c, &d->type_params); + cr_str(c, &d->value_type); } static void cr_walk_call(cr_ctx_t *c, CBMCall *call) { diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index 14323fc33..300463334 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -694,6 +694,11 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch } else { dst->return_types = src->return_type ? cbm_arena_strdup(arena, src->return_type) : NULL; } + if (lang == CBM_LANG_GO && !dst->return_types && src->value_type) { + /* A Go package-level value's type: the Go registrars register the + * Variable as a value of it (go_lsp.c); the graph never sees it. */ + dst->return_types = cbm_arena_strdup(arena, src->value_type); + } /* Languages whose cross registrars read embedded_types as QNs get their * bases resolved against the project registry; everyone else keeps the * raw source spelling their own registrar already knows how to handle. */ diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index 2b32c9ba1..824c10389 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2608,7 +2608,8 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c census_len(def->client_route_path) + census_len(def->impl_trait) + census_len(def->http_base_url) + census_list(def->extra_props) + census_len(def->decl_namespace) + census_len(def->variant_key) + - census_len(def->alias_target) + census_len(def->type_params); + census_len(def->alias_target) + census_len(def->type_params) + + census_len(def->value_type); } for (int c = 0; c < r->calls.count; c++) { const CBMCall *call = &r->calls.items[c]; diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index e03b09d8a..3550602ae 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -976,6 +976,15 @@ static int go_shared_qn_case(bool shared) { printf(" go shared QN (%s): order A real=%d fake=%d, order B real=%d fake=%d\n", shared ? "shared" : "per-file", hits[0][0], hits[0][1], hits[1][0], hits[1][1]); ASSERT_EQ(hits[0][0] + hits[0][1] + hits[1][0] + hits[1][1], 0); + /* Build variants of one struct (prometheus' labels.Builder): the same + * fields with the same identities give one answer in every order, so + * the fields stay. */ + CBMLSPDef variants[6] = {real_s, real_s}; + memcpy(variants + 2, rest, sizeof(rest)); + int same = ts_go_registry_hits(shared, source, "p.svc", variants, 6, NULL, NULL, 0, + "p.real.Store.Get"); + printf(" go shared QN, same fields (%s): real=%d\n", shared ? "shared" : "per-file", same); + ASSERT_EQ(same, 1); PASS(); } @@ -1016,6 +1025,169 @@ TEST(type_scope_go_closure_parameters_in_composite_literals) { return ts_twins("goclos", go_closure_files, CBM_LANG_GO, go_closure_check); } +/* ── Go: package-level values ─────────────────────────────────────── */ + +/* How many Variable nodes named `name` carry a `return_type` property: a + * value's type crosses files through the LSP defs only, never as a graph + * property (Variable nodes carry none on any other language). */ +static int ts_variable_return_type_props(cbm_store_t *s, const char *project, const char *name) { + cbm_node_t *nodes = NULL; + int count = 0; + if (cbm_store_find_nodes_by_name(s, project, name, &nodes, &count) != CBM_STORE_OK) { + return -1; + } + int hits = 0; + for (int i = 0; i < count; i++) { + if (nodes[i].label && strcmp(nodes[i].label, "Variable") == 0 && nodes[i].properties_json && + strstr(nodes[i].properties_json, "\"return_type\"")) { + hits++; + } + } + cbm_store_free_nodes(nodes, count); + return hits; +} + +/* Package-level values of another package typed by their declaration or + * initializer (`&T{}`, `T{}`, `new(T)`, a typed const and the const block's + * implicit repetition). decoy/ declares the same names. */ +#define TS_GO_VALUES_STORE \ + "type Store struct{ n int }\n\nfunc (s *Store) Get(k string) string { return k }\n\n" \ + "type Kind string\n\nfunc (k Kind) String() string { return string(k) }\n" +static const ts_file_t go_values_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\n" TS_GO_VALUES_STORE}, + {"decoy/store.go", "package decoy\n\n" TS_GO_VALUES_STORE}, + {"conf/conf.go", "package conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n\nvar Plain = store.Store{}\n\n" + "var Fresh = new(store.Store)\n\nconst Primary store.Kind = \"primary\"\n\n" + "const (\n\tFirst store.Kind = \"a\"\n\tSecond\n)\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string { return conf.Default.Get(\"a\") }\n\n" + "func Value() string { return conf.Plain.Get(\"b\") }\n\n" + "func Fresh() string { return conf.Fresh.Get(\"c\") }\n\n" + "func Typed() string { return conf.Primary.String() }\n\n" + "func Repeated() string { return conf.Second.String() }\n"}, + {NULL, NULL}}; + +static int go_values_check(cbm_store_t *s, const char *project, const char *label) { + int pointer = ts_calls_to(s, project, "Pointer", "store.Store.Get", TS_LSP); + int value = ts_calls_to(s, project, "Value", "store.Store.Get", TS_LSP); + int fresh = ts_calls_to(s, project, "Fresh", "store.Store.Get", TS_LSP); + int typed = ts_calls_to(s, project, "Typed", "store.Kind.String", TS_LSP); + int repeated = ts_calls_to(s, project, "Repeated", "store.Kind.String", TS_LSP); + int decoy = ts_calls_to(s, project, "Pointer", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Value", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Fresh", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Typed", "decoy.Kind.String", NULL) + + ts_calls_to(s, project, "Repeated", "decoy.Kind.String", NULL); + /* A value is no callee: no CALLS edge reaches a Variable node. */ + int to_value = ts_calls_to(s, project, "Pointer", "conf.Default", NULL) + + ts_calls_to(s, project, "Value", "conf.Plain", NULL); + int props = ts_variable_return_type_props(s, project, "Default") + + ts_variable_return_type_props(s, project, "Primary"); + printf(" go values (%s): pointer=%d value=%d new=%d typed=%d repeated=%d decoy=%d " + "to_value=%d return_type_props=%d\n", + label, pointer, value, fresh, typed, repeated, decoy, to_value, props); + return !(pointer == 1 && value == 1 && fresh == 1 && typed == 1 && repeated == 1 && + decoy == 0 && to_value == 0 && props == 0); +} + +TEST(type_scope_go_package_values) { + return ts_twins("govals", go_values_files, CBM_LANG_GO, go_values_check); +} + +/* Finding 4: `package svc` and `package svc_test` in one directory declare + * a value of one name (svc.go: real, a_test.go: fake); b_test.go uses the + * fake one, use.go the real one. Their values share a directory QN, so + * neither is typed, in either file order; and a function value called + * through `conf.Hook()` keeps main's edge (the value is no call target of + * the LSP). */ +static int go_test_package_case(bool tests_last) { + const char *a_test = tests_last ? "svc/za_test.go" : "svc/a_test.go"; + const char *b_test = tests_last ? "svc/zb_test.go" : "svc/b_test.go"; + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"conf/conf.go", "package conf\n\nfunc impl() string { return \"x\" }\n\n" + "var Hook func() string = impl\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Run() string { return conf.Hook() }\n"}, + {"real/real.go", + "package real\n\ntype Store struct{ n int }\n\nfunc (s *Store) Get() string { return \"r\" }\n"}, + {"fake/fake.go", + "package fake\n\ntype Store struct{ n int }\n\nfunc (s *Store) Get() string { return \"f\" }\n"}, + {"svc/svc.go", "package svc\n\nimport \"example.com/demo/real\"\n\n" + "var defaultStore = &real.Store{}\n\n" + "func Keep() *real.Store { return defaultStore }\n"}, + {"svc/use.go", "package svc\n\nfunc Use() string { return defaultStore.Get() }\n"}, + {a_test, "package svc_test\n\nimport \"example.com/demo/fake\"\n\n" + "var defaultStore = &fake.Store{}\n"}, + {b_test, "package svc_test\n\nfunc helper() string { return defaultStore.Get() }\n"}, + {NULL, NULL}}; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_gotest_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + ts_write(tmp, files); + ts_pad(tmp, CBM_LANG_GO, TS_PAD_FILES); + int bad = 0; + for (int run = 0; run < 2; run++) { + char project[256] = {0}; + cbm_store_t *s = ts_index_workers(tmp, run ? "par.db" : "seq.db", run ? 4 : 1, project, + sizeof(project)); + if (!s) { + bad++; + continue; + } + int helper_real = ts_calls_to(s, project, "helper", "real.Store.Get", NULL); + int helper_fake = ts_calls_to(s, project, "helper", "fake.Store.Get", NULL); + int use_fake = ts_calls_to(s, project, "Use", "fake.Store.Get", NULL); + int use_real = ts_calls_to(s, project, "Use", "real.Store.Get", NULL); + int hook = ts_calls_to(s, project, "Run", "conf.Hook", NULL); + int hook_main = ts_calls_to(s, project, "Run", "conf.Hook", "\"strategy\":\"import_map\""); + printf(" go test package (%s, tests %s): helper real=%d fake=%d, Use real=%d fake=%d, " + "Run->conf.Hook=%d (import_map %d)\n", + run ? "4 workers" : "1 worker", tests_last ? "last" : "first", helper_real, + helper_fake, use_real, use_fake, hook, hook_main); + bad += helper_real + helper_fake + use_fake + use_real != 0 || hook != 1 || hook_main != 1; + cbm_store_close(s); + } + th_rmtree(tmp); + ASSERT_EQ(bad, 0); + PASS(); +} + +TEST(type_scope_go_test_package_values_share_no_name) { + ASSERT_EQ(go_test_package_case(false), 0); + ASSERT_EQ(go_test_package_case(true), 0); + PASS(); +} + +/* Build variants of one value (`//go:build linux` and `!linux` files that + * both declare `var Default = &store.Store{}`) give one answer, so the value + * stays typed. */ +static const ts_file_t go_variant_value_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"conf/conf_linux.go", "//go:build linux\n\npackage conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n"}, + {"conf/conf_other.go", "//go:build !linux\n\npackage conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string { return conf.Default.Get(\"a\") }\n"}, + {NULL, NULL}}; + +static int go_variant_value_check(cbm_store_t *s, const char *project, const char *label) { + int hit = ts_calls_to(s, project, "Pointer", "store.Store.Get", TS_LSP); + printf(" go variant values (%s): pointer=%d\n", label, hit); + return hit != 1; +} + +TEST(type_scope_go_build_variant_values_stay_typed) { + return ts_twins("govar", go_variant_value_files, CBM_LANG_GO, go_variant_value_check); +} + /* ── Full index versus every incremental route ───────────────────── */ static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, @@ -1160,6 +1332,25 @@ TEST(type_scope_incremental_caller_edit_per_file_go) { PASS(); } +/* The same through package-level values: the per-file Go registrar types + * `conf.Default` from conf.go's stored row. */ +TEST(type_scope_incremental_caller_edit_per_file_go_values) { + const ts_file_t edit[] = { + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string {\n\tv := conf.Default.Get(\"a\")\n\treturn v\n}\n\n" + "func Value() string { return conf.Plain.Get(\"b\") }\n\n" + "func Fresh() string { return conf.Fresh.Get(\"c\") }\n\n" + "func Typed() string { return conf.Primary.String() }\n\n" + "func Repeated() string { return conf.Second.String() }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = + ts_incremental(go_values_files, CBM_LANG_GO, 0, edit, "go values caller edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + /* Finding 9: a body edit of the file that holds the identities, with twelve * dependents in a 40-file tree (the review's go-incr), stays a one-file * repair as on main: the probe and the stored row hash the same bytes. */ @@ -1383,7 +1574,11 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file); RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared); RUN_TEST(type_scope_go_closure_parameters_in_composite_literals); + RUN_TEST(type_scope_go_package_values); + RUN_TEST(type_scope_go_test_package_values_share_no_name); + RUN_TEST(type_scope_go_build_variant_values_stay_typed); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); + RUN_TEST(type_scope_incremental_caller_edit_per_file_go_values); RUN_TEST(type_scope_incremental_body_edit_stays_one_file); RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); RUN_TEST(type_scope_incremental_type_shape_changes_match_full); From 18d5f14e60333e540b17769e47b1765388003d9a Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 04:22:14 +0100 Subject: [PATCH 09/25] feat(lsp): promote embedded Go struct members across files Go promotes the methods and fields of an embedded type to the struct that embeds it. A struct of another file reached the Go registrars without its embedded types (unnamed fields are neither fields nor base classes), and the walked file's own structs qualified `logging.LogHolder` against the file's module, so `o.Hello()` through an embedded `base.Base` was lost. The extractor records a struct's embedded types as written (CBMDefinition.go_embedded; no graph edge is drawn from it), the pipeline hands them to the cross-file LSP, the declared-type scope step resolves their spellings in the declaring file's scope, and one Go-specific hook (go_embedded_qns) turns them into the QNs the member lookup falls through to: the identity, or for a bare name the declaring package's own type. The walked file's own structs take the same answer through their imports. The member lookup walked embedded types depth-first and took the first hit in declaration order at any depth. It now follows Go's selector rule for methods and fields alike: breadth-first, the member at the shallowest depth wins, two at that depth (or a field and a method) is no selection, and an outer field of the name shadows every promoted method; in one file as across files. A struct QN of several definitions (a package and its external test package, build-tagged variants) keeps what every definition agrees on: the fields declared with the same type text and identity, and the embedded types only when all embed the same, so prometheus' build-tagged labels.Builder keeps its shared `base` field and the answer never depends on file order. An embedded type swapped for another package's type of the same name is a change of the named type the closure planner declines on. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 6 + internal/cbm/extract_defs.c | 29 ++ internal/cbm/lsp/go_lsp.c | 484 +++++++++++++++++++++++++--------- internal/cbm/result_compact.c | 1 + src/pipeline/pass_lsp_cross.c | 8 + src/pipeline/pipeline.c | 2 +- src/pipeline/type_scope.c | 3 +- tests/test_type_scope.c | 145 +++++++++- 8 files changed, 555 insertions(+), 123 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 8b4fe71fe..c2ad36db0 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -341,6 +341,12 @@ typedef struct { * and is never written to the graph. NULL for anything else and in every * other language. Tail field: zero-init stays valid. */ const char *value_type; + /* Go only: the types a struct embeds, '|'-joined as written + * ("logging.LogHolder|*Base"). The cross-file LSP promotes their members + * (go_lsp.c, embedded-member hook); no graph edge is drawn from it. NULL + * when none and in every other language. Tail field: zero-init stays + * valid. */ + const char *go_embedded; } CBMDefinition; /* extra_props key of a generated member, one the compiler writes and the diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 70c561555..04dd14e23 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -8589,6 +8589,32 @@ static const char *cs_type_decl_namespace(CBMExtractCtx *ctx, TSNode node) { return ts_node_has_error(top) ? NULL : ""; } +/* Go: the types a struct type_spec embeds (its unnamed field declarations), + * '|'-joined as written, or NULL. */ +static const char *go_struct_embedded_text(CBMArena *a, TSNode spec, const char *source) { + TSNode st = ts_node_child_by_field_name(spec, TS_FIELD("type")); + if (ts_node_is_null(st) || strcmp(ts_node_type(st), "struct_type") != 0) { + return NULL; + } + TSNode list = cbm_find_child_by_kind(st, "field_declaration_list"); + uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list); + const char *out = NULL; + for (uint32_t i = 0; i < n; i++) { + TSNode field = ts_node_named_child(list, i); + if (strcmp(ts_node_type(field), "field_declaration") != 0 || + !ts_node_is_null(ts_node_child_by_field_name(field, TS_FIELD("name")))) { + continue; + } + TSNode type = ts_node_child_by_field_name(field, TS_FIELD("type")); + const char *text = ts_node_is_null(type) ? NULL : cbm_node_text(a, type, source); + if (!text || !text[0] || strchr(text, '|')) { + continue; + } + out = out ? cbm_arena_sprintf(a, "%s|%s", out, text) : text; + } + return out; +} + static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) { CBMArena *a = ctx->arena; const char *kind = ts_node_type(node); @@ -9023,6 +9049,9 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s if (ctx->language == CBM_LANG_PYTHON) { def.type_params = py_type_param_names(a, node, ctx->source); } + if (ctx->language == CBM_LANG_GO) { + def.go_embedded = go_struct_embedded_text(a, node, ctx->source); + } cbm_defs_push(&ctx->result->defs, a, def); diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 451ceeaaa..57411902e 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -1005,28 +1005,33 @@ static const char *go_requalify_via_imports(GoLSPContext *ctx, const char *type_ return NULL; } +/* Go's selector rule: `x.f` names the field or method f at the shallowest + * depth of x's embedding tree that has one, and more than one at that depth + * (two embedded types with a method of that name, a field and a method) is + * no selection at all. An alias is its target, at the same depth. The walk is + * breadth-first and visits each type once; max_depth is the depth the + * depth-first walks it replaces went to. The one member, or none. */ +typedef struct { + const CBMRegisteredFunc *method; + const CBMType *field; + const char *field_owner; /* the type declaring the field */ + int found; /* distinct members at the shallowest depth with any */ +} go_member_t; + +enum { GO_FIELD_LOOKUP_DEPTH = 5 }; /* the depth go_lookup_field always went to */ + +static go_member_t go_select_member(GoLSPContext *ctx, const char *type_qn, const char *name, + int max_depth); + +/* A field's type: the type's own field, else the one member the selector + * rule picks (go_select_member) when that is a field. */ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, const char *field_name, int depth) { - if (!type_qn || !field_name || depth > 5) + (void)depth; + if (!type_qn || !field_name) return NULL; - const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); - if (!rt && depth == 0) { - /* Import-alias re-qualification: field texts from cross-package defs - * may embed an alias segment only this file's import map resolves. */ - const char *alt_qn = go_requalify_via_imports(ctx, type_qn); - if (alt_qn) - rt = cbm_registry_lookup_type(ctx->registry, alt_qn); - } - if (!rt) - return NULL; - - // Follow alias chain - if (rt->alias_of) - return go_lookup_field(ctx, rt->alias_of, field_name, depth + 1); - - // Direct field lookup - if (rt->field_names) { + if (rt && !rt->alias_of && 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]) { @@ -1034,74 +1039,138 @@ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, } } } - - // Promoted fields from embedded types - if (rt->embedded_types) { - for (int i = 0; rt->embedded_types[i]; i++) { - const CBMType *f = go_lookup_field(ctx, rt->embedded_types[i], field_name, depth + 1); - if (f) - return f; - } - } - - return NULL; + go_member_t m = go_select_member(ctx, type_qn, field_name, GO_FIELD_LOOKUP_DEPTH); + return m.field && !cbm_type_is_unknown(m.field) ? m.field : NULL; } // --- go_lookup_field_or_method: method sets + embedding --- -static const CBMRegisteredFunc *go_lookup_field_or_method_depth(GoLSPContext *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 void go_member_note(go_member_t *m, const CBMRegisteredFunc *method, const CBMType *field, + const char *owner) { + if (!method && !field) { + return; /* nothing of that name here */ + } + if (method) { + if (m->method == method || + (m->method && m->method->qualified_name && method->qualified_name && + strcmp(m->method->qualified_name, method->qualified_name) == 0)) { + return; + } + if (!m->method) { + m->method = method; + } + m->found++; + return; + } + if (m->field_owner && owner && strcmp(m->field_owner, owner) == 0) { + return; + } + if (!m->field) { + m->field = field; + m->field_owner = owner; + } + m->found++; +} - // Direct method lookup - const CBMRegisteredFunc *f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name); - if (f) - return f; - - /* Import-alias re-qualification fallback: NAMED receivers built from - * cross-package field type texts can carry a ".svc.Svc" QN; - * retry the method set on the import-resolved QN (see - * go_requalify_via_imports). */ - if (depth == 0) { - const char *alt_qn = go_requalify_via_imports(ctx, type_qn); - if (alt_qn) { - f = go_lookup_field_or_method_depth(ctx, alt_qn, member_name, depth + 1); - if (f) - return f; +static const CBMType *go_own_field(const CBMRegisteredType *rt, const char *name) { + for (int i = 0; rt->field_names && rt->field_names[i]; i++) { + if (strcmp(rt->field_names[i], name) == 0) { + return rt->field_types && rt->field_types[i] ? rt->field_types[i] : cbm_type_unknown(); } } + return NULL; +} - const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); - if (rt) { - // Follow type alias chain - if (rt->alias_of) { - f = go_lookup_field_or_method_depth(ctx, rt->alias_of, member_name, depth + 1); - if (f) - return f; +/* Append `qn` to a level unless the walk has seen it. */ +static void go_member_push(CBMArena *a, CBMHashTable *seen, const char ***level, int *count, + int *cap, const char *qn) { + if (!qn || !seen || cbm_ht_get(seen, qn)) { + return; + } + cbm_ht_set(seen, qn, (void *)qn); + if (*count == *cap) { + int grown_cap = *cap ? *cap * 2 : 8; + const char **grown = (const char **)cbm_arena_alloc(a, (size_t)grown_cap * sizeof(char *)); + if (!grown) { + return; } + if (*count) { + memcpy(grown, *level, (size_t)*count * sizeof(char *)); + } + *level = grown; + *cap = grown_cap; + } + (*level)[(*count)++] = qn; +} - // Check embedded types (promoted methods) - if (rt->embedded_types) { - for (int i = 0; rt->embedded_types[i]; i++) { - f = go_lookup_field_or_method_depth(ctx, rt->embedded_types[i], member_name, - depth + 1); - if (f) - return f; +static go_member_t go_select_member(GoLSPContext *ctx, const char *type_qn, const char *name, + int max_depth) { + go_member_t m = {0}; + CBMHashTable *seen = cbm_ht_create(16); + if (!type_qn || !name || !seen) { + cbm_ht_free(seen); + return m; + } + const char **level = NULL; + int count = 0; + int cap = 0; + go_member_push(ctx->arena, seen, &level, &count, &cap, type_qn); + /* Import-alias re-qualification: NAMED receivers built from cross-package + * field type texts can carry a ".svc.Svc" QN only this file's + * import map resolves (go_requalify_via_imports); it names the same type. */ + go_member_push(ctx->arena, seen, &level, &count, &cap, go_requalify_via_imports(ctx, type_qn)); + for (int depth = 0; count > 0 && depth <= max_depth && m.found == 0; depth++) { + const char **next = NULL; + int next_count = 0; + int next_cap = 0; + for (int i = 0; i < count; i++) { + const char *t = level[i]; + while (t) { + go_member_note(&m, cbm_registry_lookup_method(ctx->registry, t, name), NULL, NULL); + const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, t); + if (!rt) { + break; + } + const CBMType *field = go_own_field(rt, name); + if (field) { + go_member_note(&m, NULL, field, t); + } + for (int e = 0; rt->embedded_types && rt->embedded_types[e]; e++) { + go_member_push(ctx->arena, seen, &next, &next_count, &next_cap, + rt->embedded_types[e]); + } + /* the alias target is this type, at this depth */ + const char *target = rt->alias_of; + t = target && !cbm_ht_get(seen, target) ? target : NULL; + if (t) { + cbm_ht_set(seen, t, (void *)t); + } } } + level = next; + count = next_count; } - - return NULL; + cbm_ht_free(seen); + if (m.found != 1) { + m.method = NULL; + m.field = NULL; + } + return m; } const CBMRegisteredFunc *go_lookup_field_or_method(GoLSPContext *ctx, const char *type_qn, const char *member_name) { - return go_lookup_field_or_method_depth(ctx, type_qn, member_name, 0); + if (!type_qn || !member_name) + return NULL; + // Direct method lookup (a type has no field of a method's name) + const CBMRegisteredFunc *f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name); + if (f) + return f; + // Its own field of that name: a field, never a promoted method + const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); + if (rt && !rt->alias_of && go_own_field(rt, member_name)) + return NULL; + return go_select_member(ctx, type_qn, member_name, CBM_LSP_MAX_LOOKUP_DEPTH).method; } /* Resolve only source forms that prove one callable identity. This is @@ -2775,9 +2844,9 @@ static const CBMType **split_pipe_types(CBMArena *a, const char *text, const cha return idx > 0 ? arr : NULL; } -/* The mark of a QN in the tables below (go_shared_type_qns, - * go_value_qn_counts) whose definitions give different answers; any other - * value is the QN's first definition. */ +/* The mark of a QN in the value table below (go_value_qn_counts) whose + * definitions give different answers; any other value is the QN's first + * definition. */ static char g_go_qn_shared_mark; static bool go_type_qn_shared(const CBMHashTable *shared, const char *qn) { @@ -2830,11 +2899,11 @@ static CBMHashTable *go_value_qn_counts(CBMArena *a, const CBMLSPDef *defs, int continue; } const CBMLSPDef *first = (const CBMLSPDef *)prev; - bool same_value = prev != &g_go_qn_shared_mark && value_qn && - go_value_qn(a, first, first->def_module_qn ? first->def_module_qn - : fallback_mod) && - go_same_text(first->return_types, d->return_types) && - go_same_text(first->type_scope, d->type_scope); + bool same_value = + prev != &g_go_qn_shared_mark && value_qn && + go_value_qn(a, first, first->def_module_qn ? first->def_module_qn : fallback_mod) && + go_same_text(first->return_types, d->return_types) && + go_same_text(first->type_scope, d->type_scope); if (!same_value) { cbm_ht_set(seen, keys[k], &g_go_qn_shared_mark); } @@ -2843,6 +2912,55 @@ static CBMHashTable *go_value_qn_counts(CBMArena *a, const CBMLSPDef *defs, int return seen; } +/* ── Language hook: promotion of embedded-struct members ───────────── + * + * Go promotes the methods and fields of an embedded type to the struct that + * embeds it. A member lookup on the struct falls through to its embedded + * types (go_lookup_promoted), which needs their QNs; a struct from another + * file brings them as their source spelling ("logging.LogHolder", "*Base"). + * The QN of a spelling is its identity in the declaring file's scope + * (type_scope.h), or for a bare name the declaring package's own type; a + * spelling neither gives is dropped. This is the one Go-specific step on top + * of the shared layer. */ +static const char **go_embedded_qns(CBMArena *a, const char *embedded, const char *def_mod, + const cbm_type_scope_index_t *scope_ix) { + if (!embedded || !embedded[0]) { + return NULL; + } + int count = 1; + for (const char *p = embedded; *p; p++) { + count += *p == '|'; + } + const char **out = (const char **)cbm_arena_alloc(a, (size_t)(count + 1) * sizeof(*out)); + if (!out) { + return NULL; + } + int n = 0; + for (const char *p = embedded; *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + const char *s = p; + while (len > 0 && *s == '*') { + s++; + len--; + } + const char *bracket = memchr(s, '[', len); /* a generic instance: its type */ + if (bracket) { + len = (size_t)(bracket - s); + } + const char *qn = len ? cbm_type_scope_find(scope_ix, s, len) : NULL; + if (!qn && len && !memchr(s, '.', len) && def_mod && def_mod[0]) { + qn = cbm_arena_sprintf(a, "%s.%.*s", def_mod, (int)len, s); + } + if (qn) { + out[n++] = qn; + } + p = bar ? bar + 1 : p + strlen(p); + } + out[n] = NULL; + return n > 0 ? out : NULL; +} + /* A package-level value (a Go `var`/`const` Variable def whose declaration or * initializer spells its type): registered under . with * CBM_FUNC_FLAG_VALUE and that type as the signature's single result, so @@ -2984,35 +3102,137 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char /* Go module QNs are directories, so a package and its external test package * (`foo` and `foo_test`), or build-tagged variants, can declare two types of * one QN. A type lookup answers with one entry of a name, which one depends on - * file order; what is keyed by such a QN (its fields, its embedded types) is - * therefore registered for neither, unless every definition of the QN spells - * the same fields and embedded types with the same identities (build variants - * of one struct): then every order gives one answer. Returns the QNs whose - * definitions differ (marked shared; keys borrowed from defs; free with - * cbm_ht_free), or NULL on allocation failure (then nothing counts as - * shared). */ -static CBMHashTable *go_shared_type_qns(const CBMLSPDef *defs, int def_count) { - CBMHashTable *seen = cbm_ht_create((uint32_t)(def_count / 4 + 64)); - for (int i = 0; seen && i < def_count; i++) { + * file order, so what is keyed by such a QN is registered only where every + * definition of the QN gives the same answer: + * - a field when every definition declares it with the same type text whose + * name means the same type (its identity, or the package's own type); + * - the embedded types when every definition embeds the same types. + * Build variants of one struct keep what they share; `foo` and `foo_test` + * declaring different structs of one name keep only what agrees. */ +typedef struct { + const CBMLSPDef *first; + int count; /* definitions of the QN */ + const char *first_embeds; /* the first definition's embedded QNs, '|'-joined */ + bool embeds_differ; + bool fields_done; + const char *fields; /* count > 1: the fields every definition agrees on, or NULL */ +} go_type_qn_t; + +/* What a field type text means in one definition: the part the parser looks + * up after `*` and `[]`, resolved through the def's identities, or NULL for + * the package's own name (the same in every definition of one directory). */ +static const char *go_field_type_identity(const cbm_type_scope_index_t *ix, const char *text) { + while (text && (*text == '*' || (text[0] == '[' && text[1] == ']'))) { + text += *text == '*' ? 1 : 2; + } + return text ? cbm_type_scope_find(ix, text, strlen(text)) : NULL; +} + +static const char *go_join_embeds(CBMArena *a, const CBMLSPDef *d) { + const char *mod = d->def_module_qn ? d->def_module_qn : ""; + const char **qns = + go_embedded_qns(a, d->embedded_types, mod, cbm_type_scope_index(a, d->type_scope)); + const char *out = ""; + for (int i = 0; qns && qns[i]; i++) { + out = cbm_arena_sprintf(a, "%s%s%s", out, i ? "|" : "", qns[i]); + } + return out; +} + +/* Keep the fields of `agreed` ("name:type|...") that `d` declares alike. */ +static const char *go_agreed_fields(CBMArena *a, const char *agreed, const CBMLSPDef *agreed_def, + const CBMLSPDef *d) { + if (!agreed || !agreed[0] || !d->field_defs || !d->field_defs[0]) { + return NULL; + } + const cbm_type_scope_index_t *agreed_ix = cbm_type_scope_index(a, agreed_def->type_scope); + const cbm_type_scope_index_t *d_ix = cbm_type_scope_index(a, d->type_scope); + CBMHashTable *mine = cbm_ht_create(16); + char *copy = cbm_arena_strdup(a, d->field_defs); + for (char *p = copy; mine && p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *colon = strchr(p, ':'); + if (colon) { + *colon = '\0'; + cbm_ht_set(mine, p, colon + 1); /* name -> type text */ + } + p = bar ? bar + 1 : NULL; + } + const char *out = NULL; + char *keep = cbm_arena_strdup(a, agreed); + for (char *p = keep; mine && p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *colon = strchr(p, ':'); + const char *theirs = + colon ? (const char *)cbm_ht_get(mine, cbm_arena_strndup(a, p, (size_t)(colon - p))) + : NULL; + if (theirs && strcmp(theirs, colon + 1) == 0 && + go_same_text(go_field_type_identity(agreed_ix, colon + 1), + go_field_type_identity(d_ix, theirs))) { + out = out ? cbm_arena_sprintf(a, "%s|%s", out, p) : cbm_arena_strdup(a, p); + } + p = bar ? bar + 1 : NULL; + } + cbm_ht_free(mine); + return out; +} + +/* QN -> go_type_qn_t for every Go type definition (keys borrowed from defs; + * free with cbm_ht_free, entries live in `a`), or NULL on allocation failure + * (then a QN of two definitions keeps nothing). */ +static CBMHashTable *go_type_qn_table(CBMArena *a, const CBMLSPDef *defs, int def_count) { + CBMHashTable *table = cbm_ht_create((uint32_t)(def_count / 4 + 64)); + for (int i = 0; table && i < def_count; i++) { const CBMLSPDef *d = &defs[i]; if (!d->qualified_name || !d->label || d->lang != CBM_LANG_GO || !cbm_label_is_type_like(d->label)) { continue; } - void *prev = cbm_ht_get(seen, d->qualified_name); - if (!prev) { - cbm_ht_set(seen, d->qualified_name, (void *)d); /* the first definition */ - continue; + go_type_qn_t *e = (go_type_qn_t *)cbm_ht_get(table, d->qualified_name); + if (!e) { + e = (go_type_qn_t *)cbm_arena_alloc(a, sizeof(*e)); + if (!e) { + cbm_ht_free(table); + return NULL; + } + memset(e, 0, sizeof(*e)); + e->first = d; + cbm_ht_set(table, d->qualified_name, e); } - const CBMLSPDef *first = (const CBMLSPDef *)prev; - if (prev != &g_go_qn_shared_mark && - (!go_same_text(first->field_defs, d->field_defs) || - !go_same_text(first->embedded_types, d->embedded_types) || - !go_same_text(first->type_scope, d->type_scope))) { - cbm_ht_set(seen, d->qualified_name, &g_go_qn_shared_mark); + e->count++; + if (e->count == 2) { + e->first_embeds = go_join_embeds(a, e->first); + e->fields = e->first->field_defs; + } + if (e->count >= 2) { + e->embeds_differ = + e->embeds_differ || !go_same_text(e->first_embeds, go_join_embeds(a, d)); + e->fields = go_agreed_fields(a, e->fields, e->first, d); } } - return seen; + return table; +} + +/* The fields to register for `d`: its own when it is its QN's only definition, + * else those every definition of the QN agrees on (NULL: none). Without a + * table (allocation failure) every def keeps its own, as before the table. */ +static const char *go_type_qn_fields(const CBMHashTable *table, const CBMLSPDef *d) { + const go_type_qn_t *e = + table ? (const go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + return !e || e->count < 2 ? d->field_defs : e->fields; +} + +/* Whether `d`'s embedded types are the same in every definition of its QN. */ +static bool go_type_qn_embeds(const CBMHashTable *table, const CBMLSPDef *d) { + const go_type_qn_t *e = + table ? (const go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + return !e || e->count < 2 || !e->embeds_differ; } // --- Phase 1c: Extract type parameters from generic function declarations --- @@ -3524,7 +3744,7 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // caller's arena which outlives this call, so cbm_arena_strdup is // wasted work. On kubernetes (~110k defs × 11k files × 5 strdups // ~= 6B mallocs) this alone saves ~90s of resolve wall time. - CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); + CBMHashTable *type_qns = go_type_qn_table(arena, defs, def_count); CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, module_qn); for (int i = 0; i < def_count; i++) { CBMLSPDef *d = &defs[i]; @@ -3543,7 +3763,11 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, rt.qualified_name = d->qualified_name; // borrowed rt.short_name = d->short_name; // borrowed rt.is_interface = d->is_interface || strcmp(d->label, "Interface") == 0; - rt.embedded_types = split_pipe_strings(arena, d->embedded_types); + /* Embedded types other definitions of the QN differ in promote + * nothing (go_type_qn_table). */ + rt.embedded_types = go_type_qn_embeds(type_qns, d) + ? go_embedded_qns(arena, d->embedded_types, def_mod, scope_ix) + : NULL; // Set method_names for interfaces from "|"-separated string if (rt.is_interface && d->method_names_str && d->method_names_str[0]) { @@ -3553,11 +3777,11 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // Struct field types from field_defs, on this def's own entry: a // type lookup answers with the last entry of a name, so fields on - // an earlier receiver placeholder were never seen. A QN two type - // definitions share keeps none (go_shared_type_qns). - if (d->field_defs && d->field_defs[0] && - !go_type_qn_shared(shared_qns, d->qualified_name)) { - (void)parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &rt.field_names, + // an earlier receiver placeholder were never seen. A QN of several + // definitions keeps the fields they agree on (go_type_qn_table). + const char *fields = go_type_qn_fields(type_qns, d); + if (fields && fields[0]) { + (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, &rt.field_types); } @@ -3597,7 +3821,7 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, } go_register_value(®, arena, d, def_mod, scope_ix, value_qns); } - cbm_ht_free(shared_qns); /* NULL-safe */ + cbm_ht_free(type_qns); /* NULL-safe */ cbm_ht_free(value_qns); // 3. Phase 1b: Scan AST for struct definitions to populate embedded_types @@ -3703,13 +3927,29 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, TSNode ftype = ts_node_child_by_field_name(field, "type", 4); if (ts_node_is_null(fname) && !ts_node_is_null(ftype)) { if (embed_count < 15) { + /* The embedded-member hook's QN: a bare name is + * this package's, `pkg.T` the import's (the same + * answer the shared registry gets from the + * declaring file's scope). */ char *embed_text = cbm_node_text(arena, ftype, source); - if (embed_text && embed_text[0]) { - const char *et = embed_text; - while (*et == '*') - et++; - embeds[embed_count++] = - cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + char *et = embed_text; + while (et && *et == '*') + et++; + char *bracket = et ? strchr(et, '[') : NULL; + if (bracket) + *bracket = '\0'; + char *dot = et ? strchr(et, '.') : NULL; + const char *eqn = NULL; + if (et && et[0] && !dot) { + eqn = cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + } else if (et && dot && dot > et) { + *dot = '\0'; + const char *pkg_qn = resolve_import(&tmp_ctx, et); + eqn = pkg_qn ? cbm_arena_sprintf(arena, "%s.%s", pkg_qn, dot + 1) + : NULL; + } + if (eqn) { + embeds[embed_count++] = eqn; } } } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype) && @@ -3821,7 +4061,7 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * receives the struct's fields as well as the struct's own entry. * NULL on allocation failure: the receiver check scans the registry. */ CBMHashTable *first_type = cbm_ht_create((uint32_t)(def_count / 4 + 1024)); - CBMHashTable *shared_qns = go_shared_type_qns(defs, def_count); + CBMHashTable *type_qns = go_type_qn_table(arena, defs, def_count); CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, ""); int noted_types = 0; #define GO_NOTE_NEW_TYPES() \ @@ -3857,7 +4097,11 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i rt.qualified_name = d->qualified_name; /* borrowed */ rt.short_name = d->short_name; rt.is_interface = d->is_interface || strcmp(d->label, "Interface") == 0; - rt.embedded_types = split_pipe_strings(arena, d->embedded_types); + /* Embedded types other definitions of the QN differ in promote + * nothing (go_type_qn_table). */ + rt.embedded_types = go_type_qn_embeds(type_qns, d) + ? go_embedded_qns(arena, d->embedded_types, def_mod, scope_ix) + : NULL; if (rt.is_interface && d->method_names_str && d->method_names_str[0]) { rt.method_names = split_pipe_strings(arena, d->method_names_str); } @@ -3865,11 +4109,11 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i /* Fields on this def's own entry, which a lookup after finalize * answers with (the last entry of a name). The first entry -- a * receiver placeholder when a method came earlier -- keeps them - * too, for the first-registered readers. A QN two type - * definitions share keeps none (go_shared_type_qns). */ - if (d->field_defs && d->field_defs[0] && - !go_type_qn_shared(shared_qns, d->qualified_name)) { - (void)parse_field_defs(arena, d->field_defs, def_mod, scope_ix, &rt.field_names, + * too, for the first-registered readers. A QN of several + * definitions keeps the fields they agree on (go_type_qn_table). */ + const char *fields = go_type_qn_fields(type_qns, d); + if (fields && fields[0]) { + (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, &rt.field_types); } cbm_registry_add_type(reg, rt); @@ -3912,7 +4156,7 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i } #undef GO_NOTE_NEW_TYPES cbm_ht_free(first_type); - cbm_ht_free(shared_qns); /* NULL-safe */ + cbm_ht_free(type_qns); /* NULL-safe */ cbm_ht_free(value_qns); cbm_registry_finalize(reg); diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index 2cc6def62..770629c19 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -284,6 +284,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) { cr_str(c, &d->alias_target); cr_str(c, &d->type_params); cr_str(c, &d->value_type); + cr_str(c, &d->go_embedded); } static void cr_walk_call(cr_ctx_t *c, CBMCall *call) { diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index 300463334..4fc11e16e 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -706,6 +706,14 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch (bs && bs->reg && pxc_lang_resolves_base_qns(lang)) ? pxc_join_base_qns(arena, src->base_classes, bs, module_qn, src->qualified_name) : pxc_join_pipe(arena, src->base_classes); + if (lang == CBM_LANG_GO && src->go_embedded && src->go_embedded[0]) { + /* A Go struct's embedded types, as written; the Go registrar promotes + * their members (the embedded-member hook, go_lsp.c). */ + dst->embedded_types = + dst->embedded_types && dst->embedded_types[0] + ? cbm_arena_sprintf(arena, "%s|%s", dst->embedded_types, src->go_embedded) + : cbm_arena_strdup(arena, src->go_embedded); + } dst->signature_param_types = NULL; dst->signature_param_count = 0; if (src->signature_param_types && src->signature_param_count > 0) { diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index 824c10389..ba3596a1e 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2609,7 +2609,7 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c census_len(def->http_base_url) + census_list(def->extra_props) + census_len(def->decl_namespace) + census_len(def->variant_key) + census_len(def->alias_target) + census_len(def->type_params) + - census_len(def->value_type); + census_len(def->value_type) + census_len(def->go_embedded); } for (int c = 0; c < r->calls.count; c++) { const CBMCall *call = &r->calls.items[c]; diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index cc5f7d724..87f13114a 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -34,7 +34,8 @@ static const cbm_type_scope_lang_t type_scope_langs[] = { .imports_bind_modules = true, .return_types = true, .param_types = true, - .field_types = true}, + .field_types = true, + .embedded_types = true}, {.lang = CBM_LANG_PYTHON, .quoted_names = true, .labels = py_labels, diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 3550602ae..23e26e5ef 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -983,8 +983,37 @@ static int go_shared_qn_case(bool shared) { memcpy(variants + 2, rest, sizeof(rest)); int same = ts_go_registry_hits(shared, source, "p.svc", variants, 6, NULL, NULL, 0, "p.real.Store.Get"); - printf(" go shared QN, same fields (%s): real=%d\n", shared ? "shared" : "per-file", same); + /* Variants that differ elsewhere (prometheus' labels.Builder: one adds + * fields) keep the field they declare alike, in both orders. */ + CBMLSPDef wider = real_s; + wider.field_defs = "X:*real.Store|Extra:int"; + int partial[2]; + for (int order = 0; order < 2; order++) { + CBMLSPDef defs[6] = {order ? wider : real_s, order ? real_s : wider}; + memcpy(defs + 2, rest, sizeof(rest)); + partial[order] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.real.Store.Get"); + } + /* The same text naming another type in each (`store` is real in one, + * fake in the other): no agreement. */ + CBMLSPDef via_real = real_s; + via_real.field_defs = "X:*store.Store"; + via_real.type_scope = "store.Store=p.real.Store"; + CBMLSPDef via_fake = via_real; + via_fake.type_scope = "store.Store=p.fake.Store"; + CBMLSPDef split[6] = {via_real, via_fake}; + memcpy(split + 2, rest, sizeof(rest)); + int split_hits = ts_go_registry_hits(shared, source, "p.svc", split, 6, NULL, NULL, 0, + "p.real.Store.Get") + + ts_go_registry_hits(shared, source, "p.svc", split, 6, NULL, NULL, 0, + "p.fake.Store.Get"); + printf(" go shared QN (%s): same fields real=%d, agreed field %d/%d, same text other " + "identity %d\n", + shared ? "shared" : "per-file", same, partial[0], partial[1], split_hits); ASSERT_EQ(same, 1); + ASSERT_EQ(partial[0], 1); + ASSERT_EQ(partial[1], 1); + ASSERT_EQ(split_hits, 0); PASS(); } @@ -1188,6 +1217,89 @@ TEST(type_scope_go_build_variant_values_stay_typed) { return ts_twins("govar", go_variant_value_files, CBM_LANG_GO, go_variant_value_check); } +/* ── Go: embedded-member promotion ────────────────────────────────── */ + +/* A struct of another file embeds `base.Base` (an imported package's type) + * and `*Local` (its own package's); the promoted methods are found through + * the declaring file's scope. decoy/ declares the same Base with the same + * method. */ +static const ts_file_t go_embed_files[] = { + {"go.mod", "module example.com/emb\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Base struct{ n int }\n\n" + "func (b *Base) Hello() string { return \"x\" }\n"}, + {"decoy/base.go", "package decoy\n\ntype Base struct{ n int }\n\n" + "func (b *Base) Hello() string { return \"y\" }\n"}, + {"outer/outer.go", "package outer\n\nimport \"example.com/emb/base\"\n\n" + "type Outer struct {\n\tbase.Base\n\tname string\n}\n\n" + "type Local struct{ k int }\n\nfunc (l *Local) Bye() string { return \"z\" }\n\n" + "type Both struct {\n\t*Local\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/emb/outer\"\n\n" + "func Run(o *outer.Outer) string { return o.Hello() }\n\n" + "func Run2(b *outer.Both) string { return b.Bye() }\n"}, + {NULL, NULL}}; + +static int go_embed_check(cbm_store_t *s, const char *project, const char *label) { + int imported = ts_calls_to(s, project, "Run", "base.Base.Hello", TS_LSP); + int decoy = ts_calls_to(s, project, "Run", "decoy.Base.Hello", NULL); + int own = ts_calls_to(s, project, "Run2", "outer.Local.Bye", TS_LSP); + printf(" go embedded (%s): imported=%d decoy=%d own=%d\n", label, imported, decoy, own); + return !(imported == 1 && decoy == 0 && own == 1); +} + +TEST(type_scope_go_embedded_members_promote) { + return ts_twins("goemb", go_embed_files, CBM_LANG_GO, go_embed_check); +} + +/* Finding 5: Go selects the member at the shallowest depth, and a tie there + * is no selection. Across files (the review's go-embed: Outer embeds base.A, + * which embeds Inner with Hello, and base.B with Hello: B.Hello at depth 1 + * wins over Inner.Hello at depth 2), in one file the same, a tie of two + * embedded types at one depth, and an outer field of the member's name. */ +static const ts_file_t go_depth_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Inner struct{ n int }\n\n" + "func (i *Inner) Hello() string { return \"inner\" }\n\n" + "type A struct{ Inner }\n\n" + "type B struct{ k int }\n\n" + "func (b *B) Hello() string { return \"b\" }\n\n" + "type C struct{ k int }\n\n" + "func (c *C) Hello() string { return \"c\" }\n"}, + {"outer/outer.go", "package outer\n\nimport \"example.com/demo/base\"\n\n" + "type Outer struct {\n\tbase.A\n\tbase.B\n}\n\n" + "type Tie struct {\n\tbase.B\n\tbase.C\n}\n\n" + "type Shadow struct {\n\tHello func() string\n\tbase.B\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/outer\"\n\n" + "func Run(o *outer.Outer) string { return o.Hello() }\n\n" + "func Tied(t *outer.Tie) string { return t.Hello() }\n\n" + "func Field(s *outer.Shadow) string { return s.Hello() }\n"}, + {"local/local.go", "package local\n\ntype Inner struct{ n int }\n\n" + "func (i *Inner) Hello() string { return \"inner\" }\n\n" + "type A struct{ Inner }\n\n" + "type B struct{ k int }\n\n" + "func (b *B) Hello() string { return \"b\" }\n\n" + "type Outer struct {\n\tA\n\tB\n}\n\n" + "func Here(o *Outer) string { return o.Hello() }\n"}, + {NULL, NULL}}; + +static int go_depth_check(cbm_store_t *s, const char *project, const char *label) { + int shallow = ts_calls_to(s, project, "Run", "base.B.Hello", NULL); + int deep = ts_calls_to(s, project, "Run", "base.Inner.Hello", NULL); + int tied = ts_calls_to(s, project, "Tied", "base.B.Hello", NULL) + + ts_calls_to(s, project, "Tied", "base.C.Hello", NULL); + int shadowed = ts_calls_to(s, project, "Field", "base.B.Hello", NULL); + int here_shallow = ts_calls_to(s, project, "Here", "local.B.Hello", NULL); + int here_deep = ts_calls_to(s, project, "Here", "local.Inner.Hello", NULL); + printf(" go promotion depth (%s): Run B=%d Inner=%d, tie=%d, field=%d, one file B=%d " + "Inner=%d\n", + label, shallow, deep, tied, shadowed, here_shallow, here_deep); + return !(deep == 0 && shallow <= 1 && tied == 0 && shadowed == 0 && here_deep == 0 && + here_shallow <= 1); +} + +TEST(type_scope_go_promotion_takes_the_shallowest_depth) { + return ts_twins("godepth", go_depth_files, CBM_LANG_GO, go_depth_check); +} + /* ── Full index versus every incremental route ───────────────────── */ static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, @@ -1471,6 +1583,34 @@ TEST(type_scope_incremental_type_shape_changes_match_full) { PASS(); } +/* The shape only the identity gate catches: the struct an identity names + * embeds another package's type of the same name (`p1.E` -> `p2.E`, both + * imported already). The doc-link scope sees the same type, kind and field + * names; the caller reached the promoted method through fixture.go's + * identity and has no edge into model/b.go, so a repair would keep its stale + * edge to p1.E.Hello. */ +TEST(type_scope_incremental_named_type_embed_change_matches_full) { + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{ n int }\n\nfunc (e *E) Hello() string { return \"1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{ n int }\n\nfunc (e *E) Hello() string { return \"2\" }\n"}, + {"model/b.go", "package model\n\nimport (\n\t\"example.com/demo/p1\"\n\t\"example.com/demo/p2\"\n)\n\n" + "var _ p2.E\n\ntype T struct {\n\tp1.E\n}\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/model\"\n\n" + "func Make() *model.T { return &model.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().Hello() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"model/b.go", "package model\n\nimport (\n\t\"example.com/demo/p1\"\n\t\"example.com/demo/p2\"\n)\n\n" + "var _ p1.E\n\ntype T struct {\n\tp2.E\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go named type embed change"); + ASSERT_TRUE(r.same_graph); + ASSERT_STR_EQ(r.plan.decline, "identity_target_changed"); + PASS(); +} + /* The gate is narrow: a signature change of another definition in the * declaring file stays a repair. */ TEST(type_scope_incremental_other_def_edit_stays_a_repair) { @@ -1577,10 +1717,13 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_package_values); RUN_TEST(type_scope_go_test_package_values_share_no_name); RUN_TEST(type_scope_go_build_variant_values_stay_typed); + RUN_TEST(type_scope_go_embedded_members_promote); + RUN_TEST(type_scope_go_promotion_takes_the_shallowest_depth); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); RUN_TEST(type_scope_incremental_caller_edit_per_file_go_values); RUN_TEST(type_scope_incremental_body_edit_stays_one_file); RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); + RUN_TEST(type_scope_incremental_named_type_embed_change_matches_full); RUN_TEST(type_scope_incremental_type_shape_changes_match_full); RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); RUN_TEST(type_scope_incremental_python_body_edits); From b8e7c1e4e38f01e6ad699bea459db6f2f4bc4540 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 06:57:54 +0100 Subject: [PATCH 10/25] fix(lsp): class-body bindings, Go type parameters, one facts record Three defects the second review found, and its memory finding: - A Python class body binds names besides its nested definitions (`Config = OtherConfig`, an import, an annotated name, a for, with, except or match target, a walrus, global/nonlocal/del), and inside its methods' annotations such a name is the class attribute, not the module's class of that name. The extractor lists them per class (CBMDefTypeFacts.class_bindings) and the declared-type step gives none of them an identity; a name the body does not bind keeps its own. They also join the class's field_defs as `name:` (an attribute of unknown type the Python registrar skips), so they are part of the stored row the incremental planner compares: an edit of a class body is never a stale repair. - A class and a module of one QN (class Thing in pkg/a/__init__.py beside pkg/a/Thing.py) share their members' QNs, so a member edge through the class's identity named the module's function. A type QN the graph holds as a module gets no identity (the graph the import map reads). - A Go type parameter in a definition's types (`func First[T any](xs []T) T`, `func (b Box[T]) Get() T`, `type Box[T any] struct{ v T }`) was read by the cross registrars as the package's own type of that name, and the embedded-member promotion carried that to its embedded types. The extractor records a Go definition's type parameters (its own, its generic receiver's), and the cross-file texts spell them `any`: no registrar reads them as a project type. The three definition fields the declared-type step added (type_params, value_type, go_embedded) were 24 bytes on every definition of every language. They move to one optional record, CBMDefTypeFacts, allocated in the result arena only for a Go or Python definition that has a fact, which also carries the Go type parameters and the class bindings: 8 bytes per definition for the pointer. Compaction and the spill walk it. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 50 ++++-- internal/cbm/extract_defs.c | 329 +++++++++++++++++++++++++++++++++- internal/cbm/result_compact.c | 12 +- src/pipeline/pass_lsp_cross.c | 218 +++++++++++++++++++++- src/pipeline/pipeline.c | 10 +- src/pipeline/type_scope.c | 45 ++++- src/pipeline/type_scope.h | 15 +- tests/test_type_scope.c | 125 ++++++++++++- 8 files changed, 755 insertions(+), 49 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index c2ad36db0..022c17e45 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -328,27 +328,39 @@ typedef struct { * for a defined type `type A B` (its method set is its own) and in every * other language. Tail field: zero-init stays valid. */ const char *alias_target; - /* Python only: the names a PEP 695 type parameter list declares - * (`def f[T, *Ts, **P]`, `class C[T]`), '|'-joined. The cross-file type - * step keeps them from taking a real type's identity (type_scope.h); never - * written to the graph. NULL when none and in every other language. Tail - * field: zero-init stays valid. */ - const char *type_params; - /* Go only: the type a package-level `var`/`const` declares, or the type - * its single initializer spells (`T{}` is T, `&T{}` and `new(T)` are *T, - * a const block's bare spec repeats the previous one's). It reaches the - * cross-file LSP as the Variable's type (go_lsp.c, package-level values) - * and is never written to the graph. NULL for anything else and in every - * other language. Tail field: zero-init stays valid. */ - const char *value_type; - /* Go only: the types a struct embeds, '|'-joined as written - * ("logging.LogHolder|*Base"). The cross-file LSP promotes their members - * (go_lsp.c, embedded-member hook); no graph edge is drawn from it. NULL - * when none and in every other language. Tail field: zero-init stays - * valid. */ - const char *go_embedded; + /* Go and Python only: the facts the declared-type scope step and the + * cross-file registrars read (CBMDefTypeFacts), in the result arena; NULL + * for a definition without one and in every other language. One pointer, + * so the other languages pay 8 bytes per definition. Tail field: + * zero-init stays valid. */ + const struct CBMDefTypeFacts *type_facts; } CBMDefinition; +/* Facts of one Go or Python definition that no graph property carries; only + * the cross-file step reads them (src/pipeline/type_scope.h, the Go and + * Python cross registrars). Every field is NULL when absent. */ +typedef struct CBMDefTypeFacts { + /* The names its type parameter lists declare, '|'-joined: Python PEP 695 + * (`def f[T, *Ts, **P]`, `class C[T]`), Go (`func F[K, V any]`, a generic + * receiver `(s *Set[T])`, `type Box[T any]`). They never name a type of + * the project. */ + const char *type_params; + /* Go: the type a package-level `var`/`const` declares, or the type its + * single initializer spells (`T{}` is T, `&T{}` and `new(T)` are *T, a + * const block's bare spec repeats the previous one's): the Variable's + * type in the cross-file LSP (go_lsp.c, package-level values). */ + const char *value_type; + /* Go: the types a struct embeds, '|'-joined as written + * ("logging.LogHolder|*Base"): the cross-file LSP promotes their members + * and names them as fields (go_lsp.c, embedded-member hook). */ + const char *go_embedded; + /* Python class: the names its body binds other than by a nested def or + * class (assignments, annotated names, imports, for/with/except/match + * targets, walrus, global/nonlocal/del), '|'-joined. A method annotation + * naming one of them means the class attribute, not the module's name. */ + const char *class_bindings; +} CBMDefTypeFacts; + /* extra_props key of a generated member, one the compiler writes and the * source never spells: a Java record's implicit accessor carries * `generated: record`. The node keeps the property, and the pipeline registers diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 04dd14e23..8ab1dbe50 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -6983,6 +6983,303 @@ static const char *py_type_param_names(CBMArena *a, TSNode node, const char *sou return at ? out : NULL; } +/* ── Facts only the declared-type scope step reads (CBMDefTypeFacts) ── */ + +/* The record of a definition being built, allocated on first use. */ +static CBMDefTypeFacts *def_type_facts(CBMArena *a, CBMDefinition *def) { + if (!def->type_facts) { + CBMDefTypeFacts *f = (CBMDefTypeFacts *)cbm_arena_alloc(a, sizeof(*f)); + if (!f) { + return NULL; + } + memset(f, 0, sizeof(*f)); + def->type_facts = f; + } + return (CBMDefTypeFacts *)def->type_facts; +} + +static void def_set_type_params(CBMArena *a, CBMDefinition *def, const char *names) { + CBMDefTypeFacts *f = names && names[0] ? def_type_facts(a, def) : NULL; + if (f) { + f->type_params = names; + } +} + +/* A '|'-joined list of names built in the arena (the grown buffers stay in + * the arena: at most twice the final size). */ +typedef struct { + CBMArena *a; + char *buf; + size_t len; + size_t cap; +} tf_names_t; + +static void tf_names_add(tf_names_t *b, const char *s, size_t n) { + if (!s || n == 0) { + return; + } + size_t need = b->len + n + 2; + if (need > b->cap) { + size_t cap = b->cap ? b->cap * 2 : 64; + while (cap < need) { + cap *= 2; + } + char *grown = (char *)cbm_arena_alloc(b->a, cap); + if (!grown) { + return; + } + if (b->len) { + memcpy(grown, b->buf, b->len); + } + b->buf = grown; + b->cap = cap; + } + if (b->len) { + b->buf[b->len++] = '|'; + } + memcpy(b->buf + b->len, s, n); + b->len += n; + b->buf[b->len] = '\0'; +} + +static void tf_names_node(tf_names_t *b, TSNode node, const char *source) { + if (!ts_node_is_null(node)) { + tf_names_add(b, source + ts_node_start_byte(node), + ts_node_end_byte(node) - ts_node_start_byte(node)); + } +} + +enum { TF_BIND_DEPTH = 64 }; /* statement and pattern nesting the binders follow */ + +/* Go: `[K comparable, V any]` declares K and V (every `name` of every + * type_parameter_declaration). */ +static void go_type_param_list(tf_names_t *b, TSNode list, const char *source) { + uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list); + for (uint32_t i = 0; i < n; i++) { + TSNode decl = ts_node_named_child(list, i); + if (strcmp(ts_node_type(decl), "type_parameter_declaration") != 0) { + continue; + } + uint32_t cc = ts_node_child_count(decl); + for (uint32_t k = 0; k < cc; k++) { + const char *field = ts_node_field_name_for_child(decl, k); + if (field && strcmp(field, "name") == 0) { + tf_names_node(b, ts_node_child(decl, k), source); + } + } + } +} + +/* Go: a generic receiver `(s *Set[K, V])` declares K and V. */ +static void go_receiver_type_params(tf_names_t *b, TSNode node, bool in_args, int depth, + const char *source) { + if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) { + return; + } + const char *kind = ts_node_type(node); + if (in_args && strcmp(kind, "type_identifier") == 0) { + tf_names_node(b, node, source); + return; + } + bool args = in_args || strcmp(kind, "type_arguments") == 0; + uint32_t n = ts_node_named_child_count(node); + for (uint32_t i = 0; i < n; i++) { + go_receiver_type_params(b, ts_node_named_child(node, i), args, depth + 1, source); + } +} + +/* Go: the type parameter names of a function, a method (its receiver's) or + * a type spec, '|'-joined, or NULL. */ +static const char *go_type_param_names(CBMArena *a, TSNode node, const char *source) { + tf_names_t b = {.a = a}; + go_type_param_list(&b, ts_node_child_by_field_name(node, TS_FIELD("type_parameters")), source); + if (strcmp(ts_node_type(node), "method_declaration") == 0) { + go_receiver_type_params(&b, ts_node_child_by_field_name(node, TS_FIELD("receiver")), false, + 0, source); + } + return b.len ? b.buf : NULL; +} + +/* Python: the identifiers a binding target binds (`a`, `a, (b, *c)`, + * `[d]`); an attribute or subscript target binds no name of the scope. */ +static void py_bind_target(tf_names_t *b, TSNode t, const char *source, int depth) { + if (ts_node_is_null(t) || depth > TF_BIND_DEPTH) { + return; + } + const char *kind = ts_node_type(t); + if (strcmp(kind, "identifier") == 0) { + tf_names_node(b, t, source); + return; + } + if (strcmp(kind, "attribute") == 0 || strcmp(kind, "subscript") == 0) { + return; + } + uint32_t n = ts_node_named_child_count(t); + for (uint32_t i = 0; i < n; i++) { + py_bind_target(b, ts_node_named_child(t, i), source, depth + 1); + } +} + +/* Python: walrus names (`(x := ...)`) inside an expression of the class body + * itself, not inside a nested scope (lambda, comprehension, def, class). */ +static void py_bind_walrus(tf_names_t *b, TSNode e, const char *source, int depth) { + if (ts_node_is_null(e) || depth > TF_BIND_DEPTH * 2) { + return; + } + const char *kind = ts_node_type(e); + if (strcmp(kind, "lambda") == 0 || strcmp(kind, "list_comprehension") == 0 || + strcmp(kind, "set_comprehension") == 0 || strcmp(kind, "dictionary_comprehension") == 0 || + strcmp(kind, "generator_expression") == 0 || strcmp(kind, "function_definition") == 0 || + strcmp(kind, "class_definition") == 0 || strcmp(kind, "decorated_definition") == 0) { + return; + } + if (strcmp(kind, "named_expression") == 0) { + tf_names_node(b, ts_node_child_by_field_name(e, TS_FIELD("name")), source); + } + uint32_t n = ts_node_named_child_count(e); + for (uint32_t i = 0; i < n; i++) { + py_bind_walrus(b, ts_node_named_child(e, i), source, depth + 1); + } +} + +/* Python: the targets after an `as` among a node's children (with items, + * except clauses, as-patterns), and every identifier of a match pattern. */ +static void py_bind_as_targets(tf_names_t *b, TSNode node, const char *source, int depth) { + if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) { + return; + } + const char *kind = ts_node_type(node); + if (strcmp(kind, "block") == 0) { + return; /* a clause body: its statements are walked as statements */ + } + if (strcmp(kind, "case_pattern") == 0) { + py_bind_target(b, node, source, depth + 1); /* captures: every name, over-listed */ + return; + } + bool after_as = false; + uint32_t n = ts_node_child_count(node); + for (uint32_t i = 0; i < n; i++) { + TSNode c = ts_node_child(node, i); + if (!ts_node_is_named(c)) { + after_as = strcmp(ts_node_type(c), "as") == 0; + continue; + } + if (after_as) { + py_bind_target(b, c, source, depth + 1); + after_as = false; + continue; + } + py_bind_as_targets(b, c, source, depth + 1); + } +} + +static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int depth); + +/* Python: the names one statement of a class body binds (it recurses into + * compound statements, whose bodies are the same scope). */ +static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int depth) { + if (ts_node_is_null(s) || depth > TF_BIND_DEPTH) { + return; + } + const char *kind = ts_node_type(s); + if (strcmp(kind, "function_definition") == 0 || strcmp(kind, "class_definition") == 0 || + strcmp(kind, "decorated_definition") == 0) { + return; /* definitions of the class: the step sees them as such */ + } + if (strcmp(kind, "expression_statement") == 0) { + uint32_t n = ts_node_named_child_count(s); + for (uint32_t i = 0; i < n; i++) { + TSNode e = ts_node_named_child(s, i); + /* `a = b = v`: each assignment's left side, down the chain */ + for (int chain = 0; !ts_node_is_null(e) && chain < TF_BIND_DEPTH; chain++) { + const char *ek = ts_node_type(e); + if (strcmp(ek, "assignment") != 0 && strcmp(ek, "augmented_assignment") != 0) { + py_bind_walrus(b, e, source, depth + 1); + break; + } + py_bind_target(b, ts_node_child_by_field_name(e, TS_FIELD("left")), source, + depth + 1); + e = ts_node_child_by_field_name(e, TS_FIELD("right")); + } + } + return; + } + if (strcmp(kind, "import_statement") == 0 || strcmp(kind, "import_from_statement") == 0) { + bool from = kind[7] == 'f'; + uint32_t cc = ts_node_child_count(s); + for (uint32_t i = 0; i < cc; i++) { + const char *field = ts_node_field_name_for_child(s, i); + if (!field || strcmp(field, "name") != 0) { + continue; + } + TSNode name = ts_node_child(s, i); + TSNode alias = strcmp(ts_node_type(name), "aliased_import") == 0 + ? ts_node_child_by_field_name(name, TS_FIELD("alias")) + : (TSNode){0}; + if (!ts_node_is_null(alias)) { + tf_names_node(b, alias, source); + continue; + } + TSNode dotted = strcmp(ts_node_type(name), "aliased_import") == 0 + ? ts_node_child_by_field_name(name, TS_FIELD("name")) + : name; + /* `import a.b` binds `a`; `from m import x` binds `x` */ + TSNode first = !from && ts_node_named_child_count(dotted) > 0 + ? ts_node_named_child(dotted, 0) + : dotted; + tf_names_node(b, first, source); + } + return; + } + if (strcmp(kind, "global_statement") == 0 || strcmp(kind, "nonlocal_statement") == 0 || + strcmp(kind, "delete_statement") == 0) { + py_bind_target(b, s, source, depth + 1); + return; + } + if (strcmp(kind, "type_alias_statement") == 0) { + py_bind_target(b, ts_node_child_by_field_name(s, TS_FIELD("left")), source, depth + 1); + return; + } + if (strcmp(kind, "for_statement") == 0) { + py_bind_target(b, ts_node_child_by_field_name(s, TS_FIELD("left")), source, depth + 1); + } + /* A compound statement: walrus names and `as` targets of its headers, + * then the statements of every block and clause. */ + uint32_t n = ts_node_named_child_count(s); + for (uint32_t i = 0; i < n; i++) { + TSNode c = ts_node_named_child(s, i); + const char *ck = ts_node_type(c); + if (strcmp(ck, "block") == 0) { + py_bind_block(b, c, source, depth + 1); + } else if (strstr(ck, "_clause") != NULL) { + py_bind_as_targets(b, c, source, depth + 1); + py_bind_statement(b, c, source, depth + 1); + } else { + py_bind_walrus(b, c, source, depth + 1); + py_bind_as_targets(b, c, source, depth + 1); + } + } +} + +static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int depth) { + uint32_t n = ts_node_is_null(block) ? 0 : ts_node_named_child_count(block); + for (uint32_t i = 0; i < n; i++) { + py_bind_statement(b, ts_node_named_child(block, i), source, depth); + } +} + +/* Python: the names a class body binds besides its nested definitions, + * '|'-joined (repeats allowed), or NULL. */ +static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char *source) { + if (strcmp(ts_node_type(node), "decorated_definition") == 0) { + node = ts_node_child_by_field_name(node, TS_FIELD("definition")); + } + TSNode body = ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body")); + tf_names_t b = {.a = a}; + py_bind_block(&b, body, source, 0); + return b.len ? b.buf : NULL; +} + /* Make: a rule names several targets (`up down: deps`), each a goal * `make ` runs. The rule's definition carries the first target; * every further one gets a definition of its own over the same rule span -- @@ -7295,7 +7592,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec); extract_route_from_decorators(a, node, ctx->source, spec, &def.route_path, &def.route_method); if (ctx->language == CBM_LANG_PYTHON) { - def.type_params = py_type_param_names(a, node, ctx->source); + def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source)); + } else if (ctx->language == CBM_LANG_GO) { + def_set_type_params(a, &def, go_type_param_names(a, node, ctx->source)); } // Rust: cfg-gated twins (#[cfg(windows)] fn f / #[cfg(not(windows))] fn f) @@ -9047,10 +9346,20 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec); def.docstring = extract_docstring(ctx, node, name); if (ctx->language == CBM_LANG_PYTHON) { - def.type_params = py_type_param_names(a, node, ctx->source); + def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source)); + const char *bound = py_class_body_bindings(a, node, ctx->source); + CBMDefTypeFacts *facts = bound ? def_type_facts(a, &def) : NULL; + if (facts) { + facts->class_bindings = bound; + } } if (ctx->language == CBM_LANG_GO) { - def.go_embedded = go_struct_embedded_text(a, node, ctx->source); + def_set_type_params(a, &def, go_type_param_names(a, node, ctx->source)); + const char *embedded = go_struct_embedded_text(a, node, ctx->source); + CBMDefTypeFacts *facts = embedded && embedded[0] ? def_type_facts(a, &def) : NULL; + if (facts) { + facts->go_embedded = embedded; + } } cbm_defs_push(&ctx->result->defs, a, def); @@ -9577,7 +9886,9 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node, def.decorators = extract_decorators(a, child, ctx->source, ctx->language, spec); extract_route_from_decorators(a, child, ctx->source, spec, &def.route_path, &def.route_method); if (ctx->language == CBM_LANG_PYTHON) { - def.type_params = py_type_param_names(a, child, ctx->source); + def_set_type_params(a, &def, py_type_param_names(a, child, ctx->source)); + } else if (ctx->language == CBM_LANG_GO) { + def_set_type_params(a, &def, go_type_param_names(a, child, ctx->source)); } const char *client_path = NULL; const char *client_method = NULL; @@ -11188,9 +11499,13 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a int before = ctx->result->defs.count; push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child); /* The value's type reaches other files (pkg.V.Method()), - * never the graph (CBMDefinition.value_type). */ - if (vtype && ctx->result->defs.count == before + 1) { - ctx->result->defs.items[before].value_type = vtype; + * never the graph (CBMDefTypeFacts.value_type). */ + CBMDefTypeFacts *facts = + vtype && ctx->result->defs.count == before + 1 + ? def_type_facts(a, &ctx->result->defs.items[before]) + : NULL; + if (facts) { + facts->value_type = vtype; } } } diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index 770629c19..3c5a9d082 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -282,9 +282,15 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) { cr_str(c, &d->decl_namespace); cr_str(c, &d->variant_key); cr_str(c, &d->alias_target); - cr_str(c, &d->type_params); - cr_str(c, &d->value_type); - cr_str(c, &d->go_embedded); + /* The type-facts record: one record, then its strings. */ + cr_array(c, (void **)&d->type_facts, d->type_facts ? 1 : 0, sizeof(CBMDefTypeFacts)); + CBMDefTypeFacts *facts = (CBMDefTypeFacts *)d->type_facts; + if (facts) { + cr_str(c, &facts->type_params); + cr_str(c, &facts->value_type); + cr_str(c, &facts->go_embedded); + cr_str(c, &facts->class_bindings); + } } static void cr_walk_call(cr_ctx_t *c, CBMCall *call) { diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index 4fc11e16e..ba9cf75d0 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -649,6 +649,74 @@ static const char *pxc_qn_leaf(const char *name) { return leaf; } +static bool pxc_go_ident_byte(unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || + c >= 0x80; +} + +/* Whether the '|'-joined name list holds exactly `name[0..len)`. */ +static bool pxc_pipe_list_has(const char *list, const char *name, size_t len) { + for (const char *p = list; p && *p;) { + const char *bar = strchr(p, '|'); + size_t n = bar ? (size_t)(bar - p) : strlen(p); + if (n == len && memcmp(p, name, len) == 0) { + return true; + } + p = bar ? bar + 1 : p + n; + } + return false; +} + +/* A Go type text with every bare identifier that names one of the + * definition's type parameters (`T` in `[]T`, `map[K]V`, `func(T) T`, not the + * `T` of `pkg.T`) spelled `any`: the registrars then type it as nothing of the + * project instead of the package's own type of that name. The text itself, + * unchanged, when it names none. */ +static const char *pxc_go_mask_type_params(CBMArena *arena, const char *text, const char *params) { + if (!text || !text[0] || !params || !params[0]) { + return text; + } + size_t n = strlen(text); + char *out = NULL; + size_t at = 0; + for (size_t i = 0; i < n;) { + if (!pxc_go_ident_byte((unsigned char)text[i])) { + if (out) { + out[at++] = text[i]; + } + i++; + continue; + } + size_t start = i; /* a whole identifier, qualified (`pkg.T`) or bare */ + while (i < n && pxc_go_ident_byte((unsigned char)text[i])) { + i++; + } + bool param = (start == 0 || text[start - 1] != '.') && + pxc_pipe_list_has(params, text + start, i - start); + if (param && !out) { + /* Worst case: every byte a one-byte parameter, 3 bytes each. */ + out = (char *)cbm_arena_alloc(arena, n * 3 + 1); + if (!out) { + return text; + } + memcpy(out, text, start); + at = start; + } + if (param) { + memcpy(out + at, "any", 3); + at += 3; + } else if (out) { + memcpy(out + at, text + start, i - start); + at += i - start; + } + } + if (!out) { + return text; + } + out[at] = '\0'; + return out; +} + /* Convert one CBMDefinition into a CBMLSPDef. Returns 0 on success, -1 * to skip (unsupported label or missing required field). dst gets borrowed * pointers into src and into `arena` for synthesised composites. */ @@ -694,10 +762,11 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch } else { dst->return_types = src->return_type ? cbm_arena_strdup(arena, src->return_type) : NULL; } - if (lang == CBM_LANG_GO && !dst->return_types && src->value_type) { + const CBMDefTypeFacts *facts = src->type_facts; + if (lang == CBM_LANG_GO && !dst->return_types && facts && facts->value_type) { /* A Go package-level value's type: the Go registrars register the * Variable as a value of it (go_lsp.c); the graph never sees it. */ - dst->return_types = cbm_arena_strdup(arena, src->value_type); + dst->return_types = cbm_arena_strdup(arena, facts->value_type); } /* Languages whose cross registrars read embedded_types as QNs get their * bases resolved against the project registry; everyone else keeps the @@ -706,13 +775,13 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch (bs && bs->reg && pxc_lang_resolves_base_qns(lang)) ? pxc_join_base_qns(arena, src->base_classes, bs, module_qn, src->qualified_name) : pxc_join_pipe(arena, src->base_classes); - if (lang == CBM_LANG_GO && src->go_embedded && src->go_embedded[0]) { + if (lang == CBM_LANG_GO && facts && facts->go_embedded && facts->go_embedded[0]) { /* A Go struct's embedded types, as written; the Go registrar promotes * their members (the embedded-member hook, go_lsp.c). */ dst->embedded_types = dst->embedded_types && dst->embedded_types[0] - ? cbm_arena_sprintf(arena, "%s|%s", dst->embedded_types, src->go_embedded) - : cbm_arena_strdup(arena, src->go_embedded); + ? cbm_arena_sprintf(arena, "%s|%s", dst->embedded_types, facts->go_embedded) + : cbm_arena_strdup(arena, facts->go_embedded); } dst->signature_param_types = NULL; dst->signature_param_count = 0; @@ -729,6 +798,15 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch dst->signature_param_count = src->signature_param_count; } } + if (lang == CBM_LANG_GO && facts && facts->type_params) { + /* A type parameter is never the package's type of its name: the + * registrars see `any` for it (pxc_go_mask_type_params). */ + dst->return_types = pxc_go_mask_type_params(arena, dst->return_types, facts->type_params); + for (int i = 0; i < dst->signature_param_count; i++) { + dst->signature_param_types[i] = + pxc_go_mask_type_params(arena, dst->signature_param_types[i], facts->type_params); + } + } dst->lang = lang; dst->alias_target = (lang == CBM_LANG_GO && src->alias_target) ? cbm_arena_strdup(arena, src->alias_target) @@ -963,6 +1041,133 @@ static void pxc_fold_py_field_types(CBMArena *arena, const CBMFileResult *result } } +/* Go: a generic type's field_defs ("name:type|...") with its type parameters + * masked in the type parts (pxc_go_mask_type_params), never in the names. */ +static const char *pxc_go_mask_field_types(CBMArena *arena, const char *field_defs, + const char *params) { + if (!field_defs || !field_defs[0]) { + return field_defs; + } + char *copy = cbm_arena_strdup(arena, field_defs); + size_t cap = strlen(field_defs) * 3 + 1; + char *out = copy ? (char *)cbm_arena_alloc(arena, cap) : NULL; + if (!out) { + return field_defs; + } + size_t at = 0; + for (char *p = copy; p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *colon = strchr(p, ':'); + const char *type = colon ? pxc_go_mask_type_params(arena, colon + 1, params) : NULL; + size_t name_len = colon ? (size_t)(colon - p) + 1 : strlen(p); + if (at) { + out[at++] = '|'; + } + memcpy(out + at, p, name_len); + at += name_len; + if (type) { + size_t tl = strlen(type); + memcpy(out + at, type, tl); + at += tl; + } + p = bar ? bar + 1 : NULL; + } + out[at] = '\0'; + return out; +} + +/* Python: a class's field_defs with each name its body binds (other than its + * nested definitions) added as `name:` -- an attribute of unknown type the + * registrar skips (py_split_field_defs keeps typed fields only). The names + * decide this file's identities (type_scope.h), so they must be part of its + * stored row, which the incremental planner compares. */ +static const char *pxc_py_add_class_bindings(CBMArena *arena, const char *field_defs, + const char *bindings) { + size_t total = (field_defs ? strlen(field_defs) : 0) + 2 * strlen(bindings) + 2; + char *out = (char *)cbm_arena_alloc(arena, total); + CBMHashTable *have = cbm_ht_create(16); + if (!out || !have) { + cbm_ht_free(have); + return field_defs; + } + size_t at = 0; + for (const char *p = field_defs; p && *p;) { + const char *bar = strchr(p, '|'); + size_t n = bar ? (size_t)(bar - p) : strlen(p); + const char *colon = memchr(p, ':', n); + const char *name = cbm_arena_strndup(arena, p, colon ? (size_t)(colon - p) : n); + if (name) { + cbm_ht_set(have, name, (void *)name); + } + memcpy(out + at, p, n); + at += n; + out[at++] = '|'; + p = bar ? bar + 1 : p + n; + } + for (const char *p = bindings; *p;) { + const char *bar = strchr(p, '|'); + size_t n = bar ? (size_t)(bar - p) : strlen(p); + const char *name = n ? cbm_arena_strndup(arena, p, n) : NULL; + if (name && !cbm_ht_get(have, name)) { + cbm_ht_set(have, name, (void *)name); + memcpy(out + at, p, n); + at += n; + out[at++] = ':'; + out[at++] = '|'; + } + p = bar ? bar + 1 : p + n; + } + cbm_ht_free(have); + if (at > 0) { + at--; /* the last separator */ + } + out[at] = '\0'; + return at ? out : field_defs; +} + +/* The facts only the cross-file step reads (CBMDefTypeFacts), on the file's + * LSP defs after the field folds: a Go generic type's field types name its + * type parameters as `any`; a Python class body's bindings join its + * field_defs. One hash of the file's defs, built only when one applies. */ +static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLSPDef *defs, + int start, int end, CBMLanguage lang) { + if (!fr || (lang != CBM_LANG_GO && lang != CBM_LANG_PYTHON) || start >= end) { + return; + } + CBMHashTable *by_qn = NULL; + for (int di = 0; di < fr->defs.count; di++) { + const CBMDefinition *d = &fr->defs.items[di]; + const CBMDefTypeFacts *f = d->type_facts; + if (!f || !d->qualified_name || !d->label || !cbm_label_is_type_like(d->label)) { + continue; + } + bool go_generic = lang == CBM_LANG_GO && f->type_params; + bool py_bound = lang == CBM_LANG_PYTHON && f->class_bindings; + if (!go_generic && !py_bound) { + continue; + } + if (!by_qn) { + by_qn = cbm_ht_create((uint32_t)(end - start + 1)); + for (int si = start; by_qn && si < end; si++) { + if (defs[si].qualified_name && !cbm_ht_get(by_qn, defs[si].qualified_name)) { + cbm_ht_set(by_qn, defs[si].qualified_name, &defs[si]); + } + } + } + CBMLSPDef *dst = by_qn ? (CBMLSPDef *)cbm_ht_get(by_qn, d->qualified_name) : NULL; + if (!dst) { + continue; + } + dst->field_defs = go_generic + ? pxc_go_mask_field_types(arena, dst->field_defs, f->type_params) + : pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings); + } + cbm_ht_free(by_qn); +} + /* Carry one Rust type-level impl independently of any method definition. * `impl Trait for Type {}` is semantically meaningful even when the block is * empty (the trait may provide defaults), so attaching the relation only to @@ -1342,6 +1547,8 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are * the structs its `.c` files access. */ pxc_fold_struct_fields(arena, fr, defs, file_start, idx, "Class"); } + /* Go generic types and Python class bodies (CBMDefTypeFacts). */ + pxc_apply_type_facts(arena, fr, defs, file_start, idx, files[fi].language); if (files[fi].language == CBM_LANG_RUST) { for (int ii = 0; ii < fr->impl_traits.count; ii++) { if (pxc_build_rust_impl_relation(arena, &fr->impl_traits.items[ii], project_name, @@ -1365,6 +1572,7 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are scope.file_defs = fr->defs.items; scope.file_def_count = fr->defs.count; scope.module_facts = &fr->py_namespace; + scope.graph = ctx->gbuf; /* the graph the import map read */ } cbm_type_scope_file_t *ts_file = cbm_type_scope_file_begin(scope_lang, &scope); for (int di = file_start; ts_file && di < idx; di++) { diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index ba3596a1e..96630e133 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2608,8 +2608,14 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c census_len(def->client_route_path) + census_len(def->impl_trait) + census_len(def->http_base_url) + census_list(def->extra_props) + census_len(def->decl_namespace) + census_len(def->variant_key) + - census_len(def->alias_target) + census_len(def->type_params) + - census_len(def->value_type) + census_len(def->go_embedded); + census_len(def->alias_target); + if (def->type_facts) { + str_def_misc += sizeof(*def->type_facts) + + census_len(def->type_facts->type_params) + + census_len(def->type_facts->value_type) + + census_len(def->type_facts->go_embedded) + + census_len(def->type_facts->class_bindings); + } } for (int c = 0; c < r->calls.count; c++) { const CBMCall *call = &r->calls.items[c]; diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index 87f13114a..bf6ecd1bf 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -12,6 +12,7 @@ #include "pipeline/type_scope.h" #include "foundation/constants.h" +#include "graph_buffer/graph_buffer.h" /* the module check of a target */ #include #include @@ -95,6 +96,7 @@ struct cbm_type_scope_file { CBMHashTable *seen; /* spelling -> serial of the last def that wrote it */ /* lexical scopes only */ CBMHashTable *defs; /* file def QN -> index + 1 into scope.file_defs */ + CBMHashTable *class_binds; /* "." a class body binds (not a def) */ CBMHashTable *tparams; /* every type parameter name the file declares */ CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */ CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */ @@ -159,13 +161,33 @@ static bool type_scope_rebound(const cbm_type_scope_file_t *f, const char *head) return f->bindings && cbm_ht_get(f->bindings, head) == TYPE_SCOPE_BOUND_MANY; } -/* Hash the file's own definitions and its type parameter names. */ +/* Each name a class body binds besides its definitions, keyed as a member of + * the class (".", the key type_scope_shadowed probes). */ +static void type_scope_index_class_bindings(cbm_type_scope_file_t *f, const CBMDefinition *d) { + const char *bound = d->type_facts ? d->type_facts->class_bindings : NULL; + for (const char *p = bound; p && *p && d->qualified_name;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + TYPE_SCOPE_WORK(len + 1); + char *key = len ? cbm_arena_sprintf(&f->keys, "%s.%.*s", d->qualified_name, (int)len, p) + : NULL; + if (key && !cbm_ht_get(f->class_binds, key)) { + cbm_ht_set(f->class_binds, key, key); + } + p = bar ? bar + 1 : p + len; + } +} + +/* Hash the file's own definitions, its type parameter names and the names + * its class bodies bind. */ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { int n = f->scope.file_def_count; f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); + f->class_binds = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); - if (!f->defs || !f->tparams || !f->nesting || !type_scope_index_module_facts(f)) { + if (!f->defs || !f->class_binds || !f->tparams || !f->nesting || + !type_scope_index_module_facts(f)) { return false; } for (int i = 0; i < n; i++) { @@ -174,7 +196,8 @@ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { TYPE_SCOPE_WORK(1); cbm_ht_set(f->defs, d->qualified_name, (void *)(uintptr_t)(i + 1)); } - for (const char *p = d->type_params; p && *p;) { + type_scope_index_class_bindings(f, d); + for (const char *p = d->type_facts ? d->type_facts->type_params : NULL; p && *p;) { const char *bar = strchr(p, '|'); size_t len = bar ? (size_t)(bar - p) : strlen(p); char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL; @@ -234,6 +257,7 @@ void cbm_type_scope_file_end(cbm_type_scope_file_t *file) { cbm_ht_free(file->memo); cbm_ht_free(file->seen); cbm_ht_free(file->defs); + cbm_ht_free(file->class_binds); cbm_ht_free(file->tparams); cbm_ht_free(file->nesting); cbm_ht_free(file->bindings); @@ -243,7 +267,9 @@ void cbm_type_scope_file_end(cbm_type_scope_file_t *file) { /* ── Resolution ───────────────────────────────────────────────────── */ -/* `qn` when it names a project definition of an allowed label, else NULL. */ +/* `qn` when it names a project definition of an allowed label, else NULL. A + * QN the graph holds as a module (a class and a module of one QN) is none: + * the two share their members' QNs. */ static const char *type_scope_target(const cbm_type_scope_file_t *f, const char *qn) { TYPE_SCOPE_WORK(1); const char *label = cbm_registry_label_of(f->scope.reg, qn); @@ -252,7 +278,10 @@ static const char *type_scope_target(const cbm_type_scope_file_t *f, const char } for (const char *const *l = f->lang->labels; *l; l++) { if (strcmp(*l, label) == 0) { - return qn; + const cbm_gbuf_node_t *node = + f->lang->lexical_scopes && f->scope.graph ? cbm_gbuf_find_by_qn(f->scope.graph, qn) + : NULL; + return node && node->label && strcmp(node->label, "Module") == 0 ? NULL : qn; } } return NULL; @@ -449,7 +478,8 @@ static const char *type_scope_enclosing_class(cbm_type_scope_file_t *f, const ch /* True when the def's own scopes bind the head of this spelling before the * module does: a type parameter the file declares, or a name the enclosing - * class body declares. */ + * class body declares (a nested definition) or binds (an assignment, an + * import, a loop or with or except target...). */ static bool type_scope_shadowed(cbm_type_scope_file_t *f, const char *name, size_t len) { size_t head_len = type_scope_head_len(name, len); char head[CBM_SZ_256]; @@ -465,7 +495,8 @@ static bool type_scope_shadowed(cbm_type_scope_file_t *f, const char *name, size } const char *member = cbm_arena_sprintf(&f->keys, "%s.%s", f->enclosing_class, head); TYPE_SCOPE_WORK(1); - return !member || cbm_ht_get(f->defs, member) != NULL; + return !member || cbm_ht_get(f->defs, member) != NULL || + cbm_ht_get(f->class_binds, member) != NULL; } /* ── Reduction of a type text to the names it writes ──────────────── */ diff --git a/src/pipeline/type_scope.h b/src/pipeline/type_scope.h index 2235a0f55..cf547850f 100644 --- a/src/pipeline/type_scope.h +++ b/src/pipeline/type_scope.h @@ -67,9 +67,12 @@ typedef struct { /* Python: an annotation is evaluated in the def's enclosing scopes before * the module. A def nested in a function sees that function's locals, * which the step cannot list, so it gets no identity; a name the - * immediately enclosing class body declares and a PEP 695 type parameter - * of the file get none, and neither does a name the module binds more - * than once (cbm_type_scope_t.module_facts). */ + * immediately enclosing class body declares or binds (any binding: + * CBMDefTypeFacts.class_bindings) and a PEP 695 type parameter of the + * file get none, and neither does a name the module binds more than once + * (cbm_type_scope_t.module_facts), nor a type whose QN the graph holds as + * a module (a class `Thing` in pkg/a/__init__.py beside pkg/a/Thing.py: + * their members share QNs, so no member answer is that class's). */ bool lexical_scopes; /* Which CBMLSPDef texts hold raw type spellings for this language. */ bool return_types; @@ -91,7 +94,7 @@ typedef struct { const char *const *imp_vals; int imp_count; /* lexical_scopes only: the file's extraction definitions, in any order - * (their QNs, labels and type_params); NULL with def_count 0 = none. */ + * (their QNs, labels and type facts); NULL with def_count 0 = none. */ const CBMDefinition *file_defs; int file_def_count; /* lexical_scopes only: the module's ordered namespace facts. Without a @@ -99,6 +102,10 @@ typedef struct { * no identity; a name the module binds twice (two imports, an import and * a definition, a later assignment) gets none. */ const CBMPyNamespaceFacts *module_facts; + /* lexical_scopes only: the graph the import map reads (its nodes' + * labels), so a QN that is a module's gets no identity; NULL = not + * checked. */ + const struct cbm_gbuf *graph; } cbm_type_scope_t; /* Per-file working state: the import map by key, the file's own scopes, and diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 23e26e5ef..820f625f2 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -285,6 +285,38 @@ TEST(type_scope_python_enclosing_scopes) { PASS(); } +/* Round 3, N2: a name the class body binds without defining it (`Config = + * Other`, an import, a loop, with or except target) is the class attribute in + * its methods' annotations, so it gets no identity; a name the body does not + * bind keeps the module's. */ +TEST(type_scope_python_class_body_bindings) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "Config", "p.app.Config", "Class", false); + cbm_registry_add(u.reg, "Keep", "p.app.Keep", "Class", false); + static const CBMDefTypeFacts model_binds = {.class_bindings = "x|Config|Other"}; + const CBMDefinition defs[] = { + {.qualified_name = "p.app.Config", .label = "Class"}, + {.qualified_name = "p.app.Keep", .label = "Class"}, + {.qualified_name = "p.app.Model", .label = "Class", .type_facts = &model_binds}, + {.qualified_name = "p.app.Model.cfg", .label = "Method"}, + {.qualified_name = "p.app.top", .label = "Function"}, + }; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .file_defs = defs, + .file_def_count = (int)(sizeof(defs) / sizeof(defs[0])), + .def_qn = "p.app.Model.cfg", + .ret = "Optional[Config]"}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "Keep"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Keep=p.app.Keep"); + in.def_qn = "p.app.top"; /* outside the class: the module's Config */ + in.ret = "Config"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Config=p.app.Config"); + ts_unit_end(&u); + PASS(); +} + /* Type parameters: a PEP 695 parameter of the file (`def f[T]`, * `class C[T]`) and a TypeVar the module assigns over an import never take a * real type's identity. */ @@ -293,10 +325,12 @@ TEST(type_scope_python_type_parameters) { ts_unit_begin(&u); cbm_registry_add(u.reg, "T", "p.app.T", "Class", false); cbm_registry_add(u.reg, "Item", "p.a.Item", "Class", false); + static const CBMDefTypeFacts wrap_params = {.type_params = "T"}; + static const CBMDefTypeFacts box_params = {.type_params = "K|T"}; const CBMDefinition defs[] = { {.qualified_name = "p.app.T", .label = "Class"}, - {.qualified_name = "p.app.wrap", .label = "Function", .type_params = "T"}, - {.qualified_name = "p.app.Box", .label = "Class", .type_params = "K|T"}, + {.qualified_name = "p.app.wrap", .label = "Function", .type_facts = &wrap_params}, + {.qualified_name = "p.app.Box", .label = "Class", .type_facts = &box_params}, {.qualified_name = "p.app.Box.get", .label = "Method"}, }; ts_attach_t in = {.lang = CBM_LANG_PYTHON, @@ -785,6 +819,90 @@ TEST(type_scope_python_nested_class_is_not_the_module_class) { return ts_twins("pynest", py_nested_files, CBM_LANG_PYTHON, py_nested_check); } +/* Round 3, N2 (the review's py-classattr): a class body that binds a name + * without defining it -- `Config = OtherConfig`, an import, an annotated + * assignment, a for, with or except target, a walrus -- makes that name the + * class attribute in its methods' annotations (Python: get_type_hints gives + * OtherConfig, Other, None, 1...). None of them may become the module-level + * class of that name; a name the body does not bind (Keep) still does. */ +static const ts_file_t py_classbind_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/other.py", "class OtherConfig:\n def load(self):\n return 'other'\n\n\n" + "class Other:\n def load(self):\n return 'other'\n"}, + {"pkg/mod.py", + "import contextlib\nfrom pkg.other import Other, OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class A:\n def load(self):\n return 'A'\n\n\n" + "class B:\n def load(self):\n return 'B'\n\n\n" + "class C:\n def load(self):\n return 'C'\n\n\n" + "class D:\n def load(self):\n return 'D'\n\n\n" + "class F:\n def load(self):\n return 'F'\n\n\n" + "class Keep:\n def load(self):\n return 'keep'\n\n\n" + "class Model:\n" + " Config = OtherConfig\n" + " from pkg.other import Other as A\n" + " B: type = Other\n" + " for C in (1,):\n pass\n" + " with contextlib.nullcontext() as D:\n pass\n" + " (F := 1)\n\n" + " def cfg(self) -> Config:\n return OtherConfig()\n\n" + " def ma(self) -> A:\n return Other()\n\n" + " def mb(self) -> B:\n return Other()\n\n" + " def mc(self) -> C:\n return None\n\n" + " def md(self) -> D:\n return None\n\n" + " def mf(self) -> F:\n return None\n\n" + " def keep(self) -> Keep:\n return Keep()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run():\n return Model().cfg().load()\n\n\n" + "def run_a():\n return Model().ma().load()\n\n\n" + "def run_b():\n return Model().mb().load()\n\n\n" + "def run_c():\n return Model().mc().load()\n\n\n" + "def run_d():\n return Model().md().load()\n\n\n" + "def run_f():\n return Model().mf().load()\n\n\n" + "def run_keep():\n return Model().keep().load()\n"}, + {NULL, NULL}}; + +static int py_classbind_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL) + + ts_calls_to(s, project, "run_a", "pkg.mod.A.load", NULL) + + ts_calls_to(s, project, "run_b", "pkg.mod.B.load", NULL) + + ts_calls_to(s, project, "run_c", "pkg.mod.C.load", NULL) + + ts_calls_to(s, project, "run_d", "pkg.mod.D.load", NULL) + + ts_calls_to(s, project, "run_f", "pkg.mod.F.load", NULL); + int keep = ts_calls_to(s, project, "run_keep", "pkg.mod.Keep.load", NULL); + printf(" python class-body bindings (%s): module-class edges=%d, keep=%d\n", label, wrong, + keep); + return !(wrong == 0 && keep == 1); +} + +TEST(type_scope_python_class_body_bindings_shadow_the_module) { + return ts_twins("pybind", py_classbind_files, CBM_LANG_PYTHON, py_classbind_check); +} + +/* Round 3 (a class and a module of one QN): pkg/a/__init__.py defines class + * Thing beside the module pkg/a/Thing.py; both share the QN pkg.a.Thing and + * their members `run` share pkg.a.Thing.run, so no member edge through an + * identity Thing=pkg.a.Thing is that class's (the graph keeps the module's + * nodes). Python: `from pkg.a import Thing` is the class while nothing imports + * the submodule, and the submodule once something does. */ +static const ts_file_t py_classmod_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a/__init__.py", "class Thing:\n def run(self):\n return 'class'\n"}, + {"pkg/a/Thing.py", "def run():\n return 'module'\n"}, + {"pkg/b.py", "from pkg.a import Thing\n\n\ndef make() -> Thing:\n return Thing()\n"}, + {"pkg/c.py", "from pkg.b import make\n\n\ndef go():\n return make().run()\n"}, + {NULL, NULL}}; + +static int py_classmod_check(cbm_store_t *s, const char *project, const char *label) { + int member = ts_calls_to(s, project, "go", "pkg.a.Thing.run", NULL); + printf(" python class and module of one QN (%s): go -> Thing.run=%d\n", label, member); + return member != 0; +} + +TEST(type_scope_python_class_and_module_of_one_qn) { + return ts_twins("pyclassmod", py_classmod_files, CBM_LANG_PYTHON, py_classmod_check); +} + /* Finding 6: `-> Self` chains across files keep main's edges; `Self` comes * from typing, which the project does not define. A decoy declares the same * method names. */ @@ -1729,3 +1847,6 @@ SUITE(type_scope) { RUN_TEST(type_scope_incremental_python_body_edits); RUN_TEST(type_scope_incremental_python_declaring_change_matches_full); } + RUN_TEST(type_scope_python_class_body_bindings); + RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); + RUN_TEST(type_scope_python_class_and_module_of_one_qn); From a1c003423e5f7d776e25bd232cc7adbbe1ee8046 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 06:58:06 +0100 Subject: [PATCH 11/25] fix(lsp): Go embedded field names, function-declared types, all fields Three defects the second review found in the Go engine, and one limit beside them: - The unqualified type name of an embedded field is a field of its depth (Go spec), so in `Server{ Config; base.Handler }` the selector s.Config is the embedded Config even where Handler has a field Config one level down, and an embedded func type `Logger` shadows a promoted method Logger. The member lookup saw named fields only: a deeper field won (main's right edge replaced by a wrong one) and a deeper method was called. Every registry route now names each embedded type as a field of the embedding type: typed as the embedded type when its QN is known, of unknown type otherwise (it shadows and answers nothing, e.g. sync.Mutex). A QN of several definitions (build variants, foo and foo_test) shadows every field name any of them declares, so no deeper member of that name is selected where they disagree. - The walker typed a function's type parameter, its generic receiver's, and a type the function declares itself (`type T struct{...}` in the body) as the package's own T, which now promoted T's embedded members. Those names shadow the package's types in the function (a local type from its declaration on); they are unknown to the walker, which abstains. Main's own false edge from a type parameter to a method of the package's T goes with it. - The per-file route replaced the walked file's struct fields and embedded types with a scan of its syntax tree that kept 15 embedded types and 63 fields, while the full index took them from the definitions: a one-file repair lacked edges the full index had. Every route now takes them from the definitions, all of them; parse_field_defs and the in-file scan keep every field too (the 63-field limit cut both routes alike and decided which field calls resolve). The agreement table's joins are linear now (one buffer each). Signed-off-by: Martin Vogel --- internal/cbm/lsp/go_lsp.c | 561 +++++++++++++++++++++++++++----------- internal/cbm/lsp/go_lsp.h | 5 + tests/test_go_lsp.c | 6 +- tests/test_type_scope.c | 226 ++++++++++++++- 4 files changed, 633 insertions(+), 165 deletions(-) diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 57411902e..4dab9b4ab 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -33,6 +33,8 @@ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, const char *field_name, int depth); static void extract_type_params_from_ast(CBMArena *arena, CBMTypeRegistry *reg, TSNode root, const char *source, const char *module_qn); +static const char *go_embedded_spelling(const char **next, size_t *len); +static const char *go_embedded_field_name(CBMArena *a, const char *s, size_t len); // --- Initialization --- @@ -125,6 +127,80 @@ static const CBMType *resolve_builtin_type(GoLSPContext *ctx, const char *name) // --- go_parse_type_node: AST type node -> CBMType --- +/* ── Type names a function declares itself ──────────────────────────── + * + * A function's type parameters (and its receiver's) and the types it declares + * in its body are not the package's types of those names: `func F[T any](x T)` + * and `func F() { type T struct{...}; var t T }` in a package with its own T. + * The walker types such a name as unknown (it abstains) instead of the + * package-level type. A local type's scope starts at its declaration; one + * declared in an inner block shadows for the rest of the function (an + * abstention, never another answer). */ +static bool go_type_shadowed(const GoLSPContext *ctx, const char *name) { + return ctx->shadow_types && name && cbm_ht_get(ctx->shadow_types, name) != NULL; +} + +static void go_shadow_add(GoLSPContext *ctx, TSNode name_node) { + char *name = ts_node_is_null(name_node) ? NULL : lsp_node_text(ctx, name_node); + if (!name || !name[0] || strcmp(name, "_") == 0) { + return; + } + if (!ctx->shadow_types) { + ctx->shadow_types = cbm_ht_create(16); + } + if (ctx->shadow_types && !cbm_ht_get(ctx->shadow_types, name)) { + cbm_ht_set(ctx->shadow_types, name, name); + } +} + +/* `[K comparable, V any]`: every name of every type_parameter_declaration. */ +static void go_shadow_type_params(GoLSPContext *ctx, TSNode list) { + uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list); + for (uint32_t i = 0; i < n; i++) { + TSNode decl = ts_node_named_child(list, i); + if (strcmp(ts_node_type(decl), "type_parameter_declaration") != 0) { + continue; + } + uint32_t cc = ts_node_child_count(decl); + for (uint32_t k = 0; k < cc; k++) { + const char *field = ts_node_field_name_for_child(decl, k); + if (field && strcmp(field, "name") == 0) { + go_shadow_add(ctx, ts_node_child(decl, k)); + } + } + } +} + +/* A generic receiver `(s *Set[K, V])` declares K and V: the type identifiers + * inside the receiver type's type arguments. */ +static void go_shadow_receiver_params(GoLSPContext *ctx, TSNode node, bool in_args, int depth) { + if (ts_node_is_null(node) || depth > CBM_LSP_MAX_LOOKUP_DEPTH) { + return; + } + const char *kind = ts_node_type(node); + if (in_args && strcmp(kind, "type_identifier") == 0) { + go_shadow_add(ctx, node); + return; + } + bool args = in_args || strcmp(kind, "type_arguments") == 0; + uint32_t n = ts_node_named_child_count(node); + for (uint32_t i = 0; i < n; i++) { + go_shadow_receiver_params(ctx, ts_node_named_child(node, i), args, depth + 1); + } +} + +/* `type T struct{...}` / `type T = U` inside the function being walked. */ +static void go_shadow_declared_types(GoLSPContext *ctx, TSNode decl) { + uint32_t n = ts_node_named_child_count(decl); + for (uint32_t i = 0; i < n; i++) { + TSNode spec = ts_node_named_child(decl, i); + const char *sk = ts_node_type(spec); + if (strcmp(sk, "type_spec") == 0 || strcmp(sk, "type_alias") == 0) { + go_shadow_add(ctx, ts_node_child_by_field_name(spec, "name", 4)); + } + } +} + const CBMType *go_parse_type_node(GoLSPContext *ctx, TSNode node) { if (ts_node_is_null(node)) return cbm_type_unknown(); @@ -136,6 +212,8 @@ const CBMType *go_parse_type_node(GoLSPContext *ctx, TSNode node) { char *name = lsp_node_text(ctx, node); if (!name) return cbm_type_unknown(); + if (go_type_shadowed(ctx, name)) + return cbm_type_unknown(); /* the function's own T, not the package's */ const CBMType *builtin = resolve_builtin_type(ctx, name); if (builtin) return builtin; @@ -430,6 +508,9 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { const CBMType *t = cbm_scope_lookup(ctx->current_scope, name); if (cbm_scope_contains(ctx->current_scope, name)) return t ? t : cbm_type_unknown(); + // A type the function declares itself (a conversion `T(x)`) + if (go_type_shadowed(ctx, name)) + return cbm_type_unknown(); // A package-level function or value (of any file of the package) const CBMType *st = @@ -1635,6 +1716,10 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { go_walk_func_literal(ctx, node); return; } + /* A type declared in the function shadows the package's from here on. */ + if (ctx->in_function && strcmp(kind, "type_declaration") == 0) { + go_shadow_declared_types(ctx, node); + } // Process statements to build scope go_process_statement(ctx, node); @@ -2125,6 +2210,18 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { CBMScope *saved_scope = ctx->current_scope; ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); + // The function's type parameters (and its receiver's) shadow the + // package's types of those names, in its signature and its body. + CBMHashTable *saved_shadow = ctx->shadow_types; + bool saved_in_function = ctx->in_function; + ctx->shadow_types = NULL; + ctx->in_function = true; + go_shadow_type_params(ctx, ts_node_child_by_field_name(func_node, "type_parameters", 15)); + if (strcmp(ts_node_type(func_node), "method_declaration") == 0) { + go_shadow_receiver_params(ctx, ts_node_child_by_field_name(func_node, "receiver", 8), false, + 0); + } + // Bind parameters into scope (including variadic) TSNode params = ts_node_child_by_field_name(func_node, "parameters", 10); if (!ts_node_is_null(params)) { @@ -2236,6 +2333,9 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { // Restore scope ctx->current_scope = saved_scope; + cbm_ht_free(ctx->shadow_types); /* NULL-safe */ + ctx->shadow_types = saved_shadow; + ctx->in_function = saved_in_function; } // --- Process entire file --- @@ -2701,12 +2801,20 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, if (ts_node_is_null(field_list)) continue; - // Scan field_declarations for embeds and named fields - const char *embeds[16]; + // Scan field_declarations for embeds and named fields: all of + // them (no count decides what the registry holds). An embedded + // type is also a field named by its unqualified type name. + uint32_t fl_cap = ts_node_child_count(field_list) * 2 + 1; + const char **embeds = + (const char **)cbm_arena_alloc(arena, fl_cap * sizeof(const char *)); int embed_count = 0; - const char *fld_names[64]; - const CBMType *fld_types[64]; + const char **fld_names = + (const char **)cbm_arena_alloc(arena, fl_cap * sizeof(const char *)); + const CBMType **fld_types = + (const CBMType **)cbm_arena_alloc(arena, fl_cap * sizeof(const CBMType *)); int fld_count = 0; + if (!embeds || !fld_names || !fld_types) + continue; // Create a temporary LSP context for parsing field types GoLSPContext tmp_ctx; @@ -2730,18 +2838,24 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, if (ts_node_is_null(fname) && !ts_node_is_null(ftype)) { // Embedded field: has type but no name - if (embed_count < 15) { - char *embed_text = cbm_node_text(arena, ftype, source); - if (embed_text && embed_text[0]) { - const char *et = embed_text; - while (*et == '*') - et++; - embeds[embed_count++] = - cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + char *embed_text = cbm_node_text(arena, ftype, source); + if (embed_text && embed_text[0]) { + const char *et = embed_text; + while (*et == '*') + et++; + const char *eqn = cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + embeds[embed_count++] = eqn; + size_t elen = 0; + const char *enext = embed_text; + const char *es = go_embedded_spelling(&enext, &elen); + const char *ename = es ? go_embedded_field_name(arena, es, elen) : NULL; + if (ename && eqn) { + fld_names[fld_count] = ename; + fld_types[fld_count] = cbm_type_named(arena, eqn); + fld_count++; } } - } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype) && - fld_count < 63) { + } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype)) { // Named field: name + type char *fn = cbm_node_text(arena, fname, source); if (fn && fn[0]) { @@ -2922,6 +3036,51 @@ static CBMHashTable *go_value_qn_counts(CBMArena *a, const CBMLSPDef *defs, int * (type_scope.h), or for a bare name the declaring package's own type; a * spelling neither gives is dropped. This is the one Go-specific step on top * of the shared layer. */ +/* One embedded spelling of a '|'-joined list, without its `*` and its type + * arguments (a generic instance names its type): sets *len, returns its + * start, or NULL at the end of the list. *next moves past it. */ +static const char *go_embedded_spelling(const char **next, size_t *len) { + const char *p = *next; + if (!p || !*p) { + return NULL; + } + const char *bar = strchr(p, '|'); + size_t n = bar ? (size_t)(bar - p) : strlen(p); + *next = bar ? bar + 1 : p + n; + while (n > 0 && *p == '*') { + p++; + n--; + } + const char *bracket = memchr(p, '[', n); + *len = bracket ? (size_t)(bracket - p) : n; + return p; +} + +/* The QN of one embedded spelling: its identity in the declaring file's + * scope, or for a bare name the declaring package's own type; NULL when + * neither gives one. */ +static const char *go_embedded_qn(CBMArena *a, const char *s, size_t len, const char *def_mod, + const cbm_type_scope_index_t *scope_ix) { + const char *qn = len ? cbm_type_scope_find(scope_ix, s, len) : NULL; + if (!qn && len && !memchr(s, '.', len) && def_mod && def_mod[0]) { + qn = cbm_arena_sprintf(a, "%s.%.*s", def_mod, (int)len, s); + } + return qn; +} + +/* The field name an embedded spelling declares: Go's unqualified type name + * (`pkg.T` -> `T`). NULL when it has none. */ +static const char *go_embedded_field_name(CBMArena *a, const char *s, size_t len) { + const char *name = s; + for (size_t i = 0; i < len; i++) { + if (s[i] == '.') { + name = s + i + 1; + } + } + size_t n = len - (size_t)(name - s); + return n ? cbm_arena_strndup(a, name, n) : NULL; +} + static const char **go_embedded_qns(CBMArena *a, const char *embedded, const char *def_mod, const cbm_type_scope_index_t *scope_ix) { if (!embedded || !embedded[0]) { @@ -2936,31 +3095,92 @@ static const char **go_embedded_qns(CBMArena *a, const char *embedded, const cha return NULL; } int n = 0; - for (const char *p = embedded; *p;) { - const char *bar = strchr(p, '|'); - size_t len = bar ? (size_t)(bar - p) : strlen(p); - const char *s = p; - while (len > 0 && *s == '*') { - s++; - len--; - } - const char *bracket = memchr(s, '[', len); /* a generic instance: its type */ - if (bracket) { - len = (size_t)(bracket - s); - } - const char *qn = len ? cbm_type_scope_find(scope_ix, s, len) : NULL; - if (!qn && len && !memchr(s, '.', len) && def_mod && def_mod[0]) { - qn = cbm_arena_sprintf(a, "%s.%.*s", def_mod, (int)len, s); - } + size_t len = 0; + for (const char *next = embedded, *s; (s = go_embedded_spelling(&next, &len)) != NULL;) { + const char *qn = go_embedded_qn(a, s, len, def_mod, scope_ix); if (qn) { out[n++] = qn; } - p = bar ? bar + 1 : p + strlen(p); } out[n] = NULL; return n > 0 ? out : NULL; } +/* Append fields to rt (a name rt already declares keeps its entry). One hash + * set of the names, so the cost is linear in the fields. */ +static void go_append_fields(CBMArena *a, CBMRegisteredType *rt, const char *const *names, + const CBMType *const *types, int n) { + if (n <= 0) { + return; + } + int had = 0; + while (rt->field_names && rt->field_names[had]) { + had++; + } + const char **out_names = (const char **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(char *)); + const CBMType **out_types = + (const CBMType **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(CBMType *)); + CBMHashTable *present = cbm_ht_create((uint32_t)(had + n + 8)); + if (!out_names || !out_types || !present) { + cbm_ht_free(present); + return; + } + int count = 0; + for (int i = 0; i < had; i++) { + out_names[count] = rt->field_names[i]; + out_types[count++] = rt->field_types ? rt->field_types[i] : NULL; + cbm_ht_set(present, rt->field_names[i], (void *)1); + } + for (int i = 0; i < n; i++) { + if (!names[i] || cbm_ht_get(present, names[i])) { + continue; + } + cbm_ht_set(present, names[i], (void *)1); + out_names[count] = names[i]; + out_types[count++] = types[i] ? types[i] : cbm_type_unknown(); + } + cbm_ht_free(present); + out_names[count] = NULL; + out_types[count] = NULL; + rt->field_names = out_names; + rt->field_types = out_types; +} + +/* Go's selector rule names an embedded field by its unqualified type name, at + * the embedding type's depth: `s.Config` is the embedded Config even where an + * embedded type has a field Config one level down, and a method of that name + * one level down is shadowed by it. Each embedded spelling of `embedded` + * becomes a field of rt: typed as the embedded type when `typed` and its QN is + * known, else of unknown type (it shadows, and answers nothing). */ +static void go_add_embedded_fields(CBMArena *a, CBMRegisteredType *rt, const char *embedded, + const char *def_mod, const cbm_type_scope_index_t *scope_ix, + bool typed) { + if (!embedded || !embedded[0] || rt->is_interface) { + return; + } + int count = 1; + for (const char *p = embedded; *p; p++) { + count += *p == '|'; + } + const char **names = (const char **)cbm_arena_alloc(a, (size_t)count * sizeof(char *)); + const CBMType **types = (const CBMType **)cbm_arena_alloc(a, (size_t)count * sizeof(CBMType *)); + if (!names || !types) { + return; + } + int n = 0; + size_t len = 0; + for (const char *next = embedded, *s; (s = go_embedded_spelling(&next, &len)) != NULL;) { + const char *name = go_embedded_field_name(a, s, len); + if (!name) { + continue; + } + const char *qn = typed ? go_embedded_qn(a, s, len, def_mod, scope_ix) : NULL; + names[n] = name; + types[n++] = qn ? cbm_type_named(a, qn) : cbm_type_unknown(); + } + go_append_fields(a, rt, names, types, n); +} + /* A package-level value (a Go `var`/`const` Variable def whose declaration or * initializer spells its type): registered under . with * CBM_FUNC_FLAG_VALUE and that type as the signature's single result, so @@ -3051,14 +3271,12 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char const cbm_type_scope_index_t *scope_ix, const char ***names_out, const CBMType ***types_out) { - // Count fields + // Count fields: all of them (no count decides which fields a struct has) int count = 1; for (const char *p = field_defs; *p; p++) { if (*p == '|') count++; } - if (count > 63) - count = 63; const char **names = (const char **)cbm_arena_alloc(arena, (count + 1) * sizeof(const char *)); const CBMType **types = @@ -3108,14 +3326,22 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char * name means the same type (its identity, or the package's own type); * - the embedded types when every definition embeds the same types. * Build variants of one struct keep what they share; `foo` and `foo_test` - * declaring different structs of one name keep only what agrees. */ + * declaring different structs of one name keep only what agrees. A name any + * definition declares as a field (named or embedded) is still a field of the + * QN at its depth, of unknown type where they do not agree, so no deeper + * member of that name is selected (go_type_qn_shadow). */ typedef struct { const CBMLSPDef *first; int count; /* definitions of the QN */ const char *first_embeds; /* the first definition's embedded QNs, '|'-joined */ bool embeds_differ; bool fields_done; - const char *fields; /* count > 1: the fields every definition agrees on, or NULL */ + const char *fields; /* count > 1: the fields every definition agrees on, or NULL */ + const CBMLSPDef **all; /* count > 1: every definition of the QN */ + int all_cap; + bool shadow_done; + const char **shadow_names; /* every field name some definition declares */ + int shadow_count; } go_type_qn_t; /* What a field type text means in one definition: the part the parser looks @@ -3132,10 +3358,24 @@ static const char *go_join_embeds(CBMArena *a, const CBMLSPDef *d) { const char *mod = d->def_module_qn ? d->def_module_qn : ""; const char **qns = go_embedded_qns(a, d->embedded_types, mod, cbm_type_scope_index(a, d->type_scope)); - const char *out = ""; + size_t total = 1; for (int i = 0; qns && qns[i]; i++) { - out = cbm_arena_sprintf(a, "%s%s%s", out, i ? "|" : "", qns[i]); + total += strlen(qns[i]) + 1; } + char *out = (char *)cbm_arena_alloc(a, total); + if (!out) { + return ""; + } + size_t at = 0; + for (int i = 0; qns && qns[i]; i++) { + if (i) { + out[at++] = '|'; + } + size_t n = strlen(qns[i]); + memcpy(out + at, qns[i], n); + at += n; + } + out[at] = '\0'; return out; } @@ -3161,9 +3401,11 @@ static const char *go_agreed_fields(CBMArena *a, const char *agreed, const CBMLS } p = bar ? bar + 1 : NULL; } - const char *out = NULL; + /* The kept fields are a subset of `agreed`: one buffer of its size. */ + char *out = (char *)cbm_arena_alloc(a, strlen(agreed) + 1); + size_t at = 0; char *keep = cbm_arena_strdup(a, agreed); - for (char *p = keep; mine && p && *p;) { + for (char *p = keep; mine && out && p && *p;) { char *bar = strchr(p, '|'); if (bar) { *bar = '\0'; @@ -3175,11 +3417,20 @@ static const char *go_agreed_fields(CBMArena *a, const char *agreed, const CBMLS if (theirs && strcmp(theirs, colon + 1) == 0 && go_same_text(go_field_type_identity(agreed_ix, colon + 1), go_field_type_identity(d_ix, theirs))) { - out = out ? cbm_arena_sprintf(a, "%s|%s", out, p) : cbm_arena_strdup(a, p); + size_t n = strlen(p); + if (at) { + out[at++] = '|'; + } + memcpy(out + at, p, n); + at += n; } p = bar ? bar + 1 : NULL; } cbm_ht_free(mine); + if (!out || at == 0) { + return NULL; + } + out[at] = '\0'; return out; } @@ -3214,11 +3465,106 @@ static CBMHashTable *go_type_qn_table(CBMArena *a, const CBMLSPDef *defs, int de e->embeds_differ = e->embeds_differ || !go_same_text(e->first_embeds, go_join_embeds(a, d)); e->fields = go_agreed_fields(a, e->fields, e->first, d); + if (e->count > e->all_cap) { + int cap = e->all_cap ? e->all_cap * 2 : 4; + const CBMLSPDef **grown = + (const CBMLSPDef **)cbm_arena_alloc(a, (size_t)cap * sizeof(*grown)); + if (!grown) { + cbm_ht_free(table); + return NULL; + } + if (e->all_cap) { + memcpy(grown, e->all, (size_t)(e->count - 1) * sizeof(*grown)); + } else { + grown[0] = e->first; + } + e->all = grown; + e->all_cap = cap; + } + e->all[e->count - 1] = d; } } return table; } +/* The field names some definition of a QN of several declares (named fields + * and embedded types), each once; computed on the first call. */ +static int go_pipe_pieces(const char *s) { + int n = s && *s ? 1 : 0; + for (; s && *s; s++) { + n += *s == '|'; + } + return n; +} + +static void go_shadow_note(go_type_qn_t *e, CBMHashTable *seen, const char *name) { + if (name && !cbm_ht_get(seen, name)) { + cbm_ht_set(seen, name, (void *)name); + e->shadow_names[e->shadow_count++] = name; + } +} + +static void go_type_qn_shadow(CBMArena *a, go_type_qn_t *e) { + if (e->shadow_done) { + return; + } + e->shadow_done = true; + int bound = 0; + for (int i = 0; i < e->count; i++) { + bound += go_pipe_pieces(e->all[i]->field_defs) + go_pipe_pieces(e->all[i]->embedded_types); + } + CBMHashTable *seen = bound ? cbm_ht_create((uint32_t)(bound + 8)) : NULL; + e->shadow_names = + seen ? (const char **)cbm_arena_alloc(a, (size_t)(bound + 1) * sizeof(char *)) : NULL; + if (!e->shadow_names) { + cbm_ht_free(seen); + return; + } + /* In definition order, then declaration order: a fixed order. */ + for (int i = 0; i < e->count; i++) { + const CBMLSPDef *d = e->all[i]; + for (const char *p = d->field_defs; p && *p;) { + const char *colon = strchr(p, ':'); + const char *bar = strchr(p, '|'); + if (colon && (!bar || colon < bar) && colon > p) { + go_shadow_note(e, seen, cbm_arena_strndup(a, p, (size_t)(colon - p))); + } + p = bar ? bar + 1 : NULL; + } + size_t len = 0; + for (const char *next = d->embedded_types, *s; + (s = go_embedded_spelling(&next, &len)) != NULL;) { + go_shadow_note(e, seen, go_embedded_field_name(a, s, len)); + } + } + e->shadow_names[e->shadow_count] = NULL; + cbm_ht_free(seen); +} + +/* A type QN of several definitions: every field name some definition + * declares that rt does not register with a type becomes a field of unknown + * type (it shadows deeper members and answers nothing). */ +static void go_add_shadow_fields(CBMArena *a, CBMRegisteredType *rt, const CBMHashTable *table, + const CBMLSPDef *d) { + go_type_qn_t *e = table ? (go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + if (!e || e->count < 2 || rt->is_interface) { + return; + } + go_type_qn_shadow(a, e); + if (e->shadow_count == 0) { + return; + } + const CBMType **types = + (const CBMType **)cbm_arena_alloc(a, (size_t)e->shadow_count * sizeof(CBMType *)); + if (!types) { + return; + } + for (int i = 0; i < e->shadow_count; i++) { + types[i] = cbm_type_unknown(); + } + go_append_fields(a, rt, e->shadow_names, types, e->shadow_count); +} + /* The fields to register for `d`: its own when it is its QN's only definition, * else those every definition of the QN agrees on (NULL: none). Without a * table (allocation failure) every def keeps its own, as before the table. */ @@ -3784,6 +4130,11 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, &rt.field_types); } + /* Embedded types are fields too (Go's selector rule), and a QN of + * several definitions shadows every field name one declares. */ + go_add_embedded_fields(arena, &rt, d->embedded_types, def_mod, scope_ix, + go_type_qn_embeds(type_qns, d)); + go_add_shadow_fields(arena, &rt, type_qns, d); cbm_registry_add_type(®, rt); } @@ -3824,21 +4175,10 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, cbm_ht_free(type_qns); /* NULL-safe */ cbm_ht_free(value_qns); - // 3. Phase 1b: Scan AST for struct definitions to populate embedded_types + // 3. Phase 1b: the walked file's type aliases. Its structs' fields and + // embedded types come from their definitions, as on the shared registry: + // every field and every embedded type, the same answer on every route. { - /* One context parses every struct's field types, so its import rows are - * chained once (resolve_import), not once per struct. */ - GoLSPContext tmp_ctx; - memset(&tmp_ctx, 0, sizeof(tmp_ctx)); - tmp_ctx.arena = arena; - tmp_ctx.source = source; - tmp_ctx.source_len = source_len; - tmp_ctx.registry = ® - tmp_ctx.package_qn = module_qn; - tmp_ctx.import_local_names = import_names; - tmp_ctx.import_package_qns = import_qns; - tmp_ctx.import_count = import_count; - // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). uint32_t rkn = 0; TSNode *rkids = cbm_lsp_collect_children(arena, root, &rkn); @@ -3886,112 +4226,6 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, } continue; } - - if (strcmp(spec_kind2, "type_spec") != 0) - continue; - - TSNode name_node = ts_node_child_by_field_name(spec, "name", 4); - TSNode type_node = ts_node_child_by_field_name(spec, "type", 4); - if (ts_node_is_null(name_node) || ts_node_is_null(type_node)) - continue; - if (strcmp(ts_node_type(type_node), "struct_type") != 0) - continue; - - char *type_name = cbm_node_text(arena, name_node, source); - if (!type_name || !type_name[0]) - continue; - const char *type_qn = cbm_arena_sprintf(arena, "%s.%s", module_qn, type_name); - - TSNode field_list = ts_node_child_by_field_name(type_node, "body", 4); - if (ts_node_is_null(field_list)) { - if (ts_node_named_child_count(type_node) > 0) - field_list = ts_node_named_child(type_node, 0); - } - if (ts_node_is_null(field_list)) - continue; - - const char *embeds[16]; - int embed_count = 0; - const char *fld_names[64]; - const CBMType *fld_types[64]; - int fld_count = 0; - - uint32_t fl_nc = ts_node_child_count(field_list); - for (uint32_t k = 0; k < fl_nc; k++) { - TSNode field = ts_node_child(field_list, k); - if (ts_node_is_null(field) || !ts_node_is_named(field)) - continue; - if (strcmp(ts_node_type(field), "field_declaration") != 0) - continue; - TSNode fname = ts_node_child_by_field_name(field, "name", 4); - TSNode ftype = ts_node_child_by_field_name(field, "type", 4); - if (ts_node_is_null(fname) && !ts_node_is_null(ftype)) { - if (embed_count < 15) { - /* The embedded-member hook's QN: a bare name is - * this package's, `pkg.T` the import's (the same - * answer the shared registry gets from the - * declaring file's scope). */ - char *embed_text = cbm_node_text(arena, ftype, source); - char *et = embed_text; - while (et && *et == '*') - et++; - char *bracket = et ? strchr(et, '[') : NULL; - if (bracket) - *bracket = '\0'; - char *dot = et ? strchr(et, '.') : NULL; - const char *eqn = NULL; - if (et && et[0] && !dot) { - eqn = cbm_arena_sprintf(arena, "%s.%s", module_qn, et); - } else if (et && dot && dot > et) { - *dot = '\0'; - const char *pkg_qn = resolve_import(&tmp_ctx, et); - eqn = pkg_qn ? cbm_arena_sprintf(arena, "%s.%s", pkg_qn, dot + 1) - : NULL; - } - if (eqn) { - embeds[embed_count++] = eqn; - } - } - } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype) && - fld_count < 63) { - char *fn = cbm_node_text(arena, fname, source); - if (fn && fn[0]) { - fld_names[fld_count] = fn; - fld_types[fld_count] = go_parse_type_node(&tmp_ctx, ftype); - fld_count++; - } - } - } - - for (int ti = 0; ti < reg.type_count; ti++) { - if (!reg.types[ti].qualified_name || - strcmp(reg.types[ti].qualified_name, type_qn) != 0) - continue; - - if (embed_count > 0) { - const char **arr = (const char **)cbm_arena_alloc( - arena, (embed_count + 1) * sizeof(const char *)); - for (int ei = 0; ei < embed_count; ei++) - arr[ei] = embeds[ei]; - arr[embed_count] = NULL; - reg.types[ti].embedded_types = arr; - } - if (fld_count > 0) { - const char **names = (const char **)cbm_arena_alloc( - arena, (fld_count + 1) * sizeof(const char *)); - const CBMType **types = (const CBMType **)cbm_arena_alloc( - arena, (fld_count + 1) * sizeof(const CBMType *)); - for (int fi = 0; fi < fld_count; fi++) { - names[fi] = fld_names[fi]; - types[fi] = fld_types[fi]; - } - names[fld_count] = NULL; - types[fld_count] = NULL; - reg.types[ti].field_names = names; - reg.types[ti].field_types = types; - } - break; - } } } } @@ -4116,6 +4350,11 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, &rt.field_types); } + /* Embedded types are fields too (Go's selector rule), and a QN of + * several definitions shadows every field name one declares. */ + go_add_embedded_fields(arena, &rt, d->embedded_types, def_mod, scope_ix, + go_type_qn_embeds(type_qns, d)); + go_add_shadow_fields(arena, &rt, type_qns, d); cbm_registry_add_type(reg, rt); GO_NOTE_NEW_TYPES(); uintptr_t at = first_type ? (uintptr_t)cbm_ht_get(first_type, rt.qualified_name) : 0; diff --git a/internal/cbm/lsp/go_lsp.h b/internal/cbm/lsp/go_lsp.h index fc612cfef..751e13d95 100644 --- a/internal/cbm/lsp/go_lsp.h +++ b/internal/cbm/lsp/go_lsp.h @@ -23,6 +23,11 @@ typedef struct { // Current function context const char* enclosing_func_qn; + // Type names the function being walked declares itself -- its type + // parameters (and its receiver's) and the local types declared so far: + // they never name the package's type of that name. NULL when none. + struct CBMHashTable* shadow_types; + bool in_function; const char* package_qn; // module QN for this file const char* rel_path; // repo-relative file path: init() QN suffix (#1910); NULL = flat diff --git a/tests/test_go_lsp.c b/tests/test_go_lsp.c index 1f0d58087..49a948384 100644 --- a/tests/test_go_lsp.c +++ b/tests/test_go_lsp.c @@ -1168,11 +1168,15 @@ TEST(golsp_crossfile_interface_field_chain) { "type Context struct {\n\techo *echo.Echo\n}\n\n" "func (c *Context) process() {\n\tc.echo.Binder.Bind(\"hello\")\n}\n"; + /* The walked file's struct carries its fields as the pipeline folds them + * (pxc_fold_struct_fields): every route reads a struct's fields from its + * definition. */ CBMLSPDef defs[] = { {.qualified_name = "test.main.Context", .short_name = "Context", .label = "Type", - .def_module_qn = "test.main"}, + .def_module_qn = "test.main", + .field_defs = "echo:*echo.Echo"}, {.qualified_name = "test.main.Context.process", .short_name = "process", .label = "Method", diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 820f625f2..66015f603 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -1418,6 +1418,159 @@ TEST(type_scope_go_promotion_takes_the_shallowest_depth) { return ts_twins("godepth", go_depth_files, CBM_LANG_GO, go_depth_check); } +/* Round 3, N1: the unqualified type name of an embedded field is a field of + * its depth (Go spec). srv.Server{ Config; base.Handler } with Handler's own + * field `Config *base.Config`: s.Config is srv.Config at depth 0, in another + * package and in one of srv's files (main's right edge there stays); an + * embedded func type `Logger` shadows base.W's method Logger one level down; + * the same in one file; an embedded type the project does not have + * (sync.Mutex) still shadows a deeper `Mutex`; and build variants of one + * struct, one of which declares a field `Item` the other does not, select no + * deeper `Item`. `go run` agrees on each. */ +static const ts_file_t go_embfield_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Config struct{ n int }\n\n" + "func (c *Config) Validate() string { return \"base\" }\n\n" + "type Handler struct {\n\tConfig *Config\n}\n\n" + "type W struct{ n int }\n\nfunc (w W) Logger(s string) string { return s }\n\n" + "type M struct{ n int }\n\nfunc (m *M) Lock() {}\n\n" + "type Locker struct {\n\tMutex *M\n}\n\n" + "type Item struct{ n int }\n\nfunc (i *Item) Do() string { return \"item\" }\n\n" + "type Item2 struct{ n int }\n\nfunc (i *Item2) Do() string { return \"item2\" }\n\n" + "type Deep struct {\n\tItem *Item2\n}\n"}, + {"srv/config.go", "package srv\n\ntype Config struct{ port int }\n\n" + "func (c Config) Validate() string { return \"srv\" }\n"}, + {"srv/server.go", "package srv\n\nimport (\n\t\"sync\"\n\n\t\"example.com/demo/base\"\n)\n\n" + "type Server struct {\n\tConfig\n\tbase.Handler\n}\n\n" + "type Logger func(string) string\n\n" + "type Outer struct {\n\tLogger\n\tbase.W\n}\n\n" + "type U struct {\n\tsync.Mutex\n\tbase.Locker\n}\n"}, + {"srv/local.go", "package srv\n\nfunc Local(s *Server) string { return s.Config.Validate() }\n"}, + {"srv/v_linux.go", "//go:build linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" + "type V struct {\n\tItem *base.Item\n\tbase.Deep\n}\n"}, + {"srv/v_other.go", "//go:build !linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" + "type V struct {\n\tbase.Deep\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/srv\"\n\n" + "func Run(s *srv.Server) string { return s.Config.Validate() }\n\n" + "func Log(o srv.Outer) string { return o.Logger(\"x\") }\n\n" + "func Lock(u *srv.U) { u.Mutex.Lock() }\n\n" + "func Use(v *srv.V) string { return v.Item.Do() }\n"}, + {"one/one.go", "package one\n\ntype Cfg struct{ n int }\n\nfunc (c Cfg) Check() string { return \"cfg\" }\n\n" + "type Other struct{ n int }\n\nfunc (o Other) Check() string { return \"other\" }\n\n" + "type H struct {\n\tCfg Other\n}\n\n" + "type S struct {\n\tCfg\n\tH\n}\n\n" + "func Here(s *S) string { return s.Cfg.Check() }\n"}, + {NULL, NULL}}; + +static int go_embfield_check(cbm_store_t *s, const char *project, const char *label) { + int run_right = ts_calls_to(s, project, "Run", "srv.Config.Validate", NULL); + int local_right = ts_calls_to(s, project, "Local", "srv.Config.Validate", NULL); + int wrong = ts_calls_to(s, project, "Run", "base.Config.Validate", NULL) + + ts_calls_to(s, project, "Local", "base.Config.Validate", NULL) + + ts_calls_to(s, project, "Log", "base.W.Logger", NULL) + + ts_calls_to(s, project, "Lock", "base.M.Lock", NULL) + + ts_calls_to(s, project, "Use", "base.Item2.Do", NULL) + + ts_calls_to(s, project, "Here", "one.Other.Check", NULL); + int here_right = ts_calls_to(s, project, "Here", "one.Cfg.Check", NULL); + printf(" go embedded field names (%s): Run=%d Local=%d Here=%d, wrong=%d\n", label, run_right, + local_right, here_right, wrong); + return !(run_right == 1 && local_right == 1 && here_right <= 1 && wrong == 0); +} + +TEST(type_scope_go_embedded_field_names_are_fields) { + return ts_twins("goembfield", go_embfield_files, CBM_LANG_GO, go_embfield_check); +} + +/* Round 3, N3: a type the function declares itself -- a local `type T` and a + * type parameter, of a function, of a generic receiver, of a generic type -- + * is never the package's T, whose embedded p1.E would promote Hello: not in + * the walker (Local, Generic, Direct: main's own false `Direct -> m.T.Own` + * goes too) and not through another package's signatures (Call through a + * generic result, Boxed through a generic method's result). Pkg uses the + * package's T and keeps its promoted edge. `go run` agrees on each. */ +static const ts_file_t go_shadowtype_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p2\" }\n\n" + "func (E) Own() string { return \"p2own\" }\n"}, + {"m/t.go", "package m\n\nimport \"example.com/demo/p1\"\n\ntype T struct{ p1.E }\n\n" + "func (T) Own() string { return \"m\" }\n"}, + {"m/use.go", "package m\n\nimport \"example.com/demo/p2\"\n\n" + "func Local() string {\n\ttype T struct{ p2.E }\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func Generic[T interface{ Hello() string }](x T) string { return x.Hello() }\n\n" + "func Direct[T interface{ Own() string }](x T) string { return x.Own() }\n\n" + "func Pkg() string {\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func First[T any](xs []T) T { return xs[0] }\n\n" + "type Box[T any] struct{ v T }\n\n" + "func (b Box[T]) Get() T { return b.v }\n"}, + {"app/app.go", "package app\n\nimport (\n\t\"example.com/demo/m\"\n\t\"example.com/demo/p2\"\n)\n\n" + "func Call() string { return m.First([]p2.E{{}}).Hello() }\n\n" + "func Boxed() string { return m.Box[p2.E]{}.Get().Hello() }\n"}, + {NULL, NULL}}; + +static int go_shadowtype_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "Local", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Generic", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Direct", "m.T.Own", NULL) + + ts_calls_to(s, project, "Call", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Boxed", "p1.E.Hello", NULL); + int pkg = ts_calls_to(s, project, "Pkg", "p1.E.Hello", NULL); + printf(" go function-declared types (%s): wrong=%d, package T Pkg=%d\n", label, wrong, pkg); + return !(wrong == 0 && pkg == 1); +} + +TEST(type_scope_go_function_declared_types_are_not_the_package_types) { + return ts_twins("goshadow", go_shadowtype_files, CBM_LANG_GO, go_shadowtype_check); +} + +/* Round 3, the 63-field limit beside N4: a struct of 66 named fields whose + * last two are typed. Every route registers every field now. */ +static const ts_file_t go_wide_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"kind/kind.go", "package kind\n\ntype K struct{}\n\nfunc (K) Name() string { return \"k\" }\n\n" + "type L struct{}\n\nfunc (L) Name() string { return \"l\" }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/wide\"\n\n" + "func Run(w *wide.Wide) string { return w.Last.Name() }\n"}, + {NULL, NULL}}; + +static int go_wide_check(cbm_store_t *s, const char *project, const char *label) { + int run = ts_calls_to(s, project, "Run", "kind.L.Name", NULL); + int use = ts_calls_to(s, project, "Use", "kind.K.Name", NULL) + + ts_calls_to(s, project, "Use", "kind.L.Name", NULL); + printf(" go wide struct (%s): Run=%d Use=%d\n", label, run, use); + return !(run == 1 && use == 2); +} + +static char g_go_wide_source[4096]; +static char g_go_wide_edited[4096]; + +static const char *go_wide_source(char *buf, size_t cap, bool edited) { + size_t at = (size_t)snprintf(buf, cap, + "package wide\n\nimport \"example.com/demo/kind\"\n\ntype Wide struct {\n"); + for (int i = 0; i < 64; i++) { + at += (size_t)snprintf(buf + at, cap - at, "\tF%d int\n", i); + } + snprintf(buf + at, cap - at, + "\tLate kind.K\n\tLast kind.L\n}\n\nfunc Use(w *Wide) string {\n\t%s\n}\n", + edited ? "s := w.Late.Name() + w.Last.Name()\n\treturn s" + : "return w.Late.Name() + w.Last.Name()"); + return buf; +} + +static void go_wide_fixture(ts_file_t *files) { + int n = (int)(sizeof(go_wide_files) / sizeof(go_wide_files[0])) - 1; + memcpy(files, go_wide_files, (size_t)n * sizeof(ts_file_t)); + files[n] = (ts_file_t){"wide/wide.go", + go_wide_source(g_go_wide_source, sizeof(g_go_wide_source), false)}; + files[n + 1] = (ts_file_t){NULL, NULL}; +} + +TEST(type_scope_go_struct_fields_have_no_limit) { + ts_file_t files[8]; + go_wide_fixture(files); + return ts_twins("gowide", files, CBM_LANG_GO, go_wide_check); +} + /* ── Full index versus every incremental route ───────────────────── */ static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, @@ -1729,6 +1882,68 @@ TEST(type_scope_incremental_named_type_embed_change_matches_full) { PASS(); } +/* Round 3, N4 (the review's go-emb16): a body edit of the file declaring a + * struct of 17 embedded types is a one-file repair, and the repaired graph is + * the full index's: the per-file route takes the struct's embedded types from + * its definition, as the full index does, all of them (it kept 15). */ +static char g_go_emb_parts[4096]; +static char g_go_emb_big[2048]; +static char g_go_emb_big_edited[2048]; + +static void go_emb_sources(void) { + size_t at = (size_t)snprintf(g_go_emb_parts, sizeof(g_go_emb_parts), "package big\n\n"); + size_t fa = 0; + char fields[512]; + for (int i = 0; i < 17; i++) { + at += (size_t)snprintf(g_go_emb_parts + at, sizeof(g_go_emb_parts) - at, + "type E%d struct{}\n\nfunc (E%d) M%d() string { return \"%d\" }\n\n", i, + i, i, i); + fa += (size_t)snprintf(fields + fa, sizeof(fields) - fa, "\tE%d\n", i); + } + snprintf(g_go_emb_big, sizeof(g_go_emb_big), + "package big\n\ntype Big struct {\n%s}\n\n" + "func Use(b *Big) string {\n\treturn b.M16() + b.M14()\n}\n", + fields); + snprintf(g_go_emb_big_edited, sizeof(g_go_emb_big_edited), + "package big\n\ntype Big struct {\n%s}\n\n" + "func Use(b *Big) string {\n\ts := b.M16() + b.M14()\n\treturn s\n}\n", + fields); +} + +TEST(type_scope_incremental_many_embedded_types_match_full) { + go_emb_sources(); + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"big/parts.go", g_go_emb_parts}, + {"big/big.go", g_go_emb_big}, + {"big/use2.go", "package big\n\nfunc Use2(b *Big) string { return b.M16() }\n"}, + {"decoy/d.go", "package decoy\n\ntype D struct{}\n\nfunc (D) M16() string { return \"d\" }\n\n" + "func (D) M14() string { return \"d\" }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/big\"\n\n" + "func Run(b *big.Big) string { return b.M16() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = {{"big/big.go", g_go_emb_big_edited}, {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 40, edit, "go 17 embedded types"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* The same for a struct of 66 fields (the 63-field limit beside N4). */ +TEST(type_scope_incremental_many_fields_match_full) { + ts_file_t files[8]; + go_wide_fixture(files); + const ts_file_t edit[] = { + {"wide/wide.go", go_wide_source(g_go_wide_edited, sizeof(g_go_wide_edited), true)}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 40, edit, "go 66 fields"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + /* The gate is narrow: a signature change of another definition in the * declaring file stays a repair. */ TEST(type_scope_incremental_other_def_edit_stays_a_repair) { @@ -1815,6 +2030,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_bare_names_and_own_module); RUN_TEST(type_scope_python_own_module); RUN_TEST(type_scope_python_enclosing_scopes); + RUN_TEST(type_scope_python_class_body_bindings); RUN_TEST(type_scope_python_type_parameters); RUN_TEST(type_scope_python_unlisted_bindings_get_none); RUN_TEST(type_scope_step_work_grows_linearly); @@ -1825,6 +2041,8 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_type_parameter_is_no_import); RUN_TEST(type_scope_python_return_types); RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); + RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); + RUN_TEST(type_scope_python_class_and_module_of_one_qn); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); @@ -1837,16 +2055,18 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_build_variant_values_stay_typed); RUN_TEST(type_scope_go_embedded_members_promote); RUN_TEST(type_scope_go_promotion_takes_the_shallowest_depth); + RUN_TEST(type_scope_go_embedded_field_names_are_fields); + RUN_TEST(type_scope_go_function_declared_types_are_not_the_package_types); + RUN_TEST(type_scope_go_struct_fields_have_no_limit); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); RUN_TEST(type_scope_incremental_caller_edit_per_file_go_values); RUN_TEST(type_scope_incremental_body_edit_stays_one_file); RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); RUN_TEST(type_scope_incremental_named_type_embed_change_matches_full); + RUN_TEST(type_scope_incremental_many_embedded_types_match_full); + RUN_TEST(type_scope_incremental_many_fields_match_full); RUN_TEST(type_scope_incremental_type_shape_changes_match_full); RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); RUN_TEST(type_scope_incremental_python_body_edits); RUN_TEST(type_scope_incremental_python_declaring_change_matches_full); } - RUN_TEST(type_scope_python_class_body_bindings); - RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); - RUN_TEST(type_scope_python_class_and_module_of_one_qn); From 8d801b64aec2f2f5093939ca3b6b7be2d6908f51 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 06:59:14 +0100 Subject: [PATCH 12/25] test(lsp): a generic type's field and a class-body edit on the repair route The type-parameter test also reads an exported field of a generic type from another package (m.Box[p2.E]{}.V.Hello()), and an incremental test edits a class body so that it binds the name a method annotation uses (same lines): the class's bindings are part of its stored row, so the run is not a one-file repair that keeps a stale caller edge. Signed-off-by: Martin Vogel --- tests/test_type_scope.c | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 66015f603..21e5f83ff 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -1501,11 +1501,12 @@ static const ts_file_t go_shadowtype_files[] = { "func Direct[T interface{ Own() string }](x T) string { return x.Own() }\n\n" "func Pkg() string {\n\tvar t T\n\treturn t.Hello()\n}\n\n" "func First[T any](xs []T) T { return xs[0] }\n\n" - "type Box[T any] struct{ v T }\n\n" - "func (b Box[T]) Get() T { return b.v }\n"}, + "type Box[T any] struct{ V T }\n\n" + "func (b Box[T]) Get() T { return b.V }\n"}, {"app/app.go", "package app\n\nimport (\n\t\"example.com/demo/m\"\n\t\"example.com/demo/p2\"\n)\n\n" "func Call() string { return m.First([]p2.E{{}}).Hello() }\n\n" - "func Boxed() string { return m.Box[p2.E]{}.Get().Hello() }\n"}, + "func Boxed() string { return m.Box[p2.E]{}.Get().Hello() }\n\n" + "func Field(b m.Box[p2.E]) string { return b.V.Hello() }\n"}, {NULL, NULL}}; static int go_shadowtype_check(cbm_store_t *s, const char *project, const char *label) { @@ -1513,7 +1514,8 @@ static int go_shadowtype_check(cbm_store_t *s, const char *project, const char * ts_calls_to(s, project, "Generic", "p1.E.Hello", NULL) + ts_calls_to(s, project, "Direct", "m.T.Own", NULL) + ts_calls_to(s, project, "Call", "p1.E.Hello", NULL) + - ts_calls_to(s, project, "Boxed", "p1.E.Hello", NULL); + ts_calls_to(s, project, "Boxed", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Field", "p1.E.Hello", NULL); int pkg = ts_calls_to(s, project, "Pkg", "p1.E.Hello", NULL); printf(" go function-declared types (%s): wrong=%d, package T Pkg=%d\n", label, wrong, pkg); return !(wrong == 0 && pkg == 1); @@ -2022,6 +2024,33 @@ TEST(type_scope_incremental_python_declaring_change_matches_full) { PASS(); } +/* Round 3, N2 on the incremental routes: a class-body edit that binds the + * name a method annotation uses (`marker = OtherConfig` becomes `Config = + * OtherConfig`: same lines, same bytes otherwise) changes the class's + * identities. The class's bindings are part of its stored row, so the run is + * not a one-file repair that keeps the caller's stale `run -> + * pkg.mod.Config.load`. */ +TEST(type_scope_incremental_python_class_body_binding_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/other.py", "class OtherConfig:\n def load(self):\n return 'other'\n"}, + {"pkg/mod.py", "from pkg.other import OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class Model:\n marker = OtherConfig\n\n" + " def cfg(self) -> Config:\n return Config()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\ndef run():\n return Model().cfg().load()\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"pkg/mod.py", "from pkg.other import OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class Model:\n Config = OtherConfig\n\n" + " def cfg(self) -> Config:\n return Config()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_PYTHON, 0, edit, "py class-body binding"); + ASSERT_TRUE(r.same_graph); + PASS(); +} + SUITE(type_scope) { RUN_TEST(type_scope_import_binding_is_the_identity); RUN_TEST(type_scope_dotted_spelling_through_its_head); @@ -2065,6 +2094,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_incremental_named_type_embed_change_matches_full); RUN_TEST(type_scope_incremental_many_embedded_types_match_full); RUN_TEST(type_scope_incremental_many_fields_match_full); + RUN_TEST(type_scope_incremental_python_class_body_binding_matches_full); RUN_TEST(type_scope_incremental_type_shape_changes_match_full); RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); RUN_TEST(type_scope_incremental_python_body_edits); From 8b8e5496e3daf2bb61665a0bdb4aaf8420af2e65 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 07:08:20 +0100 Subject: [PATCH 13/25] perf(lsp): a smaller per-definition identity index A definition's identity index (cbm_type_scope_index) held a 24-byte slot per entry in a table of at least four, plus the string copy: about 140 bytes for one identity, 300 for three, retained in the registry arena for the resolve phase. Entries are 12 bytes of offsets into the copy now, and up to four identities (most definitions) are a plain list a lookup scans, a bounded cost; more stay a hash table. The answers are the same. Also formats the round-3 lines clang-format reported. Signed-off-by: Martin Vogel --- internal/cbm/extract_defs.c | 3 +- internal/cbm/lsp/go_lsp.c | 3 +- internal/cbm/lsp/type_rep.c | 66 +++++++++++++++++++++++++---------- internal/cbm/lsp/type_rep.h | 6 ++-- src/pipeline/pass_lsp_cross.c | 6 ++-- src/pipeline/type_scope.c | 10 +++--- 6 files changed, 63 insertions(+), 31 deletions(-) diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 8ab1dbe50..69afa8a9b 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -7274,7 +7274,8 @@ static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char * if (strcmp(ts_node_type(node), "decorated_definition") == 0) { node = ts_node_child_by_field_name(node, TS_FIELD("definition")); } - TSNode body = ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body")); + TSNode body = + ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body")); tf_names_t b = {.a = a}; py_bind_block(&b, body, source, 0); return b.len ? b.buf : NULL; diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 4dab9b4ab..e8a5ebe41 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -3117,7 +3117,8 @@ static void go_append_fields(CBMArena *a, CBMRegisteredType *rt, const char *con while (rt->field_names && rt->field_names[had]) { had++; } - const char **out_names = (const char **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(char *)); + const char **out_names = + (const char **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(char *)); const CBMType **out_types = (const CBMType **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(CBMType *)); CBMHashTable *present = cbm_ht_create((uint32_t)(had + n + 8)); diff --git a/internal/cbm/lsp/type_rep.c b/internal/cbm/lsp/type_rep.c index 6e10980a1..a7694fb46 100644 --- a/internal/cbm/lsp/type_rep.c +++ b/internal/cbm/lsp/type_rep.c @@ -967,15 +967,24 @@ const CBMType *cbm_type_substitute(CBMArena *a, const CBMType *t, const char **t /* ── Declared-type identities of one definition ─────────────────── */ +/* One identity: offsets into the index's copy of the scope, where '=' and '|' + * are cut to NULs (12 bytes; len 0 = an empty slot). */ typedef struct { - const char *name; /* spelling, NUL-terminated copy */ - size_t len; - const char *qn; /* NUL-terminated copy */ + uint32_t name; + uint32_t len; + uint32_t qn; } cbm_type_scope_entry_t; +/* Up to TYPE_SCOPE_LIST_MAX identities (most definitions have one to three) + * are a plain list a lookup scans, a bounded cost; more are an open-addressing + * table of a power-of-two size. Same answers either way. */ +enum { TYPE_SCOPE_LIST_MAX = 4 }; + struct cbm_type_scope_index { - cbm_type_scope_entry_t *slots; /* open addressing, power-of-two size */ - uint32_t mask; + const char *text; /* the copy the entries point into */ + cbm_type_scope_entry_t *slots; /* the list (mask 0) or the table */ + uint32_t mask; /* table size - 1, or 0 for a list */ + uint32_t count; /* list entries */ }; #if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS @@ -1003,12 +1012,16 @@ const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scop } size_t n = strlen(scope); TYPE_SCOPE_INDEX_WORK(n); + if (n >= UINT32_MAX) { + return NULL; + } uint32_t entries = 1; for (size_t i = 0; i < n; i++) { entries += scope[i] == '|'; } - uint32_t size = 4; - while (size < entries * 2) { + bool list = entries <= TYPE_SCOPE_LIST_MAX; + uint32_t size = list ? entries : 4; + while (!list && size < entries * 2) { size *= 2; } char *copy = cbm_arena_strndup(a, scope, n); @@ -1019,8 +1032,7 @@ const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scop return NULL; } memset(slots, 0, (size_t)size * sizeof(*slots)); - ix->slots = slots; - ix->mask = size - 1; + *ix = (cbm_type_scope_index_t){.text = copy, .slots = slots, .mask = list ? 0 : size - 1}; for (char *p = copy; p && *p;) { char *bar = strchr(p, '|'); if (bar) { @@ -1029,15 +1041,21 @@ const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scop char *eq = strchr(p, '='); if (eq && eq > p && eq[1]) { *eq = '\0'; - size_t len = (size_t)(eq - p); - uint32_t at = type_scope_hash(p, len) & ix->mask; - while (slots[at].name && - !(slots[at].len == len && memcmp(slots[at].name, p, len) == 0)) { + uint32_t len = (uint32_t)(eq - p); + cbm_type_scope_entry_t e = { + .name = (uint32_t)(p - copy), .len = len, .qn = (uint32_t)(eq + 1 - copy)}; + uint32_t at = list ? 0 : type_scope_hash(p, len) & ix->mask; + uint32_t end = list ? ix->count : UINT32_MAX; + /* the first entry of a spelling stands */ + while (at < end && slots[at].len && + !(slots[at].len == len && memcmp(copy + slots[at].name, p, len) == 0)) { TYPE_SCOPE_INDEX_WORK(1); - at = (at + 1) & ix->mask; + at = list ? at + 1 : (at + 1) & ix->mask; } - if (!slots[at].name) { /* the first entry of a spelling stands */ - slots[at] = (cbm_type_scope_entry_t){.name = p, .len = len, .qn = eq + 1}; + if (list && at == ix->count) { + slots[ix->count++] = e; + } else if (!list && !slots[at].len) { + slots[at] = e; } } p = bar ? bar + 1 : NULL; @@ -1051,11 +1069,21 @@ const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *na return NULL; } TYPE_SCOPE_INDEX_WORK(name_len); + const cbm_type_scope_entry_t *slots = ix->slots; + if (ix->mask == 0) { + for (uint32_t i = 0; i < ix->count; i++) { + TYPE_SCOPE_INDEX_WORK(1); + if (slots[i].len == name_len && memcmp(ix->text + slots[i].name, name, name_len) == 0) { + return ix->text + slots[i].qn; + } + } + return NULL; + } uint32_t at = type_scope_hash(name, name_len) & ix->mask; - while (ix->slots[at].name) { + while (slots[at].len) { TYPE_SCOPE_INDEX_WORK(1); - if (ix->slots[at].len == name_len && memcmp(ix->slots[at].name, name, name_len) == 0) { - return ix->slots[at].qn; + if (slots[at].len == name_len && memcmp(ix->text + slots[at].name, name, name_len) == 0) { + return ix->text + slots[at].qn; } at = (at + 1) & ix->mask; } diff --git a/internal/cbm/lsp/type_rep.h b/internal/cbm/lsp/type_rep.h index db2b8b6d6..c5e2b2f31 100644 --- a/internal/cbm/lsp/type_rep.h +++ b/internal/cbm/lsp/type_rep.h @@ -238,8 +238,10 @@ const CBMType* cbm_type_substitute(CBMArena* a, const CBMType* t, // The identities of the type names one definition's declared types write // ("spelling=QN|spelling=QN", CBMLSPDef.type_scope, resolved once in the scope // of the file that wrote it by the pipeline's type-scope step), indexed once -// per definition so each lookup is a hash probe. NULL for a NULL or empty -// scope (or on allocation failure: the engine then qualifies as before). +// per definition: a short list (up to 4 identities, most definitions) or a +// hash table, 12 bytes an entry, so each lookup is bounded work. NULL for a +// NULL or empty scope (or on allocation failure: the engine then qualifies as +// before). typedef struct cbm_type_scope_index cbm_type_scope_index_t; const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope); diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index ba9cf75d0..680f01068 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -1161,9 +1161,9 @@ static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLS if (!dst) { continue; } - dst->field_defs = go_generic - ? pxc_go_mask_field_types(arena, dst->field_defs, f->type_params) - : pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings); + dst->field_defs = + go_generic ? pxc_go_mask_field_types(arena, dst->field_defs, f->type_params) + : pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings); } cbm_ht_free(by_qn); } diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index bf6ecd1bf..5e4305221 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -169,8 +169,8 @@ static void type_scope_index_class_bindings(cbm_type_scope_file_t *f, const CBMD const char *bar = strchr(p, '|'); size_t len = bar ? (size_t)(bar - p) : strlen(p); TYPE_SCOPE_WORK(len + 1); - char *key = len ? cbm_arena_sprintf(&f->keys, "%s.%.*s", d->qualified_name, (int)len, p) - : NULL; + char *key = + len ? cbm_arena_sprintf(&f->keys, "%s.%.*s", d->qualified_name, (int)len, p) : NULL; if (key && !cbm_ht_get(f->class_binds, key)) { cbm_ht_set(f->class_binds, key, key); } @@ -278,9 +278,9 @@ static const char *type_scope_target(const cbm_type_scope_file_t *f, const char } for (const char *const *l = f->lang->labels; *l; l++) { if (strcmp(*l, label) == 0) { - const cbm_gbuf_node_t *node = - f->lang->lexical_scopes && f->scope.graph ? cbm_gbuf_find_by_qn(f->scope.graph, qn) - : NULL; + const cbm_gbuf_node_t *node = f->lang->lexical_scopes && f->scope.graph + ? cbm_gbuf_find_by_qn(f->scope.graph, qn) + : NULL; return node && node->label && strcmp(node->label, "Module") == 0 ? NULL : qn; } } From 700c1ce9b25a4a9b4e84dc277833a74594777ae5 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 07:31:14 +0100 Subject: [PATCH 14/25] fix(lsp): an annotation alone binds no class attribute A class body's `x: T` without a value records an annotation and binds nothing, so a method annotation naming x still means the module's x; the class-body list no longer counts it (main's python_typed_field_external_import_stays_unresolved asserts that such a class gets no field_defs). The class-body test gains an annotation-only name whose method keeps its identity. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 7 ++++--- internal/cbm/extract_defs.c | 10 ++++++++-- tests/test_type_scope.c | 1 + 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 022c17e45..c67db3caf 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -355,9 +355,10 @@ typedef struct CBMDefTypeFacts { * and names them as fields (go_lsp.c, embedded-member hook). */ const char *go_embedded; /* Python class: the names its body binds other than by a nested def or - * class (assignments, annotated names, imports, for/with/except/match - * targets, walrus, global/nonlocal/del), '|'-joined. A method annotation - * naming one of them means the class attribute, not the module's name. */ + * class (assignments, annotated assignments with a value, imports, + * for/with/except/match targets, walrus, global/nonlocal/del; an + * annotation alone binds nothing), '|'-joined. A method annotation naming + * one of them means the class attribute, not the module's name. */ const char *class_bindings; } CBMDefTypeFacts; diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 69afa8a9b..d23974ea7 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -7190,16 +7190,22 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d uint32_t n = ts_node_named_child_count(s); for (uint32_t i = 0; i < n; i++) { TSNode e = ts_node_named_child(s, i); - /* `a = b = v`: each assignment's left side, down the chain */ + /* `a = b = v`: each assignment's left side, down the chain. An + * annotation alone (`x: T`) binds nothing (Python records it in + * __annotations__ only). */ for (int chain = 0; !ts_node_is_null(e) && chain < TF_BIND_DEPTH; chain++) { const char *ek = ts_node_type(e); if (strcmp(ek, "assignment") != 0 && strcmp(ek, "augmented_assignment") != 0) { py_bind_walrus(b, e, source, depth + 1); break; } + TSNode right = ts_node_child_by_field_name(e, TS_FIELD("right")); + if (ts_node_is_null(right)) { + break; + } py_bind_target(b, ts_node_child_by_field_name(e, TS_FIELD("left")), source, depth + 1); - e = ts_node_child_by_field_name(e, TS_FIELD("right")); + e = right; } } return; diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 21e5f83ff..1b3bbdfd9 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -840,6 +840,7 @@ static const ts_file_t py_classbind_files[] = { "class Keep:\n def load(self):\n return 'keep'\n\n\n" "class Model:\n" " Config = OtherConfig\n" + " Keep: type\n" /* an annotation alone binds nothing: Keep stays the module's */ " from pkg.other import Other as A\n" " B: type = Other\n" " for C in (1,):\n pass\n" From d1986a2e45bf3e9be0363e7262a11c7040ae46f1 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 18:06:51 +0100 Subject: [PATCH 15/25] fix(semantic): allocate slow-path import-map keys through the memory core The semantic pass builds a file's import map from its extracted imports or, when the file extracted none, from the IMPORTS edges another pass drew for it (the slow path). The slow path copied each key with cbm_strndup, which is libc strndup, while free_import_map releases every key with cbm_free. In the product build cbm_free is mi_free, and on macOS the mimalloc global override is off, so the key was a foreign block. An Ansible playbook is such a file: it extracts no imports, and the Ansible pass gives it IMPORTS edges for its roles and includes. On macOS the index worker crashed in the semantic pass (SIGSEGV in mi_free, or SIGBUS in mi_usable_size) on every repository of 50 files or fewer holding a role or an include, for example these two files: site.yml "- hosts: all\n tasks:\n - include_tasks: other.yml\n" other.yml "- debug:\n msg: hi\n" and on any repository indexed with one worker (kubespray). The same pass runs for the frozen test-impact index and for changed files on the incremental route. The slow-path key is now allocated with cbm_alloc under the semantic class, like the fast path's cbm_mem_strdup keys. The test suite never saw the crash: the test build backs the memory core with the C runtime allocator, where cbm_free is free. The new test indexes a playbook with a role and an include once, to warm what the process builds once and keeps (the pretrained token table), then takes the semantic class's live block and byte counts around a second, identical full index and an incremental re-index after an edit, and requires them to end where they started. The memory core counts only the blocks it hands out, so a key it takes back without having handed it out leaves the class below its start on every platform, independent of the allocator, of where the string landed and of what ran before the test. Signed-off-by: Martin Vogel --- src/pipeline/pass_semantic.c | 14 ++++-- tests/test_pipeline.c | 92 ++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c index 9ad910852..5397e5f6a 100644 --- a/src/pipeline/pass_semantic.c +++ b/src/pipeline/pass_semantic.c @@ -154,9 +154,17 @@ static int build_import_map(cbm_pipeline_ctx_t *ctx, const char *rel_path, start += strlen("\"local_name\":\""); const char *end = strchr(start, '"'); if (end && end > start) { - keys[count] = cbm_strndup(start, end - start); - vals[count] = target->qualified_name; - count++; + /* free_import_map releases every key through the memory core, + * so this key comes from it too, like the fast path's. */ + size_t len = (size_t)(end - start); + char *key = cbm_alloc(CBM_MEM_CLASS_SEMANTIC, len + SKIP_ONE); + if (key) { + memcpy(key, start, len); + key[len] = '\0'; + keys[count] = key; + vals[count] = target->qualified_name; + count++; + } } } } diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 124a1514d..f6adc208f 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -2416,6 +2416,97 @@ TEST(pipeline_incremental_keeps_ansible_includes_of_an_edited_file) { PASS(); } +/* IMPORTS edges the Ansible pass drew (via ansible); -1 on a query error. */ +static int ansible_import_edges(cbm_store_t *s, const char *project) { + sqlite3_stmt *st = NULL; + int n = -1; + if (sqlite3_prepare_v2(cbm_store_get_db(s), + "SELECT COUNT(*) FROM edges WHERE project=?1 AND type='IMPORTS' AND " + "json_extract(properties,'$.via')='ansible'", + -1, &st, NULL) == SQLITE_OK && + sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT) == SQLITE_OK && + sqlite3_step(st) == SQLITE_ROW) { + n = sqlite3_column_int(st, 0); + } + sqlite3_finalize(st); + return n; +} + +/* A playbook extracts no imports of its own: its role and include edges come + * from the Ansible pass, so the semantic pass builds its import map from those + * IMPORTS edges (the slow path). Those keys were libc copies released through + * the memory core, and on macOS, where the core's allocator is not the libc + * one, the index worker crashed in the semantic pass on every repository of 50 + * files or fewer holding a role or an include (any repository at one worker). + * Here the memory core's own count binds, whatever the allocator and wherever + * the string landed: a block the core takes back without having handed it out + * leaves its class below where it started. A first index of the same tree + * warms what the process builds once and keeps (the semantic pass's + * pretrained token table is one), so the readings are taken around a second, + * identical full index and an incremental re-index of the edited playbook + * (the incremental route runs the same pass for changed files): the verdict + * does not depend on what ran before in the process. */ +TEST(pipeline_semantic_import_map_keys_come_from_the_memory_core) { + if (setup_test_repo() != 0) { + FAIL("failed to create temp dir"); + } + write_temp_file(g_tmpdir, "site.yml", + "- hosts: localhost\n roles:\n - web\n tasks:\n" + " - include_tasks: tasks/setup.yml\n"); + write_temp_file(g_tmpdir, "roles/web/tasks/main.yml", + "- name: Say hi\n debug:\n msg: hi\n"); + write_temp_file(g_tmpdir, "tasks/setup.yml", "- name: Setup\n debug:\n msg: setup\n"); + char warm_path[512]; + snprintf(warm_path, sizeof(warm_path), "%s/semantic_keys_warm.db", g_tmpdir); + int warm_rc = -1; + cbm_pipeline_t *warm = cbm_pipeline_new(g_tmpdir, warm_path, CBM_MODE_FULL); + if (warm) { + warm_rc = cbm_pipeline_run(warm); + cbm_pipeline_free(warm); + } + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/semantic_keys.db", g_tmpdir); + + cbm_mem_class_flush_thread(); + size_t blocks_before = cbm_mem_class_live_blocks(CBM_MEM_CLASS_SEMANTIC); + size_t bytes_before = cbm_mem_class_live_bytes(CBM_MEM_CLASS_SEMANTIC); + int full_rc = -1; + int incr_rc = -1; + int imports = -1; + cbm_pipeline_t *p1 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL); + if (p1) { + full_rc = cbm_pipeline_run(p1); + cbm_store_t *s = cbm_store_open_path(db_path); + if (s) { + imports = ansible_import_edges(s, cbm_pipeline_project_name(p1)); + cbm_store_close(s); + } + cbm_pipeline_free(p1); + } + write_temp_file(g_tmpdir, "site.yml", + "- hosts: localhost\n roles:\n - web\n tasks:\n" + " - include_tasks: tasks/setup.yml\n - debug:\n msg: edited\n"); + cbm_pipeline_t *p2 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL); + if (p2) { + incr_rc = cbm_pipeline_run(p2); + cbm_pipeline_free(p2); + } + cbm_mem_class_flush_thread(); + size_t blocks_after = cbm_mem_class_live_blocks(CBM_MEM_CLASS_SEMANTIC); + size_t bytes_after = cbm_mem_class_live_bytes(CBM_MEM_CLASS_SEMANTIC); + teardown_test_repo(); + + ASSERT_EQ(warm_rc, 0); + ASSERT_EQ(full_rc, 0); + ASSERT_EQ(incr_rc, 0); + /* The playbook's role and include are the IMPORTS edges the slow path reads. */ + ASSERT_TRUE(imports >= 2); + /* Every SEMANTIC block taken back was handed out: the class is where it began. */ + ASSERT_TRUE(blocks_after == blocks_before); + ASSERT_TRUE(bytes_after == bytes_before); + PASS(); +} + /* The CALLS edges an Ansible notify draws (via notify); -1 on a query error. */ static int ansible_notify_calls(cbm_store_t *s, const char *project) { sqlite3_stmt *st = NULL; @@ -35535,6 +35626,7 @@ SUITE(pipeline) { RUN_TEST(pipeline_incremental_preserves_cross_file_calls); RUN_TEST(pipeline_incremental_drops_terraform_reads_of_a_moved_module); RUN_TEST(pipeline_incremental_keeps_ansible_includes_of_an_edited_file); + RUN_TEST(pipeline_semantic_import_map_keys_come_from_the_memory_core); RUN_TEST(pipeline_incremental_keeps_ansible_notifies_across_files); RUN_TEST(pipeline_incremental_keeps_ansible_deploys_across_files); RUN_TEST(pipeline_field_named_like_method_keeps_its_reads_and_writes); From 3c187ab99a521661a3cc95a0c1a35bbf66c1e161 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 02:56:02 +0100 Subject: [PATCH 16/25] test(cli): size the update tests' decompression limit to their fixture On macOS, cli_update_agent_configs_finish_before_guard_release and cli_update_names_the_failing_staging_step_and_os_error package the test runner itself as the fake release. The in-process updater, which exists only in test builds, refuses a tar.gz that inflates past 500 MiB (DECOMPRESS_MAX_BYTES), and an ASan runner carrying every vendored grammar sits right at that limit. The ObjectScript v1.11.0 parse tables add about 4.9 MB to the runner, which took both CI macOS runners over it: the archive was refused as "binary not found in archive" right after its checksum was verified, so the first test got rc 1 and the second never reached the staging write that fails with ENOSPC. Linux packages /bin/true and was not affected. The limit keeps its own test, cli_update_refuses_an_archive_over_the_decompression_limit. These two tests only need their archive accepted, so they set the limit to twice the fixture's inflated tar, which the doubling decompression buffer can never exceed, and restore it right after the update runs. x86_64 ASan runner under Rosetta, the macos-15-intel analog: main 1ec2f262 is 520,665,520 bytes and passes; 0bde6dea is 525,530,264 bytes and fails both tests with the CI messages; main plus only the vendored grammar directories of 086967955 is 525,502,864 bytes and fails the same way. With this change both tests pass at 525,530,264 bytes, and fail again with it reverted. Signed-off-by: Martin Vogel (cherry picked from commit 9d3f2af1ec701cbe737aa90f9864dfb7ee97e117) --- tests/test_cli.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/test_cli.c b/tests/test_cli.c index df0a289d2..a20468cc8 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -1018,6 +1018,24 @@ static unsigned char *create_test_targz(const char *filename, const unsigned cha return gz; } +/* Two update tests package a native executable as the release, and on macOS + * that executable is this test runner. An ASan runner that carries every + * vendored grammar sits right at the updater's 500 MiB decompression limit; + * the ObjectScript v1.11.0 parse tables took the CI runners past it, and the + * archive was refused ("binary not found in archive") before the step under + * test ran. The limit has its own test; these tests only need their archive + * accepted, so the limit is sized to the fixture. Twice the inflated tar can + * never refuse it: the decompression buffer only doubles from below the + * inflated size. cbm_cli_set_decompress_max_for_test(0) restores the limit. + * Both tests use the tar path, which is POSIX-only. */ +#ifndef _WIN32 +static void cli_update_fit_decompress_limit(long fixture_size) { + /* create_test_targz adds a header block, block padding and two end blocks. */ + enum { TARGZ_OVERHEAD = 4 * 512 }; + cbm_cli_set_decompress_max_for_test(((size_t)fixture_size + TARGZ_OVERHEAD) * 2U); +} +#endif + /* ═══════════════════════════════════════════════════════════════════ * Mandatory daemon activation safety * ═══════════════════════════════════════════════════════════════════ */ @@ -3618,6 +3636,7 @@ TEST(cli_update_agent_configs_finish_before_guard_release) { }; cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); + cli_update_fit_decompress_limit(native_size); char *argv[] = {"--force"}; int rc = cli_test_cmd_update(1, argv); cbm_cli_set_activation_ops_for_test(NULL); @@ -3643,6 +3662,7 @@ TEST(cli_update_agent_configs_finish_before_guard_release) { cbm_cli_set_activation_ops_for_test(&failure_ops); int config_failure_rc = cli_test_cmd_update(1, argv); cbm_cli_set_activation_ops_for_test(NULL); + cbm_cli_set_decompress_max_for_test(0); struct stat updated_status; bool replacement_kept = stat(bin_target, &updated_status) == 0 && updated_status.st_size != (off_t)(sizeof(old_binary) - 1U); @@ -3760,6 +3780,7 @@ TEST(cli_update_names_the_failing_staging_step_and_os_error) { }; cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); + cli_update_fit_decompress_limit(native_size); FILE *capture = tmpfile(); int saved_stdout = capture ? dup(STDOUT_FILENO) : -1; int saved_stderr = capture ? dup(STDERR_FILENO) : -1; @@ -3785,6 +3806,7 @@ TEST(cli_update_names_the_failing_staging_step_and_os_error) { close(saved_stderr); } cbm_cli_set_activation_ops_for_test(NULL); + cbm_cli_set_decompress_max_for_test(0); char output[16384] = {0}; if (capture) { rewind(capture); From 817a292a72a5b9b4d6b2b25a3591636d0051ef78 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:04 +0100 Subject: [PATCH 17/25] test(lsp): edges the type-scope tests expect, besides those they forbid The checks that an edge is absent gain partners that require one: the class-and-module test reaches a second class's method through the same shape; the embedded-names test calls through Ping, Lock2 and UseSame and requires Here exactly once, and Use's targets are labelled by build (Item on linux, Item2 elsewhere, as `go run` answers per platform); the function-declared-types test requires the calls into the generic functions themselves (First, Box.Get). The incremental harness can check the graph before and after the edit (ts_incremental_checked); the 17-embeds, 66-fields and class-body-edit tests now require the edges the edit keeps or drops, which 18d5f14e's routes did not draw (a per-file route that kept 15 embedded types, a 63-field limit on every route, a class body outside the stored row). Signed-off-by: Martin Vogel --- tests/test_type_scope.c | 139 ++++++++++++++++++++++++++++++++-------- 1 file changed, 114 insertions(+), 25 deletions(-) diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 1b3bbdfd9..6d8325c12 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -885,19 +885,26 @@ TEST(type_scope_python_class_body_bindings_shadow_the_module) { * their members `run` share pkg.a.Thing.run, so no member edge through an * identity Thing=pkg.a.Thing is that class's (the graph keeps the module's * nodes). Python: `from pkg.a import Thing` is the class while nothing imports - * the submodule, and the submodule once something does. */ + * the submodule, and the submodule once something does. The partner: a class + * of the same __init__ with no module of its QN (Other) is reached through + * the same kind of identity. */ static const ts_file_t py_classmod_files[] = { {"pkg/__init__.py", ""}, - {"pkg/a/__init__.py", "class Thing:\n def run(self):\n return 'class'\n"}, + {"pkg/a/__init__.py", "class Thing:\n def run(self):\n return 'class'\n\n\n" + "class Other:\n def run(self):\n return 'other'\n"}, {"pkg/a/Thing.py", "def run():\n return 'module'\n"}, - {"pkg/b.py", "from pkg.a import Thing\n\n\ndef make() -> Thing:\n return Thing()\n"}, - {"pkg/c.py", "from pkg.b import make\n\n\ndef go():\n return make().run()\n"}, + {"pkg/b.py", "from pkg.a import Other, Thing\n\n\ndef make() -> Thing:\n return Thing()\n\n\n" + "def make_other() -> Other:\n return Other()\n"}, + {"pkg/c.py", "from pkg.b import make, make_other\n\n\ndef go():\n return make().run()\n\n\n" + "def go_other():\n return make_other().run()\n"}, {NULL, NULL}}; static int py_classmod_check(cbm_store_t *s, const char *project, const char *label) { int member = ts_calls_to(s, project, "go", "pkg.a.Thing.run", NULL); - printf(" python class and module of one QN (%s): go -> Thing.run=%d\n", label, member); - return member != 0; + int other = ts_calls_to(s, project, "go_other", "pkg.a.Other.run", NULL); + printf(" python class and module of one QN (%s): go -> Thing.run=%d, go_other -> Other.run=%d\n", + label, member, other); + return !(member == 0 && other == 1); } TEST(type_scope_python_class_and_module_of_one_qn) { @@ -1427,13 +1434,18 @@ TEST(type_scope_go_promotion_takes_the_shallowest_depth) { * the same in one file; an embedded type the project does not have * (sync.Mutex) still shadows a deeper `Mutex`; and build variants of one * struct, one of which declares a field `Item` the other does not, select no - * deeper `Item`. `go run` agrees on each. */ + * `Item` at all: `v.Item` is base.Item on a linux build and Deep's Item2 + * elsewhere (`go run` on darwin: item2), so no one edge is right. Each "no + * edge" case has a positive partner: a promoted method of Outer (Ping), the + * explicit path to the deeper Mutex (Lock2), a field both variants declare + * alike (UseSame); Here's edge is the embedded Cfg's. `go run` agrees. */ static const ts_file_t go_embfield_files[] = { {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, {"base/base.go", "package base\n\ntype Config struct{ n int }\n\n" "func (c *Config) Validate() string { return \"base\" }\n\n" "type Handler struct {\n\tConfig *Config\n}\n\n" "type W struct{ n int }\n\nfunc (w W) Logger(s string) string { return s }\n\n" + "func (w W) Ping() string { return \"p\" }\n\n" "type M struct{ n int }\n\nfunc (m *M) Lock() {}\n\n" "type Locker struct {\n\tMutex *M\n}\n\n" "type Item struct{ n int }\n\nfunc (i *Item) Do() string { return \"item\" }\n\n" @@ -1448,14 +1460,17 @@ static const ts_file_t go_embfield_files[] = { "type U struct {\n\tsync.Mutex\n\tbase.Locker\n}\n"}, {"srv/local.go", "package srv\n\nfunc Local(s *Server) string { return s.Config.Validate() }\n"}, {"srv/v_linux.go", "//go:build linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" - "type V struct {\n\tItem *base.Item\n\tbase.Deep\n}\n"}, + "type V struct {\n\tItem *base.Item\n\tSame *base.Item\n\tbase.Deep\n}\n"}, {"srv/v_other.go", "//go:build !linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" - "type V struct {\n\tbase.Deep\n}\n"}, + "type V struct {\n\tSame *base.Item\n\tbase.Deep\n}\n"}, {"app/app.go", "package app\n\nimport \"example.com/demo/srv\"\n\n" "func Run(s *srv.Server) string { return s.Config.Validate() }\n\n" "func Log(o srv.Outer) string { return o.Logger(\"x\") }\n\n" "func Lock(u *srv.U) { u.Mutex.Lock() }\n\n" - "func Use(v *srv.V) string { return v.Item.Do() }\n"}, + "func Use(v *srv.V) string { return v.Item.Do() }\n\n" + "func Ping(o srv.Outer) string { return o.Ping() }\n\n" + "func Lock2(u *srv.U) { u.Locker.Mutex.Lock() }\n\n" + "func UseSame(v *srv.V) string { return v.Same.Do() }\n"}, {"one/one.go", "package one\n\ntype Cfg struct{ n int }\n\nfunc (c Cfg) Check() string { return \"cfg\" }\n\n" "type Other struct{ n int }\n\nfunc (o Other) Check() string { return \"other\" }\n\n" "type H struct {\n\tCfg Other\n}\n\n" @@ -1466,16 +1481,23 @@ static const ts_file_t go_embfield_files[] = { static int go_embfield_check(cbm_store_t *s, const char *project, const char *label) { int run_right = ts_calls_to(s, project, "Run", "srv.Config.Validate", NULL); int local_right = ts_calls_to(s, project, "Local", "srv.Config.Validate", NULL); + int here_right = ts_calls_to(s, project, "Here", "one.Cfg.Check", NULL); + int ping = ts_calls_to(s, project, "Ping", "base.W.Ping", NULL); + int lock2 = ts_calls_to(s, project, "Lock2", "base.M.Lock", NULL); + int same = ts_calls_to(s, project, "UseSame", "base.Item.Do", NULL); int wrong = ts_calls_to(s, project, "Run", "base.Config.Validate", NULL) + ts_calls_to(s, project, "Local", "base.Config.Validate", NULL) + ts_calls_to(s, project, "Log", "base.W.Logger", NULL) + ts_calls_to(s, project, "Lock", "base.M.Lock", NULL) + - ts_calls_to(s, project, "Use", "base.Item2.Do", NULL) + ts_calls_to(s, project, "Here", "one.Other.Check", NULL); - int here_right = ts_calls_to(s, project, "Here", "one.Cfg.Check", NULL); - printf(" go embedded field names (%s): Run=%d Local=%d Here=%d, wrong=%d\n", label, run_right, - local_right, here_right, wrong); - return !(run_right == 1 && local_right == 1 && here_right <= 1 && wrong == 0); + /* the answer of a build: Item on linux, Item2 elsewhere */ + int by_build = ts_calls_to(s, project, "Use", "base.Item2.Do", NULL) + + ts_calls_to(s, project, "Use", "base.Item.Do", NULL); + printf(" go embedded field names (%s): Run=%d Local=%d Here=%d Ping=%d Lock2=%d UseSame=%d, " + "wrong=%d, by build=%d\n", + label, run_right, local_right, here_right, ping, lock2, same, wrong, by_build); + return !(run_right == 1 && local_right == 1 && here_right == 1 && ping == 1 && lock2 == 1 && + same == 1 && wrong == 0 && by_build == 0); } TEST(type_scope_go_embedded_field_names_are_fields) { @@ -1518,8 +1540,12 @@ static int go_shadowtype_check(cbm_store_t *s, const char *project, const char * ts_calls_to(s, project, "Boxed", "p1.E.Hello", NULL) + ts_calls_to(s, project, "Field", "p1.E.Hello", NULL); int pkg = ts_calls_to(s, project, "Pkg", "p1.E.Hello", NULL); - printf(" go function-declared types (%s): wrong=%d, package T Pkg=%d\n", label, wrong, pkg); - return !(wrong == 0 && pkg == 1); + /* the signatures are read: the calls themselves resolve */ + int direct = ts_calls_to(s, project, "Call", "m.First", NULL) + + ts_calls_to(s, project, "Boxed", "m.Box.Get", NULL); + printf(" go function-declared types (%s): wrong=%d, package T Pkg=%d, First/Get=%d\n", label, + wrong, pkg, direct); + return !(wrong == 0 && pkg == 1 && direct == 2); } TEST(type_scope_go_function_declared_types_are_not_the_package_types) { @@ -1648,13 +1674,31 @@ typedef struct { cbm_incremental_route_t route; cbm_incremental_closure_plan_t plan; bool same_graph; + int before_bad; /* the `before` check on the first index (0 = right) */ + int after_bad; /* the `after` check on the repaired graph (0 = right) */ } ts_incr_result_t; +/* Run `check` on one database of the harness: 0 when it holds (or there is + * no check), else nonzero (also when the index named no project). */ +static int ts_db_check(const char *db, const char *project, ts_check_fn check, const char *label) { + if (!check || !project[0]) { + return check ? 1 : 0; + } + cbm_store_t *s = cbm_store_open_path(db); + int bad = s ? check(s, project, label) : 1; + if (s) { + cbm_store_close(s); + } + return bad; +} + /* Index `files` (plus `pad` Go or Python fillers), apply `edits`, index again * incrementally into the same database, then index the edited tree afresh; - * the two graphs must be equal whatever route the incremental run took. */ -static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_lang, int pad, - const ts_file_t *edits, const char *tag) { + * the two graphs must be equal whatever route the incremental run took. + * `before` (optional) checks the first index, `after` the repaired graph. */ +static ts_incr_result_t ts_incremental_checked(const ts_file_t *files, CBMLanguage pad_lang, + int pad, const ts_file_t *edits, const char *tag, + ts_check_fn before, ts_check_fn after) { ts_incr_result_t r = {.route = CBM_INCREMENTAL_ROUTE_NONE}; char tmp[256]; snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_incr_XXXXXX"); @@ -1671,6 +1715,7 @@ static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_l snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(base)); } cbm_pipeline_free(base); + r.before_bad = ts_db_check(db, project, before, "before the edit"); ts_write(tmp, edits); cbm_pipeline_incremental_test_reset_faults(); @@ -1679,6 +1724,7 @@ static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_l r.route = cbm_pipeline_incremental_test_last_route(); r.plan = cbm_pipeline_incremental_test_last_closure_plan(); cbm_pipeline_free(incr); + r.after_bad = rc == 0 ? ts_db_check(db, project, after, "repaired") : 1; char full_db[512]; snprintf(full_db, sizeof(full_db), "%s/full.db", tmp); @@ -1703,6 +1749,11 @@ static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_l return r; } +static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_lang, int pad, + const ts_file_t *edits, const char *tag) { + return ts_incremental_checked(files, pad_lang, pad, edits, tag, NULL, NULL); +} + /* Only the caller is re-parsed (a closure of one file: the per-file Go * registrar): fixture.go's identities come back from its stored row. */ TEST(type_scope_incremental_caller_edit_per_file_go) { @@ -1913,6 +1964,14 @@ static void go_emb_sources(void) { fields); } +/* The repaired graph has the edge through the 17th embedded type. */ +static int go_emb16_after(cbm_store_t *s, const char *project, const char *label) { + int m16 = ts_calls_to(s, project, "Use", "big.E16.M16", NULL); + int m14 = ts_calls_to(s, project, "Use", "big.E14.M14", NULL); + printf(" go 17 embedded types (%s): Use -> E16.M16=%d E14.M14=%d\n", label, m16, m14); + return !(m16 == 1 && m14 == 1); +} + TEST(type_scope_incremental_many_embedded_types_match_full) { go_emb_sources(); const ts_file_t files[] = { @@ -1926,24 +1985,37 @@ TEST(type_scope_incremental_many_embedded_types_match_full) { "func Run(b *big.Big) string { return b.M16() }\n"}, {NULL, NULL}}; const ts_file_t edit[] = {{"big/big.go", g_go_emb_big_edited}, {NULL, NULL}}; - ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 40, edit, "go 17 embedded types"); + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_GO, 40, edit, "go 17 embedded types", + NULL, go_emb16_after); ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); ASSERT_EQ(r.plan.files, 1); ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.after_bad, 0); PASS(); } -/* The same for a struct of 66 fields (the 63-field limit beside N4). */ +/* The same for a struct of 66 fields (the 63-field limit beside N4): the + * repaired graph is the full index's and has the calls through fields 65 + * and 66 (both routes cut at 63 before). */ +static int go_wide_after(cbm_store_t *s, const char *project, const char *label) { + int use = ts_calls_to(s, project, "Use", "kind.K.Name", NULL) + + ts_calls_to(s, project, "Use", "kind.L.Name", NULL); + printf(" go 66 fields (%s): Use through fields 65 and 66=%d\n", label, use); + return use != 2; +} + TEST(type_scope_incremental_many_fields_match_full) { ts_file_t files[8]; go_wide_fixture(files); const ts_file_t edit[] = { {"wide/wide.go", go_wide_source(g_go_wide_edited, sizeof(g_go_wide_edited), true)}, {NULL, NULL}}; - ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 40, edit, "go 66 fields"); + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_GO, 40, edit, "go 66 fields", NULL, + go_wide_after); ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); ASSERT_EQ(r.plan.files, 1); ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.after_bad, 0); PASS(); } @@ -2030,7 +2102,20 @@ TEST(type_scope_incremental_python_declaring_change_matches_full) { * OtherConfig`: same lines, same bytes otherwise) changes the class's * identities. The class's bindings are part of its stored row, so the run is * not a one-file repair that keeps the caller's stale `run -> - * pkg.mod.Config.load`. */ + * pkg.mod.Config.load`: before the edit the edge is there (Config is the + * module's), after it the repaired graph has none (python3: OtherConfig). */ +static int py_classedit_before(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" py class-body edit (%s): run -> Config.load=%d\n", label, edge); + return edge != 1; +} + +static int py_classedit_after(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" py class-body edit (%s): run -> Config.load=%d\n", label, edge); + return edge != 0; +} + TEST(type_scope_incremental_python_class_body_binding_matches_full) { const ts_file_t files[] = { {"pkg/__init__.py", ""}, @@ -2047,8 +2132,12 @@ TEST(type_scope_incremental_python_class_body_binding_matches_full) { "class Model:\n Config = OtherConfig\n\n" " def cfg(self) -> Config:\n return Config()\n"}, {NULL, NULL}}; - ts_incr_result_t r = ts_incremental(files, CBM_LANG_PYTHON, 0, edit, "py class-body binding"); + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_PYTHON, 0, edit, + "py class-body binding", py_classedit_before, + py_classedit_after); ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.before_bad, 0); + ASSERT_EQ(r.after_bad, 0); PASS(); } From 05ef90bf700b25ed0a975eeb8f158477a40dd88b Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:13 +0100 Subject: [PATCH 18/25] perf(extract): a Go struct's embedded-type text in one linear pass go_struct_embedded_text joined each embedded type's spelling onto the text so far with a new sprintf, copying the whole prefix again for every embed: quadratic in the number of embedded types. It now measures the spellings in one cursor pass over the field list and copies them into one arena buffer in a second: linear, with the same text. A test seam counts the work (cursor steps and bytes copied), and a test extracts structs of 2000 and 4000 embedded types: the work doubles, and the last spelling is in the list. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 3 ++ internal/cbm/extract_defs.c | 86 ++++++++++++++++++++++++++++++------- tests/test_type_scope.c | 43 +++++++++++++++++++ 3 files changed, 117 insertions(+), 15 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index c67db3caf..152e89afa 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -1419,6 +1419,9 @@ bool cbm_py_namespace_facts_copy(CBMArena *arena, const CBMPyNamespaceFacts *sou #ifdef CBM_ENABLE_TEST_SEAMS void cbm_py_namespace_test_capture_fail_after(int successful_allocations); void cbm_py_namespace_test_copy_fail_after(int successful_allocations); +/* Work of building Go structs' embedded-type texts (field-list entries + * visited plus spelling bytes): the growth test counts it at three sizes. */ +uint64_t cbm_extract_test_go_embedded_work(void); #endif // Growable array push functions (arena-allocated, no individual free needed). diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index d23974ea7..b1e2d690e 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -16,6 +16,7 @@ #include "semantic/ast_profile.h" #include "tree_sitter/api.h" // TSNode, ts_node_* #include // INT_MAX +#include // test-seam work counters #include // uint32_t, SIZE_MAX #include // snprintf (ObjectScript storage/trigger sidecars) #include // malloc/free (child-collection scratch) @@ -8895,29 +8896,84 @@ static const char *cs_type_decl_namespace(CBMExtractCtx *ctx, TSNode node) { return ts_node_has_error(top) ? NULL : ""; } +#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_go_embedded_text_work; +uint64_t cbm_extract_test_go_embedded_work(void) { + return atomic_load_explicit(&g_go_embedded_text_work, memory_order_relaxed); +} +#define GO_EMBEDDED_TEXT_WORK(n) \ + atomic_fetch_add_explicit(&g_go_embedded_text_work, (uint64_t)(n), memory_order_relaxed) +#else +#define GO_EMBEDDED_TEXT_WORK(n) ((void)0) +#endif + +/* The type of an embedded field (an unnamed field declaration) of a struct's + * field list, or a null node. */ +static TSNode go_embedded_field_type(TSNode field) { + if (strcmp(ts_node_type(field), "field_declaration") != 0 || + !ts_node_is_null(ts_node_child_by_field_name(field, TS_FIELD("name")))) { + return (TSNode){0}; + } + return ts_node_child_by_field_name(field, TS_FIELD("type")); +} + +/* Its spelling's span when it can join a '|'-list (non-empty, no '|'). */ +static bool go_embedded_span(TSNode type, const char *source, uint32_t *start, uint32_t *len) { + if (ts_node_is_null(type)) { + return false; + } + *start = ts_node_start_byte(type); + *len = ts_node_end_byte(type) - *start; + GO_EMBEDDED_TEXT_WORK(*len); + return *len > 0 && !memchr(source + *start, '|', *len); +} + /* Go: the types a struct type_spec embeds (its unnamed field declarations), - * '|'-joined as written, or NULL. */ + * '|'-joined as written, or NULL. Two passes over the field list with a + * cursor (measure, then copy once): linear in the struct's size. */ static const char *go_struct_embedded_text(CBMArena *a, TSNode spec, const char *source) { TSNode st = ts_node_child_by_field_name(spec, TS_FIELD("type")); if (ts_node_is_null(st) || strcmp(ts_node_type(st), "struct_type") != 0) { return NULL; } TSNode list = cbm_find_child_by_kind(st, "field_declaration_list"); - uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list); - const char *out = NULL; - for (uint32_t i = 0; i < n; i++) { - TSNode field = ts_node_named_child(list, i); - if (strcmp(ts_node_type(field), "field_declaration") != 0 || - !ts_node_is_null(ts_node_child_by_field_name(field, TS_FIELD("name")))) { - continue; - } - TSNode type = ts_node_child_by_field_name(field, TS_FIELD("type")); - const char *text = ts_node_is_null(type) ? NULL : cbm_node_text(a, type, source); - if (!text || !text[0] || strchr(text, '|')) { - continue; - } - out = out ? cbm_arena_sprintf(a, "%s|%s", out, text) : text; + if (ts_node_is_null(list)) { + return NULL; } + size_t total = 0; + char *out = NULL; + size_t at = 0; + for (int pass = 0; pass < 2; pass++) { + TSTreeCursor cur = ts_tree_cursor_new(list); + for (bool ok = ts_tree_cursor_goto_first_child(&cur); ok; + ok = ts_tree_cursor_goto_next_sibling(&cur)) { + GO_EMBEDDED_TEXT_WORK(1); + uint32_t start = 0; + uint32_t len = 0; + TSNode field = ts_tree_cursor_current_node(&cur); + if (!ts_node_is_named(field) || + !go_embedded_span(go_embedded_field_type(field), source, &start, &len)) { + continue; + } + if (pass == 0) { + total += len + 1; + continue; + } + if (at) { + out[at++] = '|'; + } + memcpy(out + at, source + start, len); + at += len; + } + ts_tree_cursor_delete(&cur); + if (pass == 0) { + out = total ? (char *)cbm_arena_alloc(a, total) : NULL; + if (!out) { + return NULL; + } + } + } + out[at] = '\0'; return out; } diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 6d8325c12..bb323a171 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -911,6 +911,48 @@ TEST(type_scope_python_class_and_module_of_one_qn) { return ts_twins("pyclassmod", py_classmod_files, CBM_LANG_PYTHON, py_classmod_check); } +/* A struct's embedded-type text is built once, with one buffer: the + * extractor's work for n embedded types is linear in n. */ +static uint64_t ts_go_embedded_work(int n) { + size_t cap = (size_t)n * 24 + 256; + char *src = (char *)calloc(cap, 1); + if (!src) { + return 0; + } + size_t at = (size_t)snprintf(src, cap, + "package p\n\nimport \"example.com/demo/parts\"\n\ntype S struct {\n"); + for (int i = 0; i < n; i++) { + at += (size_t)snprintf(src + at, cap - at, "\tparts.E%d\n", i); + } + at += (size_t)snprintf(src + at, cap - at, "}\n"); + uint64_t before = cbm_extract_test_go_embedded_work(); + CBMFileResult *r = + cbm_extract_file(src, (int)at, CBM_LANG_GO, "proj", "p/s.go", 0, NULL, NULL); + uint64_t work = cbm_extract_test_go_embedded_work() - before; + /* the whole list is there: n spellings, the last one included */ + char last[32]; + snprintf(last, sizeof(last), "parts.E%d", n - 1); + bool whole = false; + for (int i = 0; r && i < r->defs.count; i++) { + const CBMDefTypeFacts *f = r->defs.items[i].type_facts; + whole = whole || (f && f->go_embedded && strstr(f->go_embedded, last)); + } + cbm_free_result(r); + free(src); + return whole ? work : 0; +} + +TEST(type_scope_go_embedded_text_work_grows_linearly) { + uint64_t small = ts_go_embedded_work(2000); + uint64_t mid = ts_go_embedded_work(4000); + uint64_t large = ts_go_embedded_work(8000); + printf(" go embedded text work: 2000 embeds=%llu 4000=%llu 8000=%llu\n", + (unsigned long long)small, (unsigned long long)mid, (unsigned long long)large); + ASSERT_TRUE(ts_linear(small, mid)); + ASSERT_TRUE(ts_linear(mid, large)); + PASS(); +} + /* Finding 6: `-> Self` chains across files keep main's edges; `Self` comes * from typing, which the project does not define. A decoy declares the same * method names. */ @@ -2176,6 +2218,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_promotion_takes_the_shallowest_depth); RUN_TEST(type_scope_go_embedded_field_names_are_fields); RUN_TEST(type_scope_go_function_declared_types_are_not_the_package_types); + RUN_TEST(type_scope_go_embedded_text_work_grows_linearly); RUN_TEST(type_scope_go_struct_fields_have_no_limit); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); RUN_TEST(type_scope_incremental_caller_edit_per_file_go_values); From ae5bae29504effd0459f7481369a3c4dfdff90a8 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:21 +0100 Subject: [PATCH 19/25] fix(lsp): del and except-as unbind a name in a Python class body A class body's `del D` and `except ValueError as E` counted as bindings of the class, so a method annotation naming D or E after them took no identity, although by then the name is the module's again (Python unbinds an except target when its clause ends). The class-body list now takes the body's top-level statements in order: a binding holds from its statement on, and a later top-level `del` unbinds it unless a method is defined between the two (evaluated at definition time its annotation saw the class's binding, evaluated lazily the module's: no one answer, so the name stays bound); a `del` inside a compound statement may not run and unbinds nothing. An except target is a binding only for a definition inside its clause. python3.15 and 3.14 (lazy annotations) and 3.9 (eager) agree on the module's E and D; D2, bound when its method was defined, differs between them and keeps the abstention. Signed-off-by: Martin Vogel --- internal/cbm/extract_defs.c | 132 +++++++++++++++++++++++++++++++++--- tests/test_type_scope.c | 40 +++++++++++ 2 files changed, 161 insertions(+), 11 deletions(-) diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index b1e2d690e..0572b5149 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -7176,8 +7176,38 @@ static void py_bind_as_targets(tf_names_t *b, TSNode node, const char *source, i static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int depth); +static bool py_defines_kind(const char *kind) { + return strcmp(kind, "function_definition") == 0 || strcmp(kind, "class_definition") == 0 || + strcmp(kind, "decorated_definition") == 0; +} + +/* Statement-level nodes a scope's statements nest in (not expressions). */ +static bool py_statement_level(const char *kind) { + return strcmp(kind, "block") == 0 || strstr(kind, "_statement") != NULL || + strstr(kind, "_clause") != NULL; +} + +/* Whether a definition stands among the statements of `node`. */ +static bool py_has_def(TSNode node, int depth) { + if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) { + return false; + } + uint32_t n = ts_node_named_child_count(node); + for (uint32_t i = 0; i < n; i++) { + TSNode c = ts_node_named_child(node, i); + const char *ck = ts_node_type(c); + if (py_defines_kind(ck) || (py_statement_level(ck) && py_has_def(c, depth + 1))) { + return true; + } + } + return false; +} + /* Python: the names one statement of a class body binds (it recurses into - * compound statements, whose bodies are the same scope). */ + * compound statements, whose bodies are the same scope). `del` binds nothing + * (py_class_body_bindings unbinds at the body's top level), and neither does + * `except ... as E`: Python unbinds E when the clause ends, so it is a binding + * only for a definition inside the clause. */ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int depth) { if (ts_node_is_null(s) || depth > TF_BIND_DEPTH) { return; @@ -7238,11 +7268,13 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d } return; } - if (strcmp(kind, "global_statement") == 0 || strcmp(kind, "nonlocal_statement") == 0 || - strcmp(kind, "delete_statement") == 0) { + if (strcmp(kind, "global_statement") == 0 || strcmp(kind, "nonlocal_statement") == 0) { py_bind_target(b, s, source, depth + 1); return; } + if (strcmp(kind, "delete_statement") == 0) { + return; + } if (strcmp(kind, "type_alias_statement") == 0) { py_bind_target(b, ts_node_child_by_field_name(s, TS_FIELD("left")), source, depth + 1); return; @@ -7258,6 +7290,19 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d const char *ck = ts_node_type(c); if (strcmp(ck, "block") == 0) { py_bind_block(b, c, source, depth + 1); + } else if (strncmp(ck, "except", 6) == 0 && strstr(ck, "_clause") != NULL) { + if (py_has_def(c, depth + 1)) { + py_bind_as_targets(b, c, source, depth + 1); + } + uint32_t m = ts_node_named_child_count(c); + for (uint32_t j = 0; j < m; j++) { + TSNode part = ts_node_named_child(c, j); + if (strcmp(ts_node_type(part), "block") == 0) { + py_bind_block(b, part, source, depth + 2); + } else { + py_bind_walrus(b, part, source, depth + 2); + } + } } else if (strstr(ck, "_clause") != NULL) { py_bind_as_targets(b, c, source, depth + 1); py_bind_statement(b, c, source, depth + 1); @@ -7275,17 +7320,82 @@ static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int d } } -/* Python: the names a class body binds besides its nested definitions, - * '|'-joined (repeats allowed), or NULL. */ -static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char *source) { +static TSNode py_def_body(TSNode node) { if (strcmp(ts_node_type(node), "decorated_definition") == 0) { node = ts_node_child_by_field_name(node, TS_FIELD("definition")); } - TSNode body = - ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body")); - tf_names_t b = {.a = a}; - py_bind_block(&b, body, source, 0); - return b.len ? b.buf : NULL; + return ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body")); +} + +/* Python: the names a class body binds besides its nested definitions, + * '|'-joined, each once, or NULL. The top-level statements are taken in + * order: a binding holds from its statement on, and a later top-level `del` + * unbinds it -- unless a definition stands between the two, which saw the + * name bound when its annotations were evaluated at definition time (a + * top-level one: a definition inside a compound statement is no method the + * extractor lists). A `del` inside a compound statement may not run: the name + * stays bound. */ +static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char *source) { + TSNode body = py_def_body(node); + if (ts_node_is_null(body)) { + return NULL; + } + CBMHashTable *state = cbm_ht_create(32); /* name -> epoch of its binding, or 1: unbound */ + if (!state) { + return NULL; + } + tf_names_t order = {.a = a}; /* every name bound once, in first-binding order */ + uintptr_t epoch = 2; /* moves on at each definition */ + TSTreeCursor cur = ts_tree_cursor_new(body); + for (bool ok = ts_tree_cursor_goto_first_child(&cur); ok; + ok = ts_tree_cursor_goto_next_sibling(&cur)) { + TSNode s = ts_tree_cursor_current_node(&cur); + if (!ts_node_is_named(s)) { + continue; + } + const char *kind = ts_node_type(s); + if (py_defines_kind(kind)) { + epoch++; + continue; + } + tf_names_t one = {.a = a}; + bool del = strcmp(kind, "delete_statement") == 0; + if (del) { + py_bind_target(&one, s, source, 1); + } else { + py_bind_statement(&one, s, source, 0); + } + for (const char *p = one.buf; p && *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + char *name = cbm_arena_strndup(a, p, len); + uintptr_t was = name ? (uintptr_t)cbm_ht_get(state, name) : 0; + if (name && del) { + if (was == epoch) { + cbm_ht_set(state, name, (void *)(uintptr_t)1); + } + } else if (name) { + if (!was) { + tf_names_add(&order, name, len); + } + cbm_ht_set(state, name, (void *)epoch); + } + p = bar ? bar + 1 : p + len; + } + } + ts_tree_cursor_delete(&cur); + tf_names_t out = {.a = a}; + for (const char *p = order.buf; p && *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + char *name = cbm_arena_strndup(a, p, len); + if (name && (uintptr_t)cbm_ht_get(state, name) > 1) { + tf_names_add(&out, name, len); + } + p = bar ? bar + 1 : p + len; + } + cbm_ht_free(state); + return out.len ? out.buf : NULL; } /* Make: a rule names several targets (`up down: deps`), each a goal diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index bb323a171..b947a0c8e 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -911,6 +911,45 @@ TEST(type_scope_python_class_and_module_of_one_qn) { return ts_twins("pyclassmod", py_classmod_files, CBM_LANG_PYTHON, py_classmod_check); } +/* `except ValueError as E` unbinds E when the clause + * ends, and `D = Other; del D` leaves D unbound: methods defined after them + * name the module's E and D (python3 agrees). A `del` after a method that saw + * the binding (`D2 = Other`, `def md2(self) -> D2`, `del D2`) keeps the + * abstention: evaluated at definition time (Python before 3.14) the annotation + * is Other, evaluated lazily (3.14 on) the module's D2 -- no one answer. */ +static const ts_file_t py_unbind_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/mod.py", "class Other:\n def load(self):\n return 'other'\n\n\n" + "class D:\n def load(self):\n return 'D'\n\n\n" + "class E:\n def load(self):\n return 'E'\n\n\n" + "class D2:\n def load(self):\n return 'D2'\n\n\n" + "class Model:\n" + " try:\n raise ValueError()\n except ValueError as E:\n pass\n" + " D = Other\n del D\n D2 = Other\n\n" + " def md2(self) -> D2:\n return D2()\n\n" + " del D2\n\n" + " def me(self) -> E:\n return E()\n\n" + " def md(self) -> D:\n return D()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run_e():\n return Model().me().load()\n\n\n" + "def run_d():\n return Model().md().load()\n\n\n" + "def run_d2():\n return Model().md2().load()\n"}, + {NULL, NULL}}; + +static int py_unbind_check(cbm_store_t *s, const char *project, const char *label) { + int e = ts_calls_to(s, project, "run_e", "pkg.mod.E.load", NULL); + int d = ts_calls_to(s, project, "run_d", "pkg.mod.D.load", NULL); + int d2 = ts_calls_to(s, project, "run_d2", "pkg.mod.D2.load", NULL) + + ts_calls_to(s, project, "run_d2", "pkg.mod.Other.load", NULL); + printf(" python class-body unbinding (%s): E=%d D=%d, D2 (bound at definition)=%d\n", label, e, + d, d2); + return !(e == 1 && d == 1 && d2 == 0); +} + +TEST(type_scope_python_unbound_class_names_are_the_module_names) { + return ts_twins("pyunbind", py_unbind_files, CBM_LANG_PYTHON, py_unbind_check); +} + /* A struct's embedded-type text is built once, with one buffer: the * extractor's work for n embedded types is linear in n. */ static uint64_t ts_go_embedded_work(int n) { @@ -2204,6 +2243,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); RUN_TEST(type_scope_python_class_and_module_of_one_qn); + RUN_TEST(type_scope_python_unbound_class_names_are_the_module_names); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); From 148dd0521f51eb9ec8c20853ff714edac7b9e57a Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:29 +0100 Subject: [PATCH 20/25] fix(lsp): a Python name a body declares global and binds takes no identity `global R` in a class body (run at import) or in a function body that binds R (`from pkg.b import R`) rebinds the module's R, so an annotation naming R in that module may mean that other binding (python3: pkg.b.R after the class body). Like a name the module binds twice, R now takes no identity there. The extractor records the names a body declares global and binds (CBMDefTypeFacts.global_names: assignments, imports, for and with targets, a nested def's or class's name, del and except targets count, the declaration alone does not), and the step marks them as bound more than once in the file's module bindings. The names join the definition's stored row (field_defs, as `name:` without a type), so an edit that adds or drops one is not a one-file repair. A function that declares `global R` and only reads it keeps the identity. Signed-off-by: Martin Vogel --- internal/cbm/cbm.h | 4 ++ internal/cbm/extract_defs.c | 90 +++++++++++++++++++++++++++++++++-- internal/cbm/result_compact.c | 1 + src/pipeline/pass_lsp_cross.c | 28 +++++++---- src/pipeline/pipeline.c | 3 +- src/pipeline/type_scope.c | 18 +++++++ tests/test_type_scope.c | 78 ++++++++++++++++++++++++++++++ 7 files changed, 208 insertions(+), 14 deletions(-) diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 152e89afa..0af407789 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -360,6 +360,10 @@ typedef struct CBMDefTypeFacts { * annotation alone binds nothing), '|'-joined. A method annotation naming * one of them means the class attribute, not the module's name. */ const char *class_bindings; + /* Python function or class: the names its body declares `global` and + * binds, '|'-joined. The body rebinds them in the module, so no + * annotation of the file names them through the module's other binding. */ + const char *global_names; } CBMDefTypeFacts; /* extra_props key of a generated member, one the compiler writes and the diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 0572b5149..843fcfbae 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -7006,6 +7006,13 @@ static void def_set_type_params(CBMArena *a, CBMDefinition *def, const char *nam } } +static void def_set_global_names(CBMArena *a, CBMDefinition *def, const char *names) { + CBMDefTypeFacts *f = names && names[0] ? def_type_facts(a, def) : NULL; + if (f) { + f->global_names = names; + } +} + /* A '|'-joined list of names built in the arena (the grown buffers stay in * the arena: at most twice the final size). */ typedef struct { @@ -7013,6 +7020,10 @@ typedef struct { char *buf; size_t len; size_t cap; + /* Python binding walks: what a body binds in the module through names it + * declares `global` (py_body_global_names) -- `del`, `except ... as`, a + * nested def's or class's name bind; the declaration itself does not. */ + bool module; } tf_names_t; static void tf_names_add(tf_names_t *b, const char *s, size_t n) { @@ -7213,8 +7224,15 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d return; } const char *kind = ts_node_type(s); - if (strcmp(kind, "function_definition") == 0 || strcmp(kind, "class_definition") == 0 || - strcmp(kind, "decorated_definition") == 0) { + if (py_defines_kind(kind)) { + if (b->module) { + TSNode def = strcmp(kind, "decorated_definition") == 0 + ? ts_node_child_by_field_name(s, TS_FIELD("definition")) + : s; + if (!ts_node_is_null(def)) { + tf_names_node(b, ts_node_child_by_field_name(def, TS_FIELD("name")), source); + } + } return; /* definitions of the class: the step sees them as such */ } if (strcmp(kind, "expression_statement") == 0) { @@ -7269,10 +7287,15 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d return; } if (strcmp(kind, "global_statement") == 0 || strcmp(kind, "nonlocal_statement") == 0) { - py_bind_target(b, s, source, depth + 1); + if (!b->module) { + py_bind_target(b, s, source, depth + 1); + } return; } if (strcmp(kind, "delete_statement") == 0) { + if (b->module) { + py_bind_target(b, s, source, depth + 1); + } return; } if (strcmp(kind, "type_alias_statement") == 0) { @@ -7291,7 +7314,7 @@ static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int d if (strcmp(ck, "block") == 0) { py_bind_block(b, c, source, depth + 1); } else if (strncmp(ck, "except", 6) == 0 && strstr(ck, "_clause") != NULL) { - if (py_has_def(c, depth + 1)) { + if (b->module || py_has_def(c, depth + 1)) { py_bind_as_targets(b, c, source, depth + 1); } uint32_t m = ts_node_named_child_count(c); @@ -7398,6 +7421,62 @@ static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char * return out.len ? out.buf : NULL; } +/* The names declared `global` among a scope's statements (compound ones + * included, nested definitions not: they are scopes of their own). */ +static void py_global_statements(tf_names_t *b, TSNode node, const char *source, int depth) { + if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) { + return; + } + uint32_t n = ts_node_named_child_count(node); + for (uint32_t i = 0; i < n; i++) { + TSNode c = ts_node_named_child(node, i); + const char *ck = ts_node_type(c); + if (strcmp(ck, "global_statement") == 0) { + py_bind_target(b, c, source, depth + 1); + } else if (!py_defines_kind(ck) && py_statement_level(ck)) { + py_global_statements(b, c, source, depth + 1); + } + } +} + +/* Python: the names a function's or class's body declares `global` and + * binds, '|'-joined, or NULL: the body rebinds them in the module. */ +static const char *py_body_global_names(CBMArena *a, TSNode node, const char *source) { + TSNode body = py_def_body(node); + tf_names_t declared = {.a = a}; + py_global_statements(&declared, body, source, 0); + if (!declared.len) { + return NULL; + } + tf_names_t bound = {.a = a, .module = true}; + py_bind_block(&bound, body, source, 0); + CBMHashTable *binds = bound.len ? cbm_ht_create(16) : NULL; + if (!binds) { + return NULL; + } + for (const char *p = bound.buf; *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + char *name = cbm_arena_strndup(a, p, len); + if (name) { + cbm_ht_set(binds, name, name); + } + p = bar ? bar + 1 : p + len; + } + tf_names_t out = {.a = a}; + for (const char *p = declared.buf; *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + char *name = cbm_arena_strndup(a, p, len); + if (name && cbm_ht_get(binds, name)) { + tf_names_add(&out, name, len); + } + p = bar ? bar + 1 : p + len; + } + cbm_ht_free(binds); + return out.len ? out.buf : NULL; +} + /* Make: a rule names several targets (`up down: deps`), each a goal * `make ` runs. The rule's definition carries the first target; * every further one gets a definition of its own over the same rule span -- @@ -7711,6 +7790,7 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec extract_route_from_decorators(a, node, ctx->source, spec, &def.route_path, &def.route_method); if (ctx->language == CBM_LANG_PYTHON) { def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source)); + def_set_global_names(a, &def, py_body_global_names(a, node, ctx->source)); } else if (ctx->language == CBM_LANG_GO) { def_set_type_params(a, &def, go_type_param_names(a, node, ctx->source)); } @@ -9520,6 +9600,7 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s def.docstring = extract_docstring(ctx, node, name); if (ctx->language == CBM_LANG_PYTHON) { def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source)); + def_set_global_names(a, &def, py_body_global_names(a, node, ctx->source)); const char *bound = py_class_body_bindings(a, node, ctx->source); CBMDefTypeFacts *facts = bound ? def_type_facts(a, &def) : NULL; if (facts) { @@ -10060,6 +10141,7 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node, extract_route_from_decorators(a, child, ctx->source, spec, &def.route_path, &def.route_method); if (ctx->language == CBM_LANG_PYTHON) { def_set_type_params(a, &def, py_type_param_names(a, child, ctx->source)); + def_set_global_names(a, &def, py_body_global_names(a, child, ctx->source)); } else if (ctx->language == CBM_LANG_GO) { def_set_type_params(a, &def, go_type_param_names(a, child, ctx->source)); } diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index 3c5a9d082..64aa44dac 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -290,6 +290,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) { cr_str(c, &facts->value_type); cr_str(c, &facts->go_embedded); cr_str(c, &facts->class_bindings); + cr_str(c, &facts->global_names); } } diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index 680f01068..9299fe4eb 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -1130,8 +1130,10 @@ static const char *pxc_py_add_class_bindings(CBMArena *arena, const char *field_ /* The facts only the cross-file step reads (CBMDefTypeFacts), on the file's * LSP defs after the field folds: a Go generic type's field types name its - * type parameters as `any`; a Python class body's bindings join its - * field_defs. One hash of the file's defs, built only when one applies. */ + * type parameters as `any`; a Python class body's bindings and a Python + * body's `global` names join its field_defs (as `name:`, no type), so they are + * part of the stored row the planner compares. One hash of the file's defs, + * built only when one applies. */ static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLSPDef *defs, int start, int end, CBMLanguage lang) { if (!fr || (lang != CBM_LANG_GO && lang != CBM_LANG_PYTHON) || start >= end) { @@ -1141,12 +1143,14 @@ static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLS for (int di = 0; di < fr->defs.count; di++) { const CBMDefinition *d = &fr->defs.items[di]; const CBMDefTypeFacts *f = d->type_facts; - if (!f || !d->qualified_name || !d->label || !cbm_label_is_type_like(d->label)) { + if (!f || !d->qualified_name || !d->label) { continue; } - bool go_generic = lang == CBM_LANG_GO && f->type_params; - bool py_bound = lang == CBM_LANG_PYTHON && f->class_bindings; - if (!go_generic && !py_bound) { + bool type_like = cbm_label_is_type_like(d->label); + bool go_generic = lang == CBM_LANG_GO && type_like && f->type_params; + bool py_bound = lang == CBM_LANG_PYTHON && type_like && f->class_bindings; + bool py_global = lang == CBM_LANG_PYTHON && f->global_names; + if (!go_generic && !py_bound && !py_global) { continue; } if (!by_qn) { @@ -1161,9 +1165,15 @@ static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLS if (!dst) { continue; } - dst->field_defs = - go_generic ? pxc_go_mask_field_types(arena, dst->field_defs, f->type_params) - : pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings); + if (go_generic) { + dst->field_defs = pxc_go_mask_field_types(arena, dst->field_defs, f->type_params); + } + if (py_bound) { + dst->field_defs = pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings); + } + if (py_global) { + dst->field_defs = pxc_py_add_class_bindings(arena, dst->field_defs, f->global_names); + } } cbm_ht_free(by_qn); } diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index 96630e133..48b69aa19 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2614,7 +2614,8 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c census_len(def->type_facts->type_params) + census_len(def->type_facts->value_type) + census_len(def->type_facts->go_embedded) + - census_len(def->type_facts->class_bindings); + census_len(def->type_facts->class_bindings) + + census_len(def->type_facts->global_names); } } for (int c = 0; c < r->calls.count; c++) { diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index 5e4305221..ab5b6edd7 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -178,6 +178,23 @@ static void type_scope_index_class_bindings(cbm_type_scope_file_t *f, const CBMD } } +/* A name some function or class body of the file declares `global` and binds + * is rebound in the module by that body (when it runs, or at import for a + * class body): like a name the module binds twice, it gets no identity. */ +static void type_scope_index_global_names(cbm_type_scope_file_t *f, const CBMDefinition *d) { + const char *names = d->type_facts ? d->type_facts->global_names : NULL; + for (const char *p = names; p && *p;) { + const char *bar = strchr(p, '|'); + size_t len = bar ? (size_t)(bar - p) : strlen(p); + TYPE_SCOPE_WORK(len + 1); + char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL; + if (name) { + cbm_ht_set(f->bindings, name, TYPE_SCOPE_BOUND_MANY); + } + p = bar ? bar + 1 : p + len; + } +} + /* Hash the file's own definitions, its type parameter names and the names * its class bodies bind. */ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { @@ -197,6 +214,7 @@ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { cbm_ht_set(f->defs, d->qualified_name, (void *)(uintptr_t)(i + 1)); } type_scope_index_class_bindings(f, d); + type_scope_index_global_names(f, d); for (const char *p = d->type_facts ? d->type_facts->type_params : NULL; p && *p;) { const char *bar = strchr(p, '|'); size_t len = bar ? (size_t)(bar - p) : strlen(p); diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index b947a0c8e..23f37ea87 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -911,6 +911,45 @@ TEST(type_scope_python_class_and_module_of_one_qn) { return ts_twins("pyclassmod", py_classmod_files, CBM_LANG_PYTHON, py_classmod_check); } +/* `global R` in a class body (run at import) or a function body that binds R + * rebinds the module's R, so `def make_r() -> R` after it names whatever that + * body bound (python3: pkg.b.R for the class body; for the function, whether + * it ran). No identity is taken from the import. A module that only imports R + * keeps it (run_a), and so does one whose function declares `global R` and + * only reads it (run_p). */ +static const ts_file_t py_global_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a.py", "class R:\n def save(self):\n return 'a'\n"}, + {"pkg/b.py", "class R:\n def save(self):\n return 'b'\n"}, + {"pkg/mod.py", "from pkg.a import R\n\n\nclass Rebind:\n global R\n from pkg.b import R\n\n\n" + "def make_r() -> R:\n return R()\n"}, + {"pkg/mod2.py", "from pkg.a import R\n\n\ndef setup():\n global R\n from pkg.b import R\n\n\n" + "def make_s() -> R:\n return R()\n"}, + {"pkg/mod3.py", "from pkg.a import R\n\n\ndef make_a() -> R:\n return R()\n"}, + {"pkg/mod4.py", "from pkg.a import R\n\n\ndef peek():\n global R\n return R.__name__\n\n\n" + "def make_p() -> R:\n return R()\n"}, + {"pkg/use.py", "from pkg.mod import make_r\nfrom pkg.mod2 import make_s\nfrom pkg.mod3 import make_a\n" + "from pkg.mod4 import make_p\n\n\n" + "def run_r():\n return make_r().save()\n\n\n" + "def run_s():\n return make_s().save()\n\n\n" + "def run_a():\n return make_a().save()\n\n\n" + "def run_p():\n return make_p().save()\n"}, + {NULL, NULL}}; + +static int py_global_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run_r", "pkg.a.R.save", NULL) + + ts_calls_to(s, project, "run_s", "pkg.a.R.save", NULL); + int kept = ts_calls_to(s, project, "run_a", "pkg.a.R.save", NULL); + int read = ts_calls_to(s, project, "run_p", "pkg.a.R.save", NULL); + printf(" python global rebinding (%s): rebound edges=%d, plain import=%d, global read=%d\n", + label, wrong, kept, read); + return !(wrong == 0 && kept == 1 && read == 1); +} + +TEST(type_scope_python_global_rebinding_takes_no_identity) { + return ts_twins("pyglobal", py_global_files, CBM_LANG_PYTHON, py_global_check); +} + /* `except ValueError as E` unbinds E when the clause * ends, and `D = Other; del D` leaves D unbound: methods defined after them * name the module's E and D (python3 agrees). A `del` after a method that saw @@ -2222,6 +2261,43 @@ TEST(type_scope_incremental_python_class_body_binding_matches_full) { PASS(); } +/* A function body edit (same lines) that declares the module's R `global` + * and binds it: the module's annotation `-> R` loses its identity. The + * function's global names are part of its stored row, so the run is not a + * one-file repair that keeps the caller's stale `run -> pkg.a.R.save`. */ +static int py_globaledit_before(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.a.R.save", NULL); + printf(" py global edit (%s): run -> pkg.a.R.save=%d\n", label, edge); + return edge != 1; +} + +static int py_globaledit_after(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.a.R.save", NULL); + printf(" py global edit (%s): run -> pkg.a.R.save=%d\n", label, edge); + return edge != 0; +} + +TEST(type_scope_incremental_python_global_binding_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a.py", "class R:\n def save(self):\n return 'a'\n"}, + {"pkg/b.py", "class R:\n def save(self):\n return 'b'\n"}, + {"pkg/mod.py", "from pkg.a import R\n\n\ndef setup():\n r = None\n from pkg.b import R\n\n\n" + "def make() -> R:\n return R()\n"}, + {"pkg/use.py", "from pkg.mod import make\n\n\ndef run():\n return make().save()\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"pkg/mod.py", "from pkg.a import R\n\n\ndef setup():\n global R\n from pkg.b import R\n\n\n" + "def make() -> R:\n return R()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_PYTHON, 0, edit, "py global binding", + py_globaledit_before, py_globaledit_after); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.before_bad, 0); + ASSERT_EQ(r.after_bad, 0); + PASS(); +} + SUITE(type_scope) { RUN_TEST(type_scope_import_binding_is_the_identity); RUN_TEST(type_scope_dotted_spelling_through_its_head); @@ -2243,6 +2319,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); RUN_TEST(type_scope_python_class_and_module_of_one_qn); + RUN_TEST(type_scope_python_global_rebinding_takes_no_identity); RUN_TEST(type_scope_python_unbound_class_names_are_the_module_names); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); @@ -2268,6 +2345,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_incremental_many_embedded_types_match_full); RUN_TEST(type_scope_incremental_many_fields_match_full); RUN_TEST(type_scope_incremental_python_class_body_binding_matches_full); + RUN_TEST(type_scope_incremental_python_global_binding_matches_full); RUN_TEST(type_scope_incremental_type_shape_changes_match_full); RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); RUN_TEST(type_scope_incremental_python_body_edits); From d2d4f02891620042107eb525d1123ff206adc020 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:37 +0100 Subject: [PATCH 21/25] fix(lsp): a Go local type shadows the package's type only in its block A type declared inside a function shadowed the package's type of that name for the rest of the whole function, so after the `if` block or outside the closure that declared it, a value of the package's type was typed unknown and its calls lost their edges. The walker now binds each type parameter and each local type name in its own lexical scope (the function, a block, a func literal) under a key no identifier can spell (`#T`), and a lookup asks the scope chain: a local type shadows from its declaration to the end of its block, as in Go. `go run` decides the new fixture (Block p1, Clo p2p1). Signed-off-by: Martin Vogel --- internal/cbm/lsp/go_lsp.c | 39 +++++++++++++++++++++++---------------- internal/cbm/lsp/go_lsp.h | 6 ++---- tests/test_type_scope.c | 29 +++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 20 deletions(-) diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index e8a5ebe41..dede34b93 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -133,24 +133,34 @@ static const CBMType *resolve_builtin_type(GoLSPContext *ctx, const char *name) * in its body are not the package's types of those names: `func F[T any](x T)` * and `func F() { type T struct{...}; var t T }` in a package with its own T. * The walker types such a name as unknown (it abstains) instead of the - * package-level type. A local type's scope starts at its declaration; one - * declared in an inner block shadows for the rest of the function (an - * abstention, never another answer). */ + * package-level type. Each one is bound in the walker's own lexical scope + * under a key no identifier can spell ("#T"), so it holds exactly where Go's + * does: a type parameter for the function, a local type from its declaration + * to the end of its block or closure. */ +#define GO_SHADOW_KEY_MAX 256 + +static bool go_shadow_key(const char *name, char *key) { + size_t n = name ? strlen(name) : 0; + if (n == 0 || n + 2 > GO_SHADOW_KEY_MAX) { + return false; + } + key[0] = '#'; + memcpy(key + 1, name, n + 1); + return true; +} + static bool go_type_shadowed(const GoLSPContext *ctx, const char *name) { - return ctx->shadow_types && name && cbm_ht_get(ctx->shadow_types, name) != NULL; + char key[GO_SHADOW_KEY_MAX]; + return go_shadow_key(name, key) && cbm_scope_contains(ctx->current_scope, key); } static void go_shadow_add(GoLSPContext *ctx, TSNode name_node) { char *name = ts_node_is_null(name_node) ? NULL : lsp_node_text(ctx, name_node); - if (!name || !name[0] || strcmp(name, "_") == 0) { + char key[GO_SHADOW_KEY_MAX]; + if (!name || strcmp(name, "_") == 0 || !go_shadow_key(name, key)) { return; } - if (!ctx->shadow_types) { - ctx->shadow_types = cbm_ht_create(16); - } - if (ctx->shadow_types && !cbm_ht_get(ctx->shadow_types, name)) { - cbm_ht_set(ctx->shadow_types, name, name); - } + cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, key), cbm_type_unknown()); } /* `[K comparable, V any]`: every name of every type_parameter_declaration. */ @@ -2211,10 +2221,9 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); // The function's type parameters (and its receiver's) shadow the - // package's types of those names, in its signature and its body. - CBMHashTable *saved_shadow = ctx->shadow_types; + // package's types of those names, in its signature and its body (bound in + // the function scope just pushed). bool saved_in_function = ctx->in_function; - ctx->shadow_types = NULL; ctx->in_function = true; go_shadow_type_params(ctx, ts_node_child_by_field_name(func_node, "type_parameters", 15)); if (strcmp(ts_node_type(func_node), "method_declaration") == 0) { @@ -2333,8 +2342,6 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { // Restore scope ctx->current_scope = saved_scope; - cbm_ht_free(ctx->shadow_types); /* NULL-safe */ - ctx->shadow_types = saved_shadow; ctx->in_function = saved_in_function; } diff --git a/internal/cbm/lsp/go_lsp.h b/internal/cbm/lsp/go_lsp.h index 751e13d95..ec7b04ea1 100644 --- a/internal/cbm/lsp/go_lsp.h +++ b/internal/cbm/lsp/go_lsp.h @@ -23,10 +23,8 @@ typedef struct { // Current function context const char* enclosing_func_qn; - // Type names the function being walked declares itself -- its type - // parameters (and its receiver's) and the local types declared so far: - // they never name the package's type of that name. NULL when none. - struct CBMHashTable* shadow_types; + // Walking a function body: a type declaration met there shadows the + // package's type of its name in the current block (go_shadow_add). bool in_function; const char* package_qn; // module QN for this file const char* rel_path; // repo-relative file path: init() QN suffix (#1910); NULL = flat diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 23f37ea87..87af52bc6 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -1672,6 +1672,34 @@ TEST(type_scope_go_function_declared_types_are_not_the_package_types) { return ts_twins("goshadow", go_shadowtype_files, CBM_LANG_GO, go_shadowtype_check); } +/* A local type declared in an inner block or in a + * closure shadows the package's type only there (Go's block scope): after the + * `if` block and outside the closure, `T` is the package's again, whose + * embedded p1.E promotes Hello (`go run`: Block p1, Clo p2p1). Inside the + * closure the local T (embedding p2.E) gets no package edge. */ +static const ts_file_t go_blocktype_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p2\" }\n"}, + {"m/t.go", "package m\n\nimport \"example.com/demo/p1\"\n\ntype T struct{ p1.E }\n"}, + {"m/use.go", "package m\n\nimport \"example.com/demo/p2\"\n\n" + "func Block(c bool) string {\n\tif c {\n\t\ttype T struct{ p2.E }\n\t\tvar t T\n" + "\t\t_ = t\n\t}\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func Clo() string {\n\tf := func() string {\n\t\ttype T struct{ p2.E }\n" + "\t\tvar t T\n\t\treturn t.Hello()\n\t}\n\tvar t T\n\treturn f() + t.Hello()\n}\n"}, + {NULL, NULL}}; + +static int go_blocktype_check(cbm_store_t *s, const char *project, const char *label) { + int block = ts_calls_to(s, project, "Block", "p1.E.Hello", NULL); + int clo = ts_calls_to(s, project, "Clo", "p1.E.Hello", NULL); + printf(" go block-local types (%s): Block p1=%d, Clo p1=%d\n", label, block, clo); + return !(block == 1 && clo == 1); +} + +TEST(type_scope_go_local_types_shadow_only_their_block) { + return ts_twins("goblock", go_blocktype_files, CBM_LANG_GO, go_blocktype_check); +} + /* Round 3, the 63-field limit beside N4: a struct of 66 named fields whose * last two are typed. Every route registers every field now. */ static const ts_file_t go_wide_files[] = { @@ -2335,6 +2363,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_go_promotion_takes_the_shallowest_depth); RUN_TEST(type_scope_go_embedded_field_names_are_fields); RUN_TEST(type_scope_go_function_declared_types_are_not_the_package_types); + RUN_TEST(type_scope_go_local_types_shadow_only_their_block); RUN_TEST(type_scope_go_embedded_text_work_grows_linearly); RUN_TEST(type_scope_go_struct_fields_have_no_limit); RUN_TEST(type_scope_incremental_caller_edit_per_file_go); From 28f20234c1487e68a30b5cdfa7f47d901cebd1e3 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:45 +0100 Subject: [PATCH 22/25] fix(lsp): an overloaded Python function whose declarations differ takes no identity A function declared with @overload is typed at a call by the overload its arguments select (scrapy's `response.replace(cls=HtmlResponse)` is an HtmlResponse); the implementation's annotation (`-> Response`) is the type of no call, and neither is any one overload's. A definition whose QN the file also declares with @overload (`overload`, `typing.overload`, `t.overload`) now takes no identity from its annotations when the definitions of that QN declare different return types, so main's answer stays; when they all declare the same one (sqlalchemy's Connection.execution_options, `-> Connection` throughout), every call has that type and the identity stays. python3 runs Text.css for the fixture's `replace(cls=Text)` and Response.css for `opts(a=1)`; a plain method of the same class keeps its identity. Signed-off-by: Martin Vogel --- src/pipeline/type_scope.c | 69 +++++++++++++++++++++++++++++++++++++-- tests/test_type_scope.c | 42 ++++++++++++++++++++++++ 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index ab5b6edd7..7f00c3eb0 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -80,12 +80,16 @@ static char g_nest_open_mark; static char g_nest_local_mark; static char g_bound_once_mark; static char g_bound_many_mark; +static char g_overload_mark; +static char g_overload_differ_mark; #define TYPE_SCOPE_BOUND_ONCE ((void *)&g_bound_once_mark) #define TYPE_SCOPE_BOUND_MANY ((void *)&g_bound_many_mark) #define TYPE_SCOPE_AMBIGUOUS ((void *)&g_ambiguous_mark) #define TYPE_SCOPE_MISS ((void *)&g_miss_mark) #define TYPE_SCOPE_NEST_OPEN ((void *)&g_nest_open_mark) /* module or class bodies only */ #define TYPE_SCOPE_NEST_LOCAL ((void *)&g_nest_local_mark) /* inside a function */ +#define TYPE_SCOPE_OVERLOAD ((void *)&g_overload_mark) /* declared with @overload */ +#define TYPE_SCOPE_OVERLOAD_DIFFER ((void *)&g_overload_differ_mark) struct cbm_type_scope_file { const cbm_type_scope_lang_t *lang; @@ -97,6 +101,8 @@ struct cbm_type_scope_file { /* lexical scopes only */ CBMHashTable *defs; /* file def QN -> index + 1 into scope.file_defs */ CBMHashTable *class_binds; /* "." a class body binds (not a def) */ + CBMHashTable *overloaded; /* QN some def declares with @overload -> the return text + * all its defs share, or TYPE_SCOPE_OVERLOAD_DIFFER */ CBMHashTable *tparams; /* every type parameter name the file declares */ CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */ CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */ @@ -195,15 +201,68 @@ static void type_scope_index_global_names(cbm_type_scope_file_t *f, const CBMDef } } +/* Whether a decorator's text is typing's @overload (`@overload`, + * `@typing.overload`, `@t.overload`). */ +static bool type_scope_overload_decorator(const char *text) { + while (text && (*text == '@' || *text == ' ' || *text == '\t')) { + text++; + } + if (!text || !*text) { + return false; + } + size_t len = strcspn(text, "( \t\r\n"); + const char *name = text; + for (size_t i = 0; i < len; i++) { + if (text[i] == '.') { + name = text + i + 1; + } + } + return (size_t)(text + len - name) == strlen("overload") && + memcmp(name, "overload", strlen("overload")) == 0; +} + +/* A function with @overload declarations: callers see the overloads, which + * pick the result from the arguments, so the implementation's annotations are + * not its type at a call, nor is any one overload's -- unless all of its + * definitions declare the same return type (whichever overload a call picks, + * that is the type). Where they differ its QN takes no identity. */ +static void type_scope_index_overload(cbm_type_scope_file_t *f, const CBMDefinition *d) { + for (int i = 0; d->decorators && d->decorators[i] && d->qualified_name; i++) { + TYPE_SCOPE_WORK(1); + if (type_scope_overload_decorator(d->decorators[i])) { + cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD); + return; + } + } +} + +/* Second pass: whether the definitions of each overloaded QN agree on the + * return type text (none counts as a text of its own). */ +static void type_scope_compare_overloads(cbm_type_scope_file_t *f) { + int n = cbm_ht_count(f->overloaded) ? f->scope.file_def_count : 0; + for (int i = 0; i < n; i++) { + const CBMDefinition *d = &f->scope.file_defs[i]; + void *seen = d->qualified_name ? cbm_ht_get(f->overloaded, d->qualified_name) : NULL; + const char *ret = d->return_type ? d->return_type : ""; + TYPE_SCOPE_WORK(strlen(ret) + 1); + if (seen == TYPE_SCOPE_OVERLOAD) { + cbm_ht_set(f->overloaded, d->qualified_name, (void *)ret); + } else if (seen && seen != TYPE_SCOPE_OVERLOAD_DIFFER && strcmp((const char *)seen, ret)) { + cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD_DIFFER); + } + } +} + /* Hash the file's own definitions, its type parameter names and the names * its class bodies bind. */ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { int n = f->scope.file_def_count; f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); f->class_binds = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); + f->overloaded = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); - if (!f->defs || !f->class_binds || !f->tparams || !f->nesting || + if (!f->defs || !f->class_binds || !f->overloaded || !f->tparams || !f->nesting || !type_scope_index_module_facts(f)) { return false; } @@ -215,6 +274,7 @@ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { } type_scope_index_class_bindings(f, d); type_scope_index_global_names(f, d); + type_scope_index_overload(f, d); for (const char *p = d->type_facts ? d->type_facts->type_params : NULL; p && *p;) { const char *bar = strchr(p, '|'); size_t len = bar ? (size_t)(bar - p) : strlen(p); @@ -226,6 +286,7 @@ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { p = bar ? bar + 1 : p + len; } } + type_scope_compare_overloads(f); return true; } @@ -276,6 +337,7 @@ void cbm_type_scope_file_end(cbm_type_scope_file_t *file) { cbm_ht_free(file->seen); cbm_ht_free(file->defs); cbm_ht_free(file->class_binds); + cbm_ht_free(file->overloaded); cbm_ht_free(file->tparams); cbm_ht_free(file->nesting); cbm_ht_free(file->bindings); @@ -696,8 +758,9 @@ void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPD * binding unknown names), and a def inside a function (it sees locals * the step cannot list): neither gets one. */ if (file->closed || !def->qualified_name || - type_scope_function_local(file, def->qualified_name)) { - return; + type_scope_function_local(file, def->qualified_name) || + cbm_ht_get(file->overloaded, def->qualified_name) == TYPE_SCOPE_OVERLOAD_DIFFER) { + return; /* (an overloaded function: type_scope_index_overload) */ } file->enclosing_class = type_scope_enclosing_class(file, def->qualified_name); } diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index 87af52bc6..fa519d536 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -989,6 +989,47 @@ TEST(type_scope_python_unbound_class_names_are_the_module_names) { return ts_twins("pyunbind", py_unbind_files, CBM_LANG_PYTHON, py_unbind_check); } +/* A method declared with @overload (the shape of scrapy's Response.replace). + * Callers see the overloads, which pick the result from the arguments + * (`replace(cls=Text)` is a Text, python3 runs Text.css); the + * implementation's `-> Response` is no call's type, so no identity is taken + * from any of its signatures. A plain method keeps its own (run_plain), and so + * does an overloaded one whose definitions all return Response (run_opts, the + * shape of sqlalchemy's Connection.execution_options). */ +static const ts_file_t py_overload_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/resp.py", "from __future__ import annotations\n\nfrom typing import Self, TypeVar, overload\n\n" + "T = TypeVar(\"T\", bound=\"Response\")\n\n\n" + "class Response:\n def css(self):\n return 'base'\n\n" + " @overload\n def replace(self, cls: type[T]) -> T: ...\n\n" + " @overload\n def replace(self, cls: None = None) -> Self: ...\n\n" + " def replace(self, cls=None) -> Response:\n" + " return (cls or type(self))()\n\n" + " @overload\n def opts(self, *, a: int) -> Response: ...\n\n" + " @overload\n def opts(self, **kw: int) -> Response: ...\n\n" + " def opts(self, **kw) -> Response:\n return Response()\n\n" + " def plain(self) -> Response:\n return Response()\n\n\n" + "class Text(Response):\n def css(self):\n return 'text'\n"}, + {"pkg/make.py", "from pkg.resp import Response\n\n\ndef make() -> Response:\n return Response()\n"}, + {"pkg/use.py", "from pkg.make import make\nfrom pkg.resp import Text\n\n\n" + "def run():\n return make().replace(cls=Text).css()\n\n\n" + "def run_plain():\n return make().plain().css()\n\n\n" + "def run_opts():\n return make().opts(a=1).css()\n"}, + {NULL, NULL}}; + +static int py_overload_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.resp.Response.css", NULL); + int plain = ts_calls_to(s, project, "run_plain", "pkg.resp.Response.css", NULL); + int agreed = ts_calls_to(s, project, "run_opts", "pkg.resp.Response.css", NULL); + printf(" python overloaded method (%s): run -> Response.css=%d, run_plain=%d, run_opts=%d\n", + label, wrong, plain, agreed); + return !(wrong == 0 && plain == 1 && agreed == 1); +} + +TEST(type_scope_python_overloaded_method_takes_no_identity) { + return ts_twins("pyoverload", py_overload_files, CBM_LANG_PYTHON, py_overload_check); +} + /* A struct's embedded-type text is built once, with one buffer: the * extractor's work for n embedded types is linear in n. */ static uint64_t ts_go_embedded_work(int n) { @@ -2349,6 +2390,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_python_class_and_module_of_one_qn); RUN_TEST(type_scope_python_global_rebinding_takes_no_identity); RUN_TEST(type_scope_python_unbound_class_names_are_the_module_names); + RUN_TEST(type_scope_python_overloaded_method_takes_no_identity); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); From accfcf6fa7b8f75044c76125b5f25e1369fb52c1 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 19:09:52 +0100 Subject: [PATCH 23/25] fix(lsp): an overload decorator imported under another name `from typing import overload as ovl` followed by `@ovl` was not recognised as @overload (the decorator's last dotted name is matched against `overload`), so the implementation's return annotation still gave the call its type: `make().replace(cls=AliasText).css()` drew Alias.css where python3 runs AliasText.css. A plain decorator name now also counts when the module's imports bind it to typing's or typing_extensions' overload (the module's namespace facts, `from ... import overload as X`); `@typing.overload`, `@tp.overload` and `@overload` match as before. A method of the same class under an ordinary decorator keeps its identity. Signed-off-by: Martin Vogel --- src/pipeline/type_scope.c | 48 ++++++++++++++++++++++++++++++++------- tests/test_type_scope.c | 38 +++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c index 7f00c3eb0..ed840cb69 100644 --- a/src/pipeline/type_scope.c +++ b/src/pipeline/type_scope.c @@ -90,6 +90,7 @@ static char g_overload_differ_mark; #define TYPE_SCOPE_NEST_LOCAL ((void *)&g_nest_local_mark) /* inside a function */ #define TYPE_SCOPE_OVERLOAD ((void *)&g_overload_mark) /* declared with @overload */ #define TYPE_SCOPE_OVERLOAD_DIFFER ((void *)&g_overload_differ_mark) +#define TYPE_SCOPE_ALIAS_MAX 256 /* a decorator name read through the imports */ struct cbm_type_scope_file { const cbm_type_scope_lang_t *lang; @@ -103,6 +104,8 @@ struct cbm_type_scope_file { CBMHashTable *class_binds; /* "." a class body binds (not a def) */ CBMHashTable *overloaded; /* QN some def declares with @overload -> the return text * all its defs share, or TYPE_SCOPE_OVERLOAD_DIFFER */ + CBMHashTable *ovl_alias; /* local name a module-level `from typing import overload + * as X` binds */ CBMHashTable *tparams; /* every type parameter name the file declares */ CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */ CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */ @@ -201,9 +204,26 @@ static void type_scope_index_global_names(cbm_type_scope_file_t *f, const CBMDef } } -/* Whether a decorator's text is typing's @overload (`@overload`, - * `@typing.overload`, `@t.overload`). */ -static bool type_scope_overload_decorator(const char *text) { +/* The local names the module's imports bind to typing's overload under another + * name (`from typing import overload as ovl`, typing_extensions too). */ +static void type_scope_index_ovl_alias(cbm_type_scope_file_t *f) { + const CBMPyNamespaceFacts *facts = f->scope.module_facts; + for (int i = 0; facts && i < facts->count; i++) { + const CBMPyNamespaceFact *x = &facts->items[i]; + TYPE_SCOPE_WORK(1); + if (x->kind == CBM_PY_NS_IMPORT_NAME && x->relative_level == 0 && x->local_name && + x->module_name && x->member_name && strcmp(x->member_name, "overload") == 0 && + (strcmp(x->module_name, "typing") == 0 || + strcmp(x->module_name, "typing_extensions") == 0)) { + cbm_ht_set(f->ovl_alias, x->local_name, (void *)x->local_name); + } + } +} + +/* Whether a decorator's text is typing's @overload: its last dotted name is + * `overload` (`@overload`, `@typing.overload`, `@t.overload`), or it is a + * plain name the module imports as typing's overload (`@ovl`). */ +static bool type_scope_overload_decorator(const cbm_type_scope_file_t *f, const char *text) { while (text && (*text == '@' || *text == ' ' || *text == '\t')) { text++; } @@ -217,8 +237,17 @@ static bool type_scope_overload_decorator(const char *text) { name = text + i + 1; } } - return (size_t)(text + len - name) == strlen("overload") && - memcmp(name, "overload", strlen("overload")) == 0; + if ((size_t)(text + len - name) == strlen("overload") && + memcmp(name, "overload", strlen("overload")) == 0) { + return true; + } + char local[TYPE_SCOPE_ALIAS_MAX]; + if (name != text || len >= sizeof(local) || cbm_ht_count(f->ovl_alias) == 0) { + return false; + } + memcpy(local, text, len); + local[len] = '\0'; + return cbm_ht_get(f->ovl_alias, local) != NULL; } /* A function with @overload declarations: callers see the overloads, which @@ -229,7 +258,7 @@ static bool type_scope_overload_decorator(const char *text) { static void type_scope_index_overload(cbm_type_scope_file_t *f, const CBMDefinition *d) { for (int i = 0; d->decorators && d->decorators[i] && d->qualified_name; i++) { TYPE_SCOPE_WORK(1); - if (type_scope_overload_decorator(d->decorators[i])) { + if (type_scope_overload_decorator(f, d->decorators[i])) { cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD); return; } @@ -260,12 +289,14 @@ static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) { f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); f->class_binds = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->overloaded = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); + f->ovl_alias = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8); f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1)); - if (!f->defs || !f->class_binds || !f->overloaded || !f->tparams || !f->nesting || - !type_scope_index_module_facts(f)) { + if (!f->defs || !f->class_binds || !f->overloaded || !f->ovl_alias || !f->tparams || + !f->nesting || !type_scope_index_module_facts(f)) { return false; } + type_scope_index_ovl_alias(f); for (int i = 0; i < n; i++) { const CBMDefinition *d = &f->scope.file_defs[i]; if (d->qualified_name && !cbm_ht_get(f->defs, d->qualified_name)) { @@ -338,6 +369,7 @@ void cbm_type_scope_file_end(cbm_type_scope_file_t *file) { cbm_ht_free(file->defs); cbm_ht_free(file->class_binds); cbm_ht_free(file->overloaded); + cbm_ht_free(file->ovl_alias); cbm_ht_free(file->tparams); cbm_ht_free(file->nesting); cbm_ht_free(file->bindings); diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c index fa519d536..ad7f7fc6a 100644 --- a/tests/test_type_scope.c +++ b/tests/test_type_scope.c @@ -1030,6 +1030,43 @@ TEST(type_scope_python_overloaded_method_takes_no_identity) { return ts_twins("pyoverload", py_overload_files, CBM_LANG_PYTHON, py_overload_check); } +/* The same through an import under another name (`from typing import + * overload as ovl`, `@ovl`): the name is read through the module's imports + * (python3: `replace(cls=AliasText)` runs AliasText.css). A method of the + * same class under a plain decorator keeps its identity (run_kept, python3 + * Alias.css). */ +static const ts_file_t py_overload_alias_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/resp.py", "from __future__ import annotations\n\nfrom typing import Self, TypeVar\n" + "from typing import overload as ovl\n\n" + "T = TypeVar(\"T\", bound=\"Alias\")\n\n\n" + "def keep(fn):\n return fn\n\n\n" + "class Alias:\n def css(self):\n return 'alias'\n\n" + " @ovl\n def replace(self, cls: type[T]) -> T: ...\n\n" + " @ovl\n def replace(self, cls: None = None) -> Self: ...\n\n" + " def replace(self, cls=None) -> Alias:\n" + " return (cls or type(self))()\n\n" + " @keep\n def kept(self) -> Alias:\n return Alias()\n\n\n" + "class AliasText(Alias):\n def css(self):\n return 'text'\n"}, + {"pkg/make.py", "from pkg.resp import Alias\n\n\ndef make() -> Alias:\n return Alias()\n"}, + {"pkg/use.py", "from pkg.make import make\nfrom pkg.resp import AliasText\n\n\n" + "def run_alias():\n return make().replace(cls=AliasText).css()\n\n\n" + "def run_kept():\n return make().kept().css()\n"}, + {NULL, NULL}}; + +static int py_overload_alias_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run_alias", "pkg.resp.Alias.css", NULL); + int kept = ts_calls_to(s, project, "run_kept", "pkg.resp.Alias.css", NULL); + printf(" python overload under another name (%s): run_alias -> Alias.css=%d, run_kept=%d\n", + label, wrong, kept); + return !(wrong == 0 && kept == 1); +} + +TEST(type_scope_python_overload_imported_under_another_name) { + return ts_twins("pyovlalias", py_overload_alias_files, CBM_LANG_PYTHON, + py_overload_alias_check); +} + /* A struct's embedded-type text is built once, with one buffer: the * extractor's work for n embedded types is linear in n. */ static uint64_t ts_go_embedded_work(int n) { @@ -2391,6 +2428,7 @@ SUITE(type_scope) { RUN_TEST(type_scope_python_global_rebinding_takes_no_identity); RUN_TEST(type_scope_python_unbound_class_names_are_the_module_names); RUN_TEST(type_scope_python_overloaded_method_takes_no_identity); + RUN_TEST(type_scope_python_overload_imported_under_another_name); RUN_TEST(type_scope_python_self_chain_keeps_its_edges); RUN_TEST(type_scope_python_type_parameter_is_no_import); RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); From 6d80cce23c69a673c027e1435383afec8ad5fbe9 Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 21:04:57 +0100 Subject: [PATCH 24/25] test: stop hashing the test runner in the copied-image and install tests The daemon_runtime copied-image probes and the CLI install/update tests made full SHA-256 passes over the sanitized test runner (about 520 MB on macOS arm64, about 790 MB on hosted x86) or over copies of it: about 10 passes per daemon_runtime run and 66 passes plus 31 staged, fsync'd copies in the cli suite. On hosted x86 jobs that draw an Intel Xeon runner one pass takes 70-95 s (1-3 s on AMD EPYC), so the copied-image probes ran out of their 60 s budget and the cli suite ran past its 3600 s wall clock: the verdict depended on the CPU the job drew. A small dedicated executable, the image probe, now takes the runner's place in those tests. It links only the daemon runtime, the foundation layer and mimalloc (about 2 MB) and carries the roles the tests need (serve, the HELLO and activation clients, --version for installs); the role code moved from tests/test_main.c. Makefile.cbm builds -image-probe beside each runner flavour with that flavour's flags as an order-only prerequisite of the runner, leaving out workspace.c and slab_alloc.c, which serve the indexer. The copied-image tests run the daemon from the probe and the clients from identical or changed copies of it; the install tests stage and publish the probe through the existing self-path seam. Production verification is unchanged. macOS arm64 ASan/UBSan: runner 518,227,624 bytes, probe 1,981,480 bytes; daemon_runtime, daemon_bootstrap, daemon_frontend, cli, activation_transaction and agent_clients: 575 passed, 1 skipped, 1 host-specific failure that also fails on main here; contracts pass. Signed-off-by: Martin Vogel --- Makefile.cbm | 32 ++- tests/image_probe_main.c | 56 ++++ tests/image_probe_roles.c | 342 +++++++++++++++++++++++ tests/test_cli.c | 60 ++-- tests/test_daemon_runtime.c | 526 ++++++++++++++++++++++++++++++------ tests/test_image_probe.h | 104 +++++++ tests/test_main.c | 145 +--------- 7 files changed, 1026 insertions(+), 239 deletions(-) create mode 100644 tests/image_probe_main.c create mode 100644 tests/image_probe_roles.c create mode 100644 tests/test_image_probe.h diff --git a/Makefile.cbm b/Makefile.cbm index 66cccffe2..dbe08e8e4 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -848,7 +848,8 @@ TEST_DAEMON_SRCS = \ tests/test_daemon_application.c \ tests/test_daemon_frontend.c \ tests/test_daemon_bootstrap.c \ - tests/test_daemon_ipc.c + tests/test_daemon_ipc.c \ + tests/image_probe_roles.c TEST_DISCOVER_SRCS = \ tests/test_language.c \ @@ -1213,7 +1214,32 @@ $(UNIXCODER_OBJ): $(UNIXCODER_BLOB_SRC) vendored/nomic/code_vectors.bin | $(BUIL OBJS_VENDORED_TEST = $(MIMALLOC_OBJ_TEST) $(SQLITE3_OBJ_TEST) $(TRE_OBJ_TEST) $(GRAMMAR_OBJS_TEST) $(TS_RUNTIME_OBJ_TEST) $(LSP_OBJ_TEST) $(PP_OBJ_TEST) $(LZ4_OBJ_TEST) $(ZSTD_OBJ_TEST) $(UNIXCODER_OBJ) OBJS_VENDORED_TSAN = $(MIMALLOC_OBJ_TSAN) $(SQLITE3_OBJ_TSAN) $(TRE_OBJ_TSAN) $(GRAMMAR_OBJS_TSAN) $(TS_RUNTIME_OBJ_TSAN) $(LSP_OBJ_TSAN) $(PP_OBJ_TSAN) $(LZ4_OBJ_TSAN) $(ZSTD_OBJ_TSAN) $(UNIXCODER_OBJ) -$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) +# ── Image probe (tests/test_image_probe.h) ────────────────────── +# The small executable that copied-image and install tests run or publish +# instead of a copy of the runner: the daemon runtime, foundation and the probe +# roles, ~5 MB against ~800 MB for the sanitized runner, every full SHA-256 of +# which costs 70-95 s on some hosted x86 CPUs. One beside each runner flavour, +# built with that flavour's flags and found by the runner's own name +# (-image-probe), so every venue that builds a runner builds its probe: +# each runner rule lists its probe as an order-only prerequisite. Coverage +# instrumentation stays out: the probe's profile must never land in the +# per-test profile of the runner that started it. +# workspace.c (needs mcp.c's path check) and slab_alloc.c (needs the tree-sitter +# runtime) serve the indexer, not the daemon runtime, so the probe leaves them out. +IMAGE_PROBE_FOUNDATION_SRCS = $(filter-out src/foundation/workspace.c src/foundation/slab_alloc.c,$(FOUNDATION_SRCS)) +IMAGE_PROBE_SRCS = tests/image_probe_main.c tests/image_probe_roles.c \ + src/daemon/daemon.c src/daemon/ipc.c src/daemon/runtime.c \ + src/daemon/service.c $(IMAGE_PROBE_FOUNDATION_SRCS) +CFLAGS_IMAGE_PROBE = $(filter-out $(TEST_COVERAGE_FLAGS) $(TEST_COVERAGE_DEFINE),$(CFLAGS_TEST)) + +$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(CFLAGS_IMAGE_PROBE) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) \ + $(LDFLAGS_TEST) + +$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(CFLAGS_TSAN) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(LDFLAGS_TSAN) + +$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-image-probe $(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \ $(ALL_TEST_SRCS) $(PROD_SRCS) \ $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ @@ -1301,7 +1327,7 @@ TSAN_OPTIONS ?= halt_on_error=1:report_thread_leaks=0 # Normal ASan/native/soak paths remain uncapped. High-worker TSan diagnostics # invoke test-runner-tsan directly so release gates cannot drift accidentally. -$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) +$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-tsan-image-probe $(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -o $@ \ $(ALL_TEST_SRCS) $(PROD_SRCS) \ $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \ diff --git a/tests/image_probe_main.c b/tests/image_probe_main.c new file mode 100644 index 000000000..636e789fd --- /dev/null +++ b/tests/image_probe_main.c @@ -0,0 +1,56 @@ +/* + * image_probe_main.c — entry point of the image probe (tests/test_image_probe.h), + * the small executable that copied-image and install tests run instead of the + * test runner. Its roles live in tests/image_probe_roles.c. + */ +#include "test_image_probe.h" + +#include +#include + +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) +#define PROBE_MSAN_MIMALLOC_OUTPUT 1 +#endif +#endif + +#ifdef PROBE_MSAN_MIMALLOC_OUTPUT +#include +#include + +/* MSan lane only, exactly as the runner's tf_msan_mi_output (tests/test_main.c): + * mimalloc is uninstrumented there, so text it formats on its own stack must + * be marked initialized before it reaches an MSan interceptor. */ +static bool probe_msan_mi_output_live; + +static void probe_msan_mi_output(const char *msg, void *arg) { + (void)arg; + if (!probe_msan_mi_output_live || !msg) { + return; + } + __msan_unpoison_string(msg); + if (!msg[0]) { + return; + } + (void)fputs(msg, stderr); +} +#endif + +int main(int argc, char **argv) { +#ifdef PROBE_MSAN_MIMALLOC_OUTPUT + mi_register_output(probe_msan_mi_output, NULL); + probe_msan_mi_output_live = true; +#endif + /* An install verifies the candidate it staged by running it with + * --version (src/cli/cli.c); the probe stands in for that binary. */ + if (argc == 2 && strcmp(argv[1], "--version") == 0) { + (void)puts("codebase-memory-mcp test image probe"); + return 0; + } + int role_rc = tf_image_probe_dispatch(argc, argv); + if (role_rc >= 0) { + return role_rc; + } + (void)fprintf(stderr, "image probe: no role named by argv[1] (tests/test_image_probe.h)\n"); + return 2; +} diff --git a/tests/image_probe_roles.c b/tests/image_probe_roles.c new file mode 100644 index 000000000..918b504ef --- /dev/null +++ b/tests/image_probe_roles.c @@ -0,0 +1,342 @@ +/* + * image_probe_roles.c — the roles of the image probe (tests/test_image_probe.h). + * + * Linked into the probe (tests/image_probe_main.c) and into the test runner. + * The runner dispatches only the image holder from here (daemon_runtime's + * own-image cache test spawns the runner itself); its role table in + * tests/test_main.c names every other literal too, so that the test-impact + * engine still maps a change these roles reach to the tests that start them. + * Every role is called directly from tf_image_probe_dispatch for the same + * reason: a call edge, not a function-pointer table, links them. + * + * Exit codes: 0 success; 24/25 holder failures; 26 the daemon ANSWERED a HELLO + * and refused it; 27 the HELLO session did not close; 28 the macOS mapping + * failed; 29 the daemon answered an activation request and refused it; 30/31 a + * HELLO/activation that got no answer inside the exchange budget (a slow peer + * hash fails as itself, never as a refusal); 32 bad serve arguments; 33 the + * served daemon did not start; 34 its teardown failed. + */ +#include "test_image_probe.h" +#include "test_daemon_runtime_contract.h" + +#include "daemon/daemon.h" +#include "daemon/ipc.h" +#include "daemon/runtime.h" +#include "foundation/compat.h" + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#else +#include +#ifdef __APPLE__ +#include +#include +#endif +#endif + +enum { + /* The in-process daemon_runtime fixture's bounds (RUNTIME_TEST_TIMEOUT_MS, + * RUNTIME_TEST_CLEANUP_TIMEOUT_MS, RUNTIME_TEST_CLEANUP_FREE_ATTEMPTS): + * the served daemon behaves exactly like that fixture's. */ + PROBE_TIMEOUT_MS = 2000, + PROBE_CLEANUP_TIMEOUT_MS = 60000, + PROBE_CLEANUP_FREE_ATTEMPTS = 3, + PROBE_PATH_CAP = 1024, +}; + +static uint64_t probe_process_id(void) { +#ifdef _WIN32 + return (uint64_t)GetCurrentProcessId(); +#else + return (uint64_t)getpid(); +#endif +} + +static int probe_role_holder(int argc, char **argv) { +#ifdef _WIN32 + if (argc != 3) { + return -1; + } + HANDLE ready = OpenEventA(EVENT_MODIFY_STATE, FALSE, argv[2]); + bool announced = ready && SetEvent(ready) != 0; + if (ready) { + (void)CloseHandle(ready); + } + if (!announced) { + return 24; + } + Sleep(INFINITE); + return 25; +#else + /* POSIX copied-image holder: block reading stdin until the parent closes + * the release pipe, exactly like the cat(1) donor this replaced. A system + * utility cannot serve as the copied image — a multi-call coreutils + * binary (uutils cat) refuses to execute under the copied name. */ + (void)argv; + if (argc != 2) { + return -1; + } + char release[16]; + ssize_t count; + do { + count = read(STDIN_FILENO, release, sizeof(release)); + } while (count > 0 || (count < 0 && errno == EINTR)); + return count == 0 ? 0 : 25; +#endif +} + +/* Real copied-image HELLO probe: the daemon authenticates and fingerprints an + * ordinary, separately executed process image; no production-only hook. */ +static int probe_role_hello(int argc, char **argv) { + if (argc != 6) { + return -1; + } + cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]); + cbm_daemon_build_identity_t identity = { + .semantic_version = argv[4], + .build_fingerprint = argv[5], + }; + cbm_daemon_runtime_connect_result_t result; + memset(&result, 0, sizeof(result)); + cbm_daemon_runtime_client_t *client = + endpoint ? cbm_daemon_runtime_client_connect(endpoint, &identity, + TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result) + : NULL; + bool accepted = client && result.status == CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED && + result.hello_status == CBM_DAEMON_HELLO_COMPATIBLE; + bool closed = + !client || cbm_daemon_runtime_client_close(client, TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS); + cbm_daemon_ipc_endpoint_free(endpoint); + if (!accepted) { + /* 26 only when the daemon ANSWERED and refused. No answer inside the + * exchange budget (the daemon still hashing this copy, or I/O) is 30: + * a slow peer-image hash must fail loudly as itself, never satisfy a + * rejection assertion by timing out. */ + return result.status == CBM_DAEMON_RUNTIME_CONNECT_ERROR ? 30 : 26; + } + return closed ? 0 : 27; +} + +/* Real copied-image activation probe. The request identity is supplied by the + * executing copy so the daemon must authenticate that peer image rather than + * require the active generation's build fingerprint. */ +static int probe_role_activation(int argc, char **argv) { + if (argc != 7) { + return -1; + } + char *action_end = NULL; + unsigned long action_value = strtoul(argv[6], &action_end, 10); + bool action_valid = action_end != argv[6] && *action_end == '\0' && + action_value >= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL && + action_value <= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL; + cbm_daemon_ipc_endpoint_t *endpoint = + action_valid ? cbm_daemon_ipc_endpoint_new(argv[3], argv[2]) : NULL; + cbm_daemon_build_identity_t identity = { + .semantic_version = argv[4], + .build_fingerprint = argv[5], + }; + cbm_daemon_runtime_activation_result_t result; + memset(&result, 0, sizeof(result)); + bool exchanged = + endpoint && cbm_daemon_runtime_request_activation_shutdown( + endpoint, &identity, (cbm_daemon_runtime_activation_action_t)action_value, + TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result); + cbm_daemon_ipc_endpoint_free(endpoint); + if (!exchanged) { + return 31; /* no answer inside the exchange budget; see the HELLO probe */ + } + return result.accepted ? 0 : 29; +} + +/* macOS adversarial HELLO probe: execute this mode from a foreign process + * image while mapping the genuine daemon image RX. The daemon must + * authenticate the main image, not merely find its own vnode in an arbitrary + * executable map. */ +static int probe_role_mapped_hello(int argc, char **argv) { +#ifdef __APPLE__ + if (argc != 7) { + return -1; + } + int image_fd = open(argv[2], O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + void *mapping = + image_fd >= 0 ? mmap(NULL, 1, PROT_READ | PROT_EXEC, MAP_PRIVATE, image_fd, 0) : MAP_FAILED; + bool mapped = mapping != MAP_FAILED; + if (image_fd >= 0 && close(image_fd) != 0) { + mapped = false; + } + if (!mapped) { + if (mapping != MAP_FAILED) { + (void)munmap(mapping, 1); + } + return 28; + } + + char *hello_argv[] = {argv[0], "__cbm_runtime_hello_client", argv[3], argv[4], argv[5], + argv[6]}; + int result = probe_role_hello(6, hello_argv); + if (munmap(mapping, 1) != 0) { + return 28; + } + return result >= 0 ? result : 28; +#else + (void)argc; + (void)argv; + return -1; +#endif +} + +static void probe_reply(const char *line) { + (void)fputs(line, stdout); + (void)fputc('\n', stdout); + (void)fflush(stdout); +} + +/* The daemon of the copied-image tests, running from THIS image: + * __cbm_runtime_serve + * A runtime service starts only with its own image's fingerprint as identity, + * so a daemon whose peers are copies of this probe must run here, not in the + * runner. The configuration is the in-process daemon_runtime fixture's + * (runtime_test_fixture_start, ABIs of runtime_test_identity), and with owner 1 + * a committed session of the active image is held in this process, like that + * fixture's in-process owner client. + * + * One line answers each step on stdout; commands arrive on stdin, one byte: + * start "ready " or "failed " + * 'i' "1" when the held owner session was interrupted (its heartbeat + * fails), else "0" + * 'x' closes the owner session, then "1" when the service has exited by + * itself within the fixture's bound, else "0" + * EOF the runner's release: stop what still runs, free it, exit. + * No step waits on a clock of its own: every bound is the runtime API's, and + * the runner closing stdin ends the role. */ +static int probe_role_serve(int argc, char **argv) { + if (argc != 6 || (strcmp(argv[5], "0") != 0 && strcmp(argv[5], "1") != 0)) { + return 32; + } +#ifdef _WIN32 + /* Exact bytes both ways: no CRLF translation on the protocol pipes. */ + (void)_setmode(_fileno(stdin), _O_BINARY); + (void)_setmode(_fileno(stdout), _O_BINARY); +#endif + bool with_owner = argv[5][0] == '1'; + char build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; + char log_path[PROBE_PATH_CAP]; + int log_written = snprintf(log_path, sizeof(log_path), "%s/conflicts.ndjson", argv[2]); + cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]); + const char *failed = NULL; + if (log_written <= 0 || log_written >= (int)sizeof(log_path)) { + failed = "conflict-log-path"; + } else if (!endpoint) { + failed = "endpoint"; + } else if (!cbm_daemon_runtime_process_build_fingerprint(probe_process_id(), build)) { + failed = "own-image-fingerprint"; + } + cbm_daemon_build_identity_t identity = { + .semantic_version = argv[4], + .build_fingerprint = build, + .protocol_abi = 3, + .store_abi = 11, + .feature_abi = 7, + }; + cbm_daemon_runtime_service_t *service = NULL; + if (!failed) { + cbm_daemon_runtime_service_config_t config = { + .endpoint = endpoint, + .identity = identity, + .conflict_log_path = log_path, + .conflict_log_cap_bytes = 64U * 1024U, + .max_clients = 8, + .lease_timeout_ms = 5000, + .request_timeout_ms = PROBE_TIMEOUT_MS, + .shutdown_timeout_ms = PROBE_TIMEOUT_MS, + }; + service = cbm_daemon_runtime_service_start(&config); + if (!service || + cbm_daemon_runtime_service_state(service) != CBM_DAEMON_RUNTIME_SERVICE_RUNNING) { + failed = "service-start"; + } + } + cbm_daemon_runtime_client_t *owner = NULL; + if (!failed && with_owner) { + cbm_daemon_runtime_connect_result_t result; + memset(&result, 0, sizeof(result)); + owner = cbm_daemon_runtime_client_connect(endpoint, &identity, PROBE_TIMEOUT_MS, &result); + if (!owner || result.status != CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED) { + failed = "owner-connect"; + } + } + char line[CBM_DAEMON_BUILD_FINGERPRINT_SIZE + 16]; + (void)snprintf(line, sizeof(line), "%s %s", failed ? "failed" : "ready", + failed ? failed : build); + probe_reply(line); + + for (int command = failed ? EOF : getchar(); command != EOF; command = getchar()) { + if (command == 'i') { + bool interrupted = + owner && !cbm_daemon_runtime_client_heartbeat(owner, PROBE_TIMEOUT_MS); + probe_reply(interrupted ? "1" : "0"); + } else if (command == 'x') { + if (owner) { + (void)cbm_daemon_runtime_client_close(owner, PROBE_TIMEOUT_MS); + owner = NULL; + } + probe_reply(cbm_daemon_runtime_service_wait_exited(service, PROBE_TIMEOUT_MS) ? "1" + : "0"); + } + } + + if (owner) { + (void)cbm_daemon_runtime_client_close(owner, PROBE_TIMEOUT_MS); + } + bool freed = service == NULL; + if (service) { + /* runtime_test_fixture_finish's teardown, unchanged. */ + bool stopped = + cbm_daemon_runtime_service_state(service) == CBM_DAEMON_RUNTIME_SERVICE_EXITED || + cbm_daemon_runtime_service_stop(service, PROBE_CLEANUP_TIMEOUT_MS); + for (int attempt = 0; stopped && !freed && attempt < PROBE_CLEANUP_FREE_ATTEMPTS; + attempt++) { + freed = cbm_daemon_runtime_service_free(service); + if (!freed) { + cbm_usleep(1000); + } + } + } + cbm_daemon_ipc_endpoint_free(endpoint); + if (failed) { + return 33; + } + return freed ? 0 : 34; +} + +int tf_image_probe_dispatch(int argc, char **argv) { + if (argc < 2 || !argv || !argv[1]) { + return -1; + } + const char *role = argv[1]; + if (strcmp(role, "__cbm_runtime_image_holder") == 0) { + return probe_role_holder(argc, argv); + } + if (strcmp(role, "__cbm_runtime_serve") == 0) { + return probe_role_serve(argc, argv); + } + if (strcmp(role, "__cbm_runtime_hello_client") == 0) { + return probe_role_hello(argc, argv); + } + if (strcmp(role, "__cbm_runtime_activation_client") == 0) { + return probe_role_activation(argc, argv); + } + if (strcmp(role, "__cbm_runtime_mapped_hello_client") == 0) { + return probe_role_mapped_hello(argc, argv); + } + return -1; +} diff --git a/tests/test_cli.c b/tests/test_cli.c index df0a289d2..478740313 100644 --- a/tests/test_cli.c +++ b/tests/test_cli.c @@ -13,6 +13,7 @@ #include "../src/foundation/compat_thread.h" #include "test_framework.h" #include "test_helpers.h" +#include "test_image_probe.h" #include #include #include @@ -917,6 +918,25 @@ static int cli_test_cmd_install(int argc, char **argv) { return cli_test_cmd_dispatch(cbm_cmd_install, argc, argv); } +/* An install whose running binary is the image probe (tests/test_image_probe.h), + * not this runner. These tests need a real executable to stage, verify (it is + * run with --version) and publish, never this one: each install of the ~800 MB + * sanitized runner made up to five full SHA-256 passes and two fsync'd staged + * copies of it, and one such hash costs 70-95 s on some hosted x86 CPUs. -1, + * said on stderr, when the probe was not built. */ +static int cli_test_cmd_install_probe(int argc, char **argv) { + static char probe[1024]; + if (!probe[0] && !th_image_probe_path(probe, sizeof(probe))) { + (void)fprintf(stderr, "cli: no image probe beside this runner; it is built with the " + "runner (Makefile.cbm, -image-probe)\n"); + return -1; + } + cbm_cli_set_self_path_override_for_test(probe); + int rc = cli_test_cmd_install(argc, argv); + cbm_cli_set_self_path_override_for_test(NULL); + return rc; +} + static int cli_test_cmd_uninstall(int argc, char **argv) { return cli_test_cmd_dispatch(cbm_cmd_uninstall, argc, argv); } @@ -1430,7 +1450,7 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) { char dir_arg[640]; snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", install_dir); char *install_argv[] = {"--force", "--skip-config", "--yes", dir_arg}; - int install_rc = child_ready ? cli_test_cmd_install(4, install_argv) : -1; + int install_rc = child_ready ? cli_test_cmd_install_probe(4, install_argv) : -1; close(install_done_pipe[1]); /* the child's watch ends here at the latest */ cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent); cbm_set_auto_answer_for_test(0); @@ -1541,7 +1561,7 @@ TEST(cli_install_recovers_markerless_stale_rendezvous) { char dir_arg[640]; snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", install_dir); char *install_argv[] = {"--force", "--skip-config", "--yes", dir_arg}; - int install_rc = orphan_created ? cli_test_cmd_install(4, install_argv) : -1; + int install_rc = orphan_created ? cli_test_cmd_install_probe(4, install_argv) : -1; cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent); cbm_set_auto_answer_for_test(0); @@ -1951,7 +1971,7 @@ static int cli_scope_install(cli_scope_fixture_t *fixture, const char *home, con snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir); char *install_argv[] = {skip_binary ? "--skip-binary" : "--force", "--skip-config", "--yes", dir_arg}; - int rc = cli_test_cmd_install(4, install_argv); + int rc = cli_test_cmd_install_probe(4, install_argv); cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent); cbm_set_auto_answer_for_test(0); return rc; @@ -2375,7 +2395,7 @@ TEST(cli_install_force_quiesces_active_cohort_before_replacing_binary) { cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); char *argv[] = {"--force"}; - int rc = cli_test_cmd_install(1, argv); + int rc = cli_test_cmd_install_probe(1, argv); cbm_cli_set_activation_ops_for_test(NULL); const char *installed = read_test_file(bin_target); @@ -2427,11 +2447,11 @@ TEST(cli_install_dir_and_skip_config_stage_first_install_safely) { cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); char *argv[] = {"--force", "--skip-config", "--yes", "--dir", install_dir}; - int rc = cli_test_cmd_install(5, argv); + int rc = cli_test_cmd_install_probe(5, argv); char equals_arg[640]; snprintf(equals_arg, sizeof(equals_arg), "--dir=%s", install_dir); char *dry_argv[] = {"--force", "--skip-config", "--dry-run", equals_arg}; - int dry_rc = cli_test_cmd_install(4, dry_argv); + int dry_rc = cli_test_cmd_install_probe(4, dry_argv); cbm_cli_set_activation_ops_for_test(NULL); cbm_set_auto_answer_for_test(0); @@ -2835,12 +2855,12 @@ TEST(cli_no_hooks_removes_codex_pretool_hook) { size_t owned = 0U; size_t foreign = 0U; char *default_args[] = {"--skip-binary", "--clients=codex", "--yes"}; - int default_rc = cli_test_cmd_install(3, default_args); + int default_rc = cli_test_cmd_install_probe(3, default_args); test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign); bool default_json = default_rc == 0 && owned == 1U && foreign == 1U; char *no_hooks_args[] = {"--no-hooks", "--skip-binary", "--clients=codex", "--yes"}; - int no_hooks_rc = cli_test_cmd_install(4, no_hooks_args); + int no_hooks_rc = cli_test_cmd_install_probe(4, no_hooks_args); test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign); char *json_state = read_test_file_alloc(hooks_path); char *toml_state = read_test_file_alloc(config_path); @@ -2851,26 +2871,26 @@ TEST(cli_no_hooks_removes_codex_pretool_hook) { free(json_state); free(toml_state); - int bare_rc = cli_test_cmd_install(3, default_args); + int bare_rc = cli_test_cmd_install_probe(3, default_args); test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign); bool bare_disabled = bare_rc == 0 && owned == 0U && foreign == 1U; /* Without hooks.json the config.toml managed block carries the hooks. */ (void)remove(hooks_path); char *hooks_args[] = {"--hooks", "--skip-binary", "--clients=codex", "--yes"}; - int toml_enable_rc = cli_test_cmd_install(4, hooks_args); + int toml_enable_rc = cli_test_cmd_install_probe(4, hooks_args); toml_state = read_test_file_alloc(config_path); bool toml_enabled = toml_enable_rc == 0 && toml_state && test_count_substring(toml_state, "[[hooks.PreToolUse]]") == 1U; free(toml_state); - int toml_disable_rc = cli_test_cmd_install(4, no_hooks_args); + int toml_disable_rc = cli_test_cmd_install_probe(4, no_hooks_args); toml_state = read_test_file_alloc(config_path); bool toml_disabled = toml_disable_rc == 0 && toml_state && !strstr(toml_state, "hooks.PreToolUse") && !strstr(toml_state, "hook-augment") && strstr(toml_state, "[mcp_servers.codebase-memory-mcp]"); free(toml_state); - int restore_rc = cli_test_cmd_install(4, hooks_args); + int restore_rc = cli_test_cmd_install_probe(4, hooks_args); toml_state = read_test_file_alloc(config_path); bool restored = restore_rc == 0 && toml_state && test_count_substring(toml_state, "[[hooks.PreToolUse]]") == 1U; @@ -2951,12 +2971,12 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) { cbm_cli_set_activation_ops_for_test(&ops); char *default_args[] = {"--skip-binary", "--clients=augment", "--yes"}; - int default_rc = cli_test_cmd_install(3, default_args); + int default_rc = cli_test_cmd_install_probe(3, default_args); bool default_scripts = default_rc == 0 && cbm_file_exists(session_path) && cbm_file_exists(coverage_path); char *no_hooks_args[] = {"--no-hooks", "--skip-binary", "--clients=augment", "--yes"}; - int no_hooks_rc = cli_test_cmd_install(4, no_hooks_args); + int no_hooks_rc = cli_test_cmd_install_probe(4, no_hooks_args); bool scripts_removed = no_hooks_rc == 0 && !cbm_file_exists(session_path) && !cbm_file_exists(coverage_path); char *settings = read_test_file_alloc(settings_path); @@ -2966,12 +2986,12 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) { !strstr(settings, "codebase-memory-coverage"); free(settings); - int bare_rc = cli_test_cmd_install(3, default_args); + int bare_rc = cli_test_cmd_install_probe(3, default_args); bool bare_disabled = bare_rc == 0 && !cbm_file_exists(session_path) && !cbm_file_exists(coverage_path); char *hooks_args[] = {"--hooks", "--skip-binary", "--clients=augment", "--yes"}; - int hooks_rc = cli_test_cmd_install(4, hooks_args); + int hooks_rc = cli_test_cmd_install_probe(4, hooks_args); settings = read_test_file_alloc(settings_path); bool restored = hooks_rc == 0 && cbm_file_exists(session_path) && cbm_file_exists(coverage_path) && settings && @@ -2987,7 +3007,7 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) { owned_session ? owned_session : ""); free(owned_session); write_test_file(session_path, user_session); - int user_rc = cli_test_cmd_install(4, no_hooks_args); + int user_rc = cli_test_cmd_install_probe(4, no_hooks_args); char *kept_session = read_test_file_alloc(session_path); bool user_script_kept = user_rc == 0 && kept_session && strcmp(kept_session, user_session) == 0 && @@ -2997,7 +3017,7 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) { /* End on --hooks, as the Codex case does: the opt-out is process state, * and later tests install without the command line. */ (void)remove(session_path); - int final_rc = cli_test_cmd_install(4, hooks_args); + int final_rc = cli_test_cmd_install_probe(4, hooks_args); bool final_restored = final_rc == 0 && cbm_file_exists(session_path) && cbm_file_exists(coverage_path); @@ -3057,7 +3077,7 @@ TEST(cli_install_reset_deletion_waits_for_final_activation_guard) { cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); char *argv[] = {"--force", "--reset-indexes", "--yes"}; - int rc = cli_test_cmd_install(3, argv); + int rc = cli_test_cmd_install_probe(3, argv); cbm_cli_set_activation_ops_for_test(NULL); cbm_set_auto_answer_for_test(0); @@ -3375,7 +3395,7 @@ TEST(cli_install_config_failure_keeps_published_binary) { cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake); cbm_cli_set_activation_ops_for_test(&ops); char *argv[] = {"--force", "--yes"}; - int rc = cli_test_cmd_install(2, argv); + int rc = cli_test_cmd_install_probe(2, argv); cbm_cli_set_activation_ops_for_test(NULL); cbm_set_auto_answer_for_test(0); diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.c index c34c45f5b..e58a92aec 100644 --- a/tests/test_daemon_runtime.c +++ b/tests/test_daemon_runtime.c @@ -8,6 +8,7 @@ #include "test_framework.h" #include "test_helpers.h" #include "test_daemon_runtime_contract.h" +#include "test_image_probe.h" #include "daemon/application.h" #include "daemon/host.h" @@ -37,6 +38,7 @@ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif +#include "foundation/subprocess.h" /* cbm_build_win_cmdline */ #include "foundation/win_utf8.h" #include #include @@ -505,6 +507,37 @@ static bool runtime_test_copy_self_image(const char *destination) { #endif } +/* The image probe beside this runner (tests/test_image_probe.h): the small + * executable the copied-image tests copy, hash and run instead of this runner. + * NULL, said once on stderr, when it was not built. */ +static const char *runtime_test_probe_image(void) { + static char path[RUNTIME_TEST_PATH_CAP]; + if (!path[0] && !th_image_probe_path(path, sizeof(path))) { + fprintf(stderr, "daemon_runtime: no image probe beside this runner; it is built " + "with the runner (Makefile.cbm, -image-probe)\n"); + return NULL; + } + return path; +} + +static bool runtime_test_copy_probe_image(const char *destination) { + const char *probe = runtime_test_probe_image(); +#ifdef _WIN32 + wchar_t *source_wide = probe && destination ? cbm_path_to_wide(probe) : NULL; + wchar_t *destination_wide = source_wide ? cbm_path_to_wide(destination) : NULL; + bool copied = destination_wide && CopyFileW(source_wide, destination_wide, TRUE) != 0; + free(destination_wide); + free(source_wide); + return copied; +#elif defined(__APPLE__) || defined(__linux__) + return probe && destination && runtime_test_copy_executable(probe, destination); +#else + (void)probe; + (void)destination; + return false; +#endif +} + static bool runtime_test_paths_refer_to_same_file(const char *left, const char *right) { enum { CANONICAL_CAP = 4096 }; char left_canonical[CANONICAL_CAP]; @@ -1287,10 +1320,10 @@ typedef struct { * fixture's convenience start also joins a service-owned participant guard. */ static runtime_test_coordination_t *runtime_test_fixture_coordination = NULL; -static bool runtime_test_fixture_start_configured( - runtime_test_fixture_t *fixture, const char *tag, const cbm_daemon_build_identity_t *identity, - uint32_t max_clients, uint64_t lease_timeout_ms, - const cbm_daemon_runtime_application_callbacks_t *application) { +/* The private parent, rendezvous key, endpoint and log paths of a fixture, + * before any daemon serves it: shared by the in-process service below and the + * image probe's daemon (runtime_test_probe_daemon_start). */ +static bool runtime_test_fixture_prepare(runtime_test_fixture_t *fixture, const char *tag) { memset(fixture, 0, sizeof(*fixture)); if (!th_secure_runtime_parent_new(fixture->parent, sizeof(fixture->parent), tag)) { return runtime_test_fixture_start_failed(tag, "temporary-directory", @@ -1325,7 +1358,16 @@ static bool runtime_test_fixture_start_configured( if (lock_written <= 0 || lock_written >= (int)sizeof(fixture->lock_log_path)) { return runtime_test_fixture_start_failed(tag, "lock-log-path", lock_written); } + return true; +} +static bool runtime_test_fixture_start_configured( + runtime_test_fixture_t *fixture, const char *tag, const cbm_daemon_build_identity_t *identity, + uint32_t max_clients, uint64_t lease_timeout_ms, + const cbm_daemon_runtime_application_callbacks_t *application) { + if (!runtime_test_fixture_prepare(fixture, tag)) { + return false; + } cbm_daemon_runtime_service_config_t config = { .endpoint = fixture->endpoint, .identity = *identity, @@ -1549,6 +1591,306 @@ static void runtime_test_fixture_finish(runtime_test_fixture_t *fixture) { memset(fixture, 0, sizeof(*fixture)); } +/* ── The image probe's daemon ──────────────────────────────────────────── + * The copied-image tests need a daemon whose peers are separately executed + * copies of the daemon's own image. A runtime service starts only with its own + * image's fingerprint as identity, so that daemon runs in the small image + * probe (__cbm_runtime_serve, tests/image_probe_roles.c), not in this runner: + * it fingerprints every peer copy before answering, and a copy of this + * ~800 MB sanitized runner took 70-95 s per hash on some hosted x86 CPUs, past + * the clients' exchange budget. Paths, key, endpoint and cleanup are the + * in-process fixture's (its .service stays NULL); the daemon is driven over + * its stdin and stdout, and nothing here waits on a clock: every read ends on + * a reply or on EOF when the probe is gone. */ +typedef struct { + runtime_test_fixture_t fixture; + char build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]; /* its identity: the probe's fingerprint */ + bool spawned; +#ifdef _WIN32 + HANDLE process; + HANDLE commands; /* the probe's stdin */ + HANDLE replies; /* the probe's stdout */ +#else + pid_t process; + int commands; + int replies; +#endif +} runtime_test_probe_daemon_t; + +#ifdef _WIN32 +/* Start argv with exactly the two pipe ends (and a duplicate of this runner's + * stderr, when there is one) inherited, as tf_rss_tree_start_descendant does. */ +static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon, + const char *const *argv) { + SECURITY_ATTRIBUTES inheritable; + memset(&inheritable, 0, sizeof(inheritable)); + inheritable.nLength = sizeof(inheritable); + inheritable.bInheritHandle = TRUE; + HANDLE child_input = NULL; + HANDLE commands = NULL; + HANDLE replies = NULL; + HANDLE child_output = NULL; + HANDLE child_error = NULL; + bool piped = CreatePipe(&child_input, &commands, &inheritable, 0) && + CreatePipe(&replies, &child_output, &inheritable, 0) && + SetHandleInformation(commands, HANDLE_FLAG_INHERIT, 0) && + SetHandleInformation(replies, HANDLE_FLAG_INHERIT, 0); + HANDLE error = GetStdHandle(STD_ERROR_HANDLE); + if (piped && error && error != INVALID_HANDLE_VALUE && + !DuplicateHandle(GetCurrentProcess(), error, GetCurrentProcess(), &child_error, 0, TRUE, + DUPLICATE_SAME_ACCESS)) { + child_error = NULL; /* the probe then runs without a stderr */ + } + char command_line[RUNTIME_TEST_PATH_CAP * 4]; + bool built = piped && cbm_build_win_cmdline(command_line, sizeof(command_line), argv); + wchar_t *application = built ? cbm_path_to_wide(argv[0]) : NULL; + wchar_t *command = application ? cbm_utf8_to_wide(command_line) : NULL; + HANDLE inherit[3] = {child_input, child_output, child_error}; + DWORD inherit_count = child_error ? 3U : 2U; + SIZE_T attrs_size = 0; + (void)InitializeProcThreadAttributeList(NULL, 1, 0, &attrs_size); + LPPROC_THREAD_ATTRIBUTE_LIST attrs = + command ? (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attrs_size) : NULL; + bool attrs_init = attrs && InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size); + bool attrs_ready = + attrs_init && UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, + inherit, inherit_count * sizeof(HANDLE), NULL, + NULL); + STARTUPINFOEXW startup; + memset(&startup, 0, sizeof(startup)); + startup.StartupInfo.cb = sizeof(startup); + startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES; + startup.StartupInfo.hStdInput = child_input; + startup.StartupInfo.hStdOutput = child_output; + startup.StartupInfo.hStdError = child_error; + startup.lpAttributeList = attrs; + PROCESS_INFORMATION process; + memset(&process, 0, sizeof(process)); + bool started = attrs_ready && + CreateProcessW(application, command, NULL, NULL, TRUE, + EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, NULL, NULL, + &startup.StartupInfo, &process) != 0; + if (attrs_init) { + DeleteProcThreadAttributeList(attrs); + } + free(attrs); + free(command); + free(application); + HANDLE child_ends[3] = {child_input, child_output, child_error}; + for (size_t i = 0; i < 3U; i++) { + if (child_ends[i]) { + (void)CloseHandle(child_ends[i]); + } + } + if (!started) { + if (commands) { + (void)CloseHandle(commands); + } + if (replies) { + (void)CloseHandle(replies); + } + return false; + } + (void)CloseHandle(process.hThread); + daemon->process = process.hProcess; + daemon->commands = commands; + daemon->replies = replies; + return true; +} +#elif defined(__APPLE__) || defined(__linux__) +/* posix_spawn, not fork, for the reason runtime_test_spawn_blocked_executable + * gives. This runner's pipe ends are close-on-exec, so no later child holds + * the daemon's stdin open past its release. */ +static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon, + const char *const *argv) { + int commands[2] = {-1, -1}; + int replies[2] = {-1, -1}; + if (pipe(commands) != 0) { + return false; + } + if (pipe(replies) != 0) { + (void)close(commands[0]); + (void)close(commands[1]); + return false; + } + bool private_ends = fcntl(commands[1], F_SETFD, FD_CLOEXEC) == 0 && + fcntl(replies[0], F_SETFD, FD_CLOEXEC) == 0; + posix_spawn_file_actions_t actions; + bool actions_ready = private_ends && posix_spawn_file_actions_init(&actions) == 0; + bool actions_set = actions_ready && + posix_spawn_file_actions_adddup2(&actions, commands[0], STDIN_FILENO) == 0 && + posix_spawn_file_actions_adddup2(&actions, replies[1], STDOUT_FILENO) == 0 && + posix_spawn_file_actions_addclose(&actions, commands[0]) == 0 && + posix_spawn_file_actions_addclose(&actions, replies[1]) == 0; + pid_t child = -1; + bool started = actions_set && posix_spawn(&child, argv[0], &actions, NULL, + (char *const *)argv, environ) == 0; + if (actions_ready) { + (void)posix_spawn_file_actions_destroy(&actions); + } + (void)close(commands[0]); + (void)close(replies[1]); + if (!started) { + (void)close(commands[1]); + (void)close(replies[0]); + return false; + } + daemon->process = child; + daemon->commands = commands[1]; + daemon->replies = replies[0]; + return true; +} +#else +static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon, + const char *const *argv) { + (void)daemon; + (void)argv; + return false; +} +#endif + +/* One reply line, without its line end. false on EOF (the probe is gone), a + * read error, or a line longer than cap. */ +static bool runtime_test_probe_daemon_read_line(runtime_test_probe_daemon_t *daemon, char *line, + size_t cap) { + size_t used = 0; + bool fits = cap > 0; + for (;;) { + char ch = 0; +#ifdef _WIN32 + DWORD got = 0; + if (!ReadFile(daemon->replies, &ch, 1, &got, NULL) || got != 1) { + return false; + } +#else + ssize_t got = read(daemon->replies, &ch, 1); + if (got < 0 && errno == EINTR) { + continue; + } + if (got != 1) { + return false; + } +#endif + if (ch == '\n') { + if (fits) { + line[used] = '\0'; + } + return fits; + } + if (ch != '\r' && fits && used + 1 < cap) { + line[used++] = ch; + } else if (ch != '\r') { + fits = false; + } + } +} + +static bool runtime_test_probe_daemon_send(runtime_test_probe_daemon_t *daemon, char command) { +#ifdef _WIN32 + DWORD written = 0; + return WriteFile(daemon->commands, &command, 1, &written, NULL) != 0 && written == 1; +#else + /* A probe that is already gone must fail the test, not kill the runner + * with SIGPIPE: ignore it for this one write, as test_subprocess does. */ + struct sigaction ignore; + struct sigaction previous; + memset(&ignore, 0, sizeof(ignore)); + ignore.sa_handler = SIG_IGN; + sigemptyset(&ignore.sa_mask); + if (sigaction(SIGPIPE, &ignore, &previous) != 0) { + return false; + } + ssize_t written; + do { + written = write(daemon->commands, &command, 1); + } while (written < 0 && errno == EINTR); + bool restored = sigaction(SIGPIPE, &previous, NULL) == 0; + return written == 1 && restored; +#endif +} + +/* Start the probe's daemon in a fresh fixture: true once it reported "ready" + * with its fingerprint, which then is daemon->build. with_owner also holds a + * committed session of the active image inside the probe. */ +static bool runtime_test_probe_daemon_start(runtime_test_probe_daemon_t *daemon, const char *tag, + const char *version, bool with_owner) { + memset(daemon, 0, sizeof(*daemon)); + const char *probe = runtime_test_probe_image(); + if (!probe) { + return runtime_test_fixture_start_failed(tag, "image-probe", 0); + } + if (!runtime_test_fixture_prepare(&daemon->fixture, tag)) { + return false; + } + const char *argv[] = {probe, + "__cbm_runtime_serve", + daemon->fixture.parent, + daemon->fixture.key, + version, + with_owner ? "1" : "0", + NULL}; + daemon->spawned = runtime_test_probe_daemon_spawn(daemon, argv); + if (!daemon->spawned) { + return runtime_test_fixture_start_failed(tag, "image-probe-spawn", + runtime_test_last_os_error()); + } + char line[CBM_DAEMON_BUILD_FINGERPRINT_SIZE + 16] = {0}; + bool answered = runtime_test_probe_daemon_read_line(daemon, line, sizeof(line)); + bool ready = answered && strncmp(line, "ready ", 6) == 0 && runtime_test_is_fingerprint(line + 6); + if (!ready) { + printf(" image probe daemon did not start: tag=%s reply=%s\n", tag, + answered ? line : "(none: the probe exited)"); + return false; + } + memcpy(daemon->build, line + 6, CBM_DAEMON_BUILD_FINGERPRINT_SIZE); + return true; +} + +/* Ask the daemon one question ('i' owner interrupted, 'x' exited by itself): + * true when it answered, the answer in *answer. */ +static bool runtime_test_probe_daemon_ask(runtime_test_probe_daemon_t *daemon, char command, + bool *answer) { + char line[8] = {0}; + bool answered = daemon->spawned && runtime_test_probe_daemon_send(daemon, command) && + runtime_test_probe_daemon_read_line(daemon, line, sizeof(line)) && + (strcmp(line, "0") == 0 || strcmp(line, "1") == 0); + *answer = answered && line[0] == '1'; + return answered; +} + +/* Release the daemon (EOF on its stdin), reap it and remove the fixture's + * paths. Returns its exit code, or -1 when it never ran or did not exit + * normally. Safe on a daemon whose start failed, and on a memset one. */ +static int runtime_test_probe_daemon_finish(runtime_test_probe_daemon_t *daemon) { + int exit_code = -1; + if (daemon->spawned) { +#ifdef _WIN32 + (void)CloseHandle(daemon->commands); + bool waited = runtime_test_windows_wait_image_probe(daemon->process); + DWORD code = 0; + if (waited && GetExitCodeProcess(daemon->process, &code) != 0 && code <= INT_MAX) { + exit_code = (int)code; + } + (void)CloseHandle(daemon->process); + (void)CloseHandle(daemon->replies); +#elif defined(__APPLE__) || defined(__linux__) + (void)close(daemon->commands); + int status = 0; + pid_t waited; + do { + waited = waitpid(daemon->process, &status, 0); + } while (waited < 0 && errno == EINTR); + if (waited == daemon->process && WIFEXITED(status)) { + exit_code = WEXITSTATUS(status); + } + (void)close(daemon->replies); +#endif + daemon->spawned = false; + } + runtime_test_fixture_finish(&daemon->fixture); + return exit_code; +} + static bool runtime_test_read_log(const char *path, char out[RUNTIME_TEST_LOG_CAP]) { FILE *file = cbm_fopen(path, "rb"); if (!file) { @@ -2323,8 +2665,6 @@ TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients) { #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) TEST(daemon_runtime_activation_accepts_authenticated_different_build) { - cbm_daemon_build_identity_t active_identity = - runtime_test_identity("2.4.0", runtime_test_self_build()); char directory[RUNTIME_TEST_PATH_CAP] = {0}; char foreign_image[RUNTIME_TEST_PATH_CAP] = {0}; int directory_written = @@ -2334,8 +2674,12 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) { int image_written = directory_created ? snprintf(foreign_image, sizeof(foreign_image), "%s/foreign-activation", directory) : -1; + /* The active daemon and the foreign requester are both the image probe + * (runtime_test_probe_daemon_t): the daemon hashes the requester's image + * to authenticate its claimed build, over a few MB instead of a copy of + * this runner. */ bool copied = image_written > 0 && image_written < (int)sizeof(foreign_image) && - runtime_test_copy_self_image(foreign_image); + runtime_test_copy_probe_image(foreign_image); #ifdef __APPLE__ /* Appending an overlay invalidates Mach-O strict validation. A distinct * signing identifier changes the executable bytes while keeping the copy @@ -2349,38 +2693,28 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) { char foreign_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; bool fingerprinted = runnable && cbm_daemon_build_fingerprint_file(foreign_image, foreign_build); - bool differs = fingerprinted && strcmp(foreign_build, active_identity.build_fingerprint) != 0; cbm_daemon_build_identity_t foreign_identity = runtime_test_identity("9.9.9", foreign_build); - /* Finalize the foreign executable before the runtime starts any worker - * threads. In particular, macOS code signing is an external process; the - * test must not fork that helper from the live multithreaded daemon. The - * immutable signed copy remains the actual peer image authenticated by - * the activation request below. */ - runtime_test_fixture_t fixture; - memset(&fixture, 0, sizeof(fixture)); - bool started = - differs && runtime_test_fixture_start(&fixture, "activation-foreign", &active_identity); - cbm_daemon_runtime_connect_result_t owner_result = {0}; - cbm_daemon_runtime_client_t *owner = NULL; - if (started) { - owner = cbm_daemon_runtime_client_connect(fixture.endpoint, &active_identity, - RUNTIME_TEST_TIMEOUT_MS, &owner_result); - } + /* The foreign executable is final before the daemon starts; macOS code + * signing above is an external process. The immutable signed copy remains + * the actual peer image authenticated by the activation request below. + * The daemon holds one committed owner session of its own image. */ + runtime_test_probe_daemon_t daemon; + memset(&daemon, 0, sizeof(daemon)); + bool started = fingerprinted && + runtime_test_probe_daemon_start(&daemon, "activation-foreign", "2.4.0", true); + bool differs = started && strcmp(foreign_build, daemon.build) != 0; int foreign_exit = -1; bool foreign_ran = - owner && differs && - runtime_test_run_activation_image(foreign_image, &fixture, &foreign_identity, + differs && + runtime_test_run_activation_image(foreign_image, &daemon.fixture, &foreign_identity, CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL, &foreign_exit); - bool owner_interrupted = owner && foreign_ran && - !cbm_daemon_runtime_client_heartbeat(owner, RUNTIME_TEST_TIMEOUT_MS); - if (owner) { - (void)cbm_daemon_runtime_client_close(owner, RUNTIME_TEST_TIMEOUT_MS); - owner = NULL; - } - bool exited = - started && cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS); - runtime_test_fixture_finish(&fixture); + bool owner_interrupted = false; + bool interrupted_asked = + foreign_ran && runtime_test_probe_daemon_ask(&daemon, 'i', &owner_interrupted); + bool exited = false; + bool exited_asked = started && runtime_test_probe_daemon_ask(&daemon, 'x', &exited); + int daemon_exit = runtime_test_probe_daemon_finish(&daemon); if (image_written > 0 && image_written < (int)sizeof(foreign_image)) { (void)cbm_unlink(foreign_image); } @@ -2388,18 +2722,20 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) { (void)cbm_rmdir(directory); } - ASSERT_TRUE(started); - ASSERT_EQ(owner_result.status, CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED); ASSERT_TRUE(directory_created); ASSERT_TRUE(copied); ASSERT_TRUE(changed); ASSERT_TRUE(runnable); ASSERT_TRUE(fingerprinted); + ASSERT_TRUE(started); ASSERT_TRUE(differs); ASSERT_TRUE(foreign_ran); ASSERT_EQ(foreign_exit, 0); + ASSERT_TRUE(interrupted_asked); ASSERT_TRUE(owner_interrupted); + ASSERT_TRUE(exited_asked); ASSERT_TRUE(exited); + ASSERT_EQ(daemon_exit, 0); PASS(); } #endif @@ -4875,15 +5211,20 @@ TEST(daemon_runtime_process_fingerprint_supports_extended_length_image) { } bool directory_created = path_built && cbm_mkdir_p(directory, 0700); int image_written = directory_created ? snprintf(image_path, sizeof(image_path), - "%s/test-runner-long-image.exe", directory) + "%s/image-probe-long-image.exe", directory) : -1; wchar_t *ordinary_wide = image_written > 0 && image_written < (int)sizeof(image_path) ? cbm_utf8_to_wide(image_path) : NULL; bool exceeds_legacy_limit = ordinary_wide && wcslen(ordinary_wide) >= MAX_PATH; free(ordinary_wide); - bool copied = exceeds_legacy_limit && runtime_test_windows_copy_self(image_path); - const char *expected = runtime_test_self_build(); + /* A copy of the image probe, not of this runner: the fingerprint below + * hashes the whole held image (runtime_test_probe_daemon_t says why). */ + bool copied = exceeds_legacy_limit && runtime_test_copy_probe_image(image_path); + char expected_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; + const char *probe = runtime_test_probe_image(); + const char *expected = + probe && cbm_daemon_build_fingerprint_file(probe, expected_build) ? expected_build : NULL; int event_written = snprintf(event_name, sizeof(event_name), "Local\\cbm-runtime-long-image-%lu-%llu", @@ -4964,10 +5305,7 @@ TEST(daemon_runtime_process_fingerprint_supports_extended_length_image) { * Re-signing the changed copy keeps the probe runnable on arm64 while ensuring * that only the deliberately injected mapping has the active identity. */ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) { - cbm_daemon_build_identity_t identity = - runtime_test_identity("2.4.0", runtime_test_self_build()); char directory[RUNTIME_TEST_PATH_CAP] = {0}; - char active_image[RUNTIME_TEST_PATH_CAP] = {0}; char foreign_image[RUNTIME_TEST_PATH_CAP] = {0}; char foreign_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; int directory_written = @@ -4977,7 +5315,11 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) { int foreign_written = directory_created ? snprintf(foreign_image, sizeof(foreign_image), "%s/foreign-client", directory) : -1; - bool active_resolved = runtime_test_self_image_path(active_image); + /* The daemon runs from the image probe (runtime_test_probe_daemon_t), so + * the active image the foreign client maps is the probe, and the foreign + * main image the daemon must hash is a re-signed copy of the probe. */ + const char *active_image = runtime_test_probe_image(); + bool active_resolved = active_image != NULL; bool foreign_copied = active_resolved && foreign_written > 0 && foreign_written < (int)sizeof(foreign_image) && runtime_test_copy_executable(active_image, foreign_image); @@ -4987,22 +5329,20 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) { bool foreign_signed = foreign_changed && runtime_test_mac_ad_hoc_sign(foreign_image); bool foreign_fingerprinted = foreign_signed && cbm_daemon_build_fingerprint_file(foreign_image, foreign_fingerprint); - bool fingerprint_differs = - foreign_fingerprinted && strcmp(foreign_fingerprint, identity.build_fingerprint) != 0; - runtime_test_fixture_t fixture; - memset(&fixture, 0, sizeof(fixture)); - bool fixture_attempted = directory_created && active_resolved && fingerprint_differs; - bool started = - fixture_attempted && runtime_test_fixture_start(&fixture, "mapped-foreign", &identity); + runtime_test_probe_daemon_t daemon; + memset(&daemon, 0, sizeof(daemon)); + bool started = directory_created && foreign_fingerprinted && + runtime_test_probe_daemon_start(&daemon, "mapped-foreign", "2.4.0", false); + cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", daemon.build); + bool fingerprint_differs = + started && strcmp(foreign_fingerprint, identity.build_fingerprint) != 0; int foreign_exit = -1; bool foreign_ran = - started && runtime_test_run_mapped_hello_image(foreign_image, active_image, &fixture, - &identity, &foreign_exit); - - if (fixture_attempted) { - runtime_test_fixture_finish(&fixture); - } + fingerprint_differs && runtime_test_run_mapped_hello_image( + foreign_image, active_image, &daemon.fixture, &identity, + &foreign_exit); + int daemon_exit = runtime_test_probe_daemon_finish(&daemon); if (foreign_written > 0 && foreign_written < (int)sizeof(foreign_image)) { (void)cbm_unlink(foreign_image); } @@ -5016,33 +5356,41 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) { ASSERT_TRUE(foreign_changed); ASSERT_TRUE(foreign_signed); ASSERT_TRUE(foreign_fingerprinted); - ASSERT_TRUE(fingerprint_differs); ASSERT_TRUE(started); + ASSERT_TRUE(fingerprint_differs); ASSERT_TRUE(foreign_ran); + /* 26 = the daemon answered with a rejection. A probe that got no answer + * inside the exchange budget exits 30 and must not pass here. */ ASSERT_EQ(foreign_exit, 26); + ASSERT_EQ(daemon_exit, 0); PASS(); } #endif +/* The daemon admits a peer running a DIFFERENT file only after hashing that + * file: identical bytes are admitted, changed bytes refused. The daemon runs + * from the image probe and its peers are copies of the probe + * (runtime_test_probe_daemon_t), so the hash it pays before answering is over + * a few MB, not over a copy of this runner. */ TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed) { - cbm_daemon_build_identity_t identity = - runtime_test_identity("2.4.0", runtime_test_self_build()); - runtime_test_fixture_t identical_fixture; + runtime_test_probe_daemon_t identical_daemon; bool identical_started = - runtime_test_fixture_start(&identical_fixture, "copied-identical", &identity); + runtime_test_probe_daemon_start(&identical_daemon, "copied-identical", "2.4.0", false); + cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", identical_daemon.build); char identical_path[RUNTIME_TEST_PATH_CAP] = {0}; int identical_path_written = identical_started #ifdef _WIN32 ? snprintf(identical_path, sizeof(identical_path), - "%s/client-copy.exe", identical_fixture.parent) + "%s/client-copy.exe", + identical_daemon.fixture.parent) #else ? snprintf(identical_path, sizeof(identical_path), - "%s/client-copy", identical_fixture.parent) + "%s/client-copy", identical_daemon.fixture.parent) #endif : -1; bool identical_copied = identical_path_written > 0 && identical_path_written < (int)sizeof(identical_path) && - runtime_test_copy_self_image(identical_path); + runtime_test_copy_probe_image(identical_path); char identical_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; bool identical_bytes = identical_copied && @@ -5050,35 +5398,39 @@ TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed) strcmp(identical_fingerprint, identity.build_fingerprint) == 0; int identical_exit = -1; bool identical_ran = - identical_bytes && runtime_test_run_hello_image(identical_path, &identical_fixture, + identical_bytes && runtime_test_run_hello_image(identical_path, &identical_daemon.fixture, &identity, &identical_exit); - bool identical_exited = - identical_ran && identical_exit == 0 && - cbm_daemon_runtime_service_wait_exited(identical_fixture.service, RUNTIME_TEST_TIMEOUT_MS); + bool identical_exited = false; + bool identical_asked = identical_ran && identical_exit == 0 && + runtime_test_probe_daemon_ask(&identical_daemon, 'x', &identical_exited); (void)cbm_unlink(identical_path); - runtime_test_fixture_finish(&identical_fixture); + int identical_daemon_exit = runtime_test_probe_daemon_finish(&identical_daemon); #ifdef __linux__ - runtime_test_fixture_t changed_fixture; + runtime_test_probe_daemon_t changed_daemon; bool changed_started = - runtime_test_fixture_start(&changed_fixture, "copied-changed", &identity); + runtime_test_probe_daemon_start(&changed_daemon, "copied-changed", "2.4.0", false); + cbm_daemon_build_identity_t changed_identity = + runtime_test_identity("2.4.0", changed_daemon.build); char changed_path[RUNTIME_TEST_PATH_CAP] = {0}; - int changed_path_written = changed_started ? snprintf(changed_path, sizeof(changed_path), - "%s/client-copy", changed_fixture.parent) - : -1; + int changed_path_written = + changed_started ? snprintf(changed_path, sizeof(changed_path), "%s/client-copy", + changed_daemon.fixture.parent) + : -1; bool changed_copied = changed_path_written > 0 && changed_path_written < (int)sizeof(changed_path) && - runtime_test_copy_self_image(changed_path) && + runtime_test_copy_probe_image(changed_path) && runtime_test_append_image_marker(changed_path); char changed_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0}; bool changed_bytes = changed_copied && cbm_daemon_build_fingerprint_file(changed_path, changed_fingerprint) && - strcmp(changed_fingerprint, identity.build_fingerprint) != 0; + strcmp(changed_fingerprint, changed_identity.build_fingerprint) != 0; int changed_exit = -1; - bool changed_ran = changed_bytes && runtime_test_run_hello_image(changed_path, &changed_fixture, - &identity, &changed_exit); + bool changed_ran = + changed_bytes && runtime_test_run_hello_image(changed_path, &changed_daemon.fixture, + &changed_identity, &changed_exit); (void)cbm_unlink(changed_path); - runtime_test_fixture_finish(&changed_fixture); + int changed_daemon_exit = runtime_test_probe_daemon_finish(&changed_daemon); #endif ASSERT_TRUE(identical_started); @@ -5086,13 +5438,18 @@ TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed) ASSERT_TRUE(identical_bytes); ASSERT_TRUE(identical_ran); ASSERT_EQ(identical_exit, 0); + ASSERT_TRUE(identical_asked); ASSERT_TRUE(identical_exited); + ASSERT_EQ(identical_daemon_exit, 0); #ifdef __linux__ ASSERT_TRUE(changed_started); ASSERT_TRUE(changed_copied); ASSERT_TRUE(changed_bytes); ASSERT_TRUE(changed_ran); + /* 26 = the daemon answered with a rejection; no answer inside the + * exchange budget exits 30 and fails here instead of passing. */ ASSERT_EQ(changed_exit, 26); + ASSERT_EQ(changed_daemon_exit, 0); #endif PASS(); } @@ -5118,7 +5475,7 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) { setup = setup && image_written > 0 && image_written < (int)sizeof(image_path) && replacement_written > 0 && replacement_written < (int)sizeof(replacement_path) && event_written > 0 && event_written < (int)sizeof(event_name) && - runtime_test_windows_copy_self(image_path); + runtime_test_copy_probe_image(image_path); FILE *replacement_file = setup ? cbm_fopen(replacement_path, "wb") : NULL; bool replacement_written_ok = @@ -5188,12 +5545,13 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) { int replacement_written = setup ? snprintf(replacement_path, sizeof(replacement_path), "%s/replacement", directory) : -1; - /* The copied image is this runner in holder mode, not a system utility: - * a multi-call coreutils /bin/cat (uutils) prints "unknown program" and - * exits when executed under the copied name. */ + /* The copied image is the image probe in holder mode, not a system + * utility: a multi-call coreutils /bin/cat (uutils) prints "unknown + * program" and exits when executed under the copied name. Not this runner + * either: the fingerprint below hashes the whole held image. */ setup = setup && image_written > 0 && image_written < (int)sizeof(image_path) && replacement_written > 0 && replacement_written < (int)sizeof(replacement_path) && - runtime_test_copy_self_image(image_path); + runtime_test_copy_probe_image(image_path); FILE *replacement_file = setup ? cbm_fopen(replacement_path, "wb") : NULL; bool replacement_written_ok = diff --git a/tests/test_image_probe.h b/tests/test_image_probe.h new file mode 100644 index 000000000..be975dc68 --- /dev/null +++ b/tests/test_image_probe.h @@ -0,0 +1,104 @@ +#ifndef TEST_IMAGE_PROBE_H +#define TEST_IMAGE_PROBE_H + +/* + * The image probe: a small executable built beside every test runner + * (Makefile.cbm, -image-probe, e.g. build/c/test-runner-image-probe) + * from tests/image_probe_main.c, tests/image_probe_roles.c, the daemon runtime + * and foundation (~5 MB with sanitizers, against ~800 MB for the runner). + * + * Tests that need a real, separately executed process image use it instead of + * a copy of the runner: daemon_runtime's copied-image probes run their daemon + * and clients from it, and the cli install tests publish it as the installed + * binary. Each of those used to SHA-256 the whole sanitized runner, several + * times per test, and one such hash costs 70-95 s on some hosted x86 CPUs: a + * daemon still hashing a peer copy missed the client's exchange budget, and the + * cli suite ran past its wall-clock ceiling, decided by which CPU a job drew. + * The production verification code is unchanged; only the image is smaller. + * + * Roles (argv[1]), dispatched by tf_image_probe_dispatch: + * __cbm_runtime_serve + * __cbm_runtime_hello_client + * __cbm_runtime_activation_client + * __cbm_runtime_mapped_hello_client + * __cbm_runtime_image_holder [] + * The probe's main also answers --version (install verification runs it). + */ + +#include "foundation/compat_fs.h" /* cbm_fopen: the probe path may be non-ASCII */ + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include "foundation/win_utf8.h" +#include +#else +#include +#ifdef __APPLE__ +#include +#endif +#endif + +/* Runs the role argv[1] names: its exit code, or -1 when argv names none. */ +int tf_image_probe_dispatch(int argc, char **argv); + +/* The probe built beside the running runner: the runner's own image path + * without ".exe", then "-image-probe" (".exe" again on Windows). False when + * the path cannot be formed or names no file: a missing probe is a build + * defect the calling test reports, never a skip. */ +static inline bool th_image_probe_path(char *out, size_t cap) { + if (!out || cap == 0) { + return false; + } + out[0] = '\0'; + char self[4096] = {0}; +#ifdef _WIN32 + char *module = cbm_module_path_utf8(); + size_t module_length = module ? strlen(module) : 0; + bool resolved = module_length > 0 && module_length < sizeof(self); + if (resolved) { + memcpy(self, module, module_length + 1); + } + free(module); + size_t length = resolved ? strlen(self) : 0; + if (length > 4 && _stricmp(self + length - 4, ".exe") == 0) { + self[length - 4] = '\0'; + } + const char *suffix = "-image-probe.exe"; +#elif defined(__APPLE__) + int length = proc_pidpath(getpid(), self, (uint32_t)sizeof(self)); + bool resolved = length > 0 && length < (int)sizeof(self); + if (resolved) { + self[length] = '\0'; + } + const char *suffix = "-image-probe"; +#elif defined(__linux__) + ssize_t length = readlink("/proc/self/exe", self, sizeof(self) - 1); + bool resolved = length > 0 && length < (ssize_t)sizeof(self) - 1; + if (resolved) { + self[length] = '\0'; + } + const char *suffix = "-image-probe"; +#else + bool resolved = false; + const char *suffix = ""; +#endif + int written = resolved ? snprintf(out, cap, "%s%s", self, suffix) : -1; + if (written <= 0 || (size_t)written >= cap) { + out[0] = '\0'; + return false; + } + FILE *probe = cbm_fopen(out, "rb"); + if (!probe) { + out[0] = '\0'; + return false; + } + (void)fclose(probe); + return true; +} + +#endif /* TEST_IMAGE_PROBE_H */ diff --git a/tests/test_main.c b/tests/test_main.c index 189ad8e93..dcd7bec88 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -11,7 +11,7 @@ int tf_deselected_count = 0; #include "test_framework.h" #include "test_helpers.h" -#include "test_daemon_runtime_contract.h" +#include "test_image_probe.h" #include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */ #include "foundation/compat_fs.h" /* cbm_fopen — worker response file */ #include "foundation/constants.h" /* CBM_SZ_4K — forced stderr buffer */ @@ -48,10 +48,6 @@ int tf_deselected_count = 0; #include /* INT_MAX: a handed-down descriptor */ #include /* waitpid: the process-tree probe root */ #include -#ifdef __APPLE__ -#include -#include -#endif #ifdef CBM_TEST_COVERAGE #include /* the libc functions behind the profile-keeping ones */ #include /* the marker of a forked child */ @@ -657,129 +653,12 @@ static int tf_maybe_run_version_cohort_crash_holder(int argc, char **argv) { #endif } -static int tf_maybe_run_runtime_image_holder(int argc, char **argv) { -#ifdef _WIN32 - if (argc != 3 || strcmp(argv[1], "__cbm_runtime_image_holder") != 0) { - return -1; - } - HANDLE ready = OpenEventA(EVENT_MODIFY_STATE, FALSE, argv[2]); - bool announced = ready && SetEvent(ready) != 0; - if (ready) { - (void)CloseHandle(ready); - } - if (!announced) { - return 24; - } - Sleep(INFINITE); - return 25; -#else - /* POSIX copied-image holder: block reading stdin until the parent closes - * the release pipe, exactly like the cat(1) donor this replaced. A system - * utility cannot serve as the copied image — a multi-call coreutils - * binary (uutils cat) refuses to execute under the copied name. */ - if (argc != 2 || strcmp(argv[1], "__cbm_runtime_image_holder") != 0) { - return -1; - } - char release[16]; - ssize_t count; - do { - count = read(STDIN_FILENO, release, sizeof(release)); - } while (count > 0 || (count < 0 && errno == EINTR)); - return count == 0 ? 0 : 25; -#endif -} - -/* Real copied-image HELLO probe used by daemon_runtime. Keeping this in the - * test runner avoids any production-only test hook: the daemon authenticates - * and fingerprints an ordinary, separately executed process image. */ -static int tf_maybe_run_runtime_hello_client(int argc, char **argv) { - if (argc != 6 || strcmp(argv[1], "__cbm_runtime_hello_client") != 0) { - return -1; - } - cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]); - cbm_daemon_build_identity_t identity = { - .semantic_version = argv[4], - .build_fingerprint = argv[5], - }; - cbm_daemon_runtime_connect_result_t result; - memset(&result, 0, sizeof(result)); - cbm_daemon_runtime_client_t *client = - endpoint ? cbm_daemon_runtime_client_connect(endpoint, &identity, - TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result) - : NULL; - bool accepted = client && result.status == CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED && - result.hello_status == CBM_DAEMON_HELLO_COMPATIBLE; - bool closed = - !client || cbm_daemon_runtime_client_close(client, TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS); - cbm_daemon_ipc_endpoint_free(endpoint); - if (!accepted) { - return 26; - } - return closed ? 0 : 27; -} - -/* Real copied-image activation probe. The request identity is supplied by the - * executing copy so the daemon must authenticate that peer image rather than - * require the active generation's build fingerprint. */ -static int tf_maybe_run_runtime_activation_client(int argc, char **argv) { - if (argc != 7 || strcmp(argv[1], "__cbm_runtime_activation_client") != 0) { - return -1; - } - char *action_end = NULL; - unsigned long action_value = strtoul(argv[6], &action_end, 10); - bool action_valid = action_end != argv[6] && *action_end == '\0' && - action_value >= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL && - action_value <= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL; - cbm_daemon_ipc_endpoint_t *endpoint = - action_valid ? cbm_daemon_ipc_endpoint_new(argv[3], argv[2]) : NULL; - cbm_daemon_build_identity_t identity = { - .semantic_version = argv[4], - .build_fingerprint = argv[5], - }; - cbm_daemon_runtime_activation_result_t result; - memset(&result, 0, sizeof(result)); - bool exchanged = - endpoint && cbm_daemon_runtime_request_activation_shutdown( - endpoint, &identity, (cbm_daemon_runtime_activation_action_t)action_value, - TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result); - cbm_daemon_ipc_endpoint_free(endpoint); - return exchanged && result.accepted ? 0 : 29; -} - -/* macOS adversarial HELLO probe: execute this mode from a foreign process - * image while mapping the genuine runner RX. The daemon must authenticate the - * main image, not merely find its own vnode in an arbitrary executable map. */ -static int tf_maybe_run_runtime_mapped_hello_client(int argc, char **argv) { -#ifdef __APPLE__ - if (argc != 7 || strcmp(argv[1], "__cbm_runtime_mapped_hello_client") != 0) { - return -1; - } - int image_fd = open(argv[2], O_RDONLY | O_CLOEXEC | O_NOFOLLOW); - void *mapping = - image_fd >= 0 ? mmap(NULL, 1, PROT_READ | PROT_EXEC, MAP_PRIVATE, image_fd, 0) : MAP_FAILED; - bool mapped = mapping != MAP_FAILED; - if (image_fd >= 0 && close(image_fd) != 0) { - mapped = false; - } - if (!mapped) { - if (mapping != MAP_FAILED) { - (void)munmap(mapping, 1); - } - return 28; - } - - char *hello_argv[] = {argv[0], "__cbm_runtime_hello_client", argv[3], argv[4], argv[5], - argv[6]}; - int result = tf_maybe_run_runtime_hello_client(6, hello_argv); - if (munmap(mapping, 1) != 0) { - return 28; - } - return result >= 0 ? result : 28; -#else - (void)argc; - (void)argv; - return -1; -#endif +/* The image probe's roles (tests/image_probe_roles.c, tests/test_image_probe.h). + * The runner itself dispatches only the image holder through here; tf_roles + * names the probe's other literals under TF_PHASE_PROBE so the test-impact + * engine still maps a change those roles reach to the tests that start them. */ +static int tf_role_image_probe(int argc, char **argv) { + return tf_image_probe_dispatch(argc, argv); } static int tf_maybe_run_mcp_idxfailclosed_probe(int argc, char **argv) { @@ -2289,6 +2168,7 @@ typedef enum { TF_PHASE_SEAMED, /* after the spill and build-fingerprint pins */ TF_PHASE_WORKER, /* after the fingerprint capture; the literal anywhere in argv */ TF_PHASE_SPAWNER, /* never dispatched: one more literal a spawner names */ + TF_PHASE_PROBE, /* never dispatched here: the image probe runs the role */ } tf_phase_t; typedef struct { @@ -2314,10 +2194,11 @@ static const tf_role_t tf_roles[] = { TF_ROLE(TF_PHASE_INSTALL, "--build-config", tf_role_build_config), TF_ROLE(TF_PHASE_SEAMED, "--userns-secure-probe", tf_role_userns_secure_probe), TF_ROLE(TF_PHASE_SEAMED, "__cbm_mcp_idxfailclosed_probe", tf_maybe_run_mcp_idxfailclosed_probe), - TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_image_holder", tf_maybe_run_runtime_image_holder), - TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_hello_client", tf_maybe_run_runtime_hello_client), - TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_activation_client", tf_maybe_run_runtime_activation_client), - TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_mapped_hello_client", tf_maybe_run_runtime_mapped_hello_client), + TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_image_holder", tf_role_image_probe), + TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_serve", tf_role_image_probe), + TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_hello_client", tf_role_image_probe), + TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_activation_client", tf_role_image_probe), + TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_mapped_hello_client", tf_role_image_probe), TF_ROLE(TF_PHASE_SEAMED, "__cbm_version_cohort_crash_holder", tf_maybe_run_version_cohort_crash_holder), TF_ROLE(TF_PHASE_SEAMED, "__cbm_daemon_ipc_lock_probe", tf_maybe_run_daemon_ipc_lock_probe), TF_ROLE(TF_PHASE_SEAMED, "__cbm_deleted_self_probe", tf_maybe_run_deleted_self_probe), From 88dbd8eb4fbc429e13ad580fc40189a63bec65cc Mon Sep 17 00:00:00 2001 From: Martin Vogel Date: Wed, 18 Nov 2026 23:30:53 +0100 Subject: [PATCH 25/25] test: link TRE into the image probe on Windows compat_regex.c is backed by the vendored TRE library on Windows, so the probe failed to link there (undefined tre_regcomp/tre_regexec/tre_regfree, CLANG64 job 135123199250). Link TRE_OBJ_TEST / TRE_OBJ_TSAN into the two probe flavours as the runners do; both are empty on every other platform. Signed-off-by: Martin Vogel --- Makefile.cbm | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Makefile.cbm b/Makefile.cbm index dbe08e8e4..81dc097bb 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -1232,12 +1232,14 @@ IMAGE_PROBE_SRCS = tests/image_probe_main.c tests/image_probe_roles.c \ src/daemon/service.c $(IMAGE_PROBE_FOUNDATION_SRCS) CFLAGS_IMAGE_PROBE = $(filter-out $(TEST_COVERAGE_FLAGS) $(TEST_COVERAGE_DEFINE),$(CFLAGS_TEST)) -$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) +# TRE_OBJ_* is empty except on Windows, where compat_regex.c is backed by TRE. +$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) $(TRE_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(CC) $(CFLAGS_IMAGE_PROBE) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) \ - $(LDFLAGS_TEST) + $(TRE_OBJ_TEST) $(LDFLAGS_TEST) -$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) - $(CC) $(CFLAGS_TSAN) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(LDFLAGS_TSAN) +$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) + $(CC) $(CFLAGS_TSAN) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) \ + $(LDFLAGS_TSAN) $(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-image-probe $(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \