Merge branch 'main' into fix-count-failed-read

This commit is contained in:
Martin Vogel
2026-09-07 01:16:14 +02:00
committed by GitHub
28 changed files with 1860 additions and 157 deletions
+3 -1
View File
@@ -98,9 +98,10 @@ endif
KOTLIN_DEDUP_TEST_DEFINE = -DCBM_KOTLIN_DEDUP_TEST_API=1
CALL_REFERENCE_LOOKUP_TEST_DEFINE = -DCBM_CALL_REFERENCE_LOOKUP_TEST_API=1
INCREMENTAL_TEST_DEFINE = -DCBM_INCREMENTAL_TEST_API=1
COVERAGE_MARKER_TEST_DEFINE = -DCBM_COVERAGE_MARKER_TEST_API=1
CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(SANITIZED_DEFINE) \
$(KOTLIN_DEDUP_TEST_DEFINE) $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) \
$(INCREMENTAL_TEST_DEFINE) -g -O1 $(SANITIZE)
$(INCREMENTAL_TEST_DEFINE) $(COVERAGE_MARKER_TEST_DEFINE) -g -O1 $(SANITIZE)
CXXFLAGS_TEST = $(CXXFLAGS_COMMON) $(SANITIZED_DEFINE) -g -O1 $(SANITIZE) $(CXX_STDLIB_FLAGS)
# TSan (can't combine with ASan)
@@ -118,6 +119,7 @@ TSAN_SANITIZE = -fsanitize=thread -fno-omit-frame-pointer
# macro of ours.
CFLAGS_TSAN = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(KOTLIN_DEDUP_TEST_DEFINE) \
$(CALL_REFERENCE_LOOKUP_TEST_DEFINE) $(INCREMENTAL_TEST_DEFINE) \
$(COVERAGE_MARKER_TEST_DEFINE) \
-DCBM_SANITIZED_BUILD=1 -g -O1 $(TSAN_SANITIZE)
CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -DCBM_SANITIZED_BUILD=1 -g -O1 \
$(TSAN_SANITIZE)
+413 -31
View File
@@ -778,16 +778,24 @@ static bool cbm_source_nesting_exceeds(const char *source, int source_len, int c
* nodes (does not descend into an error subtree — one range per failed region).
* Bounded by CBM_MAX_ERROR_REGIONS so pathological input can't blow up the
* output. The ranges mark where constructs were dropped; they are a detection
* aid, never a completeness proof. */
#define CBM_MAX_ERROR_REGIONS 64
* aid, never a completeness proof.
*
* `dropped` counts the ranges the cap threw away. It exists so a clipped list
* cannot read as a complete one: cbm_error_ranges_str turns a non-zero count
* into a trailing "+<N>" marker. Phase 2 split one whole-file range into many
* small ones, which pushed real files straight into a cap that used to be
* unreachable, so the clip is live behaviour and not a theoretical limit. */
#define CBM_MAX_ERROR_REGIONS 256
typedef struct {
uint32_t starts[CBM_MAX_ERROR_REGIONS];
uint32_t ends[CBM_MAX_ERROR_REGIONS];
int count;
int dropped;
} cbm_error_regions_t;
static void cbm_error_regions_push(cbm_error_regions_t *acc, TSNode n) {
if (acc->count >= CBM_MAX_ERROR_REGIONS) {
acc->dropped++;
return;
}
acc->starts[acc->count] = ts_node_start_point(n).row + 1;
@@ -851,13 +859,14 @@ static bool cbm_is_eof_terminator_miss(TSNode n, const char *source, int source_
return true;
}
/* Walks to the end even after the cap is full, so `dropped` is the real number
* of ranges lost rather than a lower bound. This costs little: the walk never
* descends into an ERROR subtree — it records the top-most node and moves on —
* so it only visits the spine of nodes that contain an error, plus one level. */
static void cbm_collect_error_regions(TSNode n, cbm_error_regions_t *acc, const char *source,
int source_len) {
if (acc->count >= CBM_MAX_ERROR_REGIONS) {
return;
}
uint32_t k = ts_node_child_count(n);
for (uint32_t i = 0; i < k && acc->count < CBM_MAX_ERROR_REGIONS; i++) {
for (uint32_t i = 0; i < k; i++) {
TSNode c = ts_node_child(n, i);
if (ts_node_is_missing(c) || strcmp(ts_node_type(c), "ERROR") == 0) {
if (cbm_is_eof_terminator_miss(c, source, source_len)) {
@@ -870,6 +879,130 @@ static void cbm_collect_error_regions(TSNode n, cbm_error_regions_t *acc, const
}
}
/* ── Phase 2 line map: what the preprocessed parse already explained ───────
*
* The raw parse is preprocessor-blind. When an #ifdef splits a brace it sees
* both branches at once, the braces do not balance, and the ERROR node
* swallows the whole construct — at file scope it swallows the whole FILE.
* The second parse, on preprocessed source, does not have that problem: the
* preprocessor already picked one branch, so that parse is clean.
*
* So we build one byte per ORIGINAL line and use it to cut the raw ranges
* down to the lines the second parse cannot vouch for. Lines in the branch
* the preprocessor threw away never appear in the second parse at all, so
* they stay flagged — which is right, because they really are missing from
* the graph.
*
* CBM_LINE_PP_PARSED — the preprocessed parse covered this original line and
* found no error on it. Nothing here was dropped.
* CBM_LINE_NO_CODE — the line is empty, is only a comment, or is a
* preprocessor directive. A reported range must never
* begin or end on one.
*
* Directives are in this set because the preprocessor
* CONSUMES them: no directive line ever survives into
* the expanded text, so the second parse can never
* vouch for one, and treating that silence as a miss
* would flag every #include block in the file. The
* known cost is a #define that the raw parse really did
* drop: it no longer shows up on its own. That trade is
* deliberate — it removes far more noise than signal. */
enum { CBM_LINE_PP_PARSED = 1u, CBM_LINE_NO_CODE = 2u };
/* True when the line's first non-blank character starts a preprocessor
* directive. */
static bool cbm_is_directive_line(const char *line, int len) {
int i = 0;
while (i < len && (line[i] == ' ' || line[i] == '\t')) {
i++;
}
return i < len && line[i] == '#';
}
/* True when the line ends with a backslash, so the directive carries on to
* the next line. */
static bool cbm_line_continues(const char *line, int len) {
int end = len;
while (end > 0 && (line[end - 1] == ' ' || line[end - 1] == '\t' || line[end - 1] == '\r')) {
end--;
}
return end > 0 && line[end - 1] == '\\';
}
/* Set CBM_LINE_NO_CODE on every line of `src` that holds no construct.
* One pass over the file. Carries block-comment state across lines so a line
* in the middle of a comment counts as no-code too. */
static void cbm_mark_no_code_lines(const char *src, int src_len, uint8_t *map,
uint32_t line_count) {
bool in_block = false;
bool in_directive = false;
uint32_t line = 1;
int i = 0;
while (i <= src_len && line <= line_count) {
int end = i;
while (end < src_len && src[end] != '\n') {
end++;
}
bool has_code = false;
bool line_starts_in_block = in_block;
for (int j = i; j < end; j++) {
if (in_block) {
if (src[j] == '*' && j + 1 < end && src[j + 1] == '/') {
in_block = false;
j++;
}
continue;
}
if (src[j] == '/' && j + 1 < end && src[j + 1] == '*') {
in_block = true;
j++;
continue;
}
if (src[j] == '/' && j + 1 < end && src[j + 1] == '/') {
break; /* rest of the line is a comment */
}
if (src[j] != ' ' && src[j] != '\t' && src[j] != '\r') {
has_code = true;
}
}
bool directive =
!line_starts_in_block && (in_directive || cbm_is_directive_line(src + i, end - i));
if (!has_code || directive) {
map[line] |= CBM_LINE_NO_CODE;
}
in_directive = directive && cbm_line_continues(src + i, end - i);
line++;
i = end + 1;
}
}
/* Paint CBM_LINE_PP_PARSED for every original line the preprocessed parse
* covered without an error on it.
*
* Step 1 marks the EXPANDED rows that sit under an ERROR/MISSING node.
* Step 2 walks the expanded lines and, for each one that is unmarked, belongs
* to the file itself (not an included header) and maps back to a real
* original line, records that original line as parsed. */
static void cbm_mark_pp_error_rows(TSNode n, uint8_t *rows, uint32_t row_count, const char *src,
int src_len) {
uint32_t k = ts_node_child_count(n);
for (uint32_t i = 0; i < k; i++) {
TSNode c = ts_node_child(n, i);
if (ts_node_is_missing(c) || strcmp(ts_node_type(c), "ERROR") == 0) {
if (cbm_is_eof_terminator_miss(c, src, src_len)) {
continue; /* absent final newline only — nothing was dropped */
}
uint32_t s = ts_node_start_point(c).row + 1;
uint32_t e = ts_node_end_point(c).row + 1;
for (uint32_t r = s; r <= e && r <= row_count; r++) {
rows[r] = 1;
}
} else if (ts_node_has_error(c)) {
cbm_mark_pp_error_rows(c, rows, row_count, src, src_len);
}
}
}
/* Recovery subtraction (#963): tree-sitter error recovery plus the
* ERROR-descending def walker often still extract constructs INSIDE a failed
* region (verified: a function in an #ifdef-split ERROR region and even a
@@ -1075,27 +1208,12 @@ static void cbm_subtract_recovered_regions(cbm_error_regions_t *regs, const CBMD
* missing from the graph; it's a benign call the grammar can't parse without the
* preprocessor. True if the [start_line, end_line] span contains a call `NAME(` to
* a file-defined function-like macro (Macro label + a parameter signature). */
static bool cbm_span_is_macro_invocation(const char *src, int src_len, uint32_t start_line,
uint32_t end_line, const CBMDefArray *defs) {
if (!src || src_len <= 0 || !defs || start_line == 0 || end_line < start_line) {
static bool cbm_byte_span_is_macro_invocation(const char *src, int src_len, int span_start,
int span_end, const CBMDefArray *defs) {
if (!src || src_len <= 0 || !defs || span_start < 0 || span_end > src_len ||
span_start >= span_end) {
return false;
}
int span_start = 0;
uint32_t line = 1;
while (span_start < src_len && line < start_line) {
if (src[span_start++] == '\n') {
line++;
}
}
if (line != start_line) {
return false;
}
int span_end = span_start;
while (span_end < src_len && line <= end_line) {
if (src[span_end++] == '\n') {
line++;
}
}
for (int di = 0; di < defs->count; di++) {
const CBMDefinition *d = &defs->items[di];
/* Function-like macros only: an object-like macro (#define PI 3.14) has no
@@ -1123,6 +1241,66 @@ static bool cbm_span_is_macro_invocation(const char *src, int src_len, uint32_t
return false;
}
/* Byte offset where every 1-based line starts, so finding a line's span costs
* one table read instead of a walk from the start of the file.
*
* The table holds line_count + 2 entries. Entry [L] is where line L starts, and
* the last entry is the end of the source, which gives the final line somewhere
* to stop. A line the file never reaches starts at the end of the source, so its
* span is empty and nothing can match inside it — the same answer the walk gives.
*
* Returns NULL when the allocation fails; a caller then falls back to the walk. */
static int *cbm_build_line_offsets(const char *src, int src_len, uint32_t line_count) {
int *offsets = (int *)malloc(((size_t)line_count + 2) * sizeof(int));
if (!offsets) {
return NULL;
}
for (uint32_t l = 0; l <= line_count + 1; l++) {
offsets[l] = src_len;
}
offsets[0] = 0;
offsets[1] = 0;
uint32_t line = 1;
for (int i = 0; i < src_len; i++) {
if (src[i] != '\n') {
continue;
}
line++;
if (line > line_count + 1) {
break;
}
offsets[line] = i + 1;
}
return offsets;
}
/* Same question by line number, for the few callers that ask about one region
* rather than every line of a file. This form walks the source to find the span,
* which is why the per-line caller below uses a table instead. */
static bool cbm_span_is_macro_invocation(const char *src, int src_len, uint32_t start_line,
uint32_t end_line, const CBMDefArray *defs) {
if (!src || src_len <= 0 || !defs || start_line == 0 || end_line < start_line) {
return false;
}
int span_start = 0;
uint32_t line = 1;
while (span_start < src_len && line < start_line) {
if (src[span_start++] == '\n') {
line++;
}
}
if (line != start_line) {
return false;
}
int span_end = span_start;
while (span_end < src_len && line <= end_line) {
if (src[span_end++] == '\n') {
line++;
}
}
return cbm_byte_span_is_macro_invocation(src, src_len, span_start, span_end, defs);
}
/* True if [rs, re] is fully enclosed by an extracted callable definition (a
* Function/Method body). A macro invocation INSIDE a real function body is an
* expression-level use where nothing is missing (#1071). A TOP-LEVEL invocation
@@ -1163,13 +1341,123 @@ static void cbm_subtract_macro_invocation_regions(cbm_error_regions_t *regs,
regs->count = kept;
}
/* Push [start, end] after trimming no-code lines off both ends. A run made
* only of directives, comments or blank lines disappears entirely — there was
* never a construct on it to lose. */
static void cbm_push_trimmed_run(cbm_error_regions_t *out, uint32_t start, uint32_t end,
const uint8_t *map, uint32_t line_count) {
while (start <= end && start <= line_count && (map[start] & CBM_LINE_NO_CODE)) {
start++;
}
while (end >= start && end <= line_count && (map[end] & CBM_LINE_NO_CODE)) {
end--;
}
if (start > end) {
return; /* nothing but blank, comment or directive lines — no construct lost */
}
if (out->count >= CBM_MAX_ERROR_REGIONS) {
out->dropped++;
return;
}
out->starts[out->count] = start;
out->ends[out->count] = end;
out->count++;
}
/* #949: a top-level macro invocation is the one place where a clean second
* parse proves nothing. The macro can expand to a whole definition, and the
* recovery walker deliberately refuses to adopt that definition because it is
* absent from the original span. So the expanded line parses fine while the
* construct really is missing from the graph, and the line must stay flagged.
* An invocation INSIDE a function body is the benign #1071 case and is left
* alone here — cbm_subtract_macro_invocation_regions handles it later. */
static bool cbm_line_is_toplevel_macro_call(const char *src, int src_len, uint32_t line,
const int *line_offsets, const CBMDefArray *defs) {
bool is_call = line_offsets
? cbm_byte_span_is_macro_invocation(src, src_len, line_offsets[line],
line_offsets[line + 1], defs)
: cbm_span_is_macro_invocation(src, src_len, line, line, defs);
return is_call && !cbm_region_inside_callable(line, line, defs);
}
/* Cut every raw region down to the lines the preprocessed parse could not
* vouch for. Each region becomes zero or more smaller ranges: one per run of
* consecutive lines that the second parse did not cover cleanly.
*
* This is what collapses a whole-file range on a file whose only real problem
* is an #ifdef splitting a brace. It deliberately does NOT clear the region
* outright — the branch the preprocessor discarded is genuinely absent from
* the graph and must stay flagged. */
static void cbm_refine_regions_with_pp_lines(cbm_error_regions_t *regs, const uint8_t *map,
uint32_t line_count, const char *src, int src_len,
const CBMDefArray *defs) {
cbm_error_regions_t out = {{0}, {0}, 0, regs->dropped};
/* One offset table for the whole file. The macro check below runs once per
* line, and without the table each of those calls walks the source from byte
* 0 to find its line — bytes times lines, on exactly the whole-file-error
* shape this refinement exists to narrow. */
int *line_offsets = cbm_build_line_offsets(src, src_len, line_count);
for (int i = 0; i < regs->count; i++) {
uint32_t run_start = 0;
uint32_t run_end = 0;
uint32_t end = regs->ends[i] < line_count ? regs->ends[i] : line_count;
for (uint32_t line = regs->starts[i]; line <= end; line++) {
if ((map[line] & CBM_LINE_PP_PARSED) &&
!cbm_line_is_toplevel_macro_call(src, src_len, line, line_offsets, defs)) {
if (run_start != 0) {
cbm_push_trimmed_run(&out, run_start, run_end, map, line_count);
run_start = 0;
}
} else {
if (run_start == 0) {
run_start = line;
}
run_end = line;
}
}
if (run_start != 0) {
cbm_push_trimmed_run(&out, run_start, run_end, map, line_count);
}
}
free(line_offsets);
*regs = out;
}
/* Serialize collected regions as "start-end,start-end,..." into the arena. */
/* Share of a file one range must cover before the range stops being advice and
* becomes noise. 80% is well clear of anything real: the widest single range in
* this repo covers 25.5% of its file, and the next widest 3.9%. */
#define CBM_UNUSABLE_PCT 80
/* Number of 1-based lines in `src`. A file that does not end with a newline
* still has a last line, so the count is separators plus one. */
static uint32_t cbm_count_lines(const char *src, int src_len) {
uint32_t n = 1;
for (int i = 0; i < src_len; i++) {
if (src[i] == '\n' && i + 1 < src_len) {
n++;
}
}
return n;
}
/* Serialize collected regions as "start-end,start-end,...", with a trailing
* ",+<N>" when the cap threw N ranges away.
*
* The marker must stay a SUFFIX and nothing else. Every reader stops at the
* first token that is not a range, so a marker in the middle of a string
* silently hides everything after it. objectscript_export_append_error_ranges
* strips markers before joining two parts for exactly that reason.
*
* N can be non-zero while the kept list is short, because the recovery and
* macro rules run after collection and remove ranges the cap never saw. That
* still reports honestly: the cap bound, so what was lost is unknown. */
static const char *cbm_error_ranges_str(CBMArena *a, const cbm_error_regions_t *regs) {
if (regs->count <= 0) {
if (regs->count <= 0 && regs->dropped <= 0) {
return NULL;
}
enum { RANGE_MAX = 24 }; /* "4294967295-4294967295," */
char *buf = (char *)cbm_arena_alloc(a, (size_t)regs->count * RANGE_MAX);
char *buf = (char *)cbm_arena_alloc(a, (size_t)(regs->count + 1) * RANGE_MAX);
if (!buf) {
return NULL;
}
@@ -1178,6 +1466,9 @@ static const char *cbm_error_ranges_str(CBMArena *a, const cbm_error_regions_t *
off += (size_t)snprintf(buf + off, RANGE_MAX, "%s%u-%u", i ? "," : "", regs->starts[i],
regs->ends[i]);
}
if (regs->dropped > 0) {
snprintf(buf + off, RANGE_MAX, "%s+%d", off ? "," : "", regs->dropped);
}
return buf;
}
@@ -1419,6 +1710,14 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
// metrics. Remember the boundary.
int orig_calls_count = result->calls.count;
/* Phase 2 line map, built by the second (preprocessed) pass below and read
* by the parse-coverage block near the end of this function. Stays NULL
* for every language that has no second pass, which leaves the coverage
* signal exactly as it was. Arena-allocated so it outlives the
* preprocessed source and its tree. */
uint8_t *pp_line_map = NULL;
uint32_t pp_line_map_lines = 0;
// Second pass: preprocess C/C++/CUDA and extract additional macro-hidden calls.
// Defs keep original-source line numbers; only CALLS are extracted from expanded source.
if (language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA) {
@@ -1505,7 +1804,7 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
* the raw source line, and whose QN the raw pass did not
* already extract. */
if (ts_node_has_error(root)) {
cbm_error_regions_t raw_regs = {{0}, {0}, 0};
cbm_error_regions_t raw_regs = {{0}, {0}, 0, 0};
cbm_collect_error_regions(root, &raw_regs, source, source_len);
if (raw_regs.count > 0) {
int defs_before = result->defs.count;
@@ -1545,6 +1844,59 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
}
}
/* Build the original-line map before the expanded tree
* goes away. Skipped when the expanded parse is itself a
* total loss (root is ERROR), because then it vouches for
* nothing and there is no refinement to make. */
if (strcmp(ts_node_type(pp_root), "ERROR") != 0) {
uint32_t orig_lines = 1;
for (int ci = 0; ci < source_len; ci++) {
if (source[ci] == '\n') {
orig_lines++;
}
}
uint8_t *map = (uint8_t *)cbm_arena_alloc(a, (size_t)orig_lines + 2);
int exp_lines = preprocessed->expanded_line_count;
uint8_t *bad_rows =
exp_lines > 0 ? (uint8_t *)calloc((size_t)exp_lines + 2, 1) : NULL;
if (map && bad_rows) {
memset(map, 0, (size_t)orig_lines + 2);
cbm_mark_no_code_lines(source, source_len, map, orig_lines);
cbm_mark_pp_error_rows(pp_root, bad_rows, (uint32_t)exp_lines, expanded,
expanded_len);
/* Walk the expanded text once. An expanded line
* only vouches for its original line when it
* actually HAS content: the preprocessor emits a
* blank line where it dropped a branch, and a
* blank line proves nothing about the code that
* used to be there. */
uint32_t eline = 1;
bool eline_has_text = false;
for (int ci = 0; ci <= expanded_len; ci++) {
if (ci < expanded_len && expanded[ci] != '\n') {
char ch = expanded[ci];
if (ch != ' ' && ch != '\t' && ch != '\r') {
eline_has_text = true;
}
continue;
}
if (eline_has_text && (int)eline <= exp_lines && !bad_rows[eline] &&
preprocessed->belongs_to_main_file[eline]) {
uint32_t orig =
preprocessed->original_line_by_expanded_line[eline];
if (orig >= 1 && orig <= orig_lines) {
map[orig] |= CBM_LINE_PP_PARSED;
}
}
eline++;
eline_has_text = false;
}
pp_line_map = map;
pp_line_map_lines = orig_lines;
}
free(bad_rows);
}
ts_tree_delete(pp_tree);
}
}
@@ -1660,20 +2012,50 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
* miss, and a fully recovered file is not flagged at all. Detection aid
* only: the absence of this flag is NOT a completeness guarantee. */
if (ts_node_has_error(root)) {
cbm_error_regions_t regs = {{0}, {0}, 0};
cbm_error_regions_t regs = {{0}, {0}, 0, 0};
if (strcmp(ts_node_type(root), "ERROR") == 0) {
cbm_error_regions_push(&regs, root); /* whole file unparseable */
} else {
cbm_collect_error_regions(root, &regs, source, source_len);
}
/* Recovery subtraction runs on the RAW ranges, before the Phase 2
* refinement below. Its evidence is a whole definition that starts
* inside the range, so it has to be asked while the range still
* matches the construct. Ask it after the refinement and an #ifdef
* splitting a brace inside a recovered function looks unrecovered:
* the refinement keeps only the discarded branch, the function starts
* above it, and the evidence falls outside the range. */
cbm_subtract_recovered_regions(&regs, &result->defs);
/* Phase 2: cut what is left down to the lines the preprocessed parse
* could not explain. */
if (pp_line_map) {
cbm_refine_regions_with_pp_lines(&regs, pp_line_map, pp_line_map_lines, source,
source_len, &result->defs);
}
/* #1071: don't flag a benign function-like-macro call (defined in-file)
* that tree-sitter can't parse without the preprocessor. */
* that tree-sitter can't parse without the preprocessor. Runs AFTER the
* refinement, because its evidence is per-line: a narrow range points at
* the call itself instead of the whole blob around it. */
cbm_subtract_macro_invocation_regions(&regs, &result->defs, source, source_len);
if (regs.count > 0) {
/* A file whose kept list is empty but whose cap still bound is NOT clean:
* the ranges the cap threw away were never judged by the two rules
* above, so nothing proves they were recovered. Flag it. */
if (regs.count > 0 || regs.dropped > 0) {
result->parse_incomplete = true;
result->error_region_count = regs.count;
result->error_ranges = cbm_error_ranges_str(a, &regs);
/* One range covering nearly the whole file is not advice, it is
* noise: "look at lines 1 to 13047" of a 13046-line file tells a
* reader nothing they did not already know. Mark those separately
* so the report can say "read the source" instead. See
* parse_unusable in cbm.h for which files land here and why. */
if (regs.count == 1 && regs.dropped == 0) {
uint32_t total = cbm_count_lines(source, source_len);
uint32_t span = regs.ends[0] - regs.starts[0] + 1;
if (total > 0 && span * 100 >= total * CBM_UNUSABLE_PCT) {
result->parse_unusable = true;
}
}
}
}
+15
View File
@@ -522,6 +522,21 @@ typedef struct CBMFileResult {
* completeness guarantee. Callers should treat a flagged file as "prefer
* grep here", never treat an unflagged file as provably complete. */
bool parse_incomplete;
/* True when the ranges cover so much of the file that they are no longer
* useful advice — one range over 80% of the line count. The file WAS
* indexed, but pointing a reader at almost every line tells them nothing,
* so the report says "read the source" instead of listing the range.
*
* Its main customers are non-C languages. The refinement that narrows a
* whole-file range using the preprocessed parse only runs for C, C++ and
* CUDA, so a Python, Java or Ruby file whose root node is ERROR still
* reports 1-N.
*
* Note the naming: this field and the phase string it produces are both
* `parse_unusable`. The older `parse_incomplete` field emits the phase
* `parse_partial` instead. That mismatch is historical, not deliberate —
* do not copy it. */
bool parse_unusable;
const char *error_ranges;
int error_region_count;
bool is_test_file;
+80 -66
View File
@@ -1383,12 +1383,13 @@ static void parse_spec_imports(CBMExtractCtx *ctx) {
ts_tree_cursor_delete(&cursor);
}
// --- Embedded-language imports ---
// Generic walker for host grammars (Svelte, Vue, HTML, Astro, ...) whose AST
// keeps embedded sub-language source as raw_text (or similar) without parsing
// it. The host's CBMLangSpec.embedded_imports declares which content nodes
// hold which sub-language; we re-parse each match with the embedded grammar
// and run the standard ES import walker over the inner AST.
// --- Embedded-language structure and imports ---
// Generic walker for host grammars (Svelte, Vue, HTML, Astro, CFML, ...) whose
// AST keeps embedded sub-language source as raw_text (or similar) without
// parsing it. The host's CBMLangSpec.embedded_imports declares which content
// nodes hold which sub-language; we re-parse each match with the embedded
// grammar and run the definition, import and call extractors over the inner
// AST, so a component's script contributes symbols like a standalone file.
//
// No grammar symbols are referenced here — the embedded TSLanguage is
// resolved through cbm_ts_language(spec->embedded_language), the same hook
@@ -1458,66 +1459,94 @@ static bool ascii_trimmed_equals(const char *value, const char *expected) {
return true;
}
/* Vue is the only host that opts into structural embedded extraction. Restrict
* its inline programs to the language forms whose parsers we can select
* exactly. A src attribute always denotes an external program and therefore
* suppresses any inline extraction, even for malformed mixed markup. */
static bool vue_embedded_language(CBMExtractCtx *ctx, TSNode script, CBMLanguage *language) {
enum { VUE_ATTR_STACK_CAP = 128 };
TSNode stack[VUE_ATTR_STACK_CAP];
/* The text of a <script> attribute's value, or "" when it carries none
* (`<script type>`), so every attribute reads through one path. */
static const char *script_attribute_value(CBMExtractCtx *ctx, TSNode attribute) {
TSNode value_node = attribute;
if (!find_first_descendant_of(attribute, "attribute_value", &value_node)) {
return "";
}
return cbm_node_text(ctx->arena, value_node, ctx->source);
}
/* Apply one <script> attribute to the parse decision. Returns false when the
* attribute rules the block out of inline extraction:
* src= always names an external program, so nothing inline is extracted,
* even for malformed mixed markup;
* lang= selects the JavaScript or TypeScript grammar; any other language
* has no parser here;
* type= plain HTML routinely carries non-program blocks (application/json,
* importmap, text/x-template, application/ld+json) that would parse
* into garbage definitions and calls. Only the JavaScript forms in
* current use pass — absent or empty, module, text/javascript,
* application/javascript — and the rest bail. */
static bool apply_script_attribute(CBMExtractCtx *ctx, TSNode attribute, CBMLanguage *language) {
if (ts_node_named_child_count(attribute) == 0) {
return false;
}
const char *name = cbm_node_text(ctx->arena, ts_node_named_child(attribute, 0), ctx->source);
if (ascii_trimmed_equals(name, "src")) {
return false;
}
if (ascii_trimmed_equals(name, "lang")) {
const char *value = script_attribute_value(ctx, attribute);
if (ascii_trimmed_equals(value, "js") || ascii_trimmed_equals(value, "javascript")) {
*language = CBM_LANG_JAVASCRIPT;
return true;
}
if (ascii_trimmed_equals(value, "ts") || ascii_trimmed_equals(value, "typescript")) {
*language = CBM_LANG_TYPESCRIPT;
return true;
}
return false;
}
if (ascii_trimmed_equals(name, "type")) {
const char *value = script_attribute_value(ctx, attribute);
return ascii_trimmed_equals(value, "") || ascii_trimmed_equals(value, "module") ||
ascii_trimmed_equals(value, "text/javascript") ||
ascii_trimmed_equals(value, "application/javascript");
}
return true;
}
/* Markup hosts (Vue, Svelte, HTML, Astro) hang the attributes that decide
* whether and how an inline program is parsed off the <script> start tag.
* *language enters holding the spec row's default and leaves holding the
* grammar to parse with; an attribute-free block (Astro's frontmatter fence)
* keeps the row's language rather than falling through to JavaScript. */
static bool script_embedded_language(CBMExtractCtx *ctx, TSNode script, CBMLanguage *language) {
enum { SCRIPT_ATTR_STACK_CAP = 128 };
TSNode stack[SCRIPT_ATTR_STACK_CAP];
int top = 0;
bool has_lang = false;
bool lang_supported = true;
CBMLanguage selected = CBM_LANG_JAVASCRIPT;
stack[top++] = script;
while (top > 0) {
TSNode node = stack[--top];
if (strcmp(ts_node_type(node), "attribute") == 0) {
uint32_t named_count = ts_node_named_child_count(node);
if (named_count == 0) {
if (!apply_script_attribute(ctx, node, language)) {
return false;
}
TSNode name_node = ts_node_named_child(node, 0);
char *name = cbm_node_text(ctx->arena, name_node, ctx->source);
if (ascii_trimmed_equals(name, "src")) {
return false;
}
if (ascii_trimmed_equals(name, "lang")) {
TSNode value_node = node;
if (!find_first_descendant_of(node, "attribute_value", &value_node)) {
return false;
}
char *value = cbm_node_text(ctx->arena, value_node, ctx->source);
has_lang = true;
if (ascii_trimmed_equals(value, "js") ||
ascii_trimmed_equals(value, "javascript")) {
selected = CBM_LANG_JAVASCRIPT;
} else if (ascii_trimmed_equals(value, "ts") ||
ascii_trimmed_equals(value, "typescript")) {
selected = CBM_LANG_TYPESCRIPT;
} else {
lang_supported = false;
}
}
continue;
}
uint32_t count = ts_node_named_child_count(node);
if ((int)count > VUE_ATTR_STACK_CAP - top) {
if ((int)count > SCRIPT_ATTR_STACK_CAP - top) {
return false;
}
for (int i = (int)count - 1; i >= 0; i--) {
stack[top++] = ts_node_named_child(node, (uint32_t)i);
}
}
if (has_lang && !lang_supported) {
return false;
}
*language = selected;
return true;
}
/* CFML's <cfscript> carries no attributes and its embedded language is fixed
* by the spec row; only the markup hosts consult the <script> tag. */
static bool markup_script_host(CBMLanguage language) {
return language == CBM_LANG_VUE || language == CBM_LANG_SVELTE || language == CBM_LANG_HTML ||
language == CBM_LANG_ASTRO;
}
static void parse_one_embedded_block(CBMExtractCtx *ctx, const CBMEmbeddedBlock *block,
CBMLanguage embedded_language, bool extract_structure) {
CBMLanguage embedded_language) {
const TSLanguage *language = cbm_ts_language(embedded_language);
if (!language || ctx->source_len < 0) {
return;
@@ -1564,13 +1593,9 @@ static void parse_one_embedded_block(CBMExtractCtx *ctx, const CBMEmbeddedBlock
.macro_table = ctx->macro_table,
.return_type_table = ctx->return_type_table,
};
if (extract_structure) {
cbm_extract_definitions_without_module(&sub_ctx);
}
cbm_extract_definitions_without_module(&sub_ctx);
walk_es_imports(&sub_ctx, sub_ctx.root);
if (extract_structure) {
cbm_extract_unified(&sub_ctx);
}
cbm_extract_unified(&sub_ctx);
ts_tree_delete(tree);
ts_parser_delete(parser);
@@ -1588,22 +1613,11 @@ static void parse_embedded_imports(CBMExtractCtx *ctx) {
embedded_collect_content_nodes(ctx->root, e, hits, &hit_count, MAX_EMBEDDED_BLOCKS);
for (int i = 0; i < hit_count; i++) {
CBMLanguage embedded_language = e->embedded_language;
/* Structure (defs + calls), not just imports, for hosts whose
* embedded language carries real code. Vue since #1852; CFML's
* <cfscript> since the #1412 distillation. */
bool extract_structure =
ctx->language == CBM_LANG_VUE || ctx->language == CBM_LANG_CFML;
/* The attribute resolver is Vue's: it inspects <script lang=/src=>
* and OVERRIDES the spec's embedded language (JS default, TS on
* lang="ts", bail on src=). CFML's cf_script_tag carries no such
* attributes and its embedded language is fixed by the spec row
* (CFSCRIPT) — running the resolver would silently rewrite it to
* JavaScript. Resolve only for Vue. */
if (ctx->language == CBM_LANG_VUE &&
!vue_embedded_language(ctx, hits[i].script, &embedded_language)) {
if (markup_script_host(ctx->language) &&
!script_embedded_language(ctx, hits[i].script, &embedded_language)) {
continue;
}
parse_one_embedded_block(ctx, &hits[i], embedded_language, extract_structure);
parse_one_embedded_block(ctx, &hits[i], embedded_language);
}
}
}
+9 -6
View File
@@ -890,8 +890,9 @@ static const char *graphql_field_types[] = {"field_definition", "input_value_def
// ==================== Embedded sub-languages ====================
// Host grammars (Svelte/Vue/HTML/Astro) treat <script> bodies as raw_text and
// do not recurse into them. Declaring the host's script-content node here lets
// the generic embedded-imports walker re-parse that slice with the JS grammar
// so the existing ES import extractor sees real import_statement nodes.
// the generic embedded walker re-parse that slice with the declared grammar so
// its definitions, imports and calls extract in host-file coordinates. The
// declared language is the default; a <script lang=> attribute overrides it.
// Terminator: an entry whose script_node_type is NULL.
static const CBMEmbeddedLangSpec cfml_embedded_imports[] = {
/* Tag-dialect CFML keeps <cfscript> bodies as opaque cf_script_content;
@@ -915,10 +916,12 @@ static const CBMEmbeddedLangSpec html_embedded_imports[] = {
};
static const CBMEmbeddedLangSpec astro_embedded_imports[] = {
/* Astro component scripts live in the `---` frontmatter fence, which the
* grammar keeps as an unparsed frontmatter_js_block. Re-parse that slice
* with the JS grammar so `import X from './X.astro'` becomes a real edge. */
{"frontmatter", "frontmatter_js_block", CBM_LANG_JAVASCRIPT},
{"script_element", "raw_text", CBM_LANG_JAVASCRIPT},
* grammar keeps as an unparsed frontmatter_js_block. Astro type-checks the
* fence and its <script> bodies as TypeScript without any lang= attribute
* saying so (the fence cannot carry one), so TypeScript is the deliberate
* default for both; it parses untyped JavaScript unchanged. */
{"frontmatter", "frontmatter_js_block", CBM_LANG_TYPESCRIPT},
{"script_element", "raw_text", CBM_LANG_TYPESCRIPT},
{NULL, NULL, 0},
};
+50
View File
@@ -3601,8 +3601,49 @@ int cbm_yaml_upsert_mapping_entry(const char *file_path, const char *section_key
return result == 0 && release_result == 0 ? 0 : YAML_ERROR;
}
/* Removal is idempotent: a config that does not exist has nothing to remove.
* The JSON removers already answer OK here (cbm_json_like_read_document's
* "missing" result); the YAML removers instead took the lock first, and the
* lock directory is created beside the target — so with the parent directory
* absent (`~/.hermes/` never created because Hermes was detected by its
* binary on PATH, not by its home) every uninstall reported
* "does not exist or cannot be inspected" and refused to remove the
* executable. Only a true ENOENT short-circuits: a dangling symlink still
* reaches the reader and its byte-identical rejection. */
static bool yaml_remove_target_absent(const char *path) {
if (!path) {
return false;
}
#ifdef _WIN32
/* FILE_FLAG_OPEN_REPARSE_POINT, as in toml_read_file: opens the link
* itself rather than following it, so a dangling symlink does NOT count as
* absent and still reaches the reader — matching the POSIX branch, where
* lstat does not follow either. */
wchar_t *wide = cbm_utf8_to_wide(path);
if (!wide) {
return false;
}
HANDLE handle = CreateFileW(
wide, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
DWORD error = handle == INVALID_HANDLE_VALUE ? GetLastError() : 0;
free(wide);
if (handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
return false;
}
return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND;
#else
struct stat path_state;
return lstat(path, &path_state) != 0 && errno == ENOENT;
#endif
}
int cbm_yaml_remove_mapping_entry(const char *file_path, const char *section_key,
const char *entry_key) {
if (yaml_remove_target_absent(file_path)) {
return 0;
}
yaml_config_lock_t lock;
if (yaml_lock_acquire(file_path, &lock) != 0) {
return YAML_ERROR;
@@ -3626,6 +3667,9 @@ int cbm_yaml_upsert_owned_mapping_entry(const char *file_path, const char *secti
int cbm_yaml_remove_owned_mapping_entry(const char *file_path, const char *section_key,
const char *entry_key, const char *canonical_entry_block) {
if (yaml_remove_target_absent(file_path)) {
return CBM_YAML_IDENTITY_EDIT_OK;
}
yaml_config_lock_t lock;
if (yaml_lock_acquire(file_path, &lock) != 0) {
return CBM_YAML_IDENTITY_EDIT_ERROR;
@@ -3653,6 +3697,9 @@ int cbm_yaml_upsert_mapping_sequence_item(const char *file_path, const char *con
int cbm_yaml_remove_mapping_sequence_item(const char *file_path, const char *const *sequence_path,
size_t sequence_path_len, const char *identity_key,
const char *identity_scalar, const char *canonical_item) {
if (yaml_remove_target_absent(file_path)) {
return CBM_YAML_IDENTITY_EDIT_OK;
}
yaml_config_lock_t lock;
if (yaml_lock_acquire(file_path, &lock) != 0) {
return CBM_YAML_IDENTITY_EDIT_ERROR;
@@ -3675,6 +3722,9 @@ int cbm_yaml_upsert_string_list_item(const char *file_path, const char *key, con
}
int cbm_yaml_remove_string_list_item(const char *file_path, const char *key, const char *item) {
if (yaml_remove_target_absent(file_path)) {
return 0;
}
yaml_config_lock_t lock;
if (yaml_lock_acquire(file_path, &lock) != 0) {
return YAML_ERROR;
+33
View File
@@ -1588,6 +1588,33 @@ static bool application_index_args_normalize_defaults(yyjson_mut_val *root) {
return true;
}
/* One directory is one root. The auto-index job spells repo_path the way the
* session policy holds it - the platform's native form, backslashes on
* Windows - while an explicit index_repository request arrives in the
* handler's forward-slash spelling. Compared byte-exact the two never matched
* on Windows, and the request was refused as an options conflict instead of
* joining the job already running for its root. The policy keeps its
* spelling: the sensitive-root and allowed-root containment checks match it
* byte-exact against HOME and the granted roots, and respelling it there
* admitted $HOME. So the fold happens here, on this comparison's private copy,
* and nothing the daemon stores changes. */
static bool application_index_args_fold_repo_path(yyjson_mut_doc *document) {
yyjson_mut_val *root = yyjson_mut_doc_get_root(document);
yyjson_mut_val *repo_path = yyjson_mut_obj_get(root, "repo_path");
if (!repo_path || !yyjson_mut_is_str(repo_path)) {
return true;
}
char *folded = strdup(yyjson_mut_get_str(repo_path));
if (!folded) {
return false;
}
cbm_normalize_path_sep(folded);
yyjson_mut_val *key = yyjson_mut_str(document, "repo_path");
yyjson_mut_val *value = yyjson_mut_strcpy(document, folded);
free(folded);
return key && value && yyjson_mut_obj_replace(root, key, value);
}
static bool application_index_args_equal(const char *left, const char *right) {
if (!left || !right) {
return false;
@@ -1600,6 +1627,8 @@ static bool application_index_args_equal(const char *left, const char *right) {
yyjson_mut_val *right_root = right_copy ? yyjson_mut_doc_get_root(right_copy) : NULL;
bool equal = application_index_args_normalize_defaults(left_root) &&
application_index_args_normalize_defaults(right_root) &&
application_index_args_fold_repo_path(left_copy) &&
application_index_args_fold_repo_path(right_copy) &&
yyjson_mut_equals(left_root, right_root);
yyjson_mut_doc_free(left_copy);
yyjson_mut_doc_free(right_copy);
@@ -1608,6 +1637,10 @@ static bool application_index_args_equal(const char *left, const char *right) {
return equal;
}
bool cbm_daemon_application_index_args_equal_for_test(const char *left, const char *right) {
return application_index_args_equal(left, right);
}
/* Caller holds application->mutex. Keeping watcher ownership validation and
* this admission in the same critical section closes the unwatch race. */
static cbm_daemon_application_job_t *application_job_subscribe_locked(
+6
View File
@@ -45,4 +45,10 @@ int cbm_daemon_application_busy_queue_waits_for_test(void);
char *cbm_daemon_application_framable_response_for_test(char *response,
const cbm_jsonrpc_request_t *request);
/* The job registry's index-argument equality: the running job's args against
* a request's. Exposed because the two repo_path spellings it folds - the
* session policy's native root and a handler's forward-slash one - only differ
* on Windows, while the fold itself runs on every platform. */
bool cbm_daemon_application_index_args_equal_for_test(const char *left, const char *right);
#endif /* CBM_DAEMON_APPLICATION_INTERNAL_H */
+5 -1
View File
@@ -700,7 +700,7 @@ static CBMLanguage detect_file_language(const char *entry_name, const char *abs_
if (dot && strcmp(dot, ".m") == 0) {
lang = cbm_disambiguate_m(abs_path);
}
/* Special: .cls is shared by ObjectScript UDL and Apex */
/* Special: .cls is shared by ObjectScript UDL, Apex and VB6 class modules */
if (dot && strcmp(dot, ".cls") == 0) {
lang = cbm_disambiguate_cls(abs_path);
}
@@ -712,6 +712,10 @@ static CBMLanguage detect_file_language(const char *entry_name, const char *abs_
if (dot && strcmp(dot, ".cfc") == 0) {
lang = cbm_disambiguate_cfc(abs_path);
}
/* Special: .frm is shared by FORM and VB6 forms (#721) */
if (dot && strcmp(dot, ".frm") == 0) {
lang = cbm_disambiguate_frm(abs_path);
}
/* Special: ObjectScript Studio Export XML (<Export generator="...">) is
* detected by content; otherwise .xml stays XML. */
if (lang == CBM_LANG_XML) {
+6
View File
@@ -41,9 +41,15 @@ CBMLanguage cbm_disambiguate_m(const char *path);
/* Disambiguate .cls files by reading first 4KB of content.
* Returns CBM_LANG_OBJECTSCRIPT_UDL if a line starts with "Class <Uppercase>",
* CBM_LANG_COUNT (unsupported) for a Visual Basic 6 class module (#721),
* otherwise CBM_LANG_APEX. On read failure, defaults to CBM_LANG_APEX. */
CBMLanguage cbm_disambiguate_cls(const char *path);
/* Disambiguate .frm files by reading first 4KB of content (#721).
* Returns CBM_LANG_COUNT (unsupported) for a Visual Basic 6 form, otherwise
* CBM_LANG_FORM. On read failure, defaults to CBM_LANG_FORM. */
CBMLanguage cbm_disambiguate_frm(const char *path);
/* Disambiguate .inc files by reading first 4KB of content.
* Returns CBM_LANG_OBJECTSCRIPT_ROUTINE if it looks like an ObjectScript
* include (a "ROUTINE <Uppercase>" header), otherwise CBM_LANG_BITBAKE.
+47 -3
View File
@@ -1249,9 +1249,49 @@ CBMLanguage cbm_disambiguate_m(const char *path) {
return CBM_LANG_MATLAB;
}
/* Disambiguate .cls files: shared by InterSystems ObjectScript UDL and
* Salesforce Apex. ObjectScript class files begin with a line of the form
* "Class <UppercasePackage>...". Defaults to Apex on any doubt. */
/* Visual Basic 6 / VBA source exports are recognisable from their header (#721):
* every module carries `Attribute VB_Name = "..."`, class modules open with
* `VERSION 1.0 CLASS`, forms/controls with `VERSION 5.00` + `Begin VB.Form` /
* `Begin VB.UserControl`. None of these occur in Apex or ObjectScript classes
* or in FORM programs, whose .cls / .frm extensions VB6 happens to share. */
static bool has_vb6_markers(const char *buf) {
return str_contains(buf, "Attribute VB_Name") || str_contains(buf, "VERSION 1.0 CLASS") ||
str_contains(buf, "Begin VB.") || str_contains(buf, "\nOption Explicit");
}
/* Disambiguate .frm files: shared by the FORM symbolic-manipulation language
* and Visual Basic 6 forms (#721). There is no Visual Basic language yet, so a
* VB6 form is reported as unsupported (CBM_LANG_COUNT) rather than handed to
* the FORM grammar, which yields no defs and stray junk nodes. Defaults to
* FORM on any doubt (preserves existing behaviour). */
CBMLanguage cbm_disambiguate_frm(const char *path) {
if (!path) {
return CBM_LANG_FORM;
}
FILE *f = cbm_fopen(path, "r");
if (!f) {
return CBM_LANG_FORM;
}
char buf[CBM_SZ_4K + SKIP_ONE];
size_t n = fread(buf, SKIP_ONE, CBM_SZ_4K, f);
buf[n] = '\0';
(void)fclose(f);
/* VB6 form files open with "VERSION x.yy" on line 1. */
if (strncmp(buf, "VERSION ", SLEN("VERSION ")) == 0 &&
isdigit((unsigned char)buf[SLEN("VERSION ")])) {
return CBM_LANG_COUNT;
}
return has_vb6_markers(buf) ? CBM_LANG_COUNT : CBM_LANG_FORM;
}
/* Disambiguate .cls files: shared by InterSystems ObjectScript UDL, Salesforce
* Apex and Visual Basic 6 class modules (#721). ObjectScript class files begin
* with a line of the form "Class <UppercasePackage>..."; VB6 class modules
* carry the VB6 header markers and are reported as unsupported (CBM_LANG_COUNT)
* until a Visual Basic grammar exists. Defaults to Apex on any doubt. */
CBMLanguage cbm_disambiguate_cls(const char *path) {
if (!path) {
return CBM_LANG_APEX;
@@ -1267,6 +1307,10 @@ CBMLanguage cbm_disambiguate_cls(const char *path) {
buf[n] = '\0';
(void)fclose(f);
if (has_vb6_markers(buf)) {
return CBM_LANG_COUNT;
}
const char *line = buf;
while (*line) {
if (strncmp(line, "Class ", SLEN("Class ")) == 0 &&
+149 -18
View File
@@ -6052,10 +6052,12 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s
bool have_meta = cbm_store_coverage_meta_get(store, project, &meta) == CBM_STORE_OK;
yyjson_mut_val *pp_files = yyjson_mut_arr(doc);
yyjson_mut_val *pu_files = yyjson_mut_arr(doc);
yyjson_mut_val *sk_files = yyjson_mut_arr(doc);
yyjson_mut_val *ni_dirs = yyjson_mut_arr(doc);
yyjson_mut_val *ni_files = yyjson_mut_arr(doc);
int pp_n = 0;
int pu_n = 0;
int sk_n = 0;
int ni_dir_n = 0;
int ni_file_n = 0;
@@ -6070,6 +6072,21 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s
yyjson_mut_arr_add_val(pp_files, fe);
}
pp_n++;
} else if (strcmp(kind, "parse_unusable") == 0) {
/* Needs its own branch. The catch-all below builds skipped[], and
* a reader who finds a file there believes it was never indexed. */
if (pu_n < COVERAGE_FILE_CAP) {
yyjson_mut_val *fe = yyjson_mut_obj(doc);
yyjson_mut_obj_add_strcpy(doc, fe, "path", rows[i].rel_path);
yyjson_mut_obj_add_bool(doc, fe, "whole_file", true);
/* The end of the range, not the length of the file. A grammar
* can end an error node past the last line, so this number can
* be larger than the file. See range_end_is_not_file_length. */
const char *dash = rows[i].detail ? strchr(rows[i].detail, '-') : NULL;
yyjson_mut_obj_add_int(doc, fe, "range_end", dash ? atoi(dash + 1) : 0);
yyjson_mut_arr_add_val(pu_files, fe);
}
pu_n++;
} else if (strcmp(kind, "not_indexed_dir") == 0) {
if (ni_dir_n < sample_limit) {
yyjson_mut_arr_add_strcpy(doc, ni_dirs, rows[i].rel_path);
@@ -6119,6 +6136,14 @@ static void add_coverage_report(yyjson_mut_doc *doc, yyjson_mut_val *root, cbm_s
}
yyjson_mut_obj_add_val(doc, root, "parse_partial", pp);
/* Indexed, but the parse failed across nearly the whole file, so naming
* line ranges helps nobody — read the source instead. */
yyjson_mut_val *pu = yyjson_mut_obj(doc);
yyjson_mut_obj_add_val(doc, pu, "files", pu_files);
yyjson_mut_obj_add_int(doc, pu, "count", pu_n);
yyjson_mut_obj_add_bool(doc, pu, "truncated", pu_n > COVERAGE_FILE_CAP);
yyjson_mut_obj_add_val(doc, root, "parse_unusable", pu);
yyjson_mut_val *sk = yyjson_mut_obj(doc);
yyjson_mut_obj_add_val(doc, sk, "files", sk_files);
yyjson_mut_obj_add_int(doc, sk, "count", sk_n);
@@ -6173,7 +6198,8 @@ enum {
COVERAGE_SCOPE_MAX = 32,
COVERAGE_SCOPE_DEFAULT_LIMIT = 200,
COVERAGE_SCOPE_MAX_LIMIT = 1000,
COVERAGE_RANGE_MAX = 128,
COVERAGE_RANGE_MAX = 256, /* matches CBM_MAX_ERROR_REGIONS — a lower value here
would just move the silent clip downstream */
};
bool cbm_path_within_root(const char *root_path, const char *abs_path); /* defined below */
@@ -6285,6 +6311,14 @@ static const char *coverage_path_freshness(cbm_store_t *store, const char *proje
return matches ? "metadata_match" : "metadata_changed";
}
/* Read an "start-end,start-end,...[,+<N>]" string into a JSON ranges array.
*
* The optional trailing "+<N>" says the producer's own cap threw N ranges away.
* Without reading it, a clipped list arrives here looking complete: the loop
* below stops at the '+' with no error and no leftover, so the row would claim
* a short, tidy set of ranges that is in fact missing entries. Set
* "ranges_truncated": true whenever ranges were lost — either by that marker,
* or by COVERAGE_RANGE_MAX stopping this loop. */
static bool coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const char *detail) {
if (!detail || !detail[0]) {
return false;
@@ -6292,10 +6326,15 @@ static bool coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const
yyjson_mut_val *ranges = yyjson_mut_arr(doc);
const char *p = detail;
int emitted = 0;
bool truncated = false;
while (*p && emitted < COVERAGE_RANGE_MAX) {
while (*p == ' ' || *p == ',') {
p++;
}
if (*p == '+') {
truncated = true; /* the producer's cap dropped ranges we never saw */
break;
}
if (!isdigit((unsigned char)*p)) {
break;
}
@@ -6327,11 +6366,17 @@ static bool coverage_add_ranges(yyjson_mut_doc *doc, yyjson_mut_val *row, const
break;
}
}
if (emitted >= COVERAGE_RANGE_MAX && *p) {
truncated = true; /* our own limit stopped the loop with input left over */
}
if (emitted > 0) {
yyjson_mut_obj_add_val(doc, row, "ranges", ranges);
if (emitted == COVERAGE_RANGE_MAX && *p) {
yyjson_mut_obj_add_bool(doc, row, "ranges_truncated", true);
}
}
/* Losing ranges to the producer's cap and losing them to this reader's cap
* are the same fact for a caller: the list is short and what is missing is
* unknown. One flag says so, whether or not any range survived. */
if (truncated) {
yyjson_mut_obj_add_bool(doc, row, "ranges_truncated", true);
}
return emitted > 0;
}
@@ -6348,7 +6393,8 @@ static void coverage_add_row_json(yyjson_mut_doc *doc, yyjson_mut_val *array,
row->rel_path && strcmp(row->rel_path, requested_path) == 0 ? "exact" : "ancestor");
}
bool ranges_added = false;
if (row->kind && strcmp(row->kind, "parse_partial") == 0) {
if (row->kind &&
(strcmp(row->kind, "parse_partial") == 0 || strcmp(row->kind, "parse_unusable") == 0)) {
ranges_added = coverage_add_ranges(doc, item, row->detail);
}
/* A parse_partial detail such as "3-4,9" is byte-for-byte redundant once
@@ -6381,6 +6427,12 @@ static const char *coverage_status(const cbm_coverage_row_t *rows, int count,
continue;
}
const char *kind = rows[i].kind ? rows[i].kind : "";
/* "parse_unusable" must be named here. Without its own case it
* falls through to the catch-all below and reports "skipped",
* which is wrong in the way that matters: the file WAS indexed. */
if (pass == 0 && strcmp(kind, "parse_unusable") == 0) {
return "unusable";
}
if (pass == 0 && strcmp(kind, "parse_partial") == 0) {
return "partial";
}
@@ -6408,6 +6460,11 @@ static const char *coverage_recommended_action(const char *status, const char *f
if (strcmp(status, "partial") == 0) {
return "read_ranges_and_verify_scope";
}
if (strcmp(status, "unusable") == 0) {
/* The ranges cover nearly the whole file, so sending a reader to them
* is the same as sending them to the file. Say the useful thing. */
return "read_source_directly";
}
if (strcmp(status, "skipped") == 0) {
return "read_source_directly";
}
@@ -10008,6 +10065,19 @@ static bool is_parse_partial(const cbm_file_error_t *e) {
return e->phase && strcmp(e->phase, "parse_partial") == 0;
}
/* The same, for the whole-file variant: one range covers 80% or more of the
* file, so listing the lines is useless advice. Also indexed, also not a skip. */
static bool is_parse_unusable(const cbm_file_error_t *e) {
return e->phase && strcmp(e->phase, "parse_unusable") == 0;
}
/* Either coverage phase. Both mean the file WAS indexed, so both must stay out
* of skipped[] — a reader who sees a file there believes it is absent from the
* graph entirely. */
static bool is_parse_coverage(const cbm_file_error_t *e) {
return is_parse_partial(e) || is_parse_unusable(e);
}
/* Attach a summary of per-file skips (Stage 2 / Track B). Always emits a
* top-level "skipped_count" (0 on clean runs) so consumers can rely on it.
* When there are skips, also emits:
@@ -10015,13 +10085,13 @@ static bool is_parse_partial(const cbm_file_error_t *e) {
* and, if a per-run logfile was written, "logfile": "<path>".
* The run status stays "indexed" — a skipped file is the expected handled
* outcome, not a failure. errs[] is borrowed (copied into doc) and may contain
* parse_partial entries, which are filtered out here (reported separately by
* add_parse_partial_summary). */
* parse_partial and parse_unusable entries, which are filtered out here (both
* reported separately by add_parse_partial_summary). */
static void add_skipped_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,
const cbm_file_error_t *errs, int count, const char *logfile) {
int skips = 0;
for (int i = 0; i < count; i++) {
if (!is_parse_partial(&errs[i])) {
if (!is_parse_coverage(&errs[i])) {
skips++;
}
}
@@ -10036,7 +10106,7 @@ static void add_skipped_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,
yyjson_mut_val *files = yyjson_mut_arr(doc);
int shown = 0;
for (int i = 0; i < count && shown < INDEX_SKIPPED_FILE_CAP; i++) {
if (is_parse_partial(&errs[i])) {
if (is_parse_coverage(&errs[i])) {
continue;
}
yyjson_mut_val *fe = yyjson_mut_obj(doc);
@@ -10095,6 +10165,55 @@ static void add_parse_partial_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,
yyjson_mut_obj_add_val(doc, root, "parse_partial", pp);
}
/* Attach the whole-file half of the coverage summary. Always emits a top-level
* "parse_unusable_count" (0 on clean runs) so the CI coverage gate can read it
* without parsing anything else. When files were flagged:
* "parse_unusable": {"files":[{path,range_end,whole_file}..(<=50)], "count":N,
* "truncated":bool, "note":"..."}
*
* These files WERE indexed, exactly like parse_partial ones. The difference is
* that their range covers 80% or more of the file, so the range is not worth
* printing — "range_end" gives the last line the range names and "whole_file"
* says plainly that reading the ranges is the same as reading the file. */
static void add_parse_unusable_summary(yyjson_mut_doc *doc, yyjson_mut_val *root,
const cbm_file_error_t *errs, int count) {
int unusable = 0;
for (int i = 0; i < count; i++) {
if (is_parse_unusable(&errs[i])) {
unusable++;
}
}
yyjson_mut_obj_add_int(doc, root, "parse_unusable_count", unusable);
if (!errs || unusable <= 0) {
return;
}
yyjson_mut_val *pu = yyjson_mut_obj(doc);
yyjson_mut_val *files = yyjson_mut_arr(doc);
int shown = 0;
for (int i = 0; i < count && shown < INDEX_SKIPPED_FILE_CAP; i++) {
if (!is_parse_unusable(&errs[i])) {
continue;
}
yyjson_mut_val *fe = yyjson_mut_obj(doc);
yyjson_mut_obj_add_strcpy(doc, fe, "path", errs[i].path ? errs[i].path : "");
yyjson_mut_obj_add_bool(doc, fe, "whole_file", true);
/* The end of the range, not the length of the file. A grammar can end
* an error node past the last line, so this number can be larger than
* the file. See range_end_is_not_file_length. */
const char *dash = errs[i].reason ? strchr(errs[i].reason, '-') : NULL;
yyjson_mut_obj_add_int(doc, fe, "range_end", dash ? atoi(dash + 1) : 0);
yyjson_mut_arr_add_val(files, fe);
shown++;
}
yyjson_mut_obj_add_val(doc, pu, "files", files);
yyjson_mut_obj_add_int(doc, pu, "count", unusable);
yyjson_mut_obj_add_bool(doc, pu, "truncated", unusable > INDEX_SKIPPED_FILE_CAP);
yyjson_mut_obj_add_str(doc, pu, "note",
"Indexed, but the parse failed across nearly the whole file, so line "
"ranges are not useful here — read the source directly.");
yyjson_mut_obj_add_val(doc, root, "parse_unusable", pu);
}
/* The pipeline persists the complete current coverage set before this
* response is built. Prefer that set over the per-run errors so incremental
* runs that do not revisit a flagged file, and artifact bootstraps, do not
@@ -10138,6 +10257,7 @@ static bool add_persisted_failure_summaries(yyjson_mut_doc *doc, yyjson_mut_val
add_skipped_summary(doc, root, failures, failure_count, logfile);
add_parse_partial_summary(doc, root, failures, failure_count);
add_parse_unusable_summary(doc, root, failures, failure_count);
free(failures);
cbm_store_free_coverage(rows, row_count);
return true;
@@ -10215,6 +10335,7 @@ static bool build_index_success_response(cbm_mcp_server_t *srv, yyjson_mut_doc *
if (!store || !add_persisted_failure_summaries(doc, root, store, project_name, logfile)) {
add_skipped_summary(doc, root, file_errors, file_error_count, logfile);
add_parse_partial_summary(doc, root, file_errors, file_error_count);
add_parse_unusable_summary(doc, root, file_errors, file_error_count);
}
int nodes = 0;
int edges = 0;
@@ -11376,10 +11497,10 @@ static void add_string_array(yyjson_mut_doc *doc, yyjson_mut_val *obj, const cha
}
/* get_code_snippet coverage note (#963): if the resolved node's file is
* flagged parse_partial, warn that the graph may under-report this file.
* Correlated by construction — the result names its file. (An entirely-
* skipped file cannot appear here: it has no nodes to resolve a snippet
* from.) */
* flagged parse_partial or parse_unusable, warn that the graph may
* under-report this file. Correlated by construction — the result names its
* file. (An entirely-skipped file cannot appear here: it has no nodes to
* resolve a snippet from.) */
static void add_snippet_coverage_note(yyjson_mut_doc *doc, yyjson_mut_val *root_obj,
cbm_store_t *store, const cbm_node_t *node) {
if (!node->file_path || !node->file_path[0] || !node->project) {
@@ -11392,18 +11513,28 @@ static void add_snippet_coverage_note(yyjson_mut_doc *doc, yyjson_mut_val *root_
return;
}
for (int i = 0; i < count; i++) {
if (rows[i].rel_path && strcmp(rows[i].rel_path, node->file_path) == 0 && rows[i].kind &&
strcmp(rows[i].kind, "parse_partial") == 0) {
char note[CBM_SZ_1K];
if (!rows[i].rel_path || strcmp(rows[i].rel_path, node->file_path) != 0 || !rows[i].kind) {
continue;
}
char note[CBM_SZ_1K];
if (strcmp(rows[i].kind, "parse_unusable") == 0) {
snprintf(note, sizeof(note),
"The parse of this file failed across nearly the whole of it, so most "
"constructs are missing from the graph and naming line ranges would not "
"help. Read the source directly — the source above is ground truth. "
"(best-effort signal)");
} else if (strcmp(rows[i].kind, "parse_partial") == 0) {
snprintf(note, sizeof(note),
"This file was only PARTIALLY indexed — line range(s) %s could not be "
"parsed, so constructs there may be missing from the graph (callers/callees "
"and search results can under-report this file). The source above is ground "
"truth. (best-effort signal)",
rows[i].detail && rows[i].detail[0] ? rows[i].detail : "?");
yyjson_mut_obj_add_strcpy(doc, root_obj, "coverage_note", note);
break;
} else {
continue;
}
yyjson_mut_obj_add_strcpy(doc, root_obj, "coverage_note", note);
break;
}
cbm_store_free_coverage(rows, count);
}
+75 -8
View File
@@ -18,6 +18,7 @@ enum { PD_RING = 4, PD_RING_MASK = 3, PD_JSON_MARGIN = 10, PD_ESC_MARGIN = 3, PD
enum { PD_JSON_FIELD_OVERHEAD = 6 };
#include "pipeline/pipeline.h"
#include <stdint.h>
#include <ctype.h>
#include "pipeline/pipeline_internal.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
@@ -544,27 +545,93 @@ static bool objectscript_export_append_secondary_arrays(CBMFileResult *aggregate
/* Preserve every generated class's parse diagnostics. The generated UDL
* snippets all map back to one physical Studio Export file, so their compact
* range lists can be concatenated using the ordinary comma separator. */
/* Read the trailing ",+<N>" truncation marker off a range string. Returns the
* number of dropped ranges the marker reports, or 0 when there is no marker,
* and writes the length of the part before the marker to `body_len`. */
static int objectscript_export_split_range_marker(const char *ranges, size_t *body_len) {
size_t len = ranges ? strlen(ranges) : 0;
*body_len = len;
if (len == 0) {
return 0;
}
size_t i = len;
while (i > 0 && isdigit((unsigned char)ranges[i - 1])) {
i--;
}
if (i == len || i == 0 || ranges[i - 1] != '+') {
return 0;
}
size_t marker = i - 1; /* index of '+' */
if (marker > 0 && ranges[marker - 1] == ',') {
marker--; /* drop the separator too */
}
*body_len = marker;
return atoi(ranges + i);
}
/* Join one Studio Export part's ranges onto the aggregate.
*
* One export file can hold several <Class> elements, each parsed separately,
* so their range strings get concatenated. A ",+<N>" truncation marker must
* end up ONCE, at the very end: every reader stops at the first token that is
* not a range, so a marker left in the middle would silently hide every range
* after it. Strip the marker off both sides, join the plain ranges, then add
* one marker back carrying the summed count. */
static bool objectscript_export_append_error_ranges(CBMFileResult *aggregate,
const CBMFileResult *part) {
aggregate->parse_incomplete = aggregate->parse_incomplete || part->parse_incomplete;
aggregate->parse_unusable = aggregate->parse_unusable || part->parse_unusable;
aggregate->error_region_count += part->error_region_count;
if (!part->error_ranges || !part->error_ranges[0]) {
return true;
}
const char *combined = NULL;
if (aggregate->error_ranges && aggregate->error_ranges[0]) {
combined = cbm_arena_sprintf(&aggregate->arena, "%s,%s", aggregate->error_ranges,
part->error_ranges);
size_t agg_len = 0;
size_t part_len = 0;
int dropped = 0;
const char *agg_body = aggregate->error_ranges;
if (agg_body && agg_body[0]) {
dropped += objectscript_export_split_range_marker(agg_body, &agg_len);
} else {
combined = cbm_arena_strdup(&aggregate->arena, part->error_ranges);
agg_body = NULL;
}
dropped += objectscript_export_split_range_marker(part->error_ranges, &part_len);
const char *combined = NULL;
if (agg_body && agg_len > 0 && part_len > 0) {
combined = cbm_arena_sprintf(&aggregate->arena, "%.*s,%.*s", (int)agg_len, agg_body,
(int)part_len, part->error_ranges);
} else if (agg_body && agg_len > 0) {
combined = cbm_arena_sprintf(&aggregate->arena, "%.*s", (int)agg_len, agg_body);
} else if (part_len > 0) {
combined = cbm_arena_sprintf(&aggregate->arena, "%.*s", (int)part_len, part->error_ranges);
} else {
combined = cbm_arena_strdup(&aggregate->arena, "");
}
if (!combined) {
return false;
}
if (dropped > 0) {
combined = cbm_arena_sprintf(&aggregate->arena, "%s%s+%d", combined, combined[0] ? "," : "",
dropped);
if (!combined) {
return false;
}
}
aggregate->error_ranges = combined;
return true;
}
#if defined(CBM_COVERAGE_MARKER_TEST_API) && CBM_COVERAGE_MARKER_TEST_API
/* Test seam. This join only fires for a Studio Export file holding several
* <Class> elements where a class overruns the 256-region cap — hard to reach
* through the pipeline, easy to get wrong, and a wrong result hides ranges
* without saying so. Expose the join so the marker rules can be pinned. */
bool cbm_pipeline_coverage_marker_test_join(CBMFileResult *aggregate, const CBMFileResult *part) {
return objectscript_export_append_error_ranges(aggregate, part);
}
#endif
/* Studio Export files may contain multiple <Class> elements, while the
* pipeline cache has one slot per physical file. Extract each generated UDL
* class independently (preserving the upstream parser behavior), then compose
@@ -785,9 +852,9 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
} else if (result->parse_incomplete) {
/* Best-effort parse-coverage signal (#963): indexed, but with
* ERROR/MISSING regions — see pass_parallel.c (keep in sync). */
cbm_pipeline_add_file_error(ctx->pipeline, rel,
result->error_ranges ? result->error_ranges : "unknown",
"parse_partial");
cbm_pipeline_add_file_error(
ctx->pipeline, rel, result->error_ranges ? result->error_ranges : "unknown",
result->parse_unusable ? "parse_unusable" : "parse_partial");
}
/* Create nodes for each definition */
+5 -4
View File
@@ -889,11 +889,12 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
} else if (result->parse_incomplete) {
/* Best-effort parse-coverage signal (#963): the file WAS indexed,
* but its tree contains ERROR/MISSING regions whose constructs are
* silently absent from the graph. Not a skip — recorded under the
* distinct "parse_partial" phase (reason = the line-range list) so
* the MCP layer reports it separately from skipped[]. */
* silently absent from the graph. Neither phase is a skip — both
* are recorded separately from skipped[] by the MCP layer.
* "parse_unusable" means one range covers so much of the file that
* naming the lines helps nobody; see parse_unusable in cbm.h. */
pp_err_add(errs, fi->rel_path, result->error_ranges ? result->error_ranges : "unknown",
"parse_partial");
result->parse_unusable ? "parse_unusable" : "parse_partial");
}
/* Create definition nodes in local gbuf */
+6
View File
@@ -864,6 +864,12 @@ void cbm_pp_bp_nap_cycles_reset(void);
uint64_t cbm_pp_lsp_linear_fallback_rows(void);
void cbm_pp_lsp_linear_fallback_rows_reset(void);
#if defined(CBM_COVERAGE_MARKER_TEST_API) && CBM_COVERAGE_MARKER_TEST_API
/* Test-only view of the Studio Export range join, so the ",+<N>" truncation
* marker rules can be checked without building a 256-region export file. */
bool cbm_pipeline_coverage_marker_test_join(CBMFileResult *aggregate, const CBMFileResult *part);
#endif
#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
/* Deterministic test-only operation count for the shared semantic-reference
* matcher used by both sequential and fused-parallel usage materialization. */
+19 -3
View File
@@ -301,9 +301,25 @@ static int init_schema(cbm_store_t *s) {
" PRIMARY KEY (project, rel_path)"
");"
/* Best-effort indexing-coverage signal (#963). One row per file the
* indexer could not fully cover: kind "parse_partial" (indexed, but the
* parse tree had ERROR/MISSING regions — detail = 1-based line ranges)
* or a skip phase ("read"/"extract"/"oversized" — detail = reason).
* indexer could not fully cover. `kind` says which of three things
* happened, and `detail` means something different in each:
*
* "parse_partial" the file WAS indexed, but the parse tree had
* ERROR/MISSING regions. detail = 1-based line
* ranges, "start-end,start-end", with an optional
* trailing "+<N>" saying N more ranges were dropped
* by the producer's cap. Read those lines.
* "parse_unusable" the file WAS indexed, but one range covers 80% or
* more of it, so naming the lines is useless advice.
* detail = the same range string. Read the source.
* a skip phase the file was NOT indexed at all: "read",
* "extract" or "oversized". detail = the reason.
*
* The first two are easy to confuse with the third, and the difference
* matters to a reader: a skipped file is absent from the graph, while
* the other two are present but incomplete. Name a new kind so that
* distinction stays obvious — "parse_failed" would read as a skip.
*
* Deliberately SEPARATE from the graph tables: coverage is metadata
* about the graph, not part of it. */
"CREATE TABLE IF NOT EXISTS index_coverage ("
+10
View File
@@ -2033,6 +2033,15 @@ TEST(cli_uninstall_quiesces_active_cohort_before_removing_binary_and_index) {
char *old_cache = NULL;
cli_activation_save_env(&old_home, &old_cache);
cbm_setenv("HOME", tmpdir, 1);
/* PATH has to move with HOME. Agent detection asks cbm_find_cli, which
* reads PATH before anything else, so a real agent binary on the developer's
* PATH is found even though HOME points at this fixture. Uninstall then
* tries to edit that agent's config file here, fails because the fixture
* never created one, and stops before removing the binary and the index —
* which is exactly what this test measures. Redirecting PATH makes the
* result the same on every machine. */
char *old_path = save_test_env("PATH");
cbm_setenv("PATH", tmpdir, 1);
char cache_dir[512];
char index_path[640];
@@ -2070,6 +2079,7 @@ TEST(cli_uninstall_quiesces_active_cohort_before_removing_binary_and_index) {
bool binary_preserved =
installed && strcmp(installed, "binary must survive active-daemon refusal") == 0;
cli_activation_restore_env(old_home, old_cache);
restore_test_env("PATH", old_path);
test_rmdir_r(tmpdir);
ASSERT_EQ(rc, 0);
+33
View File
@@ -2,6 +2,7 @@
* test_config_yaml_edit.c — Conservative YAML config editor tests.
*/
#include "../src/foundation/compat.h"
#include "../src/foundation/compat_fs.h"
#include "test_framework.h"
#include "test_helpers.h"
@@ -1826,6 +1827,37 @@ TEST(config_yaml_edit_nested_sequence_removes_only_exact_canonical_item) {
PASS();
}
/* Uninstall must be idempotent against a config that was never written. Hermes
* is detected by its binary on PATH, so a HOME without `.hermes/` reached the
* YAML removers with an absent target — and they failed acquiring the lock
* beside a file whose directory does not exist, which `uninstall` then
* counted as an agent cleanup error and refused to remove the executable.
* Every remover answers OK for a genuinely absent path and creates nothing.
* Runs on every platform: the fix has a separate Windows branch. */
TEST(config_yaml_edit_remove_on_absent_config_is_a_no_op) {
yaml_fixture_t fixture;
ASSERT_EQ(yaml_fixture_init(&fixture, NULL), 0);
char absent[sizeof(fixture.path) + 32U];
ASSERT(snprintf(absent, sizeof(absent), "%s/no-such-dir/config.yaml", fixture.dir) > 0);
ASSERT_EQ(cbm_yaml_remove_mapping_sequence_item(absent, yaml_hook_sequence_path, 2U, "id",
yaml_hook_identity, yaml_hook_canonical_item),
CBM_YAML_IDENTITY_EDIT_OK);
ASSERT_EQ(cbm_yaml_remove_owned_mapping_entry(absent, "mcp_servers", "codebase-memory-mcp",
" command: \"/opt/cbm\"\n"),
CBM_YAML_IDENTITY_EDIT_OK);
ASSERT_EQ(cbm_yaml_remove_mapping_entry(absent, "hooks", "pre_llm_call"), 0);
ASSERT_EQ(cbm_yaml_remove_string_list_item(absent, "read", "AGENTS.md"), 0);
/* Nothing was created. cbm_path_info_utf8 rather than lstat: same meaning
* — it reports the link instead of following it — and it compiles on
* Windows, which is exactly where the fix has its own branch. */
cbm_path_info_t absent_info;
ASSERT(cbm_path_info_utf8(absent, &absent_info) != 0);
th_cleanup(fixture.dir);
PASS();
}
TEST(config_yaml_edit_nested_sequence_ambiguity_fails_byte_identically) {
const char *cases[] = {
"hooks:\n pre_llm_call:\n - id: \"bad-indent\"\n",
@@ -1980,6 +2012,7 @@ SUITE(config_yaml_edit) {
RUN_TEST(config_yaml_edit_nested_sequence_foreign_identity_is_preserved);
RUN_TEST(config_yaml_edit_nested_sequence_removes_only_exact_canonical_item);
RUN_TEST(config_yaml_edit_nested_sequence_ambiguity_fails_byte_identically);
RUN_TEST(config_yaml_edit_remove_on_absent_config_is_a_no_op);
#ifndef _WIN32
RUN_TEST(config_yaml_edit_accepts_interior_asterisk_in_plain_scalar_issue1631);
RUN_TEST(config_yaml_edit_still_refuses_leading_alias_issue1631);
+21
View File
@@ -467,6 +467,26 @@ TEST(daemon_sessions_keep_distinct_roots_and_allowed_root_policy) {
PASS();
}
/* The session policy keeps a root in the spelling the daemon canonicalized it
* to - the platform's native form, backslashes on Windows. The sensitive-root
* and allowed-root containment checks compare that spelling byte-exact against
* HOME and the granted roots, so a root respelled with forward slashes on the
* way in stopped matching them, and $HOME was admitted for auto-index and
* watch on Windows. One directory being one root for the job registry is
* folded at that comparison, never by respelling the policy. */
TEST(daemon_session_context_keeps_the_policy_spelling_of_a_root) {
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
ASSERT_NOT_NULL(srv);
cbm_mcp_server_set_background_tasks(srv, false);
ASSERT_TRUE(cbm_mcp_server_set_session_context(srv, "C:\\repos\\cbm", "C:\\repos"));
ASSERT_STR_EQ(cbm_mcp_server_session_root(srv), "C:\\repos\\cbm");
ASSERT_STR_EQ(cbm_mcp_server_allowed_root(srv), "C:\\repos");
cbm_mcp_server_free(srv);
PASS();
}
SUITE(daemon) {
RUN_TEST(daemon_client_ids_are_connection_bound);
RUN_TEST(daemon_shared_job_survives_until_final_subscriber_disconnects);
@@ -480,4 +500,5 @@ SUITE(daemon) {
RUN_TEST(daemon_bridge_rejects_embedded_nul_body);
RUN_TEST(daemon_bridge_rejects_oversized_headers);
RUN_TEST(daemon_sessions_keep_distinct_roots_and_allowed_root_policy);
RUN_TEST(daemon_session_context_keeps_the_policy_spelling_of_a_root);
}
+25
View File
@@ -5382,6 +5382,30 @@ TEST(daemon_application_oversized_reply_is_a_jsonrpc_error_not_a_death) {
PASS();
}
/* One directory is one root for the job registry. The auto-index job spells
* repo_path the way the session policy holds it - the platform's native form,
* backslashes on Windows - while an explicit index_repository request arrives
* in the handler's forward-slash spelling. Compared byte-exact the two never
* matched on Windows, and the request was refused as an options conflict
* instead of joining the job already running for its root. The fold runs on
* every platform, so this binds wherever the suite runs; every other option
* stays exact. */
TEST(daemon_application_index_args_compare_repo_path_separator_equivalently) {
ASSERT_TRUE(cbm_daemon_application_index_args_equal_for_test(
"{\"repo_path\":\"C:\\\\repos\\\\cbm\"}", "{\"repo_path\":\"C:/repos/cbm\"}"));
ASSERT_TRUE(cbm_daemon_application_index_args_equal_for_test(
"{\"repo_path\":\"C:\\\\repos\\\\cbm\",\"mode\":\"full\"}",
"{\"mode\":\"full\",\"repo_path\":\"C:/repos/cbm\"}"));
ASSERT_FALSE(cbm_daemon_application_index_args_equal_for_test(
"{\"repo_path\":\"C:\\\\repos\\\\cbm\"}", "{\"repo_path\":\"C:/repos/cbm2\"}"));
ASSERT_FALSE(cbm_daemon_application_index_args_equal_for_test(
"{\"repo_path\":\"C:\\\\repos\\\\cbm\"}", "{\"repo_path\":\"C:/repos/cbm/sub\"}"));
ASSERT_FALSE(cbm_daemon_application_index_args_equal_for_test(
"{\"repo_path\":\"C:\\\\repos\\\\cbm\",\"mode\":\"incremental\"}",
"{\"repo_path\":\"C:/repos/cbm\"}"));
PASS();
}
SUITE(daemon_application) {
RUN_TEST(daemon_application_oversized_reply_is_a_jsonrpc_error_not_a_death);
RUN_TEST(daemon_application_new_session_does_not_retain_initial_store);
@@ -5400,6 +5424,7 @@ SUITE(daemon_application) {
RUN_TEST(daemon_application_initialize_coalesces_auto_index_for_full_sessions);
RUN_TEST(daemon_application_sensitive_root_blocks_auto_index_but_preserves_controls);
RUN_TEST(daemon_application_sensitive_root_blocks_watch_but_preserves_controls);
RUN_TEST(daemon_application_index_args_compare_repo_path_separator_equivalently);
RUN_TEST(daemon_application_auto_index_honors_tracked_file_limit);
RUN_TEST(daemon_application_auto_index_file_count_handles_literal_metacharacter_path);
RUN_TEST(daemon_application_auto_index_file_count_supports_non_git_roots);
+14
View File
@@ -420,6 +420,19 @@ TEST(es_calls_vue_embedded_issue1410) {
PASS();
}
TEST(es_calls_svelte_embedded_issue1807) {
static const ES_LangFile f[] = {
{"Toggle.svelte",
"<script lang=\"ts\">\n"
"function callee(): number { return 42; }\n"
"function caller(): number { return callee(); }\n"
"</script>\n"
"<button on:click={caller}>Toggle</button>\n"},
};
ASSERT_EQ(es_exact_edge_by_name(f, 1, "CALLS", "caller", "callee"), 1);
PASS();
}
/* Java: caller in Main.java calls static method from Util.java (same package). */
TEST(es_calls_crossfile_java) {
static const ES_LangFile f[] = {
@@ -927,6 +940,7 @@ SUITE(edge_structural) {
RUN_TEST(es_calls_crossfile_kotlin);
RUN_TEST(es_calls_crossfile_csharp);
RUN_TEST(es_calls_vue_embedded_issue1410);
RUN_TEST(es_calls_svelte_embedded_issue1807);
/* ── FAMILY 2: INHERITS cross-file ────────────────────────── */
/* GREEN: Java, C#, C++ (extraction confirmed correct). */
+184 -10
View File
@@ -3372,7 +3372,10 @@ TEST(vue_embedded_structure_negative_controls_issue1410) {
PASS();
}
TEST(vue_embedded_structure_host_controls_issue1410) {
/* The sibling hosts ride Vue's embedded seam: the function and call a .ts file
* yields come out of a plain <script> (or Astro's frontmatter fence) the same
* way, alongside the import those blocks always produced. */
TEST(embedded_structure_sibling_hosts_issue1807) {
CBMFileResult *plain =
extract("function plainTs(): void { target(); }\n", CBM_LANG_TYPESCRIPT, "t", "plain.ts");
ASSERT_NOT_NULL(plain);
@@ -3386,26 +3389,193 @@ TEST(vue_embedded_structure_host_controls_issue1410) {
const char *path;
const char *source;
} hosts[] = {
{CBM_LANG_SVELTE, "Control.svelte",
"<script>import value from './svelte.js'; function hidden() { target(); }</script>\n"},
{CBM_LANG_HTML, "control.html",
"<script>import value from './html.js'; function hidden() { target(); }</script>\n"},
{CBM_LANG_ASTRO, "Control.astro",
"---\nimport value from './astro.js'; function hidden() { target(); }\n---\n"},
{CBM_LANG_SVELTE, "Sibling.svelte",
"<script>import value from './svelte.js'; function visible() { target(); }</script>\n"},
{CBM_LANG_HTML, "sibling.html",
"<script>import value from './html.js'; function visible() { target(); }</script>\n"},
{CBM_LANG_ASTRO, "Sibling.astro",
"---\nimport value from './astro.js'; function visible() { target(); }\n---\n"},
};
for (int i = 0; i < 3; i++) {
CBMFileResult *r = extract(hosts[i].source, hosts[i].language, "t", hosts[i].path);
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(count_defs_with_label(r, "Module"), 1);
ASSERT_EQ(count_defs_with_label(r, "Function"), 0);
ASSERT_EQ(r->calls.count, 0);
ASSERT_EQ(count_defs_named(r, "Function", "visible"), 1);
ASSERT_EQ(count_calls_named(r, "target"), 1);
ASSERT_EQ(r->imports.count, 1);
cbm_free_result(r);
}
PASS();
}
/* Blocks that must never yield inline symbols, whatever the host: an external
* program (src=) and a non-JavaScript MIME type. The bodies are deliberately
* code, so a leak would surface as a definition and a call. HTML's own tag
* walker still records the src= reference as an import; that edge names the
* external file and is not the inline body leaking through. */
TEST(embedded_structure_inert_blocks_issue1807) {
static const struct {
CBMLanguage language;
const char *path;
const char *source;
int imports;
} blocks[] = {
{CBM_LANG_VUE, "Inert.vue",
"<script type=\"application/json\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_VUE, "Inert.vue",
"<script src=\"./x.js\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_SVELTE, "Inert.svelte",
"<script type=\"application/json\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_SVELTE, "Inert.svelte",
"<script src=\"./x.js\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_HTML, "inert.html",
"<script type=\"application/json\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_HTML, "inert.html",
"<script type=\"importmap\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_HTML, "inert.html",
"<script type=\"text/x-template\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_HTML, "inert.html",
"<script src=\"./x.js\">function hidden() { target(); }</script>\n", 1},
{CBM_LANG_ASTRO, "Inert.astro",
"<script type=\"application/json\">function hidden() { target(); }</script>\n", 0},
{CBM_LANG_ASTRO, "Inert.astro",
"<script src=\"./x.js\">function hidden() { target(); }</script>\n", 0},
};
for (int i = 0; i < 10; i++) {
CBMFileResult *r = extract(blocks[i].source, blocks[i].language, "t", blocks[i].path);
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(count_defs_with_label(r, "Module"), 1);
ASSERT_EQ(count_defs_with_label(r, "Function"), 0);
ASSERT_EQ(r->calls.count, 0);
ASSERT_EQ(r->imports.count, blocks[i].imports);
cbm_free_result(r);
}
PASS();
}
/* Svelte's module-level block (<script context="module">, or <script module>
* since Svelte 5) is a second block in the same file: both contribute, each
* honouring its own lang=, in host-file coordinates. */
TEST(svelte_embedded_structure_both_blocks_issue1807) {
static const char *sources[] = {
"<script context=\"module\" lang=\"ts\">\n"
"export function fromModule(): number { return shared(); }\n"
"</script>\n"
"<script lang=\"ts\">\n"
"import { shared } from './shared';\n"
"function fromInstance(): number { return shared() + fromModule(); }\n"
"</script>\n"
"<button on:click={fromInstance}>{fromModule()}</button>\n",
"<script module lang=\"ts\">\n"
"export function fromModule(): number { return shared(); }\n"
"</script>\n"
"<script lang=\"ts\">\n"
"import { shared } from './shared';\n"
"function fromInstance(): number { return shared() + fromModule(); }\n"
"</script>\n"
"<button onclick={fromInstance}>{fromModule()}</button>\n",
};
for (int i = 0; i < 2; i++) {
CBMFileResult *r = extract(sources[i], CBM_LANG_SVELTE, "t", "Widget.svelte");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(count_defs_with_label(r, "Function"), 2);
ASSERT_EQ(count_defs_named(r, "Function", "fromModule"), 1);
ASSERT_EQ(count_defs_named(r, "Function", "fromInstance"), 1);
ASSERT_EQ(count_calls_named(r, "shared"), 2);
ASSERT_EQ(count_calls_named(r, "fromModule"), 1);
ASSERT_EQ(r->imports.count, 1);
ASSERT(has_import(r, "shared"));
for (int d = 0; d < r->defs.count; d++) {
const CBMDefinition *def = &r->defs.items[d];
if (strcmp(def->name, "fromModule") == 0) {
ASSERT_EQ(def->start_line, 2);
} else if (strcmp(def->name, "fromInstance") == 0) {
ASSERT_EQ(def->start_line, 6);
}
}
cbm_free_result(r);
}
PASS();
}
/* Every type= form HTML itself runs as JavaScript contributes, in host-file
* coordinates; a data block on the same page does not. */
TEST(html_embedded_structure_issue1807) {
CBMFileResult *r =
extract("<!DOCTYPE html><html><head>\n"
"<script type=\"module\">\n"
"import { renderApp } from './app.js';\n"
"function boot() { renderApp(); }\n"
"</script>\n"
"<script type=\"text/javascript\">\n"
"function legacy() { boot(); }\n"
"</script>\n"
"<script type=\"application/javascript\">\n"
"function fallback() { legacy(); }\n"
"</script>\n"
"<script type=\"application/ld+json\">{\"@type\": \"Thing\"}</script>\n"
"</head><body></body></html>\n",
CBM_LANG_HTML, "t", "index.html");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(count_defs_with_label(r, "Function"), 3);
ASSERT_EQ(count_calls_named(r, "renderApp"), 1);
ASSERT_EQ(count_calls_named(r, "boot"), 1);
ASSERT_EQ(count_calls_named(r, "legacy"), 1);
ASSERT_EQ(r->imports.count, 1);
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (strcmp(d->name, "boot") == 0) {
ASSERT_EQ(d->start_line, 4);
} else if (strcmp(d->name, "legacy") == 0) {
ASSERT_EQ(d->start_line, 7);
} else if (strcmp(d->name, "fallback") == 0) {
ASSERT_EQ(d->start_line, 10);
}
}
cbm_free_result(r);
PASS();
}
/* Astro's frontmatter fence and <script> bodies are TypeScript by default: an
* interface and typed signatures parse, and both blocks contribute in
* host-file coordinates. */
TEST(astro_embedded_structure_issue1807) {
CBMFileResult *r = extract("---\n"
"import Header from './Header.astro';\n"
"interface Props { title: string }\n"
"const { title }: Props = Astro.props;\n"
"function heading(): string { return format(title); }\n"
"---\n"
"<Header />\n"
"<script>\n"
"function hydrate(): void { heading(); }\n"
"</script>\n",
CBM_LANG_ASTRO, "t", "Page.astro");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT(has_def_any(r, "Props"));
ASSERT_EQ(count_defs_named(r, "Function", "heading"), 1);
ASSERT_EQ(count_defs_named(r, "Function", "hydrate"), 1);
ASSERT_EQ(count_calls_named(r, "format"), 1);
ASSERT_EQ(count_calls_named(r, "heading"), 1);
ASSERT_EQ(r->imports.count, 1);
ASSERT(has_import(r, "Header.astro"));
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (strcmp(d->name, "heading") == 0) {
ASSERT_EQ(d->start_line, 5);
} else if (strcmp(d->name, "hydrate") == 0) {
ASSERT_EQ(d->start_line, 9);
}
}
cbm_free_result(r);
PASS();
}
TEST(html_imports_basic) {
/* Plain HTML with inline ES module imports — same generic walker. */
CBMFileResult *r = extract("<!DOCTYPE html><html><head>\n"
@@ -7235,7 +7405,11 @@ SUITE(extraction) {
RUN_TEST(vue_imports_basic);
RUN_TEST(vue_embedded_structure_issue1410);
RUN_TEST(vue_embedded_structure_negative_controls_issue1410);
RUN_TEST(vue_embedded_structure_host_controls_issue1410);
RUN_TEST(embedded_structure_sibling_hosts_issue1807);
RUN_TEST(embedded_structure_inert_blocks_issue1807);
RUN_TEST(svelte_embedded_structure_both_blocks_issue1807);
RUN_TEST(html_embedded_structure_issue1807);
RUN_TEST(astro_embedded_structure_issue1807);
RUN_TEST(html_imports_basic);
/* config_extraction_test.go ports */
+4 -2
View File
@@ -236,8 +236,10 @@ static const LabelGolden LABEL_GOLDENS[] = {
{"liquid", "Module:1"},
{"blade", "Module:1"},
{"vue", "Module:1"},
{"svelte", "Module:1"},
{"astro", "Module:1"},
/* Svelte's <script> and Astro's frontmatter fence extract structure like a
* standalone script, so each fixture's one declaration is a Variable. */
{"svelte", "Module:1,Variable:1"},
{"astro", "Module:1,Variable:1"},
{"templ", "Class:1,Module:1"},
{"typst", "Module:1"},
{"mermaid", "Module:1"},
+104 -1
View File
@@ -337,8 +337,16 @@ TEST(index_parse_partial_reported) {
ASSERT_STR_EQ("indexed", status);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(sc, "skipped_count")), 0);
/* The coverage signal is surfaced with ranges + the best-effort note. */
/* The coverage signal is surfaced with ranges + the best-effort note.
* Both bounds matter. The floor catches the signal going missing. The
* ceiling catches the opposite failure: exactly one of the two files has
* a gap, so a count above 1 means the clean Python neighbour got flagged
* as well, which is how over-flagging looks from the outside. */
ASSERT_GTE(yyjson_get_int(yyjson_obj_get(sc, "parse_partial_count")), 1);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(sc, "parse_partial_count")), 1);
/* A local gap is not a whole-file failure, so the other coverage kind
* must stay empty here. */
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(sc, "parse_unusable_count")), 0);
yyjson_val *pp = yyjson_obj_get(sc, "parse_partial");
ASSERT_NOT_NULL(pp);
yyjson_val *files = yyjson_obj_get(pp, "files");
@@ -354,7 +362,13 @@ TEST(index_parse_partial_reported) {
found_split = 1;
ASSERT_NOT_NULL(ranges);
ASSERT_GT((int)strlen(ranges), 0);
/* The gap is the two-header block, not the whole file. An
* 8-line file reported as 1-8 would be the old whole-file
* blame coming back. */
ASSERT_NULL(strstr(ranges, "1-8"));
}
/* The clean file must not appear in the list at all. */
ASSERT_NULL(fp ? strstr(fp, "good.py") : NULL);
}
ASSERT_TRUE(found_split);
const char *note = yyjson_get_str(yyjson_obj_get(pp, "note"));
@@ -474,6 +488,94 @@ TEST(index_parse_partial_reported) {
PASS();
}
/* The whole-file class as index_status prints it, and what its number means.
*
* Each parse_unusable entry reports the END of the file's one range. The field
* was called "lines", which reads as the length of the file, and the two are
* not the same number — a grammar can end an error node past the last line,
* which this repo has already seen (a 326-line PowerShell file whose range
* ended at 327). "lines" also already means a definition's line span in the
* rest of this response, so the old name collided as well.
*
* The end line is checked against the persisted coverage row rather than a
* constant, so the test states the property and not a measurement. */
TEST(index_parse_unusable_names_the_range_end) {
RProj lp;
memset(&lp, 0, sizeof(lp));
snprintf(lp.tmpdir, sizeof(lp.tmpdir), "/tmp/cbm_resil_XXXXXX");
if (!cbm_mkdtemp(lp.tmpdir)) {
FAIL("mkdtemp failed");
}
rh_to_fwd_slashes(lp.tmpdir);
/* Python gets no C preprocessor refinement, so a root-level ERROR still
* reports one range over the whole file — the parse_unusable class. */
ri_write_text(lp.tmpdir, "unparseable.py", ")))\n((( \n]]] [[[\ndef x(:\n");
ri_write_text(lp.tmpdir, "good.py", "def alpha():\n return 1\n");
char *resp = NULL;
cbm_store_t *store = ri_index_capture(&lp, &resp);
if (!resp) {
FAIL("no MCP response");
}
if (!store) {
free(resp);
FAIL("store did not open");
}
/* The end line the report should be naming, read from the persisted row. */
cbm_coverage_row_t *rows = NULL;
int cov_count = 0;
ASSERT_EQ(cbm_store_coverage_get(store, lp.project, &rows, &cov_count), CBM_STORE_OK);
int want_end = 0;
for (int i = 0; i < cov_count; i++) {
if (rows[i].rel_path && strstr(rows[i].rel_path, "unparseable.py") && rows[i].detail) {
const char *dash = strchr(rows[i].detail, '-');
if (dash) {
want_end = atoi(dash + 1);
}
}
}
cbm_store_free_coverage(rows, cov_count);
ASSERT_GT(want_end, 0);
yyjson_doc *d = yyjson_read(resp, strlen(resp), 0);
ASSERT_NOT_NULL(d);
yyjson_val *sc = yyjson_obj_get(yyjson_doc_get_root(d), "structuredContent");
ASSERT_NOT_NULL(sc);
ASSERT_EQ(yyjson_get_int(yyjson_obj_get(sc, "parse_unusable_count")), 1);
yyjson_val *pu = yyjson_obj_get(sc, "parse_unusable");
ASSERT_NOT_NULL(pu);
yyjson_val *files = yyjson_obj_get(pu, "files");
ASSERT_NOT_NULL(files);
int found = 0;
size_t idx = 0;
size_t fmax = 0;
yyjson_val *fe = NULL;
yyjson_arr_foreach(files, idx, fmax, fe) {
const char *fp = yyjson_get_str(yyjson_obj_get(fe, "path"));
/* The clean neighbour must not be listed at all. */
ASSERT_NULL(fp ? strstr(fp, "good.py") : NULL);
if (!fp || !strstr(fp, "unparseable.py")) {
continue;
}
found = 1;
yyjson_val *range_end = yyjson_obj_get(fe, "range_end");
ASSERT_NOT_NULL(range_end);
ASSERT_EQ(yyjson_get_int(range_end), want_end);
ASSERT_TRUE(yyjson_get_bool(yyjson_obj_get(fe, "whole_file")));
/* The old name is gone, not kept beside the new one. */
ASSERT_NULL(yyjson_obj_get(fe, "lines"));
}
ASSERT_TRUE(found);
yyjson_doc_free(d);
free(resp);
rh_cleanup(&lp, store);
PASS();
}
/* INV(parse-partial-clears-on-fix, #963): the persisted coverage signal must
* stay FRESH — after the broken file is fixed and the project re-indexed
* (incremental route: the DB already exists), its parse_partial row is gone
@@ -799,6 +901,7 @@ SUITE(index_resilience) {
RUN_TEST(index_clean_run_no_logfile);
RUN_TEST(index_parse_partial_reported);
RUN_TEST(index_parse_partial_clears_on_fix);
RUN_TEST(index_parse_unusable_names_the_range_end);
RUN_TEST(index_not_indexed_by_design_reported);
RUN_TEST(index_relative_repo_path_canonicalized);
}
+71
View File
@@ -640,6 +640,72 @@ static CBMLanguage disambiguate_cfc_content(const char *name, const char *conten
return lang;
}
/* ── .cls / .frm: VB6 vs Apex / ObjectScript / FORM (#721) ────────── */
static bool write_probe_file(const char *path, const char *content) {
FILE *f = fopen(path, "w");
if (!f) {
return false;
}
fputs(content, f);
fclose(f);
return true;
}
TEST(lang_cls_vb6_class_module_unsupported) {
char path[256];
snprintf(path, sizeof(path), "%s/test_lang_vb6.cls", cbm_tmpdir());
ASSERT_TRUE(write_probe_file(path, "VERSION 1.0 CLASS\r\nBEGIN\r\n MultiUse = -1 'True\r\n"
"END\r\nAttribute VB_Name = \"Widget\"\r\n"
"Option Explicit\r\n\r\nPublic Sub Go()\r\nEnd Sub\r\n"));
ASSERT_EQ(cbm_disambiguate_cls(path), CBM_LANG_COUNT);
remove(path);
PASS();
}
TEST(lang_cls_apex_stays_apex) {
char path[256];
snprintf(path, sizeof(path), "%s/test_lang_apex.cls", cbm_tmpdir());
ASSERT_TRUE(write_probe_file(path, "public with sharing class Widget {\n"
" public void go() {}\n}\n"));
ASSERT_EQ(cbm_disambiguate_cls(path), CBM_LANG_APEX);
remove(path);
/* Unreadable file keeps the pre-existing owner. */
ASSERT_EQ(cbm_disambiguate_cls("/tmp/nonexistent_file_12345.cls"), CBM_LANG_APEX);
PASS();
}
TEST(lang_cls_objectscript_stays_objectscript) {
char path[256];
snprintf(path, sizeof(path), "%s/test_lang_udl.cls", cbm_tmpdir());
ASSERT_TRUE(write_probe_file(path, "Class MyPkg.Widget Extends %RegisteredObject\n{\n\n"
"Method Go()\n{\n}\n\n}\n"));
ASSERT_EQ(cbm_disambiguate_cls(path), CBM_LANG_OBJECTSCRIPT_UDL);
remove(path);
PASS();
}
TEST(lang_frm_vb6_form_unsupported) {
char path[256];
snprintf(path, sizeof(path), "%s/test_lang_vb6.frm", cbm_tmpdir());
ASSERT_TRUE(write_probe_file(path, "VERSION 5.00\r\nBegin VB.Form Form1 \r\n"
" Caption = \"Hi\"\r\nEnd\r\n"
"Attribute VB_Name = \"Form1\"\r\nOption Explicit\r\n"));
ASSERT_EQ(cbm_disambiguate_frm(path), CBM_LANG_COUNT);
remove(path);
PASS();
}
TEST(lang_frm_form_stays_form) {
char path[256];
snprintf(path, sizeof(path), "%s/test_lang_form.frm", cbm_tmpdir());
ASSERT_TRUE(write_probe_file(path, "Symbols x, y;\nLocal F = x + y;\nPrint;\n.end\n"));
ASSERT_EQ(cbm_disambiguate_frm(path), CBM_LANG_FORM);
remove(path);
ASSERT_EQ(cbm_disambiguate_frm("/tmp/nonexistent_file_12345.frm"), CBM_LANG_FORM);
PASS();
}
TEST(lang_cfc_tag_component) {
/* <cfcomponent> wrapper ⇒ tag dialect. */
ASSERT_EQ(disambiguate_cfc_content("test_cfc_tag.cfc",
@@ -1351,6 +1417,11 @@ SUITE(language) {
RUN_TEST(lang_cfc_tag_after_license_comment);
RUN_TEST(lang_cfc_script_after_license_comment);
RUN_TEST(lang_cfc_default_on_read_fail);
RUN_TEST(lang_cls_vb6_class_module_unsupported);
RUN_TEST(lang_cls_apex_stays_apex);
RUN_TEST(lang_cls_objectscript_stays_objectscript);
RUN_TEST(lang_frm_vb6_form_unsupported);
RUN_TEST(lang_frm_form_stays_form);
/* Go test ports */
/* New languages */
+81
View File
@@ -5601,6 +5601,86 @@ TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics) {
PASS();
}
/* The range string can carry a trailing ",+<N>" marker saying the producer hit
* its own cap and threw ranges away. The reader must emit every range in front
* of the marker, must not turn the marker itself into a range, and must say
* "ranges_truncated" so nobody reads a short list as a complete one. The reader has a
* second cap of its own, and that one must report itself the same way. */
TEST(tool_check_index_coverage_reports_truncation_marker_issue963) {
enum { WIDE_RANGE_COUNT = 300 };
cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);
ASSERT_NOT_NULL(srv);
cbm_store_t *st = cbm_mcp_server_store(srv);
ASSERT_NOT_NULL(st);
const char *project = "coverage-marker";
ASSERT_EQ(cbm_store_upsert_project(st, project, "/tmp/coverage-marker"), CBM_STORE_OK);
cbm_mcp_server_set_project(srv, project);
/* 300 one-line ranges — past the reader's own 256 limit. */
char *wide = calloc(1, WIDE_RANGE_COUNT * 12 + 1);
ASSERT_NOT_NULL(wide);
size_t off = 0;
for (int i = 0; i < WIDE_RANGE_COUNT; i++) {
off += (size_t)snprintf(wide + off, WIDE_RANGE_COUNT * 12 + 1 - off, "%s%d-%d",
i ? "," : "", i * 3 + 1, i * 3 + 1);
}
cbm_coverage_row_t rows[3] = {
{.rel_path = "src/marked.c", .kind = "parse_partial", .detail = "3-4,9-9,+12"},
{.rel_path = "src/plain.c", .kind = "parse_partial", .detail = "3-4,9-9"},
{.rel_path = "src/wide.c", .kind = "parse_partial", .detail = wide},
};
for (int i = 0; i < 3; i++) {
ASSERT_EQ(cbm_store_upsert_file_hash(st, project, rows[i].rel_path, "fixture", i + 1, 10),
CBM_STORE_OK);
}
ASSERT_EQ(cbm_store_coverage_replace(st, project, rows, 3), CBM_STORE_OK);
/* The marked file: both real ranges survive, the marker is flagged, and the
* "12" from the marker never becomes a range of its own. */
char *marked =
cbm_mcp_handle_tool(srv, "check_index_coverage",
"{\"project\":\"coverage-marker\",\"paths\":[\"src/marked.c\"],\"format\":\"json\"}");
ASSERT_NOT_NULL(marked);
char *marked_inner = extract_text_content(marked);
ASSERT_NOT_NULL(marked_inner);
ASSERT_NOT_NULL(strstr(marked_inner, "\"start\":3"));
ASSERT_NOT_NULL(strstr(marked_inner, "\"start\":9"));
ASSERT_NULL(strstr(marked_inner, "\"start\":12"));
ASSERT_NOT_NULL(strstr(marked_inner, "\"ranges_truncated\":true"));
free(marked_inner);
free(marked);
/* The same ranges without a marker must NOT be reported as truncated. */
char *plain =
cbm_mcp_handle_tool(srv, "check_index_coverage",
"{\"project\":\"coverage-marker\",\"paths\":[\"src/plain.c\"],\"format\":\"json\"}");
ASSERT_NOT_NULL(plain);
char *plain_inner = extract_text_content(plain);
ASSERT_NOT_NULL(plain_inner);
ASSERT_NOT_NULL(strstr(plain_inner, "\"start\":3"));
ASSERT_NULL(strstr(plain_inner, "\"ranges_truncated\":true"));
free(plain_inner);
free(plain);
/* The reader's own limit stops the list early, so it must say so even
* though the producer sent no marker. */
char *widest =
cbm_mcp_handle_tool(srv, "check_index_coverage",
"{\"project\":\"coverage-marker\",\"paths\":[\"src/wide.c\"],\"format\":\"json\"}");
ASSERT_NOT_NULL(widest);
char *wide_inner = extract_text_content(widest);
ASSERT_NOT_NULL(wide_inner);
ASSERT_NOT_NULL(strstr(wide_inner, "\"ranges_truncated\":true"));
free(wide_inner);
free(widest);
free(wide);
cbm_mcp_server_free(srv);
PASS();
}
TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges) {
char tmp[256];
cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));
@@ -20092,6 +20172,7 @@ SUITE(mcp) {
RUN_TEST(tool_list_projects_preserves_root_beyond_one_kib);
RUN_TEST(tool_index_status_no_project);
RUN_TEST(tool_check_index_coverage_finds_path_beyond_status_cap);
RUN_TEST(tool_check_index_coverage_reports_truncation_marker_issue963);
RUN_TEST(tool_check_index_coverage_reports_paths_scopes_and_ranges);
RUN_TEST(tool_check_index_coverage_pages_exact_paths_and_restores_raw_diagnostics);
RUN_TEST(tool_check_index_coverage_preserves_multiple_scope_labels);
+308 -3
View File
@@ -20,7 +20,7 @@
* GREEN (fixed): cbm_extract_file sets parse_incomplete=true iff the tree
* contains ERROR/MISSING nodes, records the 1-based line
* ranges of the TOP-MOST error regions ("start-end,..."),
* bounded by the 64-region cap, and clean files stay
* bounded by the 256-region cap, and clean files stay
* completely unflagged (no false positives).
*
* BEST-EFFORT framing (must never be weakened the other way): a flag means
@@ -33,6 +33,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Convenience extract wrapper (same shape as test_extraction_imports.c). */
static CBMFileResult *do_extract(const char *src, CBMLanguage lang, const char *path) {
@@ -104,6 +105,29 @@ static const char *PY_CLEAN = "def ok():\n"
"def ok2():\n"
" return 2\n";
/* #1610 fixtures follow. Refinement fixtures live here so they sit beside the
* split-brace fixture they build on. */
/* Same split-brace shape as C_IFDEF_SPLIT, plus real garbage further down.
* Guards against over-suppression: the preprocessor explains the guarded
* region but explains nothing about the garbage, so BOTH must stay flagged
* and they must be reported as two separate ranges, not one big one. */
static const char *C_IFDEF_SPLIT_PLUS_GARBAGE = "#include <stdio.h>\n" /* 1 */
"\n" /* 2 */
"void ok_before(void) { }\n" /* 3 */
"\n" /* 4 */
"#ifdef FEATURE_A\n" /* 5 */
"static int guarded(int x) {\n" /* 6 */
"#else\n" /* 7 */
"static int guarded_alt(int x) {\n" /* 8 */
"#endif\n" /* 9 */
" return x + 1;\n" /* 10 */
"}\n" /* 11 */
"\n" /* 12 */
"%%% ((( &&& ))) %%%\n" /* 13 */
"\n" /* 14 */
"void ok_after(void) { }\n"; /* 15 */
/* Perl formats have a line-oriented body terminated by a lone dot. The
* following named sub pins the important recovery boundary: a grammar must
* both accept the format and resume normal declaration parsing afterwards. */
@@ -214,12 +238,22 @@ TEST(py_clean_file_not_flagged) {
PASS();
}
/* Read the trailing "+<N>" truncation marker off a range string. Returns N, or
* 0 when the string carries no marker. */
static int ranges_dropped_marker(const char *ranges) {
const char *plus = ranges ? strrchr(ranges, '+') : NULL;
if (!plus || !isdigit((unsigned char)plus[1])) {
return 0;
}
return atoi(plus + 1);
}
TEST(error_region_cap_is_honored) {
/* Pathological input: many separate unrecoverable garbage blocks
* interleaved with valid defs. The collector must stay bounded by its
* 64-region cap (matches CBM_MAX_ERROR_REGIONS in cbm.c) — pathological
* 256-region cap (matches CBM_MAX_ERROR_REGIONS in cbm.c) — pathological
* input can't blow up the report, and the flag itself still fires. */
enum { GARBAGE_BLOCKS = 200, LINE_CAP = 64 };
enum { GARBAGE_BLOCKS = 400, LINE_CAP = 256 };
char *src = (char *)malloc(GARBAGE_BLOCKS * 96 + 1);
ASSERT_NOT_NULL(src);
size_t off = 0;
@@ -238,6 +272,55 @@ TEST(error_region_cap_is_honored) {
PASS();
}
/* A clipped range list must say so. 400 garbage blocks overrun the 256-region
* cap, so the report keeps 256 ranges and ends with a "+<N>" marker naming the
* number thrown away. Without the marker the short list reads as a complete
* one, which is the whole defect this guards. */
TEST(error_region_cap_reports_what_it_dropped) {
enum { GARBAGE_BLOCKS = 400, LINE_CAP = 256 };
char *src = (char *)malloc(GARBAGE_BLOCKS * 96 + 1);
ASSERT_NOT_NULL(src);
size_t off = 0;
for (int i = 0; i < GARBAGE_BLOCKS; i++) {
off += (size_t)snprintf(
src + off, 96, "def ok%d():\n return %d\n%%%%%% garbage%d ((( %%%%%%\n", i, i, i);
}
CBMFileResult *r = do_extract(src, CBM_LANG_PYTHON, "cap_marker.py");
free(src);
ASSERT_NOT_NULL(r);
ASSERT_NOT_NULL(r->error_ranges);
/* The cap bound, so the kept list is full and the marker is present. */
ASSERT_EQ(r->error_region_count, LINE_CAP);
int dropped = ranges_dropped_marker(r->error_ranges);
ASSERT_GTE(dropped, 1);
/* Every block produces at most one region, so the total cannot exceed the
* number of blocks — a marker that overcounts would fail here. */
ASSERT_LTE(r->error_region_count + dropped, GARBAGE_BLOCKS);
/* The marker is a SUFFIX: nothing follows it, or a reader stops early and
* silently loses every range after it. */
const char *plus = strrchr(r->error_ranges, '+');
ASSERT_NOT_NULL(plus);
for (const char *c = plus + 1; *c; c++) {
ASSERT_TRUE(isdigit((unsigned char)*c));
}
cbm_free_result(r);
PASS();
}
/* Inverse guard: a file that stays under the cap must carry NO marker, or
* every ordinary report would look clipped. */
TEST(uncapped_ranges_carry_no_marker) {
const char *src = "def ok():\n return 1\n%%% garbage (((\ndef ok2():\n return 2\n";
CBMFileResult *r = do_extract(src, CBM_LANG_PYTHON, "small.py");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_NOT_NULL(r->error_ranges);
ASSERT_EQ(ranges_dropped_marker(r->error_ranges), 0);
ASSERT_NULL(strchr(r->error_ranges, '+'));
cbm_free_result(r);
PASS();
}
/* Trailing recovered functions AFTER the failed #ifdef region must not
* unflag it: recovery evidence must originate INSIDE the region, and the
* unrecovered lines (the first branch's `guarded`) keep it flagged. */
@@ -541,6 +624,216 @@ TEST(width_bearing_error_at_eof_still_flagged_with_trailing_blank_issue1746) {
PASS();
}
/* ── Phase 2: refine raw ranges with the preprocessed tree ──────────────────
*
* The raw parse sees both #ifdef branches at once, so its ERROR node covers
* the whole guarded construct (lines 5-11). The PREPROCESSED parse sees only
* the branch the preprocessor picked, and parses it clean. Every original
* line that shows up clean in that second parse is therefore accounted for,
* and reporting it as unparsed is false.
*
* What is left is the branch the preprocessor threw away — line 6 here. That
* one really is missing from the graph, so it stays flagged. Directive lines
* (#ifdef / #else / #endif) hold no construct, so a range never starts or
* ends on one.
*/
/* Return 1 if the "a-b,c-d" range string covers 1-based `line`. */
static int ranges_cover_line(const char *ranges, unsigned int line) {
const char *p = ranges;
while (p && *p) {
unsigned int s = 0, e = 0;
if (sscanf(p, "%u-%u", &s, &e) == 2 && line >= s && line <= e) {
return 1;
}
p = strchr(p, ',');
if (p) {
p++;
}
}
return 0;
}
/* Total lines covered by every range in the string. */
static unsigned int ranges_total_span(const char *ranges) {
const char *p = ranges;
unsigned int total = 0;
while (p && *p) {
unsigned int s = 0, e = 0;
if (sscanf(p, "%u-%u", &s, &e) == 2 && e >= s) {
total += e - s + 1;
}
p = strchr(p, ',');
if (p) {
p++;
}
}
return total;
}
TEST(c_ifdef_split_range_narrows_to_dropped_branch) {
/* RED before the refinement: the raw range covers the whole 5-11
* construct. GREEN after: only line 6, the branch the preprocessor did
* not pick, is still reported. */
CBMFileResult *r = do_extract(C_IFDEF_SPLIT, CBM_LANG_C, "split.c");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_NOT_NULL(r->error_ranges);
ASSERT_TRUE(ranges_cover_line(r->error_ranges, 6u)); /* dropped branch */
ASSERT_LTE(ranges_total_span(r->error_ranges), 3u); /* was 7 lines */
cbm_free_result(r);
PASS();
}
TEST(c_ifdef_split_range_excludes_lines_the_preprocessor_explained) {
/* Lines 10 and 11 are the shared body and closing brace. They parse
* clean once a branch is chosen, so pointing an agent at them is wrong. */
CBMFileResult *r = do_extract(C_IFDEF_SPLIT, CBM_LANG_C, "split.c");
ASSERT_NOT_NULL(r);
ASSERT_NOT_NULL(r->error_ranges);
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 10u));
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 11u));
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 3u)); /* ok_before */
cbm_free_result(r);
PASS();
}
TEST(c_ifdef_split_range_never_starts_on_a_directive) {
/* Lines 5, 7 and 9 are bare #ifdef / #else / #endif. No construct can
* live on them, so they must not appear in a range. */
CBMFileResult *r = do_extract(C_IFDEF_SPLIT, CBM_LANG_C, "split.c");
ASSERT_NOT_NULL(r);
ASSERT_NOT_NULL(r->error_ranges);
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 5u));
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 7u));
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 9u));
cbm_free_result(r);
PASS();
}
TEST(c_refinement_does_not_suppress_real_garbage) {
/* Anti-over-suppression. The preprocessor cannot explain line 13, so it
* stays flagged even though the guarded region above it narrowed. */
CBMFileResult *r = do_extract(C_IFDEF_SPLIT_PLUS_GARBAGE, CBM_LANG_C, "both.c");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_NOT_NULL(r->error_ranges);
ASSERT_TRUE(ranges_cover_line(r->error_ranges, 13u)); /* the garbage */
ASSERT_FALSE(ranges_cover_line(r->error_ranges, 3u)); /* ok_before */
cbm_free_result(r);
PASS();
}
TEST(c_clean_file_stays_unflagged_after_refinement) {
/* The refinement must never invent a range on a file that parses. */
CBMFileResult *r = do_extract(C_CLEAN, CBM_LANG_C, "clean.c");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->parse_incomplete);
ASSERT_NULL(r->error_ranges);
cbm_free_result(r);
PASS();
}
/* The whole-file class, and the reason the parse_unusable kind exists.
*
* The Phase 2 refinement that narrows a whole-file range using the
* preprocessed parse only runs for C, C++ and CUDA. A Python file whose root
* node is ERROR gets no such help, so it still reports one range covering
* every line — and one range over 80% of a file is not advice worth printing. */
TEST(python_whole_file_error_is_unusable) {
const char *src = ")))\n((( \n]]] [[[\ndef x(:\n";
CBMFileResult *r = do_extract(src, CBM_LANG_PYTHON, "unparseable.py");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_TRUE(r->parse_unusable);
ASSERT_EQ(r->error_region_count, 1);
ASSERT_NOT_NULL(r->error_ranges);
cbm_free_result(r);
PASS();
}
/* Inverse guard, and the one that keeps the kind meaningful: a file with a
* real but LOCAL parse failure must stay parse_partial. If this flipped, every
* flagged file would say "read the source" and the ranges would stop earning
* their keep. */
TEST(local_error_stays_partial_not_unusable) {
const char *src = "def ok():\n return 1\n%%% garbage (((\ndef ok2():\n return 2\n"
"def ok3():\n return 3\ndef ok4():\n return 4\n"
"def ok5():\n return 5\ndef ok6():\n return 6\n";
CBMFileResult *r = do_extract(src, CBM_LANG_PYTHON, "local_error.py");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_FALSE(r->parse_unusable);
cbm_free_result(r);
PASS();
}
/* A clean file is neither. */
TEST(clean_file_is_neither_partial_nor_unusable) {
CBMFileResult *r = do_extract(C_CLEAN, CBM_LANG_C, "clean_kinds.c");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->parse_incomplete);
ASSERT_FALSE(r->parse_unusable);
cbm_free_result(r);
PASS();
}
/* The C file that started this work must NOT land in the unusable class. Its
* whole-file range is exactly what Phase 2 broke up, so if this ever flips
* back to true the refinement has stopped working. */
TEST(c_ifdef_split_is_partial_never_unusable) {
CBMFileResult *r = do_extract(C_IFDEF_SPLIT, CBM_LANG_C, "split_kind.c");
ASSERT_NOT_NULL(r);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_FALSE(r->parse_unusable);
cbm_free_result(r);
PASS();
}
/* Phase 0 finding 2, pinned so a tree-sitter bump cannot change it quietly.
*
* The C grammar handles `_Thread_local` unevenly, and these are the three
* forms measured on the grammar shipped today:
*
* static _Thread_local int x = 0; parses clean
* static _Thread_local int *p; parses clean
* static _Thread_local char b[8]; fails — flagged as range 1-1
*
* The array line really is missing from the graph, so flagging it is the
* honest answer, not a false positive. This test exists to make a grammar
* bump visible: if a newer grammar fixes the array form, this goes red and
* says so, instead of leaving a wrong note in the plan. (The plan's Phase 0
* also listed the pointer form as failing. It does not fail today.) */
TEST(c_thread_local_grammar_limit_is_pinned_issue963) {
CBMFileResult *ok = do_extract("static _Thread_local int x = 0;\n"
"void f(void) { x = 1; }\n",
CBM_LANG_C, "tls_init.c");
ASSERT_NOT_NULL(ok);
ASSERT_FALSE(ok->parse_incomplete);
cbm_free_result(ok);
CBMFileResult *ptr = do_extract("static _Thread_local int *p;\n"
"void f(void) { p = 0; }\n",
CBM_LANG_C, "tls_ptr.c");
ASSERT_NOT_NULL(ptr);
ASSERT_FALSE(ptr->parse_incomplete);
cbm_free_result(ptr);
CBMFileResult *arr = do_extract("static _Thread_local char b[8];\n"
"void f(void) { b[0] = 0; }\n",
CBM_LANG_C, "tls_arr.c");
ASSERT_NOT_NULL(arr);
ASSERT_TRUE(arr->parse_incomplete);
ASSERT_NOT_NULL(arr->error_ranges);
/* The range names the one broken line, not the whole file. */
ASSERT_STR_EQ("1-1", arr->error_ranges);
/* The clean function below it still reaches the graph. */
ASSERT_TRUE(has_def(arr, "f"));
cbm_free_result(arr);
PASS();
}
SUITE(parse_coverage) {
RUN_TEST(c_ifdef_split_brace_sets_parse_incomplete);
RUN_TEST(c_ifdef_split_brace_neighbors_still_extracted);
@@ -550,6 +843,12 @@ SUITE(parse_coverage) {
RUN_TEST(py_recovered_def_not_flagged);
RUN_TEST(py_clean_file_not_flagged);
RUN_TEST(error_region_cap_is_honored);
RUN_TEST(error_region_cap_reports_what_it_dropped);
RUN_TEST(uncapped_ranges_carry_no_marker);
RUN_TEST(python_whole_file_error_is_unusable);
RUN_TEST(local_error_stays_partial_not_unusable);
RUN_TEST(clean_file_is_neither_partial_nor_unusable);
RUN_TEST(c_ifdef_split_is_partial_never_unusable);
RUN_TEST(c_trailing_recovered_defs_keep_flag);
RUN_TEST(dockerfile_missing_final_newline_not_flagged_issue1610);
RUN_TEST(dockerfile_with_final_newline_still_clean_issue1610);
@@ -560,9 +859,15 @@ SUITE(parse_coverage) {
RUN_TEST(missing_final_newline_not_flagged_across_grammars_issue1610);
RUN_TEST(real_error_before_eof_still_flagged_without_final_newline_issue1610);
RUN_TEST(width_bearing_error_at_eof_still_flagged_issue1610);
RUN_TEST(c_ifdef_split_range_narrows_to_dropped_branch);
RUN_TEST(c_ifdef_split_range_excludes_lines_the_preprocessor_explained);
RUN_TEST(c_ifdef_split_range_never_starts_on_a_directive);
RUN_TEST(c_refinement_does_not_suppress_real_garbage);
RUN_TEST(c_clean_file_stays_unflagged_after_refinement);
RUN_TEST(perl_format_followed_by_named_sub_is_complete_issue1838);
RUN_TEST(perl_malformed_source_remains_partial_issue1838);
RUN_TEST(dockerfile_trailing_blank_at_eof_not_flagged_issue1746);
RUN_TEST(real_error_before_eof_still_flagged_with_trailing_blank_issue1746);
RUN_TEST(width_bearing_error_at_eof_still_flagged_with_trailing_blank_issue1746);
RUN_TEST(c_thread_local_grammar_limit_is_pinned_issue963);
}
+84
View File
@@ -13409,6 +13409,87 @@ TEST(pipeline_markdown_and_config_prose_reaches_fts_body) {
PASS();
}
#if defined(CBM_COVERAGE_MARKER_TEST_API) && CBM_COVERAGE_MARKER_TEST_API
/* Join two Studio Export range strings and hand back the result. The caller
* owns nothing: the string lives in the aggregate's arena, so copy it out
* before the arena goes away. */
static void join_export_ranges(const char *agg_ranges, int agg_regions, const char *part_ranges,
int part_regions, char *out, size_t out_size, int *out_regions) {
CBMFileResult aggregate;
CBMFileResult part;
memset(&aggregate, 0, sizeof(aggregate));
memset(&part, 0, sizeof(part));
cbm_arena_init(&aggregate.arena);
cbm_arena_init(&part.arena);
aggregate.error_ranges = agg_ranges;
aggregate.error_region_count = agg_regions;
aggregate.parse_incomplete = true;
part.error_ranges = part_ranges;
part.error_region_count = part_regions;
part.parse_incomplete = true;
out[0] = '\0';
*out_regions = 0;
if (cbm_pipeline_coverage_marker_test_join(&aggregate, &part)) {
snprintf(out, out_size, "%s", aggregate.error_ranges ? aggregate.error_ranges : "");
*out_regions = aggregate.error_region_count;
}
cbm_arena_destroy(&aggregate.arena);
cbm_arena_destroy(&part.arena);
}
/* Count the "+" characters in a range string. A truncation marker must appear
* once and only at the end: every reader stops at the first token that is not
* a range, so a marker in the middle silently hides every range after it. */
static int count_plus(const char *s) {
int n = 0;
for (const char *p = s; *p; p++) {
if (*p == '+') {
n++;
}
}
return n;
}
TEST(pipeline_objectscript_export_range_join_keeps_one_trailing_marker) {
char joined[256];
int regions = 0;
/* Neither side dropped anything, so nothing invents a marker. */
join_export_ranges("1-2,5-9", 2, "20-24", 1, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("1-2,5-9,20-24", joined);
ASSERT_EQ(0, count_plus(joined));
ASSERT_EQ(3, regions);
/* The first class overran the cap. Its marker must move to the end, so the
* second class's ranges stay visible in front of it. */
join_export_ranges("1-2,5-9,+7", 2, "20-24", 1, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("1-2,5-9,20-24,+7", joined);
ASSERT_EQ(1, count_plus(joined));
/* The second class overran the cap. Same single trailing marker. */
join_export_ranges("1-2", 1, "20-24,+3", 1, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("1-2,20-24,+3", joined);
ASSERT_EQ(1, count_plus(joined));
/* Both overran. One marker, carrying the sum, or the report would
* under-count what it threw away. */
join_export_ranges("1-2,+7", 1, "20-24,+3", 1, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("1-2,20-24,+10", joined);
ASSERT_EQ(1, count_plus(joined));
/* An empty aggregate is the first class in the file. No leading comma. */
join_export_ranges(NULL, 0, "20-24,+3", 1, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("20-24,+3", joined);
ASSERT_EQ(1, regions);
/* A part with nothing to say leaves the aggregate exactly as it was. */
join_export_ranges("1-2,+7", 1, "", 0, joined, sizeof(joined), &regions);
ASSERT_STR_EQ("1-2,+7", joined);
PASS();
}
#endif
SUITE(pipeline) {
RUN_TEST(pipeline_lsp_surface_persisted_and_body_edit_invariant);
/* Index lock */
@@ -13453,6 +13534,9 @@ SUITE(pipeline) {
RUN_TEST(pipeline_objectscript_export_preserves_calls_sequential_parallel);
RUN_TEST(pipeline_objectscript_export_incremental_matches_full_relationships);
RUN_TEST(pipeline_objectscript_export_aggregate_exceeds_arena_block_table);
#if defined(CBM_COVERAGE_MARKER_TEST_API) && CBM_COVERAGE_MARKER_TEST_API
RUN_TEST(pipeline_objectscript_export_range_join_keeps_one_trailing_marker);
#endif
RUN_TEST(pipeline_env_access_configures_sequential_parallel_parity);
RUN_TEST(pipeline_call_reference_sequential_parallel_edge_set_parity);
RUN_TEST(pipeline_incremental_cross_file_call_reference_matches_fresh_full);