diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c index 003fb6f20..697c2a688 100644 --- a/internal/cbm/cbm.c +++ b/internal/cbm/cbm.c @@ -3898,6 +3898,43 @@ static void record_included_files(CBMArena *a, CBMFileResult *result, result->included_files = list; } +static int test_span_order(const void *left, const void *right) { + const CBMTestSpan *a = left; + const CBMTestSpan *b = right; + if (a->start_line != b->start_line) { + return a->start_line < b->start_line ? -1 : 1; + } + if (a->end_line != b->end_line) { + return a->end_line < b->end_line ? -1 : 1; + } + return strcmp(a->qualified_name, b->qualified_name); +} + +/* The raw view's GoogleTest definitions (recorded by the def walk), sorted, the + * preprocessor's line map, and the index of the preprocessed view's top-level + * definitions that map onto them, for that view of the same file. NULL when + * the raw view named no test or the map is missing. */ +static const CBMTestSpanMap *pp_test_span_map(CBMTestSpanMap *map, CBMExtractCtx *raw, + const CBMPreprocessedSource *pp, TSNode pp_root) { + if (raw->test_span_count <= 0 || !pp->original_line_by_expanded_line || + !pp->belongs_to_main_file) { + return NULL; + } + qsort(raw->test_spans, (size_t)raw->test_span_count, sizeof(CBMTestSpan), test_span_order); +#ifdef CBM_ENABLE_TEST_SEAMS + cbm_test_span_test_count((uint64_t)raw->test_span_count); +#endif + *map = (CBMTestSpanMap){raw->test_spans, + raw->test_span_count, + pp->original_line_by_expanded_line, + pp->belongs_to_main_file, + pp->expanded_line_count, + NULL, + 0}; + cbm_test_span_index_view(map, raw->scratch ? raw->scratch : raw->arena, pp_root); + return map; +} + 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, @@ -3916,6 +3953,7 @@ static CBMFileResult *extract_file_ex_body( language == CBM_LANG_PYTHON ? CBM_PY_NS_NOT_CAPTURED : CBM_PY_NS_NOT_APPLICABLE; cbm_work_arena_take(&result->arena); CBMArena *a = &result->arena; + result->cpp_test_macro_names = cbm_cpp_test_macro_names_on(language, test_declarations); if (!cbm_test_declarations_validate(result, test_declarations)) { return result; } @@ -4330,6 +4368,12 @@ static CBMFileResult *extract_file_ex_body( TSNode pp_root = ts_tree_root_node(pp_tree); // Build context for expanded source — extract only calls via unified extractor + /* The raw view's GoogleTest definitions, so that this + * view names their bodies the same way however the + * expanded head reads (cbm_test_span_owner_qn). */ + CBMTestSpanMap pp_map; + const CBMTestSpanMap *pp_spans = + pp_test_span_map(&pp_map, &ctx, preprocessed, pp_root); CBMExtractCtx pp_ctx = { .arena = a, .scratch = scratch, @@ -4345,6 +4389,7 @@ static CBMFileResult *extract_file_ex_body( * cannot acquire a raw configured definition identity. */ .test_declarations = test_declarations, .test_declarations_raw_source = false, + .pp_test_spans = pp_spans, }; // Re-run unified extraction on expanded source. // This adds macro-expanded calls; duplicates with original calls are @@ -4366,7 +4411,8 @@ static CBMFileResult *extract_file_ex_body( // block). Runs in every mode. if (!result->lsp_skipped) { cbm_run_c_lsp(a, result, expanded, expanded_len, pp_root, - language != CBM_LANG_C, CBM_SOURCE_ORIGIN_PREPROCESSED); + language != CBM_LANG_C, CBM_SOURCE_ORIGIN_PREPROCESSED, + pp_spans); } /* All C-LSP emitters stamp origin directly so rewrite-time diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 15f2979a8..9841e3858 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -1105,6 +1105,10 @@ typedef struct CBMFileResult { int test_owner_source_len; CBMLanguage test_owner_language; char test_owner_source_sha256[65]; /* exact raw source; identity, not authentication */ + /* The def walk named this file's GoogleTest macro heads TEST_Suite_Case + * (cbm_cpp_test_macro_names_on): the C/C++ engine, per file and across + * files, names the callers in those bodies the same way. */ + bool cpp_test_macro_names; /* Doc-comment references of this file's definitions (doclink.h), and the * file's doc-link scope: a language-tagged text blob with what OTHER @@ -1150,6 +1154,40 @@ typedef struct { // Forward declaration: ObjectScript macro table (defined in macro_table.h). typedef struct CBMMacroTable CBMMacroTable; +/* The raw line span of a GoogleTest definition the def walk named with + * cbm_cpp_test_macro_name, and its qualified name. */ +typedef struct { + uint32_t start_line; + uint32_t end_line; + const char *qualified_name; +} CBMTestSpan; + +/* A top-level function definition of the preprocessed view (directly in the + * translation unit or in a namespace body) by its bytes in that view, and the + * raw test span its first and last lines map onto; span -1 when another + * top-level definition of the view maps onto the same span. */ +typedef struct { + uint32_t start_byte; + uint32_t end_byte; + int span; +} CBMTestViewDef; + +/* What the preprocessed second view of a C/C++ file needs to name a test body + * as the raw view did: the raw test definitions sorted by (start_line, + * end_line), the preprocessor's 1-based map from expanded lines to raw lines + * (0 = no raw line) with the lines that belong to the file itself, and the + * view's top-level definitions that map onto a raw test span, in document + * order (cbm_test_span_index_view). */ +typedef struct { + const CBMTestSpan *spans; + int count; + const uint32_t *raw_line_by_line; + const uint8_t *in_main_file; + int line_count; + const CBMTestViewDef *view_defs; + int view_def_count; +} CBMTestSpanMap; + // Method-return-type table for ObjectScript variable type inference. Populated // from definition nodes (method QN -> declared return type) so a later // `Set x = obj.Method()` can resolve x's class. @@ -1237,6 +1275,14 @@ typedef struct { /* Go: what each block's statements bind (extract_calls.c), NULL until a route call asks; * allocated in `scratch`. */ void *go_block_bindings; + /* C++/CUDA raw view: the GoogleTest definitions the def walk named + * (CBMTestSpan, in `scratch`), in walk order. */ + CBMTestSpan *test_spans; + int test_span_count; + int test_span_cap; + /* The preprocessed second view only: the raw view's test definitions and + * the line map (cbm_test_span_owner_qn). NULL in every raw view. */ + const CBMTestSpanMap *pp_test_spans; } CBMExtractCtx; /* Internal configured-definition seams. No declarations pointer enters a result. */ @@ -1261,6 +1307,46 @@ bool cbm_test_definition_owners_match(const CBMFileResult *owners, const char *s int source_len, bool cpp_mode, const char *module_qn); const char *cbm_test_definition_owner_qn(const CBMFileResult *owners, TSNode function); +/* GoogleTest test-case macros (TEST, TEST_F, TEST_P, TYPED_TEST, TYPED_TEST_P) + * parse as function definitions named by the bare macro. With the gtest preset + * on, a C++/CUDA definition is named __ (#1266), and every + * place that names the caller of a call in such a body names it through this + * one function: the def walk, the call-scope walk (compute_func_qn), + * cbm_enclosing_func_qn_cached and the C/C++ engine (c_process_function). + * `func_node` is the function_definition. NULL when `enabled` is false, `name` + * is not one of the five macros, or the head carries no argument; the caller + * keeps its own name then. */ +char *cbm_cpp_test_macro_name(CBMArena *a, bool enabled, const char *name, TSNode func_node, + const char *source); +/* The `enabled` argument above for a file of `language`: C++ or CUDA with the + * gtest preset on (on when nothing is configured). */ +bool cbm_cpp_test_macro_names_on(CBMLanguage language, const cbm_test_declarations_t *declarations); +/* The preprocessed view reads a head after macro expansion and without its + * comments, so it can spell a test differently from the raw view (a project + * macro among the arguments, a project's own TEST macro). A top-level function + * definition of that view whose first and last lines map to exactly one raw + * test definition's span (CBMTestSpanMap), and the only top-level definition + * of the view that does, is that test: its QN. Otherwise NULL and the caller + * names the body as usual: a method of a local class, a function written on a + * one-line test's line, two raw tests on one line. Used by the call scope, the + * enclosing-function helper and the C/C++ engine, the three places that name + * a caller. A binary search over the view's indexed definitions. */ +const char *cbm_test_span_owner_qn(const CBMTestSpanMap *map, TSNode function); +/* Index the preprocessed view's top-level function definitions (directly in + * the translation unit, or in namespace, extern-block, template and + * conditional bodies; never inside a function or class body) that map onto a + * raw test span, into map->view_defs (allocated in `a`). One pass over those + * containers plus a binary search per definition. On allocation failure the + * index stays empty and no body is named from a span. */ +void cbm_test_span_index_view(CBMTestSpanMap *map, CBMArena *a, TSNode root); +#ifdef CBM_ENABLE_TEST_SEAMS +/* Steps of the test-span searches and the view index walk plus spans indexed, + * since reset. */ +void cbm_test_span_test_reset(void); +uint64_t cbm_test_span_test_work(void); +void cbm_test_span_test_count(uint64_t work); +#endif + // --- Public API --- // Bind third-party allocators (tree-sitter, sqlite3) to mimalloc as diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 1cd747a6b..c0d052a35 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -5980,30 +5980,82 @@ static bool is_cpp_test_macro(const char *name) { * Returns an arena-allocated string, or NULL when the parameters cannot be * resolved (caller keeps the original name in that case). */ static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode node, - const char *source) { + const char *source); + +char *cbm_cpp_test_macro_name(CBMArena *a, bool enabled, const char *name, TSNode func_node, + const char *source) { + if (!enabled || !name || !source || ts_node_is_null(func_node) || !is_cpp_test_macro(name)) { + return NULL; + } + return resolve_cpp_test_macro_name(a, name, func_node, source); +} + +/* An argument's text without comments and without the blanks around it, in + * place: `Suite /\* c *\/` reads `Suite`, as the compiler (and the second, + * preprocessed view) sees it. */ +static char *cpp_test_arg_text(char *text) { + if (!text) { + return NULL; + } + char *w = text; + for (const char *r = text; *r;) { + if (r[0] == '/' && r[1] == '*') { + const char *close = strstr(r + 2, "*/"); + r = close ? close + 2 : r + strlen(r); + *w++ = ' '; + } else if (r[0] == '/' && r[1] == '/') { + while (*r && *r != '\n') { + r++; + } + } else { + *w++ = *r++; + } + } + *w = '\0'; + while (w > text && (w[-1] == ' ' || w[-1] == '\t' || w[-1] == '\n' || w[-1] == '\r')) { + *--w = '\0'; + } + char *start = text; + while (*start == ' ' || *start == '\t' || *start == '\n' || *start == '\r') { + start++; + } + return start; +} + +/* The first two arguments of a GoogleTest-style head `MACRO(a, b) {`: the text + * of each named parameter, its type node where the grammar gives one (`Suite` + * parses as a parameter whose type is that name). A comment in the head is an + * extra of the grammar, not an argument. Returns how many it found, at most + * two. */ +static int cpp_test_macro_args(CBMArena *a, TSNode node, const char *source, const char *args[2]) { TSNode params = ts_node_child_by_field_name(node, TS_FIELD("parameters")); if (ts_node_is_null(params)) { params = find_c_params(node); } if (ts_node_is_null(params)) { - return NULL; + return 0; } - - const char *args[2] = {NULL, NULL}; int count = 0; uint32_t nc = ts_node_named_child_count(params); for (uint32_t i = 0; i < nc && count < 2; i++) { TSNode child = ts_node_named_child(params, i); - if (ts_node_is_null(child)) { + if (ts_node_is_null(child) || strcmp(ts_node_type(child), "comment") == 0) { continue; } TSNode type_node = ts_node_child_by_field_name(child, TS_FIELD("type")); - char *text = cbm_node_text(a, ts_node_is_null(type_node) ? child : type_node, source); + char *text = cpp_test_arg_text( + cbm_node_text(a, ts_node_is_null(type_node) ? child : type_node, source)); if (text && text[0]) { args[count++] = text; } } + return count; +} +static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode node, + const char *source) { + const char *args[2] = {NULL, NULL}; + int count = cpp_test_macro_args(a, node, source, args); if (count == 2) { return cbm_arena_sprintf(a, "%s_%s_%s", macro, args[0], args[1]); } @@ -6013,6 +6065,192 @@ static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode return NULL; } +#ifdef CBM_ENABLE_TEST_SEAMS +static _Atomic uint64_t g_test_span_work = 0; +void cbm_test_span_test_reset(void) { + atomic_store_explicit(&g_test_span_work, 0, memory_order_relaxed); +} +uint64_t cbm_test_span_test_work(void) { + return atomic_load_explicit(&g_test_span_work, memory_order_relaxed); +} +void cbm_test_span_test_count(uint64_t work) { + atomic_fetch_add_explicit(&g_test_span_work, work, memory_order_relaxed); +} +#define TEST_SPAN_WORK(n) cbm_test_span_test_count(n) +#else +#define TEST_SPAN_WORK(n) ((void)0) +#endif + +static int test_span_cmp(const CBMTestSpan *s, uint32_t start, uint32_t end) { + if (s->start_line != start) { + return s->start_line < start ? -1 : 1; + } + return s->end_line == end ? 0 : (s->end_line < end ? -1 : 1); +} + +/* The raw test span (start, end): its index, or -1 when none or two raw tests + * share it. Binary search. */ +static int test_span_at(const CBMTestSpanMap *map, uint32_t start, uint32_t end) { + int lo = 0; + int hi = map->count; + while (lo < hi) { /* the first span not below (start, end) */ + int mid = lo + (hi - lo) / 2; + TEST_SPAN_WORK(1); + if (test_span_cmp(&map->spans[mid], start, end) < 0) { + lo = mid + 1; + } else { + hi = mid; + } + } + if (lo >= map->count || test_span_cmp(&map->spans[lo], start, end) != 0 || + (lo + 1 < map->count && test_span_cmp(&map->spans[lo + 1], start, end) == 0)) { + return -1; /* none, or two raw tests on one span */ + } + return lo; +} + +/* The raw test span a preprocessed-view definition's first and last lines map + * onto, or -1. */ +static int test_span_of(const CBMTestSpanMap *map, TSNode function) { + uint32_t first = ts_node_start_point(function).row + 1; + uint32_t last = ts_node_end_point(function).row + 1; + if (last < first || last > (uint32_t)map->line_count || !map->in_main_file[first] || + !map->in_main_file[last]) { + return -1; + } + uint32_t start = map->raw_line_by_line[first]; + uint32_t end = map->raw_line_by_line[last]; + return start && end ? test_span_at(map, start, end) : -1; +} + +/* Nodes whose children are still top level: namespace, extern-block and + * template bodies and the branches of conditionals. */ +static bool test_view_container(const char *kind) { + return strcmp(kind, "namespace_definition") == 0 || strcmp(kind, "declaration_list") == 0 || + strcmp(kind, "linkage_specification") == 0 || + strcmp(kind, "template_declaration") == 0 || strncmp(kind, "preproc_", 8) == 0; +} + +void cbm_test_span_index_view(CBMTestSpanMap *map, CBMArena *a, TSNode root) { + if (!map) { + return; + } + map->view_defs = NULL; + map->view_def_count = 0; + if (map->count <= 0 || !map->raw_line_by_line || !map->in_main_file || !a || + ts_node_is_null(root)) { + return; + } + CBMTestViewDef *defs = NULL; + int count = 0; + int cap = 0; + bool failed = false; + TSTreeCursor cursor = ts_tree_cursor_new(root); + int depth = 1; + bool more = ts_tree_cursor_goto_first_child(&cursor); + while (more && !failed) { + TSNode node = ts_tree_cursor_current_node(&cursor); + const char *kind = ts_node_type(node); + TEST_SPAN_WORK(1); + if (strcmp(kind, "function_definition") == 0) { + int span = test_span_of(map, node); + if (span >= 0 && count == cap) { + int grown_cap = cap ? cap * 2 : 16; + CBMTestViewDef *grown = + cbm_arena_alloc(a, (size_t)grown_cap * sizeof(CBMTestViewDef)); + if (!grown) { + failed = true; + break; + } + if (count) { + memcpy(grown, defs, (size_t)count * sizeof(CBMTestViewDef)); + } + defs = grown; + cap = grown_cap; + } + if (span >= 0) { + defs[count++] = + (CBMTestViewDef){ts_node_start_byte(node), ts_node_end_byte(node), span}; + } + } else if (test_view_container(kind) && ts_tree_cursor_goto_first_child(&cursor)) { + depth++; + continue; + } + while (!(more = ts_tree_cursor_goto_next_sibling(&cursor)) && depth > 1) { + ts_tree_cursor_goto_parent(&cursor); + depth--; + } + } + ts_tree_cursor_delete(&cursor); + int *per_span = + failed || count == 0 ? NULL : cbm_arena_alloc(a, (size_t)map->count * sizeof(int)); + if (!per_span) { + return; /* nothing maps, or out of memory: no body is named from a span */ + } + memset(per_span, 0, (size_t)map->count * sizeof(int)); + for (int i = 0; i < count; i++) { + per_span[defs[i].span]++; + } + for (int i = 0; i < count; i++) { + if (per_span[defs[i].span] != 1) { + defs[i].span = -1; /* two definitions of this view on one span: neither */ + } + } + map->view_defs = defs; + map->view_def_count = count; +} + +/* The raw test span of an indexed top-level definition of the preprocessed + * view, or -1: not indexed (not top level, or mapping onto no single raw + * test), or sharing its span with another such definition. */ +static int test_view_def_span(const CBMTestSpanMap *map, TSNode function) { + if (!map || map->view_def_count <= 0 || ts_node_is_null(function)) { + return -1; + } + uint32_t start = ts_node_start_byte(function); + int lo = 0; + int hi = map->view_def_count; + while (lo < hi) { /* the first indexed definition not before `function` */ + int mid = lo + (hi - lo) / 2; + TEST_SPAN_WORK(1); + if (map->view_defs[mid].start_byte < start) { + lo = mid + 1; + } else { + hi = mid; + } + } + if (lo >= map->view_def_count || map->view_defs[lo].start_byte != start || + map->view_defs[lo].end_byte != ts_node_end_byte(function)) { + return -1; /* not an indexed top-level definition of the view */ + } + return map->view_defs[lo].span; /* -1 on a shared span */ +} + +const char *cbm_test_span_owner_qn(const CBMTestSpanMap *map, TSNode function) { + int span = test_view_def_span(map, function); + return span >= 0 ? map->spans[span].qualified_name : NULL; +} + +/* Record a raw test definition's span for the preprocessed view (in scratch; + * amortised constant work per test). */ +static void record_test_span(CBMExtractCtx *ctx, const CBMDefinition *def) { + if (ctx->test_span_count == ctx->test_span_cap) { + int cap = ctx->test_span_cap ? ctx->test_span_cap * 2 : 16; + CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena; + CBMTestSpan *grown = cbm_arena_alloc(scratch, (size_t)cap * sizeof(*grown)); + if (!grown) { + return; /* the second view then names this body from its own head */ + } + if (ctx->test_span_count) { + memcpy(grown, ctx->test_spans, (size_t)ctx->test_span_count * sizeof(*grown)); + } + ctx->test_spans = grown; + ctx->test_span_cap = cap; + } + ctx->test_spans[ctx->test_span_count++] = + (CBMTestSpan){def->start_line, def->end_line, def->qualified_name}; +} + /* Configured macro definitions are interpreted only in their raw source. * The map lives in traversal scratch; its QNs live in the result arena. */ struct CBMTestDefinitionMatch { @@ -6135,11 +6373,21 @@ bool cbm_test_declarations_validate(CBMFileResult *result, return result->test_declarations_status == CBM_TEST_EXTRACT_OK; } -static bool tdx_preset(const CBMExtractCtx *ctx, cbm_test_preset_t preset) { - if (!ctx->test_declarations) +static bool tdx_preset_of(const cbm_test_declarations_t *declarations, cbm_test_preset_t preset) { + if (!declarations) return preset != CBM_TEST_PRESET_C_CBM; bool enabled = false; - return cbm_test_declarations_preset(ctx->test_declarations, preset, &enabled) && enabled; + return cbm_test_declarations_preset(declarations, preset, &enabled) && enabled; +} + +static bool tdx_preset(const CBMExtractCtx *ctx, cbm_test_preset_t preset) { + return tdx_preset_of(ctx->test_declarations, preset); +} + +bool cbm_cpp_test_macro_names_on(CBMLanguage language, + const cbm_test_declarations_t *declarations) { + return (language == CBM_LANG_CPP || language == CBM_LANG_CUDA) && + tdx_preset_of(declarations, CBM_TEST_PRESET_GTEST); } static bool tdx_equal(const char *name, const char *text, size_t size) { @@ -7569,7 +7817,8 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec /* C++/CUDA: GoogleTest macros (TEST, TEST_F, TEST_P, ...) parse as * function definitions whose name resolves to the bare macro identifier. * Multiple test cases per file collide on qualified name; derive a unique - * name from the macro arguments so each gets its own graph node (#1266). */ + * name from the macro arguments so each gets its own graph node (#1266). + * The callers of calls in the body are named by the same helper. */ bool is_gtest = false; const char *configured_name = NULL; TDXRule configured_rule; @@ -7579,14 +7828,14 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec return; name = (char *)configured_name; } - if (!configured && tdx_preset(ctx, CBM_TEST_PRESET_GTEST) && - (ctx->language == CBM_LANG_CPP || ctx->language == CBM_LANG_CUDA) && - is_cpp_test_macro(name)) { - char *gtest_name = resolve_cpp_test_macro_name(a, name, node, ctx->source); - if (gtest_name) { - name = gtest_name; - is_gtest = true; - } + char *gtest_name = + configured ? NULL + : cbm_cpp_test_macro_name( + a, cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), + name, node, ctx->source); + if (gtest_name) { + name = gtest_name; + is_gtest = true; } /* Nix `"${foo}" = x: …`: an interpolated attrpath segment has no statically @@ -7875,6 +8124,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec return; } cbm_defs_push(&ctx->result->defs, a, def); + if (is_gtest && ctx->test_declarations_raw_source && def.qualified_name) { + record_test_span(ctx, &def); + } if (ctx->language == CBM_LANG_MAKEFILE && strcmp(ts_node_type(node), "rule") == 0) { push_make_rule_targets(ctx, node, &def); } diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.c index 5176cd88d..8be0b6e63 100644 --- a/internal/cbm/extract_unified.c +++ b/internal/cbm/extract_unified.c @@ -1139,6 +1139,14 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan if (configured_qn) { return configured_qn; } + /* The preprocessed view of a C/C++ file: a body whose lines are a raw + * GoogleTest definition's is that test, whatever its expanded head reads. */ + if (ctx->pp_test_spans && strcmp(ts_node_type(node), "function_definition") == 0) { + const char *raw_test = cbm_test_span_owner_qn(ctx->pp_test_spans, node); + if (raw_test) { + return raw_test; + } + } /* C# local functions nested in a member have no graph node. Attribute calls * in them to the enclosing function, whose definition span contains the @@ -1307,6 +1315,17 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan return NULL; } + /* GoogleTest `TEST(Suite, Case) {...}` and its four siblings: the def + * extractor names the definition TEST_Suite_Case (#1266). Name the call + * scope through the same helper, or every call in the body names a + * definition that was never minted and is sourced at the File node. */ + char *test_name = cbm_cpp_test_macro_name( + ctx->arena, cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), name, node, + ctx->source); + if (test_name) { + name = test_name; + } + /* C++/CUDA out-of-line method `void Foo::bar() {...}`: the def extractor * records this as Method "proj.file.Foo.bar". The call-scope QN must match * (be class-qualified) so an in-body call sources to the method, not a bare diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.c index b14f371ec..259853306 100644 --- a/internal/cbm/helpers.c +++ b/internal/cbm/helpers.c @@ -1565,16 +1565,28 @@ static const char *func_node_name(CBMArena *a, TSNode func_node, const char *sou } const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source, - const char *project, const char *rel_path, - const char *module_qn) { + const char *project, const char *rel_path, const char *module_qn, + bool test_macro_names, const CBMTestSpanMap *pp_test_spans) { TSNode func_node = cbm_find_enclosing_func(node, lang); if (ts_node_is_null(func_node)) { return module_qn; } + /* The preprocessed view: a raw GoogleTest definition's body is that test. */ + if (pp_test_spans && strcmp(ts_node_type(func_node), "function_definition") == 0) { + const char *raw_test = cbm_test_span_owner_qn(pp_test_spans, func_node); + if (raw_test) { + return raw_test; + } + } const char *name = func_node_name(a, func_node, source, lang); if (!name || !name[0]) { return module_qn; } + /* GoogleTest TEST(Suite, Case): the def walk's TEST_Suite_Case (#1266). */ + const char *test_name = cbm_cpp_test_macro_name(a, test_macro_names, name, func_node, source); + if (test_name) { + name = test_name; + } // Check if the function is inside a class — compute classQN.funcName. // For nested classes the class QN must carry the FULL nesting chain @@ -1641,8 +1653,9 @@ const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node) { } // Cache miss: compute via parent walk - const char *qn = cbm_enclosing_func_qn(ctx->arena, node, ctx->language, ctx->source, - ctx->project, ctx->rel_path, ctx->module_qn); + const char *qn = cbm_enclosing_func_qn( + ctx->arena, node, ctx->language, ctx->source, ctx->project, ctx->rel_path, ctx->module_qn, + cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), ctx->pp_test_spans); // Cache the result: find the enclosing function's byte range TSNode func_node = cbm_find_enclosing_func(node, ctx->language); diff --git a/internal/cbm/helpers.h b/internal/cbm/helpers.h index 86757e5b1..62e2039a4 100644 --- a/internal/cbm/helpers.h +++ b/internal/cbm/helpers.h @@ -48,9 +48,14 @@ bool cbm_is_test_file(const char *rel_path, CBMLanguage lang); // Returns a null node if none found. TSNode cbm_find_enclosing_func(TSNode node, CBMLanguage lang); -// Get the QN of an enclosing function, or module_qn if none. +// Get the QN of an enclosing function, or module_qn if none. test_macro_names: +// a GoogleTest macro head is named as the def walk names it +// (cbm_cpp_test_macro_name; cbm_cpp_test_macro_names_on gives the value). +// pp_test_spans: the preprocessed view's map to the raw tests +// (cbm_test_span_owner_qn), NULL in a raw view. const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source, - const char *project, const char *rel_path, const char *module_qn); + const char *project, const char *rel_path, const char *module_qn, + bool test_macro_names, const CBMTestSpanMap *pp_test_spans); // Cached version: uses ctx->ef_cache to avoid repeated parent-chain walks. const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node); diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.c index 07d335a63..49e507f42 100644 --- a/internal/cbm/lsp/c_lsp.c +++ b/internal/cbm/lsp/c_lsp.c @@ -5769,9 +5769,19 @@ static void c_process_function(CLSPContext *ctx, TSNode func_node) { } } } + if (!func_qn && ctx->pp_test_spans) { + /* The preprocessed view: a raw GoogleTest definition's body is that + * test, whatever its expanded head reads (cbm_test_span_owner_qn). */ + func_qn = cbm_test_span_owner_qn(ctx->pp_test_spans, func_node); + } if (!func_qn) { + /* GoogleTest `TEST(Suite, Case)`: the definition is TEST_Suite_Case + * (#1266), named by the same helper as the def walk and the call + * scope; the pipeline joins this caller with theirs by exact QN. */ + const char *test_name = cbm_cpp_test_macro_name(ctx->arena, ctx->test_macro_names, + func_name, func_node, ctx->source); // Build enclosing function QN - func_qn = c_build_qn(ctx, func_name); + func_qn = c_build_qn(ctx, test_name ? test_name : func_name); // For a method defined INLINE inside its class body, func_name is a bare // identifier ("compute") and enclosing_class_qn was inherited from // c_process_class (saved_class_qn == enclosing_class_qn). The textual @@ -6827,16 +6837,30 @@ static void c_add_type_indexed(CBMTypeRegistry *reg, CTypeFirstIndex *ix, CBMAre } } +static bool c_lsp_file_run(CBMArena *arena, CBMFileResult *result, const char *source, + int source_len, TSNode root, bool cpp_mode, + CBMSourceOrigin source_origin, const CBMFileResult *test_owners, + const CBMTestSpanMap *pp_test_spans); + void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len, - TSNode root, bool cpp_mode, CBMSourceOrigin source_origin) { - (void)cbm_run_c_lsp_with_test_owners(arena, result, source, source_len, root, - cpp_mode, source_origin, NULL); + TSNode root, bool cpp_mode, CBMSourceOrigin source_origin, + const CBMTestSpanMap *pp_test_spans) { + (void)c_lsp_file_run(arena, result, source, source_len, root, cpp_mode, source_origin, NULL, + pp_test_spans); } -bool cbm_run_c_lsp_with_test_owners( - CBMArena *arena, CBMFileResult *result, const char *source, int source_len, - TSNode root, bool cpp_mode, CBMSourceOrigin source_origin, - const CBMFileResult *test_owners) { +bool cbm_run_c_lsp_with_test_owners(CBMArena *arena, CBMFileResult *result, const char *source, + int source_len, TSNode root, bool cpp_mode, + CBMSourceOrigin source_origin, + const CBMFileResult *test_owners) { + return c_lsp_file_run(arena, result, source, source_len, root, cpp_mode, source_origin, + test_owners, NULL); +} + +static bool c_lsp_file_run(CBMArena *arena, CBMFileResult *result, const char *source, + int source_len, TSNode root, bool cpp_mode, + CBMSourceOrigin source_origin, const CBMFileResult *test_owners, + const CBMTestSpanMap *pp_test_spans) { 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, @@ -7024,6 +7048,8 @@ bool cbm_run_c_lsp_with_test_owners( c_lsp_init(&ctx, arena, source, source_len, ®, module_qn, cpp_mode, &result->resolved_calls); ctx.source_origin = source_origin; ctx.test_definition_owners = test_owners; + ctx.test_macro_names = cpp_mode && result->cpp_test_macro_names; + ctx.pp_test_spans = pp_test_spans; c_memo_test_stage(&ctx, source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED ? "preprocessed" : "raw"); @@ -7225,7 +7251,7 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i const char **include_ns_qns, int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, CBMSourceOrigin source_origin, - const CBMFileResult *test_owners, + const CBMFileResult *test_owners, bool test_macro_names, CBMLSPStatus *status) { *status = CBM_LSP_COMPLETE; /* The retained or re-read source is the file on disk; read it the way the @@ -7263,6 +7289,7 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i c_lsp_init(&ctx, arena, source, source_len, reg, module_qn, cpp_mode, out); ctx.source_origin = source_origin; ctx.test_definition_owners = test_owners; + ctx.test_macro_names = cpp_mode && test_macro_names; ctx.registry_shared = true; /* Tier-2 shared registry: read-only, see flag doc */ for (int i = 0; i < include_count; i++) { c_lsp_add_include(&ctx, include_paths[i], include_ns_qns[i]); @@ -7277,6 +7304,8 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i return c_test_owners_complete(&ctx); } +/* Without a file result the extraction default holds: no configuration, so a + * C++ file's GoogleTest heads are named (cbm_cpp_test_macro_names_on). */ bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns, @@ -7284,17 +7313,17 @@ bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int CBMResolvedCallArray *out) { return cbm_run_c_lsp_cross_with_registry_status( arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns, - include_count, cached_tree, out) == CBM_LSP_COMPLETE; + include_count, cached_tree, out, cpp_mode) == CBM_LSP_COMPLETE; } CBMLSPStatus cbm_run_c_lsp_cross_with_registry_status( CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns, - int include_count, TSTree *cached_tree, CBMResolvedCallArray *out) { + int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, bool test_macro_names) { CBMLSPStatus status; - (void)c_lsp_cross_with_registry_run(arena, source, source_len, module_qn, cpp_mode, reg, - include_paths, include_ns_qns, include_count, cached_tree, - out, CBM_SOURCE_ORIGIN_RAW, NULL, &status); + (void)c_lsp_cross_with_registry_run( + arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns, + include_count, cached_tree, out, CBM_SOURCE_ORIGIN_RAW, NULL, test_macro_names, &status); return status; } @@ -7305,12 +7334,11 @@ bool cbm_run_c_lsp_cross_with_registry_with_test_owners( CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns, int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, - CBMSourceOrigin source_origin, const CBMFileResult *test_owners) { + CBMSourceOrigin source_origin, const CBMFileResult *test_owners, bool test_macro_names) { CBMLSPStatus status; - bool owners_ok = c_lsp_cross_with_registry_run(arena, source, source_len, module_qn, cpp_mode, - reg, include_paths, include_ns_qns, - include_count, cached_tree, out, source_origin, - test_owners, &status); + bool owners_ok = c_lsp_cross_with_registry_run( + arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns, + include_count, cached_tree, out, source_origin, test_owners, test_macro_names, &status); return owners_ok && status == CBM_LSP_COMPLETE; } @@ -7321,7 +7349,7 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len, const char **include_paths, const char **include_ns_qns, int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, CBMSourceOrigin source_origin, const CBMFileResult *test_owners, - CBMLSPStatus *status) { + bool test_macro_names, CBMLSPStatus *status) { *status = CBM_LSP_COMPLETE; /* Same bytes as the per-file extract (#1546); see * c_lsp_cross_with_registry_run. */ @@ -7376,6 +7404,7 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len, c_lsp_init(&ctx, arena, source, source_len, ®, module_qn, cpp_mode, out); ctx.source_origin = source_origin; ctx.test_definition_owners = test_owners; + ctx.test_macro_names = cpp_mode && test_macro_names; // Add include mappings for (int i = 0; i < include_count; i++) { @@ -7392,24 +7421,27 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len, return c_test_owners_complete(&ctx); } +/* No file result: the extraction default without configuration, as for + * cbm_run_c_lsp_cross_with_registry. */ bool cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths, const char **include_ns_qns, int include_count, TSTree *cached_tree, CBMResolvedCallArray *out) { return cbm_run_c_lsp_cross_status(arena, source, source_len, module_qn, cpp_mode, defs, def_count, include_paths, include_ns_qns, include_count, - cached_tree, out) == CBM_LSP_COMPLETE; + cached_tree, out, cpp_mode) == CBM_LSP_COMPLETE; } CBMLSPStatus cbm_run_c_lsp_cross_status(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths, const char **include_ns_qns, int include_count, - TSTree *cached_tree, CBMResolvedCallArray *out) { + TSTree *cached_tree, CBMResolvedCallArray *out, + bool test_macro_names) { CBMLSPStatus status; (void)c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs, def_count, include_paths, include_ns_qns, include_count, cached_tree, out, - CBM_SOURCE_ORIGIN_RAW, NULL, &status); + CBM_SOURCE_ORIGIN_RAW, NULL, test_macro_names, &status); return status; } @@ -7420,11 +7452,12 @@ bool cbm_run_c_lsp_cross_with_test_owners(CBMArena *arena, const char *source, i const char **include_ns_qns, int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, CBMSourceOrigin source_origin, - const CBMFileResult *test_owners) { + const CBMFileResult *test_owners, bool test_macro_names) { CBMLSPStatus status; - bool owners_ok = c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs, - def_count, include_paths, include_ns_qns, include_count, - cached_tree, out, source_origin, test_owners, &status); + bool owners_ok = + c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs, def_count, + include_paths, include_ns_qns, include_count, cached_tree, out, + source_origin, test_owners, test_macro_names, &status); return owners_ok && status == CBM_LSP_COMPLETE; } diff --git a/internal/cbm/lsp/c_lsp.h b/internal/cbm/lsp/c_lsp.h index 61289715f..76786063a 100644 --- a/internal/cbm/lsp/c_lsp.h +++ b/internal/cbm/lsp/c_lsp.h @@ -83,6 +83,9 @@ typedef struct { CBMResolvedCallArray *resolved_calls; CBMSourceOrigin source_origin; // source buffer represented by emitted occurrence spans const CBMFileResult *test_definition_owners; /* borrowed, prevalidated raw source identity */ + /* The preprocessed per-file run only: the raw view's GoogleTest spans and + * the line map (cbm_test_span_owner_qn). Borrowed; NULL otherwise. */ + const CBMTestSpanMap *pp_test_spans; int test_owner_seen_count; bool test_owner_error; @@ -113,6 +116,8 @@ typedef struct { // Flags bool cpp_mode; // C++ features enabled + bool test_macro_names; // GoogleTest heads are named as the def walk names them + // (CBMFileResult.cpp_test_macro_names, cbm_cpp_test_macro_name) bool in_template; // currently inside template declaration bool registry_shared; // ctx->registry is the Tier-2 cross registry, shared // READ-ONLY across resolve workers — never mutate it @@ -175,8 +180,11 @@ const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_p // --- Entry points --- // Single-file LSP: build registry from file defs + stdlib, run resolution. +// pp_test_spans: for the preprocessed view, the raw GoogleTest spans and line +// map (cbm_test_span_owner_qn); NULL otherwise. void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len, - TSNode root, bool cpp_mode, CBMSourceOrigin source_origin); + TSNode root, bool cpp_mode, CBMSourceOrigin source_origin, + const CBMTestSpanMap *pp_test_spans); // A memo allocation/capacity failure is an explicit incomplete-refinement error. #define CBM_C_LSP_DEPTH_ERROR "C/C++ expression recursion depth limit exceeded" @@ -191,13 +199,15 @@ uint32_t cbm_c_lsp_test_walks_take(void); // Cross-file LSP: build registry from defs + stdlib, re-parse and resolve. // Status variants distinguish memo/depth failure. Bool wrappers report success. -// Completed output before a failed walk is kept. +// Completed output before a failed walk is kept. test_macro_names: the file's +// CBMFileResult.cpp_test_macro_names (the bool wrappers pass cpp_mode, the +// extraction default without configuration). CBMLSPStatus cbm_run_c_lsp_cross_status(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths, const char **include_ns_qns, int include_count, TSTree *cached_tree, // NULL = parse internally - CBMResolvedCallArray *out); + CBMResolvedCallArray *out, bool test_macro_names); bool cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths, @@ -217,7 +227,7 @@ CBMLSPStatus cbm_run_c_lsp_cross_with_registry_status( CBMTypeRegistry *reg, // pre-built, finalized, READ-ONLY const char **include_paths, const char **include_ns_qns, int include_count, TSTree *cached_tree, // NULL = parse internally - CBMResolvedCallArray *out); + CBMResolvedCallArray *out, bool test_macro_names); bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, @@ -239,18 +249,18 @@ bool cbm_run_c_lsp_with_test_owners( CBMArena *arena, CBMFileResult *result, const char *source, int source_len, TSNode root, bool cpp_mode, CBMSourceOrigin source_origin, const CBMFileResult *test_owners); -bool cbm_run_c_lsp_cross_with_test_owners( - CBMArena *arena, const char *source, int source_len, const char *module_qn, - bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths, - const char **include_ns_qns, int include_count, TSTree *cached_tree, - CBMResolvedCallArray *out, CBMSourceOrigin source_origin, - const CBMFileResult *test_owners); +bool cbm_run_c_lsp_cross_with_test_owners(CBMArena *arena, const char *source, int source_len, + const char *module_qn, bool cpp_mode, CBMLSPDef *defs, + int def_count, const char **include_paths, + const char **include_ns_qns, int include_count, + TSTree *cached_tree, CBMResolvedCallArray *out, + CBMSourceOrigin source_origin, + const CBMFileResult *test_owners, bool test_macro_names); bool cbm_run_c_lsp_cross_with_registry_with_test_owners( - CBMArena *arena, const char *source, int source_len, const char *module_qn, - bool cpp_mode, CBMTypeRegistry *reg, const char **include_paths, - const char **include_ns_qns, int include_count, TSTree *cached_tree, - CBMResolvedCallArray *out, CBMSourceOrigin source_origin, - const CBMFileResult *test_owners); + CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode, + CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns, + int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, + CBMSourceOrigin source_origin, const CBMFileResult *test_owners, bool test_macro_names); // Register C stdlib types and functions into a registry. void cbm_c_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena); diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index 186d09ca8..7408defc4 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -2357,7 +2357,7 @@ static bool pxc_c_run_registry(const pxc_file_t *f, pxc_walk_t *w) { if (!cbm_run_c_lsp_cross_with_registry_with_test_owners( w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->reg, f->imp_keys, f->imp_vals, f->imp_count, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW, - f->result)) { + f->result, f->result->cpp_test_macro_names)) { cbm_pipeline_test_owner_error(f->result); return false; /* no append and no fallback on an invalid proof */ } @@ -2365,7 +2365,7 @@ static bool pxc_c_run_registry(const pxc_file_t *f, pxc_walk_t *w) { } CBMLSPStatus status = cbm_run_c_lsp_cross_with_registry_status( w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->reg, f->imp_keys, - f->imp_vals, f->imp_count, f->result->cached_tree, w->out); + f->imp_vals, f->imp_count, f->result->cached_tree, w->out, f->result->cpp_test_macro_names); if (status != CBM_LSP_COMPLETE) cbm_c_lsp_record_failure(f->result, status); return true; @@ -2380,15 +2380,16 @@ static bool pxc_c_run_defs(const pxc_file_t *f, pxc_walk_t *w) { if (f->result->has_test_definition_owners) { if (!cbm_run_c_lsp_cross_with_test_owners( w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->defs, w->def_count, - NULL, NULL, 0, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW, f->result)) { + NULL, NULL, 0, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW, f->result, + f->result->cpp_test_macro_names)) { cbm_pipeline_test_owner_error(f->result); return false; /* out may be partial: never append it */ } return true; } - CBMLSPStatus status = cbm_run_c_lsp_cross_status(w->scratch, f->source, f->source_len, - f->module_qn, cpp_mode, w->defs, w->def_count, - NULL, NULL, 0, f->result->cached_tree, w->out); + CBMLSPStatus status = cbm_run_c_lsp_cross_status( + w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->defs, w->def_count, NULL, + NULL, 0, f->result->cached_tree, w->out, f->result->cpp_test_macro_names); if (status != CBM_LSP_COMPLETE) cbm_c_lsp_record_failure(f->result, status); return true; diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.c index 16c1b0ca9..a7a46eb55 100644 --- a/tests/test_c_lsp.c +++ b/tests/test_c_lsp.c @@ -17130,10 +17130,10 @@ TEST(clsp_issue1527_depth_failure_reports_all_entry_points) { } else { CBMLSPStatus status = mode == 0 ? cbm_run_c_lsp_cross_status(&arena, src, (int)strlen(src), "test", true, - defs, 2, NULL, NULL, 0, NULL, &out) + defs, 2, NULL, NULL, 0, NULL, &out, true) : cbm_run_c_lsp_cross_with_registry_status(&arena, src, (int)strlen(src), "test", true, &overlay, NULL, - NULL, 0, NULL, &out); + NULL, 0, NULL, &out, true); correct = correct && status == CBM_LSP_DEPTH_EXCEEDED; } correct = correct && out.count == 0; diff --git a/tests/test_extraction.c b/tests/test_extraction.c index 8656e191c..e2ba327bd 100644 --- a/tests/test_extraction.c +++ b/tests/test_extraction.c @@ -4830,6 +4830,281 @@ TEST(cpp_gtest_f_unique_name_issue1266) { PASS(); } +/* A call written in a GoogleTest body belongs to the test's own node. The def + * walk names TEST(Suite, Case) TEST_Suite_Case (#1266), so the three places + * that name the caller of a call must name it the same way: the call-scope + * walk (CBMCall.enclosing_func_qn), the enclosing-function helper behind the + * reference extractors (CBMUsage.enclosing_func_qn) and the C/C++ engine + * (CBMResolvedCall.caller_qn). Under the bare macro name no node exists, and + * the pipeline sources every such call at the file. One row per macro form + * the def walk renames, plus one inside a namespace. */ +static const char gtest_caller_src[] = + "int helper_sum(int a, int b) { return a + b; }\n" + "int kLimit = 3;\n" + "TEST(WidgetSuite, Adds) { helper_sum(1, kLimit); }\n" + "TEST_F(WidgetFixture, Runs) { helper_sum(2, kLimit); }\n" + "TEST_P(WidgetParam, Each) { helper_sum(3, kLimit); }\n" + "TYPED_TEST(WidgetTyped, Holds) { helper_sum(4, kLimit); }\n" + "TYPED_TEST_P(WidgetTypedP, Keeps) { helper_sum(5, kLimit); }\n" + "namespace demo {\n" + "TEST(NsSuite, Inside) { helper_sum(6, kLimit); }\n" + "}\n"; + +static const char *const gtest_caller_names[] = { + "TEST_WidgetSuite_Adds", "TEST_F_WidgetFixture_Runs", "TEST_P_WidgetParam_Each", + "TYPED_TEST_WidgetTyped_Holds", "TYPED_TEST_P_WidgetTypedP_Keeps", "demo.TEST_NsSuite_Inside"}; + +static int count_resolved_from(const CBMFileResult *r, const char *caller_qn, + const char *callee_suffix) { + int count = 0; + size_t sl = strlen(callee_suffix); + for (int i = 0; i < r->resolved_calls.count; i++) { + const CBMResolvedCall *rc = &r->resolved_calls.items[i]; + size_t cl = rc->callee_qn ? strlen(rc->callee_qn) : 0; + if (rc->caller_qn && strcmp(rc->caller_qn, caller_qn) == 0 && cl >= sl && + strcmp(rc->callee_qn + cl - sl, callee_suffix) == 0) { + count++; + } + } + return count; +} + +TEST(cpp_gtest_body_caller_is_test_node) { + CBMFileResult *r = extract(gtest_caller_src, CBM_LANG_CPP, "t", "widget_test.cc"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + /* Inputs reached: every body's call and reference was extracted. */ + ASSERT_EQ(count_calls_named(r, "helper_sum"), 6); + ASSERT_EQ(count_usages_named(r, "kLimit"), 6); + for (size_t i = 0; i < sizeof(gtest_caller_names) / sizeof(gtest_caller_names[0]); i++) { + const CBMDefinition *def = find_def_in_module(r, gtest_caller_names[i]); + if (!def) { + printf(" no definition %s\n", gtest_caller_names[i]); + } + ASSERT_NOT_NULL(def); + int calls = count_calls_from(r, "helper_sum", def->qualified_name); + int refs = count_usages_from(r, "kLimit", def->qualified_name); + int lsp = count_resolved_from(r, def->qualified_name, ".helper_sum"); + if (calls != 1 || refs != 1 || lsp != 1) { + printf(" %s: calls %d, references %d, engine %d\n", def->qualified_name, calls, refs, + lsp); + } + ASSERT_EQ(calls, 1); /* RED on 08a7a586: the call-scope walk says .TEST */ + ASSERT_EQ(refs, 1); /* RED on 08a7a586: cbm_enclosing_func_qn says .TEST */ + ASSERT_EQ(lsp, 1); /* RED on 08a7a586: the engine's caller is .TEST */ + } + /* Nothing is left on the bare macro names (the positive rows above are the + * partner: the same calls, under the test names). */ + static const char *const bare[] = {"TEST", "TEST_F", "TEST_P", + "TYPED_TEST", "TYPED_TEST_P", "demo.TEST"}; + for (size_t i = 0; i < sizeof(bare) / sizeof(bare[0]); i++) { + char qn[256]; + snprintf(qn, sizeof(qn), "%s.%s", r->module_qn, bare[i]); + ASSERT_EQ(count_calls_from(r, "helper_sum", qn), 0); + ASSERT_EQ(count_usages_from(r, "kLimit", qn), 0); + ASSERT_EQ(count_resolved_from(r, qn, ".helper_sum"), 0); + } + cbm_free_result(r); + PASS(); +} + +/* Every C++ file is also read a second time after the built-in preprocessor, + * and that view can spell a test's head differently: a project macro among the + * arguments is expanded, comments are gone, and a project's own TEST macro is + * replaced by its expansion. The second view must still name the body as the + * raw view's definition, or the same call is drawn from the test node and, a + * second time, from the File. The definition's name drops comments from the + * head's arguments. Rows of each view are counted per origin, so the second + * view is shown to have run (the positive partner of "no other caller"). */ +static int pp_rows(const CBMFileResult *r, const char *callee, const char *ref, + const char *caller_qn, CBMSourceOrigin origin, int *calls, int *engine, + int *refs) { + *calls = *engine = *refs = 0; + for (int i = 0; i < r->calls.count; i++) { + const CBMCall *c = &r->calls.items[i]; + *calls += c->callee_name && strcmp(c->callee_name, callee) == 0 && + c->source_origin == origin && c->enclosing_func_qn && + (!caller_qn || strcmp(c->enclosing_func_qn, caller_qn) == 0); + } + for (int i = 0; i < r->resolved_calls.count; i++) { + const CBMResolvedCall *rc = &r->resolved_calls.items[i]; + size_t cl = rc->callee_qn ? strlen(rc->callee_qn) : 0; + size_t nl = strlen(callee); + *engine += rc->kind == CBM_RESOLVED_INVOCATION && rc->source_origin == origin && cl > nl && + rc->callee_qn[cl - nl - 1] == '.' && + strcmp(rc->callee_qn + cl - nl, callee) == 0 && rc->caller_qn && + (!caller_qn || strcmp(rc->caller_qn, caller_qn) == 0); + } + for (int i = 0; i < r->usages.count; i++) { + const CBMUsage *u = &r->usages.items[i]; + *refs += u->ref_name && strcmp(u->ref_name, ref) == 0 && u->source_origin == origin && + u->enclosing_func_qn && + (!caller_qn || strcmp(u->enclosing_func_qn, caller_qn) == 0); + } + return *calls + *engine + *refs; +} + +/* `callee` and `ref` occur in this test's body only. */ +static int assert_pp_view_names_raw_test(const CBMFileResult *r, const char *def_name, + const char *callee, const char *ref) { + const CBMDefinition *def = NULL; + for (int i = 0; i < r->defs.count; i++) { + if (r->defs.items[i].name && strcmp(r->defs.items[i].name, def_name) == 0) { + def = &r->defs.items[i]; + } + } + if (!def) { + printf(" no definition named %s\n", def_name); + } + ASSERT_NOT_NULL(def); + int any[3]; + int own[3]; + for (int origin = 0; origin < 2; origin++) { + CBMSourceOrigin o = origin ? CBM_SOURCE_ORIGIN_PREPROCESSED : CBM_SOURCE_ORIGIN_RAW; + (void)pp_rows(r, callee, ref, NULL, o, &any[0], &any[1], &any[2]); + (void)pp_rows(r, callee, ref, def->qualified_name, o, &own[0], &own[1], &own[2]); + if (any[0] != own[0] || any[1] != own[1] || any[2] != own[2]) { + printf( + " %s, %s view: calls %d of %d, engine %d of %d, references %d of %d at the test\n", + def_name, origin ? "preprocessed" : "raw", own[0], any[0], own[1], any[1], own[2], + any[2]); + } + /* Both views saw the call, its resolution and the reference. */ + ASSERT_GTE(any[0], 1); + ASSERT_GTE(any[1], 1); + ASSERT_GTE(any[2], 1); + /* RED on cbm-ctest-caller-c2a10ffd: the preprocessed view names the + * test from its own head text, a name no definition carries. */ + ASSERT_EQ(own[0], any[0]); + ASSERT_EQ(own[1], any[1]); + ASSERT_EQ(own[2], any[2]); + } + return 0; +} + +TEST(cpp_gtest_preprocessed_view_names_the_raw_test) { + static const char suites[] = "int kVia = 1;\n" + "int kBlock = 2;\n" + "int kLine = 3;\n" + "int via_target(int v) { return v; }\n" + "int block_target(int v) { return v; }\n" + "int line_target(int v) { return v; }\n" + "#define MY_SUITE RealSuite\n" + "TEST(MY_SUITE, ViaMacro) { via_target(kVia); }\n" + "TEST(CommentSuite /* c */, Commented) { block_target(kBlock); }\n" + "TEST(LineCommentSuite, // why\n" + " LineCommented) {\n" + " line_target(kLine);\n" + "}\n"; + CBMFileResult *r = extract(suites, CBM_LANG_CPP, "t", "misc_test.cc"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + /* The definitions keep the raw head's names, without its comments + * (RED on cbm-ctest-caller-c2a10ffd: TEST_CommentSuite_/\* c *\/). */ + ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_MY_SUITE_ViaMacro", "via_target", "kVia"), 0); + ASSERT_EQ( + assert_pp_view_names_raw_test(r, "TEST_CommentSuite_Commented", "block_target", "kBlock"), + 0); + ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_LineCommentSuite_LineCommented", "line_target", + "kLine"), + 0); + cbm_free_result(r); + + /* A project's own one-argument TEST macro: the def walk names its use + * TEST_alpha, the second view sees `void test_alpha()`. */ + static const char own[] = "int kShared = 1;\n" + "int helper_b(int v) { return v; }\n" + "#define TEST(name) void test_##name()\n" + "TEST(alpha) { helper_b(kShared); }\n"; + r = extract(own, CBM_LANG_CPP, "t", "own_test_macro.cc"); + ASSERT_NOT_NULL(r); + ASSERT_FALSE(r->has_error); + ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_alpha", "helper_b", "kShared"), 0); + cbm_free_result(r); + PASS(); +} + +/* Two tests on one line share their raw line span, so the second view cannot + * tell them apart by lines: each keeps the name its own head gives, which is + * the raw view's name when the two heads read the same. */ +TEST(cpp_gtest_preprocessed_view_one_line_pair) { + static const char src[] = "int kShared = 1;\n" + "int helper_c(int v) { return v; }\n" + "#define UNUSED_MACRO 1\n" + "TEST(PairSuite, First) { helper_c(kShared); } " + "TEST(PairSuite, Second) { helper_c(kShared); }\n"; + CBMFileResult *r = extract(src, CBM_LANG_CPP, "t", "pair_test.cc"); + ASSERT_NOT_NULL(r); + const CBMDefinition *first = find_def_in_module(r, "TEST_PairSuite_First"); + const CBMDefinition *second = find_def_in_module(r, "TEST_PairSuite_Second"); + ASSERT_NOT_NULL(first); + ASSERT_NOT_NULL(second); + int any[3]; + int a[3]; + int b[3]; + (void)pp_rows(r, "helper_c", "kShared", NULL, CBM_SOURCE_ORIGIN_PREPROCESSED, &any[0], &any[1], + &any[2]); + (void)pp_rows(r, "helper_c", "kShared", first->qualified_name, CBM_SOURCE_ORIGIN_PREPROCESSED, + &a[0], &a[1], &a[2]); + (void)pp_rows(r, "helper_c", "kShared", second->qualified_name, CBM_SOURCE_ORIGIN_PREPROCESSED, + &b[0], &b[1], &b[2]); + ASSERT_EQ(any[0], 2); /* the second view ran and saw both calls */ + ASSERT_EQ(a[0], 1); + ASSERT_EQ(b[0], 1); + ASSERT_EQ(a[1] + b[1], any[1]); + cbm_free_result(r); + PASS(); +} + +/* The preprocessed view finds the raw test of a body by a binary search over + * the file's test spans, sorted once per file, and over the view's indexed + * top-level definitions: counted work (spans indexed, nodes walked, search + * steps) grows like n log n with the number of tests, never n^2. So it pins + * "not worse than main's growth": main's own calls pass on such a file grows + * faster than n log n (not counted here), and this change adds no growth of + * its own beyond n log n. */ +static uint64_t pp_test_span_work(int tests, int *at_tests) { + size_t cap = (size_t)tests * 64 + 256; + char *src = malloc(cap); + if (!src) { + return UINT64_MAX; + } + int off = snprintf(src, cap, "int span_target() { return 0; }\n#define SPAN_UNUSED 1\n"); + for (int i = 0; i < tests; i++) { + off += snprintf(src + off, cap - (size_t)off, + "TEST(SpanSuite, Case%d) { span_target(); }\n", i); + } + cbm_test_span_test_reset(); + CBMFileResult *r = cbm_extract_file(src, off, CBM_LANG_CPP, "t", "span_test.cc", 0, NULL, NULL); + free(src); + uint64_t work = r ? cbm_test_span_test_work() : UINT64_MAX; + *at_tests = 0; + for (int i = 0; r && i < r->calls.count; i++) { + const CBMCall *c = &r->calls.items[i]; + *at_tests += c->source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED && c->callee_name && + strcmp(c->callee_name, "span_target") == 0 && c->enclosing_func_qn && + strstr(c->enclosing_func_qn, ".TEST_SpanSuite_Case") != NULL; + } + cbm_free_result(r); + return work; +} + +TEST(cpp_gtest_preprocessed_view_lookup_growth) { + enum { SMALL = 100, BIG = 1000, WORK_RATIO_MAX = 20 }; + int small_at = 0; + int big_at = 0; + uint64_t small = pp_test_span_work(SMALL, &small_at); + uint64_t big = pp_test_span_work(BIG, &big_at); + fprintf(stderr, " [pp-test-spans] work(%d)=%llu work(%d)=%llu\n", SMALL, + (unsigned long long)small, BIG, (unsigned long long)big); + ASSERT_TRUE(small != UINT64_MAX && big != UINT64_MAX); + ASSERT_EQ(small_at, SMALL); /* the second view ran and placed every body */ + ASSERT_EQ(big_at, BIG); + ASSERT_GTE(small, (uint64_t)SMALL); + ASSERT(big <= small * WORK_RATIO_MAX); /* 10x input: n log n is about 15x, n^2 100x */ + PASS(); +} + /* --- C++ out-of-line method definitions (#428) --- * A .cpp defining methods of a class declared elsewhere (not in this TU). * Pre-fix these were recorded as free Functions (label "Function", no @@ -16358,6 +16633,10 @@ SUITE(extraction) { RUN_TEST(cpp_function); RUN_TEST(cpp_gtest_same_name_collision_issue1266); RUN_TEST(cpp_gtest_f_unique_name_issue1266); + RUN_TEST(cpp_gtest_body_caller_is_test_node); + RUN_TEST(cpp_gtest_preprocessed_view_names_the_raw_test); + RUN_TEST(cpp_gtest_preprocessed_view_one_line_pair); + RUN_TEST(cpp_gtest_preprocessed_view_lookup_growth); RUN_TEST(cpp_out_of_line_method_issue428); RUN_TEST(cobol_paragraph); RUN_TEST(verilog_module); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index 8381337a0..a1aa54e56 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -35611,6 +35611,590 @@ TEST(pipeline_cpp_unresolvable_receiver_stays_unbound_issue1153) { PASS(); } +/* GoogleTest bodies: the CALLS edges of a call written in a TEST or TEST_F + * body start at the test's own node (TEST_Suite_Case, #1266), not at the File + * node. local_helper is bound by the C/C++ engine in the file's own pass, so + * its lsp_ strategy also proves the engine and the text path name the same + * caller (they join by exact caller QN); cross_helper lives in another file. + * pad_files > 0 adds filler C++ files past MIN_FILES_FOR_PARALLEL. */ +static void write_cpp_gtest_caller_fixture(const char *tmp, int pad_files) { + write_temp_file(tmp, "lib/helper.h", "int cross_helper(int v);\n"); + write_temp_file(tmp, "lib/helper.cc", + "#include \"helper.h\"\n" + "int cross_helper(int v) { return v + 1; }\n"); + write_temp_file(tmp, "test/widget_test.cc", + "#include \"../lib/helper.h\"\n" + "static int local_helper(int v) { return v * 2; }\n" + "class WidgetFixture {\n" + " public:\n" + " int Prepare() { return 1; }\n" + "};\n" + "TEST(WidgetSuite, Adds) {\n" + " local_helper(1);\n" + " cross_helper(2);\n" + "}\n" + "TEST_F(WidgetFixture, Runs) {\n" + " local_helper(3);\n" + " cross_helper(4);\n" + "}\n"); + for (int i = 0; i < pad_files; i++) { + char name[64]; + char body[128]; + snprintf(name, sizeof(name), "pad/filler%d.cc", i); + snprintf(body, sizeof(body), "int filler%d() { return %d; }\n", i, i); + write_temp_file(tmp, name, body); + } +} + +static int assert_cpp_gtest_caller_edges(cbm_store_t *s, const char *project, bool parallel) { + static const char *const tests[] = {".test.widget_test.TEST_WidgetSuite_Adds", + ".test.widget_test.TEST_F_WidgetFixture_Runs"}; + const char *mode = parallel ? "parallel" : "sequential"; + int local[2]; + int cross[2]; + for (int i = 0; i < 2; i++) { + local[i] = go_calls_between(s, project, tests[i], ".test.widget_test.local_helper", + "\"strategy\":\"lsp_"); + cross[i] = go_calls_between(s, project, tests[i], ".lib.helper.cross_helper", NULL); + if (local[i] != 1 || cross[i] != 1) { + printf(" [%s] %s: local_helper %d (lsp), cross_helper %d\n", mode, tests[i], local[i], + cross[i]); + } + } + /* The File node keeps no copy (the rows above are the positive partner; + * its DEFINES edge proves the File node's name, which keeps the file's + * extension). */ + const char *file_qn = ".test.widget_test.cc.__file__"; + int file_defines = + go_edges_between(s, project, "DEFINES", file_qn, ".test.widget_test.local_helper"); + int file_local = go_calls_between(s, project, file_qn, ".test.widget_test.local_helper", NULL); + int file_cross = go_calls_between(s, project, file_qn, ".lib.helper.cross_helper", NULL); + if (file_local != 0 || file_cross != 0) { + printf(" [%s] File node: local_helper %d, cross_helper %d\n", mode, file_local, + file_cross); + } + for (int i = 0; i < 2; i++) { + ASSERT_EQ(local[i], 1); /* RED on 08a7a586: sourced at the File node */ + ASSERT_EQ(cross[i], 1); /* RED on 08a7a586: sourced at the File node */ + } + ASSERT_EQ(file_defines, 1); + ASSERT_EQ(file_local, 0); + ASSERT_EQ(file_cross, 0); + return 0; +} + +TEST(pipeline_cpp_gtest_body_calls_start_at_test_node) { + int runs[2] = {-1, -1}; + int verdicts[2] = {-1, -1}; + for (int mode = 0; mode < 2; mode++) { + bool parallel = mode == 1; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_cpp_gtest_caller_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + write_cpp_gtest_caller_fixture(tmp, parallel ? 52 : 0); + const char *old_workers = getenv("CBM_WORKERS"); + char *saved = old_workers ? strdup(old_workers) : NULL; + cbm_setenv("CBM_WORKERS", parallel ? "4" : "1", 1); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/gtest_caller.db", tmp); + cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL); + int run = p ? cbm_pipeline_run(p) : -1; + cbm_store_t *s = run == 0 ? cbm_store_open_path(db_path) : NULL; + int verdict = + s ? assert_cpp_gtest_caller_edges(s, cbm_pipeline_project_name(p), parallel) : -1; + if (s) { + cbm_store_close(s); + } + if (p) { + cbm_pipeline_free(p); + } + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + th_rmtree(tmp); + runs[mode] = run; + verdicts[mode] = verdict; + } + ASSERT_EQ(runs[0], 0); + ASSERT_EQ(runs[1], 0); + ASSERT_EQ(verdicts[0], 0); /* sequential resolver */ + ASSERT_EQ(verdicts[1], 0); /* parallel resolver */ + PASS(); +} + +/* The reviewer's shapes (ctest-review finding 5): the preprocessed second view + * of a file spells the head differently from the raw view (a project macro in + * the arguments, comments, a project's own TEST macro). Each call written in + * such a body has one source, the test's node; the File keeps none. */ +static void write_cpp_gtest_pp_view_fixture(const char *tmp, int pad_files) { + write_temp_file(tmp, "lib/sites.h", + "int s01();\nint s02();\nint s09();\nint s10();\nint s11();\nint s17();\n"); + write_temp_file( + tmp, "lib/sites.cc", + "#include \"sites.h\"\n" + "int s01() { return 1; }\nint s02() { return 2; }\nint s09() { return 9; }\n" + "int s10() { return 10; }\nint s11() { return 11; }\nint s17() { return 17; }\n"); + write_temp_file(tmp, "test/misc_test.cc", + "#include \"../lib/sites.h\"\n" + "#define MY_SUITE RealSuite\n" + "TEST(MY_SUITE, ViaMacro) { s09(); }\n" + "TEST(CommentSuite, /* why */ Commented) { s10(); }\n" + "TEST(LineCommentSuite, // why\n" + " LineCommented) {\n" + " s11();\n" + "}\n" + "TEST(BlockSuite /* c */, Commented) { s17(); }\n"); + write_temp_file(tmp, "test/own_test_macro.cc", + "#include \"../lib/sites.h\"\n" + "#define TEST(name) void test_##name()\n" + "TEST(alpha) { s01(); }\n" + "TEST(beta) { s02(); }\n"); + for (int i = 0; i < pad_files; i++) { + char name[64]; + char body[128]; + snprintf(name, sizeof(name), "pad/filler%d.cc", i); + snprintf(body, sizeof(body), "int filler%d() { return %d; }\n", i, i); + write_temp_file(tmp, name, body); + } +} + +static int assert_cpp_gtest_pp_view_edges(cbm_store_t *s, const char *project, bool parallel) { + static const struct { + const char *file; + const char *test; + const char *callee; + } rows[] = { + {".test.misc_test.cc.__file__", ".test.misc_test.TEST_MY_SUITE_ViaMacro", ".lib.sites.s09"}, + {".test.misc_test.cc.__file__", ".test.misc_test.TEST_CommentSuite_Commented", + ".lib.sites.s10"}, + {".test.misc_test.cc.__file__", ".test.misc_test.TEST_LineCommentSuite_LineCommented", + ".lib.sites.s11"}, + {".test.misc_test.cc.__file__", ".test.misc_test.TEST_BlockSuite_Commented", + ".lib.sites.s17"}, + {".test.own_test_macro.cc.__file__", ".test.own_test_macro.TEST_alpha", ".lib.sites.s01"}, + {".test.own_test_macro.cc.__file__", ".test.own_test_macro.TEST_beta", ".lib.sites.s02"}, + }; + int bad = 0; + for (size_t i = 0; i < sizeof(rows) / sizeof(rows[0]); i++) { + int defines = go_edges_between(s, project, "DEFINES", rows[i].file, rows[i].test); + int from_test = go_calls_between(s, project, rows[i].test, rows[i].callee, NULL); + int from_file = go_calls_between(s, project, rows[i].file, rows[i].callee, NULL); + if (defines != 1 || from_test != 1 || from_file != 0) { + printf(" [%s] %s -> %s: DEFINES %d, from the test %d, from the File %d\n", + parallel ? "parallel" : "sequential", rows[i].test, rows[i].callee, defines, + from_test, from_file); + bad++; + } + } + ASSERT_EQ(bad, 0); /* RED on cbm-ctest-caller-c2a10ffd: the File keeps a second edge */ + return 0; +} + +TEST(pipeline_cpp_gtest_preprocessed_view_one_source) { + int runs[2] = {-1, -1}; + int verdicts[2] = {-1, -1}; + for (int mode = 0; mode < 2; mode++) { + bool parallel = mode == 1; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_cpp_gtest_ppview_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + write_cpp_gtest_pp_view_fixture(tmp, parallel ? 52 : 0); + const char *old_workers = getenv("CBM_WORKERS"); + char *saved = old_workers ? strdup(old_workers) : NULL; + cbm_setenv("CBM_WORKERS", parallel ? "4" : "1", 1); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/gtest_ppview.db", tmp); + cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL); + int run = p ? cbm_pipeline_run(p) : -1; + cbm_store_t *s = run == 0 ? cbm_store_open_path(db_path) : NULL; + int verdict = + s ? assert_cpp_gtest_pp_view_edges(s, cbm_pipeline_project_name(p), parallel) : -1; + if (s) { + cbm_store_close(s); + } + if (p) { + cbm_pipeline_free(p); + } + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + th_rmtree(tmp); + runs[mode] = run; + verdicts[mode] = verdict; + } + ASSERT_EQ(runs[0], 0); + ASSERT_EQ(runs[1], 0); + ASSERT_EQ(verdicts[0], 0); /* sequential resolver */ + ASSERT_EQ(verdicts[1], 0); /* parallel resolver */ + PASS(); +} + +/* Which definitions of the second view are matched to a raw test (review of + * round 2, shapes (a) to (c)): only a top-level one, and none when two + * top-level definitions of that view cover one raw span. The program answers + * come from compiling this file with gtest's TEST expansion, each site + * printing where it runs: s01 and s02 in L::f, s03 in helper3, s04 and + * helper3 in Pair_Helper, s05 in RealSuite2_A, s06 in Other2_B, s07 in + * Plain_One. */ +static void write_cpp_gtest_view_guard_fixture(const char *tmp, int pad_files) { + write_temp_file(tmp, "lib/sites.h", + "int s01();\nint s02();\nint s03();\nint s04();\nint s05();\nint s06();\n" + "int s07();\n"); + write_temp_file(tmp, "lib/sites.cc", + "#include \"sites.h\"\n" + "int s01() { return 1; }\nint s02() { return 2; }\nint s03() { return 3; }\n" + "int s04() { return 4; }\nint s05() { return 5; }\nint s06() { return 6; }\n" + "int s07() { return 7; }\n"); + write_temp_file(tmp, "test/views_test.cc", + "#include \"../lib/sites.h\"\n" + "TEST(OneLine, Local) { struct L { int f() { return s01(); } }; L().f(); }\n" + "TEST(Span, Local) { struct L { int f() {\n" + " return s02();\n" + "} }; L().f(); }\n" + "static int helper3() { return s03(); } TEST(Pair, Helper) { s04(); helper3(); }\n" + "#define MY_SUITE2 RealSuite2\n" + "TEST(MY_SUITE2, A) { s05(); } TEST(Other2, B) { s06(); }\n" + "TEST(Plain, One) { s07(); }\n"); + for (int i = 0; i < pad_files; i++) { + char name[64]; + char body[128]; + snprintf(name, sizeof(name), "pad/filler%d.cc", i); + snprintf(body, sizeof(body), "int filler%d() { return %d; }\n", i, i); + write_temp_file(tmp, name, body); + } +} + +typedef struct { + const char *caller; /* QN suffix of the source node */ + const char *callee; /* QN suffix of the target */ + int want; /* CALLS edges */ +} ViewGuardEdge; + +#define VG_FILE ".test.views_test.cc.__file__" +#define VG_TEST(name) ".test.views_test.TEST_" name + +/* Index the fixture sequentially and in parallel; every edge is checked and + * reported before the verdict: the number of edges that differ (-1: a run + * failed). */ +static int view_guard_edges(const ViewGuardEdge *edges, size_t n) { + int bad = 0; + for (int mode = 0; mode < 2 && bad >= 0; mode++) { + bool parallel = mode == 1; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_cpp_gtest_vguard_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + return -1; + } + write_cpp_gtest_view_guard_fixture(tmp, parallel ? 52 : 0); + const char *old_workers = getenv("CBM_WORKERS"); + char *saved = old_workers ? strdup(old_workers) : NULL; + cbm_setenv("CBM_WORKERS", parallel ? "4" : "1", 1); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/vguard.db", tmp); + cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL); + int run = p ? cbm_pipeline_run(p) : -1; + cbm_store_t *s = run == 0 ? cbm_store_open_path(db_path) : NULL; + if (!s) { + bad = -1; + } + for (size_t i = 0; s && i < n; i++) { + int got = go_calls_between(s, cbm_pipeline_project_name(p), edges[i].caller, + edges[i].callee, NULL); + if (got != edges[i].want) { + printf(" [%s] %s -> %s: %d, want %d\n", parallel ? "parallel" : "sequential", + edges[i].caller, edges[i].callee, got, edges[i].want); + bad++; + } + } + if (s) { + cbm_store_close(s); + } + if (p) { + cbm_pipeline_free(p); + } + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + th_rmtree(tmp); + } + return bad; +} + +/* (a) A method of a local class whose lines are the test's lines (one line, + * or head line to closing line). The raw view draws its call from the File + * (main's rule for local-class methods); the second view must not name the + * method's body as the test, or the call has two sources. Partner: a plain + * one-line test's call is still at the test. */ +TEST(pipeline_cpp_gtest_view_guard_local_class_method) { + static const ViewGuardEdge edges[] = { + {VG_TEST("OneLine_Local"), ".lib.sites.s01", 0}, + {VG_FILE, ".lib.sites.s01", 1}, + {VG_TEST("Span_Local"), ".lib.sites.s02", 0}, + {VG_FILE, ".lib.sites.s02", 1}, + {VG_TEST("Plain_One"), ".lib.sites.s07", 1}, + {VG_FILE, ".lib.sites.s07", 0}, + }; + ASSERT_EQ(view_guard_edges(edges, sizeof(edges) / sizeof(edges[0])), 0); + PASS(); +} + +/* (b) A function defined on the line of a one-line test: two top-level + * definitions of the second view cover the test's span, so neither is the + * test. The helper's call stays the helper's (no TEST_Pair_Helper -> s03); + * the test's own calls stay the test's (partner). */ +TEST(pipeline_cpp_gtest_view_guard_helper_on_test_line) { + static const ViewGuardEdge edges[] = { + {VG_TEST("Pair_Helper"), ".lib.sites.s03", 0}, + {".test.views_test.helper3", ".lib.sites.s03", 1}, + {VG_TEST("Pair_Helper"), ".lib.sites.s04", 1}, + {VG_TEST("Pair_Helper"), ".test.views_test.helper3", 1}, + }; + ASSERT_EQ(view_guard_edges(edges, sizeof(edges) / sizeof(edges[0])), 0); + PASS(); +} + +/* (c) Two tests on one line, one head spelled through a project macro: the + * span is shared, so the rule gives no answer and the second view names each + * body from its own expanded head. TEST(MY_SUITE2, A) becomes + * TEST_RealSuite2_A there, a name no node carries, so its call is drawn from + * the test (raw view) and from the File (main's own edge): two sources, one + * target, the right one. A known limit; this pins what the graph draws. The + * other test's call is at its test only (partner). */ +TEST(pipeline_cpp_gtest_view_guard_shared_line_macro_head) { + static const ViewGuardEdge edges[] = { + {VG_TEST("MY_SUITE2_A"), ".lib.sites.s05", 1}, + {VG_FILE, ".lib.sites.s05", 1}, + {VG_TEST("Other2_B"), ".lib.sites.s06", 1}, + {VG_FILE, ".lib.sites.s06", 0}, + }; + ASSERT_EQ(view_guard_edges(edges, sizeof(edges) / sizeof(edges[0])), 0); + PASS(); +} + +/* Every node (qualified name, label) and every edge (type, source QN, target + * QN, properties by key) of a store, one row each, sorted. Node ids and the + * index bookkeeping differ between two stores; the graph content must not. */ +typedef struct { + char **rows; + int count; +} CppGtestRows; + +static void cpp_gtest_rows_free(CppGtestRows *r) { + for (int i = 0; i < r->count; i++) { + free(r->rows[i]); + } + free(r->rows); + r->rows = NULL; + r->count = 0; +} + +static int cpp_gtest_row_cmp(const void *a, const void *b) { + return strcmp(*(const char *const *)a, *(const char *const *)b); +} + +static bool cpp_gtest_rows_add(CppGtestRows *out, int *cap, sqlite3_stmt *stmt) { + const char *cols[4]; + size_t len = 4; + for (int c = 0; c < 4; c++) { + cols[c] = (const char *)sqlite3_column_text(stmt, c); + len += cols[c] ? strlen(cols[c]) : 0; + } + if (out->count == *cap) { + int grown_cap = *cap ? *cap * 2 : 256; + char **grown = realloc(out->rows, (size_t)grown_cap * sizeof(char *)); + if (!grown) { + return false; + } + out->rows = grown; + *cap = grown_cap; + } + char *row = malloc(len + 1); + if (!row) { + return false; + } + snprintf(row, len + 1, "%s|%s|%s|%s", cols[0] ? cols[0] : "", cols[1] ? cols[1] : "", + cols[2] ? cols[2] : "", cols[3] ? cols[3] : ""); + out->rows[out->count++] = row; + return true; +} + +static bool cpp_gtest_rows(const char *db_path, CppGtestRows *out) { + memset(out, 0, sizeof(*out)); + cbm_store_t *s = cbm_store_open_path(db_path); + if (!s) { + return false; + } + static const char *const queries[] = { + "SELECT 'N', qualified_name, label, '' FROM nodes", + /* Properties with their top-level keys sorted: the incremental route + * writes CALLS properties in another key order than a full index + * (on 08a7a586 as well), which is not a difference of content. */ + "SELECT 'E' || e.type, s.qualified_name, t.qualified_name, " + "CASE WHEN json_valid(e.properties) THEN (SELECT group_concat(key || '=' || value, ',') " + "FROM (SELECT key, value FROM json_each(e.properties) ORDER BY key)) " + "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"}; + int cap = 0; + bool ok = true; + for (size_t q = 0; q < 2 && ok; q++) { + sqlite3_stmt *stmt = NULL; + ok = sqlite3_prepare_v2(cbm_store_get_db(s), queries[q], -1, &stmt, NULL) == SQLITE_OK; + while (ok && sqlite3_step(stmt) == SQLITE_ROW) { + ok = cpp_gtest_rows_add(out, &cap, stmt); + } + sqlite3_finalize(stmt); + } + cbm_store_close(s); + if (!ok) { + cpp_gtest_rows_free(out); + return false; + } + qsort(out->rows, (size_t)out->count, sizeof(char *), cpp_gtest_row_cmp); + return true; +} + +/* 0 when both stores hold the same rows; else prints the first difference. */ +static int cpp_gtest_rows_diff(const char *label, const CppGtestRows *a, const CppGtestRows *b) { + int i = 0; + int j = 0; + while (i < a->count && j < b->count) { + int c = strcmp(a->rows[i], b->rows[j]); + if (c != 0) { + printf(" [%s] first difference: %s\n against: %s\n", label, + c < 0 ? a->rows[i] : b->rows[j], + c < 0 ? "(missing on the right)" : "(missing on the left)"); + return 1; + } + i++; + j++; + } + if (i < a->count || j < b->count) { + printf(" [%s] row counts %d vs %d\n", label, a->count, b->count); + return 1; + } + return 0; +} + +/* A single-file edit of a gtest file, taken by the incremental route, gives + * the graph a full index of the edited tree gives (every node and every edge + * by content), sequential and parallel; the edited body's remaining call + * starts at the test's own node and the removed one is gone. The caller naming lives in extraction + * and in the C/C++ engine dispatch, which every route shares; this pins that no route names a test + * body differently. */ +TEST(pipeline_cpp_gtest_caller_incremental_matches_full) { + int verdicts[2] = {-1, -1}; + int routes[2] = {-1, -1}; + for (int mode = 0; mode < 2; mode++) { + bool parallel = mode == 1; + char tmp[256]; + char dbs[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_cpp_gtest_incr_XXXXXX"); + snprintf(dbs, sizeof(dbs), "/tmp/cbm_cpp_gtest_incr_db_XXXXXX"); + if (!cbm_mkdtemp(tmp) || !cbm_mkdtemp(dbs)) { + FAIL("tmpdir"); + } + write_cpp_gtest_caller_fixture(tmp, parallel ? 52 : 0); + const char *old_workers = getenv("CBM_WORKERS"); + char *saved = old_workers ? strdup(old_workers) : NULL; + cbm_setenv("CBM_WORKERS", parallel ? "4" : "1", 1); + char incr_db[512]; + char full_db[512]; + snprintf(incr_db, sizeof(incr_db), "%s/incr.db", dbs); + snprintf(full_db, sizeof(full_db), "%s/full.db", dbs); + int verdict = 1; + cbm_pipeline_t *p = cbm_pipeline_new(tmp, incr_db, CBM_MODE_FULL); + int run = p ? cbm_pipeline_run(p) : -1; + cbm_pipeline_free(p); + /* A body-only edit (a new definition name would decline the closure + * planner to a full rebuild): the TEST body drops its local_helper + * call and keeps cross_helper. */ + if (run == 0) { + write_temp_file(tmp, "test/widget_test.cc", + "#include \"../lib/helper.h\"\n" + "static int local_helper(int v) { return v * 2; }\n" + "class WidgetFixture {\n" + " public:\n" + " int Prepare() { return 1; }\n" + "};\n" + "TEST(WidgetSuite, Adds) {\n" + " cross_helper(2);\n" + "}\n" + "TEST_F(WidgetFixture, Runs) {\n" + " local_helper(3);\n" + " cross_helper(4);\n" + "}\n"); + p = cbm_pipeline_new(tmp, incr_db, CBM_MODE_FULL); + run = p ? cbm_pipeline_run(p) : -1; + routes[mode] = (int)cbm_pipeline_incremental_test_last_route(); + cbm_store_t *s = run == 0 ? cbm_store_open_path(incr_db) : NULL; + const char *proj = p ? cbm_pipeline_project_name(p) : NULL; + int kept = s ? go_calls_between(s, proj, ".test.widget_test.TEST_WidgetSuite_Adds", + ".lib.helper.cross_helper", NULL) + : -1; + int dropped = s ? go_calls_between(s, proj, ".test.widget_test.TEST_WidgetSuite_Adds", + ".test.widget_test.local_helper", NULL) + : -1; + int later = kept == 1 && dropped == 0 ? 1 : 0; + if (s) { + cbm_store_close(s); + } + cbm_pipeline_free(p); + cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL); + int full_run = full ? cbm_pipeline_run(full) : -1; + cbm_pipeline_free(full); + CppGtestRows a; + CppGtestRows b; + bool read = run == 0 && full_run == 0 && cpp_gtest_rows(incr_db, &a); + bool read_b = read && cpp_gtest_rows(full_db, &b); + if (later != 1) { + printf(" [%s] after the edit TEST_WidgetSuite_Adds: cross_helper %d, " + "local_helper %d (want 1, 0)\n", + parallel ? "parallel" : "sequential", kept, dropped); + } + verdict = read_b && later == 1 && a.count > 0 + ? cpp_gtest_rows_diff(parallel ? "parallel" : "sequential", &a, &b) + : 1; + if (read) { + cpp_gtest_rows_free(&a); + } + if (read_b) { + cpp_gtest_rows_free(&b); + } + } + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + th_rmtree(tmp); + th_rmtree(dbs); + verdicts[mode] = verdict; + } + printf(" routes: sequential %d, parallel %d ", routes[0], routes[1]); + /* Both edits took an incremental route, not a full rebuild. */ + ASSERT_TRUE(routes[0] == CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL || + routes[0] == CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_TRUE(routes[1] == CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL || + routes[1] == CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(verdicts[0], 0); + ASSERT_EQ(verdicts[1], 0); + PASS(); +} + /* ── calls_append_args: an argument longer than its formatting buffer ────── */ #if !defined(_WIN32) @@ -36676,6 +37260,12 @@ SUITE(pipeline) { RUN_TEST(pipeline_cpp_static_factory_unique_ptr_receiver_issue1153); RUN_TEST(pipeline_cpp_static_factory_shared_ptr_receiver_issue1153); RUN_TEST(pipeline_cpp_unresolvable_receiver_stays_unbound_issue1153); + RUN_TEST(pipeline_cpp_gtest_body_calls_start_at_test_node); + RUN_TEST(pipeline_cpp_gtest_caller_incremental_matches_full); + RUN_TEST(pipeline_cpp_gtest_preprocessed_view_one_source); + RUN_TEST(pipeline_cpp_gtest_view_guard_local_class_method); + RUN_TEST(pipeline_cpp_gtest_view_guard_helper_on_test_line); + RUN_TEST(pipeline_cpp_gtest_view_guard_shared_line_macro_head); RUN_TEST(pipeline_calls_args_overlong_argument_stops_cleanly); } diff --git a/tests/test_test_conventions.c b/tests/test_test_conventions.c index b289053da..ce3d41c57 100644 --- a/tests/test_test_conventions.c +++ b/tests/test_test_conventions.c @@ -388,6 +388,60 @@ TEST(conventions_presets_and_languages_are_isolated) { PASS(); } +static int tc_calls_from(const CBMFileResult *result, const char *callee, const char *scope) { + int n = 0; + for (int i = 0; result && i < result->calls.count; i++) { + const CBMCall *call = &result->calls.items[i]; + n += tc_text(call->callee_name, callee) && tc_text(call->enclosing_func_qn, scope); + } + return n; +} + +static int tc_resolved_from(const CBMFileResult *result, const char *caller, const char *callee) { + int n = 0; + for (int i = 0; result && i < result->resolved_calls.count; i++) { + const CBMResolvedCall *rc = &result->resolved_calls.items[i]; + n += tc_text(rc->caller_qn, caller) && tc_text(rc->callee_qn, callee); + } + return n; +} + +/* The caller of a call in a gtest body follows the definition's name in both + * preset states, on the text path and in the C/C++ engine: on, the test's own + * TEST_Group_Alpha; off, the bare TEST the def walk then mints. A caller name + * without a definition sources the call at the file. */ +TEST(conventions_gtest_preset_names_body_callers) { + ASSERT_EQ(tc_init_status, 0); + const char *source = "void helper() {}\nTEST(Group, Alpha) { helper(); }\n"; + cbm_test_declarations_t *disabled = tc_config(NULL, "\"gtest\":false"); + cbm_test_declarations_t *enabled = tc_config(NULL, "\"gtest\":true"); + bool parsed = disabled && enabled; + CBMFileResult *off = disabled ? tc_extract(source, CBM_LANG_CPP, "src/body.cpp", disabled) : NULL; + CBMFileResult *on = enabled ? tc_extract(source, CBM_LANG_CPP, "src/body.cpp", enabled) : NULL; + cbm_test_declarations_free(disabled); + cbm_test_declarations_free(enabled); + bool states[2] = {false, false}; + const char *names[2] = {"TEST", "TEST_Group_Alpha"}; + CBMFileResult *results[2] = {off, on}; + for (int i = 0; i < 2; i++) { + const CBMDefinition *def = tc_def(results[i], names[i]); + const CBMDefinition *helper = tc_def(results[i], "helper"); + states[i] = tc_ok(results[i]) && def && helper && def->qualified_name && + tc_calls_from(results[i], "helper", def->qualified_name) == 1 && + tc_resolved_from(results[i], def->qualified_name, helper->qualified_name) == 1; + if (!states[i]) fprintf(stderr, "gtest preset %s: caller does not follow %s\n", + i ? "on" : "off", names[i]); + } + bool off_has_no_test_name = off && !tc_def(off, "TEST_Group_Alpha"); + cbm_free_result(off); + cbm_free_result(on); + ASSERT_TRUE(parsed); + ASSERT_TRUE(off_has_no_test_name); + ASSERT_TRUE(states[0]); + ASSERT_TRUE(states[1]); /* RED on 08a7a586: the call says TEST, the def TEST_Group_Alpha */ + PASS(); +} + TEST(conventions_snapshot_and_result_strings_are_independently_owned) { ASSERT_EQ(tc_init_status, 0); char json_a[] = "{\"test_impact\":{\"version\":1,\"tests\":{\"conventions\":[" TC_CASE0 "]}}}"; @@ -585,9 +639,11 @@ static bool tc_owner_cross(tc_owner_fixture_t *f, CBMArena *arena, bool cpp, CBMSourceOrigin origin, TSTree *tree) { if (registry) return cbm_run_c_lsp_cross_with_registry_with_test_owners(arena, source, length, - module, cpp, registry, NULL, NULL, 0, tree, out, origin, f->owners); + module, cpp, registry, NULL, NULL, 0, tree, out, origin, f->owners, + f->owners && f->owners->cpp_test_macro_names); return cbm_run_c_lsp_cross_with_test_owners(arena, source, length, module, cpp, - &f->foo, 1, NULL, NULL, 0, tree, out, origin, f->owners); + &f->foo, 1, NULL, NULL, 0, tree, out, origin, f->owners, + f->owners && f->owners->cpp_test_macro_names); } TEST(conventions_cached_body_tree_cannot_drop_calls) { @@ -791,6 +847,7 @@ SUITE(test_conventions) { RUN_TEST(conventions_invalid_invocations_have_exact_typed_locations); RUN_TEST(conventions_unsupported_consumed_descriptors_fail_preflight); RUN_TEST(conventions_presets_and_languages_are_isolated); + RUN_TEST(conventions_gtest_preset_names_body_callers); RUN_TEST(conventions_snapshot_and_result_strings_are_independently_owned); RUN_TEST(conventions_roles_and_errors_survive_compaction_and_spill); RUN_TEST(conventions_only_raw_invocations_receive_configured_roles);