mirror of
https://github.com/DeusData/codebase-memory-mcp.git
synced 2026-11-22 17:30:49 +08:00
Merge pull request #2974 from DeusData/fix/graph-variation-and-content-loss
fix: two causes of run-to-run graph variation and three silent content losses
This commit is contained in:
+13
-3
@@ -138,9 +138,10 @@ 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
|
||||
MEM_CORE_TEST_DEFINE = -DCBM_MEM_TEST_API=1
|
||||
CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(SANITIZED_DEFINE) \
|
||||
$(KOTLIN_DEDUP_TEST_DEFINE) $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) \
|
||||
$(INCREMENTAL_TEST_DEFINE) $(COVERAGE_MARKER_TEST_DEFINE) $(TEST_COVERAGE_DEFINE) \
|
||||
$(INCREMENTAL_TEST_DEFINE) $(COVERAGE_MARKER_TEST_DEFINE) $(MEM_CORE_TEST_DEFINE) $(TEST_COVERAGE_DEFINE) \
|
||||
-g -O1 $(SANITIZE) $(TEST_COVERAGE_FLAGS)
|
||||
CXXFLAGS_TEST = $(CXXFLAGS_COMMON) $(SANITIZED_DEFINE) -g -O1 $(SANITIZE) $(TEST_COVERAGE_FLAGS) \
|
||||
$(CXX_STDLIB_FLAGS)
|
||||
@@ -160,7 +161,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) \
|
||||
$(COVERAGE_MARKER_TEST_DEFINE) $(MEM_CORE_TEST_DEFINE) \
|
||||
-DCBM_SANITIZED_BUILD=1 -g -O1 $(TSAN_SANITIZE)
|
||||
CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -DCBM_SANITIZED_BUILD=1 -g -O1 \
|
||||
$(TSAN_SANITIZE)
|
||||
@@ -1532,8 +1533,17 @@ lint-memory-core:
|
||||
@echo "=== memory-core linter ==="
|
||||
@python3 scripts/lint-memory-core.py
|
||||
|
||||
# Vendored tree-sitter scanners keep their state in the payload their create()
|
||||
# returns, one per parser. A file-scope variable is one object shared by every
|
||||
# parser in the process, and the indexer runs one per worker thread: properties
|
||||
# and jsonnet both made the graph differ run to run that way. Exceptions, each
|
||||
# argued, are in scripts/lint-vendored-scanners-whitelist.txt.
|
||||
lint-vendored-scanners:
|
||||
@echo "=== vendored scanner state ==="
|
||||
@python3 scripts/lint-vendored-scanners.py
|
||||
|
||||
# CI linters (no clang-tidy — platform-dependent, enforced locally via pre-commit)
|
||||
lint-ci: lint-cppcheck lint-format lint-no-suppress lint-memory-core
|
||||
lint-ci: lint-cppcheck lint-format lint-no-suppress lint-memory-core lint-vendored-scanners
|
||||
@echo "=== CI linters passed ==="
|
||||
|
||||
# ── Local memory-diagnostic lanes (not PR-CI gates by decision: the diag
|
||||
|
||||
@@ -46,6 +46,23 @@ The **canonical provenance record** — upstream repository, pinned commit, and
|
||||
cross-registry verification status for every grammar — is
|
||||
[`internal/cbm/vendored/grammars/MANIFEST.md`](internal/cbm/vendored/grammars/MANIFEST.md).
|
||||
|
||||
**Local modification** (`internal/cbm/vendored/grammars/jsonnet/scanner.c`,
|
||||
upstream [sourcegraph/tree-sitter-jsonnet](https://github.com/sourcegraph/tree-sitter-jsonnet)
|
||||
@ `ddd075f1939a`): upstream keeps the external scanner's state (inside a
|
||||
string, and which quote) in file-scope globals, so every parser in the process
|
||||
shares one copy, and its deserialize ignores the zero-length call that starts a
|
||||
parse, so each parse inherits whatever the previous one left. Indexing workers
|
||||
parse in parallel, so concurrent jsonnet parses corrupted each other's strings:
|
||||
a different set of files came back `parse_partial` on every index, with their
|
||||
definitions and edges. A file ending inside an unterminated string also left
|
||||
every later `|||` text block in the process unparseable. The CBM patch moves the
|
||||
state into a per-parser payload allocated by `..._external_scanner_create()` and
|
||||
resets it at the start of every deserialize; lexing logic and the serialized
|
||||
state are unchanged. It is recorded with the other scanner patches in
|
||||
MANIFEST.md's "Local source patches" table and pinned by
|
||||
`scripts/vendored-checksums.txt`. **On re-vendor: re-apply this patch**;
|
||||
`make -f Makefile.cbm lint-vendored-scanners` fails while the globals are back.
|
||||
|
||||
License summary:
|
||||
|
||||
- Nearly all grammars are **MIT**-licensed.
|
||||
|
||||
+22
-11
@@ -2856,15 +2856,18 @@ static void cs_collect_imports(CSLSPContext *ctx, TSNode root) {
|
||||
* whether it sits inside a namespace declaration: a block namespace's
|
||||
* body, or the compilation-unit siblings after a file-scoped namespace
|
||||
* (the grammar may attach those either way). */
|
||||
enum { CS_IMPORT_WALK_MAX = 256 };
|
||||
TSNode stack[CS_IMPORT_WALK_MAX];
|
||||
bool in_ns[CS_IMPORT_WALK_MAX];
|
||||
int top = 0;
|
||||
in_ns[top] = false;
|
||||
stack[top++] = root;
|
||||
typedef struct {
|
||||
TSNode node;
|
||||
bool in_ns;
|
||||
} cs_import_walk_t;
|
||||
enum { CS_IMPORT_WALK_INLINE = 256 };
|
||||
cs_import_walk_t held[CS_IMPORT_WALK_INLINE];
|
||||
cs_import_walk_t *stack = held;
|
||||
int top = 0, capacity = CS_IMPORT_WALK_INLINE;
|
||||
stack[top++] = (cs_import_walk_t){.node = root, .in_ns = false};
|
||||
while (top > 0) {
|
||||
TSNode n = stack[--top];
|
||||
bool n_in_ns = in_ns[top];
|
||||
TSNode n = stack[--top].node;
|
||||
bool n_in_ns = stack[top].in_ns;
|
||||
if (ts_node_is_null(n))
|
||||
continue;
|
||||
const char *k = ts_node_type(n);
|
||||
@@ -2964,7 +2967,7 @@ static void cs_collect_imports(CSLSPContext *ctx, TSNode root) {
|
||||
bool child_in_ns = n_in_ns || strcmp(k, "namespace_declaration") == 0 ||
|
||||
strcmp(k, "file_scoped_namespace_declaration") == 0;
|
||||
uint32_t cnc = ts_node_child_count(n);
|
||||
for (uint32_t i = 0; i < cnc && top < CS_IMPORT_WALK_MAX; i++) {
|
||||
for (uint32_t i = 0; i < cnc; i++) {
|
||||
TSNode c = ts_node_child(n, i);
|
||||
if (ts_node_is_null(c))
|
||||
continue;
|
||||
@@ -2973,8 +2976,16 @@ static void cs_collect_imports(CSLSPContext *ctx, TSNode root) {
|
||||
strcmp(ck, "constructor_declaration") == 0 || strcmp(ck, "block") == 0) {
|
||||
continue;
|
||||
}
|
||||
in_ns[top] = child_in_ns;
|
||||
stack[top++] = c;
|
||||
if (top == capacity) {
|
||||
cs_import_walk_t *grown =
|
||||
cbm_arena_alloc(ctx->arena, (size_t)capacity * 2 * sizeof(*grown));
|
||||
if (!grown)
|
||||
return;
|
||||
memcpy(grown, stack, (size_t)top * sizeof(*grown));
|
||||
stack = grown;
|
||||
capacity *= 2;
|
||||
}
|
||||
stack[top++] = (cs_import_walk_t){.node = c, .in_ns = child_in_ns};
|
||||
/* A file-scoped namespace covers the siblings that follow it. */
|
||||
if (strcmp(ck, "file_scoped_namespace_declaration") == 0)
|
||||
child_in_ns = true;
|
||||
|
||||
@@ -117,7 +117,8 @@ row instead.
|
||||
| objectscript_udl | `objectscript_udl/scanner.c`, deserialize | guard `memcpy(payload, buffer, length)` with `if (length > 0)` | UBSan: Tree-sitter passes a NULL buffer and zero length for empty scanner state; skip the zero-length copy |
|
||||
| purescript | `purescript/scanner.c`, serialize | guard `memcpy(buffer, indents->data, to_copy)` with `if (to_copy > 0)` | UBSan: zero-length `memcpy` with a NULL/0-size source when the indent vector is empty (formal UB, harmless) |
|
||||
| plsql | `plsql/parser.c`, include | `#include <tree_sitter/parser.h>` → `#include "tree_sitter/parser.h"` | The older ABI-14 generator emits angle brackets; every other vendored grammar uses the quoted form, which resolves the per-grammar `tree_sitter/` header from the including file's directory |
|
||||
| properties | `properties/scanner.c`, whole file | move the `reached_eof` flag out of a file-scope `static bool` and into a per-parser payload allocated by `..._external_scanner_create()` | **Data race, and the only one of its kind in 103 vendored scanners.** That flag is how the scanner refuses to emit a second end-of-input `FAKE_EOL`, and upstream keeps it in ONE process-wide object. With several worker threads indexing `.properties` files at once, whichever reached EOF first set the flag, so another thread's `!reached_eof` was false and its parse never received the `FAKE_EOL` it needed to finish — it sat at end-of-input asking for a token that would never arrive. Measured 2026-09-19: ~106 M parse operations on a 253-byte file before the per-file budget stopped it, after which the file was dropped from the graph and java/kotlin indexes differed run to run. Interleaved A/B under identical load, 40 runs each: unpatched 6 stalls, patched 0. The serialize/deserialize wire format is unchanged (the state is still the returned length). Upstream `6310671b24d4` still carries the static, so a re-vendor must re-apply this |
|
||||
| properties | `properties/scanner.c`, whole file | move the `reached_eof` flag out of a file-scope `static bool` and into a per-parser payload allocated by `..._external_scanner_create()` | **Data race** (jsonnet, below, had the same class with non-`static` globals; `make -f Makefile.cbm lint-vendored-scanners` now rejects mutable file-scope state in every vendored scanner). That flag is how the scanner refuses to emit a second end-of-input `FAKE_EOL`, and upstream keeps it in ONE process-wide object. With several worker threads indexing `.properties` files at once, whichever reached EOF first set the flag, so another thread's `!reached_eof` was false and its parse never received the `FAKE_EOL` it needed to finish — it sat at end-of-input asking for a token that would never arrive. Measured 2026-09-19: ~106 M parse operations on a 253-byte file before the per-file budget stopped it, after which the file was dropped from the graph and java/kotlin indexes differed run to run. Interleaved A/B under identical load, 40 runs each: unpatched 6 stalls, patched 0. The serialize/deserialize wire format is unchanged (the state is still the returned length). Upstream `6310671b24d4` still carries the static, so a re-vendor must re-apply this |
|
||||
| jsonnet | `jsonnet/scanner.c`, whole file | move `inside_node`, `ending_char` and `level_count` out of file-scope globals into a per-parser `Scanner` payload allocated by `..._external_scanner_create()` (freed by destroy); deserialize resets it before reading, including on the zero-length call that starts a parse | **Data race, and state carried between parses.** tree-sitter restores the scanner state right before each scan and saves it right after; with one process-wide copy, another worker's restore or string end landing in that window changed the scan in flight (a quoted string ran past its closing quote), so files came back with ERROR nodes that a sequential parse never produces. go/grafana__loki, 2026-11-13: 1-2 spurious `parse_partial` jsonnet files per index, 21-37 when only its 68 jsonnet files are indexed, a different set every run, with real definitions and their CALLS/DEFINES/IMPORTS/USAGE edges lost; `CBM_WORKERS=1` gave zero, every run. Upstream's deserialize also returned early on length 0, so a parse that ended inside a string (an unterminated quote) left that state to every later parse in the process, and no later `|||` text block could be lexed. Lexing logic and the 3-byte serialized state are unchanged. Pinned by `jsonnet_scanner_state_is_per_parser` and `jsonnet_scanner_state_not_carried_between_parses` in `tests/test_parse_coverage.c`. Upstream pin `ddd075f1939a` carries the globals, so a re-vendor must re-apply this |
|
||||
| wit | `wit/scanner.c`, `..._external_scanner_create` | `{}` → `{ return NULL; }` | **Uninitialized read (MSan).** The function returns `void *` but had no `return`, and tree-sitter's runtime stores the result as the scanner payload, so every WIT parse used an indeterminate value (C11 6.9.1p12 makes that undefined). The scanner never reads its payload, so ordinary builds were unaffected, and the vendored build's `-w` hid `-Wreturn-type`. Under MSan the report of this read crashed and posed as a "stack-overflow", which is why five grammar/pipeline suites were excluded from the MSan lane. Upstream bytecodealliance/tree-sitter-wit still carries it at `059bfdd1af72` (2025-06-23, the last change to `src/scanner.c`) |
|
||||
| vbnet | `vbnet/scanner.c`, `scan_xml_literal` (patch file: `tools/tree-sitter-vbnet/patches/xml-literal-tag-syntax.patch`) | inside an element tag, outside a quoted value, accept only name characters, blanks, `=`, quotes, `/>`, `>` and `<%=`; in element text, require `<` to start a tag, closing tag, comment, PI or embedded expression, and `&` to start a reference; otherwise the scan fails | **Quadratic lexing at attribute lines.** CodeGraph's scanner is offered a `<` where a declaration or member starts. There it opens a VB attribute block (`<Serializable()> _`), never an XML literal, but the scan took `<Serializable` for an element and read the rest of the file looking for a closing tag before giving up: 2,500 attributes in a 77 KB file advanced 38.5 M characters, and twice the file four times as many (`complexity_vbnet_attribute_lexing_is_linear` in `tests/test_complexity.c`: lexer bytes ratio 3.99 → 2.0). Each new check rejects only text that well-formed XML cannot contain, so no VB XML literal lexes differently: parse trees are byte-identical before and after on every sample and synthetic file tried (25 files, including XML literals with attributes, entities, CDATA, comments, PIs, nested embedded expressions and multi-line bodies). Not upstream in CodeGraph; drop this row if CodeGraph's scanner gains an equivalent check |
|
||||
| sql | `sql/scanner.c`, deserialize | `free(state->start_tag);` before `state->start_tag = NULL;` | **Leak (LeakSanitizer, Linux x64; 0e61867d9).** tree-sitter calls deserialize repeatedly during a parse, and each call dropped the previous `start_tag` allocation; freeing it first is safe because create() NULL-initializes it and destroy() frees and NULLs it. Upstream fixed the same leak after our pin in `ee2f84f9b857` (2026-04-24, merged via #361 on 2026-09-19; it also moves the free out of serialize and checks the allocation): drop this row on a refresh past it. `tools/tree-sitter-sql/src/scanner.c` is this patched file |
|
||||
|
||||
+54
-31
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <wctype.h>
|
||||
#include <stdio.h>
|
||||
#include "tree_sitter/alloc.h"
|
||||
#include "tree_sitter/parser.h"
|
||||
|
||||
enum TokenType {
|
||||
@@ -39,35 +40,56 @@ static inline void skip_whitespaces(TSLexer *lexer) {
|
||||
}
|
||||
}
|
||||
|
||||
void *tree_sitter_jsonnet_external_scanner_create() { return NULL; }
|
||||
void tree_sitter_jsonnet_external_scanner_destroy(void *payload) {}
|
||||
|
||||
enum InsideNode { INSIDE_NONE, INSIDE_STRING };
|
||||
|
||||
uint8_t inside_node = INSIDE_NONE;
|
||||
char ending_char = 0;
|
||||
uint8_t level_count = 0;
|
||||
/* Local patch (see grammars/MANIFEST.md, "Local source patches"): the scanner
|
||||
* state lives in the payload, one per parser, which is what tree-sitter's
|
||||
* create/destroy contract is for, and deserialize resets it first.
|
||||
*
|
||||
* Upstream keeps these three fields in file-scope globals: one object for the
|
||||
* whole process, shared by every worker thread's parser. tree-sitter restores
|
||||
* the state right before each scan and saves it right after, so another
|
||||
* thread's write in between changed a scan in flight -- a quoted string ran
|
||||
* past its closing quote, and the file came back with ERROR nodes that a
|
||||
* sequential parse never produces (go/grafana__loki: 1-2 spurious partial
|
||||
* jsonnet files per index, 21-37 when only its 68 jsonnet files are indexed,
|
||||
* a different set every run, real definitions and edges lost with them).
|
||||
* Upstream's deserialize also ignored the zero-length call that starts each
|
||||
* parse, so the state left by the previous parse carried over: after one file
|
||||
* with an unterminated quote, no later parse in the process could lex a |||
|
||||
* text block. */
|
||||
typedef struct {
|
||||
uint8_t inside_node;
|
||||
char ending_char;
|
||||
uint8_t level_count;
|
||||
} Scanner;
|
||||
|
||||
static inline void reset_state() {
|
||||
inside_node = INSIDE_NONE;
|
||||
ending_char = 0;
|
||||
level_count = 0;
|
||||
void *tree_sitter_jsonnet_external_scanner_create() { return ts_calloc(1, sizeof(Scanner)); }
|
||||
void tree_sitter_jsonnet_external_scanner_destroy(void *payload) { ts_free(payload); }
|
||||
|
||||
static inline void reset_state(Scanner *s) {
|
||||
s->inside_node = INSIDE_NONE;
|
||||
s->ending_char = 0;
|
||||
s->level_count = 0;
|
||||
}
|
||||
|
||||
unsigned tree_sitter_jsonnet_external_scanner_serialize(void *payload, char *buffer) {
|
||||
buffer[0] = inside_node;
|
||||
buffer[1] = ending_char;
|
||||
buffer[2] = level_count;
|
||||
Scanner *s = (Scanner *)payload;
|
||||
buffer[0] = s->inside_node;
|
||||
buffer[1] = s->ending_char;
|
||||
buffer[2] = s->level_count;
|
||||
return 3;
|
||||
}
|
||||
|
||||
void tree_sitter_jsonnet_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {
|
||||
Scanner *s = (Scanner *)payload;
|
||||
reset_state(s); /* length 0 = start of a parse: no state carried over */
|
||||
if (length == 0) return;
|
||||
inside_node = buffer[0];
|
||||
s->inside_node = buffer[0];
|
||||
if (length == 1) return;
|
||||
ending_char = buffer[1];
|
||||
s->ending_char = buffer[1];
|
||||
if (length == 2) return;
|
||||
level_count = buffer[2];
|
||||
s->level_count = buffer[2];
|
||||
}
|
||||
|
||||
static bool scan_block_start(TSLexer *lexer) {
|
||||
@@ -102,40 +124,40 @@ static bool scan_block_content(TSLexer *lexer) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool scan_string_start(TSLexer *lexer) {
|
||||
static bool scan_string_start(Scanner *s, TSLexer *lexer) {
|
||||
if (lexer->lookahead == '"' || lexer->lookahead == '\'') {
|
||||
inside_node = INSIDE_STRING;
|
||||
ending_char = lexer->lookahead;
|
||||
s->inside_node = INSIDE_STRING;
|
||||
s->ending_char = lexer->lookahead;
|
||||
consume(lexer);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (scan_block_start(lexer)) {
|
||||
inside_node = INSIDE_STRING;
|
||||
s->inside_node = INSIDE_STRING;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool scan_string_end(TSLexer *lexer) {
|
||||
if (ending_char == 0) { // block string
|
||||
static bool scan_string_end(Scanner *s, TSLexer *lexer) {
|
||||
if (s->ending_char == 0) { // block string
|
||||
return scan_block_end(lexer);
|
||||
}
|
||||
|
||||
if (consume_char(ending_char, lexer)) {
|
||||
if (consume_char(s->ending_char, lexer)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool scan_string_content(TSLexer *lexer) {
|
||||
if (ending_char == 0) { // block string
|
||||
static bool scan_string_content(Scanner *s, TSLexer *lexer) {
|
||||
if (s->ending_char == 0) { // block string
|
||||
return scan_block_content(lexer);
|
||||
}
|
||||
|
||||
while (lexer->lookahead != '\n' && lexer->lookahead != 0 && lexer->lookahead != ending_char) {
|
||||
while (lexer->lookahead != '\n' && lexer->lookahead != 0 && lexer->lookahead != s->ending_char) {
|
||||
while (consume_char('\\', lexer) && consume_char('z', lexer)) continue;
|
||||
|
||||
if (lexer->lookahead == 0) {
|
||||
@@ -149,14 +171,15 @@ static bool scan_string_content(TSLexer *lexer) {
|
||||
}
|
||||
|
||||
bool tree_sitter_jsonnet_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
|
||||
if (inside_node == INSIDE_STRING) {
|
||||
if (valid_symbols[STRING_END] && scan_string_end(lexer)) {
|
||||
reset_state();
|
||||
Scanner *s = (Scanner *)payload;
|
||||
if (s->inside_node == INSIDE_STRING) {
|
||||
if (valid_symbols[STRING_END] && scan_string_end(s, lexer)) {
|
||||
reset_state(s);
|
||||
lexer->result_symbol = STRING_END;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (valid_symbols[STRING_CONTENT] && scan_string_content(lexer)) {
|
||||
if (valid_symbols[STRING_CONTENT] && scan_string_content(s, lexer)) {
|
||||
lexer->result_symbol = STRING_CONTENT;
|
||||
return true;
|
||||
}
|
||||
@@ -166,7 +189,7 @@ bool tree_sitter_jsonnet_external_scanner_scan(void *payload, TSLexer *lexer, co
|
||||
|
||||
skip_whitespaces(lexer);
|
||||
|
||||
if (valid_symbols[STRING_START] && scan_string_start(lexer)) {
|
||||
if (valid_symbols[STRING_START] && scan_string_start(s, lexer)) {
|
||||
lexer->result_symbol = STRING_START;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# lint-vendored-scanners: file-scope variables that are not shared parse state
|
||||
#
|
||||
# The gate (make -f Makefile.cbm lint-vendored-scanners) rejects every
|
||||
# non-const file-scope variable in a vendored scanner, because such a variable
|
||||
# is one object shared by every parser in the process (one per indexing
|
||||
# thread). An entry here argues that one specific variable is never written
|
||||
# after its initializer, so sharing it cannot change any parse.
|
||||
#
|
||||
# Rules:
|
||||
# * Argue from the code: say where the variable is read and that nothing
|
||||
# assigns it. A variable a scan writes is never whitelisted; move it into
|
||||
# the payload instead (grammars/MANIFEST.md, "Local source patches").
|
||||
# * An entry that no longer matches a finding fails the gate, so re-check
|
||||
# the entry when a grammar is re-vendored.
|
||||
#
|
||||
# Format, one line each: path :: variable :: why
|
||||
# `variable` may be an fnmatch pattern for a family of generated variables;
|
||||
# the argument must then hold for every name it matches.
|
||||
|
||||
internal/cbm/vendored/grammars/haskell/scanner.c :: debug_parse_metadata :: initialized false and never assigned; read once, to decide whether to dump debug output (`if (debug_parse_metadata) dump_parse_metadata(env)`)
|
||||
internal/cbm/vendored/grammars/haskell/unicode.h :: bitmap_*_codepoint :: 40 generated `static int32_t bitmap_<class>_<n>_{min,max}_codepoint = <constant>` range bounds; none is ever assigned, incremented or address-taken, each is only read by the bitmap lookup generated next to it
|
||||
internal/cbm/vendored/grammars/purescript/scanner.c :: res_cont :: `static Result res_cont = {.sym = FAIL, .finished = false}`, a constant missing its const: its 30-odd uses all `return res_cont` by value; nothing assigns a field or takes its address
|
||||
internal/cbm/vendored/grammars/purescript/scanner.c :: res_fail :: `static Result res_fail = {.sym = FAIL, .finished = true}`, same as res_cont: only returned by value, never assigned or address-taken
|
||||
@@ -0,0 +1,234 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject mutable file-scope state in vendored tree-sitter external scanners.
|
||||
|
||||
tree-sitter gives every parser its own scanner state: whatever
|
||||
`tree_sitter_<lang>_external_scanner_create()` returns is that parser's
|
||||
payload. State kept anywhere else -- a file-scope variable -- is one object for
|
||||
the whole process, shared by every parser, and the indexer runs one parser per
|
||||
worker thread. Two vendored scanners did this and both made the graph differ
|
||||
from run to run: properties (a `static bool`, 2026-09) and jsonnet (three plain
|
||||
globals, 2026-11). See grammars/MANIFEST.md, "Local source patches".
|
||||
|
||||
Scope: internal/cbm/vendored/grammars/*/scanner.c and the headers next to it
|
||||
(scanners keep helpers in e.g. unicode.h). tree_sitter/ is the runtime's own
|
||||
header set and is not scanned.
|
||||
|
||||
A finding is a top-level declaration of a variable that is not const. The
|
||||
script understands just enough C for that: comments, string and character
|
||||
literals and preprocessor lines are blanked, function and type bodies are
|
||||
skipped, brace initializers are kept with their declaration. It stays
|
||||
conservative on purpose -- a missed form is acceptable, a flagged clean scanner
|
||||
is not -- so it does not report:
|
||||
* anything declared const (even `const char *p`, whose pointer is mutable),
|
||||
* anything with a parenthesis before its initializer (function prototypes,
|
||||
function-pointer variables, macro-typed or attributed declarations),
|
||||
* initialized arrays (lookup tables; an uninitialized array is reported),
|
||||
* typedef and extern declarations.
|
||||
|
||||
Exceptions live in scripts/lint-vendored-scanners-whitelist.txt, one
|
||||
`path :: name :: why` line each (name may be an fnmatch pattern for a family
|
||||
of generated variables); an entry that matches nothing is itself an error, so
|
||||
the list cannot outlive the code it excuses.
|
||||
|
||||
Usage: scripts/lint-vendored-scanners.py [--root DIR] [FILE...]
|
||||
Exit 0 clean, 1 findings or stale whitelist entries, 2 usage/IO error.
|
||||
"""
|
||||
import argparse
|
||||
import fnmatch
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
GRAMMARS = os.path.join("internal", "cbm", "vendored", "grammars")
|
||||
WHITELIST = os.path.join("scripts", "lint-vendored-scanners-whitelist.txt")
|
||||
IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
||||
|
||||
|
||||
def blank_comments_and_literals(text):
|
||||
"""Replace comments and string/char literal contents with spaces, keeping newlines."""
|
||||
out = []
|
||||
i, n = 0, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
nxt = text[i + 1] if i + 1 < n else ""
|
||||
if c == "/" and nxt == "/":
|
||||
while i < n and text[i] != "\n":
|
||||
out.append(" ")
|
||||
i += 1
|
||||
elif c == "/" and nxt == "*":
|
||||
out.append(" ")
|
||||
i += 2
|
||||
while i < n and not (text[i] == "*" and i + 1 < n and text[i + 1] == "/"):
|
||||
out.append("\n" if text[i] == "\n" else " ")
|
||||
i += 1
|
||||
out.append(" ")
|
||||
i += 2
|
||||
elif c in "\"'":
|
||||
quote = c
|
||||
out.append(c)
|
||||
i += 1
|
||||
while i < n and text[i] != quote and text[i] != "\n":
|
||||
if text[i] == "\\" and i + 1 < n:
|
||||
out.append(" " if text[i + 1] != "\n" else " \n")
|
||||
i += 2
|
||||
continue
|
||||
out.append(" ")
|
||||
i += 1
|
||||
if i < n and text[i] == quote:
|
||||
out.append(quote)
|
||||
i += 1
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def blank_preprocessor(text):
|
||||
"""Blank preprocessor lines, including backslash continuations."""
|
||||
lines = text.split("\n")
|
||||
continued = False
|
||||
for idx, line in enumerate(lines):
|
||||
if continued or line.lstrip().startswith("#"):
|
||||
continued = line.rstrip().endswith("\\")
|
||||
lines[idx] = ""
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def classify(stmt):
|
||||
"""Return the variable name if the top-level statement defines mutable state, else None."""
|
||||
tokens = IDENT.findall(stmt)
|
||||
if not tokens or "typedef" in tokens or "extern" in tokens or "const" in tokens:
|
||||
return None
|
||||
decl = stmt.split("=", 1)[0]
|
||||
if "(" in decl:
|
||||
return None
|
||||
if "[" in decl and "=" in stmt:
|
||||
return None # initialized array: a table
|
||||
if "{...}" in decl:
|
||||
decl = decl.split("{...}", 1)[1] # struct/union/enum body, then its declarators
|
||||
names = IDENT.findall(decl)
|
||||
return names[0] if names else None
|
||||
names = IDENT.findall(decl.split("[", 1)[0])
|
||||
if len(names) < 2 or names[0] in ("struct", "union", "enum") and len(names) == 2:
|
||||
return None # a lone macro call, or a forward declaration
|
||||
return names[-1]
|
||||
|
||||
|
||||
def findings(path):
|
||||
with open(path, encoding="utf-8", errors="replace") as fh:
|
||||
text = blank_preprocessor(blank_comments_and_literals(fh.read()))
|
||||
found = []
|
||||
stmt, start_line, line = "", 1, 1
|
||||
depth = 0 # depth of a skipped body or initializer
|
||||
keep_body = False # the skipped braces belong to the statement (initializer or type body)
|
||||
transparent = 0 # extern "C" { ... } blocks: their braces are not a scope
|
||||
for ch in text:
|
||||
if ch == "\n":
|
||||
line += 1
|
||||
if depth > 0:
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
if keep_body:
|
||||
stmt += "{...}"
|
||||
else:
|
||||
stmt = "" # a function body ends its definition
|
||||
continue
|
||||
if ch == "{":
|
||||
head = stmt.strip()
|
||||
if head == "extern" or re.fullmatch(r"extern\s+\"\s*\"", head):
|
||||
transparent += 1
|
||||
stmt = ""
|
||||
continue
|
||||
# an initializer, or a struct/union/enum body, stays part of the statement
|
||||
keep_body = "=" in head or ("(" not in head and bool(head))
|
||||
depth = 1
|
||||
continue
|
||||
if ch == "}" and transparent > 0:
|
||||
transparent -= 1
|
||||
stmt = ""
|
||||
continue
|
||||
if ch == ";":
|
||||
name = classify(stmt)
|
||||
if name:
|
||||
found.append((start_line, name, " ".join(stmt.split())))
|
||||
stmt = ""
|
||||
continue
|
||||
if not stmt.strip() and not ch.isspace():
|
||||
start_line = line
|
||||
stmt += ch
|
||||
return found
|
||||
|
||||
|
||||
def load_whitelist(root):
|
||||
entries = {}
|
||||
path = os.path.join(root, WHITELIST)
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
for number, raw in enumerate(fh, 1):
|
||||
text = raw.strip()
|
||||
if not text or text.startswith("#"):
|
||||
continue
|
||||
parts = [p.strip() for p in text.split("::")]
|
||||
if len(parts) != 3 or not all(parts):
|
||||
raise ValueError(f"{WHITELIST}:{number}: expected `path :: name :: why`")
|
||||
entries[(parts[0], parts[1])] = number
|
||||
return entries
|
||||
|
||||
|
||||
def scanner_files(root):
|
||||
base = os.path.join(root, GRAMMARS)
|
||||
out = []
|
||||
for lang in sorted(os.listdir(base)):
|
||||
directory = os.path.join(base, lang)
|
||||
if not os.path.isfile(os.path.join(directory, "scanner.c")):
|
||||
continue
|
||||
for name in sorted(os.listdir(directory)):
|
||||
if name == "scanner.c" or name.endswith(".h"):
|
||||
out.append(os.path.join(directory, name))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
parser.add_argument("--root", default=".")
|
||||
parser.add_argument("files", nargs="*", help="check these files instead of every scanner")
|
||||
args = parser.parse_args()
|
||||
root = os.path.abspath(args.root)
|
||||
try:
|
||||
whitelist = load_whitelist(root)
|
||||
files = [os.path.abspath(f) for f in args.files] or scanner_files(root)
|
||||
except (OSError, ValueError) as err:
|
||||
print(f"lint-vendored-scanners: {err}", file=sys.stderr)
|
||||
return 2
|
||||
used, bad = set(), 0
|
||||
for path in files:
|
||||
rel = os.path.relpath(path, root)
|
||||
try:
|
||||
hits = findings(path)
|
||||
except OSError as err:
|
||||
print(f"lint-vendored-scanners: {err}", file=sys.stderr)
|
||||
return 2
|
||||
for line, name, stmt in hits:
|
||||
entry = next((key for key in whitelist
|
||||
if key[0] == rel and fnmatch.fnmatchcase(name, key[1])), None)
|
||||
if entry:
|
||||
used.add(entry)
|
||||
continue
|
||||
bad += 1
|
||||
print(f"{rel}:{line}: mutable file-scope state `{name}`: {stmt}")
|
||||
if not args.files:
|
||||
for (rel, name), number in sorted(whitelist.items(), key=lambda kv: kv[1]):
|
||||
if (rel, name) not in used:
|
||||
bad += 1
|
||||
print(f"{WHITELIST}:{number}: stale entry, nothing matches `{rel} :: {name}`")
|
||||
print(f"lint-vendored-scanners: {len(files)} files, {bad} problem(s)")
|
||||
if bad:
|
||||
print("Scanner state belongs in the payload from ..._external_scanner_create(); "
|
||||
"see grammars/MANIFEST.md, \"Local source patches\".")
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -69,7 +69,7 @@ src/pipeline/pass_infrascan.c 2
|
||||
src/pipeline/pass_k8s.c 6
|
||||
src/pipeline/pass_lsp_cross.c 49
|
||||
src/pipeline/pass_parallel.c 31
|
||||
src/pipeline/pass_pkgmap.c 81
|
||||
src/pipeline/pass_pkgmap.c 80
|
||||
src/pipeline/pass_semantic.c 3
|
||||
src/pipeline/pass_tests.c 3
|
||||
src/pipeline/pass_usages.c 4
|
||||
|
||||
@@ -5,7 +5,7 @@ c5cfb43042b6b72045f4ba997834d0a7786d2793d91680868b5815b39f14fc78 internal/cbm/v
|
||||
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/common/tree_sitter/alloc.h
|
||||
31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/common/tree_sitter/array.h
|
||||
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/common/tree_sitter/parser.h
|
||||
e7478214041a2186a67160ccad3f08ddfcb8259b073172a19b9a2c947c260263 internal/cbm/vendored/grammars/MANIFEST.md
|
||||
94754d9c92a06fcca21f753cb91197158ea7c659725c104572ce9788bae65690 internal/cbm/vendored/grammars/MANIFEST.md
|
||||
ad8425038de519f8c4e3e9339feebf99dfad8a6002dcf79227d91402780a32cc internal/cbm/vendored/grammars/ada/LICENSE
|
||||
02805ec13939b749c891567be36bf024b09034e04c80683a1ae667272458d549 internal/cbm/vendored/grammars/ada/parser.c
|
||||
115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/ada/tree_sitter/alloc.h
|
||||
@@ -397,7 +397,7 @@ a0eb71abd5be3c0f190d7b074e4d9f5da94785307602d0ff07e17896fa29666e internal/cbm/v
|
||||
c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/json5/tree_sitter/parser.h
|
||||
9255998527012c182050a5bdb9ce619176f96bbeb2a056c3ba939011f85da611 internal/cbm/vendored/grammars/jsonnet/LICENSE
|
||||
11705370b4ba242003aa47468977d842abd4ec49ef7ee0112957c617737c7964 internal/cbm/vendored/grammars/jsonnet/parser.c
|
||||
aefbc834d85dae403669b9f9e435587e6ff5d5f5fcdaafaa430a864e5370f648 internal/cbm/vendored/grammars/jsonnet/scanner.c
|
||||
d879e4f12892d0da405549bbbff5a394af5dff9d7c2e003b65a102bafe633f81 internal/cbm/vendored/grammars/jsonnet/scanner.c
|
||||
b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/jsonnet/tree_sitter/alloc.h
|
||||
194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/jsonnet/tree_sitter/array.h
|
||||
21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/jsonnet/tree_sitter/parser.h
|
||||
|
||||
@@ -31,4 +31,23 @@ static inline const yyjson_alc *cbm_json_writer_allocator(void) {
|
||||
return &allocator;
|
||||
}
|
||||
|
||||
/* yyjson's strict writer refuses a whole document over one byte that is not
|
||||
* UTF-8, and text read from a source file can be in any encoding. A valid
|
||||
* document is written exactly as the strict writer writes it. A refused one is
|
||||
* written again with the layout writer's flags (#2907): each such byte becomes
|
||||
* an escaped U+FFFD, and valid non-ASCII text is escaped too. The result is
|
||||
* always strict JSON; NULL only for another failure the strict writer reports,
|
||||
* such as a failed allocation or a missing root. alc and len mean what they do
|
||||
* in yyjson_mut_write_opts. */
|
||||
static inline char *cbm_json_write_text(const yyjson_mut_doc *doc, const yyjson_alc *alc,
|
||||
size_t *len) {
|
||||
yyjson_write_err err = {0};
|
||||
char *json = yyjson_mut_write_opts(doc, 0, alc, len, &err);
|
||||
if (json || err.code != YYJSON_WRITE_ERROR_INVALID_STRING) {
|
||||
return json;
|
||||
}
|
||||
return yyjson_mut_write_opts(
|
||||
doc, YYJSON_WRITE_ALLOW_INVALID_UNICODE | YYJSON_WRITE_ESCAPE_UNICODE, alc, len, NULL);
|
||||
}
|
||||
|
||||
#endif /* CBM_JSON_WRITER_H */
|
||||
|
||||
@@ -11,6 +11,7 @@ static void check_owned(const void *block, const char *op);
|
||||
#include "foundation/constants.h"
|
||||
#include "foundation/log.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -281,7 +282,37 @@ void *cbm_calloc(cbm_mem_class_t cls, size_t bytes) {
|
||||
return block;
|
||||
}
|
||||
|
||||
#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API
|
||||
|
||||
static _Thread_local bool tl_test_realloc_armed;
|
||||
static _Thread_local bool tl_test_realloc_fired;
|
||||
static _Thread_local cbm_mem_class_t tl_test_realloc_class;
|
||||
|
||||
void cbm_mem_test_fail_next_realloc(cbm_mem_class_t cls) {
|
||||
tl_test_realloc_class = cls;
|
||||
tl_test_realloc_fired = false;
|
||||
tl_test_realloc_armed = true;
|
||||
}
|
||||
|
||||
bool cbm_mem_test_reset_realloc_failure(void) {
|
||||
bool fired = tl_test_realloc_fired;
|
||||
tl_test_realloc_armed = false;
|
||||
tl_test_realloc_fired = false;
|
||||
return fired;
|
||||
}
|
||||
#endif
|
||||
|
||||
void *cbm_realloc(cbm_mem_class_t cls, void *block, size_t bytes) {
|
||||
#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API
|
||||
/* Intercept before realloc(NULL) delegates to cbm_alloc. No ownership or
|
||||
* accounting state has changed when this one requested allocation fails. */
|
||||
if (tl_test_realloc_armed && cls == tl_test_realloc_class) {
|
||||
tl_test_realloc_armed = false;
|
||||
tl_test_realloc_fired = true;
|
||||
errno = ENOMEM;
|
||||
return NULL;
|
||||
}
|
||||
#endif
|
||||
if (!block) {
|
||||
return cbm_alloc(cls, bytes);
|
||||
}
|
||||
|
||||
@@ -95,6 +95,15 @@ void *cbm_realloc(cbm_mem_class_t cls, void *block, size_t bytes);
|
||||
char *cbm_mem_strdup(cbm_mem_class_t cls, const char *s);
|
||||
void cbm_free(cbm_mem_class_t cls, void *block);
|
||||
|
||||
#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API
|
||||
/* Test-only, current-thread fault: fail exactly the next cbm_realloc for this
|
||||
* class, including realloc(NULL). Other classes and allocation operations are
|
||||
* unaffected. Always reset immediately after the operation under test. */
|
||||
void cbm_mem_test_fail_next_realloc(cbm_mem_class_t cls);
|
||||
/* Disarm and clear the hook; return whether the requested fault occurred. */
|
||||
bool cbm_mem_test_reset_realloc_failure(void);
|
||||
#endif
|
||||
|
||||
/* ── Accounting ────────────────────────────────────────────────────────
|
||||
*
|
||||
* live_bytes is what the ALLOCATOR handed us (usable size), so it exceeds the
|
||||
|
||||
@@ -1905,8 +1905,14 @@ int64_t cbm_gbuf_insert_edge(cbm_gbuf_t *gb, int64_t source_id, int64_t target_i
|
||||
edge->type = (char *)gb_intern(gb, type);
|
||||
edge->properties_json = (char *)gb_intern(gb, properties_json);
|
||||
|
||||
/* Store pointer in array */
|
||||
/* Publication reads this primary array. Do not register a missing edge
|
||||
* in secondary indexes or report success when array growth fails. */
|
||||
int before = gb->edges.count;
|
||||
cbm_da_push(&gb->edges, edge);
|
||||
if (gb->edges.count != before + 1) {
|
||||
cbm_free(CBM_MEM_CLASS_GBUF_EDGE, edge);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Dedup index */
|
||||
(void)edge_key_map_set(&gb->edge_by_key, h0, h1, edge);
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
#include "cbm.h" /* cbm_label_is_relation — reg-only surface membership */
|
||||
#include "doclink.h" /* cbm_doclink_portable_scope — the "dl" key */
|
||||
#include "foundation/json_writer.h"
|
||||
#include "foundation/log.h"
|
||||
#include "foundation/mem_core.h"
|
||||
#include "foundation/sha256.h"
|
||||
@@ -495,7 +496,9 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu
|
||||
yyjson_mut_doc_free(doc);
|
||||
return NULL;
|
||||
}
|
||||
char *json = yyjson_mut_write(doc, 0, out_len);
|
||||
/* Names, types and strings come from source text, which need not be UTF-8:
|
||||
* one such byte must not cost the repository every surface row. */
|
||||
char *json = cbm_json_write_text(doc, NULL, out_len);
|
||||
yyjson_mut_doc_free(doc);
|
||||
return json;
|
||||
}
|
||||
|
||||
+71
-26
@@ -1075,6 +1075,40 @@ static bool pkgmap_is_psr4_prefix(const char *pkg_name) {
|
||||
return n > 0 && pkg_name[n - SKIP_ONE] == '\\';
|
||||
}
|
||||
|
||||
/* How far below the repository root an entry sits: 0 for the root itself. */
|
||||
static int pkgmap_entry_depth(const char *entry_rel) {
|
||||
if (!entry_rel[0] || strcmp(entry_rel, ".") == 0) {
|
||||
return 0;
|
||||
}
|
||||
int depth = SKIP_ONE;
|
||||
for (const char *p = entry_rel; *p; p++) {
|
||||
if (*p == '/') {
|
||||
depth++;
|
||||
}
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
/* Merge order: by package name, then the entry nearest the repository root,
|
||||
* then by path. Two manifests can declare one package name (a repository's
|
||||
* go.mod and a test fixture's copy of it), and which worker parsed which is
|
||||
* thread scheduling. Ordering the candidates here makes the winner a property
|
||||
* of the repository, not of the run. */
|
||||
static int pkgmap_candidate_cmp(const void *lhs, const void *rhs) {
|
||||
const cbm_pkg_entry_t *a = *(const cbm_pkg_entry_t *const *)lhs;
|
||||
const cbm_pkg_entry_t *b = *(const cbm_pkg_entry_t *const *)rhs;
|
||||
int by_name = strcmp(a->pkg_name, b->pkg_name);
|
||||
if (by_name != 0) {
|
||||
return by_name;
|
||||
}
|
||||
int depth_a = pkgmap_entry_depth(a->entry_rel);
|
||||
int depth_b = pkgmap_entry_depth(b->entry_rel);
|
||||
if (depth_a != depth_b) {
|
||||
return depth_a < depth_b ? -SKIP_ONE : SKIP_ONE;
|
||||
}
|
||||
return strcmp(a->entry_rel, b->entry_rel);
|
||||
}
|
||||
|
||||
CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_count,
|
||||
const char *project_name) {
|
||||
/* Count total entries */
|
||||
@@ -1086,39 +1120,50 @@ CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_cou
|
||||
return NULL;
|
||||
}
|
||||
|
||||
CBMHashTable *map = cbm_ht_create(PKGMAP_HT_INIT);
|
||||
int merged = 0;
|
||||
|
||||
const cbm_pkg_entry_t **candidates =
|
||||
cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)total * sizeof(*candidates));
|
||||
if (!candidates) {
|
||||
return NULL;
|
||||
}
|
||||
int candidate_count = 0;
|
||||
for (int w = 0; w < worker_count; w++) {
|
||||
cbm_pkg_entries_t *we = &worker_entries[w];
|
||||
const cbm_pkg_entries_t *we = &worker_entries[w];
|
||||
for (int i = 0; i < we->count; i++) {
|
||||
if (!we->items[i].pkg_name || !we->items[i].entry_rel) {
|
||||
continue; /* package-boundary metadata has no import specifier */
|
||||
}
|
||||
/* Convert entry_rel to QN: project.dir.parts. A PSR-4 namespace
|
||||
* prefix (key ends in '\\') keeps its repo-relative DIRECTORY
|
||||
* instead: its readers map `Prefix\Sub\Class` onto a file path
|
||||
* (<dir>/Sub/Class.php), which a dotted QN cannot express (#1186). */
|
||||
const char *entry_rel = we->items[i].entry_rel;
|
||||
char *qn = pkgmap_is_psr4_prefix(we->items[i].pkg_name)
|
||||
? cbm_strndup(entry_rel, strlen(entry_rel))
|
||||
: cbm_pipeline_fqn_module(project_name, entry_rel);
|
||||
if (!qn) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Check for duplicate — first wins */
|
||||
if (cbm_ht_has(map, we->items[i].pkg_name)) {
|
||||
free(qn);
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Transfer ownership: key = strdup'd pkg_name, value = qn */
|
||||
char *key = strdup(we->items[i].pkg_name);
|
||||
cbm_ht_set(map, key, qn);
|
||||
merged++;
|
||||
candidates[candidate_count++] = &we->items[i];
|
||||
}
|
||||
}
|
||||
qsort(candidates, (size_t)candidate_count, sizeof(*candidates), pkgmap_candidate_cmp);
|
||||
|
||||
CBMHashTable *map = cbm_ht_create(PKGMAP_HT_INIT);
|
||||
int merged = 0;
|
||||
|
||||
for (int i = 0; i < candidate_count; i++) {
|
||||
const cbm_pkg_entry_t *entry = candidates[i];
|
||||
/* Duplicate name: the first in merge order wins. */
|
||||
if (cbm_ht_has(map, entry->pkg_name)) {
|
||||
continue;
|
||||
}
|
||||
/* Convert entry_rel to QN: project.dir.parts. A PSR-4 namespace
|
||||
* prefix (key ends in '\\') keeps its repo-relative DIRECTORY
|
||||
* instead: its readers map `Prefix\Sub\Class` onto a file path
|
||||
* (<dir>/Sub/Class.php), which a dotted QN cannot express (#1186). */
|
||||
const char *entry_rel = entry->entry_rel;
|
||||
char *qn = pkgmap_is_psr4_prefix(entry->pkg_name)
|
||||
? cbm_strndup(entry_rel, strlen(entry_rel))
|
||||
: cbm_pipeline_fqn_module(project_name, entry_rel);
|
||||
if (!qn) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Transfer ownership: key = strdup'd pkg_name, value = qn */
|
||||
char *key = strdup(entry->pkg_name);
|
||||
cbm_ht_set(map, key, qn);
|
||||
merged++;
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, candidates);
|
||||
|
||||
if (merged == 0) {
|
||||
cbm_ht_free(map);
|
||||
|
||||
@@ -51,6 +51,7 @@ enum { CBM_DIR_PERMS = 0755, PL_RING = 4, PL_RING_MASK = 3, PL_SEQ_PASSES = 7 };
|
||||
#define YYJSON_HAS_STDBOOL_H 1
|
||||
#endif
|
||||
#include "yyjson/yyjson.h"
|
||||
#include "foundation/json_writer.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
@@ -1366,7 +1367,7 @@ void cbm_pipeline_record_unresolved_calls(cbm_pipeline_t *p, const char *rel_pat
|
||||
}
|
||||
ok = ok && unresolved_build_carriers(&capture) && unresolved_collect_sites(&capture);
|
||||
if (ok && yyjson_mut_arr_size(capture.sites) > 0) {
|
||||
char *detail = yyjson_mut_write_opts(capture.doc, 0, &allocator, NULL, NULL);
|
||||
char *detail = cbm_json_write_text(capture.doc, &allocator, NULL);
|
||||
char *path = cbm_mem_strdup(CBM_MEM_CLASS_RESOLVE, rel_path);
|
||||
/* The estimate reserves overhead and escaping. Enforce the serialized
|
||||
* limit as well, before any detail is transferred to persistence. */
|
||||
|
||||
@@ -1394,6 +1394,33 @@ TEST(cslsp_global_namespace_types_are_not_partial_twins) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The using-directive walk kept its pending nodes in a fixed 256-entry stack
|
||||
* and skipped every child it had no room for. A file of 300 namespace blocks
|
||||
* left the last block, and the `using static` inside it, unwalked, so the
|
||||
* unqualified `Sqrt` that directive imports bound to nothing. The walk's
|
||||
* pending set grows with the file now. */
|
||||
TEST(cslsp_using_after_many_namespace_blocks) {
|
||||
enum { PAD_BLOCKS = 300 };
|
||||
static char src[16384];
|
||||
size_t len = 0;
|
||||
for (int i = 0; i < PAD_BLOCKS; i++) {
|
||||
int w = snprintf(src + len, sizeof(src) - len, "namespace Pad%d { }\n", i);
|
||||
ASSERT(w > 0 && (size_t)w < sizeof(src) - len);
|
||||
len += (size_t)w;
|
||||
}
|
||||
int w = snprintf(src + len, sizeof(src) - len,
|
||||
"namespace App {\n"
|
||||
" using static System.Math;\n"
|
||||
" class C { public double X() { return Sqrt(2.0); } }\n"
|
||||
"}\n");
|
||||
ASSERT(w > 0 && (size_t)w < sizeof(src) - len);
|
||||
CBMFileResult *r = extract_cs(src);
|
||||
ASSERT(r);
|
||||
ASSERT(require_resolved(r, "C.X", "Math.Sqrt") >= 0);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── Suite ─────────────────────────────────────────────────── */
|
||||
|
||||
SUITE(cs_lsp) {
|
||||
@@ -1461,4 +1488,5 @@ SUITE(cs_lsp) {
|
||||
RUN_TEST(cslsp_cyclic_alias_qualifier_terminates);
|
||||
RUN_TEST(cslsp_global_namespace_types_are_not_partial_twins);
|
||||
RUN_TEST(cslsp_decl_namespace_global_needs_clean_parse);
|
||||
RUN_TEST(cslsp_using_after_many_namespace_blocks);
|
||||
}
|
||||
|
||||
@@ -2474,6 +2474,61 @@ TEST(ei_php_psr4_missing_class_leaves_type_evidence_unknown) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Two manifests can declare the same package name: a repository's own go.mod
|
||||
* and a test fixture's copy of it. Which extraction worker parses which manifest
|
||||
* is thread scheduling, so the package map must not depend on it. The manifest
|
||||
* nearest the repository root wins, and an equal depth is settled by path.
|
||||
* Found on cli/cli, where the fixture won in about one index run in thirty and
|
||||
* the IMPORTS edges fell from 3,869 to 690. */
|
||||
static char *ei_pkgmap_winner(const char *first_worker_manifest,
|
||||
const char *second_worker_manifest) {
|
||||
static const char go_mod[] = "module github.com/acme/tool/v2\n\ngo 1.22\n";
|
||||
cbm_pkg_entries_t workers[2];
|
||||
cbm_pkg_entries_init(&workers[0]);
|
||||
cbm_pkg_entries_init(&workers[1]);
|
||||
bool parsed = cbm_pkgmap_try_parse("go.mod", first_worker_manifest, go_mod, (int)strlen(go_mod),
|
||||
&workers[0]) &&
|
||||
cbm_pkgmap_try_parse("go.mod", second_worker_manifest, go_mod,
|
||||
(int)strlen(go_mod), &workers[1]);
|
||||
CBMHashTable *map = parsed ? cbm_pkgmap_build(workers, 2, "proj") : NULL;
|
||||
const char *qn = map ? (const char *)cbm_ht_get(map, "github.com/acme/tool/v2") : NULL;
|
||||
char *winner = qn ? strdup(qn) : NULL;
|
||||
if (map) {
|
||||
cbm_pkgmap_free(map);
|
||||
}
|
||||
cbm_pkg_entries_free(&workers[0]);
|
||||
cbm_pkg_entries_free(&workers[1]);
|
||||
return winner;
|
||||
}
|
||||
|
||||
TEST(ei_pkgmap_duplicate_package_name_prefers_root_manifest_in_any_worker_order) {
|
||||
char *want = cbm_pipeline_fqn_module("proj", "");
|
||||
char *root_first = ei_pkgmap_winner("go.mod", ".github/codeql/tests/fixture/go.mod");
|
||||
char *fixture_first = ei_pkgmap_winner(".github/codeql/tests/fixture/go.mod", "go.mod");
|
||||
bool root_first_ok = want && root_first && strcmp(root_first, want) == 0;
|
||||
bool fixture_first_ok = want && fixture_first && strcmp(fixture_first, want) == 0;
|
||||
free(want);
|
||||
free(root_first);
|
||||
free(fixture_first);
|
||||
ASSERT_TRUE(root_first_ok);
|
||||
ASSERT_TRUE(fixture_first_ok);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(ei_pkgmap_duplicate_package_name_at_equal_depth_is_settled_by_path) {
|
||||
char *want = cbm_pipeline_fqn_module("proj", "examples/alpha");
|
||||
char *alpha_first = ei_pkgmap_winner("examples/alpha/go.mod", "examples/beta/go.mod");
|
||||
char *beta_first = ei_pkgmap_winner("examples/beta/go.mod", "examples/alpha/go.mod");
|
||||
bool alpha_first_ok = want && alpha_first && strcmp(alpha_first, want) == 0;
|
||||
bool beta_first_ok = want && beta_first && strcmp(beta_first, want) == 0;
|
||||
free(want);
|
||||
free(alpha_first);
|
||||
free(beta_first);
|
||||
ASSERT_TRUE(alpha_first_ok);
|
||||
ASSERT_TRUE(beta_first_ok);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* SUITE registration
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
@@ -2581,4 +2636,6 @@ SUITE(edge_imports) {
|
||||
RUN_TEST(ei_php_binding_snapshot_requires_current_complete_evidence);
|
||||
RUN_TEST(ei_php_binding_snapshot_groups_kinds_and_invalidates_failed_rebuild);
|
||||
RUN_TEST(ei_php_psr4_missing_class_leaves_type_evidence_unknown);
|
||||
RUN_TEST(ei_pkgmap_duplicate_package_name_prefers_root_manifest_in_any_worker_order);
|
||||
RUN_TEST(ei_pkgmap_duplicate_package_name_at_equal_depth_is_settled_by_path);
|
||||
}
|
||||
|
||||
@@ -198,6 +198,38 @@ TEST(gbuf_insert_edge) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API
|
||||
TEST(gbuf_edge_append_oom_is_not_success) {
|
||||
cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");
|
||||
ASSERT_NOT_NULL(gb);
|
||||
int64_t source = cbm_gbuf_upsert_node(gb, "Function", "a", "pkg.a", "f.go", 1, 5, "{}");
|
||||
int64_t target = cbm_gbuf_upsert_node(gb, "Function", "b", "pkg.b", "f.go", 6, 10, "{}");
|
||||
ASSERT_GT(source, 0);
|
||||
ASSERT_GT(target, 0);
|
||||
ASSERT_EQ(cbm_gbuf_edge_count(gb), 0);
|
||||
|
||||
/* A fresh graph has no edge-array storage. Its first edge insertion must
|
||||
* grow that primary array before registering any secondary edge indexes. */
|
||||
cbm_mem_test_fail_next_realloc(CBM_MEM_CLASS_DYN_ARRAY);
|
||||
int64_t failed = cbm_gbuf_insert_edge(gb, source, target, "CALLS", "{}");
|
||||
bool injected = cbm_mem_test_reset_realloc_failure();
|
||||
int after_failure = cbm_gbuf_edge_count(gb);
|
||||
|
||||
/* A failed append must not leave a dedup entry that makes retry appear to
|
||||
* succeed while the array used by dump still contains no edge. */
|
||||
int64_t retry = cbm_gbuf_insert_edge(gb, source, target, "CALLS", "{}");
|
||||
int after_retry = cbm_gbuf_edge_count(gb);
|
||||
cbm_gbuf_free(gb);
|
||||
|
||||
ASSERT(injected);
|
||||
ASSERT_EQ(failed, 0);
|
||||
ASSERT_EQ(after_failure, 0);
|
||||
ASSERT_GT(retry, 0);
|
||||
ASSERT_EQ(after_retry, 1);
|
||||
PASS();
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(gbuf_edge_dedup) {
|
||||
cbm_gbuf_t *gb = cbm_gbuf_new("test", "/tmp");
|
||||
int64_t n1 = cbm_gbuf_upsert_node(gb, "Function", "a", "pkg.a", "f.go", 1, 5, "{}");
|
||||
@@ -1486,6 +1518,9 @@ SUITE(graph_buffer) {
|
||||
RUN_TEST(gbuf_find_by_name);
|
||||
RUN_TEST(gbuf_delete_by_label);
|
||||
RUN_TEST(gbuf_insert_edge);
|
||||
#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API
|
||||
RUN_TEST(gbuf_edge_append_oom_is_not_success);
|
||||
#endif
|
||||
RUN_TEST(gbuf_edge_dedup);
|
||||
RUN_TEST(gbuf_imports_multi_symbol_dedup);
|
||||
RUN_TEST(gbuf_imports_long_local_name_no_collision);
|
||||
|
||||
@@ -2344,6 +2344,103 @@ TEST(sqlite_alter_table_drop_index_still_flagged_issue2246) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── jsonnet: the external scanner's state belongs to one parser ─────────────
|
||||
* Upstream's jsonnet scanner kept its state (inside a string? which quote?) in
|
||||
* process globals, so every worker's parser shared it: on go/grafana__loki a
|
||||
* different set of jsonnet files came back parse_partial on every index, with
|
||||
* their definitions and edges, and none does when parsed one at a time. The
|
||||
* local patch moves the state into the per-parser payload and resets it on
|
||||
* every deserialize (grammars/MANIFEST.md, "Local source patches").
|
||||
*
|
||||
* No threads here: the input callback hands parser A one byte per call, and
|
||||
* when A first reads the byte after its opening quote -- A's scanner is then
|
||||
* inside scan_string_start -- the callback runs a complete parse of `)'` on
|
||||
* parser B. That parse ends on a string end, which clears B's state; with
|
||||
* shared globals it cleared A's too, mid-scan, and A's string broke. The
|
||||
* second test pins the other half: a parse that ends inside a string must not
|
||||
* leave that state to the next parse. */
|
||||
extern const TSLanguage *tree_sitter_jsonnet(void);
|
||||
|
||||
typedef struct {
|
||||
const char *src;
|
||||
uint32_t len;
|
||||
uint32_t trigger; /* byte at which parser B runs */
|
||||
bool fired;
|
||||
TSParser *other;
|
||||
} jsonnet_interleave_t;
|
||||
|
||||
static const char *jsonnet_read_one_byte(void *payload, uint32_t byte_index, TSPoint position,
|
||||
uint32_t *bytes_read) {
|
||||
(void)position;
|
||||
jsonnet_interleave_t *x = (jsonnet_interleave_t *)payload;
|
||||
if (byte_index >= x->len) {
|
||||
*bytes_read = 0;
|
||||
return "";
|
||||
}
|
||||
if (!x->fired && byte_index == x->trigger) {
|
||||
static const char resets_on_string_end[] = ")'\n";
|
||||
x->fired = true;
|
||||
TSTree *other = ts_parser_parse_string(x->other, NULL, resets_on_string_end,
|
||||
(uint32_t)strlen(resets_on_string_end));
|
||||
ts_tree_delete(other);
|
||||
}
|
||||
*bytes_read = 1;
|
||||
return x->src + byte_index;
|
||||
}
|
||||
|
||||
TEST(jsonnet_scanner_state_is_per_parser) {
|
||||
static const char src[] = "{\n name: 'query-scheduler-discovery',\n port: 9095,\n}\n";
|
||||
TSParser *a = ts_parser_new();
|
||||
TSParser *b = ts_parser_new();
|
||||
ASSERT_NOT_NULL(a);
|
||||
ASSERT_NOT_NULL(b);
|
||||
ASSERT_TRUE(ts_parser_set_language(a, tree_sitter_jsonnet()));
|
||||
ASSERT_TRUE(ts_parser_set_language(b, tree_sitter_jsonnet()));
|
||||
|
||||
/* Control: on its own the source parses clean. */
|
||||
TSTree *alone = ts_parser_parse_string(a, NULL, src, (uint32_t)strlen(src));
|
||||
ASSERT_NOT_NULL(alone);
|
||||
ASSERT_FALSE(ts_node_has_error(ts_tree_root_node(alone)));
|
||||
ts_tree_delete(alone);
|
||||
|
||||
jsonnet_interleave_t x = {src, (uint32_t)strlen(src), 0, false, b};
|
||||
x.trigger = (uint32_t)(strchr(src, '\'') - src) + 1;
|
||||
TSInput input = {&x, jsonnet_read_one_byte, TSInputEncodingUTF8, NULL};
|
||||
TSTree *tree = ts_parser_parse(a, NULL, input);
|
||||
ASSERT_NOT_NULL(tree);
|
||||
ASSERT_TRUE(x.fired); /* B really ran inside A's string */
|
||||
/* has_error covers ERROR and MISSING nodes alike. */
|
||||
ASSERT_FALSE(ts_node_has_error(ts_tree_root_node(tree)));
|
||||
ts_tree_delete(tree);
|
||||
ts_parser_delete(b);
|
||||
ts_parser_delete(a);
|
||||
PASS();
|
||||
}
|
||||
|
||||
TEST(jsonnet_scanner_state_not_carried_between_parses) {
|
||||
static const char unterminated[] = "local s = 'unterminated\n";
|
||||
static const char text_block[] = "local doc = |||\n a text block\n|||;\ndoc\n";
|
||||
TSParser *parser = ts_parser_new();
|
||||
ASSERT_NOT_NULL(parser);
|
||||
ASSERT_TRUE(ts_parser_set_language(parser, tree_sitter_jsonnet()));
|
||||
|
||||
/* A parse that ends inside a string... */
|
||||
TSTree *first =
|
||||
ts_parser_parse_string(parser, NULL, unterminated, (uint32_t)strlen(unterminated));
|
||||
ASSERT_NOT_NULL(first);
|
||||
ASSERT_TRUE(ts_node_has_error(ts_tree_root_node(first)));
|
||||
ts_tree_delete(first);
|
||||
|
||||
/* ...must not decide how the next file lexes: ||| blocks are lexed only by
|
||||
* the external scanner, which a carried-over "inside a string" disabled. */
|
||||
TSTree *next = ts_parser_parse_string(parser, NULL, text_block, (uint32_t)strlen(text_block));
|
||||
ASSERT_NOT_NULL(next);
|
||||
ASSERT_FALSE(ts_node_has_error(ts_tree_root_node(next)));
|
||||
ts_tree_delete(next);
|
||||
ts_parser_delete(parser);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(parse_coverage) {
|
||||
RUN_TEST(source_line_count_one_convention);
|
||||
RUN_TEST(c_ifdef_split_brace_sets_parse_incomplete);
|
||||
@@ -2418,4 +2515,8 @@ SUITE(parse_coverage) {
|
||||
RUN_TEST(sqlite_trigger_when_body_and_fts5_not_flagged_issue2246);
|
||||
RUN_TEST(sqlite_pragma_forms_not_flagged_issue2246);
|
||||
RUN_TEST(sqlite_alter_table_drop_index_still_flagged_issue2246);
|
||||
/* Per-parser first: on the unpatched scanner, the carried-over state the
|
||||
* second test leaves behind would hide the first one's defect. */
|
||||
RUN_TEST(jsonnet_scanner_state_is_per_parser);
|
||||
RUN_TEST(jsonnet_scanner_state_not_carried_between_parses);
|
||||
}
|
||||
|
||||
@@ -9183,6 +9183,125 @@ TEST(pipeline_capture_failure_preserves_general_coverage_and_rebuilds) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The latin-1 'é' of the fixtures below, as the strict JSON reader returns it. */
|
||||
#define NON_UTF8_REPLACED "caf\xef\xbf\xbd"
|
||||
|
||||
/* True when some string in value, at any depth, contains needle. */
|
||||
static bool non_utf8_json_has(yyjson_val *value, const char *needle) {
|
||||
const char *text = yyjson_get_str(value);
|
||||
if (text) {
|
||||
return strstr(text, needle) != NULL;
|
||||
}
|
||||
size_t index, count;
|
||||
yyjson_val *key, *item;
|
||||
if (yyjson_is_arr(value)) {
|
||||
yyjson_arr_foreach(value, index, count, item) {
|
||||
if (non_utf8_json_has(item, needle)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (yyjson_is_obj(value)) {
|
||||
yyjson_obj_foreach(value, index, count, key, item) {
|
||||
if (non_utf8_json_has(item, needle)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* -1: absent or not strict JSON; 0: strict without the replaced text; 1: with it. */
|
||||
static int non_utf8_json_state(const char *json) {
|
||||
yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
|
||||
if (!doc) {
|
||||
return -1;
|
||||
}
|
||||
int found = non_utf8_json_has(yyjson_doc_get_root(doc), NON_UTF8_REPLACED) ? 1 : 0;
|
||||
yyjson_doc_free(doc);
|
||||
return found;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int surface_rows;
|
||||
int surface_state[3]; /* a.ts, b.ts, c.py */
|
||||
bool unresolved_complete;
|
||||
int unresolved_state; /* b.ts's unresolved_calls detail */
|
||||
} non_utf8_outcome_t;
|
||||
|
||||
static void non_utf8_read_outcome(cbm_store_t *store, const char *project,
|
||||
non_utf8_outcome_t *out) {
|
||||
static const char *paths[] = {"a.ts", "b.ts", "c.py"};
|
||||
cbm_lsp_surface_row_t *surfaces = NULL;
|
||||
if (cbm_store_get_lsp_surfaces(store, project, &surfaces, &out->surface_rows) != CBM_STORE_OK) {
|
||||
out->surface_rows = -1;
|
||||
}
|
||||
for (int i = 0; i < out->surface_rows; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
if (strcmp(surfaces[i].rel_path, paths[j]) == 0) {
|
||||
out->surface_state[j] = non_utf8_json_state(surfaces[i].defs_json);
|
||||
}
|
||||
}
|
||||
}
|
||||
cbm_store_free_lsp_surfaces(surfaces, out->surface_rows);
|
||||
cbm_coverage_meta_t meta = {0};
|
||||
out->unresolved_complete = cbm_store_coverage_meta_get(store, project, &meta) == CBM_STORE_OK &&
|
||||
meta.unresolved_calls_complete;
|
||||
cbm_store_coverage_meta_clear(&meta);
|
||||
cbm_coverage_row_t *rows = NULL;
|
||||
int row_count = 0;
|
||||
if (cbm_store_coverage_get_path(store, project, "b.ts", &rows, &row_count) == CBM_STORE_OK) {
|
||||
for (int i = 0; i < row_count; i++) {
|
||||
if (strcmp(rows[i].kind, "unresolved_calls") == 0) {
|
||||
out->unresolved_state = non_utf8_json_state(rows[i].detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
cbm_store_free_coverage(rows, row_count);
|
||||
}
|
||||
|
||||
/* Source text is not always UTF-8. A latin-1 'é' that names a TS method reaches
|
||||
* both that file's LSP surface and the caller of its unresolved call; one in a
|
||||
* Python __all__ string reaches the namespace surface. The strict writer refused
|
||||
* each document, which cost the repository every surface row and switched off
|
||||
* unresolved-call capture for the run. Each is now strict JSON with U+FFFD. */
|
||||
TEST(pipeline_non_utf8_source_keeps_surfaces_and_unresolved_capture) {
|
||||
char tmp[256] = "/tmp/cbm_non_utf8_XXXXXX";
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
write_temp_file(tmp, "a.ts", "export function ok(): number { return 1; }\n");
|
||||
write_temp_file(tmp, "b.ts", "class A {\n \"caf\xe9\"(): void { missing(); }\n}\n");
|
||||
write_temp_file(tmp, "c.py", "__all__ = ['caf\xe9']\n");
|
||||
char db_path[512];
|
||||
snprintf(db_path, sizeof(db_path), "%s/non_utf8.db", tmp);
|
||||
cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
|
||||
ASSERT_NOT_NULL(p);
|
||||
int rc = cbm_pipeline_run(p);
|
||||
char project[256];
|
||||
snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(p));
|
||||
cbm_pipeline_free(p);
|
||||
non_utf8_outcome_t outcome = {.surface_state = {-1, -1, -1}, .unresolved_state = -1};
|
||||
cbm_store_t *store = rc == 0 ? cbm_store_open_path(db_path) : NULL;
|
||||
if (store) {
|
||||
non_utf8_read_outcome(store, project, &outcome);
|
||||
cbm_store_close(store);
|
||||
}
|
||||
th_rmtree(tmp);
|
||||
if (outcome.surface_rows != 3 || !outcome.unresolved_complete) {
|
||||
fprintf(stderr, " [non-utf8] rc=%d surfaces=%d states=%d,%d,%d complete=%d detail=%d\n",
|
||||
rc, outcome.surface_rows, outcome.surface_state[0], outcome.surface_state[1],
|
||||
outcome.surface_state[2], outcome.unresolved_complete, outcome.unresolved_state);
|
||||
}
|
||||
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(outcome.surface_rows, 3);
|
||||
ASSERT_EQ(outcome.surface_state[0], 0);
|
||||
ASSERT_EQ(outcome.surface_state[1], 1);
|
||||
ASSERT_EQ(outcome.surface_state[2], 1);
|
||||
ASSERT_TRUE(outcome.unresolved_complete);
|
||||
ASSERT_EQ(outcome.unresolved_state, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Metadata participates in exact-input compatibility. Old coverage schema or
|
||||
* an upgrade to a more comprehensive discovery/index mode must force a
|
||||
* complete replacement even when every semantic-input byte is unchanged; the
|
||||
@@ -35295,6 +35414,7 @@ SUITE(pipeline_semantic_manifest_repro) {
|
||||
RUN_TEST(pipeline_semantic_version_8_index_is_rebuilt_once);
|
||||
RUN_TEST(pipeline_semantic_version_10_index_is_rebuilt_once);
|
||||
RUN_TEST(pipeline_capture_failure_preserves_general_coverage_and_rebuilds);
|
||||
RUN_TEST(pipeline_non_utf8_source_keeps_surfaces_and_unresolved_capture);
|
||||
RUN_TEST(pipeline_existing_artifact_refreshes_after_default_forced_full_reindex);
|
||||
RUN_TEST(pipeline_full_cancel_after_predump_preserves_previous_generation);
|
||||
RUN_TEST(pipeline_full_cancel_after_destination_prepare_preserves_previous_generation);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
*/
|
||||
#include "test_framework.h"
|
||||
#include "../src/foundation/str_util.h"
|
||||
#include "foundation/json_writer.h"
|
||||
#include <math.h>
|
||||
|
||||
static CBMArena a;
|
||||
|
||||
@@ -504,7 +506,54 @@ TEST(snprintf_append_multiple_sequential) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A valid document keeps the strict writer's exact bytes. One the strict writer
|
||||
* refuses over bytes that are not UTF-8 is still strict JSON, each such byte an
|
||||
* escaped U+FFFD. Any other refusal stays a refusal. */
|
||||
TEST(json_write_text_keeps_valid_documents_and_repairs_refused_ones) {
|
||||
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
|
||||
yyjson_mut_val *root = yyjson_mut_obj(doc);
|
||||
yyjson_mut_doc_set_root(doc, root);
|
||||
ASSERT(yyjson_mut_obj_add_strcpy(doc, root, "plain", "caf\xc3\xa9"));
|
||||
size_t length = 0;
|
||||
char *json = cbm_json_write_text(doc, cbm_json_writer_allocator(), &length);
|
||||
ASSERT_STR_EQ(json, "{\"plain\":\"caf\xc3\xa9\"}");
|
||||
ASSERT_EQ((int)length, (int)strlen(json));
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, json);
|
||||
|
||||
yyjson_mut_val *list = yyjson_mut_arr(doc);
|
||||
ASSERT(yyjson_mut_obj_add_val(doc, root, "list", list));
|
||||
ASSERT(yyjson_mut_arr_add_strcpy(doc, list, "x\xe9"));
|
||||
ASSERT(yyjson_mut_obj_add_strcpy(doc, root, "k\xe9y", "\xe2\x82"));
|
||||
ASSERT(yyjson_mut_write(doc, 0, NULL) == NULL);
|
||||
json = cbm_json_write_text(doc, cbm_json_writer_allocator(), &length);
|
||||
ASSERT_STR_EQ(json, "{\"plain\":\"caf\\u00E9\",\"list\":[\"x\\uFFFD\"],"
|
||||
"\"k\\uFFFDy\":\"\\uFFFD\\uFFFD\"}");
|
||||
ASSERT_EQ((int)length, (int)strlen(json));
|
||||
yyjson_doc *strict = yyjson_read(json, length, 0);
|
||||
ASSERT_NOT_NULL(strict);
|
||||
yyjson_val *back = yyjson_doc_get_root(strict);
|
||||
ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(back, "plain")), "caf\xc3\xa9");
|
||||
ASSERT_STR_EQ(yyjson_get_str(yyjson_arr_get(yyjson_obj_get(back, "list"), 0)), "x\xef\xbf\xbd");
|
||||
ASSERT_STR_EQ(yyjson_get_str(yyjson_obj_get(back, "k\xef\xbf\xbdy")),
|
||||
"\xef\xbf\xbd\xef\xbf\xbd");
|
||||
yyjson_doc_free(strict);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, json);
|
||||
yyjson_mut_doc_free(doc);
|
||||
|
||||
yyjson_mut_doc *not_finite = yyjson_mut_doc_new(NULL);
|
||||
yyjson_mut_val *not_finite_root = yyjson_mut_obj(not_finite);
|
||||
yyjson_mut_doc_set_root(not_finite, not_finite_root);
|
||||
ASSERT(yyjson_mut_obj_add_real(not_finite, not_finite_root, "n", NAN));
|
||||
ASSERT(cbm_json_write_text(not_finite, NULL, NULL) == NULL);
|
||||
yyjson_mut_doc_free(not_finite);
|
||||
yyjson_mut_doc *empty = yyjson_mut_doc_new(NULL);
|
||||
ASSERT(cbm_json_write_text(empty, NULL, NULL) == NULL);
|
||||
yyjson_mut_doc_free(empty);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(str_util) {
|
||||
RUN_TEST(json_write_text_keeps_valid_documents_and_repairs_refused_ones);
|
||||
RUN_TEST(path_join_basic);
|
||||
RUN_TEST(path_join_trailing_slash);
|
||||
RUN_TEST(path_join_leading_slash);
|
||||
|
||||
Reference in New Issue
Block a user