Merge branch 'main' into fix/skip-binary-preserve-target

This commit is contained in:
BowenX
2026-11-26 18:10:01 -08:00
committed by GitHub
106 changed files with 2451405 additions and 1856561 deletions
+8 -4
View File
@@ -578,7 +578,9 @@ PIPELINE_SRCS = \
src/pipeline/artifact.c \
src/pipeline/pass_ensemble_routing.c \
src/pipeline/pass_pkgmap.c \
src/pipeline/site_bind.c
src/pipeline/site_bind.c \
src/pipeline/include_path.c \
src/pipeline/scope_closure.c
# SimHash / MinHash module
SIMHASH_SRCS = src/simhash/minhash.c
@@ -874,7 +876,7 @@ TEST_DISCOVER_SRCS = \
TEST_GRAPH_BUFFER_SRCS = tests/test_graph_buffer.c
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c tests/test_site_bind.c tests/test_scope_facts.c
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c tests/test_site_bind.c tests/test_scope_facts.c tests/test_include_path.c tests/test_scope_closure.c
TEST_WATCHER_SRCS = tests/test_watcher.c tests/test_svn_state.c
@@ -1118,10 +1120,12 @@ MIMALLOC_OBJ_TEST = $(BUILD_DIR)/mimalloc.o
MIMALLOC_OBJ_TSAN = $(BUILD_DIR)/tsan_mimalloc.o
MIMALLOC_OBJ_PROD = $(BUILD_DIR)/prod_mimalloc.o
$(BUILD_DIR)/mimalloc.o: $(MIMALLOC_SRC) | $(BUILD_DIR)
$(BUILD_DIR)/mimalloc.o: $(MIMALLOC_SRC) $(wildcard vendored/mimalloc/src/*.c) \
$(wildcard vendored/mimalloc/include/*.h) Makefile.cbm | $(BUILD_DIR)
$(CC) $(MIMALLOC_CFLAGS_TEST) -c -o $@ $<
$(BUILD_DIR)/tsan_mimalloc.o: $(MIMALLOC_SRC) | $(BUILD_DIR)
$(BUILD_DIR)/tsan_mimalloc.o: $(MIMALLOC_SRC) $(wildcard vendored/mimalloc/src/*.c) \
$(wildcard vendored/mimalloc/include/*.h) Makefile.cbm | $(BUILD_DIR)
$(CC) $(MIMALLOC_CFLAGS_TEST) $(TSAN_SANITIZE) -c -o $@ $<
# static.c is an AMALGAMATION: it #includes options.c and friends, none of which
+2 -1
View File
@@ -315,11 +315,12 @@ The install script placed beside the binary is **reported, not deleted**: uninst
- **Change impact**: `detect_changes` maps uncommitted changes to affected symbols with risk classification and can report test impact with `scope: "tests"`; `compare_graphs` compares indexed snapshots
- **Runtime observations**: `ingest_traces` adds observed call relationships from separately collected traces alongside static analysis; static call paths alone do not show what ran
- **Call graph**: Resolves function calls across files and packages (import-aware, type-inferred)
- **Dead code candidates**: find functions with no indexed callers, excluding entry points. Check dynamic dispatch, coverage gaps, and framework conventions before removing code.
- **Dead code candidates**: use `query_graph` with `MATCH (f:Function) WHERE NOT EXISTS { (f)<-[:CALLS]-() } RETURN f.name, f.file_path` to find functions with no indexed `CALLS` callers (repeat for `Method` as needed). Check entry points, callbacks, dynamic dispatch, coverage gaps, and framework conventions before removing code. `search_graph(max_degree=0, exclude_entry_points=true)` finds isolated symbols instead: its degree includes both incoming and outgoing calls, references, and type relationships, so it omits uncalled functions that call other code.
- **Cypher-like queries**: `MATCH (f:Function)-[:CALLS]->(g) WHERE f.name = 'main' RETURN g.name`
### Search
- **Semantic search** (the `semantic_query` parameter of `search_graph`, not a separate tool): vector search across the entire graph, powered by bundled Nomic `nomic-embed-code` embeddings (40K tokens, 768d int8) compiled into the binary; no API key, no Ollama, no Docker. 11-signal combined scoring (TF-IDF, RRI, API/Type/Decorator signatures, AST profiles, data flow, Halstead-lite, MinHash, module proximity, graph diffusion).
Supply individual keywords, e.g. `semantic_query: ["handle", "scan"]`, rather than natural-language sentences. Each array element is looked up as one token; results use the minimum cosine across tokens. Unknown tokens fall back to deterministic sparse-random vectors and can suppress useful matches. For BM25 text search use `query`; a non-empty `semantic_query` cannot be combined with it in the same request. An empty `semantic_query` array is ignored.
- **BM25 full-text search** via SQLite FTS5 with `cbm_camel_split` tokenizer (camelCase / snake_case aware)
- **Structural search** (`search_graph`): regex name patterns, label filters, min/max degree, file scoping
- **Code search** (`search_code`): graph-augmented grep over indexed files only
+2 -2
View File
@@ -168,8 +168,8 @@ License summary:
- **License:** MIT
- **Copyright:** (c) 2025 InterSystems Corporation
- **Vendored at:** `internal/cbm/vendored/grammars/objectscript_udl/`, `internal/cbm/vendored/grammars/objectscript_routine/`
- **Pinned commit:** `a7ffcdf`
- **Notes:** InterSystems-maintained grammar for the ObjectScript language (InterSystems IRIS / Caché). Vendor-maintained; not in nvim-treesitter or Helix registries. Each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` copied from upstream `common/scanner.h`; two loop counters in that copy are widened from `uint8_t` to `int` as documented in `internal/cbm/vendored/grammars/MANIFEST.md`.
- **Pinned commit:** `25cf0f67a380` (tag `v1.11.0`; refreshed from `a7ffcdf` on 2026-11-13)
- **Notes:** InterSystems-maintained grammar for the ObjectScript language (InterSystems IRIS / Caché). Vendor-maintained; not in nvim-treesitter or Helix registries. Each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` copied from upstream `common/scanner.h`; two loop counters in that copy are widened from `uint8_t` to `int`, and each `scanner.c` guards its deserialize `memcpy` against an empty state, as documented in `internal/cbm/vendored/grammars/MANIFEST.md`.
## Vendored C/C++ Libraries
+47 -1
View File
@@ -3898,6 +3898,43 @@ static void record_included_files(CBMArena *a, CBMFileResult *result,
result->included_files = list;
}
static int test_span_order(const void *left, const void *right) {
const CBMTestSpan *a = left;
const CBMTestSpan *b = right;
if (a->start_line != b->start_line) {
return a->start_line < b->start_line ? -1 : 1;
}
if (a->end_line != b->end_line) {
return a->end_line < b->end_line ? -1 : 1;
}
return strcmp(a->qualified_name, b->qualified_name);
}
/* The raw view's GoogleTest definitions (recorded by the def walk), sorted, the
* preprocessor's line map, and the index of the preprocessed view's top-level
* definitions that map onto them, for that view of the same file. NULL when
* the raw view named no test or the map is missing. */
static const CBMTestSpanMap *pp_test_span_map(CBMTestSpanMap *map, CBMExtractCtx *raw,
const CBMPreprocessedSource *pp, TSNode pp_root) {
if (raw->test_span_count <= 0 || !pp->original_line_by_expanded_line ||
!pp->belongs_to_main_file) {
return NULL;
}
qsort(raw->test_spans, (size_t)raw->test_span_count, sizeof(CBMTestSpan), test_span_order);
#ifdef CBM_ENABLE_TEST_SEAMS
cbm_test_span_test_count((uint64_t)raw->test_span_count);
#endif
*map = (CBMTestSpanMap){raw->test_spans,
raw->test_span_count,
pp->original_line_by_expanded_line,
pp->belongs_to_main_file,
pp->expanded_line_count,
NULL,
0};
cbm_test_span_index_view(map, raw->scratch ? raw->scratch : raw->arena, pp_root);
return map;
}
static CBMFileResult *extract_file_ex_body(
const char *source, int source_len, CBMLanguage language, const char *project,
const char *rel_path, int64_t timeout_micros, const char **extra_defines,
@@ -3916,6 +3953,7 @@ static CBMFileResult *extract_file_ex_body(
language == CBM_LANG_PYTHON ? CBM_PY_NS_NOT_CAPTURED : CBM_PY_NS_NOT_APPLICABLE;
cbm_work_arena_take(&result->arena);
CBMArena *a = &result->arena;
result->cpp_test_macro_names = cbm_cpp_test_macro_names_on(language, test_declarations);
if (!cbm_test_declarations_validate(result, test_declarations)) {
return result;
}
@@ -4330,6 +4368,12 @@ static CBMFileResult *extract_file_ex_body(
TSNode pp_root = ts_tree_root_node(pp_tree);
// Build context for expanded source — extract only calls via unified extractor
/* The raw view's GoogleTest definitions, so that this
* view names their bodies the same way however the
* expanded head reads (cbm_test_span_owner_qn). */
CBMTestSpanMap pp_map;
const CBMTestSpanMap *pp_spans =
pp_test_span_map(&pp_map, &ctx, preprocessed, pp_root);
CBMExtractCtx pp_ctx = {
.arena = a,
.scratch = scratch,
@@ -4345,6 +4389,7 @@ static CBMFileResult *extract_file_ex_body(
* cannot acquire a raw configured definition identity. */
.test_declarations = test_declarations,
.test_declarations_raw_source = false,
.pp_test_spans = pp_spans,
};
// Re-run unified extraction on expanded source.
// This adds macro-expanded calls; duplicates with original calls are
@@ -4366,7 +4411,8 @@ static CBMFileResult *extract_file_ex_body(
// block). Runs in every mode.
if (!result->lsp_skipped) {
cbm_run_c_lsp(a, result, expanded, expanded_len, pp_root,
language != CBM_LANG_C, CBM_SOURCE_ORIGIN_PREPROCESSED);
language != CBM_LANG_C, CBM_SOURCE_ORIGIN_PREPROCESSED,
pp_spans);
}
/* All C-LSP emitters stamp origin directly so rewrite-time
+111 -3
View File
@@ -288,6 +288,14 @@ typedef struct {
* every other definition, and in every language outside
* cbm_is_c_preprocessor_lang. */
const char *variants;
/* Ruby only: a `def self.m` / `class << self` method, which lives on the
* singleton side of its class. False for every instance method and every
* other language. */
bool is_singleton;
/* Ruby only, on a class/module def: the `include`/`prepend`/`extend`
* macros of its body as "|"-separated "<k>:<Const>" pairs, k one of i, p,
* e, in source order ("i:Auditable|e:Finders"). NULL when none. */
const char *mixin_refs;
/* Callable identity (#2061): offset of the signature suffix inside
* qualified_name (base QN = the first qn_sig_off bytes); 0 = no suffix.
* Always 0 until a language enables its callable_identity mode. */
@@ -782,6 +790,10 @@ enum {
CBM_SCOPE_REEXPORT = 1u << 4, /* INCLUDE: its names reach this file's includers */
/* inside a parse error: may or may not hold where a later name is used */
CBM_SCOPE_CONDITIONAL = 1u << 5,
/* QREF: on the way out, the first component names a symbol that is no
* type (Protobuf: a method of the enclosing service, a service of the
* file): protoc resolves the reference to it and rejects the file */
CBM_SCOPE_NOT_A_TYPE = 1u << 6,
};
typedef struct {
@@ -789,7 +801,10 @@ typedef struct {
/* DEF: the full name where the row has packages or nesting (Protobuf:
* package, enclosing messages, name: "a.b.Outer.Inner"). INCLUDE: the
* importing file's package ("" when none), which its references are
* relative to. NULL elsewhere. */
* relative to. QREF: the innermost scope around the reference, its first
* scope to search (Protobuf: the enclosing message's full name, or the
* file's package outside any message); NULL when it is unknown. NULL
* elsewhere. */
const char *qual;
uint32_t pos; /* byte offset after which the event is in effect */
int32_t index; /* into defs (DEF) or imports (INCLUDE); QREF: start byte; else -1 */
@@ -884,7 +899,13 @@ typedef struct {
* kind / group / name / ns; `path` is
* the patch file (as written, relative to the kustomization), NULL for an
* inline patch. kind and name both NULL: the patch file's documents name
* them. def_index -1: the kustomization itself is the source. */
* them. def_index -1: the kustomization itself is the source.
* CBM_K8S_FACT_FILE: a kustomization reads the file `path` (as written,
* relative to the kustomization) at `line`, named by `via`: an entry of a
* configMapGenerator's or secretGenerator's `files` (the path after
* `key=`), `envs` or `env`, or of `configurations`. The file is input to
* the build, not a member of it. def_index -1: the kustomization itself
* is the source. */
typedef enum {
CBM_K8S_FACT_REF = 0,
CBM_K8S_FACT_CRD,
@@ -893,7 +914,8 @@ typedef enum {
CBM_K8S_FACT_SOURCE,
CBM_K8S_FACT_IMAGE,
CBM_K8S_FACT_ENV,
CBM_K8S_FACT_PATCH
CBM_K8S_FACT_PATCH,
CBM_K8S_FACT_FILE
} CBMK8sFactKind;
typedef struct {
CBMK8sFactKind fact;
@@ -1105,6 +1127,10 @@ typedef struct CBMFileResult {
int test_owner_source_len;
CBMLanguage test_owner_language;
char test_owner_source_sha256[65]; /* exact raw source; identity, not authentication */
/* The def walk named this file's GoogleTest macro heads TEST_Suite_Case
* (cbm_cpp_test_macro_names_on): the C/C++ engine, per file and across
* files, names the callers in those bodies the same way. */
bool cpp_test_macro_names;
/* Doc-comment references of this file's definitions (doclink.h), and the
* file's doc-link scope: a language-tagged text blob with what OTHER
@@ -1150,6 +1176,40 @@ typedef struct {
// Forward declaration: ObjectScript macro table (defined in macro_table.h).
typedef struct CBMMacroTable CBMMacroTable;
/* The raw line span of a GoogleTest definition the def walk named with
* cbm_cpp_test_macro_name, and its qualified name. */
typedef struct {
uint32_t start_line;
uint32_t end_line;
const char *qualified_name;
} CBMTestSpan;
/* A top-level function definition of the preprocessed view (directly in the
* translation unit or in a namespace body) by its bytes in that view, and the
* raw test span its first and last lines map onto; span -1 when another
* top-level definition of the view maps onto the same span. */
typedef struct {
uint32_t start_byte;
uint32_t end_byte;
int span;
} CBMTestViewDef;
/* What the preprocessed second view of a C/C++ file needs to name a test body
* as the raw view did: the raw test definitions sorted by (start_line,
* end_line), the preprocessor's 1-based map from expanded lines to raw lines
* (0 = no raw line) with the lines that belong to the file itself, and the
* view's top-level definitions that map onto a raw test span, in document
* order (cbm_test_span_index_view). */
typedef struct {
const CBMTestSpan *spans;
int count;
const uint32_t *raw_line_by_line;
const uint8_t *in_main_file;
int line_count;
const CBMTestViewDef *view_defs;
int view_def_count;
} CBMTestSpanMap;
// Method-return-type table for ObjectScript variable type inference. Populated
// from definition nodes (method QN -> declared return type) so a later
// `Set x = obj.Method()` can resolve x's class.
@@ -1237,6 +1297,14 @@ typedef struct {
/* Go: what each block's statements bind (extract_calls.c), NULL until a route call asks;
* allocated in `scratch`. */
void *go_block_bindings;
/* C++/CUDA raw view: the GoogleTest definitions the def walk named
* (CBMTestSpan, in `scratch`), in walk order. */
CBMTestSpan *test_spans;
int test_span_count;
int test_span_cap;
/* The preprocessed second view only: the raw view's test definitions and
* the line map (cbm_test_span_owner_qn). NULL in every raw view. */
const CBMTestSpanMap *pp_test_spans;
} CBMExtractCtx;
/* Internal configured-definition seams. No declarations pointer enters a result. */
@@ -1261,6 +1329,46 @@ bool cbm_test_definition_owners_match(const CBMFileResult *owners, const char *s
int source_len, bool cpp_mode, const char *module_qn);
const char *cbm_test_definition_owner_qn(const CBMFileResult *owners, TSNode function);
/* GoogleTest test-case macros (TEST, TEST_F, TEST_P, TYPED_TEST, TYPED_TEST_P)
* parse as function definitions named by the bare macro. With the gtest preset
* on, a C++/CUDA definition is named <MACRO>_<Suite>_<Case> (#1266), and every
* place that names the caller of a call in such a body names it through this
* one function: the def walk, the call-scope walk (compute_func_qn),
* cbm_enclosing_func_qn_cached and the C/C++ engine (c_process_function).
* `func_node` is the function_definition. NULL when `enabled` is false, `name`
* is not one of the five macros, or the head carries no argument; the caller
* keeps its own name then. */
char *cbm_cpp_test_macro_name(CBMArena *a, bool enabled, const char *name, TSNode func_node,
const char *source);
/* The `enabled` argument above for a file of `language`: C++ or CUDA with the
* gtest preset on (on when nothing is configured). */
bool cbm_cpp_test_macro_names_on(CBMLanguage language, const cbm_test_declarations_t *declarations);
/* The preprocessed view reads a head after macro expansion and without its
* comments, so it can spell a test differently from the raw view (a project
* macro among the arguments, a project's own TEST macro). A top-level function
* definition of that view whose first and last lines map to exactly one raw
* test definition's span (CBMTestSpanMap), and the only top-level definition
* of the view that does, is that test: its QN. Otherwise NULL and the caller
* names the body as usual: a method of a local class, a function written on a
* one-line test's line, two raw tests on one line. Used by the call scope, the
* enclosing-function helper and the C/C++ engine, the three places that name
* a caller. A binary search over the view's indexed definitions. */
const char *cbm_test_span_owner_qn(const CBMTestSpanMap *map, TSNode function);
/* Index the preprocessed view's top-level function definitions (directly in
* the translation unit, or in namespace, extern-block, template and
* conditional bodies; never inside a function or class body) that map onto a
* raw test span, into map->view_defs (allocated in `a`). One pass over those
* containers plus a binary search per definition. On allocation failure the
* index stays empty and no body is named from a span. */
void cbm_test_span_index_view(CBMTestSpanMap *map, CBMArena *a, TSNode root);
#ifdef CBM_ENABLE_TEST_SEAMS
/* Steps of the test-span searches and the view index walk plus spans indexed,
* since reset. */
void cbm_test_span_test_reset(void);
uint64_t cbm_test_span_test_work(void);
void cbm_test_span_test_count(uint64_t work);
#endif
// --- Public API ---
// Bind third-party allocators (tree-sitter, sqlite3) to mimalloc as
+6 -1
View File
@@ -1538,6 +1538,9 @@ static int pl_pkg_order_cmp(const void *a, const void *b) {
/* Give every declaration the index of its name's P record (names in order of
* their first declaration) and write the P records. */
static void pl_number_packages(pl_walk_t *w, pl_sb_t *sb) {
if (w->npkgs == 0) {
return;
}
qsort(w->pkgs, (size_t)w->npkgs, sizeof(pl_pkg_t), pl_pkg_name_cmp);
for (int i = 0; i < w->npkgs; i++) { /* index = order of the name's first declaration */
bool repeat =
@@ -1572,7 +1575,9 @@ static int pl_subdecl_cmp(const void *a, const void *b) {
/* One S record per sub definition of the file, with the package the tree
* places it in. */
static void pl_put_subs(CBMExtractCtx *ctx, pl_walk_t *w, pl_sb_t *sb) {
qsort(w->subs, (size_t)w->nsubs, sizeof(pl_subdecl_t), pl_subdecl_cmp);
if (w->nsubs > SKIP_ONE) {
qsort(w->subs, (size_t)w->nsubs, sizeof(pl_subdecl_t), pl_subdecl_cmp);
}
const CBMDefArray *defs = &ctx->result->defs;
for (int i = 0; i < defs->count; i++) {
const CBMDefinition *d = &defs->items[i];
+25 -10
View File
@@ -1603,6 +1603,21 @@ static char *extract_puppet_callee(CBMArena *a, TSNode node, const char *source,
return NULL;
}
/* Callee container of a routine_tag_call / extrinsic_function. Older routine
* grammars always wrapped the target in line_ref. Newer ones emit a bare
* label as method_name (`Do accept`) and a bare routine as routine_ref
* (`$$^Other`). All three have the same source text. */
static TSNode objectscript_routine_callee_container(TSNode node) {
static const char *const kinds[] = {"line_ref", "method_name", "routine_ref", NULL};
for (int i = 0; kinds[i]; i++) {
TSNode child = cbm_find_child_by_kind(node, kinds[i]);
if (!ts_node_is_null(child)) {
return child;
}
}
return (TSNode){0};
}
static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *source,
CBMLanguage lang) {
const char *nk = ts_node_type(node);
@@ -1808,13 +1823,13 @@ static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *
}
return NULL;
}
// $$label^routine extrinsic / routine tag call -> the line_ref text.
// The routine grammar keeps the leading `$$` as an unnamed token, so
// both call forms have the same exact named callee container.
// $$label^routine extrinsic / routine tag call -> the callee container
// text. The routine grammar keeps the leading `$$` as an unnamed token,
// so both call forms have the same exact named callee container.
if (strcmp(nk, "extrinsic_function") == 0 || strcmp(nk, "routine_tag_call") == 0) {
TSNode line_ref = cbm_find_child_by_kind(node, "line_ref");
if (!ts_node_is_null(line_ref)) {
return cbm_node_text(a, line_ref, source);
TSNode callee = objectscript_routine_callee_container(node);
if (!ts_node_is_null(callee)) {
return cbm_node_text(a, callee, source);
}
return NULL;
}
@@ -4171,7 +4186,7 @@ static const char *resolve_objectscript_callee(CBMExtractCtx *ctx, TSNode node,
}
const char *kind = ts_node_type(node);
if ((!callee || !callee[0]) && strcmp(kind, "method_call") == 0) {
if ((!callee || !callee[0]) && cbm_objectscript_is_instance_call(node)) {
callee =
resolve_objectscript_instance_call(ctx->arena, node, ctx->source, &state->os_type_map);
}
@@ -4512,12 +4527,12 @@ static TSNode objectscript_callee_expr(TSNode node) {
if (strcmp(kind, "class_method_call") == 0) {
return cbm_find_child_by_kind(node, "method_name");
}
if (strcmp(kind, "method_call") == 0 || strcmp(kind, "relative_dot_method") == 0) {
if (cbm_objectscript_is_instance_call(node) || strcmp(kind, "relative_dot_method") == 0) {
TSNode oref = cbm_find_child_by_kind(node, "oref_method");
return ts_node_is_null(oref) ? (TSNode){0} : cbm_find_child_by_kind(oref, "method_name");
}
if (strcmp(kind, "extrinsic_function") == 0 || strcmp(kind, "routine_tag_call") == 0) {
return cbm_find_child_by_kind(node, "line_ref");
return objectscript_routine_callee_container(node);
}
return (TSNode){0};
}
@@ -4923,7 +4938,7 @@ CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBML
}
if (!callable_reference && spec->call_node_types && spec->call_node_types[0] &&
cbm_kind_in_set(node, spec->call_node_types)) {
cbm_is_call_site(ctx->language, node, spec->call_node_types)) {
CBMPrimaryCalleeSelection callee = select_primary_callee(ctx, node, state);
// Keyword-filter callees, but keep builtins we mint a node for (len, str,
// ...) so the LSP-resolved builtin call still forms a CALLS edge.
+385 -20
View File
@@ -102,9 +102,10 @@ static bool try_append_ident(const char *source, uint32_t s, int len, uint32_t *
* contract; the pending stack is not — BT_STACK is only the on-stack first
* chunk and spills to the heap, because a full fixed stack dropped a wide
* body's FIRST children and sampled a mid-body window instead.
* Subtrees ending at or before from_byte are skipped (0 = whole body).
* Returns arena-allocated string, or NULL when there are no identifiers or the
* stack could not be grown (logged; no truncated sample is ever returned). */
static char *extract_body_ident_tokens(CBMExtractCtx *ctx, TSNode body) {
static char *extract_ident_tokens_from(CBMExtractCtx *ctx, TSNode body, uint32_t from_byte) {
enum { BT_STACK = 512, BT_BUF = 2048, BT_MAX_IDENTS = 128, BT_SEEN = 256, BT_SEEN_MASK = 255 };
TSNode bt_inline[BT_STACK];
TSNode *bt_stack = bt_inline;
@@ -119,6 +120,9 @@ static char *extract_body_ident_tokens(CBMExtractCtx *ctx, TSNode body) {
while (bt_top > 0 && bt_count < BT_MAX_IDENTS) {
TSNode nd = bt_stack[--bt_top];
if (ts_node_end_byte(nd) <= from_byte) {
continue;
}
uint32_t nc = ts_node_child_count(nd);
if (nc == 0) {
const char *k = ts_node_type(nd);
@@ -156,6 +160,10 @@ static char *extract_body_ident_tokens(CBMExtractCtx *ctx, TSNode body) {
return NULL;
}
static char *extract_body_ident_tokens(CBMExtractCtx *ctx, TSNode body) {
return extract_ident_tokens_from(ctx, body, 0);
}
/* Compute MinHash fingerprint for a function body node and store in def.
* Sets def->fingerprint (arena-allocated) and def->fingerprint_k on success,
* leaves them NULL/0 if the body is too short. */
@@ -5972,30 +5980,82 @@ static bool is_cpp_test_macro(const char *name) {
* Returns an arena-allocated string, or NULL when the parameters cannot be
* resolved (caller keeps the original name in that case). */
static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode node,
const char *source) {
const char *source);
char *cbm_cpp_test_macro_name(CBMArena *a, bool enabled, const char *name, TSNode func_node,
const char *source) {
if (!enabled || !name || !source || ts_node_is_null(func_node) || !is_cpp_test_macro(name)) {
return NULL;
}
return resolve_cpp_test_macro_name(a, name, func_node, source);
}
/* An argument's text without comments and without the blanks around it, in
* place: `Suite /\* c *\/` reads `Suite`, as the compiler (and the second,
* preprocessed view) sees it. */
static char *cpp_test_arg_text(char *text) {
if (!text) {
return NULL;
}
char *w = text;
for (const char *r = text; *r;) {
if (r[0] == '/' && r[1] == '*') {
const char *close = strstr(r + 2, "*/");
r = close ? close + 2 : r + strlen(r);
*w++ = ' ';
} else if (r[0] == '/' && r[1] == '/') {
while (*r && *r != '\n') {
r++;
}
} else {
*w++ = *r++;
}
}
*w = '\0';
while (w > text && (w[-1] == ' ' || w[-1] == '\t' || w[-1] == '\n' || w[-1] == '\r')) {
*--w = '\0';
}
char *start = text;
while (*start == ' ' || *start == '\t' || *start == '\n' || *start == '\r') {
start++;
}
return start;
}
/* The first two arguments of a GoogleTest-style head `MACRO(a, b) {`: the text
* of each named parameter, its type node where the grammar gives one (`Suite`
* parses as a parameter whose type is that name). A comment in the head is an
* extra of the grammar, not an argument. Returns how many it found, at most
* two. */
static int cpp_test_macro_args(CBMArena *a, TSNode node, const char *source, const char *args[2]) {
TSNode params = ts_node_child_by_field_name(node, TS_FIELD("parameters"));
if (ts_node_is_null(params)) {
params = find_c_params(node);
}
if (ts_node_is_null(params)) {
return NULL;
return 0;
}
const char *args[2] = {NULL, NULL};
int count = 0;
uint32_t nc = ts_node_named_child_count(params);
for (uint32_t i = 0; i < nc && count < 2; i++) {
TSNode child = ts_node_named_child(params, i);
if (ts_node_is_null(child)) {
if (ts_node_is_null(child) || strcmp(ts_node_type(child), "comment") == 0) {
continue;
}
TSNode type_node = ts_node_child_by_field_name(child, TS_FIELD("type"));
char *text = cbm_node_text(a, ts_node_is_null(type_node) ? child : type_node, source);
char *text = cpp_test_arg_text(
cbm_node_text(a, ts_node_is_null(type_node) ? child : type_node, source));
if (text && text[0]) {
args[count++] = text;
}
}
return count;
}
static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode node,
const char *source) {
const char *args[2] = {NULL, NULL};
int count = cpp_test_macro_args(a, node, source, args);
if (count == 2) {
return cbm_arena_sprintf(a, "%s_%s_%s", macro, args[0], args[1]);
}
@@ -6005,6 +6065,192 @@ static char *resolve_cpp_test_macro_name(CBMArena *a, const char *macro, TSNode
return NULL;
}
#ifdef CBM_ENABLE_TEST_SEAMS
static _Atomic uint64_t g_test_span_work = 0;
void cbm_test_span_test_reset(void) {
atomic_store_explicit(&g_test_span_work, 0, memory_order_relaxed);
}
uint64_t cbm_test_span_test_work(void) {
return atomic_load_explicit(&g_test_span_work, memory_order_relaxed);
}
void cbm_test_span_test_count(uint64_t work) {
atomic_fetch_add_explicit(&g_test_span_work, work, memory_order_relaxed);
}
#define TEST_SPAN_WORK(n) cbm_test_span_test_count(n)
#else
#define TEST_SPAN_WORK(n) ((void)0)
#endif
static int test_span_cmp(const CBMTestSpan *s, uint32_t start, uint32_t end) {
if (s->start_line != start) {
return s->start_line < start ? -1 : 1;
}
return s->end_line == end ? 0 : (s->end_line < end ? -1 : 1);
}
/* The raw test span (start, end): its index, or -1 when none or two raw tests
* share it. Binary search. */
static int test_span_at(const CBMTestSpanMap *map, uint32_t start, uint32_t end) {
int lo = 0;
int hi = map->count;
while (lo < hi) { /* the first span not below (start, end) */
int mid = lo + (hi - lo) / 2;
TEST_SPAN_WORK(1);
if (test_span_cmp(&map->spans[mid], start, end) < 0) {
lo = mid + 1;
} else {
hi = mid;
}
}
if (lo >= map->count || test_span_cmp(&map->spans[lo], start, end) != 0 ||
(lo + 1 < map->count && test_span_cmp(&map->spans[lo + 1], start, end) == 0)) {
return -1; /* none, or two raw tests on one span */
}
return lo;
}
/* The raw test span a preprocessed-view definition's first and last lines map
* onto, or -1. */
static int test_span_of(const CBMTestSpanMap *map, TSNode function) {
uint32_t first = ts_node_start_point(function).row + 1;
uint32_t last = ts_node_end_point(function).row + 1;
if (last < first || last > (uint32_t)map->line_count || !map->in_main_file[first] ||
!map->in_main_file[last]) {
return -1;
}
uint32_t start = map->raw_line_by_line[first];
uint32_t end = map->raw_line_by_line[last];
return start && end ? test_span_at(map, start, end) : -1;
}
/* Nodes whose children are still top level: namespace, extern-block and
* template bodies and the branches of conditionals. */
static bool test_view_container(const char *kind) {
return strcmp(kind, "namespace_definition") == 0 || strcmp(kind, "declaration_list") == 0 ||
strcmp(kind, "linkage_specification") == 0 ||
strcmp(kind, "template_declaration") == 0 || strncmp(kind, "preproc_", 8) == 0;
}
void cbm_test_span_index_view(CBMTestSpanMap *map, CBMArena *a, TSNode root) {
if (!map) {
return;
}
map->view_defs = NULL;
map->view_def_count = 0;
if (map->count <= 0 || !map->raw_line_by_line || !map->in_main_file || !a ||
ts_node_is_null(root)) {
return;
}
CBMTestViewDef *defs = NULL;
int count = 0;
int cap = 0;
bool failed = false;
TSTreeCursor cursor = ts_tree_cursor_new(root);
int depth = 1;
bool more = ts_tree_cursor_goto_first_child(&cursor);
while (more && !failed) {
TSNode node = ts_tree_cursor_current_node(&cursor);
const char *kind = ts_node_type(node);
TEST_SPAN_WORK(1);
if (strcmp(kind, "function_definition") == 0) {
int span = test_span_of(map, node);
if (span >= 0 && count == cap) {
int grown_cap = cap ? cap * 2 : 16;
CBMTestViewDef *grown =
cbm_arena_alloc(a, (size_t)grown_cap * sizeof(CBMTestViewDef));
if (!grown) {
failed = true;
break;
}
if (count) {
memcpy(grown, defs, (size_t)count * sizeof(CBMTestViewDef));
}
defs = grown;
cap = grown_cap;
}
if (span >= 0) {
defs[count++] =
(CBMTestViewDef){ts_node_start_byte(node), ts_node_end_byte(node), span};
}
} else if (test_view_container(kind) && ts_tree_cursor_goto_first_child(&cursor)) {
depth++;
continue;
}
while (!(more = ts_tree_cursor_goto_next_sibling(&cursor)) && depth > 1) {
ts_tree_cursor_goto_parent(&cursor);
depth--;
}
}
ts_tree_cursor_delete(&cursor);
int *per_span =
failed || count == 0 ? NULL : cbm_arena_alloc(a, (size_t)map->count * sizeof(int));
if (!per_span) {
return; /* nothing maps, or out of memory: no body is named from a span */
}
memset(per_span, 0, (size_t)map->count * sizeof(int));
for (int i = 0; i < count; i++) {
per_span[defs[i].span]++;
}
for (int i = 0; i < count; i++) {
if (per_span[defs[i].span] != 1) {
defs[i].span = -1; /* two definitions of this view on one span: neither */
}
}
map->view_defs = defs;
map->view_def_count = count;
}
/* The raw test span of an indexed top-level definition of the preprocessed
* view, or -1: not indexed (not top level, or mapping onto no single raw
* test), or sharing its span with another such definition. */
static int test_view_def_span(const CBMTestSpanMap *map, TSNode function) {
if (!map || map->view_def_count <= 0 || ts_node_is_null(function)) {
return -1;
}
uint32_t start = ts_node_start_byte(function);
int lo = 0;
int hi = map->view_def_count;
while (lo < hi) { /* the first indexed definition not before `function` */
int mid = lo + (hi - lo) / 2;
TEST_SPAN_WORK(1);
if (map->view_defs[mid].start_byte < start) {
lo = mid + 1;
} else {
hi = mid;
}
}
if (lo >= map->view_def_count || map->view_defs[lo].start_byte != start ||
map->view_defs[lo].end_byte != ts_node_end_byte(function)) {
return -1; /* not an indexed top-level definition of the view */
}
return map->view_defs[lo].span; /* -1 on a shared span */
}
const char *cbm_test_span_owner_qn(const CBMTestSpanMap *map, TSNode function) {
int span = test_view_def_span(map, function);
return span >= 0 ? map->spans[span].qualified_name : NULL;
}
/* Record a raw test definition's span for the preprocessed view (in scratch;
* amortised constant work per test). */
static void record_test_span(CBMExtractCtx *ctx, const CBMDefinition *def) {
if (ctx->test_span_count == ctx->test_span_cap) {
int cap = ctx->test_span_cap ? ctx->test_span_cap * 2 : 16;
CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;
CBMTestSpan *grown = cbm_arena_alloc(scratch, (size_t)cap * sizeof(*grown));
if (!grown) {
return; /* the second view then names this body from its own head */
}
if (ctx->test_span_count) {
memcpy(grown, ctx->test_spans, (size_t)ctx->test_span_count * sizeof(*grown));
}
ctx->test_spans = grown;
ctx->test_span_cap = cap;
}
ctx->test_spans[ctx->test_span_count++] =
(CBMTestSpan){def->start_line, def->end_line, def->qualified_name};
}
/* Configured macro definitions are interpreted only in their raw source.
* The map lives in traversal scratch; its QNs live in the result arena. */
struct CBMTestDefinitionMatch {
@@ -6127,11 +6373,21 @@ bool cbm_test_declarations_validate(CBMFileResult *result,
return result->test_declarations_status == CBM_TEST_EXTRACT_OK;
}
static bool tdx_preset(const CBMExtractCtx *ctx, cbm_test_preset_t preset) {
if (!ctx->test_declarations)
static bool tdx_preset_of(const cbm_test_declarations_t *declarations, cbm_test_preset_t preset) {
if (!declarations)
return preset != CBM_TEST_PRESET_C_CBM;
bool enabled = false;
return cbm_test_declarations_preset(ctx->test_declarations, preset, &enabled) && enabled;
return cbm_test_declarations_preset(declarations, preset, &enabled) && enabled;
}
static bool tdx_preset(const CBMExtractCtx *ctx, cbm_test_preset_t preset) {
return tdx_preset_of(ctx->test_declarations, preset);
}
bool cbm_cpp_test_macro_names_on(CBMLanguage language,
const cbm_test_declarations_t *declarations) {
return (language == CBM_LANG_CPP || language == CBM_LANG_CUDA) &&
tdx_preset_of(declarations, CBM_TEST_PRESET_GTEST);
}
static bool tdx_equal(const char *name, const char *text, size_t size) {
@@ -7518,6 +7774,24 @@ static void push_make_rule_targets(CBMExtractCtx *ctx, TSNode node, const CBMDef
}
}
/* A Ruby `def self.m` (a singleton_method node) or a `def m` inside
* `class << self` lives on the singleton side of its class. */
static bool ruby_def_is_singleton(TSNode node) {
if (strcmp(ts_node_type(node), "singleton_method") == 0) {
return true;
}
for (TSNode p = ts_node_parent(node); !ts_node_is_null(p); p = ts_node_parent(p)) {
const char *t = ts_node_type(p);
if (strcmp(t, "singleton_class") == 0) {
return true;
}
if (strcmp(t, "class") == 0 || strcmp(t, "module") == 0 || strcmp(t, "program") == 0) {
return false;
}
}
return false;
}
static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
CBMArena *a = ctx->arena;
@@ -7561,7 +7835,8 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
/* C++/CUDA: GoogleTest macros (TEST, TEST_F, TEST_P, ...) parse as
* function definitions whose name resolves to the bare macro identifier.
* Multiple test cases per file collide on qualified name; derive a unique
* name from the macro arguments so each gets its own graph node (#1266). */
* name from the macro arguments so each gets its own graph node (#1266).
* The callers of calls in the body are named by the same helper. */
bool is_gtest = false;
const char *configured_name = NULL;
TDXRule configured_rule;
@@ -7571,14 +7846,14 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
return;
name = (char *)configured_name;
}
if (!configured && tdx_preset(ctx, CBM_TEST_PRESET_GTEST) &&
(ctx->language == CBM_LANG_CPP || ctx->language == CBM_LANG_CUDA) &&
is_cpp_test_macro(name)) {
char *gtest_name = resolve_cpp_test_macro_name(a, name, node, ctx->source);
if (gtest_name) {
name = gtest_name;
is_gtest = true;
}
char *gtest_name =
configured ? NULL
: cbm_cpp_test_macro_name(
a, cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations),
name, node, ctx->source);
if (gtest_name) {
name = gtest_name;
is_gtest = true;
}
/* Nix `"${foo}" = x: …`: an interpolated attrpath segment has no statically
@@ -7656,6 +7931,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
strcmp(ts_node_type(node), "function_signature_item") == 0) {
def.is_abstract = true;
}
if (ctx->language == CBM_LANG_RUBY) {
def.is_singleton = ruby_def_is_singleton(node);
}
// Parameters — use func_node (inner function for templates)
TSNode params = configured && ctx->language == CBM_LANG_C
@@ -7867,6 +8145,9 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
return;
}
cbm_defs_push(&ctx->result->defs, a, def);
if (is_gtest && ctx->test_declarations_raw_source && def.qualified_name) {
record_test_span(ctx, &def);
}
if (ctx->language == CBM_LANG_MAKEFILE && strcmp(ts_node_type(node), "rule") == 0) {
push_make_rule_targets(ctx, node, &def);
}
@@ -9467,6 +9748,59 @@ static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
emit_class_def(ctx, node, spec, kind, name);
}
/* The `include`/`prepend`/`extend` macros of a Ruby class/module body as
* "<k>:<Const>" pairs joined by '|' (k = i, p, e), in source order; NULL when
* there are none. Only constant arguments count (`extend self` is not one),
* and only bare or `self.` calls, as the per-file resolver reads them. */
static const char *ruby_class_mixin_refs(CBMArena *a, TSNode node, const char *source) {
TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
TSNode scope = ts_node_is_null(body) ? node : body;
const char *out = NULL;
uint32_t n = ts_node_named_child_count(scope);
for (uint32_t i = 0; i < n; i++) {
TSNode call = ts_node_named_child(scope, i);
if (strcmp(ts_node_type(call), "call") != 0) {
continue;
}
TSNode meth = ts_node_child_by_field_name(call, TS_FIELD("method"));
TSNode recv = ts_node_child_by_field_name(call, TS_FIELD("receiver"));
TSNode args = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
if (ts_node_is_null(meth) || ts_node_is_null(args) ||
(!ts_node_is_null(recv) && strcmp(ts_node_type(recv), "self") != 0)) {
continue;
}
char *mname = cbm_node_text(a, meth, source);
char kind;
if (mname && strcmp(mname, "include") == 0) {
kind = 'i';
} else if (mname && strcmp(mname, "prepend") == 0) {
kind = 'p';
} else if (mname && strcmp(mname, "extend") == 0) {
kind = 'e';
} else {
continue;
}
uint32_t ac = ts_node_named_child_count(args);
for (uint32_t j = 0; j < ac; j++) {
TSNode arg = ts_node_named_child(args, j);
const char *at = ts_node_type(arg);
if (strcmp(at, "constant") != 0 && strcmp(at, "scope_resolution") != 0) {
continue;
}
char *ref = cbm_node_text(a, arg, source);
if (!ref || !ref[0]) {
continue;
}
while (ref[0] == ':') {
ref++;
}
out = out ? cbm_arena_sprintf(a, "%s|%c:%s", out, kind, ref)
: cbm_arena_sprintf(a, "%c:%s", kind, ref);
}
}
return out;
}
/* Emit the class-like def for `node` under `name`, plus its members (enum
* members, methods, fields, class variables). Split from extract_class_def so a
* C `typedef struct { ... } Name;` can name its anonymous struct after the
@@ -9587,6 +9921,9 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s
}
}
def.base_classes = extract_base_classes(a, node, ctx->source, ctx->language);
if (ctx->language == CBM_LANG_RUBY) {
def.mixin_refs = ruby_class_mixin_refs(a, node, ctx->source);
}
// Go identity alias `type A = B` (#2033): keep the aliased type text so the
// cross-file registries can set alias_of. A defined type `type A B` is a
// type_spec and never gets here with this kind.
@@ -10094,6 +10431,9 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node,
strcmp(ts_node_type(child), "function_signature_item") == 0) {
def.is_abstract = true;
}
if (ctx->language == CBM_LANG_RUBY) {
def.is_singleton = ruby_def_is_singleton(child);
}
TSNode params = find_function_params(child, ctx->language);
if (!ts_node_is_null(params)) {
@@ -10550,6 +10890,13 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
a, params, ctx->source, ctx->language, true, &def.signature_param_count);
}
// Return type, as extract_func_def reads it for a free `fn`.
TSNode rt = ts_node_child_by_field_name(child, TS_FIELD("return_type"));
if (!ts_node_is_null(rt)) {
def.return_type = cbm_node_text(a, rt, ctx->source);
def.return_types = extract_return_types(a, rt, ctx->source, ctx->language);
}
if (spec->branching_node_types && spec->branching_node_types[0]) {
set_def_complexity(&def, child, spec);
}
@@ -13134,6 +13481,10 @@ static void extract_class_fields(CBMExtractCtx *ctx, TSNode class_node, const ch
if (strcmp(member_label, "Storage") == 0) {
TSNode sbody = cbm_find_child_by_kind(child, "storage_body");
if (ts_node_is_null(sbody)) {
sbody =
cbm_find_child_by_kind(child, "external_method_body_content");
}
if (!ts_node_is_null(sbody)) {
char *xml = cbm_node_text(a, sbody, ctx->source);
if (xml) {
@@ -13235,13 +13586,27 @@ static void extract_class_fields(CBMExtractCtx *ctx, TSNode class_node, const ch
}
if (strcmp(member_label, "Trigger") == 0) {
/* Grammar v1.9.15+ hides the core_trigger /
* external_trigger wrapper; the body is then
* everything after trigger_name. */
TSNode tbody = cbm_find_child_by_kind(child, "core_trigger");
if (ts_node_is_null(tbody)) {
tbody = cbm_find_child_by_kind(child, "external_trigger");
}
uint32_t body_from = 0;
if (ts_node_is_null(tbody)) {
tbody = child;
body_from = ts_node_end_byte(nname);
}
if (!ts_node_is_null(tbody)) {
mdef.body_tokens = extract_body_ident_tokens(ctx, tbody);
mdef.body_tokens = extract_ident_tokens_from(ctx, tbody, body_from);
char *raw = cbm_node_text(a, tbody, ctx->source);
if (raw && body_from > ts_node_start_byte(tbody)) {
raw += body_from - ts_node_start_byte(tbody);
while (*raw == ' ' || *raw == '\t') {
raw++;
}
}
if (raw && raw[0]) {
char esc[CBM_SZ_512];
int ei = 0;
+85
View File
@@ -515,6 +515,79 @@ static void emit_kustomize_charts(CBMExtractCtx *ctx, TSNode seq) {
}
}
static const char KUST_CONFIGMAP_GEN[] = "configMapGenerator";
static const char KUST_SECRET_GEN[] = "secretGenerator";
static const char KUST_CONFIGURATIONS[] = "configurations";
// A FILE fact: the kustomization reads `path`, named by `via` (one of the
// static names above) at the row of `at`.
static void emit_kustomize_file(CBMExtractCtx *ctx, const char *path, const char *via, TSNode at) {
if (!path || !path[0]) {
return;
}
CBMK8sFact f = {.fact = CBM_K8S_FACT_FILE,
.def_index = -1,
.via = via,
.path = path,
.line = (int)ts_node_start_point(at).row + TS_LINE_OFFSET};
cbm_k8sfact_push(&ctx->result->k8s_facts, ctx->arena, f);
}
// One FILE fact per scalar item of sequence `seq`. `keyed`: an item may be
// `key=path` (a generator's `files`), and the path is what follows the `=`.
static void emit_kustomize_file_items(CBMExtractCtx *ctx, TSNode seq, const char *via, bool keyed) {
k8s_kids_t items = k8s_kids(seq);
TSNode item;
while (k8s_kid(&items, false, &item)) {
if (strcmp(ts_node_type(item), "block_sequence_item") != 0) {
continue;
}
k8s_kids_t vals = k8s_kids(item);
TSNode val;
while (k8s_kid(&vals, false, &val)) {
const char *text = get_scalar_text(ctx->arena, val, ctx->source);
const char *eq = text && keyed ? strchr(text, '=') : NULL;
emit_kustomize_file(ctx, eq ? eq + SKIP_ONE : text, via, val);
}
}
}
// The generators of a `configMapGenerator` / `secretGenerator` list: the
// files each reads -- `files`, `envs`, and the single `env` of older
// kustomize. Literals name no file.
static void emit_kustomize_generators(CBMExtractCtx *ctx, TSNode seq, const char *via) {
CBMArena *a = ctx->arena;
k8s_kids_t items = k8s_kids(seq);
TSNode item;
while (k8s_kid(&items, false, &item)) {
TSNode map = strcmp(ts_node_type(item), "block_sequence_item") == 0
? kust_item_mapping(item)
: (TSNode){0};
if (ts_node_is_null(map)) {
continue;
}
k8s_kids_t pairs = k8s_kids(map);
TSNode pair;
while (k8s_kid(&pairs, false, &pair)) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
continue;
}
const char *key = get_scalar_text(a, ts_node_named_child(pair, 0), ctx->source);
TSNode v = unwrap_pair_value(pair);
if (!key || ts_node_is_null(v)) {
continue;
}
bool files = strcmp(key, "files") == 0;
if ((files || strcmp(key, "envs") == 0) &&
strcmp(ts_node_type(v), "block_sequence") == 0) {
emit_kustomize_file_items(ctx, v, via, files);
} else if (strcmp(key, "env") == 0) {
emit_kustomize_file(ctx, get_scalar_text(a, v, ctx->source), via, v);
}
}
}
}
// Process a single block_mapping_pair for kustomize list keys.
static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
@@ -536,6 +609,18 @@ static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
emit_kustomize_charts(ctx, val_node);
return;
}
if (strcmp(key_text, KUST_CONFIGMAP_GEN) == 0) {
emit_kustomize_generators(ctx, val_node, KUST_CONFIGMAP_GEN);
return;
}
if (strcmp(key_text, KUST_SECRET_GEN) == 0) {
emit_kustomize_generators(ctx, val_node, KUST_SECRET_GEN);
return;
}
if (strcmp(key_text, KUST_CONFIGURATIONS) == 0) {
emit_kustomize_file_items(ctx, val_node, KUST_CONFIGURATIONS, false);
return;
}
if (!is_kustomize_list_key(key_text)) {
return;
}
+115 -3
View File
@@ -28,6 +28,7 @@
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -36,6 +37,7 @@ typedef enum {
SC_ROLE_TYPE, /* defines a type (Protobuf message, enum) */
SC_ROLE_INCLUDE, /* an include statement, when an import starts here */
SC_ROLE_QREF, /* a qualified type reference: its text, qualifier included */
SC_ROLE_SERVICE, /* a service: its methods are symbols an rpc's types meet first */
} sc_role_t;
typedef struct {
@@ -51,17 +53,22 @@ typedef struct {
const char *package_kind; /* the statement naming the file's package; NULL: none */
const char *nest_kind; /* a type kind whose nested types it names; NULL: none */
bool public_reexports; /* `import public` re-exports what it imports */
/* a symbol scope that is no type (Protobuf: a service, its methods), the
* kinds of their name children ("<kind>_name"); NULL: none */
const char *service_kind;
const char *method_kind;
} sc_lang_t;
static const sc_rule_t SC_PROTO_RULES[] = {
{"message", SC_ROLE_TYPE, "Class"}, {"enum", SC_ROLE_TYPE, "Class"},
{"import", SC_ROLE_INCLUDE, NULL}, {"message_or_enum_type", SC_ROLE_QREF, NULL},
{NULL, SC_ROLE_NONE, NULL},
{"service", SC_ROLE_SERVICE, NULL}, {NULL, SC_ROLE_NONE, NULL},
};
static const char *const SC_PROTO_NAMES[] = {"message_name", "enum_name", NULL};
static const sc_lang_t SC_LANGS[] = {
{CBM_LANG_PROTOBUF, SC_PROTO_RULES, SC_PROTO_NAMES, "package", "message", true},
{CBM_LANG_PROTOBUF, SC_PROTO_RULES, SC_PROTO_NAMES, "package", "message", true, "service",
"rpc"},
};
static _Atomic uint64_t g_scope_nodes_visited = 0;
@@ -136,6 +143,14 @@ typedef struct {
uint32_t *cond_depth;
uint32_t ncond;
uint32_t cap_cond;
/* symbols that are no type: the file's services, and the methods of the
* service holding bytes [svc_start, svc_end); each sorted by name */
const char **svcs;
uint32_t nsvcs;
const char **methods;
uint32_t nmethods;
uint32_t svc_start;
uint32_t svc_end;
} sc_walk_t;
/* The definition of `label` named `name` that starts on `line`; -1 when there
@@ -278,6 +293,84 @@ static void sc_include(sc_walk_t *w, TSNode n) {
}
}
static int sc_str_cmp(const void *a, const void *b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
/* The names of `n`'s children of kind `kind` (each through its "<kind>_name"
* child), sorted, into an arena array; false when memory ran out. */
static bool sc_names_of(sc_walk_t *w, TSNode n, const char *kind, const char ***out,
uint32_t *count) {
char name_kind[CBM_SZ_64];
*out = NULL;
*count = 0;
if (snprintf(name_kind, sizeof(name_kind), "%s_name", kind) >= (int)sizeof(name_kind)) {
return true;
}
uint32_t c = ts_node_named_child_count(n);
const char **v = c ? cbm_arena_alloc(w->ctx->arena, c * sizeof(*v)) : NULL;
if (c && !v) {
return false;
}
for (uint32_t i = 0; i < c; i++) {
TSNode ch = ts_node_named_child(n, i);
if (strcmp(ts_node_type(ch), kind) != 0) {
continue;
}
uint32_t cc = ts_node_named_child_count(ch);
for (uint32_t j = 0; j < cc; j++) {
TSNode nm = ts_node_named_child(ch, j);
if (strcmp(ts_node_type(nm), name_kind) == 0) {
const char *t = sc_text(w, nm);
if (t) {
v[(*count)++] = t;
}
break;
}
}
}
if (*count > SKIP_ONE) {
qsort(v, *count, sizeof(*v), sc_str_cmp);
}
*out = v;
return true;
}
/* Entering a service: its methods, which an rpc's types meet first. */
static bool sc_service(sc_walk_t *w, TSNode n) {
w->svc_start = ts_node_start_byte(n);
w->svc_end = ts_node_end_byte(n);
return sc_names_of(w, n, w->lang->method_kind, &w->methods, &w->nmethods);
}
static bool sc_sorted_has(sc_walk_t *w, const char *const *v, uint32_t n, const char *key) {
w->steps++; /* one search */
return n > 0 && bsearch(&key, v, n, sizeof(*v), sc_str_cmp) != NULL;
}
/* Whether, on the way out from the reference at byte `at`, its first
* component names a symbol that is no type before any type: in an rpc a
* method of its service (protoc searches the service first and resolves any
* symbol there), or a service of the file; elsewhere a service only when the
* reference is qualified (an unqualified field type skips what is no type). */
static bool sc_meets_no_type(sc_walk_t *w, const char *text, uint32_t at) {
if (!w->lang->service_kind || text[0] == '.') {
return false; /* from the root: no scope is searched */
}
size_t fl = strcspn(text, ".");
char first[CBM_SZ_256];
if (fl >= sizeof(first)) {
return true; /* not read: never proven */
}
memcpy(first, text, fl);
first[fl] = '\0';
bool in_rpc = at >= w->svc_start && at < w->svc_end;
if (in_rpc && sc_sorted_has(w, w->methods, w->nmethods, first)) {
return true;
}
return (in_rpc || text[fl] == '.') && sc_sorted_has(w, w->svcs, w->nsvcs, first);
}
/* A qualified type reference as written, blanks and comments between its
* parts dropped: "google.protobuf.Empty", ".a.B", "Empty". */
static void sc_qref(sc_walk_t *w, TSNode n) {
@@ -300,8 +393,15 @@ static void sc_qref(sc_walk_t *w, TSNode n) {
k += ce - cb;
}
text[k] = '\0';
/* the innermost scope around it: the enclosing message (NULL when its
* full name is unknown), else the file's package */
const char *scope = w->lang->package_kind ? w->pkg : NULL;
if (w->nnest > 0) {
scope = w->nest_full[w->nnest - SKIP_ONE];
}
if (k > 0) {
sc_emit(w, CBM_SCOPE_QREF, text, NULL, (int32_t)b, e, 0);
uint8_t flags = sc_meets_no_type(w, text, b) ? (uint8_t)CBM_SCOPE_NOT_A_TYPE : 0;
sc_emit(w, CBM_SCOPE_QREF, text, scope, (int32_t)b, e, flags);
}
}
@@ -326,6 +426,9 @@ static bool sc_visit(sc_walk_t *w, TSNode n, bool *failed) {
case SC_ROLE_QREF:
sc_qref(w, n);
return false;
case SC_ROLE_SERVICE:
*failed = !sc_service(w, n);
return true;
case SC_ROLE_NONE:
default:
return true;
@@ -432,6 +535,9 @@ void cbm_extract_scope(CBMExtractCtx *ctx) {
if (lang->package_kind) {
w.pkg = sc_package(&w, ctx->root);
}
if (lang->service_kind && !sc_names_of(&w, ctx->root, lang->service_kind, &w.svcs, &w.nsvcs)) {
return;
}
const CBMDefArray *defs = &ctx->result->defs;
if (defs->count > 0) {
w.defs = cbm_arena_alloc(ctx->arena, (size_t)defs->count * sizeof(*w.defs));
@@ -457,6 +563,12 @@ void cbm_extract_scope(CBMExtractCtx *ctx) {
qsort(w.imps, (size_t)w.nimps, sizeof(*w.imps), sc_ref_cmp);
}
uint64_t visited = sc_walk_tree(&w, ctx->root);
if (ts_node_has_error(ctx->root)) {
/* a tree with an error the walk may not meet as an ERROR node (a
* MISSING token the parser inserted): the compiler rejects the file,
* so nothing in it is proven */
sc_emit(&w, CBM_SCOPE_OPAQUE, NULL, NULL, -1, ts_node_end_byte(ctx->root), 0);
}
atomic_fetch_add_explicit(&g_scope_nodes_visited, visited + w.steps, memory_order_relaxed);
CBMScopeEventArray *ev = &ctx->result->scope;
if (ev->count > SKIP_ONE) {
+19
View File
@@ -1139,6 +1139,14 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan
if (configured_qn) {
return configured_qn;
}
/* The preprocessed view of a C/C++ file: a body whose lines are a raw
* GoogleTest definition's is that test, whatever its expanded head reads. */
if (ctx->pp_test_spans && strcmp(ts_node_type(node), "function_definition") == 0) {
const char *raw_test = cbm_test_span_owner_qn(ctx->pp_test_spans, node);
if (raw_test) {
return raw_test;
}
}
/* C# local functions nested in a member have no graph node. Attribute calls
* in them to the enclosing function, whose definition span contains the
@@ -1307,6 +1315,17 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan
return NULL;
}
/* GoogleTest `TEST(Suite, Case) {...}` and its four siblings: the def
* extractor names the definition TEST_Suite_Case (#1266). Name the call
* scope through the same helper, or every call in the body names a
* definition that was never minted and is sourced at the File node. */
char *test_name = cbm_cpp_test_macro_name(
ctx->arena, cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), name, node,
ctx->source);
if (test_name) {
name = test_name;
}
/* C++/CUDA out-of-line method `void Foo::bar() {...}`: the def extractor
* records this as Method "proj.file.Foo.bar". The call-scope QN must match
* (be class-qualified) so an in-body call sources to the method, not a bare
+1 -1
View File
@@ -2694,7 +2694,7 @@ static void walk_usages(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec
UsageFrame *f = &frames[top - 1];
if (entering) {
try_emit_usage(ctx, f->node, spec, call_depth > 0, import_depth > 0);
f->counts_call = cbm_kind_in_set(f->node, spec->call_node_types);
f->counts_call = cbm_is_call_site(ctx->language, f->node, spec->call_node_types);
f->counts_import =
(has_imports && cbm_kind_in_set(f->node, spec->import_node_types)) ||
(has_from_imports && cbm_kind_in_set(f->node, spec->import_from_types));
+35 -4
View File
@@ -479,6 +479,24 @@ TSNode cbm_find_child_by_kind(TSNode parent, const char *kind) {
return null_node;
}
bool cbm_objectscript_is_instance_call(TSNode node) {
const char *kind = ts_node_type(node);
if (strcmp(kind, "method_call") == 0) {
return true;
}
if (strcmp(kind, "do_parameter") != 0 && strcmp(kind, "job_argument") != 0) {
return false;
}
return !ts_node_is_null(cbm_find_child_by_kind(node, "oref_method"));
}
bool cbm_is_call_site(CBMLanguage lang, TSNode node, const char **call_types) {
if (cbm_kind_in_set(node, call_types)) {
return true;
}
return lang == CBM_LANG_OBJECTSCRIPT_UDL && cbm_objectscript_is_instance_call(node);
}
int cbm_find_children_by_kind(TSNode parent, const char *kind, TSNode *out, int max) {
int n = 0;
uint32_t count = ts_node_child_count(parent);
@@ -1547,16 +1565,28 @@ static const char *func_node_name(CBMArena *a, TSNode func_node, const char *sou
}
const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source,
const char *project, const char *rel_path,
const char *module_qn) {
const char *project, const char *rel_path, const char *module_qn,
bool test_macro_names, const CBMTestSpanMap *pp_test_spans) {
TSNode func_node = cbm_find_enclosing_func(node, lang);
if (ts_node_is_null(func_node)) {
return module_qn;
}
/* The preprocessed view: a raw GoogleTest definition's body is that test. */
if (pp_test_spans && strcmp(ts_node_type(func_node), "function_definition") == 0) {
const char *raw_test = cbm_test_span_owner_qn(pp_test_spans, func_node);
if (raw_test) {
return raw_test;
}
}
const char *name = func_node_name(a, func_node, source, lang);
if (!name || !name[0]) {
return module_qn;
}
/* GoogleTest TEST(Suite, Case): the def walk's TEST_Suite_Case (#1266). */
const char *test_name = cbm_cpp_test_macro_name(a, test_macro_names, name, func_node, source);
if (test_name) {
name = test_name;
}
// Check if the function is inside a class — compute classQN.funcName.
// For nested classes the class QN must carry the FULL nesting chain
@@ -1623,8 +1653,9 @@ const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node) {
}
// Cache miss: compute via parent walk
const char *qn = cbm_enclosing_func_qn(ctx->arena, node, ctx->language, ctx->source,
ctx->project, ctx->rel_path, ctx->module_qn);
const char *qn = cbm_enclosing_func_qn(
ctx->arena, node, ctx->language, ctx->source, ctx->project, ctx->rel_path, ctx->module_qn,
cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), ctx->pp_test_spans);
// Cache the result: find the enclosing function's byte range
TSNode func_node = cbm_find_enclosing_func(node, ctx->language);
+18 -2
View File
@@ -48,9 +48,14 @@ bool cbm_is_test_file(const char *rel_path, CBMLanguage lang);
// Returns a null node if none found.
TSNode cbm_find_enclosing_func(TSNode node, CBMLanguage lang);
// Get the QN of an enclosing function, or module_qn if none.
// Get the QN of an enclosing function, or module_qn if none. test_macro_names:
// a GoogleTest macro head is named as the def walk names it
// (cbm_cpp_test_macro_name; cbm_cpp_test_macro_names_on gives the value).
// pp_test_spans: the preprocessed view's map to the raw tests
// (cbm_test_span_owner_qn), NULL in a raw view.
const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source,
const char *project, const char *rel_path, const char *module_qn);
const char *project, const char *rel_path, const char *module_qn,
bool test_macro_names, const CBMTestSpanMap *pp_test_spans);
// Cached version: uses ctx->ef_cache to avoid repeated parent-chain walks.
const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node);
@@ -209,6 +214,12 @@ bool cbm_csharp_is_extension_block(TSNode node, TSNode class_node, const char *s
// Find a child node by kind string.
TSNode cbm_find_child_by_kind(TSNode parent, const char *kind);
// ObjectScript `Do obj.M()` / `Job obj.M()`: grammar v1.9.15+ hides the old
// `method_call` wrapper, so its receiver and `oref_method` sit directly under
// `do_parameter` / `job_argument`. True for `method_call` itself or for one of
// those parents carrying a direct `oref_method` child.
bool cbm_objectscript_is_instance_call(TSNode node);
// Find every child node matching `kind` (unlike cbm_find_child_by_kind,
// which stops at the first match). Writes up to `max` nodes into `out`;
// returns how many were found. Repeated sibling nodes of the same kind are
@@ -249,6 +260,11 @@ bool cbm_chialisp_is_def_head(const char *t);
// Check if node kind matches a set of types (NULL-terminated array of strings).
bool cbm_kind_in_set(TSNode node, const char **types);
// cbm_kind_in_set over a language's call_node_types, plus the ObjectScript UDL
// `Do obj.M()` sites that no longer have a dedicated node kind (see
// cbm_objectscript_is_instance_call).
bool cbm_is_call_site(CBMLanguage lang, TSNode node, const char **call_types);
/* Namespace/module declarations that extend a qualified-name scope without
* turning their children into class methods. Shared by definition and unified
* walks so TS/TSX scope attribution cannot drift. */
+5 -2
View File
@@ -1701,8 +1701,11 @@ static const char *objectscript_udl_func_types[] = {"method", "classmethod", "qu
static const char *objectscript_udl_class_types[] = {"class_definition", NULL};
static const char *objectscript_udl_field_types[] = {
"property", "parameter", "index", "trigger", "xdata", "storage", "foreignkey", NULL};
static const char *objectscript_udl_call_types[] = {"class_method_call", "method_call",
"relative_dot_method", "macro", NULL};
/* Instance calls (`Do obj.M()`) have no call node of their own: the grammar
* hides method_call, leaving do_parameter/job_argument with an oref_method
* child. cbm_is_call_site() matches those via cbm_objectscript_is_instance_call. */
static const char *objectscript_udl_call_types[] = {"class_method_call", "relative_dot_method",
"macro", NULL};
static const char *objectscript_udl_module_types[] = {"source_file", NULL};
/* Branching nodes for cyclomatic complexity (verified against grammar node-types) */
static const char *objectscript_udl_branch_types[] = {
+60 -27
View File
@@ -5769,9 +5769,19 @@ static void c_process_function(CLSPContext *ctx, TSNode func_node) {
}
}
}
if (!func_qn && ctx->pp_test_spans) {
/* The preprocessed view: a raw GoogleTest definition's body is that
* test, whatever its expanded head reads (cbm_test_span_owner_qn). */
func_qn = cbm_test_span_owner_qn(ctx->pp_test_spans, func_node);
}
if (!func_qn) {
/* GoogleTest `TEST(Suite, Case)`: the definition is TEST_Suite_Case
* (#1266), named by the same helper as the def walk and the call
* scope; the pipeline joins this caller with theirs by exact QN. */
const char *test_name = cbm_cpp_test_macro_name(ctx->arena, ctx->test_macro_names,
func_name, func_node, ctx->source);
// Build enclosing function QN
func_qn = c_build_qn(ctx, func_name);
func_qn = c_build_qn(ctx, test_name ? test_name : func_name);
// For a method defined INLINE inside its class body, func_name is a bare
// identifier ("compute") and enclosing_class_qn was inherited from
// c_process_class (saved_class_qn == enclosing_class_qn). The textual
@@ -6827,16 +6837,30 @@ static void c_add_type_indexed(CBMTypeRegistry *reg, CTypeFirstIndex *ix, CBMAre
}
}
static bool c_lsp_file_run(CBMArena *arena, CBMFileResult *result, const char *source,
int source_len, TSNode root, bool cpp_mode,
CBMSourceOrigin source_origin, const CBMFileResult *test_owners,
const CBMTestSpanMap *pp_test_spans);
void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin) {
(void)cbm_run_c_lsp_with_test_owners(arena, result, source, source_len, root,
cpp_mode, source_origin, NULL);
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin,
const CBMTestSpanMap *pp_test_spans) {
(void)c_lsp_file_run(arena, result, source, source_len, root, cpp_mode, source_origin, NULL,
pp_test_spans);
}
bool cbm_run_c_lsp_with_test_owners(
CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin,
const CBMFileResult *test_owners) {
bool cbm_run_c_lsp_with_test_owners(CBMArena *arena, CBMFileResult *result, const char *source,
int source_len, TSNode root, bool cpp_mode,
CBMSourceOrigin source_origin,
const CBMFileResult *test_owners) {
return c_lsp_file_run(arena, result, source, source_len, root, cpp_mode, source_origin,
test_owners, NULL);
}
static bool c_lsp_file_run(CBMArena *arena, CBMFileResult *result, const char *source,
int source_len, TSNode root, bool cpp_mode,
CBMSourceOrigin source_origin, const CBMFileResult *test_owners,
const CBMTestSpanMap *pp_test_spans) {
if ((test_owners && test_owners->has_test_definition_owners &&
source_origin != CBM_SOURCE_ORIGIN_RAW) ||
!cbm_test_definition_owners_match(test_owners, source, source_len, cpp_mode,
@@ -7024,6 +7048,8 @@ bool cbm_run_c_lsp_with_test_owners(
c_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, cpp_mode, &result->resolved_calls);
ctx.source_origin = source_origin;
ctx.test_definition_owners = test_owners;
ctx.test_macro_names = cpp_mode && result->cpp_test_macro_names;
ctx.pp_test_spans = pp_test_spans;
c_memo_test_stage(&ctx,
source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED ? "preprocessed" : "raw");
@@ -7225,7 +7251,7 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i
const char **include_ns_qns, int include_count,
TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin,
const CBMFileResult *test_owners,
const CBMFileResult *test_owners, bool test_macro_names,
CBMLSPStatus *status) {
*status = CBM_LSP_COMPLETE;
/* The retained or re-read source is the file on disk; read it the way the
@@ -7263,6 +7289,7 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i
c_lsp_init(&ctx, arena, source, source_len, reg, module_qn, cpp_mode, out);
ctx.source_origin = source_origin;
ctx.test_definition_owners = test_owners;
ctx.test_macro_names = cpp_mode && test_macro_names;
ctx.registry_shared = true; /* Tier-2 shared registry: read-only, see flag doc */
for (int i = 0; i < include_count; i++) {
c_lsp_add_include(&ctx, include_paths[i], include_ns_qns[i]);
@@ -7277,6 +7304,8 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i
return c_test_owners_complete(&ctx);
}
/* Without a file result the extraction default holds: no configuration, so a
* C++ file's GoogleTest heads are named (cbm_cpp_test_macro_names_on). */
bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
const char *module_qn, bool cpp_mode, CBMTypeRegistry *reg,
const char **include_paths, const char **include_ns_qns,
@@ -7284,17 +7313,17 @@ bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int
CBMResolvedCallArray *out) {
return cbm_run_c_lsp_cross_with_registry_status(
arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns,
include_count, cached_tree, out) == CBM_LSP_COMPLETE;
include_count, cached_tree, out, cpp_mode) == CBM_LSP_COMPLETE;
}
CBMLSPStatus cbm_run_c_lsp_cross_with_registry_status(
CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode,
CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns,
int include_count, TSTree *cached_tree, CBMResolvedCallArray *out) {
int include_count, TSTree *cached_tree, CBMResolvedCallArray *out, bool test_macro_names) {
CBMLSPStatus status;
(void)c_lsp_cross_with_registry_run(arena, source, source_len, module_qn, cpp_mode, reg,
include_paths, include_ns_qns, include_count, cached_tree,
out, CBM_SOURCE_ORIGIN_RAW, NULL, &status);
(void)c_lsp_cross_with_registry_run(
arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns,
include_count, cached_tree, out, CBM_SOURCE_ORIGIN_RAW, NULL, test_macro_names, &status);
return status;
}
@@ -7305,12 +7334,11 @@ bool cbm_run_c_lsp_cross_with_registry_with_test_owners(
CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode,
CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns,
int include_count, TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin, const CBMFileResult *test_owners) {
CBMSourceOrigin source_origin, const CBMFileResult *test_owners, bool test_macro_names) {
CBMLSPStatus status;
bool owners_ok = c_lsp_cross_with_registry_run(arena, source, source_len, module_qn, cpp_mode,
reg, include_paths, include_ns_qns,
include_count, cached_tree, out, source_origin,
test_owners, &status);
bool owners_ok = c_lsp_cross_with_registry_run(
arena, source, source_len, module_qn, cpp_mode, reg, include_paths, include_ns_qns,
include_count, cached_tree, out, source_origin, test_owners, test_macro_names, &status);
return owners_ok && status == CBM_LSP_COMPLETE;
}
@@ -7321,7 +7349,7 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len,
const char **include_paths, const char **include_ns_qns,
int include_count, TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin, const CBMFileResult *test_owners,
CBMLSPStatus *status) {
bool test_macro_names, CBMLSPStatus *status) {
*status = CBM_LSP_COMPLETE;
/* Same bytes as the per-file extract (#1546); see
* c_lsp_cross_with_registry_run. */
@@ -7376,6 +7404,7 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len,
c_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, cpp_mode, out);
ctx.source_origin = source_origin;
ctx.test_definition_owners = test_owners;
ctx.test_macro_names = cpp_mode && test_macro_names;
// Add include mappings
for (int i = 0; i < include_count; i++) {
@@ -7392,24 +7421,27 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len,
return c_test_owners_complete(&ctx);
}
/* No file result: the extraction default without configuration, as for
* cbm_run_c_lsp_cross_with_registry. */
bool cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn,
bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths,
const char **include_ns_qns, int include_count, TSTree *cached_tree,
CBMResolvedCallArray *out) {
return cbm_run_c_lsp_cross_status(arena, source, source_len, module_qn, cpp_mode, defs,
def_count, include_paths, include_ns_qns, include_count,
cached_tree, out) == CBM_LSP_COMPLETE;
cached_tree, out, cpp_mode) == CBM_LSP_COMPLETE;
}
CBMLSPStatus cbm_run_c_lsp_cross_status(CBMArena *arena, const char *source, int source_len,
const char *module_qn, bool cpp_mode, CBMLSPDef *defs,
int def_count, const char **include_paths,
const char **include_ns_qns, int include_count,
TSTree *cached_tree, CBMResolvedCallArray *out) {
TSTree *cached_tree, CBMResolvedCallArray *out,
bool test_macro_names) {
CBMLSPStatus status;
(void)c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs, def_count,
include_paths, include_ns_qns, include_count, cached_tree, out,
CBM_SOURCE_ORIGIN_RAW, NULL, &status);
CBM_SOURCE_ORIGIN_RAW, NULL, test_macro_names, &status);
return status;
}
@@ -7420,11 +7452,12 @@ bool cbm_run_c_lsp_cross_with_test_owners(CBMArena *arena, const char *source, i
const char **include_ns_qns, int include_count,
TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin,
const CBMFileResult *test_owners) {
const CBMFileResult *test_owners, bool test_macro_names) {
CBMLSPStatus status;
bool owners_ok = c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs,
def_count, include_paths, include_ns_qns, include_count,
cached_tree, out, source_origin, test_owners, &status);
bool owners_ok =
c_lsp_cross_run(arena, source, source_len, module_qn, cpp_mode, defs, def_count,
include_paths, include_ns_qns, include_count, cached_tree, out,
source_origin, test_owners, test_macro_names, &status);
return owners_ok && status == CBM_LSP_COMPLETE;
}
+25 -15
View File
@@ -83,6 +83,9 @@ typedef struct {
CBMResolvedCallArray *resolved_calls;
CBMSourceOrigin source_origin; // source buffer represented by emitted occurrence spans
const CBMFileResult *test_definition_owners; /* borrowed, prevalidated raw source identity */
/* The preprocessed per-file run only: the raw view's GoogleTest spans and
* the line map (cbm_test_span_owner_qn). Borrowed; NULL otherwise. */
const CBMTestSpanMap *pp_test_spans;
int test_owner_seen_count;
bool test_owner_error;
@@ -113,6 +116,8 @@ typedef struct {
// Flags
bool cpp_mode; // C++ features enabled
bool test_macro_names; // GoogleTest heads are named as the def walk names them
// (CBMFileResult.cpp_test_macro_names, cbm_cpp_test_macro_name)
bool in_template; // currently inside template declaration
bool registry_shared; // ctx->registry is the Tier-2 cross registry, shared
// READ-ONLY across resolve workers — never mutate it
@@ -175,8 +180,11 @@ const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_p
// --- Entry points ---
// Single-file LSP: build registry from file defs + stdlib, run resolution.
// pp_test_spans: for the preprocessed view, the raw GoogleTest spans and line
// map (cbm_test_span_owner_qn); NULL otherwise.
void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin);
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin,
const CBMTestSpanMap *pp_test_spans);
// A memo allocation/capacity failure is an explicit incomplete-refinement error.
#define CBM_C_LSP_DEPTH_ERROR "C/C++ expression recursion depth limit exceeded"
@@ -191,13 +199,15 @@ uint32_t cbm_c_lsp_test_walks_take(void);
// Cross-file LSP: build registry from defs + stdlib, re-parse and resolve.
// Status variants distinguish memo/depth failure. Bool wrappers report success.
// Completed output before a failed walk is kept.
// Completed output before a failed walk is kept. test_macro_names: the file's
// CBMFileResult.cpp_test_macro_names (the bool wrappers pass cpp_mode, the
// extraction default without configuration).
CBMLSPStatus cbm_run_c_lsp_cross_status(CBMArena *arena, const char *source, int source_len,
const char *module_qn, bool cpp_mode, CBMLSPDef *defs,
int def_count, const char **include_paths,
const char **include_ns_qns, int include_count,
TSTree *cached_tree, // NULL = parse internally
CBMResolvedCallArray *out);
CBMResolvedCallArray *out, bool test_macro_names);
bool cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn,
bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths,
@@ -217,7 +227,7 @@ CBMLSPStatus cbm_run_c_lsp_cross_with_registry_status(
CBMTypeRegistry *reg, // pre-built, finalized, READ-ONLY
const char **include_paths, const char **include_ns_qns, int include_count,
TSTree *cached_tree, // NULL = parse internally
CBMResolvedCallArray *out);
CBMResolvedCallArray *out, bool test_macro_names);
bool cbm_run_c_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
const char *module_qn, bool cpp_mode,
@@ -239,18 +249,18 @@ bool cbm_run_c_lsp_with_test_owners(
CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root, bool cpp_mode, CBMSourceOrigin source_origin,
const CBMFileResult *test_owners);
bool cbm_run_c_lsp_cross_with_test_owners(
CBMArena *arena, const char *source, int source_len, const char *module_qn,
bool cpp_mode, CBMLSPDef *defs, int def_count, const char **include_paths,
const char **include_ns_qns, int include_count, TSTree *cached_tree,
CBMResolvedCallArray *out, CBMSourceOrigin source_origin,
const CBMFileResult *test_owners);
bool cbm_run_c_lsp_cross_with_test_owners(CBMArena *arena, const char *source, int source_len,
const char *module_qn, bool cpp_mode, CBMLSPDef *defs,
int def_count, const char **include_paths,
const char **include_ns_qns, int include_count,
TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin,
const CBMFileResult *test_owners, bool test_macro_names);
bool cbm_run_c_lsp_cross_with_registry_with_test_owners(
CBMArena *arena, const char *source, int source_len, const char *module_qn,
bool cpp_mode, CBMTypeRegistry *reg, const char **include_paths,
const char **include_ns_qns, int include_count, TSTree *cached_tree,
CBMResolvedCallArray *out, CBMSourceOrigin source_origin,
const CBMFileResult *test_owners);
CBMArena *arena, const char *source, int source_len, const char *module_qn, bool cpp_mode,
CBMTypeRegistry *reg, const char **include_paths, const char **include_ns_qns,
int include_count, TSTree *cached_tree, CBMResolvedCallArray *out,
CBMSourceOrigin source_origin, const CBMFileResult *test_owners, bool test_macro_names);
// Register C stdlib types and functions into a registry.
void cbm_c_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
+5
View File
@@ -114,6 +114,11 @@ typedef struct {
* by the registrar against def_module_qn like return_types. NULL = not an
* identity alias. */
const char *alias_target;
/* Ruby only: singleton-side method (`def self.m`, `class << self`), and a
* class/module's mixin macros as "|"-separated "<k>:<Const>" pairs (k = i,
* p or e). See CBMDefinition. */
bool is_singleton;
const char *mixin_refs;
/* Identities of the type names this def's declared types write, resolved
* once in the scope of the file that wrote them (src/pipeline/type_scope.h):
* "spelling=QN|spelling=QN". Read with cbm_type_scope_find (type_rep.h).
+703 -23
View File
@@ -417,14 +417,130 @@ static const char *ruby_ivar_type(RubyLSPContext *ctx, const char *class_qn,
return NULL;
}
static RubyClassInfo *ruby_class_by_qn(RubyLSPContext *ctx, const char *qn) {
/* ── shared (project-wide) class table ──────────────────────────── */
static unsigned ruby_hash(const char *s) {
unsigned h = 2166136261u;
for (; *s; s++)
h = (h ^ (unsigned char)*s) * 16777619u;
return h;
}
static unsigned ruby_hash_root_path(const char *root, const char *path) {
unsigned h = 2166136261u;
for (const char *s = root; *s; s++)
h = (h ^ (unsigned char)*s) * 16777619u;
h = (h ^ 0x1fu) * 16777619u;
for (const char *s = path; *s; s++)
h = (h ^ (unsigned char)*s) * 16777619u;
return h;
}
/* Package root of a file, from its module QN ("proj.activemodel.test.models.
* topic"): the QN prefix before the first directory named lib, app, test or
* spec ("proj.activemodel"). "" when no such directory exists or it sits
* directly under the project, so a single-package repository has one root.
* Derived from the QN alone, so a full build and the incremental route (which
* has only persisted defs) agree, with no file system access. */
static const char *ruby_package_root(CBMArena *a, const char *module_qn) {
if (!module_qn)
return "";
const char *p = strchr(module_qn, '.'); /* skip the project segment */
while (p) {
const char *seg = p + 1;
const char *end = strchr(seg, '.');
if (!end)
break; /* the last segment is the file, not a directory */
size_t n = (size_t)(end - seg);
bool marker =
(n == 3 && strncmp(seg, "lib", 3) == 0) || (n == 3 && strncmp(seg, "app", 3) == 0) ||
(n == 4 && strncmp(seg, "test", 4) == 0) || (n == 4 && strncmp(seg, "spec", 4) == 0);
if (marker)
return p == strchr(module_qn, '.')
? ""
: cbm_arena_strndup(a, module_qn, (size_t)(p - module_qn));
p = end;
}
return "";
}
/* Probe the QN index. */
static const RubyClassInfo *ruby_shared_find(const CBMRubyCrossRegistry *sh, const int *slots,
const char *qn) {
if (!sh || !slots || !qn)
return NULL;
unsigned i = ruby_hash(qn) & sh->slot_mask;
while (slots[i]) {
CBM_LSP_WORK(1);
const RubyClassInfo *c = &sh->classes[slots[i] - 1];
if (strcmp(c->qn, qn) == 0)
return c;
i = (i + 1) & sh->slot_mask;
}
return NULL;
}
/* The group head declared in `root` for `path`, or NULL. */
static const RubyClassInfo *ruby_shared_find_root_path(const CBMRubyCrossRegistry *sh,
const char *root, const char *path) {
if (!sh || !sh->by_path)
return NULL;
unsigned i = ruby_hash_root_path(root, path) & sh->slot_mask;
while (sh->by_path[i]) {
CBM_LSP_WORK(1);
const RubyClassInfo *c = &sh->classes[sh->by_path[i] - 1];
if (strcmp(c->root, root) == 0 && strcmp(c->path, path) == 0)
return c;
i = (i + 1) & sh->slot_mask;
}
return NULL;
}
/* The first group head with constant path `path` in any root; further roots
* chain through path_next. */
static const RubyClassInfo *ruby_shared_find_path(const CBMRubyCrossRegistry *sh,
const char *path) {
if (!sh || !sh->by_pp)
return NULL;
unsigned i = ruby_hash(path) & sh->slot_mask;
while (sh->by_pp[i]) {
CBM_LSP_WORK(1);
const RubyClassInfo *c = &sh->classes[sh->by_pp[i] - 1];
if (strcmp(c->path, path) == 0)
return c;
i = (i + 1) & sh->slot_mask;
}
return NULL;
}
/* This file's own declaration of a class wins; otherwise the project table.
* The own-file scan is bounded by the file, the shared probe is O(1). */
static const RubyClassInfo *ruby_class_by_qn(RubyLSPContext *ctx, const char *qn) {
if (!qn)
return NULL;
for (int i = 0; i < ctx->class_count; i++) {
if (strcmp(ctx->classes[i].qn, qn) == 0)
return &ctx->classes[i];
}
return NULL;
return ruby_shared_find(ctx->shared, ctx->shared ? ctx->shared->by_qn : NULL, qn);
}
/* The merged record for a class of the project table: the group head holding
* every reopening's methods and the superclass. NULL when `qn` is not in it. */
static const RubyClassInfo *ruby_shared_head(const CBMRubyCrossRegistry *sh, const char *qn) {
const RubyClassInfo *c = ruby_shared_find(sh, sh ? sh->by_qn : NULL, qn);
return c && c->group_head ? &sh->classes[c->group_head - 1] : NULL;
}
/* The entry whose superclass applies to `qn`. A file that reopens a class
* without `< Base` has an own entry with no superclass, so the merged record
* backs it up: inherited methods and the model checks keep working there. */
static const RubyClassInfo *ruby_effective_class(RubyLSPContext *ctx, const char *qn) {
const RubyClassInfo *ci = ruby_class_by_qn(ctx, qn);
if (ci && ci->superclass_ref)
return ci;
const RubyClassInfo *head = ruby_shared_head(ctx->shared, qn);
return head ? head : ci;
}
/* Conventional Rails superclasses for stdlib-seeded types the class table
@@ -447,7 +563,7 @@ static const char *ruby_stdlib_superclass(const char *qn) {
/* Superclass QN of a class: table entry first, then the conventional
* stdlib chain above. */
static const char *ruby_superclass_qn(RubyLSPContext *ctx, const char *class_qn) {
RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
const RubyClassInfo *ci = ruby_effective_class(ctx, class_qn);
if (ci)
return ci->superclass_qn;
return ruby_stdlib_superclass(class_qn);
@@ -455,13 +571,31 @@ static const char *ruby_superclass_qn(RubyLSPContext *ctx, const char *class_qn)
/* ── constant resolution ────────────────────────────────────────── */
/* Class-table probe by dotted path. */
static const char *ruby_class_qn_by_path(RubyLSPContext *ctx, const char *path) {
/* Class-table probe by dotted path: this file first, then the project.
* *ambiguous is set when the project declares `path` under several package
* roots, none of them the caller's: the constant exists, so Ruby would bind
* it here and the caller must not fall through to an outer one. */
static const char *ruby_class_qn_by_path(RubyLSPContext *ctx, const char *path, bool *ambiguous) {
*ambiguous = false;
for (int i = 0; i < ctx->class_count; i++) {
if (strcmp(ctx->classes[i].path, path) == 0)
return ctx->classes[i].qn;
}
return NULL;
/* The caller's own package root wins. Failing that, a constant declared
* in exactly one root resolves there; one declared under several roots,
* none of them the caller's, stays unresolved rather than landing on
* another package's same-named class. */
const CBMRubyCrossRegistry *sh = ctx->shared;
const RubyClassInfo *c =
ruby_shared_find_root_path(sh, ctx->caller_root ? ctx->caller_root : "", path);
if (c)
return c->qn;
c = ruby_shared_find_path(sh, path);
if (c && c->path_next) {
*ambiguous = true;
return NULL;
}
return c ? c->qn : NULL;
}
const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path) {
@@ -481,9 +615,12 @@ const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path) {
while (prefix[0]) {
const char *cand =
cbm_arena_sprintf(ctx->arena, "%s.%s", ruby_dotted(ctx->arena, prefix), path);
const char *qn = ruby_class_qn_by_path(ctx, cand);
bool ambiguous = false;
const char *qn = ruby_class_qn_by_path(ctx, cand, &ambiguous);
if (qn)
return qn;
if (ambiguous)
return NULL; /* declared here in several other roots: fail closed */
char *last_dot = strrchr(prefix, '.');
if (last_dot)
*last_dot = '\0';
@@ -491,10 +628,15 @@ const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path) {
prefix[0] = '\0';
}
}
const char *qn = ruby_class_qn_by_path(ctx, path);
bool ambiguous = false;
const char *qn = ruby_class_qn_by_path(ctx, path, &ambiguous);
if (qn)
return qn;
/* Stdlib types are keyed by their dotted bare path. */
/* Stdlib types are keyed by their dotted bare path. A top-level constant
* several roots declare and stdlib also has is a reopening of that one
* global class (`class String` patched in two gems), so stdlib still
* answers; without a stdlib type an ambiguous constant stays unresolved. */
(void)ambiguous;
const CBMRegisteredType *t = cbm_registry_lookup_type(ctx->registry, path);
if (t)
return t->qualified_name;
@@ -506,17 +648,26 @@ const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path) {
/* Depth cap shared by the instance/singleton lookup walks. */
#define RUBY_LOOKUP_MAX_DEPTH CBM_LSP_MAX_LOOKUP_DEPTH
/* Own instance method of one exact class (no ancestry walk). */
/* Own method of one exact class (no ancestry walk), instance or singleton
* ("<qn>.self" receiver key). Against the project table every reopening's
* methods are registered under the merged record's QN, so a class reopened in
* any number of files is still one probe. */
static const CBMRegisteredFunc *ruby_own_method(RubyLSPContext *ctx, const char *class_qn,
const char *method_name, bool singleton) {
const RubyClassInfo *head = ruby_shared_head(ctx->shared, class_qn);
const char *owner = head ? head->qn : class_qn;
const char *key = singleton ? cbm_arena_sprintf(ctx->arena, "%s.self", owner) : owner;
return cbm_registry_lookup_method(ctx->registry, key, method_name);
}
static const CBMRegisteredFunc *ruby_own_instance_method(RubyLSPContext *ctx, const char *class_qn,
const char *method_name) {
return cbm_registry_lookup_method(ctx->registry, class_qn, method_name);
return ruby_own_method(ctx, class_qn, method_name, false);
}
/* Own singleton method of one exact class ("<qn>.self" receiver key). */
static const CBMRegisteredFunc *ruby_own_singleton_method(RubyLSPContext *ctx, const char *class_qn,
const char *method_name) {
const char *key = cbm_arena_sprintf(ctx->arena, "%s.self", class_qn);
return cbm_registry_lookup_method(ctx->registry, key, method_name);
return ruby_own_method(ctx, class_qn, method_name, true);
}
/* Fail-closed ancestry. Every lookup below carries a `blocked` flag that is
@@ -540,6 +691,12 @@ typedef struct {
unsigned int stamp;
} RubyLookupWalk;
typedef struct RubySharedMark {
int index; /* shared class index + 1; 0 = empty slot */
unsigned int seen_instance;
unsigned int seen_singleton;
} RubySharedMark;
static RubyLookupWalk ruby_walk_begin(RubyLSPContext *ctx) {
if (++ctx->lookup_stamp == 0) {
/* Wrapped: clear every mark so no class looks visited. */
@@ -547,22 +704,74 @@ static RubyLookupWalk ruby_walk_begin(RubyLSPContext *ctx) {
ctx->classes[i].seen_instance = 0;
ctx->classes[i].seen_singleton = 0;
}
for (int i = 0; i < ctx->shared_mark_cap; i++) {
ctx->shared_marks[i].seen_instance = 0;
ctx->shared_marks[i].seen_singleton = 0;
}
ctx->lookup_stamp = 1;
}
RubyLookupWalk w = {false, ctx->lookup_stamp};
return w;
}
static unsigned ruby_mark_slot(int index, int cap) {
return ((unsigned)index * 2654435761u) & (unsigned)(cap - 1);
}
/* The mark pair for shared entry `index` (0-based), inserting it on first
* touch. NULL only when the arena is exhausted. */
static RubySharedMark *ruby_shared_mark(RubyLSPContext *ctx, int index) {
if ((ctx->shared_mark_count + 1) * 2 > ctx->shared_mark_cap) {
int newcap = ctx->shared_mark_cap ? ctx->shared_mark_cap * 2 : 16;
RubySharedMark *nm =
(RubySharedMark *)cbm_arena_alloc(ctx->arena, (size_t)newcap * sizeof(RubySharedMark));
if (!nm)
return NULL;
memset(nm, 0, (size_t)newcap * sizeof(RubySharedMark));
for (int i = 0; i < ctx->shared_mark_cap; i++) {
if (!ctx->shared_marks[i].index)
continue;
unsigned j = ruby_mark_slot(ctx->shared_marks[i].index, newcap);
while (nm[j].index)
j = (j + 1) & (unsigned)(newcap - 1);
nm[j] = ctx->shared_marks[i];
}
ctx->shared_marks = nm;
ctx->shared_mark_cap = newcap;
}
unsigned j = ruby_mark_slot(index + 1, ctx->shared_mark_cap);
while (ctx->shared_marks[j].index) {
if (ctx->shared_marks[j].index == index + 1)
return &ctx->shared_marks[j];
j = (j + 1) & (unsigned)(ctx->shared_mark_cap - 1);
}
ctx->shared_marks[j].index = index + 1;
ctx->shared_mark_count++;
return &ctx->shared_marks[j];
}
/* Marks `class_qn` searched on one side (instance or singleton) in this walk;
* true when it already was. Only the file's class table is marked: mixins
* and superclass refs are recorded for those classes alone, so a type outside
* the table (a stdlib type) has nothing to expand and is never a repeat. */
* true when it already was. This file's own entries carry their marks inline;
* entries of the shared table are read-only, so theirs live in the per-file
* hash. A type in neither (a stdlib type) has nothing to expand and is never
* a repeat. */
static bool ruby_walk_seen(RubyLSPContext *ctx, RubyLookupWalk *w, const char *class_qn,
bool singleton) {
RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
if (!ci)
return false;
unsigned int *mark = singleton ? &ci->seen_singleton : &ci->seen_instance;
unsigned int *mark = NULL;
for (int i = 0; i < ctx->class_count && !mark; i++) {
if (strcmp(ctx->classes[i].qn, class_qn) == 0)
mark = singleton ? &ctx->classes[i].seen_singleton : &ctx->classes[i].seen_instance;
}
if (!mark) {
const CBMRubyCrossRegistry *sh = ctx->shared;
const RubyClassInfo *c = ruby_shared_find(sh, sh ? sh->by_qn : NULL, class_qn);
if (!c)
return false;
RubySharedMark *m = ruby_shared_mark(ctx, (int)(c - sh->classes));
if (!m)
return false;
mark = singleton ? &m->seen_singleton : &m->seen_instance;
}
if (*mark == w->stamp)
return true;
*mark = w->stamp;
@@ -577,7 +786,7 @@ static const CBMRegisteredFunc *ruby_lookup_instance_method_depth(RubyLSPContext
/* True when the class declares a superclass the finalize step could not
* resolve (stdlib-seeded conventions like ApplicationRecord DO resolve). */
static bool ruby_superclass_unresolved(RubyLSPContext *ctx, const char *class_qn) {
RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
const RubyClassInfo *ci = ruby_effective_class(ctx, class_qn);
return ci && ci->superclass_ref && !ci->superclass_qn;
}
@@ -600,6 +809,23 @@ static const CBMRegisteredFunc *ruby_lookup_in_mixins(RubyLSPContext *ctx, const
if (f || w->blocked)
return f;
}
/* A class reopened in other files: those files' mixins are in the merged
* record, so a module one of them includes still shadows the superclass. */
const CBMRubyCrossRegistry *sh = ctx->shared;
const RubyClassInfo *head = ruby_shared_head(sh, owner_qn);
for (int i = head ? head->mixin_n - 1 : -1; i >= 0; i--) {
const RubyMixinInfo *mi = &sh->mixins[head->mixin_start + i];
if (mi->kind != kind)
continue;
if (!mi->module_qn) {
w->blocked = true;
return NULL;
}
const CBMRegisteredFunc *f =
ruby_lookup_instance_method_depth(ctx, mi->module_qn, method_name, depth + 1, w);
if (f || w->blocked)
return f;
}
return NULL;
}
@@ -696,6 +922,32 @@ const CBMRegisteredFunc *ruby_lookup_singleton_method(RubyLSPContext *ctx, const
/* ── ActiveRecord model detection (typing special case) ─────────── */
/* Whether the finder rule (`User.find` -> User, relation chains keep the
* model) also fires for a model declared in ANOTHER file, which is the usual
* Rails layout. Off for now, so the rule keeps to models declared in the file
* being resolved and nothing else changes. Across files it mostly meets
* relation chains, and `Model.where(...).m` reaches the relation or the
* model's class methods in Ruby, never an instance method `m`; a judged sample
* of the cross-file edges came in below the 95% precision bar. Turn it on once
* relations are typed apart from records. */
static bool ruby_ar_finder_cross_file = false;
#ifdef CBM_ENABLE_TEST_SEAMS
bool cbm_ruby_set_ar_finder_cross_file(bool on) {
bool prev = ruby_ar_finder_cross_file;
ruby_ar_finder_cross_file = on;
return prev;
}
#endif
static bool ruby_class_declared_here(const RubyLSPContext *ctx, const char *qn) {
for (int i = 0; i < ctx->class_count; i++) {
if (strcmp(ctx->classes[i].qn, qn) == 0)
return true;
}
return false;
}
/* True when class_qn's superclass chain reaches ActiveRecord::Base (or the
* conventional ApplicationRecord intermediary, which per-file extraction
* usually cannot see through). */
@@ -704,7 +956,9 @@ static bool ruby_is_ar_model(RubyLSPContext *ctx, const char *class_qn, int dept
return false;
if (strcmp(class_qn, "ActiveRecord.Base") == 0 || strcmp(class_qn, "ApplicationRecord") == 0)
return true;
RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
if (!ruby_ar_finder_cross_file && !ruby_class_declared_here(ctx, class_qn))
return false;
const RubyClassInfo *ci = ruby_effective_class(ctx, class_qn);
if (ci && ci->superclass_ref &&
(strcmp(ci->superclass_ref, "ApplicationRecord") == 0 ||
strcmp(ci->superclass_ref, "ActiveRecord.Base") == 0))
@@ -1822,3 +2076,429 @@ void cbm_run_ruby_lsp(CBMArena *arena, CBMFileResult *result, const char *source
cbm_arena_destroy(&idx_arena);
}
/* ── cross-file: shared registry ────────────────────────────────── */
extern const TSLanguage *tree_sitter_ruby(void);
/* Raw spelling of a cross-file class def below its module: the part of its QN
* after the module QN ("proj.app.models.user.Admin.Sub::User" with module
* "proj.app.models.user" → "Admin.Sub::User"), i.e. the extractor's frames
* joined by '.', each frame as written. NULL when the shape is odd. */
static const char *ruby_cross_class_suffix(const CBMLSPDef *d) {
if (!d->qualified_name)
return NULL;
if (d->def_module_qn && d->def_module_qn[0]) {
size_t mlen = strlen(d->def_module_qn);
if (strncmp(d->qualified_name, d->def_module_qn, mlen) == 0 &&
d->qualified_name[mlen] == '.') {
return d->qualified_name + mlen + 1;
}
}
return d->short_name;
}
/* The superclass a class def carries (first "|"-separated base, since Ruby
* has single inheritance; a legacy "< Base" spelling is tolerated), in the
* dotted form constant lookup uses. NULL when none. */
static const char *ruby_def_superclass_ref(CBMArena *arena, const CBMLSPDef *d) {
if (!d->embedded_types || !d->embedded_types[0])
return NULL;
const char *start = d->embedded_types;
while (*start == '<' || *start == ' ' || *start == '\t')
start++;
const char *bar = strchr(start, '|');
char *raw = bar ? cbm_arena_strndup(arena, start, (size_t)(bar - start))
: cbm_arena_strdup(arena, start);
if (!raw || !raw[0])
return NULL;
return ruby_dotted(arena, raw);
}
/* Insert entry `idx` (already stored in sh->classes) into one hash index. */
/* Insert entry `idx` into the QN index. */
static void ruby_shared_insert_qn(CBMRubyCrossRegistry *sh, int idx) {
unsigned i = ruby_hash(sh->classes[idx].qn) & sh->slot_mask;
while (sh->by_qn[i])
i = (i + 1) & sh->slot_mask;
sh->by_qn[i] = idx + 1;
}
typedef struct {
int head; /* owning merged record (table index) */
int cls; /* declaring entry (table index) */
const char *decl_qn; /* its QN, the canonical order key */
int seq; /* position among that declaration's macros */
RubyMixinKind kind;
const char *ref; /* dotted constant */
} RubyMixinTmp;
static int ruby_mixin_tmp_cmp(const void *a, const void *b) {
const RubyMixinTmp *x = (const RubyMixinTmp *)a;
const RubyMixinTmp *y = (const RubyMixinTmp *)b;
if (x->head != y->head)
return x->head < y->head ? -1 : 1;
int c = strcmp(x->decl_qn, y->decl_qn);
return c ? c : x->seq - y->seq;
}
/* Resolve every declaration's include/prepend/extend macros once, from the
* scope that declared them, into the merged record of their constant, so a
* class's mixins are visible from every file. Order is canonical (declaring QN,
* then source order), so it does not depend on def order. An unresolvable
* module keeps module_qn NULL: lookups then fail closed. */
static bool ruby_build_shared_mixins(CBMRubyCrossRegistry *sh, CBMArena *arena, RubyLSPContext *ctx,
const char **decl_mixins, const char **body_nesting) {
int total = 0;
for (int i = 0; i < sh->class_count; i++) {
if (!decl_mixins[i])
continue;
total++;
for (const char *p = decl_mixins[i]; *p; p++)
if (*p == '|')
total++;
}
if (!total)
return true;
RubyMixinTmp *tmp = (RubyMixinTmp *)cbm_arena_alloc(arena, (size_t)total * sizeof(*tmp));
if (!tmp)
return false;
int n = 0;
for (int i = 0; i < sh->class_count; i++) {
const char *p = decl_mixins[i];
int seq = 0;
while (p && *p) {
const char *end = strchr(p, '|');
size_t len = end ? (size_t)(end - p) : strlen(p);
if (len > 2 && p[1] == ':' && (p[0] == 'i' || p[0] == 'p' || p[0] == 'e') &&
n < total) {
tmp[n].head = sh->classes[i].group_head - 1;
tmp[n].cls = i;
tmp[n].decl_qn = sh->classes[i].qn;
tmp[n].seq = seq++;
tmp[n].kind = p[0] == 'i' ? RUBY_MIXIN_INCLUDE
: p[0] == 'p' ? RUBY_MIXIN_PREPEND
: RUBY_MIXIN_EXTEND;
tmp[n].ref = ruby_dotted(arena, cbm_arena_strndup(arena, p + 2, len - 2));
n++;
}
p = end ? end + 1 : NULL;
}
}
if (!n)
return true;
qsort(tmp, (size_t)n, sizeof(*tmp), ruby_mixin_tmp_cmp);
sh->mixins = (RubyMixinInfo *)cbm_arena_alloc(arena, (size_t)n * sizeof(RubyMixinInfo));
if (!sh->mixins)
return false;
for (int i = 0; i < n; i++) {
RubyClassInfo *head = &sh->classes[tmp[i].head];
if (head->mixin_n == 0)
head->mixin_start = i;
head->mixin_n++;
RubyMixinInfo *mi = &sh->mixins[i];
memset(mi, 0, sizeof(*mi));
mi->owner_qn = head->qn;
mi->module_ref = tmp[i].ref;
mi->kind = tmp[i].kind;
ctx->nesting = body_nesting[tmp[i].cls];
ctx->caller_root = sh->classes[tmp[i].cls].root;
mi->module_qn = ruby_resolve_constant(ctx, tmp[i].ref);
}
sh->mixin_count = n;
return true;
}
/* Slot of (root, path) in the by-path index, or -1 when absent. */
static int ruby_shared_path_slot(const CBMRubyCrossRegistry *sh, const char *root,
const char *path) {
unsigned i = ruby_hash_root_path(root, path) & sh->slot_mask;
while (sh->by_path[i]) {
CBM_LSP_WORK(1);
const RubyClassInfo *c = &sh->classes[sh->by_path[i] - 1];
if (strcmp(c->root, root) == 0 && strcmp(c->path, path) == 0)
return (int)i;
i = (i + 1) & sh->slot_mask;
}
return -1;
}
/* Descending QN order: the registry answers a repeated name with the entry
* registered last, so registering the largest QN first makes the smallest win. */
static int ruby_def_qn_cmp(const void *a, const void *b) {
const CBMLSPDef *x = *(const CBMLSPDef *const *)a;
const CBMLSPDef *y = *(const CBMLSPDef *const *)b;
return strcmp(y->qualified_name, x->qualified_name);
}
CBMRubyCrossRegistry *cbm_ruby_build_cross_registry(CBMArena *arena, CBMLSPDef *defs,
int def_count) {
if (!arena)
return NULL;
CBMRubyCrossRegistry *sh = (CBMRubyCrossRegistry *)cbm_arena_alloc(arena, sizeof(*sh));
if (!sh)
return NULL;
memset(sh, 0, sizeof(*sh));
cbm_registry_init(&sh->reg, arena);
cbm_ruby_stdlib_register(&sh->reg, arena);
int max_classes = 0;
for (int i = 0; i < def_count; i++) {
const CBMLSPDef *d = &defs[i];
if (d->lang == CBM_LANG_RUBY && d->label &&
(strcmp(d->label, "Class") == 0 || strcmp(d->label, "Module") == 0))
max_classes++;
}
unsigned slots = 16;
while (slots < (unsigned)max_classes * 2u)
slots <<= 1;
sh->slot_mask = slots - 1;
sh->by_qn = (int *)cbm_arena_alloc(arena, slots * sizeof(int));
sh->by_path = (int *)cbm_arena_alloc(arena, slots * sizeof(int));
sh->by_pp = (int *)cbm_arena_alloc(arena, slots * sizeof(int));
sh->classes = (RubyClassInfo *)cbm_arena_alloc(arena, (size_t)(max_classes ? max_classes : 1) *
sizeof(RubyClassInfo));
const char **decl_nesting = (const char **)cbm_arena_alloc(
arena, (size_t)(max_classes ? max_classes : 1) * sizeof(const char *));
/* Per entry: the raw mixin macros and the full nesting its body resolves
* them in. */
const char **decl_mixins = (const char **)cbm_arena_alloc(
arena, (size_t)(max_classes ? max_classes : 1) * sizeof(const char *));
const char **body_nesting = (const char **)cbm_arena_alloc(
arena, (size_t)(max_classes ? max_classes : 1) * sizeof(const char *));
if (!sh->by_qn || !sh->by_path || !sh->by_pp || !sh->classes || !decl_nesting || !decl_mixins ||
!body_nesting)
return NULL;
memset(sh->by_qn, 0, slots * sizeof(int));
memset(sh->by_path, 0, slots * sizeof(int));
memset(sh->by_pp, 0, slots * sizeof(int));
/* Ruby constants live in one global namespace, so every project class is
* a resolution candidate. Pass A: one entry per declaration, and per
* constant path the entry with the smallest QN becomes the group head, so
* the head does not depend on def order (a full build and the incremental
* closure route order defs differently). */
for (int i = 0; i < def_count; i++) {
CBMLSPDef *d = &defs[i];
if (!d->qualified_name || !d->short_name || !d->label || d->lang != CBM_LANG_RUBY)
continue;
if (strcmp(d->label, "Class") != 0 && strcmp(d->label, "Module") != 0)
continue;
const char *suffix = ruby_cross_class_suffix(d);
if (!suffix)
continue;
if (ruby_shared_find(sh, sh->by_qn, d->qualified_name))
continue; /* the same class body seen again — one entry per QN */
const char *path = ruby_dotted(arena, suffix);
int n = sh->class_count++;
RubyClassInfo *ci = &sh->classes[n];
memset(ci, 0, sizeof(*ci));
ci->path = path;
ci->root = ruby_package_root(arena, d->def_module_qn);
ci->qn = d->qualified_name;
ci->is_module = strcmp(d->label, "Module") == 0;
if (!ci->is_module)
ci->superclass_ref = ruby_def_superclass_ref(arena, d);
/* Declaring scope = every frame but the last; the superclass is
* resolved from there, as in the per-file pass. */
const char *last = strrchr(suffix, '.');
decl_nesting[n] = last ? cbm_arena_strndup(arena, suffix, (size_t)(last - suffix)) : "";
decl_mixins[n] = d->mixin_refs;
body_nesting[n] = suffix;
ruby_shared_insert_qn(sh, n);
int slot = ruby_shared_path_slot(sh, ci->root, path);
if (slot < 0) {
unsigned h = ruby_hash_root_path(ci->root, path) & sh->slot_mask;
while (sh->by_path[h])
h = (h + 1) & sh->slot_mask;
sh->by_path[h] = n + 1;
} else if (strcmp(ci->qn, sh->classes[sh->by_path[slot] - 1].qn) < 0)
sh->by_path[slot] = n + 1;
}
for (int i = 0; i < sh->class_count; i++) {
RubyClassInfo *ci = &sh->classes[i];
ci->group_head = sh->by_path[ruby_shared_path_slot(sh, ci->root, ci->path)];
}
/* Heads sharing a constant path across package roots, chained from one
* by_pp entry, so a lookup can tell "one root" from "several". A later
* head is linked right after the first one, O(1) per head: the only
* reader asks whether a second head exists, so the order behind the
* first does not matter (no tail walk, per the LSP registry checklist). */
for (int i = 0; i < sh->class_count; i++) {
if (sh->classes[i].group_head != i + 1)
continue;
unsigned h = ruby_hash(sh->classes[i].path) & sh->slot_mask;
bool placed = false;
while (sh->by_pp[h]) {
RubyClassInfo *first = &sh->classes[sh->by_pp[h] - 1];
if (strcmp(first->path, sh->classes[i].path) == 0) {
sh->classes[i].path_next = first->path_next;
first->path_next = i + 1;
placed = true;
break;
}
h = (h + 1) & sh->slot_mask;
}
if (!placed)
sh->by_pp[h] = i + 1;
}
/* Pass B: methods, in a fixed QN order so a name defined by two reopenings
* resolves to the smallest QN whatever the def order. Each registers under its
* group head's QN (the merged record), so a lookup is one probe however
* many files reopen the class; the def keeps its own file's QN. A method
* registers on exactly one key: the instance key, or "<qn>.self" for a
* `def self.m` / `class << self` method. Registering on both would let an
* instance call hit a singleton method of the same name and stop there,
* never reaching the inherited instance method Ruby would call. */
CBMLSPDef **fdefs = (CBMLSPDef **)cbm_arena_alloc(arena, (size_t)(def_count ? def_count : 1) *
sizeof(CBMLSPDef *));
if (!fdefs)
return NULL;
int fcount = 0;
for (int i = 0; i < def_count; i++) {
CBMLSPDef *d = &defs[i];
if (d->qualified_name && d->short_name && d->label && d->lang == CBM_LANG_RUBY &&
(strcmp(d->label, "Function") == 0 || strcmp(d->label, "Method") == 0))
fdefs[fcount++] = d;
}
qsort(fdefs, (size_t)fcount, sizeof(fdefs[0]), ruby_def_qn_cmp);
for (int i = 0; i < fcount; i++) {
const CBMLSPDef *d = fdefs[i];
const RubyClassInfo *owner = ruby_shared_head(sh, d->receiver_type);
const char *receiver = owner ? owner->qn : d->receiver_type;
CBMRegisteredFunc rf;
memset(&rf, 0, sizeof(rf));
rf.min_params = -1;
rf.qualified_name = d->qualified_name;
rf.short_name = d->short_name;
rf.receiver_type =
receiver && d->is_singleton ? cbm_arena_sprintf(arena, "%s.self", receiver) : receiver;
const CBMType **rets =
(const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
if (rets) {
rets[0] = cbm_type_unknown();
rets[1] = NULL;
}
rf.signature = cbm_type_func(arena, NULL, NULL, rets);
cbm_registry_add_func(&sh->reg, rf);
}
cbm_registry_finalize(&sh->reg);
sh->reg.read_only = true; /* sealed: shared across resolve workers */
/* Resolve each superclass against the complete table, once, from the
* scope that declared it. */
RubyLSPContext ctx;
ruby_lsp_init(&ctx, arena, "", 0, &sh->reg, NULL, NULL);
ctx.shared = sh;
for (int i = 0; i < sh->class_count; i++) {
RubyClassInfo *ci = &sh->classes[i];
if (!ci->superclass_ref)
continue;
ctx.nesting = decl_nesting[i];
ctx.caller_root = ci->root;
ci->superclass_qn = ruby_resolve_constant(&ctx, ci->superclass_ref);
}
/* The merged record's superclass comes from the smallest-QN declaration
* that has one, when the head itself declares none. */
int *provider = (int *)cbm_arena_alloc(arena, (size_t)(sh->class_count ? sh->class_count : 1) *
sizeof(int));
if (!provider)
return NULL;
for (int i = 0; i < sh->class_count; i++)
provider[i] = -1;
for (int i = 0; i < sh->class_count; i++) {
const RubyClassInfo *ci = &sh->classes[i];
int h = ci->group_head - 1;
if (!ci->superclass_ref || sh->classes[h].superclass_ref)
continue;
if (provider[h] < 0 || strcmp(ci->qn, sh->classes[provider[h]].qn) < 0)
provider[h] = i;
}
for (int h = 0; h < sh->class_count; h++) {
if (provider[h] < 0)
continue;
sh->classes[h].superclass_ref = sh->classes[provider[h]].superclass_ref;
sh->classes[h].superclass_qn = sh->classes[provider[h]].superclass_qn;
}
if (!ruby_build_shared_mixins(sh, arena, &ctx, decl_mixins, body_nesting))
return NULL;
return sh;
}
/* ── cross-file: per-file entry ─────────────────────────────────── */
void cbm_run_ruby_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
const char *module_qn, const CBMRubyCrossRegistry *shared,
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
CBMResolvedCallArray *out) {
if (!arena || !source || !out || !shared)
return;
RubyLSPContext ctx;
ruby_lsp_init(&ctx, arena, source, source_len, &shared->reg, module_qn, out);
ctx.shared = shared;
ctx.caller_root = ruby_package_root(arena, module_qn);
ctx.import_names = import_names;
ctx.import_qns = import_qns;
ctx.import_count = import_count;
/* Parse if the pipeline didn't hand us a cached tree. */
TSTree *tree = cached_tree;
bool owns_tree = false;
if (!tree) {
TSParser *parser = ts_parser_new();
if (!parser)
return;
const TSLanguage *lang = tree_sitter_ruby();
if (!ts_parser_set_language(parser, lang)) {
ts_parser_delete(parser);
return;
}
tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)source_len);
ts_parser_delete(parser);
if (!tree)
return;
owns_tree = true;
}
TSNode root = ts_tree_root_node(tree);
/* PASS 1 over this file's AST only: its own classes, mixins and
* nesting-packed superclass refs. build_reg stays NULL — methods and every
* other file's classes come from the shared registry, which is never
* written. */
ruby_pass1_scan(&ctx, root);
ruby_finalize_refs(&ctx);
/* PASS 1.5 + PASS 2. */
ctx.nesting = "";
ctx.enclosing_class_qn = NULL;
ruby_ivar_scan(&ctx, root);
ctx.nesting = "";
ctx.enclosing_class_qn = NULL;
ctx.enclosing_func_qn = NULL;
ctx.in_singleton_method = false;
ruby_resolve_calls_in_node(&ctx, root);
if (owns_tree)
ts_tree_delete(tree);
}
void cbm_run_ruby_lsp_cross(CBMArena *arena, const char *source, int source_len,
const char *module_qn, CBMLSPDef *defs, int def_count,
const char **import_names, const char **import_qns, int import_count,
TSTree *cached_tree, CBMResolvedCallArray *out) {
if (!arena || !source || !out)
return;
CBMArena build;
cbm_arena_init(&build);
CBMRubyCrossRegistry *sh = cbm_ruby_build_cross_registry(&build, defs, def_count);
if (sh) {
cbm_run_ruby_lsp_cross_with_registry(arena, source, source_len, module_qn, sh, import_names,
import_qns, import_count, cached_tree, out);
}
cbm_arena_destroy(&build);
}
+95 -1
View File
@@ -5,6 +5,7 @@
#include "scope.h"
#include "type_registry.h"
#include "../cbm.h"
#include "go_lsp.h" /* CBMLSPDef reused across languages */
/* Ruby mixin kinds. Lookup order for an instance method on class C:
* prepended modules (last prepended first) → C's own methods →
@@ -33,12 +34,34 @@ typedef struct {
const char *superclass_ref; /* raw dotted superclass spelling, or NULL */
const char *superclass_qn; /* resolved QN (table/stdlib), or NULL */
bool is_module; /* `module` (mixin source) vs `class` */
/* Shared (project-wide) table only. A class reopened in another file has
* a different QN there (the QN carries the file's module QN) but the same
* constant path. All declarations of one path share one merged record: the
* entry with the smallest QN (the group head), which holds every
* reopening's methods and the superclass. `group_head` is the head's table
* index + 1 (the entry's own index + 1 for the head itself); 0 in a
* per-file table. */
int group_head;
/* Shared table only: the package root this declaration sits in ("" when
* it has none; see ruby_package_root), and, on a head, the next head
* (table index + 1) with the same constant path in another root. Two
* packages of one repository can each declare their own `Topic`; the
* merged record is per (root, path) so they are never pooled. */
const char *root;
int path_next;
/* Head entries only: this constant's include/prepend/extend records, a
* range of the registry's `mixins` array (all reopenings, in declaring-QN
* then source order). */
int mixin_start;
int mixin_n;
/* Method-lookup visit marks: the stamp of the last walk that searched
* this class on the instance / singleton side (ruby_walk_seen). */
unsigned int seen_instance;
unsigned int seen_singleton;
} RubyClassInfo;
struct CBMRubyCrossRegistry;
/* One `include`/`prepend`/`extend` record: owner class QN → module ref. */
typedef struct {
const char *owner_qn; /* class/module whose body held the call */
@@ -88,7 +111,15 @@ typedef struct {
* [A::B] only, so A's constants are NOT probed. */
const char *nesting;
/* Class/module table (pass 1). */
/* Project-wide read-only class table + method registry (cross-file
* resolution). NULL for per-file extraction. Consulted after this file's
* own table, so a class declared here always wins. */
const struct CBMRubyCrossRegistry *shared;
/* Package root of the file being resolved ("" = none); picks which
* root's classes a shared-table constant lookup prefers. */
const char *caller_root;
/* Class/module table (pass 1) — this file's own declarations only. */
RubyClassInfo *classes;
int class_count;
int class_cap;
@@ -137,6 +168,14 @@ typedef struct {
* so marks left by earlier walks never match. */
unsigned int lookup_stamp;
/* Visit marks for entries of the shared (read-only) class table. The table
* is read by every resolve worker at once, so a walk never marks it; its
* marks live here, in an open-addressing hash keyed by the shared index and
* sized by what this file touches. */
struct RubySharedMark *shared_marks;
int shared_mark_cap;
int shared_mark_count;
/* Debug mode (CBM_LSP_DEBUG env). */
bool debug;
} RubyLSPContext;
@@ -173,4 +212,59 @@ void cbm_run_ruby_lsp(CBMArena *arena, CBMFileResult *result, const char *source
* (ActiveRecord/ActiveSupport/ActionController) into a registry. */
void cbm_ruby_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
/* --- Cross-file LSP resolution ---
*
* Ruby constants live in one global namespace and Rails/Zeitwerk autoloads
* them with no require, so a file may name any class in the project. The
* project's definitions are therefore indexed ONCE (cbm_ruby_build_cross_
* registry) into a sealed, read-only registry: a finalized method registry
* plus a hashed class table. Each file then resolves against it with O(1)
* lookups and builds nothing proportional to the project. */
typedef struct CBMRubyCrossRegistry {
CBMTypeRegistry reg; /* stdlib + every project method; finalized, sealed */
RubyClassInfo *classes;
int class_count;
/* Open-addressing hash indexes over `classes` (values are index + 1, 0 =
* empty slot): by QN, and by dotted constant path (group head only). */
int *by_qn;
int *by_path; /* (package root, path) -> group head */
int *by_pp; /* path alone -> first head; the rest chain via path_next */
unsigned slot_mask;
RubyMixinInfo *mixins; /* owner_qn = the merged record's QN; grouped by head */
int mixin_count;
} CBMRubyCrossRegistry;
#ifdef CBM_ENABLE_TEST_SEAMS
/* Test seam: turn the cross-file half of the ActiveRecord finder rule on or
* off (see ruby_ar_finder_cross_file in ruby_lsp.c). Returns the previous
* setting, so a test restores what it found rather than a fixed value. */
bool cbm_ruby_set_ar_finder_cross_file(bool on);
#endif
/* Build the shared registry from every project def. Strings are borrowed from
* `defs` (as the other languages' cross registries do) or copied into `arena`.
* Returns NULL on allocation failure; callers then fall back to the
* per-file path. */
CBMRubyCrossRegistry *cbm_ruby_build_cross_registry(CBMArena *arena, CBMLSPDef *defs,
int def_count);
/* Resolve one file against a prebuilt shared registry. Reads `shared` only;
* everything it allocates lives in `arena`. */
void cbm_run_ruby_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
const char *module_qn, const CBMRubyCrossRegistry *shared,
const char **import_names, const char **import_qns,
int import_count,
TSTree *cached_tree, /* NULL = parse internally */
CBMResolvedCallArray *out);
/* Convenience for callers with a def list but no prebuilt registry (the
* per-file fallback path and tests): builds a registry in a scratch arena for
* this one call. Cost is proportional to the def list, so the pipeline uses
* the prebuilt path instead. */
void cbm_run_ruby_lsp_cross(CBMArena *arena, const char *source, int source_len,
const char *module_qn, CBMLSPDef *defs, int def_count,
const char **import_names, const char **import_qns, int import_count,
TSTree *cached_tree, /* NULL = parse internally */
CBMResolvedCallArray *out);
#endif /* CBM_LSP_RUBY_LSP_H */
+2
View File
@@ -282,6 +282,7 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) {
cr_str(c, &d->decl_namespace);
cr_str(c, &d->variant_key);
cr_str(c, &d->alias_target);
cr_str(c, &d->mixin_refs);
/* The type-facts record: one record, then its strings. */
cr_array(c, (void **)&d->type_facts, d->type_facts ? 1 : 0, sizeof(CBMDefTypeFacts));
CBMDefTypeFacts *facts = (CBMDefTypeFacts *)d->type_facts;
@@ -639,6 +640,7 @@ void cbm_result_compact(CBMFileResult *result) {
tmp.diagram_arrows.cap = tmp.diagram_arrows.count;
tmp.field_types.cap = tmp.field_types.count;
tmp.doc_links.cap = tmp.doc_links.count;
tmp.scope.cap = tmp.scope.count;
/* A composite kept its per-unit results only so shallow-copied strings
* stayed valid; every string is now a copy of its own. */
+7 -5
View File
@@ -11,6 +11,7 @@ The grammars were originally vendored as bare `parser.c`+`scanner.c` with **no r
- Grammars: **164** — vendored-from-upstream: **138**, first-party/self-maintained: **21**, registry-disagreement: **5** (nim removed 2026-06-12; objectscript_udl + objectscript_routine added 2026-06-24; mojo added 2026-07-01; arkts added 2026-08-26; plsql added 2026-08-27; chialisp added 2026-08-28; javascript + tsx became self-maintained forks 2026-09-25; pascal became a self-maintained fork 2026-09-25; vbnet added as a self-maintained fork 2026-11-10; sql became a self-maintained fork 2026-11-11; vba added as a self-maintained fork 2026-11-12 — see notes below)
- ABI distribution: **9×** ABI-13 **78×** ABI-14 **77×** ABI-15 (runtime ceiling is ABI 15; never vendor ABI 16 without a runtime upgrade)
— recounted from the tree 2026-11-13 after the `objectscript_udl` / `objectscript_routine` refresh to upstream v1.11.0: unchanged (both stay ABI 15).
— recounted from the tree 2026-11-12 after adding the ABI-15 `vba` grammar (was `9×/78×/76×`; the `sql` fork regenerated 2026-11-11 stayed ABI 15).
— recounted from the tree 2026-11-10 after adding the ABI-15 `vbnet` grammar (was `9×/78×/75×`); the `haskell` fork (#2547) keeps that grammar's ABI 15, so the merge of the two leaves the ABI line unchanged.
— recounted from the tree 2026-09-25 after the tsx fork was regenerated with tree-sitter-cli 0.25.10, moving `tsx` from ABI 14 to ABI 15 (was `9×/79×/74×`).
@@ -52,7 +53,7 @@ The grammars were originally vendored as bare `parser.c`+`scanner.c` with **no r
newlines; the new files keep upstream's bytes exactly. Per-file SHA-256
values are pinned in `scripts/vendored-checksums.txt`. Regression coverage:
the `cs_*_issue1748` tests in `tests/test_parse_coverage.c`.
- **objectscript_udl / objectscript_routine** (added 2026-06-24): vendored from [intersystems/tree-sitter-objectscript](https://github.com/intersystems/tree-sitter-objectscript) @ `a7ffcdf` — MIT, the InterSystems-official grammars (a niche vendor language, hence `vendor-maintained`, not in nvim-treesitter/Helix). **Re-vendor note:** each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` (a verbatim copy of upstream `common/scanner.h`), because this repo's shared `vendored/common/scanner.h` belongs to the cfml/fsharp grammars and differs. The generated `parser.c` files remain byte-for-byte upstream. Each `scanner.c` also guards empty-state deserialization with `if (length > 0)` before `memcpy`, because Tree-sitter can pass a NULL buffer with zero length. On re-vendor, re-apply the include rename and this guard unless upstream already carries them. **Local modification (2026-07-16):** in `objectscript_common.h`, two loop counters `uint8_t i` were widened to `int i` (the `reverse_marker` scan and the `html_marker_buffer` reversal) to clear CodeQL `cpp/comparison-with-wider-type` — a false positive in practice (both lengths are hard-bounded by `MARKER_BUFFER_MAX_LEN = 30`, so `uint8_t` could never wrap), fixed for cleanliness. On re-vendor, re-apply this widening too (or upstream it at intersystems/tree-sitter-objectscript).
- **objectscript_udl / objectscript_routine** (added 2026-06-24 @ `a7ffcdf`; refreshed 2026-11-13, #1261): vendored from [intersystems/tree-sitter-objectscript](https://github.com/intersystems/tree-sitter-objectscript) tag `v1.11.0`, full commit `25cf0f67a3804727e250076a0926aa71c46fffab` (upstream `main` HEAD, ABI 15 unchanged), replacing `a7ffcdf2de8e` — MIT, (c) 2025 InterSystems Corporation, the InterSystems-official grammars (a niche vendor language, hence `vendor-maintained`, not in nvim-treesitter/Helix). Upstream `udl/src` maps to `objectscript_udl/`, `objectscript_routine/src` to `objectscript_routine/`, `common/scanner.h` to each directory's `objectscript_common.h`, the root `LICENSE` to each `LICENSE` (byte-identical to the previous pin). **Provenance:** both `parser.c` files and all `tree_sitter/*.h` are upstream's committed files byte-for-byte; regenerating the parsers from upstream's committed `src/grammar.json` + `tree-sitter.json` with tree-sitter-cli 0.27.1 (the version in upstream's `package-lock.json`; release binary checked against its published SHA-256) in a no-network, write-confined sandbox reproduces both byte-for-byte (SHA-256 `0c0c651b4a425cb8a00cdf6b8c89aeea702cb5799a9483d9994556655f441015` udl, `d496de950b085853fdf1edf1570eecdb5d2e4525344873bfabf7e34ac8e7add0` routine). No upstream JavaScript, script or workflow was run. **Why (#1261):** the `a7ffcdf` scanner only balanced braces in a `Language = python` method body, so a brace inside a Python string, comment or docstring ran the body past its closing `}` and the following methods were lost in an ERROR region; upstream lexes these bodies with Python's string, triple-quote and `#`-comment rules since v1.9.15. On intersystems/ipm @ `571e04a19aba` (429 `.cls`) the source under a top-level ERROR drops from 353,816 bytes in 138 files to 1,323 bytes in 3 files, with no file losing a method. Remaining gaps there: a class-level `[ Language = python ]` default (its method bodies still parse as ObjectScript), `Index ... [ Data = X(ELEMENTS) ]`, and a string concatenated with an underscore-led name inside a macro argument. **Node shapes:** from v1.9.15 upstream hides the `method_call` wrapper inside `Do`/`Job` (receiver and `oref_method` sit directly under `do_parameter`/`job_argument`), `core_trigger`/`external_trigger` (inlined into `trigger`) and `storage_body` (now `external_method_body_content`), and a routine `Do label` / `$$^routine` wraps its target in `method_name` / `routine_ref` instead of always `line_ref`. Extraction must handle these shapes in the same change (the adaptation is in #2368): without it, `Do obj.M()` instance calls and routine `Do label(...)` calls lose their CALLS edge, and Trigger body tokens and Storage XML properties are lost. **Size:** `parser.c` is 49,392,087 bytes (udl) and 48,934,992 bytes (routine), under the 50 MB line with little headroom. **Re-vendor note:** each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` (a verbatim copy of upstream `common/scanner.h`), because this repo's shared `vendored/common/scanner.h` belongs to the cfml/fsharp grammars and differs. The generated `parser.c` files remain byte-for-byte upstream. Each `scanner.c` also guards empty-state deserialization with `if (length > 0)` before `memcpy`, because Tree-sitter can pass a NULL buffer with zero length. On re-vendor, re-apply the include rename and this guard unless upstream already carries them. **Local modification (2026-07-16):** in `objectscript_common.h`, two loop counters `uint8_t i` were widened to `int i` (the `reverse_marker` scan and the `html_marker_buffer` reversal) to clear CodeQL `cpp/comparison-with-wider-type` — a false positive in practice (both lengths are hard-bounded by `MARKER_BUFFER_MAX_LEN = 30`, so `uint8_t` could never wrap), fixed for cleanliness. On re-vendor, re-apply this widening too (or upstream it at intersystems/tree-sitter-objectscript).
- **mojo** (added 2026-07-01): vendored from [lsh/tree-sitter-mojo](https://github.com/lsh/tree-sitter-mojo) @ `33193a99afe6` — MIT, ABI 15. Helix tracks `lsh/tree-sitter-mojo` as its Mojo grammar source, but the Helix-pinned commit (`3d7c53b8038f`) no longer resolves in the upstream repository after a force-push, so this vendor uses current upstream `main` rather than the stale registry SHA. Security review covered only the vendored C surface (`parser.c`, `scanner.c`, `tree_sitter/*.h`) plus upstream license/provenance metadata; no package manager hooks, workflow files, prompt/agent instruction files, or generated lockfiles were vendored.
- **arkts** (added 2026-08-26): **first-party derivative** — a fork of [tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)'s `typescript` dialect pinned @ `75b3874edb2d` (v0.23.2, the same commit our vendored typescript/tsx come from), on the tree-sitter-javascript base @ `3a837b6f3658` (v0.23.1, the version upstream's own package-lock pins), extended with ArkTS/ArkUI syntax (`@Component struct` declarations, UI-DSL trailing-closure calls with post-block attribute chains, decorated function declarations, `import lazy`, `@Extend`/`@Styles` leading-dot attribute chains, anonymous `stateStyles` style blocks). Grammar source + corpus tests live in `tools/tree-sitter-arkts/`; regenerate with `npx tree-sitter-cli@0.25.10 generate` (ABI 15). **External scanner:** `scanner.c` is a symbol-rename trampoline; `_common_scanner.h` is byte-identical (same SHA-256) to the reviewed `typescript/_common_scanner.h` already shipped. **LICENSE:** tree-sitter-typescript's MIT text **verbatim and byte-identical** (© 2017 Max Brunsfeld) — which is what MIT requires of a derivative work, and what lets the provenance audit byte-verify it against upstream rather than take a note on trust. The fork is registered in the audit's `FORKS` map. Our own copyright for the ArkTS additions, and the tree-sitter-javascript attribution (© 2014 Max Brunsfeld), live with the SOURCE in `tools/tree-sitter-arkts/grammar.js` and in `THIRD_PARTY.md`, which is what ships in the release archives.
- **javascript + tsx** (forked 2026-09-25, #1736): **self-maintained forks** of the pins we already vendored — [tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript) @ `58404d8cf191` and [tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)'s `tsx` dialect @ `75b3874edb2d` (javascript base @ `3a837b6f3658`, the version upstream's package-lock pins, as for arkts). **Why:** upstream accepts a `&` inside a JSX string only before a space/digit or as a complete character reference, and never inside JSX text, so a plain URL query (`href="…?a=1&b=2"`, Google Fonts `&display=swap`) or `<p>Tom & Jerry</p>` produced an ERROR node — a `parse_partial` flag, plus false USAGE edges from identifiers the error recovery pulled out of the URL (on vercel/next.js `examples/`: 45 of 92 flagged files, 115 false cross-example USAGE edges). **The change** is one patch, `tools/tree-sitter-javascript/patches/jsx-lone-ampersand.patch`, applied to both javascript bases: a lone `&` that does not begin a complete `html_character_reference` is a one-character token (lexical precedence -1, so `&amp;`/`&#38;` still lex as references) aliased to the EXISTING `string_fragment` / `jsx_text` nodes, and the string-fragment regexes stop before a `&` that directly precedes the closing quote. Node types are unchanged (same type/named set; `node-types.json` only gains an empty `fields` map on those two entries). Without the patch both directories regenerate upstream exactly (javascript: byte-identical `parser.c` apart from the generator-version comment; tsx: identical state/symbol counts, ABI 14 → 15 from the newer CLI). **External scanners** are unchanged: `javascript/scanner.c` and `tsx/scanner.c` + `_common_scanner.h` stay the reviewed upstream bytes. Regenerate with `npx tree-sitter-cli@0.25.10 generate` in `tools/tree-sitter-{javascript,tsx}/` (ABI 15) and copy `src/parser.c` (tsx: also `src/tree_sitter/*.h`) here. **On an upstream bump:** re-fetch the new pins, re-apply the patch, regenerate, re-run `test/corpus/jsx_ampersand.txt` — and drop the fork if upstream fixes it. **LICENSE:** upstream's MIT text byte-identical (registered in the audit's `FORKS` map); our copyright for the patch lives in the fork `grammar.js` headers and `THIRD_PARTY.md`.
@@ -115,8 +116,8 @@ row instead.
| crystal | `crystal/scanner.c`, serialize | guard `memcpy(&buffer[offset], state->literals.contents, literal_content_size)` with `if (literal_content_size > 0)` | UBSan: zero-length `memcpy` with a NULL/0-size source on the empty-state serialize round-trip (formal UB, harmless) |
| rescript | `rescript/scanner.c`, deserialize | guard `memcpy(state, buffer, n_bytes)` with `if (n_bytes > 0)` | UBSan: zero-length `memcpy` with a NULL `buffer` / `n_bytes == 0` on empty-state deserialize (formal UB, harmless). The sibling serialize copies a fixed `sizeof(ScannerState)` (always > 0, non-NULL src) and needs no guard. |
| rescript | `rescript/scanner.c`, scan, `TEMPLATE_CHARS` branch | `if (valid_symbols[TEMPLATE_CHARS])` → `if (valid_symbols[TEMPLATE_CHARS] && !valid_symbols[NEWLINE])` | **Quadratic lexing in error recovery (#2176).** The only parse state whose external lex state enables both tokens is tree-sitter's ERROR state (`ts_lex_modes[0]`, external state 1; the in-template state 7 has no `_newline`), where every external token is marked valid and the lexer retries at each byte. From every byte the template loop ran to the next `` ` ``, `$`, `\` or NUL — the end of file when there is none — and returned false, so an unparseable stretch cost O(n²) inside lexing, where the parse budget's progress callback never runs. 50 KB of `0xFF` took 5.3 s, 100 KB 30 s; after: 3 ms, linear (lexer bytes pulled for 4 KB → 8 KB of `0xFF`: 8.8 M → 35.3 M before, 8.7 K → 17.4 K after, `complexity_rescript_error_recovery_lexing_is_linear`). Valid files parse to byte-identical trees; broken files recover more (a `let` after an unterminated expression is kept instead of swallowed). Upstream pin `43c2f1f35024` carries the unguarded branch |
| objectscript_routine | `objectscript_routine/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 |
| 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 |
| objectscript_routine | `objectscript_routine/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. Upstream pin `25cf0f67a380` (v1.11.0) still carries the unguarded copy |
| 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. Upstream pin `25cf0f67a380` (v1.11.0) still carries the unguarded 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** (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 |
@@ -125,6 +126,7 @@ row instead.
| 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 |
| swift | `swift/scanner.c`, `OP_SYMBOL_SUPPRESSOR` + `eat_operators` | `1UL <<` / `1 <<` → `1ULL <<` | UBSan: `1 << suppressor` shifts an `int` by up to `TOKEN_COUNT` bits, undefined once the index reaches 31, while the mask it feeds is `uint64_t`. `1UL << FAKE_TRY_BANG` is the same defect on Windows, where `unsigned long` is 32 bits and `FAKE_TRY_BANG` is 32; the CLANGARM64 leg runs UBSan in trap mode, so there it is an illegal instruction rather than a log line. Upstream already carries both changes: `fb63a7004f07` (2026-04-06, upstream #558) for `eat_operators`, `6ab8d1d74ebd` (2026-08-10) for the `OP_SYMBOL_SUPPRESSOR` entry. Our pin `8abb3e8b3325` (2026-03-20) predates both, so this is a backport rather than a local invention — a re-vendor past 2026-08-10 should delete this row, not re-apply it |
| cobol | `cobol/scanner.c`, scan, `LINE_PREFIX_COMMENT` loop and `COMMENT_ENTRY` branch (#2998, #3000) | the column-prefix loop also stops at `lookahead == 0`; `COMMENT_ENTRY` is not emitted when `start_with_word()` consumed nothing | **Livelock at EOF.** `advance()` is a no-op at end of input, so a file reaching EOF at column 5 or less (a `.cob` file shorter than 6 bytes, or the empty line after a final newline in the right parser state) spun the scanner forever and the index worker until its quiet timeout. The `COMMENT_ENTRY` guard is defensive (zero-length external token); with the current tables it cannot fire. In-house grammar (see "Authored in-house"): there is no upstream to re-vendor from, the row records the change for the vendoring audit (`repro_issue2998_*` in `tests/repro/repro_extraction.c`) |
## Vendored from verified upstream
@@ -210,8 +212,8 @@ row instead.
| nickel | 15 | nickel-lang/tree-sitter-nickel | `b5b6cc3bc7b9` | VERIFIED-BOTH | ✅ |
| nix | 13 | nix-community/tree-sitter-nix | `eabf96807ea4` | VERIFIED-BOTH | ✅ |
| objc | 14 | tree-sitter-grammars/tree-sitter-objc | `181a81b8f23a` | VERIFIED-NVIM | ✅ |
| objectscript_routine | 15 | intersystems/tree-sitter-objectscript | `a7ffcdf2de8e` | vendor-maintained | ✅ |
| objectscript_udl | 15 | intersystems/tree-sitter-objectscript | `a7ffcdf2de8e` | vendor-maintained | ✅ |
| objectscript_routine | 15 | intersystems/tree-sitter-objectscript | `25cf0f67a380` | vendor-maintained | ✅ |
| objectscript_udl | 15 | intersystems/tree-sitter-objectscript | `25cf0f67a380` | vendor-maintained | ✅ |
| ocaml | 14 | tree-sitter/tree-sitter-ocaml | `5a979b3ec7f1` | VERIFIED-BOTH | ✅ |
| odin | 14 | tree-sitter-grammars/tree-sitter-odin | `d2ca8efb4487` | VERIFIED-BOTH | ✅ |
| perl | 15 | tree-sitter-perl/tree-sitter-perl | `c3e17b31179b` | UPSTREAM-RELEASE | ✅ |
+19 -3
View File
@@ -31,9 +31,14 @@ char* any_content_keyword[] = {
"procedure division",
};
static bool start_with_word( TSLexer *lexer, char *words[], int number_of_words) {
// consumed_any reports whether this call advanced the lexer at all, so the
// caller can refuse to emit a zero-length token (tree-sitter livelock).
static bool start_with_word(TSLexer *lexer, char *words[], int number_of_words,
bool *consumed_any) {
*consumed_any = false;
while(lexer->lookahead == ' ' || lexer->lookahead == '\t') {
lexer->advance(lexer, true);
*consumed_any = true;
}
char *keyword_pointer[number_of_words];
@@ -60,6 +65,7 @@ static bool start_with_word( TSLexer *lexer, char *words[], int number_of_words)
if(all_match_failed) {
for(; lexer->get_column(lexer) < 71 && lexer->lookahead != '\n' && lexer->lookahead != 0;
lexer->advance(lexer, true)) {
*consumed_any = true;
}
return false;
}
@@ -83,6 +89,7 @@ static bool start_with_word( TSLexer *lexer, char *words[], int number_of_words)
// next character
lexer->advance(lexer, true);
*consumed_any = true;
}
return false;
@@ -106,7 +113,10 @@ bool tree_sitter_COBOL_external_scanner_scan(void *payload, TSLexer *lexer,
}
if(valid_symbols[LINE_PREFIX_COMMENT] && lexer->get_column(lexer) <= 5) {
while(lexer->get_column(lexer) <= 5) {
// EOF guard: tree-sitter's advance() is a no-op at EOF (the column
// never increments), so without checking lookahead this loop spins
// forever when the input ends at column <= 5.
while(lexer->get_column(lexer) <= 5 && lexer->lookahead != 0) {
lexer->advance(lexer, true);
}
lexer->result_symbol = LINE_PREFIX_COMMENT;
@@ -143,7 +153,13 @@ bool tree_sitter_COBOL_external_scanner_scan(void *payload, TSLexer *lexer,
}
if(valid_symbols[COMMENT_ENTRY]) {
if(!start_with_word(lexer, any_content_keyword, number_of_comment_entry_keywords)) {
bool consumed_any = false;
if(!start_with_word(lexer, any_content_keyword, number_of_comment_entry_keywords, &consumed_any)) {
// Zero-length guard: emitting a token without consuming input
// livelocks the parser. Bail out and let tree-sitter recover.
if(!consumed_any) {
return false;
}
lexer->mark_end(lexer);
lexer->result_symbol = COMMENT_ENTRY;
return true;
@@ -40,6 +40,10 @@ enum ObjectScript_Core_Scanner_TokenType {
_DO_TERMINATION,
_BOL_BLOCK,
_POST_CONDITIONAL_END,
COMPILED_HEADER,
EXTERNAL_METHOD_BODY_CONTENT,
STATEMENT_IN_MACRO,
_END_IF_END,
/* Max token type */
OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX
@@ -83,7 +87,11 @@ static const char* token_names[] = {
"BOL_EXTRA",
"_DO_TERMINATION",
"_BOL_BLOCK",
"_POST_CONDITIONAL_END"
"_POST_CONDITIONAL_END",
"COMPILED_HEADER",
"EXTERNAL_METHOD_BODY_CONTENT",
"STATEMENT_IN_MACRO",
"_END_IF_END"
};
#if 0
@@ -175,14 +183,19 @@ struct ObjectScript_Core_Scanner {
int32_t js_marker_buffer_reversed[MARKER_BUFFER_MAX_LEN];
int js_marker_buffer_reversed_len;
bool is_rtn_dot;
// Allows nested old-style commands to close before the same `. }` line
// is emitted as a dotted block end.
bool pending_dotted_block_end;
bool is_python;
bool is_text;
};
static inline bool is_label_char(int32_t c) {
return iswalnum(c) || c == '%';
return iswalnum(c) || c == '%' || c >= 0x80;
}
static inline bool valid_tag_char(int32_t c) {
return iswalnum(c) || c == '%' || c == '.';
return iswalnum(c) || c == '%' || c == '.' || c >= 0x80;
}
static inline int32_t ascii_toupper_i32(int32_t c) {
@@ -237,6 +250,7 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "MVC") || ascii_upper_eq(text, len, "MVCRT")) return true;
if (ascii_upper_eq(text, len, "MVDIM")) return true;
if (ascii_upper_eq(text, len, "MVPRINT")) return true;
if (ascii_upper_eq(text, len, "MVP")) return true;
if (ascii_upper_eq(text, len, "Q") || ascii_upper_eq(text, len, "QUIT")) return true;
if (ascii_upper_eq(text, len, "G") || ascii_upper_eq(text, len, "GOTO")) return true;
if (ascii_upper_eq(text, len, "H") || ascii_upper_eq(text, len, "HALT") ||
@@ -253,6 +267,10 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "ZDELETE")) return true;
if (ascii_upper_eq(text, len, "ZERASE")) return true;
if (ascii_upper_eq(text, len, "ZETRAP")) return true;
if (ascii_upper_eq(text, len, "ZEDIT")) return true;
if (ascii_upper_eq(text, len, "ZED")) return true;
if (ascii_upper_eq(text, len, "ZE")) return true;
if (ascii_upper_eq(text, len, "ZEDI")) return true;
if (ascii_upper_eq(text, len, "ZFILE")) return true;
if (ascii_upper_eq(text, len, "ZGO")) return true;
if (ascii_upper_eq(text, len, "ZHTRAP")) return true;
@@ -281,6 +299,7 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "CLASS")) return true;
if (ascii_upper_eq(text, len, "METHOD")) return true;
if (ascii_upper_eq(text, len, "CLASSMETHOD")) return true;
if (ascii_upper_eq(text, len, "CLIENTMETHOD")) return true;
if (ascii_upper_eq(text, len, "PROPERTY")) return true;
if (ascii_upper_eq(text, len, "PARAMETER")) return true;
if (ascii_upper_eq(text, len, "RELATIONSHIP")) return true;
@@ -294,32 +313,339 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "IMPORT")) return true;
if (ascii_upper_eq(text, len, "INCLUDE")) return true;
if (ascii_upper_eq(text, len, "INCLUDEGENERATOR")) return true;
return false;
}
static bool ObjectScript_Core_Scanner_lex_fenced_text(
TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol,
char l_delim,
char r_delim) {
int leftRightDiff = 1;
// Consumes an ObjectScript interpolation (#(...)# or ##(...)##) embedded in
// &html/&xml text. Assumes lookahead is '#'. Inside the parens, '>' and '\''
// are ObjectScript operators, not XML syntax, so they must not be treated as
// tag ends or attribute quotes.
static void skip_cos_interpolation(TSLexer *lexer) {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
}
if (lexer->lookahead != '(') {
return;
}
int depth = 0;
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
int32_t c = lexer->lookahead;
if (c == '"') {
advance(lexer);
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
if (lexer->lookahead == '"') {
advance(lexer);
if (lexer->lookahead != '"') {
break;
}
}
advance(lexer);
}
continue;
}
advance(lexer);
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
break;
}
}
}
// consume the closing # (or ##)
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
}
}
}
// Consumes the rest of an XML tag up to (not including) the closing '>'.
// A quote only opens an attribute value directly after '=', so stray quotes in
// hand-written HTML (e.g. height=24") don't swallow the rest of the file.
static void skip_xml_tag_body(TSLexer *lexer) {
int32_t prev = 0;
while (!lexer->eof(lexer) && lexer->lookahead != '>') {
int32_t c = lexer->lookahead;
if (c == '#') {
skip_cos_interpolation(lexer);
prev = '#';
continue;
}
if ((c == '"' || c == '\'') && prev == '=') {
advance(lexer);
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '#') {
skip_cos_interpolation(lexer);
continue;
}
if (lexer->lookahead == c) {
advance(lexer);
if (lexer->lookahead == c) {
advance(lexer);
} else {
break;
}
} else {
advance(lexer);
}
}
prev = c;
continue;
}
if (!iswspace(c)) {
prev = c;
}
advance(lexer);
}
}
static bool lex_fenced_text(TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol, int32_t l_delim,
int32_t r_delim, bool is_xml, bool has_python_comment, bool is_text) {
int depth = 1;
const char *comment_start = "<!--";
const char *code_start = "<![CDATA[";
const char *code_end = "]]>";
const char *comment_end = "-->";
const char *script_start = "script";
const char *script_end = "</script>";
while (iswspace(lexer->lookahead) || lexer->lookahead == 0x2028 || lexer->lookahead == 0x2029) {
advance(lexer);
}
if (lexer->lookahead == '<') {
is_xml = true;
}
while(iswalnum(lexer->lookahead) || iswspace(lexer->lookahead)) {
advance(lexer);
}
while (!lexer->eof(lexer)) {
if (lexer->lookahead == r_delim) {
leftRightDiff -= 1;
} else if (lexer->lookahead == l_delim) {
leftRightDiff += 1;
while (iswspace(lexer->lookahead) || lexer->lookahead == 0x2028 || lexer->lookahead == 0x2029) {
advance(lexer);
}
if (leftRightDiff == 0) {
lexer->result_symbol = desired_symbol;
return true;
int32_t c = lexer->lookahead;
if (c == '#' && is_xml) {
skip_cos_interpolation(lexer);
continue;
}
if (c == '<' && is_xml) {
bool comment = true;
bool is_code = false;
for (unsigned i = 0; i < 4; i++) {
if (i > 1) {
is_code = true;
}
if (lexer->lookahead != comment_start[i]) {
comment = false;
break;
}
advance(lexer);
}
if (comment) {
bool is_comment_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '-') {
is_comment_end = true;
for (unsigned i = 0; i < 3; i++) {
if (lexer->lookahead != comment_end[i]) {
is_comment_end = false;
break;
}
advance(lexer);
}
}
if (is_comment_end) {
break;
}
advance(lexer);
}
continue;
} else if (is_code) {
for (unsigned i = 2; i < 9; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (lexer->lookahead != code_start[i]) {
is_code = false;
break;
}
advance(lexer);
}
// [CDATA[
if (is_code) {
bool is_code_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == ']') {
is_code_end = true;
for (unsigned i = 0; i < 3; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (lexer->lookahead != code_end[i]) {
is_code_end = false;
break;
}
advance(lexer);
}
}
if (is_code_end) {
break;
}
advance(lexer);
}
continue;
}
} else if (towlower(lexer->lookahead) == 's') {
bool is_script = true;
for (unsigned i = 0; i < 6; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (towlower(lexer->lookahead) != script_start[i]) {
is_script = false;
break;
}
advance(lexer);
}
skip_xml_tag_body(lexer);
if (lexer->lookahead == '>') {
advance(lexer);
}
if (!is_script) {
continue;
}
bool is_script_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '<') {
is_script_end = true;
for (unsigned i = 0; i < 9; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (towlower(lexer->lookahead) != script_end[i]) {
is_script_end = false;
break;
}
advance(lexer);
}
}
if (is_script_end) {
break;
}
advance(lexer);
}
continue;
}
else {
skip_xml_tag_body(lexer);
// consume the >
advance(lexer);
continue;
}
}
else if (!is_xml && (c == '"' || (c == '\'' && !is_text))) {
int32_t quote = c;
advance(lexer);
// Detect a triple-quoted string.
bool triple = false;
if (lexer->lookahead == quote) {
advance(lexer);
if (lexer->lookahead == quote) {
advance(lexer);
triple = true;
} else {
// Empty string literal ('' or ""); nothing more to skip.
continue;
}
}
// Consume the string contents.
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '\\') {
advance(lexer);
if (!lexer->eof(lexer)) {
advance(lexer);
}
continue;
}
if (lexer->lookahead == quote) {
advance(lexer);
if (!triple) {
break;
}
if (lexer->lookahead == quote) {
advance(lexer);
if (lexer->lookahead == quote) {
advance(lexer);
break;
}
}
continue;
}
if (!triple && lexer->lookahead == '\n') {
// Unterminated single-quoted string; stop before consuming the
// newline so brace counting resumes on the next line.
break;
}
advance(lexer);
}
continue;
} if (c == '#' && !is_xml && has_python_comment) {
// Line comment: consume to end of line.
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
continue;
} if (c == '/' && !is_xml) {
advance(lexer);
if (lexer->lookahead == '/') {
while (lexer->lookahead != 0 && lexer->lookahead != '\n' && lexer->lookahead != 0x2028 &&
lexer->lookahead != 0x2029) {
advance(lexer);
}
continue;
} else if (lexer->lookahead == '*') {
advance(lexer);
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '*') {
advance(lexer);
if (lexer->lookahead == '/') {
advance(lexer);
break;
}
}
else {
advance(lexer);
}
}
continue;
}
}
if (c == r_delim) {
depth--;
if (depth == 0) {
lexer->result_symbol = desired_symbol;
return true;
}
} else if (c == l_delim) {
depth++;
}
advance(lexer);
}
return false;
}
static bool ObjectScript_Core_Scanner_lex_marker_fenced_text(
TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol,
@@ -366,8 +692,35 @@ static inline bool is_objectscript_special_symbol_i32(int32_t c) {
c == '.' ;
}
static bool lex_compiled_header(TSLexer *lexer) {
lexer->mark_end(lexer);
while(!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
if (lexer->lookahead != '\n') return false;
advance(lexer);
if (lexer->lookahead != '%') return false;
advance(lexer);
if (lexer->lookahead != 'R') return false;
advance(lexer);
if (lexer->lookahead != 'O') return false;
advance(lexer);
lexer->result_symbol = COMPILED_HEADER;
int newline_count = 0;
while(newline_count < 2 && !lexer->eof(lexer)) {
if (lexer->lookahead == '\n') {
newline_count++;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
static bool ObjectScript_Core_Scanner_lex_pound_if_special_case(TSLexer *lexer) {
if (lexer->lookahead != '0') return false;
// if (lexer->lookahead != '0') return false;
uint32_t depth = 1;
bool at_line_start = false;
@@ -464,6 +817,15 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (valid_symbols[SENTINEL]) {
return false;
}
if (scanner->pending_dotted_block_end) {
if (lexer->lookahead == '.' && valid_symbols[_TERMINATION]) {
lexer->mark_end(lexer);
lexer->result_symbol = _TERMINATION;
return true;
}
scanner->pending_dotted_block_end = false;
}
scanner-> is_rtn_dot = false;
// this parses any line that ends in ##continue for
@@ -474,7 +836,11 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
static const char pattern[] = "##continue";
static const int len = sizeof(pattern)-1;
int pos = 0;
if (!lexer->eof(lexer) && !iswspace(lexer->lookahead)) {
// _STATEMENT_TERMINATION is only valid right after the macro name/args,
// where the value must be separated by whitespace. On a line continued
// by ##continue it is not valid, and the line may start in column 0.
bool is_continued_line = !valid_symbols[_STATEMENT_TERMINATION];
if (!is_continued_line && !lexer->eof(lexer) && !iswspace(lexer->lookahead)) {
scanner->terminated_newline = false;
return false;
}
@@ -487,6 +853,21 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (pos == len) {
advance(lexer);
// Allow a trailing ##; comment, e.g. "##continue ##; comment"
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == ';') {
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
}
}
}
int new_line_count = 0;
while(iswspace(lexer->lookahead) && new_line_count<1) {
if(lexer->lookahead=='\n') {
@@ -528,6 +909,15 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
}
if (valid_symbols[_END_IF_END]) {
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
advance(lexer);
}
lexer->result_symbol = _END_IF_END;
scanner->terminated_newline = true;
return true;
}
if (valid_symbols[EMBEDDED_JS_SPECIAL_CASE_COMPLETE]) {
int i = 0;
while (i<scanner->js_marker_buffer_reversed_len) {
@@ -604,6 +994,32 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
if (valid_symbols[STATEMENT_IN_MACRO]) {
lexer->mark_end(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
while (valid_tag_char(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (is_statement_or_class_keyword(ident, len)) {
if (iswspace(lexer->lookahead)) {
advance(lexer);
if (valid_tag_char(lexer->lookahead)) {
lexer->result_symbol = STATEMENT_IN_MACRO;
scanner->terminated_newline = false;
return true;
}
}
} else {
return false;
}
}
if (valid_symbols[EMBEDDED_SQL_REVERSE_MARKER]) {
while (scanner->sql_marker_buffer_len >0 && !lexer->eof(lexer)) {
int32_t expected = scanner->sql_marker_buffer[scanner->sql_marker_buffer_len - 1];
@@ -680,7 +1096,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
// an argument that is exactly one space after the keyword
if (count == 1 && (iswalnum(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '_') && valid_symbol_one_space) {
if (count == 1 && (is_label_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '_' || (lexer->lookahead == '{' && !valid_symbol_argumentless_loop)) && valid_symbol_one_space) {
lexer->mark_end(lexer);
lexer->result_symbol = _IMMEDIATE_SINGLE_WHITESPACE_FOLLOWED_BY_NON_WHITESPACE;
scanner->terminated_newline = false;
@@ -688,7 +1104,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
// argumentless command has >= 2 spaces after the keyword
else if (count >=2 && (iswalnum(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) && valid_symbol_argumentless_command_end) {
else if (count >=2 && (is_label_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '&') && valid_symbol_argumentless_command_end) {
lexer->mark_end(lexer);
lexer->result_symbol = _ARGUMENTLESS_COMMAND_END;
scanner->terminated_newline = false;
@@ -706,7 +1122,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
else if (lexer->lookahead == '#') {
lexer->mark_end(lexer);
advance(lexer);
if (towlower(lexer->lookahead) == 'e' && valid_symbols[TAG] && scanner->special_pound_if_mode && lexer->get_column(lexer) == 1) {
if (towlower(lexer->lookahead) == 'e' && (valid_symbols[TAG] || valid_symbols[TAG_END_IF]) && scanner->special_pound_if_mode) {
int32_t directive[16];
uint32_t len = 0;
while (len < (sizeof(directive) / sizeof(directive[0])) &&
@@ -720,6 +1136,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (scanner->special_pound_if_mode_if_depth<1) {
scanner->special_pound_if_mode=false;
}
// Anything after #endif on the same line is ignored (e.g. #endif ArgFor),
// but trailing comments are left for the comment rules
while (lexer->lookahead != '\n' && !lexer->eof(lexer) &&
lexer->lookahead != ';' && lexer->lookahead != '/' &&
lexer->lookahead != '#') {
advance(lexer);
}
lexer->result_symbol = TAG_END_IF;
lexer->mark_end(lexer);
return true;
@@ -892,7 +1315,37 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
else if (lexer->lookahead == '{' && valid_symbol_argumentless_loop) {
bool valid_symbol_zw_block = valid_symbols[_ZW_BLOCK];
lexer->mark_end(lexer);
if (count == 1 && valid_symbol_zw_block) {
advance(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
bool potential_tag = false;
if (lexer->get_column(lexer) == 0) {
potential_tag = true;
}
while (valid_tag_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (!is_statement_or_class_keyword(ident, len) && len > 0 && !potential_tag) {
if (len > 3) {
if (ident[0] == '$' && ident[1] == '$' && ident[2] == '$') {
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
@@ -948,26 +1401,60 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
else if (lexer->lookahead == '{') {
// this token is for commands that allow blocks as part of their command ex: w {"hi": "bye"}
if (count == 1 && valid_symbols[_ZW_BLOCK]) {
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
if (valid_symbols[DOTTED_STATEMENT_BLOCK]) {
lexer->mark_end(lexer);
lexer->result_symbol = DOTTED_STATEMENT_BLOCK;
}
else if (valid_symbol_argumentless_loop) {
bool valid_symbol_zw_block = valid_symbols[_ZW_BLOCK];
lexer->mark_end(lexer);
if (count == 1 && valid_symbol_zw_block) {
advance(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
bool potential_tag = false;
if (lexer->get_column(lexer) == 0) {
potential_tag = true;
}
while (valid_tag_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (!is_statement_or_class_keyword(ident, len) && len > 0 && !potential_tag) {
if (len > 3) {
if (ident[0] == '$' && ident[1] == '$' && ident[2] == '$') {
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
} else if (count == 1 && valid_symbols[_ZW_BLOCK]) {
lexer->mark_end(lexer);
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
if (lexer->lookahead == ')' && valid_symbol_termination) {
lexer->mark_end(lexer);
lexer->result_symbol = _TERMINATION;
scanner->terminated_newline = false;
return true;
}
if (count > 0 && valid_symbols[_WHITESPACE]) {
// there can't be a space between a keyword and the post-conditional,
@@ -1021,11 +1508,18 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
advance(lexer);
}
if (lexer->lookahead == '}') {
if (valid_symbols[_TERMINATION]) {
scanner->pending_dotted_block_end = true;
lexer->result_symbol = _TERMINATION;
return true;
}
lexer->result_symbol = _BOL_BLOCK;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
lexer->result_symbol = _BOL;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
@@ -1034,9 +1528,10 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') advance(lexer);
if (lexer->lookahead == '.') {
lexer->result_symbol = _BOL;
scanner->terminated_newline = false;
return true;
lexer->result_symbol = _BOL;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
else {
lexer->mark_end(lexer);
@@ -1087,6 +1582,44 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
if (scanner->routine_token_mode && valid_symbols[COMPILED_HEADER]) {
lexer->mark_end(lexer);
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) advance(lexer);
if (lexer->lookahead == '\n') {
advance(lexer);
if (lexer->lookahead != '%') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
advance(lexer);
if (lexer->lookahead != 'R') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
advance(lexer);
if (lexer->lookahead != 'O') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
lexer->result_symbol = COMPILED_HEADER;
int newline_count = 0;
while(newline_count < 2 && !lexer->eof(lexer)) {
if (lexer->lookahead == '\n') {
newline_count++;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
if (!scanner->column1_statement_mode) {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
@@ -1107,18 +1640,54 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
scanner->terminated_newline = false;
lexer->mark_end(lexer);
return true;
} else if (lexer->lookahead == '(') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
lexer->mark_end(lexer);
return true;
} else if (iswspace(lexer->lookahead)) {
lexer->mark_end(lexer);
advance(lexer);
int32_t ident[96];
uint32_t len = 0;
while (valid_tag_char(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (is_statement_or_class_keyword(ident, len)) {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
} else {
return false;
}
}
lexer->mark_end(lexer);
return false;
}
else if (valid_symbols[ANGLED_BRACKET_FENCED_TEXT]) {
bool ok = ObjectScript_Core_Scanner_lex_fenced_text(
lexer, ANGLED_BRACKET_FENCED_TEXT, '<', '>');
return ok;
scanner->is_python = false;
scanner->is_text = false;
return lex_fenced_text(
lexer, ANGLED_BRACKET_FENCED_TEXT, '<', '>', true, scanner->is_python, false);
}
else if (valid_symbols[PAREN_FENCED_TEXT]) {
bool ok = ObjectScript_Core_Scanner_lex_fenced_text(
lexer, PAREN_FENCED_TEXT, '(', ')');
return ok;
scanner->is_python = false;
scanner->is_text = false;
return lex_fenced_text(
lexer, PAREN_FENCED_TEXT, '(', ')', false, scanner->is_python, false);
}
else if (valid_symbols[EXTERNAL_METHOD_BODY_CONTENT]) {
// A valid method_body is one that is whose text fences
// are evenly balanced (so far only { })
// e.g. VALID: {{{ [^{}]* }}} INVALID: {{{ [^{}]* }
bool is_python = scanner->is_python;
bool is_text = scanner->is_text;
scanner->is_python=false;
scanner->is_text=false;
return lex_fenced_text(lexer, EXTERNAL_METHOD_BODY_CONTENT, '{',
'}', false, is_python, is_text);
}
else if (valid_symbols[_LINE_COMMENT_INNER]) {
@@ -1191,7 +1760,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
lexer->result_symbol = _WHITESPACE;
return true;
}
else if (valid_symbols[TAG] && scanner->special_pound_if_mode) {
else if ((valid_symbols[TAG] || valid_symbols[TAG_END_IF]) && scanner->special_pound_if_mode) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
@@ -1211,6 +1780,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (scanner->special_pound_if_mode_if_depth<1) {
scanner->special_pound_if_mode=false;
}
// Anything after #endif on the same line is ignored (e.g. #endif ArgFor),
// but trailing comments are left for the comment rules
while (lexer->lookahead != '\n' && !lexer->eof(lexer) &&
lexer->lookahead != ';' && lexer->lookahead != '/' &&
lexer->lookahead != '#') {
advance(lexer);
}
lexer->result_symbol = TAG_END_IF;
lexer->mark_end(lexer);
return true;
@@ -1226,9 +1802,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
lexer->mark_end(lexer);
lexer->result_symbol = BOL_EXTRA;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
if (valid_symbols[COMPILED_HEADER] && lex_compiled_header(lexer)) {
return true;
}
scanner->terminated_newline = false;
return false;
}
@@ -1242,4 +1822,7 @@ static void ObjectScript_Core_Scanner_init(struct ObjectScript_Core_Scanner *sca
scanner->special_pound_if_mode = false;
scanner->special_pound_if_mode_if_depth = 0;
scanner->is_rtn_dot = false;
scanner->pending_dotted_block_end = false;
scanner->is_python = false;
scanner->is_text = false;
}
File diff suppressed because it is too large Load Diff
+1 -35
View File
@@ -4,8 +4,7 @@
// Keep this in sync with grammar externals.
enum TokenType {
COMPILED_HEADER = OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX,
RTN_DOT,
RTN_DOT = OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX,
};
struct ObjectScript_Routine_Scanner {
@@ -29,33 +28,6 @@ static bool lex_rtn_dot(TSLexer *lexer) {
return false;
}
static bool lex_compiled_header(TSLexer *lexer) {
lexer->mark_end(lexer);
while(!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
if (lexer->lookahead != '\n') return false;
advance(lexer);
if (lexer->lookahead != '%') return false;
advance(lexer);
if (lexer->lookahead != 'R') return false;
advance(lexer);
if (lexer->lookahead != 'O') return false;
advance(lexer);
lexer->result_symbol = COMPILED_HEADER;
int newline_count = 0;
while(newline_count < 2 && !lexer->eof(lexer)) {
if (lexer->lookahead == '\n') {
newline_count++;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
static bool scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
struct ObjectScript_Routine_Scanner *scanner =
(struct ObjectScript_Routine_Scanner *)payload;
@@ -77,10 +49,6 @@ static bool scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
return true;
}
if (valid_symbols[COMPILED_HEADER] && lex_compiled_header(lexer)) {
return true;
}
if (valid_symbols[RTN_DOT] && lex_rtn_dot(lexer)) {
return true;
}
@@ -92,8 +60,6 @@ void *tree_sitter_objectscript_routine_external_scanner_create() {
struct ObjectScript_Routine_Scanner *scanner =
(struct ObjectScript_Routine_Scanner *)calloc(
1, sizeof(struct ObjectScript_Routine_Scanner));
// scanner->saw_compiled_header = false;
// scanner->saw_routine_header = false;
ObjectScript_Core_Scanner_init(&scanner->core_scanner);
scanner->core_scanner.column1_statement_mode = false;
scanner->core_scanner.routine_token_mode = true;
@@ -50,12 +50,18 @@ extern "C" {
/// memory allocated for the array's contents.
#define array_clear(self) ((self)->size = 0)
#ifdef __cplusplus
#define _array__cast(self, expr) (decltype((self)->contents))(expr)
#else
#define _array__cast(self, expr) (expr)
#endif
/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is
/// less than the array's current capacity, this function has no effect.
#define array_reserve(self, new_capacity) \
((self)->contents = _array__reserve( \
(void *)(self)->contents, &(self)->capacity, \
array_elem_size(self), new_capacity) \
#define array_reserve(self, new_capacity) \
((self)->contents = _array__cast(self, _array__reserve( \
(void *)(self)->contents, &(self)->capacity, \
array_elem_size(self), new_capacity)) \
)
/// Free any memory allocated for this array. Note that this does not free any
@@ -71,10 +77,10 @@ extern "C" {
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
do { \
(self)->contents = _array__grow( \
(self)->contents = _array__cast(self, _array__grow( \
(void *)(self)->contents, (self)->size, &(self)->capacity, \
1, array_elem_size(self) \
); \
)); \
(self)->contents[(self)->size++] = (element); \
} while(0)
@@ -83,10 +89,10 @@ extern "C" {
#define array_grow_by(self, count) \
do { \
if ((count) == 0) break; \
(self)->contents = _array__grow( \
(self)->contents = _array__cast(self, _array__grow( \
(self)->contents, (self)->size, &(self)->capacity, \
count, array_elem_size(self) \
); \
)); \
memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \
(self)->size += (count); \
} while (0)
@@ -98,26 +104,26 @@ extern "C" {
/// Append `count` elements to the end of the array, reading their values from the
/// `contents` pointer.
#define array_extend(self, count, other_contents) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void*)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), (self)->size, 0, count, other_contents \
)
)))
/// Remove `old_count` elements from the array starting at the given `index`. At
/// the same index, insert `new_count` new elements, reading their values from the
/// `new_contents` pointer.
#define array_splice(self, _index, old_count, new_count, new_contents) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), _index, old_count, new_count, new_contents \
)
)))
/// Insert one `element` into the array at the given `index`.
#define array_insert(self, _index, element) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), _index, 0, 1, &(element) \
)
)))
/// Remove one element from the array at the given `index`.
#define array_erase(self, _index) \
@@ -128,17 +134,17 @@ extern "C" {
/// Assign the contents of one array to another, reallocating if necessary.
#define array_assign(self, other) \
(self)->contents = _array__assign( \
((self)->contents = _array__cast(self, _array__assign( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
(const void *)(other)->contents, (other)->size, array_elem_size(self) \
)
)))
/// Swap one array with another
#define array_swap(self, other) \
do { \
void *_array_swap_tmp = (void *)(self)->contents; \
(self)->contents = (other)->contents; \
(other)->contents = _array_swap_tmp; \
(other)->contents = _array__cast(other, _array_swap_tmp); \
_array__swap(&(self)->size, &(self)->capacity, \
&(other)->size, &(other)->capacity); \
} while (0)
@@ -40,6 +40,10 @@ enum ObjectScript_Core_Scanner_TokenType {
_DO_TERMINATION,
_BOL_BLOCK,
_POST_CONDITIONAL_END,
COMPILED_HEADER,
EXTERNAL_METHOD_BODY_CONTENT,
STATEMENT_IN_MACRO,
_END_IF_END,
/* Max token type */
OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX
@@ -83,7 +87,11 @@ static const char* token_names[] = {
"BOL_EXTRA",
"_DO_TERMINATION",
"_BOL_BLOCK",
"_POST_CONDITIONAL_END"
"_POST_CONDITIONAL_END",
"COMPILED_HEADER",
"EXTERNAL_METHOD_BODY_CONTENT",
"STATEMENT_IN_MACRO",
"_END_IF_END"
};
#if 0
@@ -175,14 +183,19 @@ struct ObjectScript_Core_Scanner {
int32_t js_marker_buffer_reversed[MARKER_BUFFER_MAX_LEN];
int js_marker_buffer_reversed_len;
bool is_rtn_dot;
// Allows nested old-style commands to close before the same `. }` line
// is emitted as a dotted block end.
bool pending_dotted_block_end;
bool is_python;
bool is_text;
};
static inline bool is_label_char(int32_t c) {
return iswalnum(c) || c == '%';
return iswalnum(c) || c == '%' || c >= 0x80;
}
static inline bool valid_tag_char(int32_t c) {
return iswalnum(c) || c == '%' || c == '.';
return iswalnum(c) || c == '%' || c == '.' || c >= 0x80;
}
static inline int32_t ascii_toupper_i32(int32_t c) {
@@ -237,6 +250,7 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "MVC") || ascii_upper_eq(text, len, "MVCRT")) return true;
if (ascii_upper_eq(text, len, "MVDIM")) return true;
if (ascii_upper_eq(text, len, "MVPRINT")) return true;
if (ascii_upper_eq(text, len, "MVP")) return true;
if (ascii_upper_eq(text, len, "Q") || ascii_upper_eq(text, len, "QUIT")) return true;
if (ascii_upper_eq(text, len, "G") || ascii_upper_eq(text, len, "GOTO")) return true;
if (ascii_upper_eq(text, len, "H") || ascii_upper_eq(text, len, "HALT") ||
@@ -253,6 +267,10 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "ZDELETE")) return true;
if (ascii_upper_eq(text, len, "ZERASE")) return true;
if (ascii_upper_eq(text, len, "ZETRAP")) return true;
if (ascii_upper_eq(text, len, "ZEDIT")) return true;
if (ascii_upper_eq(text, len, "ZED")) return true;
if (ascii_upper_eq(text, len, "ZE")) return true;
if (ascii_upper_eq(text, len, "ZEDI")) return true;
if (ascii_upper_eq(text, len, "ZFILE")) return true;
if (ascii_upper_eq(text, len, "ZGO")) return true;
if (ascii_upper_eq(text, len, "ZHTRAP")) return true;
@@ -281,6 +299,7 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "CLASS")) return true;
if (ascii_upper_eq(text, len, "METHOD")) return true;
if (ascii_upper_eq(text, len, "CLASSMETHOD")) return true;
if (ascii_upper_eq(text, len, "CLIENTMETHOD")) return true;
if (ascii_upper_eq(text, len, "PROPERTY")) return true;
if (ascii_upper_eq(text, len, "PARAMETER")) return true;
if (ascii_upper_eq(text, len, "RELATIONSHIP")) return true;
@@ -294,32 +313,339 @@ static bool is_statement_or_class_keyword(const int32_t *text, uint32_t len) {
if (ascii_upper_eq(text, len, "IMPORT")) return true;
if (ascii_upper_eq(text, len, "INCLUDE")) return true;
if (ascii_upper_eq(text, len, "INCLUDEGENERATOR")) return true;
return false;
}
static bool ObjectScript_Core_Scanner_lex_fenced_text(
TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol,
char l_delim,
char r_delim) {
int leftRightDiff = 1;
// Consumes an ObjectScript interpolation (#(...)# or ##(...)##) embedded in
// &html/&xml text. Assumes lookahead is '#'. Inside the parens, '>' and '\''
// are ObjectScript operators, not XML syntax, so they must not be treated as
// tag ends or attribute quotes.
static void skip_cos_interpolation(TSLexer *lexer) {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
}
if (lexer->lookahead != '(') {
return;
}
int depth = 0;
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
int32_t c = lexer->lookahead;
if (c == '"') {
advance(lexer);
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
if (lexer->lookahead == '"') {
advance(lexer);
if (lexer->lookahead != '"') {
break;
}
}
advance(lexer);
}
continue;
}
advance(lexer);
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
break;
}
}
}
// consume the closing # (or ##)
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
}
}
}
// Consumes the rest of an XML tag up to (not including) the closing '>'.
// A quote only opens an attribute value directly after '=', so stray quotes in
// hand-written HTML (e.g. height=24") don't swallow the rest of the file.
static void skip_xml_tag_body(TSLexer *lexer) {
int32_t prev = 0;
while (!lexer->eof(lexer) && lexer->lookahead != '>') {
int32_t c = lexer->lookahead;
if (c == '#') {
skip_cos_interpolation(lexer);
prev = '#';
continue;
}
if ((c == '"' || c == '\'') && prev == '=') {
advance(lexer);
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '#') {
skip_cos_interpolation(lexer);
continue;
}
if (lexer->lookahead == c) {
advance(lexer);
if (lexer->lookahead == c) {
advance(lexer);
} else {
break;
}
} else {
advance(lexer);
}
}
prev = c;
continue;
}
if (!iswspace(c)) {
prev = c;
}
advance(lexer);
}
}
static bool lex_fenced_text(TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol, int32_t l_delim,
int32_t r_delim, bool is_xml, bool has_python_comment, bool is_text) {
int depth = 1;
const char *comment_start = "<!--";
const char *code_start = "<![CDATA[";
const char *code_end = "]]>";
const char *comment_end = "-->";
const char *script_start = "script";
const char *script_end = "</script>";
while (iswspace(lexer->lookahead) || lexer->lookahead == 0x2028 || lexer->lookahead == 0x2029) {
advance(lexer);
}
if (lexer->lookahead == '<') {
is_xml = true;
}
while(iswalnum(lexer->lookahead) || iswspace(lexer->lookahead)) {
advance(lexer);
}
while (!lexer->eof(lexer)) {
if (lexer->lookahead == r_delim) {
leftRightDiff -= 1;
} else if (lexer->lookahead == l_delim) {
leftRightDiff += 1;
while (iswspace(lexer->lookahead) || lexer->lookahead == 0x2028 || lexer->lookahead == 0x2029) {
advance(lexer);
}
if (leftRightDiff == 0) {
lexer->result_symbol = desired_symbol;
return true;
int32_t c = lexer->lookahead;
if (c == '#' && is_xml) {
skip_cos_interpolation(lexer);
continue;
}
if (c == '<' && is_xml) {
bool comment = true;
bool is_code = false;
for (unsigned i = 0; i < 4; i++) {
if (i > 1) {
is_code = true;
}
if (lexer->lookahead != comment_start[i]) {
comment = false;
break;
}
advance(lexer);
}
if (comment) {
bool is_comment_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '-') {
is_comment_end = true;
for (unsigned i = 0; i < 3; i++) {
if (lexer->lookahead != comment_end[i]) {
is_comment_end = false;
break;
}
advance(lexer);
}
}
if (is_comment_end) {
break;
}
advance(lexer);
}
continue;
} else if (is_code) {
for (unsigned i = 2; i < 9; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (lexer->lookahead != code_start[i]) {
is_code = false;
break;
}
advance(lexer);
}
// [CDATA[
if (is_code) {
bool is_code_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == ']') {
is_code_end = true;
for (unsigned i = 0; i < 3; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (lexer->lookahead != code_end[i]) {
is_code_end = false;
break;
}
advance(lexer);
}
}
if (is_code_end) {
break;
}
advance(lexer);
}
continue;
}
} else if (towlower(lexer->lookahead) == 's') {
bool is_script = true;
for (unsigned i = 0; i < 6; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (towlower(lexer->lookahead) != script_start[i]) {
is_script = false;
break;
}
advance(lexer);
}
skip_xml_tag_body(lexer);
if (lexer->lookahead == '>') {
advance(lexer);
}
if (!is_script) {
continue;
}
bool is_script_end = false;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '<') {
is_script_end = true;
for (unsigned i = 0; i < 9; i++) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
if (towlower(lexer->lookahead) != script_end[i]) {
is_script_end = false;
break;
}
advance(lexer);
}
}
if (is_script_end) {
break;
}
advance(lexer);
}
continue;
}
else {
skip_xml_tag_body(lexer);
// consume the >
advance(lexer);
continue;
}
}
else if (!is_xml && (c == '"' || (c == '\'' && !is_text))) {
int32_t quote = c;
advance(lexer);
// Detect a triple-quoted string.
bool triple = false;
if (lexer->lookahead == quote) {
advance(lexer);
if (lexer->lookahead == quote) {
advance(lexer);
triple = true;
} else {
// Empty string literal ('' or ""); nothing more to skip.
continue;
}
}
// Consume the string contents.
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '\\') {
advance(lexer);
if (!lexer->eof(lexer)) {
advance(lexer);
}
continue;
}
if (lexer->lookahead == quote) {
advance(lexer);
if (!triple) {
break;
}
if (lexer->lookahead == quote) {
advance(lexer);
if (lexer->lookahead == quote) {
advance(lexer);
break;
}
}
continue;
}
if (!triple && lexer->lookahead == '\n') {
// Unterminated single-quoted string; stop before consuming the
// newline so brace counting resumes on the next line.
break;
}
advance(lexer);
}
continue;
} if (c == '#' && !is_xml && has_python_comment) {
// Line comment: consume to end of line.
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
continue;
} if (c == '/' && !is_xml) {
advance(lexer);
if (lexer->lookahead == '/') {
while (lexer->lookahead != 0 && lexer->lookahead != '\n' && lexer->lookahead != 0x2028 &&
lexer->lookahead != 0x2029) {
advance(lexer);
}
continue;
} else if (lexer->lookahead == '*') {
advance(lexer);
while (!lexer->eof(lexer)) {
if (lexer->lookahead == '*') {
advance(lexer);
if (lexer->lookahead == '/') {
advance(lexer);
break;
}
}
else {
advance(lexer);
}
}
continue;
}
}
if (c == r_delim) {
depth--;
if (depth == 0) {
lexer->result_symbol = desired_symbol;
return true;
}
} else if (c == l_delim) {
depth++;
}
advance(lexer);
}
return false;
}
static bool ObjectScript_Core_Scanner_lex_marker_fenced_text(
TSLexer *lexer,
enum ObjectScript_Core_Scanner_TokenType desired_symbol,
@@ -366,8 +692,35 @@ static inline bool is_objectscript_special_symbol_i32(int32_t c) {
c == '.' ;
}
static bool lex_compiled_header(TSLexer *lexer) {
lexer->mark_end(lexer);
while(!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
if (lexer->lookahead != '\n') return false;
advance(lexer);
if (lexer->lookahead != '%') return false;
advance(lexer);
if (lexer->lookahead != 'R') return false;
advance(lexer);
if (lexer->lookahead != 'O') return false;
advance(lexer);
lexer->result_symbol = COMPILED_HEADER;
int newline_count = 0;
while(newline_count < 2 && !lexer->eof(lexer)) {
if (lexer->lookahead == '\n') {
newline_count++;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
static bool ObjectScript_Core_Scanner_lex_pound_if_special_case(TSLexer *lexer) {
if (lexer->lookahead != '0') return false;
// if (lexer->lookahead != '0') return false;
uint32_t depth = 1;
bool at_line_start = false;
@@ -464,6 +817,15 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (valid_symbols[SENTINEL]) {
return false;
}
if (scanner->pending_dotted_block_end) {
if (lexer->lookahead == '.' && valid_symbols[_TERMINATION]) {
lexer->mark_end(lexer);
lexer->result_symbol = _TERMINATION;
return true;
}
scanner->pending_dotted_block_end = false;
}
scanner-> is_rtn_dot = false;
// this parses any line that ends in ##continue for
@@ -474,7 +836,11 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
static const char pattern[] = "##continue";
static const int len = sizeof(pattern)-1;
int pos = 0;
if (!lexer->eof(lexer) && !iswspace(lexer->lookahead)) {
// _STATEMENT_TERMINATION is only valid right after the macro name/args,
// where the value must be separated by whitespace. On a line continued
// by ##continue it is not valid, and the line may start in column 0.
bool is_continued_line = !valid_symbols[_STATEMENT_TERMINATION];
if (!is_continued_line && !lexer->eof(lexer) && !iswspace(lexer->lookahead)) {
scanner->terminated_newline = false;
return false;
}
@@ -487,6 +853,21 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (pos == len) {
advance(lexer);
// Allow a trailing ##; comment, e.g. "##continue ##; comment"
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == '#') {
advance(lexer);
if (lexer->lookahead == ';') {
while (!lexer->eof(lexer) && lexer->lookahead != '\n') {
advance(lexer);
}
}
}
}
int new_line_count = 0;
while(iswspace(lexer->lookahead) && new_line_count<1) {
if(lexer->lookahead=='\n') {
@@ -528,6 +909,15 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
}
if (valid_symbols[_END_IF_END]) {
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
advance(lexer);
}
lexer->result_symbol = _END_IF_END;
scanner->terminated_newline = true;
return true;
}
if (valid_symbols[EMBEDDED_JS_SPECIAL_CASE_COMPLETE]) {
int i = 0;
while (i<scanner->js_marker_buffer_reversed_len) {
@@ -604,6 +994,32 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
if (valid_symbols[STATEMENT_IN_MACRO]) {
lexer->mark_end(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
while (valid_tag_char(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (is_statement_or_class_keyword(ident, len)) {
if (iswspace(lexer->lookahead)) {
advance(lexer);
if (valid_tag_char(lexer->lookahead)) {
lexer->result_symbol = STATEMENT_IN_MACRO;
scanner->terminated_newline = false;
return true;
}
}
} else {
return false;
}
}
if (valid_symbols[EMBEDDED_SQL_REVERSE_MARKER]) {
while (scanner->sql_marker_buffer_len >0 && !lexer->eof(lexer)) {
int32_t expected = scanner->sql_marker_buffer[scanner->sql_marker_buffer_len - 1];
@@ -680,7 +1096,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
// an argument that is exactly one space after the keyword
if (count == 1 && (iswalnum(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '_') && valid_symbol_one_space) {
if (count == 1 && (is_label_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '_' || (lexer->lookahead == '{' && !valid_symbol_argumentless_loop)) && valid_symbol_one_space) {
lexer->mark_end(lexer);
lexer->result_symbol = _IMMEDIATE_SINGLE_WHITESPACE_FOLLOWED_BY_NON_WHITESPACE;
scanner->terminated_newline = false;
@@ -688,7 +1104,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
// argumentless command has >= 2 spaces after the keyword
else if (count >=2 && (iswalnum(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) && valid_symbol_argumentless_command_end) {
else if (count >=2 && (is_label_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead) || lexer->lookahead == '&') && valid_symbol_argumentless_command_end) {
lexer->mark_end(lexer);
lexer->result_symbol = _ARGUMENTLESS_COMMAND_END;
scanner->terminated_newline = false;
@@ -706,7 +1122,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
else if (lexer->lookahead == '#') {
lexer->mark_end(lexer);
advance(lexer);
if (towlower(lexer->lookahead) == 'e' && valid_symbols[TAG] && scanner->special_pound_if_mode && lexer->get_column(lexer) == 1) {
if (towlower(lexer->lookahead) == 'e' && (valid_symbols[TAG] || valid_symbols[TAG_END_IF]) && scanner->special_pound_if_mode) {
int32_t directive[16];
uint32_t len = 0;
while (len < (sizeof(directive) / sizeof(directive[0])) &&
@@ -720,6 +1136,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (scanner->special_pound_if_mode_if_depth<1) {
scanner->special_pound_if_mode=false;
}
// Anything after #endif on the same line is ignored (e.g. #endif ArgFor),
// but trailing comments are left for the comment rules
while (lexer->lookahead != '\n' && !lexer->eof(lexer) &&
lexer->lookahead != ';' && lexer->lookahead != '/' &&
lexer->lookahead != '#') {
advance(lexer);
}
lexer->result_symbol = TAG_END_IF;
lexer->mark_end(lexer);
return true;
@@ -892,7 +1315,37 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
else if (lexer->lookahead == '{' && valid_symbol_argumentless_loop) {
bool valid_symbol_zw_block = valid_symbols[_ZW_BLOCK];
lexer->mark_end(lexer);
if (count == 1 && valid_symbol_zw_block) {
advance(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
bool potential_tag = false;
if (lexer->get_column(lexer) == 0) {
potential_tag = true;
}
while (valid_tag_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (!is_statement_or_class_keyword(ident, len) && len > 0 && !potential_tag) {
if (len > 3) {
if (ident[0] == '$' && ident[1] == '$' && ident[2] == '$') {
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
@@ -948,26 +1401,60 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
else if (lexer->lookahead == '{') {
// this token is for commands that allow blocks as part of their command ex: w {"hi": "bye"}
if (count == 1 && valid_symbols[_ZW_BLOCK]) {
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
if (valid_symbols[DOTTED_STATEMENT_BLOCK]) {
lexer->mark_end(lexer);
lexer->result_symbol = DOTTED_STATEMENT_BLOCK;
}
else if (valid_symbol_argumentless_loop) {
bool valid_symbol_zw_block = valid_symbols[_ZW_BLOCK];
lexer->mark_end(lexer);
if (count == 1 && valid_symbol_zw_block) {
advance(lexer);
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
int32_t ident[96];
uint32_t len = 0;
bool potential_tag = false;
if (lexer->get_column(lexer) == 0) {
potential_tag = true;
}
while (valid_tag_char(lexer->lookahead) || is_objectscript_special_symbol_i32(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (!is_statement_or_class_keyword(ident, len) && len > 0 && !potential_tag) {
if (len > 3) {
if (ident[0] == '$' && ident[1] == '$' && ident[2] == '$') {
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
lexer->result_symbol = _ARGUMENTLESS_LOOP;
scanner->terminated_newline = false;
return true;
} else if (count == 1 && valid_symbols[_ZW_BLOCK]) {
lexer->mark_end(lexer);
lexer->result_symbol = _ZW_BLOCK;
scanner->terminated_newline = false;
return true;
}
}
if (lexer->lookahead == ')' && valid_symbol_termination) {
lexer->mark_end(lexer);
lexer->result_symbol = _TERMINATION;
scanner->terminated_newline = false;
return true;
}
if (count > 0 && valid_symbols[_WHITESPACE]) {
// there can't be a space between a keyword and the post-conditional,
@@ -1021,11 +1508,18 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
advance(lexer);
}
if (lexer->lookahead == '}') {
if (valid_symbols[_TERMINATION]) {
scanner->pending_dotted_block_end = true;
lexer->result_symbol = _TERMINATION;
return true;
}
lexer->result_symbol = _BOL_BLOCK;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
lexer->result_symbol = _BOL;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
@@ -1034,9 +1528,10 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') advance(lexer);
if (lexer->lookahead == '.') {
lexer->result_symbol = _BOL;
scanner->terminated_newline = false;
return true;
lexer->result_symbol = _BOL;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
else {
lexer->mark_end(lexer);
@@ -1087,6 +1582,44 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
return true;
}
if (scanner->routine_token_mode && valid_symbols[COMPILED_HEADER]) {
lexer->mark_end(lexer);
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) advance(lexer);
if (lexer->lookahead == '\n') {
advance(lexer);
if (lexer->lookahead != '%') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
advance(lexer);
if (lexer->lookahead != 'R') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
advance(lexer);
if (lexer->lookahead != 'O') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
lexer->result_symbol = COMPILED_HEADER;
int newline_count = 0;
while(newline_count < 2 && !lexer->eof(lexer)) {
if (lexer->lookahead == '\n') {
newline_count++;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
}
if (!scanner->column1_statement_mode) {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
@@ -1107,18 +1640,54 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
scanner->terminated_newline = false;
lexer->mark_end(lexer);
return true;
} else if (lexer->lookahead == '(') {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
lexer->mark_end(lexer);
return true;
} else if (iswspace(lexer->lookahead)) {
lexer->mark_end(lexer);
advance(lexer);
int32_t ident[96];
uint32_t len = 0;
while (valid_tag_char(lexer->lookahead)) {
if (len < sizeof(ident) / sizeof(ident[0])) ident[len++] = lexer->lookahead;
advance(lexer);
}
if (is_statement_or_class_keyword(ident, len)) {
lexer->result_symbol = TAG;
scanner->terminated_newline = false;
return true;
} else {
return false;
}
}
lexer->mark_end(lexer);
return false;
}
else if (valid_symbols[ANGLED_BRACKET_FENCED_TEXT]) {
bool ok = ObjectScript_Core_Scanner_lex_fenced_text(
lexer, ANGLED_BRACKET_FENCED_TEXT, '<', '>');
return ok;
scanner->is_python = false;
scanner->is_text = false;
return lex_fenced_text(
lexer, ANGLED_BRACKET_FENCED_TEXT, '<', '>', true, scanner->is_python, false);
}
else if (valid_symbols[PAREN_FENCED_TEXT]) {
bool ok = ObjectScript_Core_Scanner_lex_fenced_text(
lexer, PAREN_FENCED_TEXT, '(', ')');
return ok;
scanner->is_python = false;
scanner->is_text = false;
return lex_fenced_text(
lexer, PAREN_FENCED_TEXT, '(', ')', false, scanner->is_python, false);
}
else if (valid_symbols[EXTERNAL_METHOD_BODY_CONTENT]) {
// A valid method_body is one that is whose text fences
// are evenly balanced (so far only { })
// e.g. VALID: {{{ [^{}]* }}} INVALID: {{{ [^{}]* }
bool is_python = scanner->is_python;
bool is_text = scanner->is_text;
scanner->is_python=false;
scanner->is_text=false;
return lex_fenced_text(lexer, EXTERNAL_METHOD_BODY_CONTENT, '{',
'}', false, is_python, is_text);
}
else if (valid_symbols[_LINE_COMMENT_INNER]) {
@@ -1191,7 +1760,7 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
lexer->result_symbol = _WHITESPACE;
return true;
}
else if (valid_symbols[TAG] && scanner->special_pound_if_mode) {
else if ((valid_symbols[TAG] || valid_symbols[TAG_END_IF]) && scanner->special_pound_if_mode) {
while (iswspace(lexer->lookahead)) {
advance(lexer);
}
@@ -1211,6 +1780,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
if (scanner->special_pound_if_mode_if_depth<1) {
scanner->special_pound_if_mode=false;
}
// Anything after #endif on the same line is ignored (e.g. #endif ArgFor),
// but trailing comments are left for the comment rules
while (lexer->lookahead != '\n' && !lexer->eof(lexer) &&
lexer->lookahead != ';' && lexer->lookahead != '/' &&
lexer->lookahead != '#') {
advance(lexer);
}
lexer->result_symbol = TAG_END_IF;
lexer->mark_end(lexer);
return true;
@@ -1226,9 +1802,13 @@ ObjectScript_Core_Scanner_scan(struct ObjectScript_Core_Scanner *scanner,
}
lexer->mark_end(lexer);
lexer->result_symbol = BOL_EXTRA;
scanner->pending_dotted_block_end = false;
scanner->terminated_newline = false;
return true;
}
if (valid_symbols[COMPILED_HEADER] && lex_compiled_header(lexer)) {
return true;
}
scanner->terminated_newline = false;
return false;
}
@@ -1242,4 +1822,7 @@ static void ObjectScript_Core_Scanner_init(struct ObjectScript_Core_Scanner *sca
scanner->special_pound_if_mode = false;
scanner->special_pound_if_mode_if_depth = 0;
scanner->is_rtn_dot = false;
scanner->pending_dotted_block_end = false;
scanner->is_python = false;
scanner->is_text = false;
}
File diff suppressed because it is too large Load Diff
+108 -53
View File
@@ -1,12 +1,15 @@
#include "objectscript_common.h"
#include "tree_sitter/parser.h"
#include <string.h>
#include <wctype.h>
// There is no way to extend enums, so keep this in sync with base.h
// All new entries should be appended at the bottom of the list
enum TokenType {
EXTERNAL_METHOD_BODY_CONTENT = OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX,
IRIS_USERNAME,
IRIS_USERNAME= OBJECTSCRIPT_CORE_TOKEN_TYPE_MAX,
PYTHON_MIME_TYPE,
_IS_PYTHON,
TEXT_MIME_TYPE,
};
struct ObjectScript_Udl_Scanner {
@@ -14,57 +17,11 @@ struct ObjectScript_Udl_Scanner {
struct ObjectScript_Core_Scanner core_scanner;
};
static bool lex_fenced_text(TSLexer *lexer,
enum TokenType desired_symbol, char l_delim,
char r_delim) {
int leftRightDiff = 1;
while (!lexer->eof(lexer)) {
if (lexer->lookahead == r_delim) {
leftRightDiff -= 1;
} else if (lexer->lookahead == l_delim) {
leftRightDiff += 1;
}
if (leftRightDiff == 0) {
lexer->result_symbol = desired_symbol;
return true;
}
advance(lexer);
}
return false;
}
/// This is the interesting function. The rest is infrastructure
static bool scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
// struct Scanner *scanner = (struct Scanner *)payload;
//
// Tree sitter will mark all terminals as valid on error
// The sentinel should never be valid in a good parse, so this ensures
// we are not in error recovery mode
// printf("Lookahead: '%c'. Col %d. Tag is valid? %d", lexer->lookahead,
// lexer->get_column(lexer), valid_symbols[TAG]);
// printf("lexer->lookahead: '%c'\n", lexer->lookahead);
// printf("====\n");
// debug_enum(valid_symbols);
// printf("====\n");
static bool scan(struct ObjectScript_Udl_Scanner *scanner, TSLexer *lexer, const bool *valid_symbols) {
if (valid_symbols[SENTINEL]) {
// printf("Thats not good!\n");
// // TODO: ERROR RECOVERY MODE ?? Why would we be better than TS's
// default? if (iswspace(lexer->lookahead)) {
// skip(lexer);
// eat_whitespace(lexer);
// lexer->result_symbol = _WHITESPACE;
// return true;
// }
return false;
}
if (valid_symbols[EXTERNAL_METHOD_BODY_CONTENT]) {
// A valid method_body is one that is whose text fences
// are evenly balanced (so far only { })
// e.g. VALID: {{{ [^{}]* }}} INVALID: {{{ [^{}]* }
return lex_fenced_text(lexer, EXTERNAL_METHOD_BODY_CONTENT, '{',
'}');
}
if (valid_symbols[IRIS_USERNAME] && !(lexer->lookahead=='}' || lexer->lookahead=='@' || lexer->lookahead=='*')) {
int count=0;
lexer->mark_end(lexer);
@@ -72,7 +29,7 @@ static bool scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
count++;
advance(lexer);
}
if(lexer->lookahead=='}') {
lexer->mark_end(lexer);
@@ -82,12 +39,110 @@ static bool scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
else {
return false;
}
}
if (valid_symbols[_IS_PYTHON]) {
scanner->core_scanner.is_python = true;
lexer->result_symbol = _IS_PYTHON;
return true;
}
if (valid_symbols[PYTHON_MIME_TYPE]) {
lexer->mark_end(lexer);
int count = 0;
while(iswspace(lexer->lookahead)) {
count ++;
advance(lexer);
}
if (count > 0) {
lexer -> mark_end(lexer);
lexer->result_symbol = _WHITESPACE;
return true;
}
bool has_string = false;
if (lexer->lookahead == '"') {
has_string = true;
advance(lexer);
}
const char* text_mime = "text/";
const char *text_python = "x-python";
const char *application_python = "application/python";
const char *markdown = "markdown";
const char *plain = "plain";
bool is_python = true;
bool is_text = true;
bool is_markdown = false;
for (unsigned i = 0; i < 5; i++) {
if (lexer->lookahead != text_mime[i]) {
is_text = false;
break;
}
if (lexer->eof(lexer)) break;
advance(lexer);
}
if (is_text) {
for (unsigned i = 0; i < 8; i++) {
if (lexer->lookahead != text_python[i]) {
is_python = false;
break;
}
if (lexer->eof(lexer)) break;
advance(lexer);
} if (!is_python) {
is_markdown = true;
for (unsigned i = 0; i < 8; i++) {
if (lexer->lookahead != markdown[i]) {
is_markdown = false;
break;
}
if (lexer->eof(lexer)) break;
advance(lexer);
}
} if (!is_markdown && !is_python) {
is_markdown = true;
for (unsigned i = 0; i < 5; i++) {
if (lexer->lookahead != plain[i]) {
is_markdown = false;
break;
}
if (lexer->eof(lexer)) break;
advance(lexer);
}
}
}
else {
for (unsigned i = 0; i < 18; i++) {
if (lexer->lookahead != application_python[i]) {
is_python = false;
break;
}
if (lexer->eof(lexer)) break;
advance(lexer);
}
}
if (has_string) {
advance(lexer);
}
if (is_python) {
scanner->core_scanner.is_python = true;
lexer->mark_end(lexer);
lexer->result_symbol = PYTHON_MIME_TYPE;
return true;
}
if (is_markdown) {
scanner->core_scanner.is_text = true;
lexer->mark_end(lexer);
lexer->result_symbol = TEXT_MIME_TYPE;
return true;
}
return false;
}
struct ObjectScript_Udl_Scanner *scanner =
(struct ObjectScript_Udl_Scanner *)payload;
return ObjectScript_Core_Scanner_scan(&scanner->core_scanner, lexer,
valid_symbols);
}
@@ -50,12 +50,18 @@ extern "C" {
/// memory allocated for the array's contents.
#define array_clear(self) ((self)->size = 0)
#ifdef __cplusplus
#define _array__cast(self, expr) (decltype((self)->contents))(expr)
#else
#define _array__cast(self, expr) (expr)
#endif
/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is
/// less than the array's current capacity, this function has no effect.
#define array_reserve(self, new_capacity) \
((self)->contents = _array__reserve( \
(void *)(self)->contents, &(self)->capacity, \
array_elem_size(self), new_capacity) \
#define array_reserve(self, new_capacity) \
((self)->contents = _array__cast(self, _array__reserve( \
(void *)(self)->contents, &(self)->capacity, \
array_elem_size(self), new_capacity)) \
)
/// Free any memory allocated for this array. Note that this does not free any
@@ -71,10 +77,10 @@ extern "C" {
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
do { \
(self)->contents = _array__grow( \
(self)->contents = _array__cast(self, _array__grow( \
(void *)(self)->contents, (self)->size, &(self)->capacity, \
1, array_elem_size(self) \
); \
)); \
(self)->contents[(self)->size++] = (element); \
} while(0)
@@ -83,10 +89,10 @@ extern "C" {
#define array_grow_by(self, count) \
do { \
if ((count) == 0) break; \
(self)->contents = _array__grow( \
(self)->contents = _array__cast(self, _array__grow( \
(self)->contents, (self)->size, &(self)->capacity, \
count, array_elem_size(self) \
); \
)); \
memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \
(self)->size += (count); \
} while (0)
@@ -98,26 +104,26 @@ extern "C" {
/// Append `count` elements to the end of the array, reading their values from the
/// `contents` pointer.
#define array_extend(self, count, other_contents) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void*)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), (self)->size, 0, count, other_contents \
)
)))
/// Remove `old_count` elements from the array starting at the given `index`. At
/// the same index, insert `new_count` new elements, reading their values from the
/// `new_contents` pointer.
#define array_splice(self, _index, old_count, new_count, new_contents) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), _index, old_count, new_count, new_contents \
)
)))
/// Insert one `element` into the array at the given `index`.
#define array_insert(self, _index, element) \
(self)->contents = _array__splice( \
((self)->contents = _array__cast(self, _array__splice( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
array_elem_size(self), _index, 0, 1, &(element) \
)
)))
/// Remove one element from the array at the given `index`.
#define array_erase(self, _index) \
@@ -128,17 +134,17 @@ extern "C" {
/// Assign the contents of one array to another, reallocating if necessary.
#define array_assign(self, other) \
(self)->contents = _array__assign( \
((self)->contents = _array__cast(self, _array__assign( \
(void *)(self)->contents, &(self)->size, &(self)->capacity, \
(const void *)(other)->contents, (other)->size, array_elem_size(self) \
)
)))
/// Swap one array with another
#define array_swap(self, other) \
do { \
void *_array_swap_tmp = (void *)(self)->contents; \
(self)->contents = (other)->contents; \
(other)->contents = _array_swap_tmp; \
(other)->contents = _array__cast(other, _array_swap_tmp); \
_array__swap(&(self)->size, &(self)->capacity, \
&(other)->size, &(other)->capacity); \
} while (0)
+15 -4
View File
@@ -51,7 +51,7 @@ const (
requestTimeout = 2 * time.Minute
connectTimeout = 15 * time.Second
responseHeaderTimeout = 30 * time.Second
candidateTimeout = 15 * time.Second
candidateVerifyBound = 5 * time.Minute
maxArchiveMembers = 64
runtimeSetLockName = ".codebase-memory-mcp-runtime.lock"
@@ -1008,15 +1008,26 @@ func validateWindowsZipMember(raw string) (string, error) {
}
func verifyCandidate(path string) error {
ctx, cancel := context.WithTimeout(context.Background(), candidateTimeout)
return verifyCandidateWithCommand(path, exec.CommandContext)
}
func verifyCandidateWithCommand(
path string, command func(context.Context, string, ...string) *exec.Cmd,
) error {
// Verification is decided by the child exit. A slow host can need far more
// than a few seconds, but this runs under the package-cache lock at every
// launch, so a candidate that never answers must not hold that lock forever:
// the bound is generous, not tight.
ctx, cancel := context.WithTimeout(context.Background(), candidateVerifyBound)
defer cancel()
cmd := exec.CommandContext(ctx, path, "--version")
cmd := command(ctx, path, "--version")
cmd.Stdin = nil
cmd.Stdout = io.Discard
cmd.Stderr = io.Discard
if err := cmd.Run(); err != nil {
if ctx.Err() != nil {
return fmt.Errorf("downloaded binary verification timed out: %w", ctx.Err())
return fmt.Errorf("downloaded binary verification did not finish within %s: %w",
candidateVerifyBound, ctx.Err())
}
return fmt.Errorf("downloaded binary failed to run: %w", err)
}
+104
View File
@@ -5,10 +5,12 @@ import (
"archive/zip"
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
@@ -1388,3 +1390,105 @@ func TestReleaseVersionFromModuleVersion(t *testing.T) {
}
}
}
// Re-executed as a candidate binary; the connection holds it until released.
func TestVerifyCandidateProcess(t *testing.T) {
address := os.Getenv("CBM_TEST_VERIFY_ADDRESS")
if address == "" {
return
}
connection, err := net.Dial("tcp", address)
if err != nil {
os.Exit(2)
}
defer connection.Close()
if _, err := connection.Write([]byte("ready")); err != nil {
os.Exit(3)
}
var release [1]byte
if _, err := io.ReadFull(connection, release[:]); err != nil {
os.Exit(4)
}
os.Exit(int(release[0]))
}
func TestVerifyCandidateWaitsForResult(t *testing.T) {
for _, exitCode := range []byte{0, 7} {
t.Run(fmt.Sprintf("exit_%d", exitCode), func(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer listener.Close()
// This bound only aborts a hung test, never decides a successful result.
guard, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
accepted := make(chan net.Conn, 1)
go func() {
connection, err := listener.Accept()
if err == nil {
accepted <- connection
}
}()
done := make(chan error, 1)
go func() {
done <- verifyCandidateWithCommand("candidate", func(ctx context.Context, path string, args ...string) *exec.Cmd {
// The bound must exist (a stuck candidate releases the cache
// lock) and be generous: at least two minutes, far above the
// old 15 s that cut off slow hosts (#2877).
if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) < 2*time.Minute {
t.Errorf("candidate verification deadline = %v (set %v), want a bound of minutes",
deadline, ok)
}
if path != "candidate" || !reflect.DeepEqual(args, []string{"--version"}) {
t.Errorf("candidate command = %q %q", path, args)
}
command := exec.CommandContext(guard, os.Args[0], "-test.run=^TestVerifyCandidateProcess$")
command.Env = append(os.Environ(), "CBM_TEST_VERIFY_ADDRESS="+listener.Addr().String())
return command
})
}()
var connection net.Conn
select {
case connection = <-accepted:
case err := <-done:
t.Fatalf("verification returned before handshake: %v", err)
case <-guard.Done():
t.Fatal("candidate handshake hung")
}
defer connection.Close()
if err := connection.SetDeadline(time.Now().Add(time.Minute)); err != nil {
t.Fatal(err)
}
ready := make([]byte, len("ready"))
if _, err := io.ReadFull(connection, ready); err != nil || string(ready) != "ready" {
t.Fatalf("candidate handshake = %q, %v", ready, err)
}
select {
case err := <-done:
t.Fatalf("verification returned while candidate held: %v", err)
default:
}
if _, err := connection.Write([]byte{exitCode}); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if exitCode == 0 && err != nil {
t.Fatal(err)
}
if exitCode != 0 {
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError.ExitCode() != int(exitCode) {
t.Fatalf("verification error = %v, want exit %d", err, exitCode)
}
}
case <-guard.Done():
t.Fatal("verification hung after candidate release")
}
})
}
if err := verifyCandidate(filepath.Join(t.TempDir(), "missing")); err == nil {
t.Fatal("verification accepted a missing executable")
}
}
+5 -1
View File
@@ -8,6 +8,10 @@ const fs = require('fs');
const { spawnSync } = require('child_process');
const isWindows = process.platform === 'win32';
// How long the cached binary may take to answer --version: the same bound as
// CANDIDATE_TIMEOUT_MS in install.js (test/candidate-bound.test.js keeps the two
// equal; the launcher stays self-contained and does not load the installer).
const CANDIDATE_TIMEOUT_MS = 300_000;
// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,
// so the cached file is the executed file — there is no launcher pair to keep
// in sync and no adjacent payload to validate.
@@ -22,7 +26,7 @@ const cacheReady = () => {
// A cached Windows binary that cannot report its own version is not usable.
const probe = spawnSync(binPath, ['--version'], {
stdio: 'ignore',
timeout: 15_000,
timeout: CANDIDATE_TIMEOUT_MS,
windowsHide: true,
});
return !probe.error && probe.status === 0;
+6 -1
View File
@@ -17,7 +17,11 @@ const VERSION = require('./package.json').version;
const BIN_DIR = path.join(__dirname, 'bin');
const MAX_REDIRECTS = 5;
const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;
const CANDIDATE_TIMEOUT_MS = 15_000;
// How long a downloaded or cached binary may take to answer --version. A slow
// host (antivirus scan, emulation, first page-in) can need far more than a few
// seconds, but a candidate that never answers must not hang the start forever.
// Keep in sync with the Go wrapper (candidateVerifyBound) and the PyPI wrapper.
const CANDIDATE_TIMEOUT_MS = 300_000;
// Entry-count guard for the zip namespace check. Keep in sync with the Go
// wrapper (pkg/go/cmd/codebase-memory-mcp/main.go) and the PyPI wrapper.
const MAX_ARCHIVE_MEMBERS = 64;
@@ -840,6 +844,7 @@ if (require.main === module || module.parent == null) {
}
module.exports = {
CANDIDATE_TIMEOUT_MS,
UNIX_ARCHIVE_NAMES,
WINDOWS_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const { CANDIDATE_TIMEOUT_MS } = require('../install.js');
// A slow host can need far more than 15 s to run a fresh binary's --version
// (#2877), while a candidate that never answers must still release the start.
// The Go wrapper (candidateVerifyBound) and the PyPI wrapper use the same bound.
test('candidate verification waits minutes, not seconds', () => {
assert.ok(CANDIDATE_TIMEOUT_MS >= 120_000, `bound is ${CANDIDATE_TIMEOUT_MS} ms`);
});
test('the launcher probes a cached binary with the same bound', () => {
const bin = fs.readFileSync(path.join(__dirname, '..', 'bin.js'), 'utf8');
const declared = bin.match(/const CANDIDATE_TIMEOUT_MS = ([\d_]+);/);
assert.ok(declared, 'bin.js declares its own CANDIDATE_TIMEOUT_MS');
assert.strictEqual(Number(declared[1].replace(/_/g, '')), CANDIDATE_TIMEOUT_MS);
assert.match(bin, /timeout: CANDIDATE_TIMEOUT_MS/);
assert.doesNotMatch(bin, /timeout:\s*\d/);
});
+4 -1
View File
@@ -46,7 +46,10 @@ _LOOPBACK_HTTP_URL = re.compile(
_LOOPBACK_HOSTNAMES = frozenset({"localhost", "127.0.0.1", "::1"})
_MAX_REDIRECTS = 5
_NETWORK_TIMEOUT_SECONDS = 120
_CANDIDATE_TIMEOUT_SECONDS = 15
# How long a downloaded binary may take to answer --version: generous for a
# slow host, finite so a candidate that never answers cannot hang the start.
# Keep in sync with the Go wrapper (candidateVerifyBound) and the npm wrapper.
_CANDIDATE_TIMEOUT_SECONDS = 300
# Entry-count guard for the archive namespace check. Keep in sync with the
# Go wrapper (pkg/go/cmd/codebase-memory-mcp/main.go) and the npm wrapper.
_MAX_ARCHIVE_MEMBERS = 64
+13
View File
@@ -113,6 +113,19 @@ class BinarySelectionTests(unittest.TestCase):
self.assertNotIn("install.sh", output)
class CandidateVerifyBoundTests(unittest.TestCase):
def test_candidate_verification_waits_minutes(self):
# A slow host can need far more than 15 s to run a fresh binary's
# --version (#2877); a candidate that never answers must still release
# the start. Same bound as the Go wrapper and the npm wrapper.
self.assertGreaterEqual(_cli._CANDIDATE_TIMEOUT_SECONDS, 120)
def test_verify_candidate_passes_the_bound(self):
with mock.patch.object(_cli.subprocess, "run") as run:
_cli._verify_candidate(Path("candidate"))
self.assertEqual(run.call_args.kwargs["timeout"], _cli._CANDIDATE_TIMEOUT_SECONDS)
class ProcessLivenessTests(unittest.TestCase):
def test_windows_probe_never_calls_os_kill(self):
with mock.patch.object(_cli.os, "name", "nt"), mock.patch.object(
+4 -2
View File
@@ -24,7 +24,8 @@
# scripts/test-impact/predict.py map it to suites with the lane
# selector's run-all triggers. Writes DIR/prediction.json and
# DIR/summary.md (appended to $GITHUB_STEP_SUMMARY when set). The
# graph is only consulted when C sources changed.
# graph is only consulted when C sources changed and the lane
# selector has not already required every suite.
# Exit: 0 = prediction written · 1 = the tooling broke · 2 = usage error.
set -euo pipefail
@@ -135,7 +136,8 @@ VERSION=$("$BINARY" --version 2>/dev/null | head -1 || true)
DETECT_ARGS=()
T_INDEX="-"
T_DETECT="-"
if [ "$(python3 "$PREDICT" --needs-graph --changed "$OUT/changed-files.txt")" = yes ]; then
if [ "$(python3 "$PREDICT" --needs-graph --changed "$OUT/changed-files.txt" \
--selection "$OUT/selection.json")" = yes ]; then
python3 -c 'import json, sys; json.dump({"repo_path": sys.argv[1]}, open(sys.argv[2], "w"))' \
"$ROOT" "$WORK/index-args.json"
t0=$(date +%s)
+2
View File
@@ -52,6 +52,8 @@ if ! "${PYTHON[@]}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3
exit 2
fi
"${PYTHON[@]}" "$ROOT/tests/test_smoke_wrapper_run.py"
echo "=== Package wrapper: Go ==="
(
cd "$ROOT/pkg/go"
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Run a wrapper smoke command; reserve the outer bound for hang diagnosis."""
import os
import signal
import subprocess
import sys
def run(command, timeout=600):
process = subprocess.Popen(command, start_new_session=os.name != "nt")
try:
return process.wait(timeout=timeout)
except subprocess.TimeoutExpired:
print("HANG go: wrapper smoke did not complete within the outer bound "
"(download, verification or execution); terminating its process tree",
file=sys.stderr, flush=True)
# Kill descendants too: killing only the wrapper leaves its verifier alive.
if os.name == "nt":
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
check=True, timeout=30)
else:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait(timeout=30)
return 124
if __name__ == "__main__":
try:
result = run(sys.argv[1:])
except (OSError, subprocess.SubprocessError) as error:
print(f"wrapper smoke could not run or clean up: {error}", file=sys.stderr)
sys.exit(125)
sys.exit(result if result >= 0 else 128 - result)
+12 -2
View File
@@ -140,8 +140,18 @@ smoke_go() {
ran go "$dir/install.log" "$rc"
return
fi
# The first run downloads the binary into the wrapper's cache.
isolated "$dir" "$dir/codebase-memory-mcp$EXE" --version >"$dir/run.log" 2>&1 || rc=$?
local py=""
if command -v python3 >/dev/null 2>&1; then
py=python3
elif command -v python >/dev/null 2>&1; then
py=python
else
missing go "Python 3 (outer hang guard)"
return
fi
# The first run downloads the binary. The outer guard diagnoses hangs;
# the verifier itself waits for the binary's exit, regardless of runner speed.
isolated "$dir" "$py" "$ROOT/scripts/smoke-wrapper-run.py" "$dir/codebase-memory-mcp$EXE" --version >"$dir/run.log" 2>&1 || rc=$?
ran go "$dir/run.log" "$rc"
}
+6 -4
View File
@@ -18,7 +18,7 @@ The mapping is the one the September 2026 test-impact replay measured
Usage: predict.py --root DIR --changed FILE --selection FILE [--detect FILE]
[--depth N] [--meta JSON] --out FILE [--summary FILE]
predict.py --needs-graph --changed FILE (prints yes|no)
predict.py --needs-graph --changed FILE [--selection FILE] (prints yes|no)
"""
import argparse
import json
@@ -205,13 +205,15 @@ def main():
a = ap.parse_args()
with open(a.changed, encoding="utf-8") as fh:
changed = sorted({line.strip() for line in fh if line.strip()})
selection = {}
if a.selection:
with open(a.selection, encoding="utf-8") as fh:
selection = json.load(fh)
if a.needs_graph:
print("yes" if needs_graph(changed) else "no")
print("yes" if needs_graph(changed) and not selection.get("full") else "no")
return 0
if not (a.root and a.selection and a.out):
ap.error("--root, --selection and --out are required")
with open(a.selection, encoding="utf-8") as fh:
selection = json.load(fh)
detect = None
if a.detect:
with open(a.detect, encoding="utf-8") as fh:
+1
View File
@@ -160,6 +160,7 @@ try {
# UI (build target cbm-with-ui); against a non-UI binary it reports a precondition
# (exit 2) and is skipped rather than failed.
$guards = @(
"tests\windows\test_worker_trace.py",
"tests\windows\test_non_ascii_path.py",
"tests\windows\test_non_ascii_cache_dump.py",
"tests\windows\test_daemon_lifecycle.py",
+10 -10
View File
@@ -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
7c4610803c12921f49279f3f4ca679dfb3081ac776475b7bcc2e0a4edc92c67b internal/cbm/vendored/grammars/MANIFEST.md
4f8164ae42590e751bdbd96f419ee3d8e8e78b1478190fcbaa1f1d15a9c572b5 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
@@ -134,7 +134,7 @@ daf550976dc40608917b1f16b5c8b21773111bdd2a7fcc23c5e5fec3737055f5 internal/cbm/v
c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/cmake/tree_sitter/parser.h
1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/cobol/LICENSE
d40a31d4854a2d82977c74d33c3ee9c004d9e63743176ebc84159a1734db7b2b internal/cbm/vendored/grammars/cobol/parser.c
0e146beb0331e4f95e2fb815e263c649f2bc404b35dd1b19eb125cbd4ed95df8 internal/cbm/vendored/grammars/cobol/scanner.c
6958b5867131d6ed02964da9a2a7b5e68db461253c6b122d90c5307055ef3d8c internal/cbm/vendored/grammars/cobol/scanner.c
8e819abdeba5866bf1aaf6e7b97522241c903d94a18395c6a75ed02984270ee8 internal/cbm/vendored/grammars/cobol/tree_sitter/parser.h
00bb7f417416e8233ae465209e72eaa6162d53b061add7d9bed0238552a6fa0c internal/cbm/vendored/grammars/commonlisp/LICENSE
27082ecef6f3fe6c09aaf2488b2003f031a165d23b15179ad6c2b52bf47b05ff internal/cbm/vendored/grammars/commonlisp/parser.c
@@ -523,18 +523,18 @@ c5fa4d1d5820cc59f39cb3cb9a9a171e5144b2f63d285cf3450be0a8e549ede8 internal/cbm/v
02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/objc/tree_sitter/array.h
2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/objc/tree_sitter/parser.h
85b458dc150c4d17873dd5e73d01cfa23c797997a09d841884e08378242e929c internal/cbm/vendored/grammars/objectscript_routine/LICENSE
f3a047fba6d238da258c0370878e703504b347aad13add09a021935daa891bd3 internal/cbm/vendored/grammars/objectscript_routine/objectscript_common.h
fb9320a77f7c3c110540e9a569c2a8dd7ff74784ae05aac962f4bcbab1343640 internal/cbm/vendored/grammars/objectscript_routine/parser.c
1da66e46ba02fcf2f9ca42b2a80c8658e150ae7b5154d81b8968117b959b5af7 internal/cbm/vendored/grammars/objectscript_routine/scanner.c
7aeb5b2933b7cb65f9714bc14ba1aff98bec3e5f2351d2e5199c2c1b477a3ba8 internal/cbm/vendored/grammars/objectscript_routine/objectscript_common.h
d496de950b085853fdf1edf1570eecdb5d2e4525344873bfabf7e34ac8e7add0 internal/cbm/vendored/grammars/objectscript_routine/parser.c
073b64efe3eff37b1a6c3f76ac99d5b5533094591dd9d329bee3982121469d04 internal/cbm/vendored/grammars/objectscript_routine/scanner.c
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/alloc.h
31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/array.h
20e6ba85abb9d5b7e2e6dedf675c9424a057a06feee03aa3e2dd48a1cb4bf8a2 internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/array.h
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/parser.h
85b458dc150c4d17873dd5e73d01cfa23c797997a09d841884e08378242e929c internal/cbm/vendored/grammars/objectscript_udl/LICENSE
f3a047fba6d238da258c0370878e703504b347aad13add09a021935daa891bd3 internal/cbm/vendored/grammars/objectscript_udl/objectscript_common.h
2003ffb1a07ec30a2f7176c65aae958b804074af8356a81a3d42417a240f2e15 internal/cbm/vendored/grammars/objectscript_udl/parser.c
537be452c5079531e08edc302b65c63f45956510f6ee96ec88c1d7531d203f1e internal/cbm/vendored/grammars/objectscript_udl/scanner.c
7aeb5b2933b7cb65f9714bc14ba1aff98bec3e5f2351d2e5199c2c1b477a3ba8 internal/cbm/vendored/grammars/objectscript_udl/objectscript_common.h
0c0c651b4a425cb8a00cdf6b8c89aeea702cb5799a9483d9994556655f441015 internal/cbm/vendored/grammars/objectscript_udl/parser.c
4d991526fa0930d023cbea841aa80298391142dbb58977f197d580f86a00b968 internal/cbm/vendored/grammars/objectscript_udl/scanner.c
b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/alloc.h
31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/array.h
20e6ba85abb9d5b7e2e6dedf675c9424a057a06feee03aa3e2dd48a1cb4bf8a2 internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/array.h
180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/parser.h
f977a20805dd6e275f14bc090a5f8e638401dad4df366841c1060f12c75b74ae internal/cbm/vendored/grammars/ocaml/LICENSE
e4934793536f53c076b24b16de2f6a48a125c632e6cce58c80c02d6d65f8dbed internal/cbm/vendored/grammars/ocaml/_common_scanner.h
+142 -2
View File
@@ -1827,7 +1827,7 @@ static const char released_skill_content_v0_10_3[] =
#undef CBM_RELEASED_SKILL_HEADER_QUOTED
#undef CBM_RELEASED_SKILL_HEADER_UNQUOTED
static const char skill_content[] =
static const char released_skill_content_v0_12_1[] =
"---\n"
"name: codebase-memory\n"
/* #1554: the value contains "Triggers on: " — a colon-space, which YAML
@@ -1948,6 +1948,144 @@ static const char skill_content[] =
"`direction=\"both\"`.\n"
"5. `search_graph` results default to 50 per page — check `has_more` and use `offset`.\n";
static const char skill_content[] =
"---\n"
"name: codebase-memory\n"
/* #1554: the value contains "Triggers on: " — a colon-space, which YAML
* reads as a nested-mapping indicator inside an unquoted scalar. Strict
* parsers (js-yaml's load, the frontmatter reader in `npx skills`) reject
* the whole file, so the skill silently fails to load rather than loading
* wrongly. Quoting the scalar is the fix; the text itself is unchanged. */
"description: \"Use the codebase knowledge graph for structural code queries. "
"Triggers on: explore the codebase, understand the architecture, what functions exist, "
"show me the structure, who calls this function, what does X call, trace the call chain, "
"find callers of, show dependencies, impact analysis, dead code, unused functions, "
"high fan-out, refactor candidates, code quality audit, graph query syntax, "
"Cypher query examples, edge types, how to use search_graph.\"\n"
"---\n"
"\n"
"# Codebase Memory — Knowledge Graph Tools\n"
"\n"
"Graph tools return precise structural results in ~500 tokens vs ~80K for grep.\n"
"\n"
"## Quick Decision Matrix\n"
"\n"
"| Question | Tool call |\n"
"|----------|----------|\n"
"| Who calls X? | `trace_path(direction=\"inbound\")` |\n"
"| What does X call? | `trace_path(direction=\"outbound\")` |\n"
"| Full call context | `trace_path(direction=\"both\")` |\n"
"| Find by name pattern | `search_graph(name_pattern=\"...\")` |\n"
"| Dead-code candidates | `query_graph` with inbound `NOT EXISTS` (see below) |\n"
"| Cross-service edges | `query_graph` with Cypher |\n"
"| Impact of local changes | `detect_changes()` |\n"
"| Risk-classified trace | `trace_path(risk_labels=true)` |\n"
"| Text search | `search_code` or Grep |\n"
"\n"
"## Exploration Workflow\n"
/* #1690: a guessed repo or folder name misses the project whenever the
* checkout directory differs from it; the root_path is what identifies it. */
"1. `list_projects` — pick the project whose `root_path` contains your working directory; "
"pass its `name` (or the absolute directory itself) as `project`, never a repo or folder "
"name\n"
"2. `get_graph_schema` — understand node/edge types\n"
"3. `search_graph(label=\"Function\", name_pattern=\".*Pattern.*\")` — find code\n"
"4. `get_code_snippet(qualified_name=\"project.path.FuncName\")` — read source\n"
"\n"
"## Tracing Workflow\n"
"1. `search_graph(name_pattern=\".*FuncName.*\")` — discover exact name\n"
"2. `trace_path(function_name=\"FuncName\", direction=\"both\", depth=3)` — trace\n"
"3. `detect_changes()` — map git diff to affected symbols\n"
"\n"
"## Evidence Tiers\n"
"- **Scout (Tier 1):** fast positive lookup with few graph calls and targeted source checks. "
"Treat results as provisional; never make absence, exhaustive, dead-code, or complete-impact "
"claims.\n"
"- **Verify (Tier 2, default):** task-directed searches, relevant trace directions, exact "
"snippets for material claims, and all relevant result pages.\n"
"- **Auditor (Tier 3):** bounded-scope full verification with a current graph generation, "
"complete relevant pagination, both call directions and broader relationships when material, "
"plus explicit unresolved limitations.\n"
"- **Every tier:** after candidate paths are known, call `check_index_coverage` once with "
"every "
"evidence path. For negative or exhaustive claims also include the relevant scopes. A clean "
"result means no recorded gap, not proof of completeness. For partial, skipped, excluded, "
"stale, pending, or unknown coverage, read/grep the reported ranges or scope before relying on "
"the graph.\n"
"\n"
"## Sessions and Subagents\n"
"- At session start or after compaction, call `list_projects`/`index_status` before "
"structural exploration, then choose Scout, Verify, or Auditor for the task.\n"
"- Before delegating, query the graph and coverage in the parent. Pass the tier, exact "
"project, "
"generation/freshness, bounded scope, queries and pagination state, qualified symbols, paths, "
"call-chain findings, coverage ranges/reasons, source fallback already performed, and "
"unresolved "
"questions to the child.\n"
"- Runtimes such as Hermes isolate child context: put those graph findings in the "
"`context` argument to `delegate_task`; do not assume the child inherits MCP access or "
"the parent's conversation.\n"
"- A child without MCP tools must not call or claim MCP access. It should work from the "
"supplied "
"evidence and use read/grep on exact source, especially every reported missed-coverage range.\n"
"\n"
"## Quality Analysis\n"
"- No indexed callers: use `query_graph` with:\n"
" `MATCH (f:Function) WHERE NOT EXISTS { (f)<-[:CALLS]-() } AND NOT EXISTS { "
"(f)<-[:CALL_REFERENCE]-() } RETURN f.name, f.file_path`\n"
" (one edge type per EXISTS; a callback passed by reference has a CALL_REFERENCE). "
"Repeat for `Method` as needed. These are candidates: verify coverage, entry points, "
"callbacks and dynamic dispatch before removing code.\n"
"- `search_graph(max_degree=0, exclude_entry_points=true)` finds isolated symbols: "
"degree is incoming plus outgoing CALLS/USAGE/CALL_REFERENCE/INHERITS/IMPLEMENTS. "
"An uncalled function that calls another function is not isolated.\n"
"- High fan-out: `search_graph(min_degree=10, relationship=\"CALLS\", "
"direction=\"outbound\")`\n"
"- High fan-in: `search_graph(min_degree=10, relationship=\"CALLS\", "
"direction=\"inbound\")`\n"
"\n"
"## 17 MCP Tools\n"
"`index_repository`, `index_status`, `list_projects`, `delete_project`,\n"
"`search_graph`, `search_code`, `trace_path`, `detect_changes`,\n"
"`query_graph`, `get_graph_schema`, `get_code_snippet`, `get_file_outline`,\n"
"`get_architecture`, `compare_graphs`, `check_index_coverage`, `manage_adr`,\n"
"`ingest_traces`\n"
"\n"
"## Semantic Queries\n"
"`search_graph(semantic_query=[\"handle\",\"scan\"])` takes individual keywords, "
"not natural-language sentences. Each array element is looked up as one token, "
"and the score is the minimum cosine across elements. Unknown tokens use "
"deterministic sparse-random vectors, so they can suppress useful matches. "
"Use `query` for BM25 text search. A non-empty `semantic_query` cannot be combined with "
"`query`; an empty array is ignored.\n"
"\n"
"## Edge Types\n"
"CALLS, HTTP_CALLS, ASYNC_CALLS, SPAWNS, DATA_FLOWS, IMPORTS, DEFINES, DEFINES_METHOD,\n"
"HANDLES, IMPLEMENTS, OVERRIDE, USAGE, CALL_REFERENCE, CONFIGURES, REFERENCES_FILE,\n"
"MENTIONS (doc comment -> referenced code), FILE_CHANGES_WITH, SIMILAR_TO,\n"
"SEMANTICALLY_RELATED, CONTAINS_FILE, CONTAINS_FOLDER,\n"
"INFRA_MAPS (K8s Service -> selected workloads), DEPENDS_ON (chart / manifest -> dependency),\n"
"DEPLOYS (what puts manifests / charts on a cluster -> what it puts there),\n"
"CONNECTS_TO (workload / compose service -> the Service its environment addresses)\n"
"\n"
"## Cypher Examples (for query_graph)\n"
"```\n"
"MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, "
"r.confidence LIMIT 20\n"
"MATCH (f:Function) WHERE f.name =~ '.*Handler.*' RETURN f.name, f.file_path\n"
"MATCH (a)-[r:CALLS]->(b) WHERE a.name = 'main' RETURN b.name\n"
"```\n"
"\n"
"## Gotchas\n"
"1. `search_graph(relationship=\"HTTP_CALLS\")` filters nodes by degree — "
"use `query_graph` with Cypher to see actual edges.\n"
"2. `query_graph` has a 100k row ceiling — add a Cypher `LIMIT` for broad queries "
"or use `search_graph` pagination.\n"
"3. `trace_path` needs exact names — use `search_graph(name_pattern=...)` first.\n"
"4. `direction=\"outbound\"` misses cross-service callers — use "
"`direction=\"both\"`.\n"
"5. `search_graph` results default to 50 per page — check `has_more` and use `offset`.\n";
/* Byte-exact consolidated skill payloads shipped by each release range. */
static const char *const released_skill_contents[] = {
/* 0.6.0 through v0.9.0 */
@@ -1958,8 +2096,10 @@ static const char *const released_skill_contents[] = {
released_skill_content_v0_10_0,
/* v0.10.3 through v0.10.8 */
released_skill_content_v0_10_3,
/* v0.12.1 / main before the query-guidance correction */
released_skill_content_v0_12_1,
};
enum { RELEASED_SKILL_CONTENT_COUNT = 4 };
enum { RELEASED_SKILL_CONTENT_COUNT = 5 };
static const char codex_instructions_content[] =
"For structural codebase exploration, use the installed `codebase-memory` skill.\n";
+6
View File
@@ -4757,12 +4757,18 @@ static int with_agg_find_or_create(with_agg_t **aggs, int *agg_cnt, int *agg_cap
return found;
}
static bool binding_has_value(binding_t *b, const char *var, const char *prop);
/* Accumulate aggregation values for a binding */
static void with_agg_accumulate(with_agg_t *agg, cbm_return_clause_t *wc, binding_t *b) {
for (int ci = 0; ci < wc->count; ci++) {
if (!is_aggregate_func(wc->items[ci].func)) {
continue;
}
if (strcmp(wc->items[ci].func, "COUNT") == 0 &&
!binding_has_value(b, wc->items[ci].variable, wc->items[ci].property)) {
continue;
}
agg->counts[ci]++;
const char *raw = binding_get_virtual(b, wc->items[ci].variable, wc->items[ci].property);
if (wc->items[ci].distinct && strcmp(wc->items[ci].func, "COUNT") == 0) {
+56 -6
View File
@@ -2020,6 +2020,43 @@ static bool posix_directory_transition_secure(int parent_fd, int child_fd, const
return true;
}
/* #3014: where the system has O_PATH, the walk holds each directory by an
* O_PATH handle. Every check below reads the handle (fstat, fstatfs), so the
* ownership, mode and symlink rules are unchanged, and a process confined by
* Landlock can validate ancestors it is not allowed to list: an O_RDONLY
* directory open needs the read-directory right on "/" and on every ancestor,
* an O_PATH open needs none. A handle that is chmod'ed or handed to the caller
* is first reopened through itself, which cannot name another directory. */
#if defined(__linux__) && !defined(O_PATH)
#error "O_PATH is not visible; the private-directory walk needs it on Linux"
#endif
#ifdef O_PATH
#define PRIVATE_DIRECTORY_WALK_OPEN (O_PATH | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)
#else
#define PRIVATE_DIRECTORY_WALK_OPEN (O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)
#endif
/* Replace a walk handle with an ordinary directory descriptor for the same
* directory. False leaves *directory_fd as it was. */
static bool private_directory_walk_reopen(int *directory_fd) {
#ifdef O_PATH
int opened = openat(*directory_fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
if (opened < 0 || !fd_set_cloexec(opened)) {
if (opened >= 0) {
int saved_errno = errno;
(void)close(opened);
errno = saved_errno;
}
return false;
}
(void)close(*directory_fd);
*directory_fd = opened;
#else
(void)directory_fd;
#endif
return true;
}
static int private_directory_tree_open(const char *directory_path) {
if (!directory_path || !directory_path[0] || O_DIRECTORY == 0 || O_NOFOLLOW == 0) {
return -1;
@@ -2029,7 +2066,7 @@ static int private_directory_tree_open(const char *directory_path) {
return -1;
}
bool absolute = path[0] == '/';
int current_fd = open(absolute ? "/" : ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
int current_fd = open(absolute ? "/" : ".", PRIVATE_DIRECTORY_WALK_OPEN);
bool ok = current_fd >= 0 && fd_set_cloexec(current_fd);
char *cursor = path;
while (ok && *cursor == '/') {
@@ -2084,16 +2121,22 @@ static int private_directory_tree_open(const char *directory_path) {
if (!created && errno != EEXIST) {
ok = false;
}
int next_fd =
ok ? openat(current_fd, component, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW)
: -1;
int next_fd = ok ? openat(current_fd, component, PRIVATE_DIRECTORY_WALK_OPEN) : -1;
struct stat status;
ok = next_fd >= 0 && fd_set_cloexec(next_fd) && fstat(next_fd, &status) == 0 &&
S_ISDIR(status.st_mode) &&
posix_directory_transition_secure(current_fd, next_fd, path);
if (ok && created) {
ok = status.st_uid == geteuid() && fchmod(next_fd, 0700) == 0 &&
cbm_macos_extended_acl_fd_clear(next_fd) &&
ok = status.st_uid == geteuid();
if (ok && !private_directory_walk_reopen(&next_fd)) {
ipc_validation_detail_set(
"%s: could not reopen the new directory '%s' to set its mode (errno %d; "
"it needs owner execute permission and, in a sandbox, the right to "
"list it)",
directory_path, component, errno);
ok = false;
}
ok = ok && fchmod(next_fd, 0700) == 0 && cbm_macos_extended_acl_fd_clear(next_fd) &&
cbm_macos_extended_acl_fd_is_empty(next_fd);
}
if (ok) {
@@ -2124,6 +2167,13 @@ static int private_directory_tree_open(const char *directory_path) {
(long)final_status.st_uid, (long)geteuid());
ok = false;
}
if (ok && !private_directory_walk_reopen(&current_fd)) {
ipc_validation_detail_set("%s: could not reopen the directory to set its mode (errno %d; "
"it needs owner execute permission and, in a sandbox, the "
"right to list it)",
directory_path, errno);
ok = false;
}
if (ok && fchmod(current_fd, 0700) != 0) {
ipc_validation_detail_set("%s: chmod 0700 failed (errno %d)", directory_path, errno);
ok = false;
+24 -11
View File
@@ -581,8 +581,8 @@ static const tool_def_t TOOLS[] = {
"\"relationship\":{\"type\":\"string\"},\"min_degree\":{\"type\":\"integer\"},"
"\"max_degree\":{\"type\":\"integer\"},\"exclude_entry_points\":{\"type\":\"boolean\"},"
"\"include_connected\":{\"type\":\"boolean\"},\"semantic_query\":{"
"\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"[] ignored; "
"otherwise omit query.\"},"
"\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Keywords; [] ignored; "
"else omit query.\"},"
"\"semantic_limit\":{\"type\":\"integer\",\"default\":50,\"minimum\":0,"
"\"maximum\":500},"
"\"semantic_offset\":{\"type\":\"integer\",\"default\":0,\"minimum\":0,"
@@ -20754,21 +20754,34 @@ static char *handle_detect_changes(cbm_mcp_server_t *srv, const char *args) {
int hunk_count = 0;
if (!seed_rows.failed && (want_symbols || seed_req.list)) {
char hunk_cmd[CBM_SZ_2K];
int hunk_len;
#ifdef _WIN32
snprintf(hunk_cmd, sizeof(hunk_cmd),
"git -C \"%s\" diff --relative --unified=0 \"%s\" \"%s\" -- 2>NUL && "
"git -C \"%s\" diff --relative --unified=0 -- 2>NUL",
root_path, merge_base, head_oid, root_path);
hunk_len =
snprintf(hunk_cmd, sizeof(hunk_cmd),
"git -C \"%s\" " CBM_TEST_IMPACT_GIT_PINS
" diff --relative " CBM_TEST_IMPACT_DIFF_FLAGS " \"%s\" \"%s\" -- 2>NUL && "
"git -C \"%s\" " CBM_TEST_IMPACT_GIT_PINS
" diff --relative " CBM_TEST_IMPACT_DIFF_FLAGS " -- 2>NUL",
root_path, merge_base, head_oid, root_path);
#else
snprintf(hunk_cmd, sizeof(hunk_cmd),
"git -C '%s' diff --relative --unified=0 '%s' '%s' -- 2>/dev/null && "
"git -C '%s' diff --relative --unified=0 -- 2>/dev/null",
root_path, merge_base, head_oid, root_path);
hunk_len =
snprintf(hunk_cmd, sizeof(hunk_cmd),
"git -C '%s' " CBM_TEST_IMPACT_GIT_PINS
" diff --relative " CBM_TEST_IMPACT_DIFF_FLAGS " '%s' '%s' -- 2>/dev/null && "
"git -C '%s' " CBM_TEST_IMPACT_GIT_PINS
" diff --relative " CBM_TEST_IMPACT_DIFF_FLAGS " -- 2>/dev/null",
root_path, merge_base, head_oid, root_path);
#endif
/* A root path long enough to truncate the command would run a cut-off
* git command (an error, or a flag list without --unified=0): skip hunk
* scoping instead, which leaves whole-file seeding. */
bool hunk_cmd_fits = hunk_len > 0 && (size_t)hunk_len < sizeof(hunk_cmd);
char hunk_output_path[CBM_SZ_2K] = {0};
cbm_proc_result_t hunk_result = {0};
int hunk_run =
mcp_run_shell_command_cancellable(srv, hunk_cmd, hunk_output_path, &hunk_result);
hunk_cmd_fits
? mcp_run_shell_command_cancellable(srv, hunk_cmd, hunk_output_path, &hunk_result)
: -1;
bool hunk_cancelled = hunk_result.cancellation_requested || mcp_request_cancelled(srv);
FILE *hfp = (!hunk_cancelled && hunk_run == 0 && hunk_result.exit_code == 0)
? cbm_fopen(hunk_output_path, "rb")
+3 -1
View File
@@ -244,7 +244,9 @@ static bool pr_index_packages(pr_index_t *ix, const cbm_doclink_build_in_t *in)
if (ix->oom) {
return false;
}
qsort(ix->decls, (size_t)ix->ndecls, sizeof(pr_decl_t), pr_decl_cmp);
if (ix->ndecls > SKIP_ONE) {
qsort(ix->decls, (size_t)ix->ndecls, sizeof(pr_decl_t), pr_decl_cmp);
}
ix->pkg = cbm_ht_create_in(CBM_MEM_CLASS_OTHER, (uint32_t)(ix->ndecls + SKIP_ONE));
if (!ix->pkg) {
return false;
+3
View File
@@ -405,6 +405,9 @@ static void rr_destroy(void *index) {
/* The documentation set a document belongs to: the nearest conf.py at or
* above its directory; NULL for none. */
static const rr_conf_t *rr_conf_for(const rr_index_t *x, const char *doc) {
if (x->nconfs == 0) {
return NULL;
}
char dir[RR_PATH_CAP];
const char *b = rr_base(doc);
size_t dl = b > doc ? (size_t)(b - doc - SKIP_ONE) : 0;
+529
View File
@@ -0,0 +1,529 @@
/*
* include_path.c — the path rule; see include_path.h.
*
* Lifted from the parked include-scope branch (round 5, include_scope.c,
* "2. The include path"): is_join, is_dirname, the listing (is_list,
* is_list_add, the suffix index), is_pick, is_unique_tail and the import
* node. The names a listing keeps come from the rows instead of a table per
* language; evaluated shell and Make paths, run directories and proven
* absence are not part of this rule.
*/
#include "pipeline/include_path.h"
#include "foundation/arena.h"
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/hash_table.h"
#include "foundation/log.h"
#include "foundation/mem_core.h"
#include "foundation/sha256.h"
#include "graph_buffer/graph_buffer.h"
#include "pipeline/pipeline_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { IP_PATH_MAX = 1024, IP_UP_LEN = 3 /* "../" */ };
/* ── Rows ────────────────────────────────────────────────────────────── */
static const char *const IP_PROTO_SUFFIXES[] = {".proto", NULL};
static const char *const IP_MAKE_SUFFIXES[] = {".mk", ".make", NULL};
static const char *const IP_MAKE_PREFIXES[] = {"Makefile", "makefile", "GNUmakefile", NULL};
static const cbm_include_path_row_t IP_ROWS[] = {
/* Protobuf: `import "a/b.proto"` names the one indexed file that is that
* path or ends with it. When several do, the file beside the importer is
* only a guess (protoc reads the one under its -I root). A row that names
* no `.proto` file, or a path protoc refuses, is not read as a path. */
{.lang = CBM_LANG_PROTOBUF,
.suffixes = IP_PROTO_SUFFIXES,
.path_needs_suffix = true,
.virtual_path = true,
.base_file_dir = true,
.whole_path_tail = true},
/* Make: `include x.mk` names the file from the makefile's directory or
* the repository root, and only when exactly one of them is a file. Below
* the root that is a guess: GNU make reads a relative include from the
* directory it runs in, which the index does not know. */
{.lang = CBM_LANG_MAKEFILE,
.suffixes = IP_MAKE_SUFFIXES,
.prefixes = IP_MAKE_PREFIXES,
.base_file_dir = true,
.base_root = true,
.exactly_one = true},
};
const cbm_include_path_row_t *cbm_include_path_row(CBMLanguage lang) {
for (size_t i = 0; i < sizeof(IP_ROWS) / sizeof(IP_ROWS[0]); i++) {
if (IP_ROWS[i].lang == lang) {
return &IP_ROWS[i];
}
}
return NULL;
}
static bool ip_has_suffix(const char *name, const char *suffix) {
size_t n = strlen(name);
size_t s = strlen(suffix);
return n > s && strcmp(name + n - s, suffix) == 0;
}
static bool ip_row_names(const cbm_include_path_row_t *row, const char *name) {
for (const char *const *s = row->suffixes; s && *s; s++) {
if (ip_has_suffix(name, *s)) {
return true;
}
}
for (const char *const *p = row->prefixes; p && *p; p++) {
if (strncmp(name, *p, strlen(*p)) == 0) {
return true;
}
}
return false;
}
bool cbm_include_path_listed_name(const char *name) {
for (size_t i = 0; name && i < sizeof(IP_ROWS) / sizeof(IP_ROWS[0]); i++) {
if (ip_row_names(&IP_ROWS[i], name)) {
return true;
}
}
return false;
}
/* ── Paths ───────────────────────────────────────────────────────────── */
/* `rel` (./ and ../ allowed) inside repository directory `base` ("" = the
* root), normalized into out; false when it leaves the repository or does
* not fit. */
static bool ip_join(char *out, size_t sz, const char *base, const char *rel) {
size_t n = 0;
out[0] = '\0';
const char *parts[2] = {base, rel};
for (int k = 0; k < 2; k++) {
for (const char *p = parts[k]; p && *p;) {
while (*p == '/') {
p++;
}
size_t sl = strcspn(p, "/");
if (sl == 0) {
break;
}
if (sl == 1 && p[0] == '.') {
p += sl;
continue;
}
if (sl == 2 && p[0] == '.' && p[1] == '.') {
if (n == 0) {
return false;
}
while (n > 0 && out[n - 1] != '/') {
n--;
}
if (n > 0) {
n--;
}
out[n] = '\0';
p += sl;
continue;
}
if (n + sl + 2 > sz) {
return false;
}
if (n) {
out[n++] = '/';
}
memcpy(out + n, p, sl);
n += sl;
out[n] = '\0';
p += sl;
}
}
return n > 0;
}
/* The directory of rel ("" at the root); false when it does not fit. */
static bool ip_dirname(char *out, size_t sz, const char *rel) {
const char *slash = strrchr(rel, '/');
size_t n = slash ? (size_t)(slash - rel) : 0;
if (n >= sz) {
return false;
}
memcpy(out, rel, n);
out[n] = '\0';
return true;
}
/* ── The universe: the run's indexed files ───────────────────────────── */
typedef struct {
const char *path; /* the one path with this tail, or the first of several */
int n;
} ip_tail_t;
struct cbm_include_universe {
CBMArena arena;
CBMHashTable *listed; /* rel -> non-NULL */
CBMHashTable *tails; /* every path suffix on a '/' boundary -> ip_tail_t */
/* the same suffixes in lower case: a path that matches one only when case
* is ignored is not known absent (a case-insensitive disk opens it) */
CBMHashTable *ftails;
/* false when an indexed path did not fit the rule's buffers: then no
* uniqueness and no absence is proven */
bool complete;
uint64_t tail_steps; /* suffix keys made while building */
};
void cbm_include_universe_free(cbm_include_universe_t *u) {
if (!u) {
return;
}
if (u->listed) {
cbm_ht_free(u->listed);
}
if (u->tails) {
cbm_ht_free(u->tails);
}
if (u->ftails) {
cbm_ht_free(u->ftails);
}
cbm_arena_destroy(&u->arena);
cbm_free(CBM_MEM_CLASS_OTHER, u);
}
uint64_t cbm_include_universe_tail_steps(const cbm_include_universe_t *u) {
return u ? u->tail_steps : 0;
}
/* "a/B.proto" -> "a/b.proto" (ASCII) into out; false when it does not fit. */
static bool ip_fold_into(char *out, size_t sz, const char *p) {
size_t n = strlen(p);
if (n >= sz) {
return false;
}
for (size_t i = 0; i <= n; i++) {
char c = p[i];
out[i] = (c >= 'A' && c <= 'Z') ? (char)(c - 'A' + 'a') : c;
}
return true;
}
/* One indexed path: into the set and the suffix indexes (building only). */
static bool ip_list_add(cbm_include_universe_t *u, const char *path) {
const char *rel = cbm_arena_strdup(&u->arena, path);
char fold[IP_PATH_MAX];
if (!rel || !ip_fold_into(fold, sizeof(fold), rel)) {
return false;
}
const char *folded = cbm_arena_strdup(&u->arena, fold);
if (!folded) {
return false;
}
for (const char *p = folded; p;) {
cbm_ht_set(u->ftails, p, (void *)folded);
const char *slash = strchr(p, '/');
p = slash ? slash + SKIP_ONE : NULL;
}
cbm_ht_set(u->listed, rel, (void *)rel);
for (const char *p = rel; p;) {
u->tail_steps++;
ip_tail_t *e = cbm_ht_get(u->tails, p);
if (!e) {
e = cbm_arena_alloc(&u->arena, sizeof(*e));
if (!e) {
return false;
}
e->path = rel;
e->n = 0;
cbm_ht_set(u->tails, p, e); /* p points into rel: arena-owned */
}
e->n++;
const char *slash = strchr(p, '/');
p = slash ? slash + SKIP_ONE : NULL;
}
return true;
}
cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, int count) {
cbm_include_universe_t *u = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*u));
if (!u) {
return NULL;
}
memset(u, 0, sizeof(*u));
cbm_arena_init(&u->arena);
u->listed = cbm_ht_create(CBM_SZ_4K);
u->tails = cbm_ht_create(CBM_SZ_4K);
u->ftails = cbm_ht_create(CBM_SZ_4K);
if (!u->listed || !u->tails || !u->ftails) {
cbm_include_universe_free(u);
return NULL;
}
u->complete = true;
for (int i = 0; files && i < count; i++) {
const char *rel = files[i].rel_path;
if (!rel || !rel[0]) {
continue;
}
const char *base = strrchr(rel, '/');
base = base ? base + SKIP_ONE : rel;
if (!cbm_include_path_listed_name(base) || cbm_ht_get(u->listed, rel)) {
continue; /* a name no row's import names, or listed already */
}
if (strlen(rel) >= IP_PATH_MAX) {
u->complete = false; /* a path the rule cannot hold */
continue;
}
if (!ip_list_add(u, rel)) {
cbm_include_universe_free(u);
return NULL;
}
}
return u;
}
enum { IP_EXISTS_NO = 0, IP_EXISTS_YES = 1, IP_EXISTS_UNKNOWN = 2 };
/* A file of the run (a File node), or an indexed one; unknown when the
* universe is not whole for a name a row keeps. */
static int ip_exists(const cbm_include_universe_t *u, const cbm_gbuf_t *graph, const char *project,
const char *rel) {
if (graph && project && cbm_pipeline_file_node(graph, project, rel)) {
return IP_EXISTS_YES;
}
if (cbm_ht_get(u->listed, rel)) {
return IP_EXISTS_YES;
}
const char *base = strrchr(rel, '/');
base = base ? base + SKIP_ONE : rel;
return u->complete || !cbm_include_path_listed_name(base) ? IP_EXISTS_NO : IP_EXISTS_UNKNOWN;
}
/* Of the candidates, the one that names a file; NULL when none does, when
* (exactly one required) several do, or when existence is unknown for a
* candidate that decides the answer. */
static const char *ip_pick(const cbm_include_universe_t *u, const cbm_gbuf_t *graph,
const char *project, char cands[][IP_PATH_MAX], int n, bool exactly_one,
char *buf, size_t buf_sz) {
const char *hit = NULL;
for (int i = 0; i < n; i++) {
bool dup = false;
for (int j = 0; j < i; j++) {
dup = dup || strcmp(cands[i], cands[j]) == 0;
}
if (dup) {
continue;
}
int ex = ip_exists(u, graph, project, cands[i]);
if (ex == IP_EXISTS_UNKNOWN) {
return NULL;
}
if (ex == IP_EXISTS_NO) {
continue;
}
if (!exactly_one) {
hit = cands[i];
break;
}
if (hit) {
return NULL;
}
hit = cands[i];
}
if (!hit || strlen(hit) >= buf_sz) {
return NULL;
}
memcpy(buf, hit, strlen(hit) + SKIP_ONE);
return buf;
}
/* The one indexed file whose repository path is `key` or ends with "/" + key. */
static const char *ip_unique_tail(const cbm_include_universe_t *u,
const cbm_include_path_row_t *row, const char *key, char *buf,
size_t buf_sz) {
const char *base = strrchr(key, '/');
base = base ? base + SKIP_ONE : key;
if (!base[0] || !ip_row_names(row, base) || !u->complete) {
return NULL; /* a name the universe does not keep, or not whole */
}
const ip_tail_t *e = cbm_ht_get(u->tails, key);
if (!e || e->n != SKIP_ONE || strlen(e->path) >= buf_sz) {
return NULL; /* none, or two files end with it */
}
memcpy(buf, e->path, strlen(e->path) + SKIP_ONE);
return buf;
}
/* Proven that no indexed file is `key` or ends with "/" + key, also when
* letter case is ignored. */
static bool ip_absent_tail(const cbm_include_universe_t *u, const cbm_include_path_row_t *row,
const char *key) {
const char *base = strrchr(key, '/');
base = base ? base + SKIP_ONE : key;
char folded[IP_PATH_MAX];
if (!base[0] || !ip_row_names(row, base) || !u->complete ||
!ip_fold_into(folded, sizeof(folded), key)) {
return false;
}
return !cbm_ht_get(u->tails, key) && !cbm_ht_get(u->ftails, folded);
}
/* A path protoc accepts as a virtual path: no `.` or `..` segment, no empty
* segment (`//`), no backslash. */
static bool ip_virtual_ok(const char *p) {
if (strchr(p, '\\')) {
return false;
}
for (const char *s = p; *s;) {
size_t sl = strcspn(s, "/");
if (sl == 0 || (sl == SKIP_ONE && s[0] == '.') ||
(sl == PAIR_LEN && s[0] == '.' && s[1] == '.')) {
return false;
}
s += sl;
if (*s == '/') {
s++;
if (!*s) {
return false; /* a trailing slash: an empty segment */
}
}
}
return true;
}
cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t *u,
const cbm_gbuf_t *graph, const char *project,
const char *rel, CBMLanguage lang,
const CBMImport *imp, char *buf,
size_t buf_sz) {
const cbm_include_path_row_t *row = cbm_include_path_row(lang);
if (!row || !imp || !imp->module_path || !imp->module_path[0] || !rel) {
return CBM_INCLUDE_PATH_NOT_A_PATH;
}
const char *p = imp->module_path;
if (row->path_needs_suffix) {
bool named = false;
for (const char *const *s = row->suffixes; s && *s; s++) {
named = named || ip_has_suffix(p, *s);
}
if (!named) {
return CBM_INCLUDE_PATH_NOT_A_PATH;
}
}
char dir[IP_PATH_MAX];
if (!u || p[0] == '/' || strpbrk(p, "$`") || (row->virtual_path && !ip_virtual_ok(p)) ||
!ip_dirname(dir, sizeof(dir), rel)) {
return CBM_INCLUDE_PATH_NONE; /* a path the rule cannot read */
}
/* The tail key: the path after its leading `./` and `../` segments (a
* Make path climbing out of its directory, from any directory make runs
* in, still names a file that ends with the rest). */
const char *kp = p;
while (strncmp(kp, "./", PAIR_LEN) == 0 || strncmp(kp, "../", IP_UP_LEN) == 0) {
kp += kp[1] == '.' ? IP_UP_LEN : PAIR_LEN;
}
char key[IP_PATH_MAX];
bool keyed = ip_join(key, sizeof(key), "", kp);
if (row->whole_path_tail && keyed && ip_unique_tail(u, row, key, buf, buf_sz)) {
return CBM_INCLUDE_PATH_FILE;
}
char cands[2][IP_PATH_MAX];
int n = 0;
if (row->base_file_dir && ip_join(cands[n], sizeof(cands[n]), dir, p)) {
n++;
}
if (row->base_root && ip_join(cands[n], sizeof(cands[n]), "", p)) {
n++;
}
if (ip_pick(u, graph, project, cands, n, row->exactly_one, buf, buf_sz)) {
/* A tail row gets here only when several indexed files end with the
* path: the one beside the importer is an assumption about the include
* root. Below the root, a base is an assumption about the directory
* the tool runs in. Only a makefile at the root decides. */
return row->whole_path_tail || dir[0] ? CBM_INCLUDE_PATH_GUESS : CBM_INCLUDE_PATH_FILE;
}
/* Proof of "no file": no indexed file is the path or ends with it, so no
* include root or run directory inside the index can supply one (absence
* at the bases alone would not do: another directory may). */
return keyed && ip_absent_tail(u, row, key) ? CBM_INCLUDE_PATH_NO_FILE : CBM_INCLUDE_PATH_NONE;
}
/* The file's Module node (named by its path) when it has one: the node a
* module-path import named before; else its File node. */
static const cbm_gbuf_node_t *ip_file_target(const cbm_pipeline_ctx_t *ctx, const char *path) {
const cbm_gbuf_node_t **hits = NULL;
int n = 0;
if (cbm_gbuf_find_by_name(ctx->gbuf, path, &hits, &n) == 0 && hits) {
for (int i = 0; i < n; i++) {
if (hits[i] && hits[i]->label && strcmp(hits[i]->label, "Module") == 0 &&
hits[i]->file_path && strcmp(hits[i]->file_path, path) == 0) {
return hits[i];
}
}
}
return cbm_pipeline_file_node(ctx->gbuf, ctx->project_name, path);
}
bool cbm_include_path_decides(const cbm_pipeline_ctx_t *ctx, const char *rel, CBMLanguage lang,
const CBMImport *imp, const cbm_gbuf_node_t **out) {
*out = NULL;
if (!ctx || !ctx->include_universe || !cbm_include_path_row(lang)) {
return false;
}
char buf[IP_PATH_MAX];
cbm_include_path_verdict_t v = cbm_include_path_resolve(
ctx->include_universe, ctx->gbuf, ctx->project_name, rel, lang, imp, buf, sizeof(buf));
if (v == CBM_INCLUDE_PATH_FILE) {
/* the statement names this repository file: its node, or no edge when
* the graph has none (a file in a skipped directory) */
*out = ip_file_target(ctx, buf);
return true;
}
/* proven to name no repository file: neither a file nor a symbol of the
* repository can be its target. Otherwise (not a path, several files,
* unknown) main's strategies decide. */
return v == CBM_INCLUDE_PATH_NO_FILE;
}
static int ip_strcmp_ptr(const void *a, const void *b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
int cbm_include_path_inventory_digest(const cbm_file_info_t *files, int count,
char out[CBM_SHA256_HEX_LEN + 1]) {
const char **sorted =
count > 0 ? cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)count * sizeof(*sorted)) : NULL;
if (count > 0 && !sorted) {
return CBM_NOT_FOUND;
}
size_t n = 0;
for (int i = 0; i < count; i++) {
const char *rel = files[i].rel_path;
const char *base = rel ? strrchr(rel, '/') : NULL;
base = base ? base + SKIP_ONE : rel;
if (rel && rel[0] && cbm_include_path_listed_name(base)) {
sorted[n++] = rel;
}
}
if (n > SKIP_ONE) {
qsort((void *)sorted, n, sizeof(*sorted), ip_strcmp_ptr);
}
cbm_sha256_ctx sha;
cbm_sha256_init(&sha);
static const char version[] = "include-inventory-v1";
cbm_sha256_update(&sha, version, sizeof(version));
for (size_t i = 0; i < n; i++) {
cbm_sha256_update(&sha, sorted[i], strlen(sorted[i]) + SKIP_ONE);
}
cbm_free(CBM_MEM_CLASS_OTHER, (void *)sorted);
uint8_t digest[CBM_SHA256_DIGEST_LEN];
cbm_sha256_final(&sha, digest);
static const char hex[] = "0123456789abcdef";
for (int i = 0; i < CBM_SHA256_DIGEST_LEN; i++) {
out[i * PAIR_LEN] = hex[digest[i] >> 4];
out[i * PAIR_LEN + SKIP_ONE] = hex[digest[i] & 0x0f];
}
out[CBM_SHA256_HEX_LEN] = '\0';
return 0;
}
+111
View File
@@ -0,0 +1,111 @@
#ifndef CBM_INCLUDE_PATH_H
#define CBM_INCLUDE_PATH_H
/*
* include_path.h — the path rule: which repository file an import statement
* names, for the languages whose imports name files by path (a row below).
*
* The rule reads the import's text as a path and finds the one indexed file it
* names: the bases a row allows (the importing file's directory, the
* repository root), "exactly one" where two bases could both name a file, and
* a whole-path tail (the one indexed file whose path is the import's path or
* ends with "/" + it). The universe is the run's indexed file list (the files
* discovery kept, on every route), never a walk of the disk: a copy of a file
* in an ignored or skipped directory (node_modules, a .gitignore'd tree) is
* not seen, so an import only such a copy could satisfy names no file.
*
* A pick that depends on what the index cannot know is a guess, its own
* verdict, never FILE: the file beside a Protobuf importer when several
* indexed files end with the path (protoc reads the one under its -I root),
* and a Make include from a makefile below the root (GNU make reads relative
* paths from the directory it runs in). A guess decides no IMPORTS edge (main
* decides) and resolves no include of the shared layer.
*
* Lifted from the parked include-scope branch (round 5, include_scope.c
* section 2): its bases, exactly-one, tail index and import node; the shell
* and Make evaluated paths and run directories stay there.
*
* Threads: a universe is built once, from the file list, before any question,
* and is read-only afterwards: a question writes nothing (sealed at creation).
*/
#include "cbm.h"
#include "foundation/sha256.h"
#include "graph_buffer/graph_buffer.h"
#include "pipeline/pipeline_internal.h"
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
/* One language whose imports name files by path. */
typedef struct {
CBMLanguage lang;
const char *const *suffixes; /* file names the listing keeps: ending in one of these */
const char *const *prefixes; /* ... or starting with one of these */
/* an import whose path does not end in one of `suffixes` is not a path
* the rule reads (Protobuf: a row that names no `.proto` file) */
bool path_needs_suffix;
/* a virtual path (protoc): `.` and `..` segments, `//` and backslashes are
* refused by the tool, so the rule reads no such path */
bool virtual_path;
bool base_file_dir; /* relative to the importing file's directory */
bool base_root; /* relative to the repository root */
bool exactly_one; /* two bases naming two files: none */
bool whole_path_tail; /* first, the one listed file that is the path or ends with it */
} cbm_include_path_row_t;
/* The row of a language, or NULL. */
const cbm_include_path_row_t *cbm_include_path_row(CBMLanguage lang);
/* True for a file name the listing keeps (a name some row's import can name). */
bool cbm_include_path_listed_name(const char *name);
typedef struct cbm_include_universe cbm_include_universe_t;
/* The universe of the run's indexed files (`files`, the discovered list of
* the run on every route): every file whose name a row's import can name.
* Built here, read-only afterwards. NULL on allocation failure. */
cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, int count);
void cbm_include_universe_free(cbm_include_universe_t *u);
/* Tail-index keys made while building: the counted work of growth tests (a
* question makes none). */
uint64_t cbm_include_universe_tail_steps(const cbm_include_universe_t *u);
typedef enum {
CBM_INCLUDE_PATH_NOT_A_PATH = 0, /* no row, or not a path the row reads: main decides */
CBM_INCLUDE_PATH_FILE, /* names one indexed file (path in the buffer) */
CBM_INCLUDE_PATH_NONE, /* a path whose file the rule cannot tell (several, unknown) */
/* proven: no indexed file is that path or ends with it (letter case
* ignored) */
CBM_INCLUDE_PATH_NO_FILE,
/* a file picked by an assumption the index cannot check (path in the
* buffer): the include root or the directory make runs in. Not FILE: main
* decides the edge, the shared layer takes the include as unresolved. */
CBM_INCLUDE_PATH_GUESS,
} cbm_include_path_verdict_t;
/* The file the import `imp` of the file `rel` names, written into buf.
* `graph`/`project`: the run's File nodes, which count as existing. */
cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t *u,
const cbm_gbuf_t *graph, const char *project,
const char *rel, CBMLanguage lang,
const CBMImport *imp, char *buf, size_t buf_sz);
/* The IMPORTS target of an import, for resolve_import_strategies: true when
* the path rule decides it, with *out the target node (the file's Module node
* when it has one, else its File node) or NULL: no edge (the named file has no
* node, or no indexed file is named; a symbol is never the target of a
* statement that names a file). False: main's strategies decide (a guess is
* not a decision). */
bool cbm_include_path_decides(const cbm_pipeline_ctx_t *ctx, const char *rel, CBMLanguage lang,
const CBMImport *imp, const cbm_gbuf_node_t **out);
/* The semantic-manifest key of the universe: every indexed path a row's
* import can name, sorted, hashed. Reads the list only (no disk). Returns 0,
* or -1 on allocation failure. */
int cbm_include_path_inventory_digest(const cbm_file_info_t *files, int count,
char out[CBM_SHA256_HEX_LEN + 1]);
#endif /* CBM_INCLUDE_PATH_H */
+112 -60
View File
@@ -418,40 +418,114 @@ static inline bool cbm_pipeline_invocation_leaf_matches(const CBMResolvedCall *r
/* #606: a sub-floor `php_method_typed_unindexed` row still proves the receiver
* is not a project class, so a weak short-name fallback must not bind it. A
* project class with the same simple name keeps the fallback, since the PHP
* LSP does not follow every cross-file type. */
* LSP does not follow every cross-file type.
*
* The check is three questions, asked by the scan below and by the per-file
* index (cbm_pipeline_lsp_index_php_receiver_unindexed) in the same words. */
/* Rows read by a per-call scan of a file's engine rows (this check's and the
* matcher's below), counted inside the scan, whoever asks. */
extern _Atomic uint64_t g_lsp_scan_rows; /* defined in pass_parallel.c */
/* Can this row answer the check at all: an unindexed-receiver row whose callee
* names a class and a method. */
static inline bool cbm_pipeline_php_unindexed_row(const CBMResolvedCall *rc) {
if (!rc || rc->kind != CBM_RESOLVED_INVOCATION || !rc->caller_qn || !rc->callee_qn ||
!rc->strategy || strcmp(rc->strategy, "php_method_typed_unindexed") != 0) {
return false;
}
const char *method_dot = strrchr(rc->callee_qn, '.');
return method_dot && method_dot != rc->callee_qn &&
(size_t)(method_dot - rc->callee_qn) < (size_t)CBM_SZ_512;
}
/* Is such a row this call's: the same caller, the same occurrence (or the
* legacy join) and the same leaf. */
static inline bool cbm_pipeline_php_unindexed_row_is_for(const CBMResolvedCall *rc,
const CBMCall *call) {
if (strcmp(rc->caller_qn, call->enclosing_func_qn) != 0) {
return false;
}
int site_rank = cbm_pipeline_invocation_site_rank(rc, call);
return site_rank != 0 && cbm_pipeline_invocation_leaf_matches(rc, call, site_rank);
}
/* The row's verdict: its receiver class is no type of the project. */
static inline bool cbm_pipeline_php_unindexed_row_verdict(const CBMResolvedCall *rc,
const cbm_registry_t *registry) {
char class_qn[CBM_SZ_512];
size_t class_len = (size_t)(strrchr(rc->callee_qn, '.') - rc->callee_qn);
memcpy(class_qn, rc->callee_qn, class_len);
class_qn[class_len] = '\0';
return !cbm_registry_has_type_named(registry, cbm_lsp_bare_segment(class_qn));
}
/* The first such row of the file, in array order, decides. */
static inline bool cbm_pipeline_php_receiver_type_unindexed(const CBMResolvedCallArray *arr,
const CBMCall *call,
const cbm_registry_t *registry) {
if (!arr || !call || !call->enclosing_func_qn || !call->callee_name) {
return false;
}
atomic_fetch_add_explicit(&g_lsp_scan_rows, (uint64_t)arr->count, memory_order_relaxed);
for (int i = 0; i < arr->count; i++) {
const CBMResolvedCall *rc = &arr->items[i];
if (rc->kind != CBM_RESOLVED_INVOCATION || !rc->caller_qn || !rc->callee_qn ||
!rc->strategy || strcmp(rc->strategy, "php_method_typed_unindexed") != 0 ||
strcmp(rc->caller_qn, call->enclosing_func_qn) != 0) {
continue;
if (cbm_pipeline_php_unindexed_row(rc) && cbm_pipeline_php_unindexed_row_is_for(rc, call)) {
return cbm_pipeline_php_unindexed_row_verdict(rc, registry);
}
int site_rank = cbm_pipeline_invocation_site_rank(rc, call);
if (site_rank == 0 || !cbm_pipeline_invocation_leaf_matches(rc, call, site_rank)) {
continue;
}
const char *method_dot = strrchr(rc->callee_qn, '.');
if (!method_dot || method_dot == rc->callee_qn) {
continue;
}
char class_qn[CBM_SZ_512];
size_t class_len = (size_t)(method_dot - rc->callee_qn);
if (class_len >= sizeof(class_qn)) {
continue;
}
memcpy(class_qn, rc->callee_qn, class_len);
class_qn[class_len] = '\0';
return !cbm_registry_has_type_named(registry, cbm_lsp_bare_segment(class_qn));
}
return false;
}
/* The matcher's row tests, asked by its scan below and by the per-file index
* (cbm_pipeline_lsp_index_find, pass_parallel.c) in the same words. */
/* Can this row answer a call at all: an invocation row with both names, at or
* above the confidence floor. */
static inline bool cbm_pipeline_invocation_row(const CBMResolvedCall *rc) {
return rc->kind == CBM_RESOLVED_INVOCATION && rc->caller_qn && rc->callee_qn &&
!(rc->confidence < CBM_LSP_CONFIDENCE_FLOOR);
}
/* The tail phase's caller test (JVM callers only): the row's caller and the
* call's caller share their Class.method tail, or, for a row at the call's
* exact occurrence, their bare last segment (Kotlin's package-against-file
* owner names of a top-level function). */
static inline bool cbm_pipeline_invocation_tail_caller_matches(const CBMResolvedCall *rc,
const CBMCall *call,
const char *call_tail,
int site_rank) {
if (call_tail && cbm_pipeline_qn_class_method_tail_eq(rc->caller_qn, call_tail)) {
return true;
}
if (site_rank != 2) {
return false;
}
const char *resolved_caller = cbm_lsp_bare_segment(rc->caller_qn);
const char *source_caller = cbm_lsp_bare_segment(call->enclosing_func_qn);
return resolved_caller && source_caller && strcmp(resolved_caller, source_caller) == 0;
}
/* One more row of the same rank for a best-row choice: the first row stays
* unless a later one names the same target with a higher confidence; a row
* with a different target makes the choice ambiguous for good. */
static inline void cbm_pipeline_invocation_fold(const CBMResolvedCall **best, bool *ambiguous,
const CBMResolvedCall *rc, const cbm_gbuf_t *gbuf,
const char *project_name, bool allow_tail_match) {
if (!*best) {
*best = rc;
return;
}
if (!cbm_pipeline_invocation_targets_equal((*best)->callee_qn, rc->callee_qn, gbuf,
project_name, allow_tail_match)) {
*ambiguous = true;
return;
}
if (rc->confidence > (*best)->confidence) {
*best = rc;
}
}
/* Look up the highest-confidence LSP-resolved call entry whose caller QN
* matches the textual call's enclosing function and whose callee QN
* short-name matches the textual callee. Returns a pointer into `arr`
@@ -471,7 +545,13 @@ static inline bool cbm_pipeline_php_receiver_type_unindexed(const CBMResolvedCal
* bare last segment by cbm_lsp_bare_segment before matching.
*
* The pointer returned aliases into `arr` and stays valid as long as the
* underlying CBMFileResult is alive. */
* underlying CBMFileResult is alive.
*
* This reads every row of the file for one call. Both resolvers ask through
* the per-file index (cbm_pipeline_lsp_index_find, pass_parallel.c), which
* comes here only where the index may not hold the answer; g_lsp_scan_rows
* counts the rows read here, whoever asks. */
static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution_in_graph(
const CBMResolvedCallArray *arr, const CBMCall *call, bool allow_tail_match,
const cbm_gbuf_t *gbuf, const char *project_name) {
@@ -481,19 +561,14 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution_in_graph(
if (!call->enclosing_func_qn || !call->callee_name) {
return NULL;
}
atomic_fetch_add_explicit(&g_lsp_scan_rows, (uint64_t)arr->count, memory_order_relaxed);
const CBMResolvedCall *best_exact_caller = NULL;
int best_exact_caller_rank = 0;
bool exact_caller_ambiguous = false;
for (int i = 0; i < arr->count; i++) {
const CBMResolvedCall *rc = &arr->items[i];
if (rc->kind != CBM_RESOLVED_INVOCATION) {
continue;
}
if (!rc->caller_qn || !rc->callee_qn) {
continue;
}
if (rc->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
if (!cbm_pipeline_invocation_row(rc)) {
continue;
}
if (strcmp(rc->caller_qn, call->enclosing_func_qn) != 0) {
@@ -529,6 +604,7 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution_in_graph(
}
const char *call_tail = cbm_pipeline_qn_class_method_tail(call->enclosing_func_qn);
atomic_fetch_add_explicit(&g_lsp_scan_rows, (uint64_t)arr->count, memory_order_relaxed);
const CBMResolvedCall *best_tail_exact = NULL;
const CBMResolvedCall *best_tail_legacy = NULL;
@@ -536,45 +612,21 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution_in_graph(
bool tail_legacy_ambiguous = false;
for (int i = 0; i < arr->count; i++) {
const CBMResolvedCall *rc = &arr->items[i];
if (rc->kind != CBM_RESOLVED_INVOCATION) {
continue;
}
if (!rc->caller_qn || !rc->callee_qn) {
continue;
}
if (rc->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
if (!cbm_pipeline_invocation_row(rc)) {
continue;
}
int site_rank = cbm_pipeline_invocation_site_rank(rc, call);
if (site_rank == 0) {
continue;
}
bool caller_matches =
call_tail && cbm_pipeline_qn_class_method_tail_eq(rc->caller_qn, call_tail);
if (!caller_matches && site_rank == 2) {
const char *resolved_caller = cbm_lsp_bare_segment(rc->caller_qn);
const char *source_caller = cbm_lsp_bare_segment(call->enclosing_func_qn);
caller_matches =
resolved_caller && source_caller && strcmp(resolved_caller, source_caller) == 0;
}
if (!caller_matches || !cbm_pipeline_invocation_leaf_matches(rc, call, site_rank)) {
if (!cbm_pipeline_invocation_tail_caller_matches(rc, call, call_tail, site_rank) ||
!cbm_pipeline_invocation_leaf_matches(rc, call, site_rank)) {
continue;
}
const CBMResolvedCall **best = site_rank == 2 ? &best_tail_exact : &best_tail_legacy;
bool *ambiguous = site_rank == 2 ? &tail_exact_ambiguous : &tail_legacy_ambiguous;
if (!*best) {
*best = rc;
continue;
}
if (!cbm_pipeline_invocation_targets_equal((*best)->callee_qn, rc->callee_qn, gbuf,
project_name, allow_tail_match)) {
*ambiguous = true;
continue;
}
if (rc->confidence > (*best)->confidence) {
*best = rc;
}
cbm_pipeline_invocation_fold(site_rank == 2 ? &best_tail_exact : &best_tail_legacy,
site_rank == 2 ? &tail_exact_ambiguous
: &tail_legacy_ambiguous,
rc, gbuf, project_name, allow_tail_match);
}
if (best_tail_exact) {
return tail_exact_ambiguous ? NULL : best_tail_exact;
+4
View File
@@ -847,6 +847,8 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu
yyjson_mut_obj_add_bool(doc, o, "ab", d->is_abstract);
add_str_array_or_null(doc, o, "dec", d->decorators, -1);
add_str_or_null(doc, o, "al", d->alias_target);
yyjson_mut_obj_add_bool(doc, o, "sg", d->is_singleton);
add_str_or_null(doc, o, "mx", d->mixin_refs);
/* Stored for the routes that resolve against this row without
* re-extracting it; never hashed (see SURFACE_CODEC_VERSION). */
if (identities && d->type_scope) {
@@ -1262,6 +1264,8 @@ int cbm_lsp_surface_defs_from_json(CBMArena *arena, const char *defs_json, CBMLS
int dec_count = 0;
d->decorators = arena_str_array(arena, yyjson_obj_get(o, "dec"), true, &dec_count);
d->alias_target = arena_str_or_null(arena, yyjson_obj_get(o, "al"));
d->is_singleton = yyjson_get_bool(yyjson_obj_get(o, "sg"));
d->mixin_refs = arena_str_or_null(arena, yyjson_obj_get(o, "mx"));
d->type_scope = arena_str_or_null(arena, yyjson_obj_get(o, "ty"));
if (!d->qualified_name || !d->short_name || !d->label) {
/* A def the writer could not have produced: qn/sn/label are
+23 -6
View File
@@ -1122,7 +1122,8 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
const char **imp_vals, int imp_count, CBMLanguage lang,
const CBMImportArray *imports, const char *route_mount,
const cbm_php_vendor_names_t *php_vendor,
cbm_external_import_index_t *ext_imports, CBMCallEvidence *evidence,
cbm_external_import_index_t *ext_imports,
const cbm_pipeline_lsp_index_t *lsp_index, CBMCallEvidence *evidence,
cbm_site_file_t *site) {
const CBMResolvedCallArray *lsp_calls = &result->resolved_calls;
const cbm_gbuf_node_t *source_node = calls_find_source(ctx, rel, call->enclosing_func_qn);
@@ -1133,8 +1134,8 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
/* LSP-resolved calls take precedence over registry-textual matching.
* Unique-tail fallbacks are JVM-only (see cbm_pipeline_lsp_allow_tail_match). */
bool allow_tail = cbm_pipeline_lsp_allow_tail_match(lang);
const CBMResolvedCall *lsp = cbm_pipeline_find_lsp_resolution_in_graph(
lsp_calls, call, allow_tail, ctx->gbuf, ctx->project_name);
const CBMResolvedCall *lsp = cbm_pipeline_lsp_index_find(lsp_index, lsp_calls, call, allow_tail,
ctx->gbuf, ctx->project_name);
/* #1186: a PHP call on a vendor type (`new Request`, or a receiver the LSP
* typed as an imported vendor class) takes the LSP result or no target: a
* same-named project symbol found by name alone is never the vendor's.
@@ -1397,7 +1398,8 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call, const CBM
cbm_pipeline_get_nsmap()) ||
/* MUST match pass_parallel.c exactly. */
(lang == CBM_LANG_PHP && cbm_suppress_weak_member_match(true, true, res.strategy) &&
cbm_pipeline_php_receiver_type_unindexed(lsp_calls, call, ctx->registry)) ||
cbm_pipeline_lsp_index_php_receiver_unindexed(lsp_index, lsp_calls, call,
ctx->registry)) ||
/* Same-module bound-receiver suppression (#1128): `axios.get()` with
* axios imported must not bind the `get` this file happens to define.
* The language list is inside the helper - MUST match pass_parallel.c. */
@@ -1591,9 +1593,12 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
int resolved = 0;
int unresolved = 0;
int errors = 0;
/* the shared layer's memo for this pass (site_bind.h) */
cbm_site_memo_t *site_memo = NULL;
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
cbm_pipeline_site_memo_free(site_memo);
return CBM_NOT_FOUND;
}
@@ -1602,6 +1607,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
CBMFileResult *result = calls_get_or_extract(ctx, i, &files[i], &result_owned);
if (!result) {
if (atomic_load(&ctx->test_declarations_failed)) {
cbm_pipeline_site_memo_free(site_memo);
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
errors++;
@@ -1612,6 +1618,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
if (result_owned) {
cbm_free_result(result);
}
cbm_pipeline_site_memo_free(site_memo);
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
@@ -1643,11 +1650,19 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
cbm_laravel_file_route_mount(ctx->repo_path, rel, files[i].language, result, route_mount,
sizeof(route_mount));
/* The file's engine rows by caller, leaf and span: one lookup per call
* instead of a scan of every row (shared with pass_parallel.c). */
cbm_pipeline_lsp_index_t lsp_index;
cbm_pipeline_lsp_index_build(&lsp_index, &result->resolved_calls, ctx->gbuf,
ctx->project_name,
cbm_pipeline_lsp_allow_tail_match(files[i].language));
/* Resolve each call */
cbm_external_import_index_t ext_imports = {0};
cbm_spawn_file_begin(result->imports.items, result->imports.count);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, files[i].language, result);
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, files[i].language, result,
&site_memo, evidence);
for (int c = 0; c < result->calls.count; c++) {
CBMCall *call = &result->calls.items[c];
if (!call->callee_name) {
@@ -1657,7 +1672,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
total_calls++;
if (resolve_single_call(ctx, call, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language, &result->imports, route_mount,
&php_vendor, &ext_imports,
&php_vendor, &ext_imports, &lsp_index,
calls_evidence_at(evidence, c, &fallback), &site)) {
resolved++;
} else {
@@ -1667,6 +1682,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
cbm_pipeline_site_bind_end(&site, ctx->gbuf);
cbm_spawn_file_end();
cbm_pipeline_external_import_index_free(&ext_imports);
cbm_pipeline_lsp_index_free(&lsp_index);
cbm_pipeline_record_unresolved_calls(ctx->pipeline, rel, result, evidence);
cbm_free(CBM_MEM_CLASS_RESOLVE, evidence);
@@ -1678,6 +1694,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
}
}
cbm_pipeline_site_memo_free(site_memo);
cbm_log_info("pass.done", "pass", "calls", "total", itoa_log(total_calls), "resolved",
itoa_log(resolved), "unresolved", itoa_log(unresolved), "errors",
itoa_log(errors));
+155 -2
View File
@@ -14,6 +14,9 @@
* unknown one. In the text, `${{ github.workspace }}` is
* $GITHUB_WORKSPACE, `${{ github.action_path }}` $GITHUB_ACTION_PATH, any
* other `${{ }}` an unknown variable (its line breaks kept).
* A local `uses:` ("./...", a path from the repository root) is handed on
* as well: a step's names an action directory, a job's a reusable
* workflow file; one with `${{` in it is none.
* - Prow: a file with a top-level presubmits / postsubmits / periodics key
* (in-repo job config). A job container's command + args is exec'd, no
* shell: the words are literal, a kubelet `$(VAR)` unknown; `bash -c TEXT`
@@ -53,6 +56,8 @@ typedef struct {
const char *src;
const char *rel;
cbm_ci_cmd_fn fn;
cbm_ci_use_fn use_fn; /* local `uses:`; NULL: not wanted */
void *use_ud; /* use_fn's own userdata */
cbm_build_site_fn site_fn; /* a build-site walk's callback */
cbm_compose_service_fn service_fn; /* a compose walk's callback */
void *ud;
@@ -451,10 +456,29 @@ static const char *ci_run_default(const ci_t *c, TSNode m, const char *key) {
return ci_get_str(c, ci_get(c, ci_get(c, m, "defaults"), "run"), key);
}
static const char *ci_repo_path(CBMArena *a, const char *base, const char *rel);
/* The `uses:` of step or job `owner` when it names something of this
* repository: "./dir", "./.github/workflows/x.yml". One with an expression in
* it, or leaving the repository, is none. */
static void ci_local_use(const ci_t *c, TSNode owner, bool job) {
int row = 0;
const char *uses = c->use_fn ? ci_scalar(c, ci_get(c, owner, "uses"), &row) : NULL;
if (!uses || uses[0] != '.' || uses[SKIP_ONE] != '/' || strstr(uses, CI_EXPR_OPEN)) {
return;
}
const char *path = ci_repo_path(c->a, "", uses);
if (path) {
cbm_ci_use_t use = {.path = path, .job = job, .line = row + SKIP_ONE};
c->use_fn(&use, c->use_ud);
}
}
static void ci_gha_steps(const ci_t *c, TSNode steps, const char *job, const ci_scope_t *sc) {
int n = 0;
TSNode *items = ci_items(c, steps, &n);
for (int i = 0; i < n; i++) {
ci_local_use(c, items[i], false);
int row = 0;
const char *run = ci_scalar(c, ci_get(c, items[i], "run"), &row);
if (!run) {
@@ -500,6 +524,7 @@ static void ci_workflow(const ci_t *c, TSNode root) {
ci_pair_t *jobs = ci_pairs(c, ci_get(c, root, "jobs"), &n);
for (int i = 0; i < n; i++) {
TSNode j = jobs[i].value;
ci_local_use(c, j, true);
const char *wd = ci_run_default(c, j, "working-directory");
const char *sh = ci_run_default(c, j, "shell");
ci_scope_t sc = {.env = ci_env_add(c, &wenv, ci_get(c, j, "env")),
@@ -1129,10 +1154,131 @@ static const char *ci_compose_build_args(const ci_t *c, TSNode build, const ci_e
return json ? cbm_arena_sprintf(c->a, "%s}", json) : NULL;
}
/* ── Files a compose service reads (PHASE 4 P4.7) ─────────────────────
* The repository paths a service names, relative to the compose file's
* directory (its project directory):
* - volumes: a bind mount's host side -- the short form `./host:/ctr[:mode]`
* whose host side begins with `.` (compose reads one without it as a
* volume's name), and the long form {type: bind, source: host}, where
* the type says it is a path;
* - env_file: a path, a list of paths, a list of {path: ...};
* - configs / secrets: the top-level entry a service's list names (a name,
* or {source: name}), by that entry's `file:`.
* Variables are interpolated from the project's .env. A variable without a
* value, an absolute or home path and a path out of the repository are none.
* Whether a path is a file the index holds is the caller's to decide. */
typedef struct {
cbm_compose_file_t *v;
int n;
int cap;
} ci_files_t;
/* `p` (interpolated already; NULL: none) as a repository path into `l`. */
static void ci_files_add(const ci_t *c, ci_files_t *l, const char *dir, const char *p,
const char *via, int row, bool dot_only) {
if (!p || !p[0] || p[0] == '~' || (dot_only && p[0] != '.') || l->n >= l->cap) {
return;
}
const char *path = ci_repo_path(c->a, dir, p);
if (path && path[0]) {
l->v[l->n++] = (cbm_compose_file_t){.path = path, .via = via, .line = row + SKIP_ONE};
}
}
static bool ci_is_mapping(TSNode n) {
return ci_type(n, "block_mapping") || ci_type(n, "flow_mapping");
}
/* name -> `file:` text (as written) of the entries of the top-level `key`
* mapping that have one; NULL: none. The caller frees the table. */
static CBMHashTable *ci_compose_named_files(const ci_t *c, TSNode root, const char *key) {
int n = 0;
ci_pair_t *defs = ci_pairs(c, ci_get(c, root, key), &n);
CBMHashTable *by_name = n > 0 ? cbm_ht_create((uint32_t)n) : NULL;
for (int i = 0; by_name && i < n; i++) {
const char *file = ci_get_str(c, defs[i].value, "file");
if (file && !cbm_ht_get(by_name, defs[i].key)) {
cbm_ht_set(by_name, defs[i].key, (void *)file);
}
}
return by_name;
}
/* The files service `svc` names; `named`: the top-level configs and secrets
* by name (ci_compose_named_files; either may be NULL). */
static int ci_compose_files(const ci_t *c, TSNode svc, const char *dir, const ci_env_t *env,
CBMHashTable *const named[PAIR_LEN], const cbm_compose_file_t **out) {
static const char *const KEY[PAIR_LEN] = {"configs", "secrets"};
static const char *const VIA[PAIR_LEN] = {"config", "secret"};
int nv = 0;
int ne = 0;
int nn[PAIR_LEN] = {0};
TSNode *vols = ci_items(c, ci_get(c, svc, "volumes"), &nv);
TSNode env_file = ci_get(c, svc, "env_file");
TSNode *envs = ci_items(c, env_file, &ne);
TSNode *refs[PAIR_LEN] = {NULL, NULL};
for (int k = 0; k < PAIR_LEN; k++) {
refs[k] = named[k] ? ci_items(c, ci_get(c, svc, KEY[k]), &nn[k]) : NULL;
}
ci_files_t l = {.cap = nv + ne + nn[0] + nn[SKIP_ONE] + SKIP_ONE};
l.v = cbm_arena_alloc(c->a, (size_t)l.cap * sizeof(*l.v));
*out = l.v;
if (!l.v) {
return 0;
}
for (int i = 0; i < nv; i++) {
int row = 0;
if (ci_is_mapping(vols[i])) {
const char *type = ci_get_str(c, vols[i], "type");
const char *source = type && strcmp(type, "bind") == 0
? ci_scalar(c, ci_get(c, vols[i], "source"), &row)
: NULL;
ci_files_add(c, &l, dir, source ? ci_interp(c->a, source, env) : NULL, "volume", row,
false);
continue;
}
/* interpolate first: a default (`${D:-./conf}`) holds a colon of its own */
const char *raw = ci_scalar(c, vols[i], &row);
const char *s = raw ? ci_interp(c->a, raw, env) : NULL;
const char *colon = s ? strchr(s, ':') : NULL;
if (colon) { /* without one: an anonymous volume's container path */
ci_files_add(c, &l, dir, cbm_arena_strndup(c->a, s, (size_t)(colon - s)), "volume", row,
true);
}
}
if (!envs) { /* a single path */
int row = 0;
const char *raw = ci_scalar(c, env_file, &row);
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, "env_file", row, false);
}
for (int i = 0; i < ne; i++) {
int row = 0;
const char *raw = ci_is_mapping(envs[i]) ? ci_scalar(c, ci_get(c, envs[i], "path"), &row)
: ci_scalar(c, envs[i], &row);
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, "env_file", row, false);
}
for (int k = 0; k < PAIR_LEN; k++) {
for (int i = 0; i < nn[k]; i++) {
int row = 0;
const char *name = ci_is_mapping(refs[k][i])
? ci_scalar(c, ci_get(c, refs[k][i], "source"), &row)
: ci_scalar(c, refs[k][i], &row);
const char *raw = name ? cbm_ht_get(named[k], name) : NULL;
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, VIA[k], row, false);
}
}
return l.n;
}
static void ci_compose(const ci_t *c, TSNode root, const char *dir, const ci_env_t *env) {
static const ci_env_t no_env = {0};
int ns = 0;
ci_pair_t *svcs = ci_pairs(c, ci_get(c, root, "services"), &ns);
CBMHashTable *named[PAIR_LEN] = {NULL, NULL};
if (c->service_fn) {
named[0] = ci_compose_named_files(c, root, "configs");
named[SKIP_ONE] = ci_compose_named_files(c, root, "secrets");
}
for (int i = 0; i < ns; i++) {
TSNode svc = ci_content(svcs[i].value);
if (!ci_type(svc, "block_mapping") && !ci_type(svc, "flow_mapping")) {
@@ -1166,9 +1312,15 @@ static void ci_compose(const ci_t *c, TSNode root, const char *dir, const ci_env
.end_line = (int)ts_node_end_point(svc).row + SKIP_ONE};
s.ndeps = ci_compose_deps(c, svc, &s.deps);
s.nenv = ci_compose_env(c, svc, env, &s.env, &s.env_lines, &s.env_hosts);
s.nfiles = ci_compose_files(c, svc, dir, env, named, &s.files);
c->service_fn(&s, c->ud);
}
}
for (int k = 0; k < PAIR_LEN; k++) {
if (named[k]) {
cbm_ht_free(named[k]);
}
}
}
bool cbm_build_path(const char *rel) {
@@ -1265,7 +1417,7 @@ bool cbm_ci_path(const char *rel) {
}
void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len, cbm_ci_cmd_fn fn,
void *ud) {
void *ud, cbm_ci_use_fn use_fn, void *use_ud) {
if (!ci_yaml_ext(rel)) {
return;
}
@@ -1278,7 +1430,8 @@ void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len,
tree = ts_parser_parse_string(parser, NULL, src, (uint32_t)len);
}
if (tree) {
ci_t c = {.a = a, .src = src, .rel = rel, .fn = fn, .ud = ud};
ci_t c = {
.a = a, .src = src, .rel = rel, .fn = fn, .ud = ud, .use_fn = use_fn, .use_ud = use_ud};
TSNode stream = ts_tree_root_node(tree);
for (uint32_t i = 0; i < ts_node_named_child_count(stream); i++) {
TSNode doc = ts_node_named_child(stream, i);
+26
View File
@@ -21,6 +21,7 @@ enum { PD_SWIFT_PROPS_MARGIN = 80 };
#include <stdint.h>
#include <ctype.h>
#include "pipeline/pipeline_internal.h"
#include "pipeline/site_bind.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
#include "foundation/mem_core.h" /* cbm_alloc/cbm_free: the grown properties buffer */
@@ -1235,6 +1236,24 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
cbm_pipeline_diagram_arrows(ctx, result);
cbm_pipeline_create_env_configures_for_file(ctx, result, files[i].rel_path);
}
/* The shared layer's scope (site_bind.h): every file is extracted and
* its IMPORTS made; built once, before any resolver. The route that
* runs the resolvers frees it. Mirrors pipeline.c's parallel route. */
if (!ctx->site_scope) {
struct timespec st;
cbm_clock_gettime(CLOCK_MONOTONIC, &st);
ctx->site_scope = cbm_pipeline_site_scope_build(ctx, files, file_count, local_cache,
NULL, 0, NULL, 0);
if (ctx->site_scope) {
struct timespec now;
cbm_clock_gettime(CLOCK_MONOTONIC, &now);
long ms = (long)((now.tv_sec - st.tv_sec) * CBM_MSEC_PER_SEC +
(now.tv_nsec - st.tv_nsec) / CBM_NSEC_PER_MSEC);
char ms_buf[CBM_SZ_32];
snprintf(ms_buf, sizeof(ms_buf), "%ld", ms);
cbm_log_info("pass.timing", "pass", "site_scope", "elapsed_ms", ms_buf);
}
}
/* Publish instead of free — see the twin in pass_parallel.c (#1355).
* Only the Scala index is pass-local. */
cbm_pipeline_import_maps_free(NULL, scala_index);
@@ -1248,6 +1267,13 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
}
cbm_free(CBM_MEM_CLASS_EXTRACT, local_cache);
}
} else if (!ctx->site_scope) {
/* No result cache (its allocation failed): no scope of the shared
* layer either, so every site keeps main's answer, as for a language
* without a row (never a wrong answer; the parallel route, which always
* has its cache, answers). Logged so a run that degraded shows it. */
cbm_log_warn("site_bind.scope_skipped", "reason", "no_result_cache", "effect",
"main_decides_every_site");
}
cbm_registry_build_swift_owners(ctx->registry, ctx->gbuf, ctx->repo_path, ctx->excluded_dirs,
+191 -10
View File
@@ -38,6 +38,22 @@
* global EnvVar a program's readers share is not joined: the same name is
* read by other programs (measured: 23 % of such joins in scope). Values are
* never read into the graph.
*
* PHASE 4 P4.6: the repository files a Dockerfile copies. Each context source
* of a COPY / ADD written as a plain path -- no --from, no URL, no glob, no
* variable -- that is an indexed file under exactly one of the two contexts a
* build of this Dockerfile can have (its directory, the repository root) is a
* file the Dockerfile REFERENCES_FILE {via: copy | add, line}: File to File,
* once per file, at the first instruction naming it. Which context a build
* reads is in the build command, not in the Dockerfile, so a source that is a
* file under both is no edge; a directory is no edge (it names no one file).
*
* PHASE 4 P4.7: the repository files a compose service names -- a bind
* mount's host side, an env_file, a listed config's or secret's file
* (pass_ci.c reads them). Compose states these paths relative to the compose
* file's directory, so each that is an indexed file is a file the service
* REFERENCES_FILE {via: volume | env_file | config | secret, line}: service
* to File, once per file, at the first line naming it.
* Run at the end of the K8s pass.
*/
#include "foundation/constants.h"
@@ -65,12 +81,15 @@
enum { DK_MAX_STAGES = 64, DK_MAX_WORDS = 256, DK_MAX_DEPTH = 8 };
typedef struct dk_copy {
const char *from; /* --from= value; NULL: none, or unknown */
bool has_from; /* --from given */
const char **srcs; /* NULL entries: unknown */
const char *from; /* --from= value; NULL: none, or unknown */
bool has_from; /* --from given */
const char **srcs; /* NULL entries: unknown */
const uint8_t *var; /* per source: written with a variable (`$`) */
int nsrc;
const char *dst; /* as written; NULL: unknown */
const char *workdir;
int line;
bool add; /* ADD, not COPY */
struct dk_copy *next; /* the stage's previous COPY */
} dk_copy_t;
@@ -920,8 +939,9 @@ static char *dk_logical_line(dk_t *d, size_t at) {
return out;
}
/* A COPY / ADD in JSON form: its strings, expanded. */
static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
/* A COPY / ADD in JSON form: its strings, expanded; var[i]: string i was
* written with a variable. */
static int dk_copy_json(dk_t *d, const char *p, const char **out, uint8_t *var, int max) {
yyjson_doc *doc = yyjson_read(p, strlen(p), YYJSON_READ_STOP_WHEN_DONE);
yyjson_val *arr = doc ? yyjson_doc_get_root(doc) : NULL;
int n = 0;
@@ -930,6 +950,7 @@ static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
if (yyjson_is_arr(arr)) {
for (yyjson_arr_iter_init(arr, &it); n < max && (v = yyjson_arr_iter_next(&it));) {
const char *s = yyjson_get_str(v);
var[n] = s && strchr(s, '$') != NULL;
out[n++] = s ? dk_expand(d, d->local, cbm_arena_strdup(d->a, s), NULL) : NULL;
}
}
@@ -947,13 +968,15 @@ static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
static void dk_copy(dk_t *d, TSNode ins) {
static const char FROM[] = "--from=";
const char *words[DK_MAX_WORDS];
uint8_t var[DK_MAX_WORDS];
int nw = 0;
dk_copy_t *c = cbm_arena_alloc(d->a, sizeof(*c));
char *p = dk_logical_line(d, ts_node_start_byte(ins));
if (!c || !p) {
return;
}
*c = (dk_copy_t){.workdir = d->workdir};
*c = (dk_copy_t){
.workdir = d->workdir, .line = dk_line(ins), .add = dk_type(ins, "add_instruction")};
p += strcspn(p, " \t"); /* the keyword */
for (;;) {
p += strspn(p, " \t");
@@ -974,10 +997,11 @@ static void dk_copy(dk_t *d, TSNode ins) {
}
p += l;
}
bool json = *p == '[' && (nw = dk_copy_json(d, p, words, DK_MAX_WORDS)) > 0;
bool json = *p == '[' && (nw = dk_copy_json(d, p, words, var, DK_MAX_WORDS)) > 0;
while (!json && *p && nw < DK_MAX_WORDS) {
size_t l = strcspn(p, " \t");
const char *w = cbm_arena_strndup(d->a, p, l);
var[nw] = w && strchr(w, '$') != NULL;
words[nw++] = w && strncmp(w, "<<", PAIR_LEN) != 0 ? dk_expand(d, d->local, w, NULL) : NULL;
p += l;
p += strspn(p, " \t");
@@ -986,10 +1010,13 @@ static void dk_copy(dk_t *d, TSNode ins) {
return;
}
c->srcs = cbm_arena_alloc(d->a, (size_t)(nw - SKIP_ONE) * sizeof(*c->srcs));
if (!c->srcs) {
uint8_t *cvar = cbm_arena_alloc(d->a, (size_t)(nw - SKIP_ONE));
if (!c->srcs || !cvar) {
return;
}
memcpy((void *)c->srcs, words, (size_t)(nw - SKIP_ONE) * sizeof(*c->srcs));
memcpy(cvar, var, (size_t)(nw - SKIP_ONE));
c->var = cvar;
c->nsrc = nw - SKIP_ONE;
c->dst = words[nw - SKIP_ONE];
c->next = d->st[d->stage].copies;
@@ -1735,6 +1762,104 @@ static void dk_image_set(dk_t *d) {
}
}
typedef struct {
int line;
bool add;
const cbm_gbuf_node_t *file;
} dk_fileref_t;
static int dk_fileref_cmp(const void *x, const void *y) {
const dk_fileref_t *a = x;
const dk_fileref_t *b = y;
if (a->line != b->line) {
return a->line < b->line ? -1 : SKIP_ONE;
}
return strcmp(a->file->file_path, b->file->file_path);
}
/* True when context source `src`, the file `hit` under one context candidate,
* is a directory under the other: the build command decides which of the two
* the instruction copies. */
static bool dk_dir_under_other_context(dk_t *d, const char *src, const char *hit) {
const char *ctxs[PAIR_LEN] = {d->dir, ""};
int nctx = d->dir[0] ? PAIR_LEN : SKIP_ONE;
while (*src == '/') {
src++;
}
for (int i = 0; d->ix->dirs && i < nctx; i++) {
const char *p = dk_norm(d, dk_join(d, ctxs[i], src));
if (p && strcmp(p, hit) != 0 && cbm_ht_get(d->ix->dirs, p)) {
return true;
}
}
return false;
}
/* P4.6: REFERENCES_FILE from the Dockerfile's File to each repository file a
* COPY / ADD of any stage names as a plain context source: no --from, no URL,
* no glob, no variable, and a file under exactly one of the two contexts
* (dk_repo) that is no directory under the other. Once per file, at the
* first instruction naming it. */
static void dk_copy_refs(dk_t *d) {
const cbm_gbuf_node_t *self = d->ix->files ? cbm_ht_get(d->ix->files, d->file) : NULL;
if (!self || d->stage < 0) {
return;
}
int cap = 0;
for (int s = 0; s <= d->stage && s < DK_MAX_STAGES; s++) {
for (const dk_copy_t *c = d->st[s].copies; c; c = c->next) {
cap += c->has_from ? 0 : c->nsrc;
}
}
dk_fileref_t *refs = cap ? cbm_arena_alloc(d->a, (size_t)cap * sizeof(*refs)) : NULL;
int n = 0;
for (int s = 0; refs && s <= d->stage && s < DK_MAX_STAGES; s++) {
for (const dk_copy_t *c = d->st[s].copies; c; c = c->next) {
for (int k = 0; !c->has_from && k < c->nsrc; k++) {
const char *src = c->srcs[k];
if (!src || c->var[k] || strstr(src, "://") || dk_glob(src)) {
continue;
}
/* Docker refuses a source that climbs out of its context,
* whichever context that is. */
const char *rel = dk_norm(d, src + strspn(src, "/"));
if (!rel || (rel[0] == '.' && rel[SKIP_ONE] == '.' &&
(rel[PAIR_LEN] == '/' || rel[PAIR_LEN] == '\0'))) {
continue;
}
const char *p = dk_repo(d, src, NULL, DK_WANT_FILE);
if (p && dk_dir_under_other_context(d, src, p)) {
continue;
}
const cbm_gbuf_node_t *file = p ? cbm_ht_get(d->ix->files, p) : NULL;
if (file && file != self) {
refs[n++] = (dk_fileref_t){c->line, c->add, file};
}
}
}
}
if (n == 0) {
return;
}
qsort(refs, (size_t)n, sizeof(*refs), dk_fileref_cmp);
CBMHashTable *seen = cbm_ht_create(0);
for (int i = 0; seen && i < n; i++) {
const char *path = refs[i].file->file_path;
if (cbm_ht_get(seen, path)) {
continue;
}
cbm_ht_set(seen, path, (void *)path);
const char *props = cbm_arena_sprintf(d->a, "{\"via\":\"%s\",\"line\":%d}",
refs[i].add ? "add" : "copy", refs[i].line);
if (props) {
cbm_gbuf_insert_edge(d->ctx->gbuf, self->id, refs[i].file->id, "REFERENCES_FILE",
props);
d->edges++;
}
}
cbm_ht_free(seen);
}
static void dk_file(dk_t *d, TSNode root) {
for (uint32_t i = 0; i < ts_node_named_child_count(root); i++) {
TSNode ins = ts_node_named_child(root, i);
@@ -1761,6 +1886,7 @@ static void dk_file(dk_t *d, TSNode root) {
dk_spawn(d);
dk_envs(d);
dk_image_set(d);
dk_copy_refs(d);
}
/* A build's view of the Dockerfile: only what decides its image references
@@ -1908,7 +2034,8 @@ typedef struct {
const char *file;
const char *base; /* the compose file's module QN */
int64_t file_node;
int pass; /* 0: make the service nodes, 1: their edges */
CBMHashTable *files; /* the repository's File nodes by path; NULL: none */
int pass; /* 0: make the service nodes, 1: their edges */
int edges;
} dk_compose_t;
@@ -1983,6 +2110,46 @@ static void dk_compose_image(dk_compose_t *c, const cbm_compose_service_t *s, in
}
}
static int dk_compose_file_cmp(const void *x, const void *y) {
const cbm_compose_file_t *a = x;
const cbm_compose_file_t *b = y;
if (a->line != b->line) {
return a->line < b->line ? -1 : SKIP_ONE;
}
int c = strcmp(a->path, b->path);
return c ? c : strcmp(a->via, b->via);
}
/* P4.7: REFERENCES_FILE {via: volume | env_file | config | secret, line} from
* service `self` to each indexed file it names (a bind mount's host side, an
* env_file, a listed config's or secret's file), once per file at the first
* line naming it. A directory, a file the index does not hold and the compose
* file itself are none: the paths are stated relative to the compose file's
* directory, so nothing is guessed. */
static void dk_compose_files(dk_compose_t *c, const cbm_compose_service_t *s, int64_t self) {
if (!c->files || s->nfiles <= 0) {
return;
}
cbm_compose_file_t *v = cbm_arena_alloc(c->a, (size_t)s->nfiles * sizeof(*v));
CBMHashTable *seen = v ? cbm_ht_create((uint32_t)s->nfiles) : NULL;
if (!seen) {
return;
}
memcpy(v, s->files, (size_t)s->nfiles * sizeof(*v));
qsort(v, (size_t)s->nfiles, sizeof(*v), dk_compose_file_cmp);
for (int i = 0; i < s->nfiles; i++) {
const cbm_gbuf_node_t *f = cbm_ht_get(c->files, v[i].path);
if (!f || f->id == c->file_node || cbm_ht_get(seen, v[i].path)) {
continue;
}
cbm_ht_set(seen, v[i].path, (void *)f);
dk_compose_edge(
c, self, f->id, "REFERENCES_FILE",
cbm_arena_sprintf(c->a, "{\"via\":\"%s\",\"line\":%d}", v[i].via, v[i].line));
}
cbm_ht_free(seen);
}
static void dk_compose_service(const cbm_compose_service_t *s, void *ud) {
dk_compose_t *c = ud;
const char *qn = dk_compose_qn(c, s->name);
@@ -2029,6 +2196,7 @@ static void dk_compose_service(const cbm_compose_service_t *s, void *ud) {
"{\"via\":\"build\",\"tool\":\"compose\"}");
}
}
dk_compose_files(c, s, self->id);
}
/* The .env of the directory of `rel` under the repository, NULL when none. */
@@ -2054,6 +2222,7 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
return 0;
}
dk_builds_t b = {.ctx = ctx, .a = a};
CBMHashTable *by_path = NULL; /* built at the first build configuration */
for (int i = 0; i < n; i++) {
const char *rel = files[i]->file_path;
if (!rel || !cbm_build_path(rel)) {
@@ -2066,6 +2235,14 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
if (!src) {
continue;
}
if (!by_path) {
by_path = cbm_ht_create((uint32_t)n);
for (int k = 0; by_path && k < n; k++) {
if (files[k]->file_path) {
cbm_ht_set(by_path, files[k]->file_path, (void *)files[k]);
}
}
}
char *dotenv = dk_read_dotenv(ctx, rel);
b.file = rel;
cbm_build_sites(a, rel, src, len, dotenv, dk_build_site, &b);
@@ -2073,7 +2250,8 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
.a = a,
.file = rel,
.base = cbm_fqn_compute(a, ctx->project_name, rel, NULL),
.file_node = files[i]->id};
.file_node = files[i]->id,
.files = by_path};
for (cs.pass = 0; cs.base && cs.pass < PAIR_LEN; cs.pass++) {
cbm_compose_services(a, rel, src, len, dotenv, dk_compose_service, &cs);
}
@@ -2083,6 +2261,9 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
}
cbm_free(CBM_MEM_CLASS_OTHER, src);
}
if (by_path) {
cbm_ht_free(by_path);
}
return b.edges;
}
+212 -5
View File
@@ -1322,6 +1322,15 @@ typedef struct {
int line;
} k8s_kchart_t;
/* A file a kustomization reads (extract_k8s.c FILE fact): input to its
* build, no member of it. */
typedef struct {
char *kust; /* the kustomization file */
char *path; /* the file, from the repository root */
const char *via; /* static: configMapGenerator, secretGenerator, configurations */
int line;
} k8s_kfile_t;
typedef struct {
k8s_ref_t *refs;
int ref_n;
@@ -1350,6 +1359,9 @@ typedef struct {
k8s_kchart_t *kcharts;
int kchart_n;
int kchart_cap;
k8s_kfile_t *kfiles;
int kfile_n;
int kfile_cap;
} k8s_facts_t;
static void k8s_facts_free(k8s_facts_t *f) {
@@ -1407,6 +1419,11 @@ static void k8s_facts_free(k8s_facts_t *f) {
cbm_free(CBM_MEM_CLASS_OTHER, c->values);
}
cbm_free(CBM_MEM_CLASS_OTHER, f->kcharts);
for (int i = 0; i < f->kfile_n; i++) {
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles[i].kust);
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles[i].path);
}
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles);
cbm_free(CBM_MEM_CLASS_OTHER, f->envs);
cbm_free(CBM_MEM_CLASS_OTHER, f->hrs);
cbm_free(CBM_MEM_CLASS_OTHER, f->srcs);
@@ -3250,6 +3267,101 @@ static char *k8s_skeleton(const char *src, int len, int *out_len) {
return out;
}
/* ── Dependency-manifest text encoding (#2941) ────────────────────── */
enum { DEP_UTF8_BOM_LEN = 3, DEP_UTF16_UNIT = 2, DEP_UTF8_MAX_PER_UNIT = 3 };
/* One UTF-16 code unit at `u`, little- or big-endian. */
static uint32_t dep_utf16_unit(const unsigned char *u, bool le) {
return le ? (uint32_t)u[0] | ((uint32_t)u[1] << 8U) : ((uint32_t)u[0] << 8U) | (uint32_t)u[1];
}
/* Append BMP code point `c` (one UTF-16 unit, not a surrogate) to `out` as
* UTF-8; returns the bytes written (at most 3). */
static size_t dep_put_utf8_bmp(char *out, uint32_t c) {
unsigned char *o = (unsigned char *)out;
if (c < 0x80U) {
o[0] = (unsigned char)c;
return 1;
}
if (c < 0x800U) {
o[0] = (unsigned char)(0xC0U | (c >> 6U));
o[1] = (unsigned char)(0x80U | (c & 0x3FU));
return 2;
}
o[0] = (unsigned char)(0xE0U | (c >> 12U));
o[1] = (unsigned char)(0x80U | ((c >> 6U) & 0x3FU));
o[2] = (unsigned char)(0x80U | (c & 0x3FU));
return 3;
}
/* Append the code point of surrogate pair `hi`/`lo` to `out` as UTF-8 (always
* 4 bytes, fits the 3-bytes-per-unit budget of the two units). */
static size_t dep_put_utf8_pair(char *out, uint32_t hi, uint32_t lo) {
uint32_t c = 0x10000U + ((hi - 0xD800U) << 10U) + (lo - 0xDC00U);
unsigned char *o = (unsigned char *)out;
o[0] = (unsigned char)(0xF0U | (c >> 18U));
o[1] = (unsigned char)(0x80U | ((c >> 12U) & 0x3FU));
o[2] = (unsigned char)(0x80U | ((c >> 6U) & 0x3FU));
o[3] = (unsigned char)(0x80U | (c & 0x3FU));
return 4;
}
/* requirements.txt / go.mod as UTF-8 text. pip decodes a requirements file by
* its BOM, and Windows tools write BOMs: Windows PowerShell 5.1 saves
* `pip freeze > requirements.txt` as UTF-16 LE with a BOM, and many editors
* put a UTF-8 BOM in front. Read as raw bytes, UTF-16 stops at the NUL after
* the first letter, and a UTF-8 BOM sticks to the first package name.
* Drops a UTF-8 BOM in place (the freed tail bytes are zeroed, so the zero tail
* k8s_read_file adds stays intact), or returns a new UTF-8 buffer with a
* K8S_TS_PAD zero tail for UTF-16 (BOM dropped, `src` freed). A non-positive
* length (an empty file, or a size k8s_read_file could not represent as int)
* is returned unchanged. */
static char *dep_manifest_utf8(char *src, int *len) {
if (*len <= 0) {
return src;
}
const unsigned char *b = (const unsigned char *)src;
size_t n = (size_t)*len;
if (n >= DEP_UTF8_BOM_LEN && b[0] == 0xEFU && b[1] == 0xBBU && b[2] == 0xBFU) {
memmove(src, src + DEP_UTF8_BOM_LEN, n - DEP_UTF8_BOM_LEN);
memset(src + n - DEP_UTF8_BOM_LEN, 0, DEP_UTF8_BOM_LEN);
*len = (int)(n - DEP_UTF8_BOM_LEN);
return src;
}
bool le = n >= DEP_UTF16_UNIT && b[0] == 0xFFU && b[1] == 0xFEU;
bool be = n >= DEP_UTF16_UNIT && b[0] == 0xFEU && b[1] == 0xFFU;
if (!le && !be) {
return src;
}
size_t units = (n - DEP_UTF16_UNIT) / DEP_UTF16_UNIT;
char *out = cbm_alloc(CBM_MEM_CLASS_OTHER, (units * DEP_UTF8_MAX_PER_UNIT) + K8S_TS_PAD);
if (!out) {
return src;
}
const unsigned char *u = b + DEP_UTF16_UNIT;
size_t w = 0;
for (size_t i = 0; i < units; i++) {
uint32_t c = dep_utf16_unit(u + (i * DEP_UTF16_UNIT), le);
if (c >= 0xD800U && c <= 0xDBFFU && i + SKIP_ONE < units) {
uint32_t lo = dep_utf16_unit(u + ((i + SKIP_ONE) * DEP_UTF16_UNIT), le);
if (lo >= 0xDC00U && lo <= 0xDFFFU) {
w += dep_put_utf8_pair(out + w, c, lo);
i++;
continue;
}
}
if (c >= 0xD800U && c <= 0xDFFFU) {
c = 0xFFFDU; /* unpaired surrogate */
}
w += dep_put_utf8_bmp(out + w, c);
}
memset(out + w, 0, K8S_TS_PAD);
cbm_free(CBM_MEM_CLASS_OTHER, src);
*len = (int)w;
return out;
}
static void k8s_prep_file(const k8s_prep_job_t *job, int i, k8s_prep_t *out) {
cbm_pipeline_ctx_t *ctx = job->ctx;
const char *path = job->files[i].path;
@@ -3259,6 +3371,9 @@ static void k8s_prep_file(const k8s_prep_job_t *job, int i, k8s_prep_t *out) {
if (is_gomod_file(base) || lang == CBM_LANG_GOMOD || is_requirements_file(base)) {
out->source = k8s_read_file(path, &out->src_len);
if (out->source) {
out->source = dep_manifest_utf8(out->source, &out->src_len);
}
out->kind = out->source ? K8S_DEP : K8S_SKIP;
} else if (lang == CBM_LANG_KUSTOMIZE) {
/* Its `namespace:` is the namespace of the objects it builds; its
@@ -5270,21 +5385,59 @@ static void k8s_kchart_keep(k8s_facts_t *f, const char *kust, const CBMK8sFact *
.line = x->line};
}
/* Keep a kustomization's facts: its patches (PATCH) and the charts it
* inflates (DEPLOY via "kustomize"), each file as a repository path -- a
* patch file outside the repository (or a URL) names no file of it, a values
* file there is left out. */
/* The static name of a FILE fact's `via`; NULL: not one of ours. */
static const char *k8s_kfile_via(const char *via) {
static const char *const names[] = {"configMapGenerator", "secretGenerator", "configurations"};
for (size_t i = 0; via && i < sizeof(names) / sizeof(names[0]); i++) {
if (strcmp(via, names[i]) == 0) {
return names[i];
}
}
return NULL;
}
/* A file kustomization `kust` reads, at repository path `path`. */
static void k8s_kfile_keep(k8s_facts_t *f, const char *kust, const CBMK8sFact *x,
const char *path) {
const char *via = k8s_kfile_via(x->via);
if (!via || !k8s_grow((void **)&f->kfiles, &f->kfile_cap, f->kfile_n, sizeof(*f->kfiles))) {
return;
}
char *kust_copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, kust);
char *path_copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, path);
if (!kust_copy || !path_copy) {
cbm_free(CBM_MEM_CLASS_OTHER, kust_copy);
cbm_free(CBM_MEM_CLASS_OTHER, path_copy);
return;
}
f->kfiles[f->kfile_n++] =
(k8s_kfile_t){.kust = kust_copy, .path = path_copy, .via = via, .line = x->line};
}
/* Keep a kustomization's facts: its patches (PATCH), the charts it inflates
* (DEPLOY via "kustomize") and the files it reads (FILE), each file as a
* repository path -- a patch file outside the repository (or a URL) names no
* file of it, a values file or a read file there is left out. */
static void k8s_kustomize_keep(k8s_facts_t *f, const char *kust, const CBMFileResult *res) {
char dir[CBM_SZ_1K];
k8s_dirname(kust, dir, sizeof(dir));
for (int i = 0; res && i < res->k8s_facts.count; i++) {
const CBMK8sFact *x = &res->k8s_facts.items[i];
bool chart = x->fact == CBM_K8S_FACT_DEPLOY && x->via && strcmp(x->via, "kustomize") == 0;
if (x->fact != CBM_K8S_FACT_PATCH && !chart) {
bool file = x->fact == CBM_K8S_FACT_FILE;
if (x->fact != CBM_K8S_FACT_PATCH && !chart && !file) {
continue;
}
char path[CBM_SZ_1K];
bool in_repo = x->path && k8s_repo_path(dir, x->path, path, sizeof(path));
if (file) {
/* An absolute path names a file of the machine, not of the
* repository: k8s_repo_path would read it from the directory. */
if (in_repo && x->path[0] != '/') {
k8s_kfile_keep(f, kust, x, path);
}
continue;
}
if (chart) {
k8s_kchart_keep(f, kust, x, in_repo ? path : NULL);
continue;
@@ -5547,6 +5700,59 @@ static void k8s_patch_builds(const k8s_kusts_t *ks, const k8s_ints_t *inc, int k
}
}
static int k8s_cmp_kfile(const void *a, const void *b) {
const k8s_kfile_t *x = a;
const k8s_kfile_t *y = b;
int c = strcmp(x->kust, y->kust);
if (c == 0) {
c = (x->line > y->line) - (x->line < y->line);
}
return c ? c : strcmp(x->path, y->path);
}
/* The files kustomizations read -> REFERENCES_FILE {via: configMapGenerator |
* secretGenerator | configurations, line}, the kustomization's File to the
* file's File: once per kustomization and file, at the first line naming it.
* A file the index does not hold (a generated kubeconfig, a secret kept out
* of the repository) is none. Never an IMPORTS: that would make the file a
* member of the build (k8s_kusts_wire). */
static void k8s_link_kfiles(cbm_pipeline_ctx_t *ctx, k8s_facts_t *f) {
if (f->kfile_n == 0) {
return;
}
k8s_qsort(f->kfiles, (size_t)f->kfile_n, sizeof(*f->kfiles), k8s_cmp_kfile);
CBMArena keys;
cbm_arena_init_lazy(&keys, CBM_SZ_4K);
CBMHashTable *seen = cbm_ht_create((uint32_t)f->kfile_n);
int edges = 0;
for (int i = 0; seen && i < f->kfile_n; i++) {
const k8s_kfile_t *x = &f->kfiles[i];
const cbm_gbuf_node_t *tgt = cbm_pipeline_file_node(ctx->gbuf, ctx->project_name, x->path);
int64_t src = k8s_file_of(ctx, x->kust);
/* a File's QN folds `/` and `.` alike: the path itself must be the file's */
if (src <= 0 || !tgt || !tgt->file_path || strcmp(tgt->file_path, x->path) != 0 ||
tgt->id == src) {
continue;
}
const char *key = cbm_arena_sprintf(&keys, "%s\x01%s", x->kust, x->path);
if (!key || cbm_ht_get(seen, key)) {
continue;
}
cbm_ht_set(seen, key, (void *)key);
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"%s\",\"line\":%d}", x->via, x->line);
cbm_gbuf_insert_edge(ctx->gbuf, src, tgt->id, "REFERENCES_FILE", props);
edges++;
}
if (seen) {
cbm_ht_free(seen);
}
cbm_arena_destroy(&keys);
if (edges > 0) {
cbm_log_info("pass.k8s.kustomize_files", "edges", itoa_k8s(edges));
}
}
/* Kustomize patches -> OVERRIDE {via: patch, kustomization, patch, line},
* child -> base: each patch against the build of the kustomization stating
* it, a component's against the build of each kustomization including it
@@ -6013,6 +6219,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
k8s_helm_collect(ctx, &facts, &helm);
k8s_link_envs(ctx, &facts);
k8s_link_patches(ctx, &kusts, &facts);
k8s_link_kfiles(ctx, &facts);
k8s_link_renames(ctx, &kusts);
k8s_facts_free(&facts);
k8s_records_free(&recs);
+49 -6
View File
@@ -30,6 +30,7 @@
#include "lsp/php_lsp.h"
#include "lsp/java_lsp.h"
#include "lsp/kotlin_lsp.h"
#include "lsp/ruby_lsp.h"
#include "lsp/rust_lsp.h"
#include "lsp/rust_cargo.h"
#include "graph_buffer/graph_buffer.h"
@@ -837,6 +838,10 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
dst->trait_qn = src->impl_trait ? cbm_arena_strdup(arena, src->impl_trait) : NULL;
dst->is_abstract = src->is_abstract;
}
if (lang == CBM_LANG_RUBY) {
dst->is_singleton = src->is_singleton;
dst->mixin_refs = src->mixin_refs ? cbm_arena_strdup(arena, src->mixin_refs) : NULL;
}
return 0;
}
@@ -2357,7 +2362,7 @@ static bool pxc_c_run_registry(const pxc_file_t *f, pxc_walk_t *w) {
if (!cbm_run_c_lsp_cross_with_registry_with_test_owners(
w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->reg, f->imp_keys,
f->imp_vals, f->imp_count, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW,
f->result)) {
f->result, f->result->cpp_test_macro_names)) {
cbm_pipeline_test_owner_error(f->result);
return false; /* no append and no fallback on an invalid proof */
}
@@ -2365,7 +2370,7 @@ static bool pxc_c_run_registry(const pxc_file_t *f, pxc_walk_t *w) {
}
CBMLSPStatus status = cbm_run_c_lsp_cross_with_registry_status(
w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->reg, f->imp_keys,
f->imp_vals, f->imp_count, f->result->cached_tree, w->out);
f->imp_vals, f->imp_count, f->result->cached_tree, w->out, f->result->cpp_test_macro_names);
if (status != CBM_LSP_COMPLETE)
cbm_c_lsp_record_failure(f->result, status);
return true;
@@ -2380,15 +2385,16 @@ static bool pxc_c_run_defs(const pxc_file_t *f, pxc_walk_t *w) {
if (f->result->has_test_definition_owners) {
if (!cbm_run_c_lsp_cross_with_test_owners(
w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->defs, w->def_count,
NULL, NULL, 0, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW, f->result)) {
NULL, NULL, 0, f->result->cached_tree, w->out, CBM_SOURCE_ORIGIN_RAW, f->result,
f->result->cpp_test_macro_names)) {
cbm_pipeline_test_owner_error(f->result);
return false; /* out may be partial: never append it */
}
return true;
}
CBMLSPStatus status = cbm_run_c_lsp_cross_status(w->scratch, f->source, f->source_len,
f->module_qn, cpp_mode, w->defs, w->def_count,
NULL, NULL, 0, f->result->cached_tree, w->out);
CBMLSPStatus status = cbm_run_c_lsp_cross_status(
w->scratch, f->source, f->source_len, f->module_qn, cpp_mode, w->defs, w->def_count, NULL,
NULL, 0, f->result->cached_tree, w->out, f->result->cpp_test_macro_names);
if (status != CBM_LSP_COMPLETE)
cbm_c_lsp_record_failure(f->result, status);
return true;
@@ -2503,6 +2509,33 @@ static bool pxc_rust_run_defs(const pxc_file_t *f, pxc_walk_t *w) {
return true;
}
/* ── Ruby ── */
/* The shared Ruby registry is a CBMRubyCrossRegistry (method registry plus a
* hashed class table); its CBMTypeRegistry is the first member, so that is
* what the engine slot holds and the walk converts it back. Sealed and
* read-only: nothing is built per file, so the overlay the dispatcher chains
* to it goes unused. */
static CBMTypeRegistry *pxc_ruby_build_registry(CBMArena *arena, CBMLSPDef *defs, int def_count) {
CBMRubyCrossRegistry *r = cbm_ruby_build_cross_registry(arena, defs, def_count);
return r ? &r->reg : NULL;
}
static bool pxc_ruby_run_registry(const pxc_file_t *f, pxc_walk_t *w) {
_Static_assert(offsetof(CBMRubyCrossRegistry, reg) == 0, "engine slot is the registry");
cbm_run_ruby_lsp_cross_with_registry(w->scratch, f->source, f->source_len, f->module_qn,
(const CBMRubyCrossRegistry *)w->shared, f->imp_keys,
f->imp_vals, f->imp_count, f->result->cached_tree, w->out);
return true;
}
static bool pxc_ruby_run_defs(const pxc_file_t *f, pxc_walk_t *w) {
cbm_run_ruby_lsp_cross(w->scratch, f->source, f->source_len, f->module_qn, w->defs,
w->def_count, f->imp_keys, f->imp_vals, f->imp_count,
f->result->cached_tree, w->out);
return true;
}
/* The rows, in the order their shared registries are built. A row's index is
* its slot in CBMCrossLspRegistries. */
static const pxc_engine_t pxc_engines[] = {
@@ -2558,6 +2591,16 @@ static const pxc_engine_t pxc_engines[] = {
.build_registry = cbm_java_build_cross_registry,
.run_with_registry = pxc_java_run_registry,
.run_one = pxc_java_run_defs},
/* Ruby constants live in one global namespace and Rails/Zeitwerk autoloads
* them without require statements, so an own+imports filter would starve
* almost all cross-file resolution: the walk always sees the whole project. */
{.name = "ruby",
.langs = {CBM_LANG_RUBY},
.lang_count = 1,
.build_registry = pxc_ruby_build_registry,
.run_with_registry = pxc_ruby_run_registry,
.run_one = pxc_ruby_run_defs,
.unfiltered_defs = true},
{.name = "php", .langs = {CBM_LANG_PHP}, .lang_count = 1, .run_one = pxc_php_run_defs},
{.name = "kotlin", .langs = {CBM_LANG_KOTLIN}, .lang_count = 1, .run_one = pxc_kotlin_run_defs},
{.name = "rust",
+2 -1
View File
@@ -14,7 +14,7 @@
*
* The languages covered are the rows of one engine table (pass_lsp_cross.c
* pxc_engines): Go, C/C++/CUDA, Python, TypeScript/JavaScript/JSX/TSX, PHP,
* C#, Java, Kotlin and Rust. Anything else short-circuits via
* C#, Ruby, Java, Kotlin and Rust. Anything else short-circuits via
* cbm_pxc_has_cross_lsp.
*
* Previously this work ran as a separate sequential pipeline pass
@@ -38,6 +38,7 @@
#include "lsp/ts_lsp.h" /* cbm_ts_build_cross_registry / cbm_run_ts_lsp_cross_with_registry */
#include "lsp/java_lsp.h" /* cbm_java_build_cross_registry / cbm_run_java_lsp_cross_with_registry */
#include "lsp/rust_lsp.h" /* cbm_rust_build_cross_registry / cbm_run_rust_lsp_cross_with_registry */
#include "lsp/ruby_lsp.h" /* cbm_ruby_build_cross_registry; _cross is the per-file fallback */
#include "pipeline/pipeline_internal.h"
#include "pipeline/type_scope.h" /* cbm_type_scope_file_t */
#include <stdbool.h>
+591 -134
View File
@@ -120,6 +120,11 @@ enum { PP_CSHARP_M_PREFIX_LEN = 2 };
* memory (the resident floor, not in-flight transients, holds the budget). */
static _Atomic long g_bp_nap_cycles = 0;
static _Atomic uint64_t g_lsp_linear_fallback_rows = 0;
static _Atomic uint64_t g_lsp_index_lookups = 0;
/* Defined here, declared in lsp_resolve.h: rows read by a per-call scan of a
* file's engine rows, counted inside the scan, so a call site that goes back
* to scanning shows up whichever way it calls. */
_Atomic uint64_t g_lsp_scan_rows = 0;
/* Defined here, declared in lsp_resolve.h — the uncapped tail-match scan's
* cost, surfaced at end of resolve (#1669). */
_Atomic uint64_t g_lsp_tail_lookups = 0;
@@ -137,8 +142,18 @@ uint64_t cbm_pp_lsp_linear_fallback_rows(void) {
return atomic_load_explicit(&g_lsp_linear_fallback_rows, memory_order_relaxed);
}
uint64_t cbm_pp_lsp_index_lookups(void) {
return atomic_load_explicit(&g_lsp_index_lookups, memory_order_relaxed);
}
uint64_t cbm_pp_lsp_scan_rows(void) {
return atomic_load_explicit(&g_lsp_scan_rows, memory_order_relaxed);
}
void cbm_pp_lsp_linear_fallback_rows_reset(void) {
atomic_store_explicit(&g_lsp_linear_fallback_rows, 0, memory_order_relaxed);
atomic_store_explicit(&g_lsp_index_lookups, 0, memory_order_relaxed);
atomic_store_explicit(&g_lsp_scan_rows, 0, memory_order_relaxed);
atomic_store_explicit(&g_lsp_tail_lookups, 0, memory_order_relaxed);
atomic_store_explicit(&g_lsp_tail_candidates, 0, memory_order_relaxed);
}
@@ -2097,7 +2112,10 @@ typedef struct __attribute__((aligned(CBM_CACHE_LINE))) {
* log line so divergence between pipelines becomes observable. */
int lsp_overrides;
CBMFileResult *loaded; /* spill-loaded result this worker is using */
char _pad[CBM_CACHE_LINE - 2 * sizeof(void *) - ((PP_RING + 1) * sizeof(int))];
/* the shared layer's memo of this worker (site_bind.h), made on its
* first lookup, freed after the workers join */
cbm_site_memo_t *site_memo;
char _pad[CBM_CACHE_LINE - 3 * sizeof(void *) - ((PP_RING + 1) * sizeof(int))];
} resolve_worker_state_t;
typedef struct {
@@ -3108,11 +3126,12 @@ static void try_field_type_hint(resolve_ctx_t *rc, cbm_resolution_t *res, const
}
}
/* Free a strdup'd key stored in the per-file lsp_idx hash table. */
/* Free a key stored in a per-file lsp_idx hash table. Keys are allocated
* through the memory core (lsp_idx_key, lsp_idx_keep_best). */
static void lsp_idx_free_key(const char *key, void *value, void *ud) {
(void)value;
(void)ud;
free((char *)key);
cbm_free(CBM_MEM_CLASS_RESOLVE, (char *)key);
}
/* A hash key may have multiple semantic rows. Keep a permanent tombstone for
@@ -3128,13 +3147,13 @@ static bool lsp_idx_keep_best(CBMHashTable *index, const char *key, CBMResolvedC
}
CBMResolvedCall *existing = (CBMResolvedCall *)cbm_ht_get(index, key);
if (!existing) {
char *owned_key = strdup(key);
char *owned_key = cbm_mem_strdup(CBM_MEM_CLASS_RESOLVE, key);
if (owned_key) {
cbm_ht_set(index, owned_key, candidate);
if (cbm_ht_get(index, key) == candidate) {
return true;
}
free(owned_key);
cbm_free(CBM_MEM_CLASS_RESOLVE, owned_key);
}
return false;
}
@@ -3160,7 +3179,11 @@ static bool lsp_idx_keep_best(CBMHashTable *index, const char *key, CBMResolvedC
/* Caller QNs are user-controlled graph identifiers and can legitimately exceed
* the old 1 KiB stack buffer. Build occurrence keys at their exact length so an
* exact semantic row can never disappear merely because its caller is long. */
* exact semantic row can never disappear merely because its caller is long.
* The key starts with the caller's length: a caller and a leaf may both
* contain '|', and without the length `a|b` + `c` and `a` + `b|c` would be one
* key. The span and the origin are read from the right, so a key names exactly
* one caller, one leaf, one span and one origin. */
static char *lsp_idx_key(const char *caller_qn, const char *leaf, bool exact_site,
uint32_t site_start_byte, uint32_t site_end_byte,
CBMSourceOrigin source_origin) {
@@ -3169,21 +3192,21 @@ static char *lsp_idx_key(const char *caller_qn, const char *leaf, bool exact_sit
}
size_t caller_len = strlen(caller_qn);
size_t leaf_len = strlen(leaf);
size_t suffix_len = exact_site ? 48U : 16U;
size_t suffix_len = exact_site ? 72U : 40U; /* the length, the span, the origin */
if (caller_len > SIZE_MAX - leaf_len - suffix_len - 2U) {
return NULL;
}
size_t cap = caller_len + 1U + leaf_len + suffix_len + 1U;
char *key = (char *)malloc(cap);
char *key = (char *)cbm_alloc(CBM_MEM_CLASS_RESOLVE, cap);
if (!key) {
return NULL;
}
int written = exact_site
? snprintf(key, cap, "%s|%s|%u:%u|%u", caller_qn, leaf, site_start_byte,
site_end_byte, (unsigned)source_origin)
: snprintf(key, cap, "%s|%s|%u", caller_qn, leaf, (unsigned)source_origin);
int written = exact_site ? snprintf(key, cap, "%zu|%s|%s|%u:%u|%u", caller_len, caller_qn, leaf,
site_start_byte, site_end_byte, (unsigned)source_origin)
: snprintf(key, cap, "%zu|%s|%s|%u", caller_len, caller_qn, leaf,
(unsigned)source_origin);
if (written <= 0 || (size_t)written >= cap) {
free(key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
return NULL;
}
return key;
@@ -3201,10 +3224,199 @@ static bool lsp_idx_insert_leaf(CBMHashTable *index, CBMResolvedCall *candidate,
return false;
}
bool inserted = lsp_idx_keep_best(index, key, candidate, gbuf, project_name, allow_tail_match);
free(key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
return inserted;
}
static bool lsp_idx_insert_tail_leaf(CBMHashTable *index, CBMResolvedCall *row, const char *tail,
const char *leaf, const cbm_gbuf_t *gbuf,
const char *project_name) {
char *key = lsp_idx_key(tail, leaf, false, 0, 0, row->source_origin);
if (!key) {
return false;
}
bool inserted = lsp_idx_keep_best(index, key, row, gbuf, project_name, true);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
return inserted;
}
/* A row without a span into the JVM tail table: under the Class.method tail of
* its caller and each leaf it answers to (its callee's, and its reason's for an
* indirect resolver), as the main tables hold it under its whole caller. A
* caller too short to have such a tail equals no call's tail and is left out;
* so is an empty leaf, whose call has no key and goes to the matcher. */
static void lsp_idx_insert_tail_row(cbm_pipeline_lsp_index_t *idx, CBMResolvedCall *row,
uint32_t capacity, const cbm_gbuf_t *gbuf,
const char *project_name) {
const char *tail = cbm_pipeline_qn_class_method_tail(row->caller_qn);
if (!tail) {
return;
}
if (!idx->tail_legacy) {
idx->tail_legacy = cbm_ht_create(capacity);
}
const char *leaf = cbm_lsp_bare_segment(row->callee_qn);
if (!(leaf && !leaf[0]) &&
!lsp_idx_insert_tail_leaf(idx->tail_legacy, row, tail, leaf, gbuf, project_name)) {
idx->tail_legacy_complete = false;
}
if (row->reason && cbm_pipeline_invocation_reason_join_strategy(row->strategy)) {
const char *reason_leaf = cbm_lsp_bare_segment(row->reason);
if (!(reason_leaf && !reason_leaf[0]) &&
!lsp_idx_insert_tail_leaf(idx->tail_legacy, row, tail, reason_leaf, gbuf,
project_name)) {
idx->tail_legacy_complete = false;
}
}
}
static int lsp_idx_site_row_cmp(const void *lhs, const void *rhs) {
const cbm_pipeline_lsp_site_row_t *a = (const cbm_pipeline_lsp_site_row_t *)lhs;
const cbm_pipeline_lsp_site_row_t *b = (const cbm_pipeline_lsp_site_row_t *)rhs;
if (a->start != b->start) {
return a->start < b->start ? -1 : 1;
}
if (a->end != b->end) {
return a->end < b->end ? -1 : 1;
}
if (a->origin != b->origin) {
return a->origin < b->origin ? -1 : 1;
}
/* The array position last: the order is total, so an unstable sort still
* leaves the rows of one occurrence in array order. */
return a->row < b->row ? -1 : (a->row > b->row ? 1 : 0);
}
/* Every row that can rank at an exact occurrence, sorted so that the rows of
* one occurrence are neighbours in array order. */
static void lsp_idx_build_site_rows(cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr) {
int count = 0;
for (int i = 0; i < arr->count; i++) {
const CBMResolvedCall *rc = &arr->items[i];
if (cbm_pipeline_invocation_row(rc) &&
cbm_pipeline_source_site_present(rc->site_start_byte, rc->site_end_byte)) {
count++;
}
}
if (count == 0) {
return;
}
cbm_pipeline_lsp_site_row_t *rows = (cbm_pipeline_lsp_site_row_t *)cbm_alloc(
CBM_MEM_CLASS_RESOLVE, (size_t)count * sizeof(*rows));
if (!rows) {
idx->site_complete = false;
return;
}
int filled = 0;
for (int i = 0; i < arr->count; i++) {
const CBMResolvedCall *rc = &arr->items[i];
if (cbm_pipeline_invocation_row(rc) &&
cbm_pipeline_source_site_present(rc->site_start_byte, rc->site_end_byte)) {
rows[filled].start = rc->site_start_byte;
rows[filled].end = rc->site_end_byte;
rows[filled].origin = (uint32_t)rc->source_origin;
rows[filled].row = i;
filled++;
}
}
qsort(rows, (size_t)count, sizeof(*rows), lsp_idx_site_row_cmp);
idx->site_rows = rows;
idx->site_count = count;
}
/* The rows at the call's own occurrence: their number, and through `first`
* where they start in idx->site_rows. */
static int lsp_idx_site_range(const cbm_pipeline_lsp_index_t *idx, const CBMCall *call,
int *first) {
cbm_pipeline_lsp_site_row_t want = {call->site_start_byte, call->site_end_byte,
(uint32_t)call->source_origin, -1};
int lo = 0;
int hi = idx->site_count;
while (lo < hi) {
int mid = lo + ((hi - lo) / 2);
if (lsp_idx_site_row_cmp(&idx->site_rows[mid], &want) < 0) {
lo = mid + SKIP_ONE;
} else {
hi = mid;
}
}
*first = lo;
int count = 0;
while (lo + count < idx->site_count && idx->site_rows[lo + count].start == want.start &&
idx->site_rows[lo + count].end == want.end &&
idx->site_rows[lo + count].origin == want.origin) {
count++;
}
return count;
}
/* The matcher's choice among the rows at the call's own occurrence, by the
* matcher's own row tests: its first phase (the call's own caller), or with
* `tail_phase` the exact rows of its tail phase. `*any` says whether a row
* qualified, because an ambiguous choice answers NULL as well. */
static const CBMResolvedCall *lsp_idx_site_choice(const cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr,
const CBMCall *call, bool tail_phase,
bool allow_tail, const cbm_gbuf_t *gbuf,
const char *project_name, bool *any) {
int first = 0;
int count = lsp_idx_site_range(idx, call, &first);
atomic_fetch_add_explicit(&g_lsp_index_lookups, 1U + (uint64_t)count, memory_order_relaxed);
const char *call_tail =
tail_phase ? cbm_pipeline_qn_class_method_tail(call->enclosing_func_qn) : NULL;
const CBMResolvedCall *best = NULL;
bool ambiguous = false;
for (int i = first; i < first + count; i++) {
const CBMResolvedCall *rc = &arr->items[idx->site_rows[i].row];
int site_rank = cbm_pipeline_invocation_site_rank(rc, call);
if (site_rank != 2) {
continue;
}
bool caller_matches =
tail_phase ? cbm_pipeline_invocation_tail_caller_matches(rc, call, call_tail, site_rank)
: strcmp(rc->caller_qn, call->enclosing_func_qn) == 0;
if (!caller_matches || !cbm_pipeline_invocation_leaf_matches(rc, call, site_rank)) {
continue;
}
cbm_pipeline_invocation_fold(&best, &ambiguous, rc, gbuf, project_name, allow_tail);
}
*any = best != NULL;
return ambiguous ? NULL : best;
}
/* The tail phase's rows without a span: the choice among the rows whose caller
* has the call's Class.method tail. `*authoritative` goes false where the table
* cannot answer for this call (no key, or a row the call rejects). */
static const CBMResolvedCall *lsp_idx_tail_legacy_choice(const cbm_pipeline_lsp_index_t *idx,
const CBMCall *call, bool *authoritative) {
*authoritative = true;
const char *call_tail = cbm_pipeline_qn_class_method_tail(call->enclosing_func_qn);
if (!call_tail || !idx->tail_legacy) {
return NULL; /* no caller tail to share, or no such row in the file */
}
char *key = lsp_idx_key(call_tail, cbm_pipeline_call_callee_leaf(call->callee_name), false, 0,
0, call->source_origin);
if (!key) {
*authoritative = false;
return NULL;
}
atomic_fetch_add_explicit(&g_lsp_index_lookups, 1, memory_order_relaxed);
const CBMResolvedCall *candidate = (const CBMResolvedCall *)cbm_ht_get(idx->tail_legacy, key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
if (!candidate || candidate == LSP_IDX_AMBIGUOUS) {
return NULL;
}
if (cbm_pipeline_invocation_row(candidate) &&
cbm_pipeline_qn_class_method_tail_eq(candidate->caller_qn, call_tail) &&
cbm_pipeline_invocation_site_rank(candidate, call) == 1 &&
cbm_pipeline_invocation_leaf_matches(candidate, call, 1)) {
return candidate;
}
*authoritative = false;
return NULL;
}
static const CBMResolvedCall *lsp_idx_lookup(const CBMHashTable *index, const CBMCall *call,
bool exact_site, bool *key_built, bool *ambiguous) {
if (key_built) {
@@ -3228,25 +3440,351 @@ static const CBMResolvedCall *lsp_idx_lookup(const CBMHashTable *index, const CB
if (key_built) {
*key_built = true;
}
atomic_fetch_add_explicit(&g_lsp_index_lookups, 1, memory_order_relaxed);
const CBMResolvedCall *candidate = (const CBMResolvedCall *)cbm_ht_get(index, key);
free(key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
if (candidate == LSP_IDX_AMBIGUOUS) {
if (ambiguous) {
*ambiguous = true;
}
return NULL;
}
if (!candidate || candidate->kind != CBM_RESOLVED_INVOCATION || !candidate->caller_qn ||
if (!candidate) {
return NULL;
}
if (candidate->kind != CBM_RESOLVED_INVOCATION || !candidate->caller_qn ||
strcmp(candidate->caller_qn, call->enclosing_func_qn) != 0 ||
candidate->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
if (key_built) {
*key_built = false;
}
return NULL;
}
int site_rank = cbm_pipeline_invocation_site_rank(candidate, call);
int expected_rank = exact_site ? 2 : 1;
return site_rank == expected_rank &&
cbm_pipeline_invocation_leaf_matches(candidate, call, site_rank)
? candidate
: NULL;
if (site_rank == expected_rank &&
cbm_pipeline_invocation_leaf_matches(candidate, call, site_rank)) {
return candidate;
}
/* The key's row does not answer for this call: the key is no authority
* for it, the matcher decides (cbm_pipeline_lsp_index_find). */
if (key_built) {
*key_built = false;
}
return NULL;
}
/* One unindexed-receiver row of PHP into the index: the first row of a key in
* array order stays, as the scan answers from the first row that matches. A
* row with a partial or reversed span ranks for no call and is left out. */
static void lsp_idx_insert_php(cbm_pipeline_lsp_index_t *idx, CBMResolvedCall *row,
uint32_t capacity) {
bool exact_site = cbm_pipeline_source_site_present(row->site_start_byte, row->site_end_byte);
if (!exact_site && !cbm_pipeline_source_site_legacy(row->site_start_byte, row->site_end_byte)) {
return;
}
idx->php_rows++;
CBMHashTable **table = exact_site ? &idx->php_exact : &idx->php_legacy;
if (!*table) {
*table = cbm_ht_create(capacity);
}
char *key = *table
? lsp_idx_key(row->caller_qn, cbm_lsp_bare_segment(row->callee_qn), exact_site,
row->site_start_byte, row->site_end_byte, row->source_origin)
: NULL;
if (!key) {
idx->php_complete = false;
return;
}
if (cbm_ht_get(*table, key)) {
cbm_free(CBM_MEM_CLASS_RESOLVE, key); /* an earlier row has the key */
return;
}
cbm_ht_set(*table, key, row);
if (cbm_ht_get(*table, key) != row) {
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
idx->php_complete = false;
}
}
/* The per-file index both resolvers look a call's engine row up in:
* exact caller+leaf+span first, then the legacy caller+leaf rows recorded
* without a span. Repeated same-leaf calls stay O(1) and a high-confidence 0:0
* record can never hide an exact source occurrence. `arr` NULL builds an empty,
* complete index. Keys are owned by the index (cbm_pipeline_lsp_index_free). */
void cbm_pipeline_lsp_index_build(cbm_pipeline_lsp_index_t *idx, const CBMResolvedCallArray *arr,
const cbm_gbuf_t *gbuf, const char *project_name,
bool allow_tail) {
idx->exact = NULL;
idx->legacy = NULL;
idx->exact_complete = true;
idx->legacy_complete = true;
idx->site_rows = NULL;
idx->site_count = 0;
idx->site_complete = true;
idx->tail_legacy = NULL;
idx->tail_legacy_complete = true;
idx->tail_indexed = allow_tail;
idx->php_exact = NULL;
idx->php_legacy = NULL;
idx->php_rows = 0;
idx->php_complete = true;
if (!arr || arr->count <= 0) {
return;
}
lsp_idx_build_site_rows(idx, arr);
uint32_t capacity = (uint32_t)arr->count * 2u + 16u;
idx->exact = cbm_ht_create(capacity);
idx->legacy = cbm_ht_create(capacity);
if (!idx->exact) {
idx->exact_complete = false;
}
if (!idx->legacy) {
idx->legacy_complete = false;
}
if (!idx->exact && !idx->legacy) {
idx->php_complete = false; /* no row was read */
idx->tail_legacy_complete = false;
return;
}
for (int i = 0; i < arr->count; i++) {
CBMResolvedCall *rc_e = &arr->items[i];
if (cbm_pipeline_php_unindexed_row(rc_e)) {
lsp_idx_insert_php(idx, rc_e, capacity);
}
if (rc_e->kind != CBM_RESOLVED_INVOCATION || !rc_e->caller_qn || !rc_e->callee_qn ||
rc_e->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
continue;
}
bool exact_site =
cbm_pipeline_source_site_present(rc_e->site_start_byte, rc_e->site_end_byte);
bool legacy_site =
cbm_pipeline_source_site_legacy(rc_e->site_start_byte, rc_e->site_end_byte);
if (!exact_site && !legacy_site) {
continue;
}
CBMHashTable *index = exact_site ? idx->exact : idx->legacy;
bool *complete = exact_site ? &idx->exact_complete : &idx->legacy_complete;
/* A row whose leaf is empty (a callee that ends in a separator, such
* as `T.operator->`) can answer only a call whose own leaf is empty,
* and such a call has no key and is decided by the matcher. Leaving
* the row out therefore loses nothing; calling the index incomplete
* for it would send every miss of the file to the scan. */
const char *leaf = cbm_lsp_bare_segment(rc_e->callee_qn);
if (!(leaf && !leaf[0]) &&
!lsp_idx_insert_leaf(index, rc_e, leaf, exact_site, gbuf, project_name, allow_tail)) {
*complete = false;
}
if (rc_e->reason && cbm_pipeline_invocation_reason_join_strategy(rc_e->strategy)) {
const char *reason_leaf = cbm_lsp_bare_segment(rc_e->reason);
if (!(reason_leaf && !reason_leaf[0]) &&
!lsp_idx_insert_leaf(index, rc_e, reason_leaf, exact_site, gbuf, project_name,
allow_tail)) {
*complete = false;
}
}
if (legacy_site && allow_tail) {
lsp_idx_insert_tail_row(idx, rc_e, capacity, gbuf, project_name);
}
}
}
void cbm_pipeline_lsp_index_free(cbm_pipeline_lsp_index_t *idx) {
if (idx->exact) {
cbm_ht_foreach(idx->exact, lsp_idx_free_key, NULL);
cbm_ht_free(idx->exact);
idx->exact = NULL;
}
if (idx->legacy) {
cbm_ht_foreach(idx->legacy, lsp_idx_free_key, NULL);
cbm_ht_free(idx->legacy);
idx->legacy = NULL;
}
if (idx->tail_legacy) {
cbm_ht_foreach(idx->tail_legacy, lsp_idx_free_key, NULL);
cbm_ht_free(idx->tail_legacy);
idx->tail_legacy = NULL;
}
if (idx->site_rows) {
cbm_free(CBM_MEM_CLASS_RESOLVE, idx->site_rows);
idx->site_rows = NULL;
idx->site_count = 0;
}
if (idx->php_exact) {
cbm_ht_foreach(idx->php_exact, lsp_idx_free_key, NULL);
cbm_ht_free(idx->php_exact);
idx->php_exact = NULL;
}
if (idx->php_legacy) {
cbm_ht_foreach(idx->php_legacy, lsp_idx_free_key, NULL);
cbm_ht_free(idx->php_legacy);
idx->php_legacy = NULL;
}
}
/* PHP's check for a receiver typed as a class the index does not hold
* (cbm_pipeline_php_receiver_type_unindexed): the first row of the file that
* is this call's decides. A call's rows share its key (caller, leaf, span and
* origin, or caller, leaf and origin for a row without a span), and a key
* names exactly one such tuple (lsp_idx_key), so the first of them is the
* earlier of the two tables' rows for that key. A key that cannot be built
* and an incomplete index go to the scan. */
bool cbm_pipeline_lsp_index_php_receiver_unindexed(const cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr,
const CBMCall *call,
const cbm_registry_t *registry) {
if (!arr || !call || !call->enclosing_func_qn || !call->callee_name) {
return false;
}
bool scan = !idx || !idx->php_complete;
if (!scan) {
if (idx->php_rows == 0) {
return false; /* the file has no such row */
}
const CBMResolvedCall *first = NULL;
bool site_present =
cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte);
if (!site_present &&
!cbm_pipeline_source_site_legacy(call->site_start_byte, call->site_end_byte)) {
return false; /* a partial or reversed span ranks no row */
}
const char *leaf = cbm_lsp_bare_segment(call->callee_name);
if (!leaf) {
return false; /* no leaf to match a row's */
}
atomic_fetch_add_explicit(&g_lsp_index_lookups, 1, memory_order_relaxed);
if (site_present && idx->php_exact) {
char *key = lsp_idx_key(call->enclosing_func_qn, leaf, true, call->site_start_byte,
call->site_end_byte, call->source_origin);
if (key) {
first = (const CBMResolvedCall *)cbm_ht_get(idx->php_exact, key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
} else {
scan = true;
}
}
if (!scan && !call->requires_lsp_resolution && idx->php_legacy) {
char *key =
lsp_idx_key(call->enclosing_func_qn, leaf, false, 0, 0, call->source_origin);
if (key) {
const CBMResolvedCall *legacy =
(const CBMResolvedCall *)cbm_ht_get(idx->php_legacy, key);
cbm_free(CBM_MEM_CLASS_RESOLVE, key);
if (legacy && (!first || legacy < first)) {
first = legacy;
}
} else {
scan = true;
}
}
if (!scan) {
return first ? cbm_pipeline_php_unindexed_row_verdict(first, registry) : false;
}
}
atomic_fetch_add_explicit(&g_lsp_linear_fallback_rows, (uint64_t)arr->count,
memory_order_relaxed);
return cbm_pipeline_php_receiver_type_unindexed(arr, call, registry);
}
/* The matcher's answer by its scan of every row, where the index may not hold
* the answer. */
static const CBMResolvedCall *lsp_idx_scan(const CBMResolvedCallArray *arr, const CBMCall *call,
bool allow_tail, const cbm_gbuf_t *gbuf,
const char *project_name) {
atomic_fetch_add_explicit(&g_lsp_linear_fallback_rows, arr ? (uint64_t)arr->count : 0U,
memory_order_relaxed);
return cbm_pipeline_find_lsp_resolution_in_graph(arr, call, allow_tail, gbuf, project_name);
}
/* The language engine's row for one call: the answer of the matcher
* (cbm_pipeline_find_lsp_resolution_in_graph), from the index where the index
* holds it and from the matcher's scan where it may not (an incomplete index,
* a key that cannot be built, a hit the call rejects). Both resolvers call
* this.
*
* The matcher has two phases. The first takes the rows of the call's own
* caller: at the call's exact occurrence first, then those without a span.
* Only if there is none, and only for a JVM caller, the tail phase takes the
* rows whose caller shares the call's Class.method tail (or, at the exact
* occurrence, its bare name), again exact before span-less. A call that needs
* the engine ranks no span-less row, so both its phases are among the rows at
* its own occurrence. */
const CBMResolvedCall *cbm_pipeline_lsp_index_find(const cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr,
const CBMCall *call, bool allow_tail,
const cbm_gbuf_t *gbuf,
const char *project_name) {
bool site_present =
cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte);
if (!site_present &&
!cbm_pipeline_source_site_legacy(call->site_start_byte, call->site_end_byte)) {
/* A partial or reversed span ranks no row: the matcher finds none. */
return NULL;
}
bool any = false;
if (call->requires_lsp_resolution) {
if (!idx->site_complete || !call->enclosing_func_qn || !call->callee_name) {
return lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
if (!site_present) {
return NULL; /* no row ranks for it without an occurrence */
}
const CBMResolvedCall *own =
lsp_idx_site_choice(idx, arr, call, false, allow_tail, gbuf, project_name, &any);
if (any || !allow_tail) {
return own;
}
return lsp_idx_site_choice(idx, arr, call, true, allow_tail, gbuf, project_name, &any);
}
/* First phase, the call's own caller: the exact occurrence, then the rows
* without a span. A miss counts only where the table is complete and the
* key could be built and was the call's; elsewhere the matcher decides. */
bool key_built = true;
bool ambiguous = false;
if (site_present) {
const CBMResolvedCall *exact =
lsp_idx_lookup(idx->exact, call, true, &key_built, &ambiguous);
if (exact) {
return exact;
}
if (!idx->exact_complete || !key_built) {
/* An incomplete exact index must fail closed: the matcher is
* asked before a row without a span can win. */
return lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
if (ambiguous) {
return NULL; /* rows of its own caller exist and disagree */
}
} else if (!idx->exact_complete) {
return lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
const CBMResolvedCall *legacy =
lsp_idx_lookup(idx->legacy, call, false, &key_built, &ambiguous);
if (legacy) {
return legacy;
}
if (!idx->legacy_complete || !key_built) {
return lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
if (ambiguous || !allow_tail) {
return NULL;
}
/* Tail phase (JVM): no row of the call's own caller answers it. */
if (!idx->site_complete || !idx->tail_legacy_complete || !idx->tail_indexed) {
return lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
if (site_present) {
const CBMResolvedCall *exact_tail =
lsp_idx_site_choice(idx, arr, call, true, allow_tail, gbuf, project_name, &any);
if (any) {
return exact_tail;
}
}
bool authoritative = true;
const CBMResolvedCall *legacy_tail = lsp_idx_tail_legacy_choice(idx, call, &authoritative);
return authoritative ? legacy_tail : lsp_idx_scan(arr, call, allow_tail, gbuf, project_name);
}
static CBMCallEvidence *resolve_evidence_at(CBMCallEvidence *evidence, int index,
@@ -3279,74 +3817,15 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
char route_mount[CBM_SZ_128];
cbm_laravel_file_route_mount(rc->repo_path, rel, lang, result, route_mount,
sizeof(route_mount));
/* Two occurrence-aware indexes preserve the authoritative matcher's
* primary ordering without restoring its O(calls × resolutions) scan:
* exact caller+leaf+span first, then the legacy caller+leaf fallback.
* Repeated same-leaf calls therefore remain O(1), and a high-confidence
* 0:0 record can never hide an exact source occurrence. */
CBMHashTable *lsp_exact_idx = NULL;
CBMHashTable *lsp_legacy_idx = NULL;
bool lsp_exact_idx_complete = true;
bool lsp_legacy_idx_complete = true;
bool allow_tail = cbm_pipeline_lsp_allow_tail_match(lang);
/* Names this file's imports bind onto external libraries, built on the
* first unresolved call that asks (see pass_calls.c). */
cbm_external_import_index_t ext_imports = {0};
if (result->calls.count > 0 && result->resolved_calls.count > 0) {
uint32_t capacity = (uint32_t)result->resolved_calls.count * 2u + 16u;
lsp_exact_idx = cbm_ht_create(capacity);
lsp_legacy_idx = cbm_ht_create(capacity);
if (!lsp_exact_idx) {
lsp_exact_idx_complete = false;
}
if (!lsp_legacy_idx) {
lsp_legacy_idx_complete = false;
}
if (lsp_exact_idx || lsp_legacy_idx) {
for (int i = 0; i < result->resolved_calls.count; i++) {
CBMResolvedCall *rc_e = &result->resolved_calls.items[i];
if (rc_e->kind != CBM_RESOLVED_INVOCATION || !rc_e->caller_qn || !rc_e->callee_qn ||
rc_e->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
continue;
}
bool exact_site =
cbm_pipeline_source_site_present(rc_e->site_start_byte, rc_e->site_end_byte);
bool legacy_site =
cbm_pipeline_source_site_legacy(rc_e->site_start_byte, rc_e->site_end_byte);
if (!exact_site && !legacy_site) {
continue;
}
CBMHashTable *index = exact_site ? lsp_exact_idx : lsp_legacy_idx;
bool inserted =
lsp_idx_insert_leaf(index, rc_e, cbm_lsp_bare_segment(rc_e->callee_qn),
exact_site, rc->main_gbuf, rc->project_name, allow_tail);
if (!inserted) {
if (exact_site) {
lsp_exact_idx_complete = false;
} else {
lsp_legacy_idx_complete = false;
}
}
if (rc_e->reason && cbm_pipeline_invocation_reason_join_strategy(rc_e->strategy)) {
inserted = lsp_idx_insert_leaf(index, rc_e, cbm_lsp_bare_segment(rc_e->reason),
exact_site, rc->main_gbuf, rc->project_name,
allow_tail);
if (!inserted) {
if (exact_site) {
lsp_exact_idx_complete = false;
} else {
lsp_legacy_idx_complete = false;
}
}
}
if (exact_site && rc_e->strategy && strcmp(rc_e->strategy, "lsp_destructor") == 0 &&
!lsp_idx_insert_leaf(index, rc_e, "~", true, rc->main_gbuf, rc->project_name,
allow_tail)) {
lsp_exact_idx_complete = false;
}
}
}
}
/* The file's engine rows by caller, leaf and span (shared with pass_calls.c). */
cbm_pipeline_lsp_index_t lsp_index;
cbm_pipeline_lsp_index_build(&lsp_index,
result->calls.count > 0 ? &result->resolved_calls : NULL,
rc->main_gbuf, rc->project_name, allow_tail);
/* Field-owner rows, indexed on the first C member call that needs them. */
cbm_pipeline_lsp_field_index_t field_index = {0};
@@ -3354,7 +3833,8 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
bool field_index_ready = false;
cbm_spawn_file_begin(result->imports.items, result->imports.count);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result, &ws->site_memo,
evidence);
for (int c = 0; c < result->calls.count; c++) {
const CBMCall *call = &result->calls.items[c];
CBMCallEvidence fallback = {0};
@@ -3372,43 +3852,15 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
}
/* LSP-resolved calls take precedence over registry textual matching.
* Same helper + same CBM_LSP_CONFIDENCE_FLOOR as the sequential
* pipeline (pass_calls.c) — both paths must admit the same set of
* LSP overrides so a project doesn't get different attributions
* depending on whether parallel mode kicked in. Unique-tail
* fallbacks are JVM-only (see cbm_pipeline_lsp_allow_tail_match). */
* Same lookup as the sequential pipeline (pass_calls.c) — both paths
* must admit the same set of LSP overrides so a project doesn't get
* different attributions depending on whether parallel mode kicked
* in. Unique-tail fallbacks are JVM-only (see
* cbm_pipeline_lsp_allow_tail_match). */
cbm_resolution_t res = {0};
const CBMResolvedCall *lsp = NULL;
bool exact_key_built = true;
bool exact_key_ambiguous = false;
bool legacy_key_built = true;
_rc_t0 = extract_now_ns();
if (cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte)) {
lsp = lsp_idx_lookup(lsp_exact_idx, call, true, &exact_key_built, &exact_key_ambiguous);
}
bool exact_index_authoritative = lsp_exact_idx_complete && exact_key_built;
if (!lsp && !exact_index_authoritative) {
/* An incomplete exact index must fail closed: consult the
* authoritative matcher before a legacy row can win. */
atomic_fetch_add_explicit(&g_lsp_linear_fallback_rows,
(uint64_t)result->resolved_calls.count, memory_order_relaxed);
lsp = cbm_pipeline_find_lsp_resolution_in_graph(
&result->resolved_calls, call, allow_tail, rc->main_gbuf, rc->project_name);
}
if (!lsp && !call->requires_lsp_resolution && exact_index_authoritative &&
!exact_key_ambiguous) {
lsp = lsp_idx_lookup(lsp_legacy_idx, call, false, &legacy_key_built, NULL);
}
if (!lsp && (!lsp_legacy_idx_complete || !legacy_key_built || allow_tail ||
call->requires_lsp_resolution)) {
/* Fallback to the linear scan for edge cases the index may
* miss (e.g. callee_name that wasn't the registered short
* name). Keeps semantics identical. */
atomic_fetch_add_explicit(&g_lsp_linear_fallback_rows,
(uint64_t)result->resolved_calls.count, memory_order_relaxed);
lsp = cbm_pipeline_find_lsp_resolution_in_graph(
&result->resolved_calls, call, allow_tail, rc->main_gbuf, rc->project_name);
}
const CBMResolvedCall *lsp = cbm_pipeline_lsp_index_find(
&lsp_index, &result->resolved_calls, call, allow_tail, rc->main_gbuf, rc->project_name);
atomic_fetch_add_explicit(&rc->time_ns_rc_lsp_lookup, extract_now_ns() - _rc_t0,
memory_order_relaxed);
_rc_t0 = extract_now_ns();
@@ -3600,8 +4052,8 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
cbm_pipeline_get_nsmap()) ||
/* MUST match pass_calls.c exactly. */
(lang == CBM_LANG_PHP && cbm_suppress_weak_member_match(true, true, res.strategy) &&
cbm_pipeline_php_receiver_type_unindexed(&result->resolved_calls, call,
rc->registry)) ||
cbm_pipeline_lsp_index_php_receiver_unindexed(&lsp_index, &result->resolved_calls,
call, rc->registry)) ||
/* Same-module bound-receiver suppression (#1128) - see pass_calls.c;
* the language list is inside the helper, so the two cannot drift. */
cbm_suppress_same_module_bound_receiver(
@@ -3838,14 +4290,7 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
ws->calls_resolved++;
}
cbm_pipeline_site_bind_end(&site, ws->local_edge_buf);
if (lsp_exact_idx) {
cbm_ht_foreach(lsp_exact_idx, lsp_idx_free_key, NULL);
cbm_ht_free(lsp_exact_idx);
}
if (lsp_legacy_idx) {
cbm_ht_foreach(lsp_legacy_idx, lsp_idx_free_key, NULL);
cbm_ht_free(lsp_legacy_idx);
}
cbm_pipeline_lsp_index_free(&lsp_index);
cbm_spawn_file_end();
cbm_pipeline_external_import_index_free(&ext_imports);
cbm_pipeline_lsp_field_index_free(&field_index);
@@ -3863,7 +4308,8 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
bool field_index_ready =
cbm_pipeline_lsp_field_index_build(&result->resolved_calls, &field_index);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result, &ws->site_memo,
NULL);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
@@ -4021,11 +4467,20 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
* also agree: the same repo indexed in parallel and sequentially has to
* produce byte-identical edge properties. */
char uprops[CBM_SZ_512];
char esc_ref[CBM_SZ_256]; /* sliced source text: escape quotes/newlines */
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
if (scoped.verdict == CBM_SITE_PROVEN) {
/* a proven answer of the shared layer names its strategy
* (site_bind.h). MUST match pass_usages.c. */
cbm_pipeline_site_usage_props(uprops, sizeof(uprops), usage, CBM_SITE_PROVEN);
} else {
char esc_ref[CBM_SZ_256]; /* sliced source text: escape quotes/newlines */
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
}
const char *edge_type = precise_call_reference ? "CALL_REFERENCE" : "USAGE";
cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, edge_type, uprops);
if (scoped.verdict == CBM_SITE_POSSIBLE) {
cbm_pipeline_site_bind_usage_drawn(&site, usage, tgt);
}
ws->usages_resolved++;
}
cbm_pipeline_site_bind_end(&site, ws->local_edge_buf);
@@ -4919,6 +5374,8 @@ int cbm_parallel_resolve(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int total_semantic = 0;
int total_lsp_overrides = 0;
for (int i = 0; i < worker_count; i++) {
cbm_pipeline_site_memo_free(workers[i].site_memo);
workers[i].site_memo = NULL;
if (workers[i].local_edge_buf) {
cbm_gbuf_merge(ctx->gbuf, workers[i].local_edge_buf);
total_calls += workers[i].calls_resolved;
+387 -51
View File
@@ -12,6 +12,7 @@
*/
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/include_path.h"
#include "pipeline/pass_lsp_cross.h"
#include "discover/discover.h"
#include "helpers.h" /* cbm_fqn_module_source_lang */
@@ -124,12 +125,29 @@ static void pkg_entries_push(cbm_pkg_entries_t *e, char *pkg_name, char *entry_r
e->items[e->count].manifest_rel = NULL;
e->items[e->count].source_rel = NULL;
e->items[e->count].source_seq = 0;
e->items[e->count].npm_dependency = false;
e->count++;
}
/* A registry dependency a package.json declares, recorded by name only:
* entry_rel stays NULL, so it never becomes an import target. Its name is
* owned by the memory core (cbm_pkg_entries_free knows by npm_dependency). */
static void pkg_entries_push_npm_dependency(cbm_pkg_entries_t *e, const char *name) {
int before = e->count;
pkg_entries_push(e, NULL, NULL);
if (e->count > before) {
e->items[before].pkg_name = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, name);
e->items[before].npm_dependency = true;
}
}
void cbm_pkg_entries_free(cbm_pkg_entries_t *e) {
for (int i = 0; i < e->count; i++) {
free(e->items[i].pkg_name);
if (e->items[i].npm_dependency) {
cbm_free(CBM_MEM_CLASS_OTHER, e->items[i].pkg_name);
} else {
free(e->items[i].pkg_name);
}
free(e->items[i].entry_rel);
cbm_free(CBM_MEM_CLASS_OTHER, e->items[i].manifest_rel);
cbm_free(CBM_MEM_CLASS_OTHER, e->items[i].source_rel);
@@ -291,7 +309,44 @@ static const char *resolve_pkg_entry(yyjson_val *root) {
return "src/index.ts"; /* last resort default */
}
/* JS/TS: package.json — name + entry point resolution */
/* A dependency version that points into the tree (`workspace:*`,
* `file:../x`, `link:`, `portal:`) names a local package, not a registry one. */
static bool npm_version_is_local(const char *version) {
static const char *const local[] = {"workspace:", "file:", "link:", "portal:"};
for (size_t i = 0; i < sizeof(local) / sizeof(local[0]); i++) {
if (strncmp(version, local[i], strlen(local[i])) == 0) {
return true;
}
}
return false;
}
/* The registry dependencies of one package.json: every section a module
* import can resolve from. */
static void push_npm_dependencies(yyjson_val *root, cbm_pkg_entries_t *entries) {
static const char *const sections[] = {"dependencies", "devDependencies", "peerDependencies",
"optionalDependencies"};
for (size_t s = 0; s < sizeof(sections) / sizeof(sections[0]); s++) {
yyjson_val *deps = yyjson_obj_get(root, sections[s]);
if (!yyjson_is_obj(deps)) {
continue;
}
size_t idx;
size_t max;
yyjson_val *key;
yyjson_val *val;
yyjson_obj_foreach(deps, idx, max, key, val) {
const char *name = yyjson_get_str(key);
const char *version = yyjson_get_str(val);
if (name && name[0] && version && !npm_version_is_local(version)) {
pkg_entries_push_npm_dependency(entries, name);
}
}
}
}
/* JS/TS: package.json — name + entry point resolution, and the names of its
* registry dependencies (a manifest without a name still declares those). */
static void parse_package_json(const char *source, int source_len, const char *rel_path,
cbm_pkg_entries_t *entries) {
yyjson_doc *doc = yyjson_read(source, (size_t)source_len, 0);
@@ -305,17 +360,8 @@ static void parse_package_json(const char *source, int source_len, const char *r
}
yyjson_val *name_val = yyjson_obj_get(root, "name");
if (!yyjson_is_str(name_val)) {
yyjson_doc_free(doc);
return;
}
const char *name = yyjson_get_str(name_val);
if (!name || name[0] == '\0') {
yyjson_doc_free(doc);
return;
}
const char *entry = resolve_pkg_entry(root);
const char *name = yyjson_is_str(name_val) ? yyjson_get_str(name_val) : NULL;
const char *entry = name && name[0] ? resolve_pkg_entry(root) : NULL;
if (entry) {
char *dir = path_dirname(rel_path);
char *resolved = join_and_strip(dir, entry);
@@ -324,6 +370,7 @@ static void parse_package_json(const char *source, int source_len, const char *r
}
free(dir);
}
push_npm_dependencies(root, entries);
yyjson_doc_free(doc);
}
@@ -1142,6 +1189,56 @@ static int pkgmap_candidate_cmp(const void *lhs, const void *rhs) {
return strcmp(a->entry_rel, b->entry_rel);
}
/* The package map also records the names of the registry dependencies that
* package.json files declare, each under this prefix. No module specifier or
* package name starts with a control byte, so such a key never answers a
* module lookup; only pkgmap_declares_npm_dependency reads them. The key is
* owned by the memory core and every such entry shares one static value
* (pkgmap_free_entry tells them apart by the prefix). */
static const char PKGMAP_NPM_DEPENDENCY_KEY[] = "\x01npm-dependency:";
static char pkgmap_npm_dependency_value[] = "";
static bool pkgmap_is_npm_dependency_key(const char *key) {
return strncmp(key, PKGMAP_NPM_DEPENDENCY_KEY, sizeof(PKGMAP_NPM_DEPENDENCY_KEY) - SKIP_ONE) ==
0;
}
/* Record every declared registry dependency once. Returns how many. */
static int pkgmap_add_npm_dependencies(CBMHashTable *map, const cbm_pkg_entries_t *worker_entries,
int worker_count) {
int added = 0;
for (int w = 0; w < worker_count; w++) {
const cbm_pkg_entries_t *we = &worker_entries[w];
for (int i = 0; i < we->count; i++) {
const cbm_pkg_entry_t *entry = &we->items[i];
if (!entry->npm_dependency || !entry->pkg_name) {
continue;
}
size_t len = sizeof(PKGMAP_NPM_DEPENDENCY_KEY) + strlen(entry->pkg_name);
char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, len);
if (!key) {
continue;
}
snprintf(key, len, "%s%s", PKGMAP_NPM_DEPENDENCY_KEY, entry->pkg_name);
if (cbm_ht_has(map, key)) {
cbm_free(CBM_MEM_CLASS_OTHER, key);
continue;
}
cbm_ht_set(map, key, pkgmap_npm_dependency_value);
added++;
}
}
return added;
}
/* True when some package.json of the tree declares `package` as a registry
* dependency. */
static bool pkgmap_declares_npm_dependency(const CBMHashTable *pkgmap, const char *package) {
char key[PKGMAP_PATH_BUF];
int n = snprintf(key, sizeof(key), "%s%s", PKGMAP_NPM_DEPENDENCY_KEY, package);
return pkgmap && n > 0 && (size_t)n < sizeof(key) && cbm_ht_has(pkgmap, key);
}
CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_count,
const char *project_name) {
/* Count total entries */
@@ -1197,12 +1294,16 @@ CBMHashTable *cbm_pkgmap_build(cbm_pkg_entries_t *worker_entries, int worker_cou
merged++;
}
cbm_free(CBM_MEM_CLASS_OTHER, candidates);
int declared = pkgmap_add_npm_dependencies(map, worker_entries, worker_count);
if (merged == 0) {
if (merged == 0 && declared == 0) {
cbm_ht_free(map);
return NULL;
}
cbm_log_info("pkgmap.build", "entries", pkgmap_itoa(merged));
if (declared > 0) {
cbm_log_info("pkgmap.build", "npm_dependencies", pkgmap_itoa(declared));
}
return map;
}
@@ -1478,6 +1579,10 @@ CBMHashTable *cbm_pkgmap_build_from_repo(const char *repo_path, const cbm_file_i
static void pkgmap_free_entry(const char *key, void *value, void *userdata) {
(void)userdata;
if (pkgmap_is_npm_dependency_key(key)) {
cbm_free(CBM_MEM_CLASS_OTHER, (void *)key); /* the value is the shared static one */
return;
}
free((void *)key);
free(value);
}
@@ -2373,21 +2478,18 @@ static const cbm_gbuf_node_t *resolve_sibling_file(const cbm_pipeline_ctx_t *ctx
return found;
}
/* The File an explicit relative import (`./x`, `../x`) names exactly, for
* files whose File QN differs from the module QN Strategy 1 tries
* (`../styles/global.css`, `../layouts/Layout.astro`, #2558). Resolved in
* stack buffers by cbm_repo_rel_join, which refuses a path above the
* repository root. */
static const cbm_gbuf_node_t *resolve_relative_file(const cbm_pipeline_ctx_t *ctx,
const char *source_rel, const char *module_path,
bool php_only) {
/* The repository path an explicit relative import (`./x`, `../x`) names,
* joined into `out` in stack buffers by cbm_repo_rel_join, which refuses a
* path above the repository root. False when there is none. */
static bool relative_import_path(const char *source_rel, const char *module_path, char *out,
size_t cap) {
if (!source_rel || !module_path || !explicit_relative_path(module_path)) {
return NULL;
return false;
}
char dir[PKGMAP_PATH_BUF];
int dir_len = snprintf(dir, sizeof(dir), "%s", source_rel);
if (dir_len < 0 || (size_t)dir_len >= sizeof(dir)) {
return NULL;
return false;
}
char *slash = strrchr(dir, '/');
if (slash) {
@@ -2395,14 +2497,248 @@ static const cbm_gbuf_node_t *resolve_relative_file(const cbm_pipeline_ctx_t *ct
} else {
dir[0] = '\0';
}
return cbm_repo_rel_join(dir, module_path, out, cap);
}
/* The File an explicit relative import (`./x`, `../x`) names exactly, for
* files whose File QN differs from the module QN Strategy 1 tries
* (`../styles/global.css`, `../layouts/Layout.astro`, #2558). */
static const cbm_gbuf_node_t *resolve_relative_file(const cbm_pipeline_ctx_t *ctx,
const char *source_rel, const char *module_path,
bool php_only) {
char path[PKGMAP_PATH_BUF];
if (!cbm_repo_rel_join(dir, module_path, path, sizeof(path))) {
if (!relative_import_path(source_rel, module_path, path, sizeof(path))) {
return NULL;
}
const cbm_gbuf_node_t *file = cbm_pipeline_file_node(ctx->gbuf, ctx->project_name, path);
return file && (!php_only || node_in_php_file(file)) ? file : NULL;
}
/* Python/TS from-import of a member: module_path is often "pkg.mod.symbol"
* while module resolution lands on the Module node "pkg.mod". Prefer the
* member Function/Class when it exists — required for `from M import f as g`
* so CALLS can import_map to f (local_name g ≠ f). */
static const cbm_gbuf_node_t *prefer_import_member(const cbm_pipeline_ctx_t *ctx,
const CBMImport *imp,
const cbm_gbuf_node_t *target, bool php_only) {
if (!target->label ||
(strcmp(target->label, "Module") != 0 && strcmp(target->label, "File") != 0)) {
return target;
}
char symbuf[256];
const char *sym = import_candidate_symbol(imp->module_path, symbuf, sizeof(symbuf));
if (!sym || !sym[0] || strcmp(sym, "*") == 0) {
return target;
}
const char *mod_tail =
import_last_segment(target->qualified_name ? target->qualified_name : "");
if (mod_tail && strcmp(mod_tail, sym) == 0) {
return target;
}
char member_qn[CBM_SZ_512];
snprintf(member_qn, sizeof(member_qn), "%s.%s", target->qualified_name, sym);
const cbm_gbuf_node_t *member = cbm_gbuf_find_by_qn(ctx->gbuf, member_qn);
if (member && (!php_only || node_in_php_file(member)) &&
import_targetable_label(member->label) && strcmp(member->label, "Module") != 0 &&
strcmp(member->label, "File") != 0) {
return member;
}
return target;
}
/* ── ECMAScript import specifiers ─────────────────────────────────── */
/* Importing-file languages whose imports are ECMAScript module specifiers:
* the script languages and the markup hosts that embed their scripts. */
static bool es_module_importer(CBMLanguage lang) {
switch (lang) {
case CBM_LANG_JAVASCRIPT:
case CBM_LANG_TYPESCRIPT:
case CBM_LANG_TSX:
case CBM_LANG_ARKTS:
case CBM_LANG_HTML:
case CBM_LANG_VUE:
case CBM_LANG_SVELTE:
case CBM_LANG_ASTRO:
return true;
default:
return false;
}
}
/* Node's built-in modules and their documented sub-paths, which a bare
* specifier names without the `node:` scheme. */
static bool node_builtin_module(const char *spec) {
static const char builtins[] =
"|assert|assert/strict|async_hooks|buffer|child_process|cluster|console|constants|crypto"
"|dgram|diagnostics_channel|dns|dns/promises|domain|events|fs|fs/promises|http|http2"
"|https|inspector|inspector/promises|module|net|os|path|path/posix|path/win32|perf_hooks"
"|process|punycode|querystring|readline|readline/promises|repl|stream|stream/consumers"
"|stream/promises|stream/web|string_decoder|sys|timers|timers/promises|tls|trace_events"
"|tty|url|util|util/types|v8|vm|wasi|worker_threads|zlib|";
char key[CBM_SZ_64];
int n = snprintf(key, sizeof(key), "|%s|", spec);
return n > 0 && (size_t)n < sizeof(key) && strstr(builtins, key) != NULL;
}
/* `node:fs`, `npm:x`, `jsr:@std/path`, `https://...`: a URL scheme names no
* file of the tree. Two characters at least, so a drive letter never counts. */
static bool es_specifier_has_scheme(const char *spec) {
if (!isalpha((unsigned char)spec[0])) {
return false;
}
size_t i = SKIP_ONE;
while (isalnum((unsigned char)spec[i]) || spec[i] == '+' || spec[i] == '-' || spec[i] == '.') {
i++;
}
return spec[i] == ':' && i >= PAIR_LEN;
}
/* The package a bare specifier names, `@scope/name` or `name`, without its
* sub-path. False when the specifier has no package shape. */
static bool es_specifier_package(const char *spec, char *out, size_t cap) {
if (spec[0] == '\0' || spec[0] == '/' || spec[0] == '.' || spec[0] == '#') {
return false;
}
const char *end = strchr(spec, '/');
if (spec[0] == '@') {
if (!end || end[SKIP_ONE] == '\0') {
return false;
}
end = strchr(end + SKIP_ONE, '/');
}
size_t len = end ? (size_t)(end - spec) : strlen(spec);
if (len == 0 || len >= cap) {
return false;
}
memcpy(out, spec, len);
out[len] = '\0';
return true;
}
typedef enum {
ES_SPECIFIER_OTHER = 0, /* a bare specifier without evidence either way */
ES_SPECIFIER_TREE_PATH, /* one file of the tree */
ES_SPECIFIER_EXTERNAL, /* a module outside the tree */
} es_specifier_t;
/* A bundler query on the basename (`./worker.ts?worker`, `~/a.svg?raw`) is
* no part of the path; a `?` in a folder name is. */
static void cut_basename_query(char *path) {
char *slash = strrchr(path, '/');
char *query = strchr(slash ? slash + SKIP_ONE : path, '?');
if (query) {
*query = '\0';
}
}
/* What an ES import specifier names. TREE_PATH: one file of the tree, by an
* explicit relative path or a tsconfig/jsconfig alias (paths or baseUrl),
* read as cbm_pipeline_resolve_module reads them; `path` receives that
* repository path (empty when it has none). EXTERNAL: a module outside the
* tree, by a URL scheme (checked before the aliases, whose baseUrl rule would
* read `node:fs/promises` as a path), a Node builtin or a registry dependency
* some package.json declares, unless a package of the tree has that name.
* OTHER: a bare specifier without such evidence (a bundler's module
* directories can still make it a project path). */
static es_specifier_t es_specifier_kind(const cbm_pipeline_ctx_t *ctx, const char *source_rel,
const char *spec, char *path, size_t cap) {
path[0] = '\0';
if (explicit_relative_path(spec) || strcmp(spec, ".") == 0 || strcmp(spec, "..") == 0) {
if (!relative_import_path(source_rel, spec, path, cap)) {
path[0] = '\0';
}
cut_basename_query(path);
return ES_SPECIFIER_TREE_PATH;
}
if (es_specifier_has_scheme(spec)) {
return ES_SPECIFIER_EXTERNAL;
}
if (ctx->path_aliases && source_rel) {
const cbm_path_alias_map_t *amap =
cbm_path_alias_find_for_file(ctx->path_aliases, source_rel);
if (amap && cbm_path_alias_resolve_into(amap, spec, path, cap)) {
cut_basename_query(path);
return ES_SPECIFIER_TREE_PATH;
}
path[0] = '\0';
}
char package[PKGMAP_PATH_BUF];
if (!es_specifier_package(spec, package, sizeof(package))) {
return ES_SPECIFIER_OTHER;
}
const CBMHashTable *pkgmap = cbm_pipeline_get_pkgmap();
if (pkgmap && cbm_ht_has(pkgmap, package)) {
return ES_SPECIFIER_OTHER; /* a package of the tree */
}
if (node_builtin_module(spec) || pkgmap_declares_npm_dependency(pkgmap, package)) {
return ES_SPECIFIER_EXTERNAL;
}
return ES_SPECIFIER_OTHER;
}
/* The Module a module loader finds for `path`: path plus a script
* extension, then path/index plus one. Looked up by the Module node's name,
* which is its file path, so a directory whose QN segment is not its name
* (`.vitepress` keeps its dot in the path, not in the Module QN) resolves
* too. */
static const cbm_gbuf_node_t *es_module_for_path(const cbm_pipeline_ctx_t *ctx, const char *path) {
static const char suffixes[] = ".ts|.tsx|.mts|.cts|.js|.jsx|.mjs|.cjs|/index.ts|/index.tsx|/"
"index.js|/index.jsx|/index.mjs";
char candidate[PKGMAP_PATH_BUF];
for (const char *s = suffixes; *s;) {
const char *bar = strchr(s, '|');
int slen = bar ? (int)(bar - s) : (int)strlen(s);
int w = snprintf(candidate, sizeof(candidate), "%s%.*s", path, slen, s);
s = bar ? bar + SKIP_ONE : s + slen;
if (w <= 0 || (size_t)w >= sizeof(candidate)) {
continue;
}
const cbm_gbuf_node_t **hits = NULL;
int count = 0;
if (cbm_gbuf_find_by_name(ctx->gbuf, candidate, &hits, &count) != 0 || !hits) {
continue;
}
for (int h = 0; h < count; h++) {
const cbm_gbuf_node_t *n = hits[h];
if (n && n->label && strcmp(n->label, "Module") == 0 && n->file_path &&
strcmp(n->file_path, candidate) == 0) {
return n;
}
}
}
return NULL;
}
/* The node of the one file an ES tree-path specifier names at `path`, once
* Strategy 1 found none: for an explicit relative path, the module of the
* file at exactly that path (`./App.vue`, whose Module QN drops the
* extension Strategy 1 keeps) or that file's File node (Strategy 1c); then,
* for any tree path, the module a loader finds for it by extension or index
* file. Nothing else. */
static const cbm_gbuf_node_t *resolve_es_tree_file(const cbm_pipeline_ctx_t *ctx,
const char *source_rel,
const char *source_file_qn, const CBMImport *imp,
const char *path) {
if (!path[0]) {
return NULL;
}
if (explicit_relative_path(imp->module_path)) {
const cbm_gbuf_node_t *sibling =
resolve_sibling_file(ctx, source_rel, source_file_qn, imp->module_path, false);
if (sibling && sibling->file_path && strcmp(sibling->file_path, path) == 0) {
return sibling;
}
const cbm_gbuf_node_t *file =
resolve_relative_file(ctx, source_rel, imp->module_path, false);
if (file) {
return file;
}
}
const cbm_gbuf_node_t *module = es_module_for_path(ctx, path);
return module ? prefer_import_member(ctx, imp, module, false) : NULL;
}
/* ── PHP PSR-4 class imports (#1186) ──────────────────────────────── */
typedef enum {
@@ -3255,6 +3591,13 @@ static const cbm_gbuf_node_t *resolve_import_strategies(
const cbm_pipeline_ctx_t *ctx, const char *source_rel, const char *source_file_qn,
const CBMImport *imp, CBMHashTable *namespace_map, CBMLanguage src_lang, bool php_only,
CBMLanguage language, const cbm_scala_index_t *scala_index) {
/* Strategy 0: a language whose imports name files by path (include_path.h):
* the path rule decides the target. */
const cbm_gbuf_node_t *by_path = NULL;
if (cbm_include_path_decides(ctx, source_rel, src_lang, imp, &by_path)) {
return by_path;
}
/* Strategy 1: module-path resolution → existing node (Python/TS/Go).
* No label filter here: directory-module languages (Go/Java packages)
* legitimately resolve straight to a Folder node -- that's the intended,
@@ -3266,32 +3609,7 @@ static const cbm_gbuf_node_t *resolve_import_strategies(
const cbm_gbuf_node_t *target = target_qn ? cbm_gbuf_find_by_qn(ctx->gbuf, target_qn) : NULL;
free(target_qn);
if (target && (!php_only || node_in_php_file(target))) {
/* Python/TS from-import of a member: module_path is often
* "pkg.mod.symbol" while resolve_module lands on the Module node
* "pkg.mod". Prefer the member Function/Class when it exists —
* required for `from M import f as g` so CALLS can import_map to f
* (local_name g ≠ f). */
if (target->label &&
(strcmp(target->label, "Module") == 0 || strcmp(target->label, "File") == 0)) {
char symbuf[256];
const char *sym = import_candidate_symbol(imp->module_path, symbuf, sizeof(symbuf));
if (sym && sym[0] && strcmp(sym, "*") != 0) {
const char *mod_tail =
import_last_segment(target->qualified_name ? target->qualified_name : "");
if (!mod_tail || strcmp(mod_tail, sym) != 0) {
char member_qn[CBM_SZ_512];
snprintf(member_qn, sizeof(member_qn), "%s.%s", target->qualified_name, sym);
const cbm_gbuf_node_t *member = cbm_gbuf_find_by_qn(ctx->gbuf, member_qn);
if (member && (!php_only || node_in_php_file(member)) &&
import_targetable_label(member->label) &&
strcmp(member->label, "Module") != 0 &&
strcmp(member->label, "File") != 0) {
return member;
}
}
}
}
return target;
return prefer_import_member(ctx, imp, target, php_only);
}
/* Rust: a `use` path names an item of one crate, never a same-named
@@ -3308,6 +3626,24 @@ static const cbm_gbuf_node_t *resolve_import_strategies(
}
}
/* ECMAScript: a specifier that names one file of the tree, or a module
* outside it, has one right target, which Strategy 1 has just missed. The
* name-guess fallbacks below would bind it to an unrelated definition
* (`./App.vue` absent -> a test's App, `ws` -> the ws.ts beside the
* importer, `node:assert/strict` -> a spec's assert), so such an import
* stays unbound, as a Go import does (#1934). */
if (!php_only && es_module_importer(src_lang)) {
char path[CBM_PATH_ALIAS_RESULT_MAX];
switch (es_specifier_kind(ctx, source_rel, imp->module_path, path, sizeof(path))) {
case ES_SPECIFIER_EXTERNAL:
return NULL;
case ES_SPECIFIER_TREE_PATH:
return resolve_es_tree_file(ctx, source_rel, source_file_qn, imp, path);
case ES_SPECIFIER_OTHER:
break;
}
}
/* Name-guess fallbacks below (Strategy 1b sibling-file, Strategy 3
* symbol-name) are gated per importing-file language — see
* cbm_import_symbol_fallback_allowed (#1934). */
+337 -17
View File
@@ -69,6 +69,9 @@
/* Candidate paths a target lookup scanned (complexity guard counter). */
_Atomic uint64_t g_sh_candidates = 0;
/* Targets, prerequisites and target-prerequisite pairs the Make dependency
* drawing looked at (complexity guard counter). */
_Atomic uint64_t g_sh_make_pairs = 0;
enum {
SH_GROW_MIN = 16,
@@ -384,12 +387,32 @@ typedef struct {
const char *default_of; /* pass-arena, build: JSON array of the ${X:-d} defaults naming `ext` */
} sh_hit_t;
/* A prerequisite a makefile rule states as one plain word. */
typedef struct {
const char *name; /* pass-arena */
int line;
bool order_only; /* after the rule's `|` */
} sh_mkpre_t;
/* A makefile rule with plain prerequisites (sh_make_deps). */
typedef struct {
const char *file; /* pass-arena: the makefile */
const char **targets; /* pass-arena: the rule's targets, as written */
int ntargets;
sh_mkpre_t *pres; /* pass-arena */
int npres;
uint32_t pos; /* the rule's source byte: the order make reads them in */
} sh_mkrule_t;
typedef struct {
sh_hit_t *items;
int count;
int cap;
CBMArena arena;
CBMHashTable *declarers; /* files running a container build: path -> path */
sh_mkrule_t *mkrules;
int nmkrules;
int cap_mkrules;
} sh_hits_t;
typedef struct {
@@ -3037,6 +3060,9 @@ struct mk {
int cap_lines;
mk_include_fn on_include; /* NULL: includes are not followed */
void *ud;
sh_hits_t *deps; /* NULL: the rules' prerequisites are not recorded */
const char *rel; /* with `deps`: the makefile */
int in_error; /* depth of the regions the grammar could not parse */
};
static const char MK_UNKNOWN[] = "${__cbm_unknown}";
@@ -3292,6 +3318,91 @@ static int mk_cmp_line(const void *a, const void *b) {
return (x > y) - (x < y);
}
/* A prerequisite make reads as written: one word that is no pattern (%), no
* glob and holds no variable. */
static bool mk_plain_word(TSNode w, const char *src) {
if (strcmp(ts_node_type(w), "word") != 0) {
return false;
}
uint32_t b = ts_node_start_byte(w);
uint32_t e = ts_node_end_byte(w);
for (uint32_t i = b; i < e; i++) {
if (src[i] == '\0' || strchr("%*?[$=", src[i])) {
return false;
}
}
return e > b;
}
static bool mk_is_prerequisites(TSNode n) {
return ts_node_is_named(n) && strcmp(ts_node_type(n), "prerequisites") == 0;
}
/* The plain prerequisites a rule states, with its targets: what sh_make_deps
* matches against the makefile's rule nodes. Read from the rule's
* `prerequisites` only, so a static pattern rule (`a.o: %.o: %.c`) yields
* none. A target-specific variable the grammar took for a rule
* (`t: override X = v`) shows as an ERROR in the rule line: none either. */
static void mk_rule_deps(mk_t *m, TSNode rule) {
sh_hits_t *h = m->deps;
TSNode targets = rule;
uint32_t nc = ts_node_child_count(rule);
uint32_t nt = 0;
int np = 0;
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_child(rule, i);
if (strcmp(ts_node_type(c), "ERROR") == 0 ||
(mk_is_prerequisites(c) && ts_node_has_error(c))) {
return;
}
if (nt == 0 && strcmp(ts_node_type(c), "targets") == 0) {
targets = c;
nt = ts_node_named_child_count(c);
}
for (uint32_t k = 0; mk_is_prerequisites(c) && k < ts_node_named_child_count(c); k++) {
np += mk_plain_word(ts_node_named_child(c, k), m->src);
}
}
if (nt == 0 || np == 0 ||
!sh_grow((void **)&h->mkrules, &h->cap_mkrules, h->nmkrules, sizeof(*h->mkrules))) {
return;
}
sh_mkrule_t r = {.file = cbm_arena_strdup(&h->arena, m->rel),
.targets = cbm_arena_alloc(&h->arena, nt * sizeof(*r.targets)),
.pres = cbm_arena_alloc(&h->arena, (size_t)np * sizeof(*r.pres)),
.pos = ts_node_start_byte(rule)};
if (!r.file || !r.targets || !r.pres) {
return;
}
for (uint32_t i = 0; i < nt; i++) {
TSNode t = ts_node_named_child(targets, i);
uint32_t tb = ts_node_start_byte(t);
const char *name = cbm_arena_strndup(&h->arena, m->src + tb, ts_node_end_byte(t) - tb);
if (name && name[0]) {
r.targets[r.ntargets++] = name;
}
}
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_child(rule, i);
bool order_only = sh_eq(ts_node_field_name_for_child(rule, i), "order_only");
for (uint32_t k = 0; mk_is_prerequisites(c) && k < ts_node_named_child_count(c); k++) {
TSNode w = ts_node_named_child(c, k);
uint32_t wb = ts_node_start_byte(w);
const char *name =
mk_plain_word(w, m->src)
? cbm_arena_strndup(&h->arena, m->src + wb, ts_node_end_byte(w) - wb)
: NULL;
if (name && r.npres < np) {
r.pres[r.npres++] =
(sh_mkpre_t){name, (int)ts_node_start_point(w).row + SKIP_ONE, order_only};
}
}
}
if (r.ntargets > 0 && r.npres > 0) {
h->mkrules[h->nmkrules++] = r;
}
}
static void mk_collect(mk_t *m, TSNode n, bool cond);
static void mk_collect_error(mk_t *m, TSNode err, bool cond);
@@ -3302,6 +3413,9 @@ static void mk_collect_one(mk_t *m, TSNode c, bool cond) {
} else if (strcmp(t, "recipe_line") == 0) {
mk_split_lines(m, c);
} else if (strcmp(t, "rule") == 0 || strcmp(t, "recipe") == 0) {
if (m->deps && m->in_error == 0 && strcmp(t, "rule") == 0) {
mk_rule_deps(m, c);
}
mk_collect(m, c, cond);
} else if (strcmp(t, "ERROR") == 0) {
mk_collect_error(m, c, cond);
@@ -3367,6 +3481,7 @@ static void mk_collect_error(mk_t *m, TSNode err, bool cond) {
uint32_t scan = ts_node_start_byte(err);
uint32_t end = ts_node_end_byte(err);
int depth = 0;
m->in_error++;
for (uint32_t i = 0; i < ts_node_named_child_count(err); i++) {
TSNode c = ts_node_named_child(err, i);
uint32_t cb = ts_node_start_byte(c);
@@ -3379,8 +3494,16 @@ static void mk_collect_error(mk_t *m, TSNode err, bool cond) {
depth = depth < 0 ? 0 : depth;
scan = le + SKIP_ONE;
}
/* The grammar resumed before a rule that stands at the start of its
* line: its prerequisites are read as written. Anything else in the
* region (an indented rule, one nested in another node) is not. */
if (m->deps && m->in_error == SKIP_ONE && strcmp(ts_node_type(c), "rule") == 0 &&
ts_node_start_point(c).column == 0) {
mk_rule_deps(m, c);
}
mk_collect_one(m, c, cond || depth > 0);
}
m->in_error--;
}
static void sh_makefile(sh_pass_t *p, const char *rel, const char *src, size_t len) {
@@ -3398,7 +3521,9 @@ static void sh_makefile(sh_pass_t *p, const char *rel, const char *src, size_t l
.src = src,
.vars = cbm_ht_create(0),
.makefile = strcmp(base, "Makefile") == 0 || strcmp(base, "GNUmakefile") == 0 ||
strcmp(base, "makefile") == 0};
strcmp(base, "makefile") == 0,
.deps = p->hits,
.rel = rel};
if (m.vars) {
mk_collect(&m, ts_tree_root_node(tree), false);
}
@@ -3537,6 +3662,168 @@ static const char *mk_rule_key(CBMArena *a, const char *file, const char *name)
return cbm_arena_sprintf(a, "%s\x1f%s", file, name);
}
/* Into `rules` (file \x1f name -> node): the rule nodes of the files in
* `want`, the first rule of a name in a file. */
static void mk_rule_nodes(cbm_pipeline_ctx_t *ctx, CBMArena *a, CBMHashTable *want,
CBMHashTable *rules) {
const cbm_gbuf_node_t **nodes = NULL;
int count = 0;
if (cbm_ht_count(want) == 0 ||
cbm_gbuf_find_by_label(ctx->gbuf, "Function", &nodes, &count) != 0) {
return;
}
for (int i = 0; i < count; i++) {
const char *fp = nodes[i]->file_path;
if (!fp || !nodes[i]->name || !cbm_ht_get(want, fp)) {
continue;
}
const char *key = mk_rule_key(a, fp, nodes[i]->name);
const cbm_gbuf_node_t *old = key ? cbm_ht_get(rules, key) : NULL;
if (key && (!old || nodes[i]->start_line < old->start_line)) {
cbm_ht_set(rules, key, (void *)nodes[i]);
}
}
}
static int mk_cmp_rule(const void *a, const void *b) {
const sh_mkrule_t *x = a;
const sh_mkrule_t *y = b;
int c = strcmp(x->file, y->file);
return c ? c : (x->pos > y->pos) - (x->pos < y->pos);
}
/* One prerequisite edge to draw (sh_make_deps). */
typedef struct {
int64_t src;
int64_t dep;
int line;
bool order_only;
} sh_mkedge_t;
/* True the first time rule `rule` names node `id` in role `role` (a target,
* a normal prerequisite, an order-only one); a repeat on the same rule line
* is skipped, so the line costs its words plus its distinct pairs, not the
* product of its repeats. Sets *failed when the key cannot be kept. */
static bool mk_first_in_rule(CBMArena *a, CBMHashTable *once, bool *failed, int rule, char role,
int64_t id) {
const char *key = cbm_arena_sprintf(a, "%d%c%lld", rule, role, (long long)id);
if (!key) {
*failed = true;
return false;
}
if (cbm_ht_get(once, key)) {
return false;
}
cbm_ht_set(once, key, (void *)key);
return true;
}
/* A rule's prerequisite that names a rule of the same makefile: DEPENDS_ON
* {via: prerequisite, line} from each of the rule's targets to that rule's
* node -- once per pair, at the first line stating it, as make merges the
* prerequisites of a target's rules; an order-only one (after `|`) says so.
* A pair listed both ways is a normal prerequisite to make, at the first
* line listing it as one. The prerequisite is a plain word (mk_rule_deps):
* one with a variable, a pattern or a glob, one naming a file or a rule of
* another makefile, and a target naming itself draw nothing. */
static void sh_make_deps(cbm_pipeline_ctx_t *ctx, sh_hits_t *h) {
CBMArena a;
cbm_arena_init(&a);
CBMHashTable *want = cbm_ht_create(0);
CBMHashTable *rules = cbm_ht_create(0);
CBMHashTable *seen = cbm_ht_create(0); /* "<source id>><target id>" -> index in edges + 1 */
CBMHashTable *once = cbm_ht_create(0); /* a rule's own repeats (mk_first_in_rule) */
sh_mkedge_t *edges = NULL;
int nedges = 0;
int cap_edges = 0;
/* What cannot be kept draws nothing: half the statements of a pair could
* leave it order-only, or at a later line, than the makefile says. */
bool failed = !want || !rules || !seen || !once;
for (int i = 0; !failed && i < h->nmkrules; i++) {
cbm_ht_set(want, h->mkrules[i].file, (void *)h->mkrules[i].file);
}
if (!failed) {
mk_rule_nodes(ctx, &a, want, rules);
qsort(h->mkrules, (size_t)h->nmkrules, sizeof(*h->mkrules), mk_cmp_rule);
}
for (int i = 0; !failed && i < h->nmkrules; i++) {
const sh_mkrule_t *r = &h->mkrules[i];
if (r->ntargets <= 0 || r->npres <= 0) {
continue;
}
const cbm_gbuf_node_t **srcs = cbm_arena_alloc(&a, (size_t)r->ntargets * sizeof(*srcs));
int nsrc = 0;
failed = !srcs;
for (int t = 0; !failed && t < r->ntargets; t++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
const char *key = mk_rule_key(&a, r->file, r->targets[t]);
const cbm_gbuf_node_t *src = key ? cbm_ht_get(rules, key) : NULL;
failed = !key;
if (src && mk_first_in_rule(&a, once, &failed, i, 't', src->id)) {
srcs[nsrc++] = src;
}
}
for (int k = 0; !failed && nsrc > 0 && k < r->npres; k++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
const char *key = mk_rule_key(&a, r->file, r->pres[k].name);
const cbm_gbuf_node_t *dep = key ? cbm_ht_get(rules, key) : NULL;
failed = !key;
if (!dep || !mk_first_in_rule(&a, once, &failed, i, r->pres[k].order_only ? 'o' : 'p',
dep->id)) {
continue;
}
for (int t = 0; !failed && t < nsrc; t++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
if (srcs[t] == dep) {
continue;
}
const char *pair =
cbm_arena_sprintf(&a, "%lld>%lld", (long long)srcs[t]->id, (long long)dep->id);
if (!pair) {
failed = true;
break;
}
intptr_t at = (intptr_t)cbm_ht_get(seen, pair);
if (at > 0) {
sh_mkedge_t *e = &edges[at - SKIP_ONE];
if (e->order_only && !r->pres[k].order_only) {
e->order_only = false;
e->line = r->pres[k].line;
}
continue;
}
if (!sh_grow((void **)&edges, &cap_edges, nedges, sizeof(*edges))) {
failed = true;
break;
}
edges[nedges++] =
(sh_mkedge_t){srcs[t]->id, dep->id, r->pres[k].line, r->pres[k].order_only};
cbm_ht_set(seen, pair, (void *)(intptr_t)nedges);
}
}
}
for (int i = 0; !failed && i < nedges; i++) {
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"prerequisite\",\"line\":%d%s}", edges[i].line,
edges[i].order_only ? ",\"order_only\":true" : "");
cbm_gbuf_insert_edge(ctx->gbuf, edges[i].src, edges[i].dep, "DEPENDS_ON", props);
}
cbm_free(CBM_MEM_CLASS_OTHER, edges);
if (want) {
cbm_ht_free(want);
}
if (rules) {
cbm_ht_free(rules);
}
if (seen) {
cbm_ht_free(seen);
}
if (once) {
cbm_ht_free(once);
}
cbm_arena_destroy(&a);
}
/* Each make hit's target: the rule node of that name in the makefile, else
* in the files it includes, in reading order (the first rule of a file).
* Read here, when linking, so an unchanged makefile is read too. */
@@ -3570,21 +3857,8 @@ static void sh_make_resolve(sh_pass_t *p, cbm_pipeline_ctx_t *ctx, sh_hits_t *h)
}
cbm_ht_set(closures, x->path, cl);
}
const cbm_gbuf_node_t **nodes = NULL;
int count = 0;
if (rules && want && cbm_ht_count(want) > 0 &&
cbm_gbuf_find_by_label(ctx->gbuf, "Function", &nodes, &count) == 0) {
for (int i = 0; i < count; i++) {
const char *fp = nodes[i]->file_path;
if (!fp || !nodes[i]->name || !cbm_ht_get(want, fp)) {
continue;
}
const char *key = mk_rule_key(&a, fp, nodes[i]->name);
const cbm_gbuf_node_t *old = key ? cbm_ht_get(rules, key) : NULL;
if (key && (!old || nodes[i]->start_line < old->start_line)) {
cbm_ht_set(rules, key, (void *)nodes[i]);
}
}
if (rules && want) {
mk_rule_nodes(ctx, &a, want, rules);
}
for (int i = 0; rules && closures && i < h->count; i++) {
sh_hit_t *x = &h->items[i];
@@ -4020,11 +4294,53 @@ static void sh_ci_cmd(const cbm_ci_cmd_t *cmd, void *ud) {
sh_state_free(&s);
}
typedef struct {
sh_pass_t *p;
const char *rel;
CBMArena *a;
CBMHashTable *seen; /* target paths drawn */
} sh_ci_use_t;
/* A local `uses:` of a workflow or composite action: REFERENCES_FILE {via:
* uses, line} from its File to the file it names -- a job's reusable
* workflow, a step's action by its action.yml or action.yaml (the one the
* directory holds; with both, or neither, there is no edge) -- once per
* file, at the first use. */
static void sh_ci_use(const cbm_ci_use_t *use, void *ud) {
static const char *const NAMES[PAIR_LEN] = {"action.yml", "action.yaml"};
sh_ci_use_t *x = ud;
const sh_index_t *ix = x->p->ix;
const char *target = use->job ? use->path : NULL;
for (int k = 0; !use->job && k < PAIR_LEN; k++) {
const char *cand =
cbm_arena_sprintf(x->a, "%s%s%s", use->path, use->path[0] ? "/" : "", NAMES[k]);
if (cand && cbm_ht_get(ix->file_ids, cand)) {
if (target) {
return; /* both spellings: which one GitHub reads is not ours to say */
}
target = cand;
}
}
int64_t src = (int64_t)(intptr_t)cbm_ht_get(ix->file_ids, x->rel);
int64_t tgt = target ? (int64_t)(intptr_t)cbm_ht_get(ix->file_ids, target) : 0;
if (src <= 0 || tgt <= 0 || src == tgt || !x->seen || cbm_ht_get(x->seen, target)) {
return;
}
cbm_ht_set(x->seen, target, (void *)target);
char props[CBM_SZ_64];
snprintf(props, sizeof(props), "{\"via\":\"uses\",\"line\":%d}", use->line);
cbm_gbuf_insert_edge(ix->ctx->gbuf, src, tgt, "REFERENCES_FILE", props);
}
static void sh_ci_file(sh_pass_t *p, const char *rel, const char *src, size_t len) {
CBMArena a;
cbm_arena_init(&a);
sh_ci_t x = {.p = p, .rel = rel, .a = &a};
cbm_ci_commands(&a, rel, src, len, sh_ci_cmd, &x);
sh_ci_use_t u = {.p = p, .rel = rel, .a = &a, .seen = cbm_ht_create(0)};
cbm_ci_commands(&a, rel, src, len, sh_ci_cmd, &x, sh_ci_use, &u);
if (u.seen) {
cbm_ht_free(u.seen);
}
cbm_arena_destroy(&a);
}
@@ -4151,6 +4467,10 @@ void cbm_pipeline_pass_shell(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
if (hits.count > 0 && p.ix_ok && p.parser) {
sh_make_resolve(&p, ctx, &hits);
}
if (hits.nmkrules > 0) {
sh_make_deps(ctx, &hits);
}
cbm_free(CBM_MEM_CLASS_OTHER, hits.mkrules);
int edges = hits.count > 0 ? sh_link(ctx, &hits) : 0;
if (hits.declarers) {
sh_mark_declarers(ctx, hits.declarers);
+101 -5
View File
@@ -954,7 +954,18 @@ static TSNode tf_root_body(TSNode root) {
* when that declares none of its names, of the nearest ancestor directory's
* module that does (applied by a -var-file the repository does not state:
* the edge says `inferred`): each assignment to a declared variable
* OVERRIDEs {via: tfvars, line} its `variable` block. */
* OVERRIDEs {via: tfvars, line} its `variable` block.
*
* A file function whose path begins at the module's own directory --
* file("${path.module}/x"), templatefile(...), filebase64(...) and the hash
* functions (filemd5, filesha1, filesha256, filesha512, filebase64sha256,
* filebase64sha512) -- reads a repository file: REFERENCES_FILE {via: <the
* function>, line} from the top-level block holding the call to that file's
* File node, once per block and file at the first call. The rest of the path
* must be literal. A path written without ${path.module} is relative to the
* directory Terraform is run in, which the module does not state: no edge;
* neither for path.root / path.cwd, another interpolation, or a file the
* index does not hold. */
typedef struct {
char *file; /* the referencing file */
@@ -974,6 +985,15 @@ typedef struct {
int line;
} tf_call_t;
/* A repository file a file function reads. */
typedef struct {
char *file; /* the calling file */
char *src; /* the holding top-level block's definition name */
char *path; /* the file it names, from the repository root */
const char *fn; /* static: the function */
int line;
} tf_fref_t;
typedef struct {
cbm_pipeline_ctx_t *ctx;
CBMArena *arena;
@@ -985,6 +1005,9 @@ typedef struct {
tf_call_t *mcalls;
int call_n;
int call_cap;
tf_fref_t *frefs;
int fref_n;
int fref_cap;
const char *dir; /* the module's directory */
const char *src; /* the file's text */
const char *file; /* its repository path (arena) */
@@ -1126,7 +1149,45 @@ static void tf_traversal(tf_mod_t *m, const char *src_block, TSNode v) {
}
}
/* Every traversal under `n` (iterative: deep expressions). */
static bool tf_text_is(const char *src, TSNode n, const char *word);
/* A call of a file function inside block `src_block`: the file its first
* argument names when that begins at ${path.module} (tf_string's anchor) and
* is literal otherwise. */
static void tf_file_call(tf_mod_t *m, const char *src_block, TSNode call) {
static const char *const FNS[] = {
"file", "templatefile", "filebase64", "filemd5", "filesha1",
"filesha256", "filesha512", "filebase64sha256", "filebase64sha512", NULL};
TSNode fn = ts_node_named_child(call, 0);
TSNode args = {0};
for (uint32_t i = 0; i < ts_node_named_child_count(call); i++) {
if (tf_type(ts_node_named_child(call, i), "function_arguments")) {
args = ts_node_named_child(call, i);
}
}
const char *name = NULL;
for (int k = 0; !ts_node_is_null(fn) && FNS[k] && !name; k++) {
name = tf_text_is(m->src, fn, FNS[k]) ? FNS[k] : NULL;
}
if (!name || ts_node_is_null(args) || ts_node_named_child_count(args) == 0) {
return;
}
char v[CBM_SZ_1K];
char path[CBM_SZ_1K];
if (!tf_string(m->src, m->dir, ts_node_named_child(args, 0), v, sizeof(v)) || v[0] != '\x01' ||
!tf_repo_path(m->dir, v, path, sizeof(path)) || !path[0] ||
!tf_grow((void **)&m->frefs, &m->fref_cap, m->fref_n, sizeof(*m->frefs))) {
return;
}
char *p = cbm_arena_strdup(m->arena, path);
if (p) {
m->frefs[m->fref_n++] = (tf_fref_t){(char *)m->file, (char *)src_block, p, name,
(int)ts_node_start_point(call).row + SKIP_ONE};
}
}
/* Every traversal and every file-function call under `n` (iterative: deep
* expressions). */
static void tf_walk_refs(tf_mod_t *m, const char *src_block, TSNode n) {
TSTreeCursor cur = ts_tree_cursor_new(n);
bool more = true;
@@ -1134,6 +1195,8 @@ static void tf_walk_refs(tf_mod_t *m, const char *src_block, TSNode n) {
TSNode c = ts_tree_cursor_current_node(&cur);
if (tf_type(c, "variable_expr")) {
tf_traversal(m, src_block, c);
} else if (tf_type(c, "function_call")) {
tf_file_call(m, src_block, c);
}
if (ts_tree_cursor_goto_first_child(&cur)) {
continue;
@@ -1280,8 +1343,11 @@ static int tf_ref_edge(tf_mod_t *m, int64_t src, int64_t tgt, const char *type,
/* Resolve the module's references against its declarations, module.X.Y
* against the outputs of X's source directory (`mods`: directory -> its
* module), and its local module calls to their directories' Folders. */
static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders) {
* module), its local module calls to their directories' Folders, and its
* file-function calls to the files they name (`files`: path -> File node;
* NULL: none). */
static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders,
CBMHashTable *files) {
int edges = 0;
for (int i = 0; i < m->ref_n; i++) {
const tf_ref_t *r = &m->refs[i];
@@ -1328,6 +1394,29 @@ static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders) {
cbm_gbuf_insert_edge(m->ctx->gbuf, src, folder->id, "IMPORTS", props);
edges++;
}
/* file functions: once per block and file, at the first call (the calls
* stand in source order, the module's files in path order) */
CBMHashTable *seen = files && m->fref_n > 0 ? cbm_ht_create((uint32_t)m->fref_n) : NULL;
for (int i = 0; seen && i < m->fref_n; i++) {
const tf_fref_t *r = &m->frefs[i];
const cbm_gbuf_node_t *f = cbm_ht_get(files, r->path);
int64_t src = f ? tf_def_node(m, r->file, r->src) : 0;
const char *key =
src > 0 && src != f->id
? cbm_arena_sprintf(m->arena, "%lld>%lld", (long long)src, (long long)f->id)
: NULL;
if (!key || cbm_ht_get(seen, key)) {
continue;
}
cbm_ht_set(seen, key, (void *)key);
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"%s\",\"line\":%d}", r->fn, r->line);
cbm_gbuf_insert_edge(m->ctx->gbuf, src, f->id, "REFERENCES_FILE", props);
edges++;
}
if (seen) {
cbm_ht_free(seen);
}
return edges;
}
@@ -1340,6 +1429,7 @@ static void tf_mod_free(tf_mod_t *m) {
}
cbm_free(CBM_MEM_CLASS_OTHER, m->refs);
cbm_free(CBM_MEM_CLASS_OTHER, m->mcalls);
cbm_free(CBM_MEM_CLASS_OTHER, m->frefs);
cbm_free(CBM_MEM_CLASS_OTHER, m);
}
@@ -1481,6 +1571,7 @@ static int tf_link_repo(cbm_pipeline_ctx_t *ctx, TSParser *parser, const char *c
tf_mod_t **list = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)pn * sizeof(*list));
int nm = 0;
int calls = 0;
int frefs = 0;
for (int i = 0; mods && list && i < pn;) {
int j = i;
while (j < pn && tf_same_dir(paths[i], paths[j])) {
@@ -1491,13 +1582,18 @@ static int tf_link_repo(cbm_pipeline_ctx_t *ctx, TSParser *parser, const char *c
list[nm++] = m;
cbm_ht_set(mods, m->dir, m);
calls += m->call_n;
frefs += m->fref_n;
}
i = j;
}
CBMHashTable *folders = calls > 0 ? tf_label_index(ctx, "Folder") : NULL;
CBMHashTable *fileix = frefs > 0 ? tf_label_index(ctx, "File") : NULL;
int edges = 0;
for (int k = 0; k < nm; k++) {
edges += tf_mod_link(list[k], mods, folders);
edges += tf_mod_link(list[k], mods, folders, fileix);
}
if (fileix) {
cbm_ht_free(fileix);
}
for (int k = 0; mods && k < vn; k++) {
edges += tf_link_tfvars(&arena, parser, mods, ctx->repo_path, vpaths[k]);
+29 -7
View File
@@ -151,7 +151,8 @@ static const cbm_gbuf_node_t *find_enclosing_node(cbm_pipeline_ctx_t *ctx, const
/* Resolve USAGE edges for one file's extracted usages. */
static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,
const char *rel, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, CBMLanguage lang) {
const char **imp_vals, int imp_count, CBMLanguage lang,
cbm_site_memo_t **site_memo) {
int resolved = 0;
cbm_pipeline_lsp_reference_index_t reference_index = {0};
bool reference_index_ready =
@@ -163,7 +164,7 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
cbm_php_vendor_names_t php_vendor;
cbm_pipeline_php_vendor_names_build(ctx->gbuf, ctx->project_name, rel, result, &php_vendor);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, lang, result, site_memo, NULL);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
@@ -321,13 +322,22 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
}
/* ref_name is sliced source text and can contain quotes/newlines —
* escape it or the edge properties JSON is malformed. */
char esc_ref[CBM_SZ_256];
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
* escape it or the edge properties JSON is malformed. A proven answer
* of the shared layer names its strategy (site_bind.h). MUST match
* pass_parallel.c. */
char uprops[CBM_SZ_512];
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
if (scoped.verdict == CBM_SITE_PROVEN) {
cbm_pipeline_site_usage_props(uprops, sizeof(uprops), usage, CBM_SITE_PROVEN);
} else {
char esc_ref[CBM_SZ_256];
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
}
const char *edge_type = precise_call_reference ? "CALL_REFERENCE" : "USAGE";
cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, edge_type, uprops);
if (scoped.verdict == CBM_SITE_POSSIBLE) {
cbm_pipeline_site_bind_usage_drawn(&site, usage, tgt);
}
resolved++;
}
cbm_pipeline_site_bind_end(&site, ctx->gbuf);
@@ -458,8 +468,20 @@ static int resolve_rw_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result
return resolved;
}
static int pass_usages_files(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files, int file_count,
cbm_site_memo_t **site_memo);
int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int file_count) {
/* the shared layer's memo for this pass (site_bind.h) */
cbm_site_memo_t *site_memo = NULL;
int rc = pass_usages_files(ctx, files, file_count, &site_memo);
cbm_pipeline_site_memo_free(site_memo);
return rc;
}
static int pass_usages_files(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files, int file_count,
cbm_site_memo_t **site_memo) {
cbm_log_info("pass.start", "pass", "usages", "files", itoa_log(file_count));
int usage_resolved = 0;
@@ -533,7 +555,7 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
pu_module_is_dir(files[i].language));
usage_resolved += resolve_usage_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language);
imp_count, files[i].language, site_memo);
throw_resolved += resolve_throw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language);
rw_resolved += resolve_rw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count,
+24 -1
View File
@@ -20,10 +20,12 @@ enum { CBM_DIR_PERMS = 0755, PL_RING = 4, PL_RING_MASK = 3, PL_SEQ_PASSES = 7 };
#include "pipeline/artifact.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/doc_links.h"
#include "pipeline/include_path.h"
#include "pipeline/lsp_surface.h"
#include "pipeline/lsp_resolve.h"
#include "pipeline/pass_lsp_cross.h"
#include "pipeline/pass_ensemble_routing.h"
#include "pipeline/site_bind.h"
#include "pipeline/worker_pool.h"
#include "graph_buffer/graph_buffer.h"
#include "git/git_context.h"
@@ -2629,7 +2631,7 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
census_len(def->client_route_path) + census_len(def->impl_trait) +
census_len(def->http_base_url) + census_list(def->extra_props) +
census_len(def->decl_namespace) + census_len(def->variant_key) +
census_len(def->alias_target);
census_len(def->alias_target) + census_len(def->mixin_refs);
if (def->type_facts) {
str_def_misc += sizeof(*def->type_facts) +
census_len(def->type_facts->type_params) +
@@ -2937,6 +2939,10 @@ static int run_sequential_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
rc = CBM_NOT_FOUND;
}
}
/* The definitions pass built the shared layer's scope; the resolvers
* are done with it. */
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
/* Consume infra bindings (YAML/HCL topic/queue/scheduler → endpoint) so
* INFRA_MAPS edges also form on the sequential path, not just the parallel
* one. process_one_infra_binding self-creates the topic Route node when no
@@ -3056,6 +3062,16 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
if (registry_next_id > atomic_load(&shared_ids)) {
atomic_store(&shared_ids, registry_next_id);
}
/* The shared layer's scope (site_bind.h): every file is extracted and
* its IMPORTS made; built once, sealed before the resolve workers start,
* freed after them. Mirrors pass_definitions.c on the sequential route. */
cbm_clock_gettime(CLOCK_MONOTONIC, t);
ctx->site_scope =
cbm_pipeline_site_scope_build(ctx, files, file_count, cache, NULL, 0, NULL, 0);
if (ctx->site_scope) {
cbm_log_info("pass.timing", "pass", "site_scope", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
}
/* Cross-file LSP precondition: build a project-wide CBMLSPDef[]
* once. The fused resolve_worker invokes cbm_pxc_run_one(_ts) per
* file using these defs + the file's IMPORTS map, so cross-file
@@ -3165,6 +3181,8 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
rc = cbm_parallel_resolve(ctx, files, file_count, cache, &shared_ids, worker_count, all_defs,
def_count, def_modules, module_def_index, &cross_registries);
cbm_doclinks_end(ctx);
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
cbm_log_info("pass.timing", "pass", "parallel_resolve", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
pipeline_phase_mark("parallel_resolve");
@@ -4396,6 +4414,7 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
struct timespec t0;
cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
cbm_path_alias_collection_t *path_aliases = NULL;
cbm_include_universe_t *include_universe = NULL;
CBMHashTable *indexed_files = NULL;
cbm_file_hash_t *baseline_manifest = NULL;
int baseline_count = 0;
@@ -4562,6 +4581,8 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
* when no usable configs are found — non-TS projects pay nothing. */
path_aliases =
cbm_load_path_aliases_excluded(p->repo_path, p->excluded_dirs, p->excluded_count);
/* The path rule's universe (include_path.h): the run's indexed files. */
include_universe = cbm_include_universe_new(files, file_count);
indexed_files = cbm_pipeline_indexed_files_new(files, file_count);
if (!indexed_files) {
rc = CBM_NOT_FOUND;
@@ -4585,6 +4606,7 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
.path_aliases = path_aliases,
.excluded_dirs = p->excluded_dirs,
.excluded_count = p->excluded_count,
.include_universe = include_universe,
};
rc = run_extraction_phase(p, &ctx, files, file_count);
@@ -4618,6 +4640,7 @@ cleanup:
cbm_registry_free(p->registry);
p->registry = NULL;
cbm_path_alias_collection_free(path_aliases);
cbm_include_universe_free(include_universe);
cbm_ht_free(indexed_files); /* keys borrowed from files */
if (restore_requested_discovery) {
cbm_discover_free_excluded(p->excluded_dirs, p->excluded_count);
+313 -1
View File
@@ -15,6 +15,7 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24 };
#include "pipeline/pipeline.h"
#include <stdio.h>
#include <time.h>
#include "pipeline/include_path.h"
#include "pipeline/lsp_surface.h"
#include "foundation/mem_core.h"
#include "pipeline/pass_lsp_cross.h"
@@ -23,6 +24,8 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24 };
#include "pipeline/pipeline_internal.h"
#include "helpers.h" /* cbm_fqn_module */
#include "pipeline/doc_links.h"
#include "pipeline/scope_closure.h"
#include "pipeline/site_bind.h"
#include "store/store.h"
#include "graph_buffer/graph_buffer.h"
#include "discover/discover.h"
@@ -569,6 +572,23 @@ int cbm_pipeline_build_semantic_manifest(const cbm_pipeline_t *p, const char *pr
rc = semantic_manifest_add_digest(&builder, project, CBM_SEMANTIC_INPUT_PROJECT_CONFIG,
project_config_digest, 0, 0);
}
/* The path rule's universe (include_path.h), only where a file of a path
* row is discovered: a changed set of the indexed names a row's import
* can name (one added, removed or renamed) changes which file an import
* names in files that did not change, so it routes to a full index. A key
* of the discovered list: nothing is walked. */
bool path_row_file = false;
for (int i = 0; i < file_count && !path_row_file; i++) {
path_row_file = cbm_include_path_row(files[i].language) != NULL;
}
if (rc == 0 && path_row_file) {
char listing_digest[CBM_SHA256_HEX_LEN + 1];
rc = cbm_include_path_inventory_digest(files, file_count, listing_digest);
if (rc == 0) {
rc = semantic_manifest_add_digest(&builder, project, CBM_SEMANTIC_INPUT_INCLUDE_LISTING,
listing_digest, 0, 0);
}
}
struct timespec t_hash;
cbm_clock_gettime(CLOCK_MONOTONIC, &t_hash);
int hash_workers = cbm_pipeline_worker_count(p);
@@ -1535,6 +1555,12 @@ typedef struct {
* the arenas live exactly as long as cr.arena itself. */
CBMArena *rehydrate_arenas;
int rehydrate_arena_count;
/* The shared layer's scope reads every discovered file: the re-parsed
* ones fresh, the others from their stored facts (borrowed). */
const cbm_file_info_t *all_files;
int all_count;
const cbm_lsp_surface_row_t *stored_rows;
int stored_count;
} closure_resolve_t;
typedef struct {
@@ -1997,6 +2023,19 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
atomic_store(&shared_ids, registry_next_id);
}
/* The shared layer's scope (site_bind.h), sealed before the resolve
* workers start: the re-parsed files fresh, every other discovered
* file of a row language from its stored facts (closure repair). */
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
ctx->site_scope = cbm_pipeline_site_scope_build(
ctx, changed_files, ci, cache, closure ? closure->all_files : NULL,
closure ? closure->all_count : 0, closure ? closure->stored_rows : NULL,
closure ? closure->stored_count : 0);
if (ctx->site_scope) {
cbm_log_info("pass.timing", "pass", "incr_site_scope", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
}
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
CBMLSPDef *all_defs = NULL;
int all_def_count = 0;
@@ -2075,7 +2114,11 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
* path, filtered through module_def_index, is the SAME
* pre-Tier-2 resolution code the full pipeline still uses
* for languages without a shared registry, so convergence
* is unaffected; only the amortization strategy changes. */
* is unaffected; only the amortization strategy changes.
* Ruby's fallback (cbm_run_ruby_lsp_cross) is exempt from the
* def filter and so rebuilds the whole project table for each
* changed Ruby file: at most CLOSURE_BUDGET_FLOOR_FILES
* builds here, which is bounded and left as is. */
if (ci > CLOSURE_BUDGET_FLOOR_FILES) {
cbm_pxc_build_cross_registries(&closure->arena, all_defs, all_def_count,
&cross_registries);
@@ -2121,6 +2164,8 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
cbm_doclinks_end(ctx);
cross_resolve_cleanup:
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
if (module_def_index) {
cbm_pxc_free_module_def_index(module_def_index);
}
@@ -2191,6 +2236,9 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
if (rc == 0) {
(void)cbm_pipeline_pass_doc_links(ctx, changed_files, ci);
}
/* the definitions pass built the shared layer's scope */
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
if (owns_cache) {
free_incremental_result_cache(cache, ci);
ctx->result_cache = prior_cache;
@@ -2675,6 +2723,141 @@ static bool closure_release_values(cbm_store_t *store, const char *project, cons
return hit;
}
/* Is p[0, n) a key of `table`? */
static bool closure_docker_has(CBMHashTable *table, const char *p, size_t n) {
char key[CBM_SZ_4K];
if (n == 0 || n >= sizeof(key)) {
return false;
}
memcpy(key, p, n);
key[n] = '\0';
return cbm_ht_get(table, key) != NULL;
}
/* A Dockerfile below the repository root reads a COPY / ADD source under its
* own directory or under the root, the one of the two that holds the file; a
* source both hold is no edge (pass_docker.c dk_repo: REFERENCES_FILE, and
* the path mapping behind SPAWNS). Deleting one file of such a pair leaves the
* other as the single candidate: an edge the full index draws from a
* Dockerfile that did not change, and a repair of the deleted file alone does
* not read that Dockerfile again. So a deleted file whose partner path is
* still indexed declines. Every Dockerfile's directory counts, whether or not
* the Dockerfile names the file: it is not parsed here.
*
* The two directions, each one lookup per directory level of a path:
* - deleted <dir>/<source>, <source> still a file at the root: the deleted
* path's own prefixes are tried as Dockerfile directories;
* - deleted <source>, <dir>/<source> still a file: every indexed file under
* a Dockerfile directory enters `under` by its path below that directory,
* and the deleted path is looked up there.
* A source that is a file under one context and a directory under the other
* is no edge either (dk_dir_under_other_context), and the directory goes
* with its last file. So the same holds one level up: a deleted file whose
* directory, below a Dockerfile directory, is a file at the root, or whose
* directory is <source> of a file <dir>/<source>, declines too -- also when
* the directory still holds other files, which costs a full run and no edge.
* Work is the path depths of the indexed and the deleted files (the deleted
* ones squared, a path being short), and only when a file was deleted and a
* Dockerfile lies below the root. Returns the reason, or NULL. */
static const char *closure_docker_context_decline(const cbm_file_info_t *files, int file_count,
CBMHashTable *files_by_path, char **deleted,
int n_deleted) {
CBMHashTable *dirs = NULL; /* directories holding a Dockerfile (keys in `keys`) */
CBMArena keys;
cbm_arena_init_lazy(&keys, CBM_SZ_4K);
const char *decline = NULL;
for (int f = 0; n_deleted > 0 && f < file_count && !decline; f++) {
const char *rel = files[f].rel_path;
const char *slash = files[f].language == CBM_LANG_DOCKERFILE ? strrchr(rel, '/') : NULL;
if (!slash) {
continue;
}
dirs = dirs ? dirs : cbm_ht_create(0);
char *dir = dirs ? cbm_arena_strndup(&keys, rel, (size_t)(slash - rel)) : NULL;
if (!dir) {
decline = "alloc";
} else {
cbm_ht_set(dirs, dir, dir);
}
}
/* <source> of each indexed <dir>/<source> */
CBMHashTable *under = dirs && !decline ? cbm_ht_create(0) : NULL;
if (dirs && !decline && !under) {
decline = "alloc";
}
for (int f = 0; under && f < file_count; f++) {
const char *rel = files[f].rel_path;
for (const char *s = strchr(rel, '/'); s; s = strchr(s + SKIP_ONE, '/')) {
if (s[SKIP_ONE] && closure_docker_has(dirs, rel, (size_t)(s - rel))) {
cbm_ht_set(under, s + SKIP_ONE, (void *)rel);
}
}
}
for (int i = 0; under && i < n_deleted && !decline; i++) {
const char *gone = deleted[i];
if (cbm_ht_get(under, gone)) {
decline = "docker_context_pair_deleted"; /* <dir>/<gone> is still a file */
}
for (const char *s = strchr(gone, '/'); s && !decline; s = strchr(s + SKIP_ONE, '/')) {
/* a directory of the deleted file that is <source> of a file
* <dir>/<source>: under the root it may be no directory now */
if (closure_docker_has(under, gone, (size_t)(s - gone))) {
decline = "docker_context_pair_deleted";
}
if (decline || !closure_docker_has(dirs, gone, (size_t)(s - gone))) {
continue;
}
const char *src = s + SKIP_ONE;
if (cbm_ht_get(files_by_path, src)) {
decline = "docker_context_pair_deleted"; /* <source> is still a file at the root */
}
/* a directory below <dir> that is a file at the root */
for (const char *t = strchr(src, '/'); t && !decline; t = strchr(t + SKIP_ONE, '/')) {
if (closure_docker_has(files_by_path, src, (size_t)(t - src))) {
decline = "docker_context_pair_deleted";
}
}
}
}
if (under) {
cbm_ht_free(under);
}
if (dirs) {
cbm_ht_free(dirs);
}
cbm_arena_destroy(&keys);
return decline;
}
/* A workflow names a local action by its directory, and its edge goes to the
* one action file that directory holds (pass_shell.c sh_ci_use); with both
* spellings, action.yml and action.yaml, there is none. Deleting one of the
* two makes the other the action: an edge the full index draws from a
* workflow that did not change, and the repair reads no workflow again. So
* a deleted action file whose other spelling is still indexed declines.
* One lookup per deleted file. Returns the reason, or NULL. */
static const char *closure_local_action_decline(CBMHashTable *files_by_path, char **deleted,
int n_deleted) {
static const char *const names[PAIR_LEN] = {"action.yml", "action.yaml"};
for (int i = 0; i < n_deleted; i++) {
const char *p = deleted[i];
const char *slash = p ? strrchr(p, '/') : NULL;
const char *base = slash ? slash + SKIP_ONE : p;
for (int k = 0; base && k < PAIR_LEN; k++) {
if (strcmp(base, names[k]) != 0) {
continue;
}
char other[CBM_SZ_4K];
int n = snprintf(other, sizeof(other), "%.*s%s", (int)(base - p), p,
names[PAIR_LEN - SKIP_ONE - k]);
if (n > 0 && (size_t)n < sizeof(other) && cbm_ht_get(files_by_path, other)) {
return "local_action_pair_deleted";
}
}
}
return NULL;
}
/* Kubernetes inputs reach past their own file (pass_k8s.c): a kustomization
* decides which manifests deploy together and in which namespace, a
* Chart.yaml links other charts, and a manifest's Services select workloads
@@ -3125,6 +3308,107 @@ static const char *closure_add_includers(const cbm_lsp_surface_row_t *rows, int
/* Decide whether this manifest delta is closure-repairable, and if so build
* the plan. Returns 1 with *plan filled, or 0 (decline → FULL) with the
* reason logged. Every early exit declines; nothing here mutates state. */
/* The file names (last path component) a row's stored facts re-export
* (`import public`), into `names`; 0, -1 when the row has no facts ("is"),
* -2 when they cannot be read. */
static int closure_scope_row(CBMArena *a, const cbm_lsp_surface_row_t *row, CBMHashTable *names) {
cbm_lsp_scope_facts_t facts;
int rc = cbm_lsp_surface_scope_from_json(a, row ? row->defs_json : NULL, &facts);
if (rc == 0) {
return CBM_NOT_FOUND;
}
if (rc != SKIP_ONE) {
return -PAIR_LEN;
}
for (int i = 0; i < facts.event_count; i++) {
const CBMScopeEvent *e = &facts.events[i];
if (names && e->kind == CBM_SCOPE_INCLUDE && (e->flags & CBM_SCOPE_REEXPORT) &&
e->index >= 0 && e->index < facts.module_count) {
const char *slash = strrchr(facts.modules[e->index], '/');
cbm_ht_set(names, slash ? slash + SKIP_ONE : facts.modules[e->index], (void *)1);
}
}
return 0;
}
/* Whether a file may be what some re-export names (by its last path
* component: never fewer than the path rule would resolve). */
static bool closure_scope_reexported(CBMHashTable *names, const char *rel) {
const char *slash = strrchr(rel, '/');
return cbm_ht_get(names, slash ? slash + SKIP_ONE : rel) != NULL;
}
/* The shared layer's scope (site_bind.h) on a repair reads every file of a
* row language the repair leaves alone from its stored facts: a row without
* them (an older binary wrote it) or with unreadable ones declines. A file's
* changed facts reach the files with an edge into it (its includers re-resolve
* as dependents); when it is re-exported (`import public`) they also reach
* the re-exporter's includers, which have no edge into it: a surface change
* (or deletion) of a file some re-export may name declines too. NULL: the
* repair may go on. */
static const char *closure_scope_decline(const cbm_lsp_surface_row_t *stored, int stored_count,
CBMHashTable *rows_by_path,
const cbm_lsp_surface_row_t *fresh, int fresh_count,
CBMHashTable *files_by_path, char **changed, int n_changed,
int n_deleted) {
CBMArena a;
cbm_arena_init(&a);
const char *why = NULL;
CBMHashTable *reexported = cbm_ht_create(CBM_SZ_16);
if (!reexported) {
cbm_arena_destroy(&a);
return "alloc";
}
for (int i = 0; i < stored_count && !why; i++) {
const cbm_file_info_t *info = cbm_ht_get(files_by_path, stored[i].rel_path);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
int rc = closure_scope_row(&a, &stored[i], reexported);
why = rc == CBM_NOT_FOUND ? "scope_facts_missing" : rc < 0 ? "scope_facts_malformed" : NULL;
}
for (int i = 0; i < fresh_count && !why; i++) {
const cbm_file_info_t *info = cbm_ht_get(files_by_path, fresh[i].rel_path);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
int rc = closure_scope_row(&a, &fresh[i], reexported);
why = rc < 0 ? "scope_facts_malformed" : NULL;
}
bool changed_scope = false;
bool any = cbm_ht_count(reexported) > 0;
for (int i = 0; i < n_changed + n_deleted && !why && any && !changed_scope; i++) {
if (!closure_scope_reexported(reexported, changed[i])) {
continue;
}
const cbm_lsp_surface_row_t *old_row = cbm_ht_get(rows_by_path, changed[i]);
if (i >= n_changed) {
/* a deleted file whose row holds facts is of a row language */
changed_scope = old_row && closure_scope_row(&a, old_row, NULL) != CBM_NOT_FOUND;
continue;
}
const cbm_file_info_t *info = cbm_ht_get(files_by_path, changed[i]);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
const cbm_lsp_surface_row_t *new_row = NULL;
for (int j = 0; j < fresh_count; j++) {
if (strcmp(fresh[j].rel_path, changed[i]) == 0) {
new_row = &fresh[j];
break;
}
}
changed_scope = old_row && (!new_row || !old_row->surface_sha || !new_row->surface_sha ||
strcmp(old_row->surface_sha, new_row->surface_sha) != 0);
}
if (!why && changed_scope) {
why = "scope_reexport_changed";
}
cbm_ht_free(reexported); /* keys borrowed from the arena */
cbm_arena_destroy(&a);
return why;
}
static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *project,
cbm_file_info_t *files, int file_count, const cbm_file_hash_t *stored,
int stored_count, const cbm_file_hash_t *fresh, int fresh_count,
@@ -3249,6 +3533,15 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
if (decline) {
goto done;
}
decline = closure_docker_context_decline(files, file_count, files_by_path,
changed_paths + n_changed, n_deleted);
if (decline) {
goto done;
}
decline = closure_local_action_decline(files_by_path, changed_paths + n_changed, n_deleted);
if (decline) {
goto done;
}
decline = closure_terraform_decline(changed_paths, n_changed + n_deleted);
if (decline) {
goto done;
@@ -3339,6 +3632,13 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
decline = "probe_failed";
goto done;
}
decline =
closure_scope_decline(plan->stored_rows, plan->stored_count, rows_by_path, probe_rows,
probe_count, files_by_path, changed_paths, n_changed, n_deleted);
if (decline) {
cbm_ht_free(rows_by_path);
goto done;
}
/* Validate Python namespace metadata before any hash cutoff or dependent
* query. Python changes require a full rebuild; other surface changes and
@@ -3701,6 +4001,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
cbm_gbuf_t *gbuf = NULL;
cbm_registry_t *registry = NULL;
cbm_path_alias_collection_t *path_aliases = NULL;
cbm_include_universe_t *include_universe = NULL;
CBMHashTable *indexed_files = NULL;
CBMHashTable *stale_surface_set = NULL;
closure_resolve_t cr = {0};
@@ -3805,6 +4106,10 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
}
cbm_arena_init(&cr.arena);
cr_arena_live = true;
cr.all_files = files;
cr.all_count = file_count;
cr.stored_rows = plan->stored_rows;
cr.stored_count = plan->stored_count;
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
{
/* Eligible rows first (skip everything being re-parsed or deleted),
@@ -3929,7 +4234,9 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
cbm_log_error("delta.err", "phase", "stored_namespaces");
goto out;
}
include_universe = cbm_include_universe_new(files, file_count);
cbm_pipeline_ctx_t ctx = {
.include_universe = include_universe,
.project_name = project,
.repo_path = cbm_pipeline_repo_path(p),
.indexed_files = indexed_files,
@@ -4275,6 +4582,7 @@ out:
cbm_registry_free(registry);
}
cbm_path_alias_collection_free(path_aliases);
cbm_include_universe_free(include_universe);
cbm_ht_free(indexed_files); /* keys borrowed from files */
if (gbuf) {
cbm_gbuf_free(gbuf);
@@ -4689,9 +4997,11 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
cbm_path_alias_collection_t *path_aliases =
cbm_load_path_aliases_excluded(cbm_pipeline_repo_path(p), excluded_dirs, excluded_count);
cbm_include_universe_t *include_universe = cbm_include_universe_new(files, file_count);
CBMHashTable *indexed_files = cbm_pipeline_indexed_files_new(files, file_count);
cbm_pipeline_ctx_t ctx = {
.include_universe = include_universe,
.project_name = project,
.repo_path = cbm_pipeline_repo_path(p),
.indexed_files = indexed_files,
@@ -4782,6 +5092,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
free(changed_files);
cbm_registry_free(registry);
cbm_path_alias_collection_free(path_aliases);
cbm_include_universe_free(include_universe);
cbm_ht_free(indexed_files); /* keys borrowed from files */
incr_free_edge_capture(&edge_cap);
cbm_store_free_coverage(old_cov, old_cov_count);
@@ -4882,6 +5193,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
free(changed_files);
cbm_registry_free(registry);
cbm_path_alias_collection_free(path_aliases);
cbm_include_universe_free(include_universe);
cbm_ht_free(indexed_files); /* keys borrowed from files */
/* Re-link inbound cross-file edges that the purge orphaned. Runs after
+112 -3
View File
@@ -390,6 +390,8 @@ typedef struct {
char *manifest_rel; /* heap: owning SwiftPM manifest, NULL for other ecosystems */
char *source_rel; /* heap: the manifest file that yielded this entry; NULL if hand-built */
int source_seq; /* position among that manifest's entries, in the parser's order */
/* A registry dependency a package.json declares, named by pkg_name; entry_rel is NULL. */
bool npm_dependency;
} cbm_pkg_entry_t;
/* Growable array of package entries (per-worker, no thread contention). */
@@ -579,6 +581,16 @@ typedef struct {
cbm_tf_release_t *tf_releases;
int tf_release_n;
int tf_release_cap;
/* The path rule's universe (include_path.h): built from the run's indexed
* files with the context, read-only afterwards, freed with it. NULL: no
* import is read by the path rule (main's strategies decide). */
struct cbm_include_universe *include_universe;
/* The shared cross-file layer's scope (site_bind.h): built after IMPORTS
* on one thread, read only by the resolvers, freed by the route that
* built it. NULL: no file of a row language (every site NO_ANSWER). */
struct cbm_site_scope *site_scope;
} cbm_pipeline_ctx_t;
/* The set for cbm_pipeline_ctx_t.indexed_files: every rel_path of `files`
@@ -1432,11 +1444,24 @@ typedef void (*cbm_ci_cmd_fn)(const cbm_ci_cmd_t *cmd, void *ud);
* (.github/workflows/<name>.yml|yaml) or a composite action (action.yml|yaml). */
bool cbm_ci_path(const char *rel);
/* A local `uses:` of a GitHub workflow or composite action (pass_ci.c): a
* path from the repository root ("./..."), which is how GitHub reads it
* wherever the file lies. A step's names an action's directory (`path`; ""
* is the root), a job's names a reusable workflow file. `line` is 1-based. */
typedef struct {
const char *path;
bool job;
int line;
} cbm_ci_use_t;
typedef void (*cbm_ci_use_fn)(const cbm_ci_use_t *use, void *ud);
/* Hand each command line the CI configuration `rel` (YAML text src) runs to
* fn: GitHub Actions run: steps for a workflow or composite action, else
* Prow job containers. Strings live in arena `a`. */
* Prow job containers. In the same walk, each local `uses:` of a workflow or
* composite action goes to use_fn (NULL: not wanted) with use_ud, in
* document order. Strings live in arena `a`. */
void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len, cbm_ci_cmd_fn fn,
void *ud);
void *ud, cbm_ci_use_fn use_fn, void *use_ud);
/* An image a build configuration builds from a Dockerfile (pass_ci.c). */
typedef struct {
@@ -1448,6 +1473,18 @@ typedef struct {
} cbm_build_site_t;
typedef void (*cbm_build_site_fn)(const cbm_build_site_t *site, void *ud);
/* A repository file a compose service names (pass_ci.c): a path relative to
* the compose file's directory, normalised -- a bind mount's host side
* ("volume"), an env_file entry ("env_file"), the file of a config or secret
* the service lists ("config" / "secret") -- with the 1-based line where the
* service names it. The path may be a directory, or a file the index does
* not hold. */
typedef struct {
const char *path;
const char *via;
int line;
} cbm_compose_file_t;
/* A compose service (pass_ci.c): its image (a reference, variables
* expanded; NULL: none or unknown), the Dockerfile its build names
* (repository path; NULL: no build, or unknown), the service names its
@@ -1458,7 +1495,7 @@ typedef void (*cbm_build_site_fn)(const cbm_build_site_t *site, void *ud);
* image_default_of: the variables whose inline default (${X:-d}) named the
* image; image_override_of: those whose default the project's .env replaced
* (JSON arrays, NULL: none), and default_image the image those defaults
* name. */
* name. files: the repository paths it names (cbm_compose_file_t). */
typedef struct {
const char *name;
const char *image;
@@ -1472,6 +1509,8 @@ typedef struct {
const int *env_lines;
const char **env_hosts;
int nenv;
const cbm_compose_file_t *files;
int nfiles;
int line;
int end_line;
} cbm_compose_service_t;
@@ -1674,6 +1713,10 @@ extern _Atomic uint64_t g_importance_store_rows;
extern _Atomic uint64_t g_k8s_candidates;
extern _Atomic uint64_t g_op_candidates;
extern _Atomic uint64_t g_sh_candidates;
/* Targets, prerequisites and target-prerequisite pairs the Make dependency
* drawing looked at (pass_shell.c sh_make_deps): linear in a rule line's
* words plus its distinct pairs, however often a name is repeated. */
extern _Atomic uint64_t g_sh_make_pairs;
/* ── Incremental pipeline (pipeline_incremental.c) ───────────────── */
@@ -1698,6 +1741,11 @@ bool cbm_pipeline_incremental_generation_exact(cbm_pipeline_t *p, cbm_store_t *s
#define CBM_SEMANTIC_INPUT_GIT_CONTEXT CBM_SEMANTIC_INPUT_PREFIX "git-context-v1"
#define CBM_SEMANTIC_INPUT_GLOBAL_CONFIG CBM_SEMANTIC_INPUT_PREFIX "global-extension-config-v1"
#define CBM_SEMANTIC_INPUT_PROJECT_CONFIG CBM_SEMANTIC_INPUT_PREFIX "project-extension-config-v1"
/* The path rule's inventory (include_path.h): the indexed files named like
* what a path row's import names; present only when a file of a path-row
* language is discovered. A changed set of such names, anywhere, routes the
* run to a full index. */
#define CBM_SEMANTIC_INPUT_INCLUDE_LISTING CBM_SEMANTIC_INPUT_PREFIX "include-listing-v1"
int cbm_pipeline_build_semantic_manifest(const cbm_pipeline_t *p, const char *project,
const char *repo_path, const cbm_file_info_t *files,
@@ -2048,6 +2096,67 @@ void cbm_pp_bp_nap_cycles_reset(void);
* coverage; deterministic and independent of wall-clock timing. */
uint64_t cbm_pp_lsp_linear_fallback_rows(void);
void cbm_pp_lsp_linear_fallback_rows_reset(void);
/* Index lookups made by cbm_pipeline_lsp_index_find since the last reset of
* the counter above (the same reset clears both). */
uint64_t cbm_pp_lsp_index_lookups(void);
/* Rows read by a per-call scan of a file's engine rows since that reset,
* counted inside the scan itself (lsp_resolve.h), whoever called it. */
uint64_t cbm_pp_lsp_scan_rows(void);
/* One file's engine rows (CBMResolvedCall invocations) by caller, leaf and
* span, built and searched by the same code on both resolvers
* (pass_parallel.c). cbm_pipeline_lsp_index_find returns what the matcher
* cbm_pipeline_find_lsp_resolution_in_graph returns, scanning only where the
* index may not hold the answer. */
typedef struct {
uint32_t start;
uint32_t end;
uint32_t origin;
int row; /* position in the file's row array */
} cbm_pipeline_lsp_site_row_t;
typedef struct {
CBMHashTable *exact; /* caller|leaf|start:end|origin */
CBMHashTable *legacy; /* caller|leaf|origin, rows without a span */
bool exact_complete;
bool legacy_complete;
/* Every row with a span, sorted by span, origin and array position: the
* rows at one occurrence are neighbours, in array order. Only such a row
* ranks for a call that needs the engine, so that call is answered from
* these alone; the JVM tail phase reads them for its exact rows. */
cbm_pipeline_lsp_site_row_t *site_rows;
int site_count;
bool site_complete;
/* JVM callers only: the rows without a span by the Class.method tail of
* their caller (tail|leaf|origin), for the tail phase. Built only when
* the index was built for tail matching (tail_indexed). */
CBMHashTable *tail_legacy;
bool tail_legacy_complete;
bool tail_indexed;
/* PHP's unindexed-receiver rows (cbm_pipeline_php_unindexed_row), which
* lie below the confidence floor and so in neither table above: the first
* row of each key in array order. */
CBMHashTable *php_exact; /* caller|leaf|start:end|origin */
CBMHashTable *php_legacy; /* caller|leaf|origin, rows without a span */
int php_rows; /* such rows in the file */
bool php_complete;
} cbm_pipeline_lsp_index_t;
void cbm_pipeline_lsp_index_build(cbm_pipeline_lsp_index_t *idx, const CBMResolvedCallArray *arr,
const cbm_gbuf_t *gbuf, const char *project_name,
bool allow_tail);
const CBMResolvedCall *cbm_pipeline_lsp_index_find(const cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr,
const CBMCall *call, bool allow_tail,
const cbm_gbuf_t *gbuf,
const char *project_name);
/* cbm_pipeline_php_receiver_type_unindexed's answer, from the index where the
* index holds it and from that scan where it may not. */
bool cbm_pipeline_lsp_index_php_receiver_unindexed(const cbm_pipeline_lsp_index_t *idx,
const CBMResolvedCallArray *arr,
const CBMCall *call,
const cbm_registry_t *registry);
void cbm_pipeline_lsp_index_free(cbm_pipeline_lsp_index_t *idx);
#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
+59
View File
@@ -3019,6 +3019,59 @@ static void candidates_without_members(const cbm_registry_t *r, const qn_array_t
.items = items, .count = n, .cap = n, .is_test = is_test, .is_test_cap = n, .lang = lang};
}
/* ── Scala, Strategy 4 with an import map (#2360 follow-up) ──────────
* Since Scala imports resolve (#2360), almost every Scala file reaches
* Strategy 4 with an import map, and resolve_multi_with_imports keeps only
* the import-reachable candidates. A method of the calling file itself is
* never import-reachable, so an imported type's same-named method displaced
* it: a bare `bimap` in EitherT.scala went to Bifunctor's syntax class. Scala
* only; every other language keeps the shared path unchanged. */
/* The best candidate declared in the calling file (its QN extends the
* caller's module QN), ranked as every pick is; NULL when there is none. */
static const char *scala_module_local_pick(const cbm_registry_t *r, const qn_array_t *arr,
const char *module_qn, bool caller_test) {
size_t mlen = module_qn ? strlen(module_qn) : 0;
if (mlen == 0) {
return NULL;
}
const char *local[CBM_SZ_256];
uint8_t local_test[CBM_SZ_256];
uint8_t local_lang[CBM_SZ_256];
const uint8_t *flags = qn_test_flags(arr);
const uint8_t *langs = qn_lang_flags(arr);
int n = 0;
for (int i = 0; i < arr->count && n < CBM_SZ_256; i++) {
const char *qn = arr->items[i];
if (strncmp(qn, module_qn, mlen) == 0 && qn[mlen] == '.') {
local[n] = qn;
local_test[n] = flags[i];
local_lang[n] = langs ? langs[i] : (uint8_t)CBM_LANG_COUNT;
n++;
}
}
if (n == 0) {
return NULL;
}
return best_by_import_distance(r, local, local_test, langs ? local_lang : NULL, n, module_qn,
caller_test);
}
/* Same-file candidate first: the calling file's own candidate, when the
* receiver gate a file without imports applies admits it (the exit at the end
* of resolve_name_candidates). An empty result means: continue as before. */
static cbm_resolution_t scala_local_first(const cbm_registry_t *r, const qn_array_t *arr,
const char *callee_name, const char *module_qn,
bool caller_test) {
const char *local = scala_module_local_pick(r, arr, module_qn, caller_test);
if (!local || !receiver_chain_admits(callee_name, local, CBM_LANG_SCALA) ||
value_receiver_blind(r, arr, callee_name, local, module_qn, NULL, 0, CBM_LANG_SCALA)) {
return empty_result();
}
double conf = candidate_count_penalty(CONF_SUFFIX_MATCH, arr->count);
return (cbm_resolution_t){local, "suffix_match", conf, arr->count};
}
/* Strategies 3.5, 3 and 4 over one same-name candidate set. `lang` reaches
* receiver_chain_admits and value_receiver_blind only (see there): it is the
* calling file's language on the CALLS path and CBM_LANG_COUNT on every other
@@ -3056,6 +3109,12 @@ static cbm_resolution_t resolve_name_candidates(const cbm_registry_t *r, const q
}
/* Strategy 4: multiple candidates */
if (lang == CBM_LANG_SCALA && import_vals && import_count > 0) {
cbm_resolution_t local = scala_local_first(r, arr, callee_name, module_qn, caller_test);
if (local.qualified_name) {
return local;
}
}
if (import_vals && import_count > 0) {
cbm_resolution_t res =
resolve_multi_with_imports(r, arr, module_qn, import_vals, import_count, caller_test);
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
#ifndef CBM_SCOPE_CLOSURE_H
#define CBM_SCOPE_CLOSURE_H
/*
* scope_closure.h — which definitions named N a file sees, unordered mode:
* the closure and the lookup of the shared cross-file layer.
*
* A file sees its own definitions, those of its package mates where the row
* says a package is visible, and what each file it includes exports. A file
* exports its own definitions and what its re-exporting includes export
* (Protobuf `import public`); a plain include is not passed on. The closure is
* never listed per file: re-exporting includes are collapsed into strongly
* connected components, and a lookup of N searches backwards from the
* components of N's defining files along re-export edges, once per name
* (memoised per name and component).
*
* The lookup answers, in its own terms (possible against proven):
* PROVEN exactly one visible definition, the closure complete, the
* name not bound locally, the definition not conditional;
* POSSIBLE exactly one visible definition otherwise (a source on the way
* is unresolved or outside the repository, opaque, a prelude);
* NO_ANSWER none visible with an incomplete closure, or two or more;
* PROVEN_ABSENT none visible, the closure complete (counted only).
* `why` says what kept an answer from being proven; drawing is the caller's.
*
* Threads: built and sealed on one thread; afterwards the closure is read
* only. A lookup writes nothing but the memo it is handed, so each thread
* brings its own (cbm_closure_memo_t). The memo only saves work: an answer is
* the same with a fresh memo, a used one or none.
*/
#include "cbm.h"
#include <stdbool.h>
#include <stdint.h>
/* One language's scope row. */
typedef struct {
CBMLanguage lang;
bool package_visible; /* a file sees its package mates' definitions without an include */
bool prelude_external; /* names may come from an implicit external prelude */
bool ambiguity_is_error; /* two visible definitions do not compile: one visible past an
* unresolved or external source is still the one */
bool qualified_refs; /* a reference as written is read against full names from the
* scopes around it (Protobuf; see cbm_closure_ref_t) */
} cbm_closure_lang_t;
/* The row of a language, or NULL. */
const cbm_closure_lang_t *cbm_closure_lang(CBMLanguage lang);
typedef enum {
CBM_CLOSURE_NO_ANSWER = 0,
CBM_CLOSURE_PROVEN,
CBM_CLOSURE_POSSIBLE,
CBM_CLOSURE_PROVEN_ABSENT,
} cbm_closure_verdict_t;
/* Why an answer is not proven (several may hold). */
enum {
CBM_CLOSURE_WHY_UNRESOLVED = 1u << 0, /* an include on the way names no repository file */
CBM_CLOSURE_WHY_OPAQUE = 1u << 1, /* a file on the way has a part the facts cannot read */
CBM_CLOSURE_WHY_PRELUDE = 1u << 2, /* the row's names may come from a prelude */
CBM_CLOSURE_WHY_LOCAL = 1u << 3, /* the reference is bound by a parameter or local */
CBM_CLOSURE_WHY_CONDITIONAL = 1u << 4, /* the one definition may not be in effect */
CBM_CLOSURE_WHY_AMBIGUOUS = 1u << 5, /* two or more definitions are visible */
CBM_CLOSURE_WHY_NO_NODE = 1u << 6, /* the one definition has no graph node */
/* the one definition is in a message of the referring file (or the
* file's package is unknown) and the reference carries no scope: the
* enclosing message decides (protoc's scope walk) */
CBM_CLOSURE_WHY_SCOPE = 1u << 7,
};
/* How the answer's definition is visible. */
enum { CBM_CLOSURE_VIA_OWN = 1, CBM_CLOSURE_VIA_INCLUDE = 2, CBM_CLOSURE_VIA_PACKAGE = 3 };
/* The lookup key of one site. */
typedef struct {
const char *name; /* the last identifier */
/* the reference as written, qualifier included ("common.Status",
* ".a.b.Outer.Inner"), or NULL for the bare name. A row with qualified
* references reads it against definitions' full names: a leading dot is
* the root; otherwise the full name is a scope around the referring site
* followed by it, the innermost scope in which its first component names
* a symbol deciding. A definition whose full name is unknown matches by
* its name alone. */
const char *written;
/* the innermost scope around the site, the first one searched
* ("a.b.Outer": the enclosing message; "a.b": the package; "": the
* root), or NULL when it is unknown: then the scopes are the referring
* file's package and each package around it, and any message of the
* file holding a definition of the first component may decide first
* (an answer is then at most possible) */
const char *scope;
uint32_t pos; /* the site's byte (ordered rows; unused in unordered mode) */
uint8_t ns; /* namespace (unused in unordered mode) */
uint8_t flags; /* CBM_CLOSURE_REF_* */
} cbm_closure_ref_t;
enum { CBM_CLOSURE_REF_LOCAL = 1u << 0 /* bound by a parameter or a local */ };
typedef struct {
cbm_closure_verdict_t verdict;
const char *qn; /* the definition's qualified name (PROVEN, POSSIBLE), else NULL */
const char *full; /* ... and its full name, NULL when unknown */
int file; /* its file, else -1 */
int visible; /* definitions named N visible from the file (2 means two or more) */
bool complete; /* every source on the way is a repository file the facts read whole */
uint32_t why; /* CBM_CLOSURE_WHY_* */
uint8_t via; /* CBM_CLOSURE_VIA_* of the answer */
} cbm_closure_answer_t;
typedef struct cbm_closure cbm_closure_t;
cbm_closure_t *cbm_closure_new(void);
void cbm_closure_free(cbm_closure_t *s);
/* A file of a language with a row; returns its index, -1 on failure (also
* for a path added twice). `package` "" when it has none, NULL when unknown
* (references from the file then read every scope as possibly around them). */
int cbm_closure_add_file(cbm_closure_t *s, const char *rel, const cbm_closure_lang_t *row,
const char *package);
/* A definition of `file`: its name, full name (or NULL: unknown), graph
* qualified name (NULL: the graph has no node for it) and whether it is
* conditional. Strings are copied. */
bool cbm_closure_add_def(cbm_closure_t *s, int file, const char *name, const char *full,
const char *qn, bool conditional);
/* An include of `file`: the included file, or -1 when it names no repository
* file; re-exporting or plain. */
bool cbm_closure_add_include(cbm_closure_t *s, int file, int target, bool reexport);
/* A part of `file` the facts cannot read (an OPAQUE event). */
bool cbm_closure_add_opaque(cbm_closure_t *s, int file);
/* After the last file: components, completeness and the by-name index.
* Returns 0, or -1 on allocation failure. No file is added after it. */
int cbm_closure_seal(cbm_closure_t *s);
/* The index of the file at `rel`, or -1. */
int cbm_closure_file(const cbm_closure_t *s, const char *rel);
/* Files and definitions added (memory reports). */
int cbm_closure_file_count(const cbm_closure_t *s);
int cbm_closure_def_count(const cbm_closure_t *s);
/* One thread's memo of what components export per name. */
typedef struct cbm_closure_memo cbm_closure_memo_t;
cbm_closure_memo_t *cbm_closure_memo_new(void);
void cbm_closure_memo_free(cbm_closure_memo_t *m);
/* What `ref` names from `file`. `memo` may be NULL (nothing is kept). */
cbm_closure_answer_t cbm_closure_lookup(const cbm_closure_t *s, cbm_closure_memo_t *memo, int file,
const cbm_closure_ref_t *ref);
/* Counted work (growth tests): of building and sealing the closure, and of
* the lookups a memo served (reach steps, lookup steps). */
uint64_t cbm_closure_work(const cbm_closure_t *s);
uint64_t cbm_closure_memo_work(const cbm_closure_memo_t *m);
#endif /* CBM_SCOPE_CLOSURE_H */
+734 -18
View File
@@ -3,28 +3,463 @@
* sites. See site_bind.h for where the resolvers ask and how they apply an
* answer.
*
* No language has a row yet, so begin marks no file active, every site gets
* NO_ANSWER and the end step draws nothing: the hook costs a few calls per
* file and one call per site.
* The run's scope is the visibility closure (scope_closure.h) of every file
* of a row language, from its scope facts (extract_scope.c): DEF events are
* the definitions, INCLUDE events the includes, resolved to repository files
* by the path rule (include_path.h), OPAQUE events parts the facts cannot
* read. A usage is looked up by the type reference it ends (a QREF event).
*/
#include "pipeline/site_bind.h"
#include "cbm.h"
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/hash_table.h"
#include "foundation/log.h"
#include "foundation/mem_core.h"
#include "foundation/platform.h"
#include "foundation/str_util.h"
#include "graph_buffer/graph_buffer.h"
#include "pipeline/include_path.h"
#include "pipeline/lsp_surface.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/scope_closure.h"
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Strategies and confidences of the layer's edges. */
#define SB_PROVEN_STRATEGY "include_scope"
#define SB_POSSIBLE_STRATEGY "include_scope_may"
#define SB_PROVEN_CONF 0.95
#define SB_POSSIBLE_CONF 0.85
enum { SB_PATH_BUF = 1024, SB_PROPS_BUF = 2048 };
struct cbm_site_scope {
cbm_closure_t *closure;
int files;
int stored_files;
int unreadable_files;
int includes;
int includes_resolved;
/* run totals (count only), summed by every resolver thread */
_Atomic uint64_t proven;
_Atomic uint64_t possible;
_Atomic uint64_t drawn;
_Atomic uint64_t same;
_Atomic uint64_t disagree;
_Atomic uint64_t present;
_Atomic uint64_t unsettled;
_Atomic uint64_t absent;
/* CBM_SITE_BIND_DUMP=<path> (test-seam builds only): one line per
* answered site and per settled possible answer, appended (measurement) */
FILE *dump;
/* building only: resolved include path -> the first import spelling
* that named it (in spell_arena); freed before the closure is sealed */
CBMHashTable *spellings;
CBMArena spell_arena;
};
static const char *sb_verdict_name(cbm_closure_verdict_t v) {
switch (v) {
case CBM_CLOSURE_PROVEN:
return "proven";
case CBM_CLOSURE_POSSIBLE:
return "possible";
case CBM_CLOSURE_PROVEN_ABSENT:
return "absent";
default:
return "no_answer";
}
}
struct cbm_site_memo {
cbm_closure_memo_t *closure_memo;
};
void cbm_pipeline_site_memo_free(cbm_site_memo_t *m) {
if (m) {
cbm_closure_memo_free(m->closure_memo);
cbm_free(CBM_MEM_CLASS_OTHER, m);
}
}
/* A POSSIBLE answer, settled when the file is done. */
struct sb_pending {
int64_t source_id;
const cbm_gbuf_node_t *target;
int index; /* the usage or call in sf->result */
bool is_call;
bool main_drew; /* usage: main's chain drew a USAGE edge at the site */
const cbm_gbuf_node_t *main_target; /* ... to this node */
};
/* ── Building the run's scope ───────────────────────────────────────── */
/* One file's facts: fresh (a result) or stored (a surface row's "is"). */
typedef struct {
const char *rel;
CBMLanguage lang;
const cbm_closure_lang_t *row;
const CBMFileResult *result; /* fresh */
cbm_lsp_scope_facts_t facts; /* stored */
bool stored;
bool readable;
int index; /* in the closure */
} sb_file_t;
/* The package a file's facts name: every INCLUDE event carries it; NULL
* (unknown) for a file without one. */
/* The file's package: the one its INCLUDE events carry; a file without one
* (no import) gives it through its definitions: the full name of the one with
* the fewest components is the package followed by its name (a top-level
* definition; a nested one has more). NULL: unknown (no import, no
* definition). `buf` holds a derived package. */
static const char *sb_package(const CBMScopeEvent *ev, int n, char *buf, size_t cap) {
int best = -1;
size_t best_dots = SIZE_MAX;
for (int i = 0; i < n; i++) {
if (ev[i].kind == CBM_SCOPE_INCLUDE && ev[i].qual) {
return ev[i].qual; /* a stored row's INCLUDE carries none: read the definitions */
}
if (ev[i].kind == CBM_SCOPE_DEF && ev[i].qual && ev[i].name) {
size_t dots = 0;
for (const char *c = ev[i].qual; *c; c++) {
dots += *c == '.';
}
if (dots < best_dots) {
best_dots = dots;
best = i;
}
}
}
if (best < 0) {
return NULL;
}
const char *qual = ev[best].qual;
size_t ql = strlen(qual);
size_t nl = strlen(ev[best].name);
if (ql == nl) {
return strcmp(qual, ev[best].name) == 0 ? "" : NULL;
}
if (ql <= nl + SKIP_ONE || qual[ql - nl - SKIP_ONE] != '.' ||
strcmp(qual + ql - nl, ev[best].name) != 0 || ql - nl - SKIP_ONE >= cap) {
return NULL;
}
memcpy(buf, qual, ql - nl - SKIP_ONE);
buf[ql - nl - SKIP_ONE] = '\0';
return buf;
}
static void sb_add_events(const cbm_pipeline_ctx_t *ctx, cbm_site_scope_t *sc, const sb_file_t *f) {
const CBMScopeEvent *ev = f->stored ? f->facts.events : f->result->scope.items;
int n = f->stored ? f->facts.event_count : f->result->scope.count;
for (int i = 0; i < n; i++) {
const CBMScopeEvent *e = &ev[i];
bool conditional = (e->flags & CBM_SCOPE_CONDITIONAL) != 0;
switch (e->kind) {
case CBM_SCOPE_DEF: {
const CBMDefinition *d = NULL;
if (f->stored && e->index >= 0 && e->index < f->facts.def_count) {
d = &f->facts.defs[e->index];
} else if (!f->stored && e->index >= 0 && e->index < f->result->defs.count) {
d = &f->result->defs.items[e->index];
}
(void)cbm_closure_add_def(sc->closure, f->index, e->name, e->qual,
d ? d->qualified_name : NULL, conditional);
if (sc->dump) {
fprintf(sc->dump, "D\t%s\t%s\t%s\t%s\n", f->rel, e->name ? e->name : "",
e->qual ? e->qual : "", d && d->qualified_name ? d->qualified_name : "");
}
break;
}
case CBM_SCOPE_ASSIGN:
/* a name defined here with no node of the graph */
(void)cbm_closure_add_def(sc->closure, f->index, e->name, NULL, NULL, conditional);
break;
case CBM_SCOPE_INCLUDE: {
CBMImport imp;
memset(&imp, 0, sizeof(imp));
if (f->stored && e->index >= 0 && e->index < f->facts.module_count) {
imp.module_path = f->facts.modules[e->index];
} else if (!f->stored && e->index >= 0 && e->index < f->result->imports.count) {
imp = f->result->imports.items[e->index];
}
char path[SB_PATH_BUF];
int target = CBM_NOT_FOUND;
if (imp.module_path &&
cbm_include_path_resolve(ctx->include_universe, ctx->gbuf, ctx->project_name,
f->rel, f->lang, &imp, path,
sizeof(path)) == CBM_INCLUDE_PATH_FILE) {
target = cbm_closure_file(sc->closure, path);
}
if (target >= 0 && sc->spellings) {
const char *first = cbm_ht_get(sc->spellings, path);
if (!first) {
const char *k = cbm_arena_strdup(&sc->spell_arena, path);
const char *v = cbm_arena_strdup(&sc->spell_arena, imp.module_path);
if (k && v) {
cbm_ht_set(sc->spellings, k, (void *)v);
}
} else if (strcmp(first, imp.module_path) != 0) {
/* one file named by two import spellings: protoc reads two
* virtual files that define the same names ("already
* defined"), so nothing through it is proven */
(void)cbm_closure_add_opaque(sc->closure, target);
}
}
sc->includes++;
sc->includes_resolved += target >= 0;
(void)cbm_closure_add_include(sc->closure, f->index, target,
(e->flags & CBM_SCOPE_REEXPORT) != 0);
break;
}
case CBM_SCOPE_OPAQUE:
(void)cbm_closure_add_opaque(sc->closure, f->index);
break;
default:
break;
}
}
}
cbm_site_scope_t *cbm_pipeline_site_scope_build(const cbm_pipeline_ctx_t *ctx,
const cbm_file_info_t *fresh, int fresh_count,
CBMFileResult **cache, const cbm_file_info_t *all,
int all_count, const cbm_lsp_surface_row_t *stored,
int stored_count) {
if (!ctx || !ctx->include_universe) {
return NULL;
}
/* Row files: the fresh ones, then the other discovered ones (stored). */
int nrow = 0;
for (int i = 0; i < fresh_count; i++) {
nrow += cbm_closure_lang(fresh[i].language) != NULL;
}
for (int i = 0; all && i < all_count; i++) {
nrow += cbm_closure_lang(all[i].language) != NULL;
}
if (nrow == 0) {
return NULL; /* no file of a row language: no cost at all */
}
cbm_site_scope_t *sc = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*sc));
sb_file_t *files = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)nrow * sizeof(*files));
bool *loaded = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)nrow * sizeof(*loaded));
CBMHashTable *fresh_rel = cbm_ht_create(CBM_SZ_64);
CBMHashTable *rows_by_rel = stored_count > 0 ? cbm_ht_create(CBM_SZ_256) : NULL;
CBMArena facts_arena;
cbm_arena_init(&facts_arena);
bool ok = sc && files && loaded && fresh_rel && (stored_count == 0 || rows_by_rel);
if (ok) {
memset(sc, 0, sizeof(*sc));
memset(files, 0, (size_t)nrow * sizeof(*files));
memset(loaded, 0, (size_t)nrow * sizeof(*loaded));
sc->closure = cbm_closure_new();
ok = sc->closure != NULL;
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
/* measurement only, in test-seam builds: the product never reads the
* variable nor opens a file (sc->dump stays NULL) */
char dump_path[SB_PATH_BUF];
if (ok && cbm_safe_getenv("CBM_SITE_BIND_DUMP", dump_path, sizeof(dump_path), NULL)) {
sc->dump = cbm_fopen(dump_path, "a");
}
#endif
} else if (sc) {
memset(sc, 0, sizeof(*sc));
}
int n = 0;
for (int i = 0; ok && i < fresh_count; i++) {
const cbm_closure_lang_t *row = cbm_closure_lang(fresh[i].language);
if (!row) {
continue;
}
sb_file_t *f = &files[n];
f->rel = fresh[i].rel_path;
f->lang = fresh[i].language;
f->row = row;
f->result = cache ? cbm_pipeline_result_acquire(ctx, cache, i, NULL, &loaded[n]) : NULL;
f->readable = f->result != NULL;
cbm_ht_set(fresh_rel, f->rel, f);
n++;
}
for (int i = 0; ok && i < stored_count; i++) {
if (stored[i].rel_path) {
cbm_ht_set(rows_by_rel, stored[i].rel_path, (void *)&stored[i]);
}
}
for (int i = 0; ok && all && i < all_count; i++) {
const cbm_closure_lang_t *row = cbm_closure_lang(all[i].language);
if (!row || cbm_ht_get(fresh_rel, all[i].rel_path)) {
continue;
}
sb_file_t *f = &files[n++];
f->rel = all[i].rel_path;
f->lang = all[i].language;
f->row = row;
f->stored = true;
const cbm_lsp_surface_row_t *r = rows_by_rel ? cbm_ht_get(rows_by_rel, f->rel) : NULL;
f->readable =
r && cbm_lsp_surface_scope_from_json(&facts_arena, r->defs_json, &f->facts) == SKIP_ONE;
}
/* Files first, so an include can name any of them. */
for (int i = 0; ok && i < n; i++) {
sb_file_t *f = &files[i];
const char *package = NULL;
char pkgbuf[SB_PATH_BUF];
if (f->readable) {
package = f->stored ? sb_package(f->facts.events, f->facts.event_count, pkgbuf,
sizeof(pkgbuf))
: sb_package(f->result->scope.items, f->result->scope.count, pkgbuf,
sizeof(pkgbuf));
}
f->index = cbm_closure_add_file(sc->closure, f->rel, f->row, package);
if (f->index < 0) {
f->readable = false; /* a path seen twice: the first one stands */
continue;
}
sc->files++;
sc->stored_files += f->stored;
if (!f->readable) {
sc->unreadable_files++;
(void)cbm_closure_add_opaque(sc->closure, f->index);
}
}
if (ok) {
cbm_arena_init(&sc->spell_arena);
sc->spellings = cbm_ht_create(CBM_SZ_256);
}
for (int i = 0; ok && i < n; i++) {
if (files[i].readable) {
sb_add_events(ctx, sc, &files[i]);
}
}
if (sc && sc->spellings) {
cbm_ht_free(sc->spellings);
sc->spellings = NULL;
cbm_arena_destroy(&sc->spell_arena);
}
ok = ok && cbm_closure_seal(sc->closure) == 0;
for (int i = 0; files && i < n; i++) {
if (!files[i].stored && files[i].result) {
cbm_pipeline_result_release((CBMFileResult *)files[i].result, loaded[i]);
}
}
cbm_arena_destroy(&facts_arena); /* the closure copied what it keeps */
cbm_free(CBM_MEM_CLASS_OTHER, files);
cbm_free(CBM_MEM_CLASS_OTHER, loaded);
if (fresh_rel) {
cbm_ht_free(fresh_rel);
}
if (rows_by_rel) {
cbm_ht_free(rows_by_rel);
}
if (!ok) {
cbm_pipeline_site_scope_free(sc);
return NULL;
}
char b[4][CBM_SZ_16];
snprintf(b[0], sizeof(b[0]), "%d", sc->files);
snprintf(b[1], sizeof(b[1]), "%d", cbm_closure_def_count(sc->closure));
snprintf(b[2], sizeof(b[2]), "%d", sc->includes);
snprintf(b[3], sizeof(b[3]), "%d", sc->includes_resolved);
cbm_log_info("site_bind.scope", "files", b[0], "defs", b[1], "includes", b[2], "resolved",
b[3]);
return sc;
}
void cbm_pipeline_site_scope_free(cbm_site_scope_t *sc) {
if (!sc) {
return;
}
if (sc->closure) {
char b[8][CBM_SZ_32];
const _Atomic uint64_t *v[8] = {&sc->proven, &sc->possible, &sc->drawn, &sc->same,
&sc->disagree, &sc->present, &sc->unsettled, &sc->absent};
for (int i = 0; i < 8; i++) {
snprintf(b[i], sizeof(b[i]), "%llu", (unsigned long long)atomic_load(v[i]));
}
/* drawn and present together: whether a possible answer's edge was drawn
* by the layer or already there depends on which worker's buffer holds
* main's edge (route-dependent); that it exists does not */
snprintf(b[2], sizeof(b[2]), "%llu",
(unsigned long long)(atomic_load(v[2]) + atomic_load(v[5])));
cbm_log_info("site_bind.run", "proven", b[0], "possible", b[1], "possible_drawn", b[2],
"possible_same", b[3], "possible_disagree", b[4], "possible_unsettled", b[6],
"proven_absent", b[7]);
}
if (sc->dump) {
fclose(sc->dump);
}
cbm_closure_free(sc->closure);
cbm_free(CBM_MEM_CLASS_OTHER, sc);
}
/* ── The test seam ───────────────────────────────────────────────────── */
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
enum { SB_MARKS = 16 };
static struct {
char name[CBM_SZ_128];
char target[CBM_SZ_512];
cbm_site_verdict_t verdict;
} g_marks[SB_MARKS];
static int g_nmarks;
void cbm_pipeline_site_bind_test_mark(const char *name, const char *target_qn,
cbm_site_verdict_t verdict) {
if (!name) {
g_nmarks = 0;
return;
}
if (g_nmarks < SB_MARKS) {
snprintf(g_marks[g_nmarks].name, sizeof(g_marks[g_nmarks].name), "%s", name);
snprintf(g_marks[g_nmarks].target, sizeof(g_marks[g_nmarks].target), "%s",
target_qn ? target_qn : "");
g_marks[g_nmarks].verdict = verdict;
g_nmarks++;
}
}
/* The mark of a site's name, or -1. */
static int sb_marked(const char *name) {
for (int i = 0; name && i < g_nmarks; i++) {
if (strcmp(name, g_marks[i].name) == 0) {
return i;
}
}
return CBM_NOT_FOUND;
}
#endif
/* ── Sites ───────────────────────────────────────────────────────────── */
void cbm_pipeline_site_bind_begin(cbm_site_file_t *sf, const cbm_pipeline_ctx_t *ctx,
const cbm_gbuf_t *graph, const char *rel, CBMLanguage lang,
const CBMFileResult *result) {
const CBMFileResult *result, cbm_site_memo_t **memo,
const CBMCallEvidence *evidence) {
if (!sf) {
return;
}
*sf = (cbm_site_file_t){
.ctx = ctx, .graph = graph, .result = result, .rel = rel, .lang = lang, .active = false};
memset(sf, 0, sizeof(*sf));
sf->ctx = ctx;
sf->graph = graph;
sf->result = result;
sf->rel = rel;
sf->lang = lang;
sf->memo = memo;
sf->evidence = evidence;
sf->file = CBM_NOT_FOUND;
const cbm_site_scope_t *sc = ctx ? ctx->site_scope : NULL;
if (sc && result && graph && rel && cbm_closure_lang(lang)) {
sf->file = cbm_closure_file(sc->closure, rel);
sf->active = sf->file >= 0;
}
}
/* The answer at every site of a file no row covers. */
@@ -33,26 +468,307 @@ static cbm_site_answer_t sb_no_answer(void) {
return none;
}
static cbm_site_answer_t sb_proven(const cbm_gbuf_node_t *target) {
cbm_site_answer_t a = {.verdict = CBM_SITE_PROVEN, .target = target};
a.res.qualified_name = target->qualified_name;
a.res.strategy = SB_PROVEN_STRATEGY;
a.res.confidence = SB_PROVEN_CONF;
a.res.candidate_count = SKIP_ONE;
return a;
}
/* Keep a POSSIBLE answer for the end step; false when out of memory (the
* site then has no answer). */
static bool sb_pend(cbm_site_file_t *sf, const cbm_gbuf_node_t *source,
const cbm_gbuf_node_t *target, int index, bool is_call) {
if (sf->npending >= sf->cap_pending) {
int ncap = sf->cap_pending ? sf->cap_pending * PAIR_LEN : CBM_SZ_16;
sb_pending_t *np = cbm_alloc(CBM_MEM_CLASS_RESOLVE, (size_t)ncap * sizeof(*np));
if (!np) {
return false;
}
if (sf->npending) {
memcpy(np, sf->pending, (size_t)sf->npending * sizeof(*np));
}
cbm_free(CBM_MEM_CLASS_RESOLVE, sf->pending);
sf->pending = np;
sf->cap_pending = ncap;
}
sf->pending[sf->npending++] = (sb_pending_t){.source_id = source->id,
.target = target,
.index = index,
.is_call = is_call,
.main_drew = false,
.main_target = NULL};
return true;
}
/* Turn a target node and a verdict into the site's answer. */
static cbm_site_answer_t sb_answer(cbm_site_file_t *sf, cbm_site_verdict_t v,
const cbm_gbuf_node_t *source, const cbm_gbuf_node_t *target,
int index, bool is_call) {
if (!target) {
return sb_no_answer();
}
if (v == CBM_SITE_PROVEN) {
sf->proven++;
return sb_proven(target);
}
if (v == CBM_SITE_POSSIBLE && sb_pend(sf, source, target, index, is_call)) {
sf->possible++;
cbm_site_answer_t a = {.verdict = CBM_SITE_POSSIBLE, .target = target};
return a;
}
return sb_no_answer();
}
cbm_site_answer_t cbm_pipeline_site_bind_call(cbm_site_file_t *sf, const CBMCall *call,
const cbm_gbuf_node_t *source) {
/* No row exists, so no file is active. */
(void)sf;
(void)call;
(void)source;
if (!sf || !call || !source || !sf->result) {
return sb_no_answer();
}
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
int mark = sb_marked(call->callee_name);
if (mark >= 0 && sf->graph) {
return sb_answer(sf, g_marks[mark].verdict, source,
cbm_gbuf_find_by_qn(sf->graph, g_marks[mark].target),
(int)(call - sf->result->calls.items), true);
}
#endif
/* No row answers calls yet (Protobuf has none). */
return sb_no_answer();
}
/* The type reference (a QREF event) that the site [start, end) is the last
* name of, or NULL. Events are sorted by position (a QREF's is its end byte,
* its index the start byte). */
static const CBMScopeEvent *sb_qref_ending(const CBMFileResult *r, uint32_t start, uint32_t end) {
const CBMScopeEvent *ev = r->scope.items;
int lo = 0;
int hi = r->scope.count;
while (lo < hi) {
int mid = lo + (hi - lo) / PAIR_LEN;
if (ev[mid].pos < end) {
lo = mid + SKIP_ONE;
} else {
hi = mid;
}
}
for (int i = lo; i < r->scope.count && ev[i].pos == end; i++) {
if (ev[i].kind == CBM_SCOPE_QREF && ev[i].name && ev[i].index >= 0 &&
(uint32_t)ev[i].index <= start) {
return &ev[i];
}
}
return NULL;
}
/* The thread's closure memo, made on its first lookup. */
static cbm_closure_memo_t *sb_memo(cbm_site_file_t *sf) {
if (!sf->memo) {
return NULL;
}
if (!*sf->memo) {
cbm_site_memo_t *m = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*m));
if (!m) {
return NULL;
}
m->closure_memo = cbm_closure_memo_new();
if (!m->closure_memo) {
cbm_free(CBM_MEM_CLASS_OTHER, m);
return NULL;
}
*sf->memo = m;
}
return (*sf->memo)->closure_memo;
}
cbm_site_answer_t cbm_pipeline_site_bind_usage(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *source) {
/* No row exists, so no file is active. */
(void)sf;
(void)usage;
(void)source;
return sb_no_answer();
if (!sf || !usage || !source || !sf->result || !usage->ref_name) {
return sb_no_answer();
}
int index = (int)(usage - sf->result->usages.items);
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
int mark = sb_marked(usage->ref_name);
if (mark >= 0 && sf->graph) {
return sb_answer(sf, g_marks[mark].verdict, source,
cbm_gbuf_find_by_qn(sf->graph, g_marks[mark].target), index, false);
}
#endif
if (!sf->active || usage->site_end_byte <= usage->site_start_byte) {
return sb_no_answer();
}
const CBMScopeEvent *qref =
sb_qref_ending(sf->result, usage->site_start_byte, usage->site_end_byte);
if (!qref) {
return sb_no_answer(); /* not the last name of a type reference */
}
if (qref->flags & CBM_SCOPE_NOT_A_TYPE) {
return sb_no_answer(); /* protoc resolves it to a method or a service */
}
const char *written = qref->name;
const char *dot = strrchr(written, '.');
if (strcmp(dot ? dot + SKIP_ONE : written, usage->ref_name) != 0) {
return sb_no_answer();
}
cbm_closure_ref_t ref = {
.name = usage->ref_name, .written = dot ? written : NULL, .scope = qref->qual};
const cbm_site_scope_t *sc = sf->ctx->site_scope;
cbm_closure_answer_t a = cbm_closure_lookup(sc->closure, sb_memo(sf), sf->file, &ref);
if (sc->dump) {
fprintf(sc->dump, "A\t%s\t%u\t%u\t%s\t%s\t%s\t%s\t%s\t%u\t%d\n", sf->rel,
usage->site_start_byte, usage->site_end_byte, usage->ref_name, written,
sb_verdict_name(a.verdict), a.qn ? a.qn : "", a.full ? a.full : "", a.why,
a.visible);
}
switch (a.verdict) {
case CBM_CLOSURE_PROVEN:
case CBM_CLOSURE_POSSIBLE: {
const cbm_gbuf_node_t *target = cbm_gbuf_find_by_qn(sf->graph, a.qn);
return sb_answer(sf, a.verdict == CBM_CLOSURE_PROVEN ? CBM_SITE_PROVEN : CBM_SITE_POSSIBLE,
source, target, index, false);
}
case CBM_CLOSURE_PROVEN_ABSENT:
sf->absent++;
return sb_no_answer();
default:
return sb_no_answer();
}
}
void cbm_pipeline_site_bind_usage_drawn(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *target) {
if (!sf || sf->npending == 0 || !usage || !sf->result) {
return;
}
sb_pending_t *last = &sf->pending[sf->npending - SKIP_ONE];
if (!last->is_call && last->index == (int)(usage - sf->result->usages.items)) {
last->main_drew = true;
last->main_target = target;
}
}
void cbm_pipeline_site_usage_props(char *buf, size_t cap, const CBMUsage *usage,
cbm_site_verdict_t verdict) {
char esc[CBM_SZ_256];
cbm_json_escape(esc, sizeof(esc), usage && usage->ref_name ? usage->ref_name : "");
bool proven = verdict == CBM_SITE_PROVEN;
snprintf(buf, cap, "{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\"}", esc,
proven ? SB_PROVEN_CONF : SB_POSSIBLE_CONF,
proven ? SB_PROVEN_STRATEGY : SB_POSSIBLE_STRATEGY);
}
/* ── The end step ────────────────────────────────────────────────────── */
static bool sb_has_edge(const cbm_gbuf_t *gb, int64_t source, int64_t target, const char *type) {
const cbm_gbuf_edge_t **out = NULL;
int count = 0;
if (!gb || cbm_gbuf_find_edges_by_source_type(gb, source, type, &out, &count) != 0) {
return false;
}
for (int i = 0; i < count; i++) {
if (out[i]->target_id == target) {
return true;
}
}
return false;
}
/* Draw a possible edge (the site's main drew nothing of its type). */
static bool sb_draw(cbm_site_file_t *sf, cbm_gbuf_t *edges, const sb_pending_t *p) {
char props[SB_PROPS_BUF];
if (!p->is_call) {
cbm_pipeline_site_usage_props(props, sizeof(props), &sf->result->usages.items[p->index],
CBM_SITE_POSSIBLE);
return cbm_gbuf_insert_edge(edges, p->source_id, p->target->id, "USAGE", props) > 0;
}
const CBMCall *call = &sf->result->calls.items[p->index];
char esc[CBM_SZ_256];
cbm_json_escape(esc, sizeof(esc), call->callee_name ? call->callee_name : "");
int n = snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d",
esc, SB_POSSIBLE_CONF, SB_POSSIBLE_STRATEGY, SKIP_ONE);
cbm_pipeline_close_call_props(props, n, call, true);
return cbm_gbuf_insert_edge(edges, p->source_id, p->target->id, "CALLS", props) > 0;
}
void cbm_pipeline_site_bind_end(cbm_site_file_t *sf, cbm_gbuf_t *edges) {
/* No POSSIBLE answer was given, so nothing is left to draw. */
(void)sf;
(void)edges;
if (!sf) {
return;
}
cbm_site_scope_t *sc = sf->ctx ? sf->ctx->site_scope : NULL;
int drawn = 0;
int same = 0;
int disagree = 0;
int present = 0;
int unsettled = 0;
for (int i = 0; edges && i < sf->npending; i++) {
const sb_pending_t *p = &sf->pending[i];
const char *type = p->is_call ? "CALLS" : "USAGE";
bool drew = false;
const cbm_gbuf_node_t *main_target = NULL;
if (p->is_call) {
if (!sf->evidence) {
unsettled++; /* what main emitted at the site is unknown: nothing drawn */
continue;
}
const CBMCallEvidence *ev = &sf->evidence[p->index];
drew = ev->calls_emitted;
main_target =
ev->candidate_qn ? cbm_gbuf_find_by_qn(sf->graph, ev->candidate_qn) : NULL;
} else {
drew = p->main_drew;
main_target = p->main_target;
}
bool exists =
sb_has_edge(edges, p->source_id, p->target->id, type) ||
(sf->graph != edges && sb_has_edge(sf->graph, p->source_id, p->target->id, type));
const char *outcome = "drawn";
if (drew) {
if (main_target == p->target || (!main_target && exists)) {
same++;
outcome = "same";
} else {
disagree++; /* main's edge stays alone */
outcome = "disagree";
}
} else if (p->target->id == p->source_id || exists) {
present++; /* the edge is there already (another site): nothing added */
outcome = "present";
} else if (sb_draw(sf, edges, p)) {
drawn++;
} else {
outcome = "failed";
}
if (sc && sc->dump) {
uint32_t at = p->is_call ? 0 : sf->result->usages.items[p->index].site_start_byte;
fprintf(sc->dump, "S\t%s\t%u\t%s\t%s\t%s\n", sf->rel ? sf->rel : "", at, outcome,
p->target->qualified_name,
main_target && main_target->qualified_name ? main_target->qualified_name : "");
}
}
if (sc && (sf->proven || sf->possible || sf->absent)) {
atomic_fetch_add(&sc->proven, (uint64_t)sf->proven);
atomic_fetch_add(&sc->possible, (uint64_t)sf->possible);
atomic_fetch_add(&sc->drawn, (uint64_t)drawn);
atomic_fetch_add(&sc->same, (uint64_t)same);
atomic_fetch_add(&sc->disagree, (uint64_t)disagree);
atomic_fetch_add(&sc->present, (uint64_t)present);
atomic_fetch_add(&sc->unsettled, (uint64_t)unsettled);
atomic_fetch_add(&sc->absent, (uint64_t)sf->absent);
char b[8][CBM_SZ_16];
const int v[8] = {sf->proven, sf->possible, drawn, same,
disagree, present, unsettled, sf->absent};
for (int i = 0; i < 8; i++) {
snprintf(b[i], sizeof(b[i]), "%d", v[i]);
}
cbm_log_info("site_bind.file", "rel", sf->rel ? sf->rel : "", "proven", b[0], "possible",
b[1], "drawn", b[2], "same", b[3], "disagree", b[4], "present", b[5],
"unsettled", b[6], "absent", b[7]);
}
cbm_free(CBM_MEM_CLASS_RESOLVE, sf->pending);
sf->pending = NULL;
sf->npending = 0;
sf->cap_pending = 0;
}
+78 -18
View File
@@ -14,23 +14,27 @@
* classification; a usage site that no engine row was found
* for, after the C member join and before the PHP vendor check
* and main's name chain.
* PROVEN replaces main's name chain at the site. A call keeps every
* later step of main (service and route classification, spawn,
* field policy, guards) on the answer; a usage takes the target.
* POSSIBLE main's chain decides the site as before. The layer may draw
* its own edge for it when the file is done
* (cbm_pipeline_site_bind_end), and only where main drew no
* edge of that type between the same two nodes.
* NO_ANSWER main's chain, unchanged.
* PROVEN replaces main's name chain at the site (strategy
* `include_scope`, confidence 0.95). A call keeps every later
* step of main (service and route classification, spawn, field
* policy, guards) on the answer; a usage takes the target.
* POSSIBLE main's chain decides the site as before. When the file is done
* (cbm_pipeline_site_bind_end) the layer draws its own edge
* (`include_scope_may`, confidence 0.85) only where main drew no
* edge of that type at the site; where main drew the same target
* nothing is added; where main drew another target main's edge
* stays alone and the disagreement is counted.
* NO_ANSWER main's chain, unchanged. A proven absence is counted only.
*
* Rules and their rows live in site_bind.c; a resolver is never edited for
* a new rule. No language has a row yet: every file is inactive, every site
* gets NO_ANSWER and the end step draws nothing, so the graph is main's on
* both routes.
* Rows: the scope rows of scope_closure.h (Protobuf). A usage is answered
* only at the last name of a type reference the scope facts recorded (a
* QREF event ending where the usage ends), read as written. Calls of a row
* language are not answered yet (Protobuf has none).
*
* Threads: one cbm_site_file_t per file being resolved, on the stack of the
* worker resolving it. Whatever run-wide input a row reads is built and
* sealed before any resolver starts.
* The run's scope (cbm_site_scope_t) is built once after IMPORTS, on one
* thread, before any resolver starts, and is read only afterwards. Each
* resolver thread brings its own memo (cbm_site_memo_t, created on its first
* lookup); no answer depends on what a memo holds.
*/
#include "cbm.h"
@@ -39,6 +43,7 @@
#include "pipeline/pipeline_internal.h"
#include <stdbool.h>
#include <stddef.h>
typedef enum {
CBM_SITE_NO_ANSWER = 0, /* main's chain decides, unchanged */
@@ -55,6 +60,15 @@ typedef struct {
const cbm_gbuf_node_t *target;
} cbm_site_answer_t;
/* The run's scope: NULL when no discovered file has a row. */
typedef struct cbm_site_scope cbm_site_scope_t;
/* One resolver thread's memo (opaque); NULL until its first lookup. */
typedef struct cbm_site_memo cbm_site_memo_t;
void cbm_pipeline_site_memo_free(cbm_site_memo_t *m);
typedef struct sb_pending sb_pending_t;
/* One file's state, on the resolver's stack between begin and end. */
typedef struct {
const cbm_pipeline_ctx_t *ctx;
@@ -62,13 +76,40 @@ typedef struct {
const CBMFileResult *result;
const char *rel;
CBMLanguage lang;
bool active; /* false: no row covers this file, every site is NO_ANSWER */
bool active; /* false: no row covers this file, every site is NO_ANSWER */
int file; /* the file in the run's scope (active only) */
cbm_site_memo_t **memo; /* the thread's memo slot */
const CBMCallEvidence *evidence; /* per call: what main emitted (calls), or NULL */
sb_pending_t *pending; /* POSSIBLE answers left to the end step */
int npending;
int cap_pending;
int proven;
int possible;
int absent;
} cbm_site_file_t;
/* Start one file: before its first site is asked. */
/* Build the run's scope from every discovered file of a row language: its
* fresh result (cache[i] for fresh[i], read through the spill-aware
* accessor) or, for a file of `all` without one, its stored facts (the
* surface row's "is" key; incremental closure repair). A row-language file
* with neither takes part as unreadable (nothing proven through it). On one
* thread, after IMPORTS and before any resolver. NULL: no row-language file
* (or out of memory): every site gets NO_ANSWER. */
cbm_site_scope_t *cbm_pipeline_site_scope_build(const cbm_pipeline_ctx_t *ctx,
const cbm_file_info_t *fresh, int fresh_count,
CBMFileResult **cache, const cbm_file_info_t *all,
int all_count, const cbm_lsp_surface_row_t *stored,
int stored_count);
/* Log the run's counts and free. */
void cbm_pipeline_site_scope_free(cbm_site_scope_t *sc);
/* Start one file: before its first site is asked. `memo`: the calling
* thread's slot; `evidence`: the file's per-call evidence (calls pass), or
* NULL. */
void cbm_pipeline_site_bind_begin(cbm_site_file_t *sf, const cbm_pipeline_ctx_t *ctx,
const cbm_gbuf_t *graph, const char *rel, CBMLanguage lang,
const CBMFileResult *result);
const CBMFileResult *result, cbm_site_memo_t **memo,
const CBMCallEvidence *evidence);
/* The answer for one call of sf->result (an element of result->calls),
* made in the function or file node `source`. */
@@ -80,9 +121,28 @@ cbm_site_answer_t cbm_pipeline_site_bind_call(cbm_site_file_t *sf, const CBMCall
cbm_site_answer_t cbm_pipeline_site_bind_usage(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *source);
/* Main's chain drew a USAGE edge to `target` at a usage the layer answered
* POSSIBLE (both usage resolvers call it right after drawing). */
void cbm_pipeline_site_bind_usage_drawn(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *target);
/* The properties of a USAGE edge the layer draws: the usage's name, the
* answer's confidence and strategy. */
void cbm_pipeline_site_usage_props(char *buf, size_t cap, const CBMUsage *usage,
cbm_site_verdict_t verdict);
/* End one file: after its last site, with the buffer its edges went to
* (the run's graph on the sequential route, the worker's edge buffer on the
* parallel one). Draws what POSSIBLE answers leave to this step. */
void cbm_pipeline_site_bind_end(cbm_site_file_t *sf, cbm_gbuf_t *edges);
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
/* Add a mark: every call and usage named `name` that the layer is asked
* about, in a file of any language, answers `verdict` with the node
* `target_qn` (PROVEN or POSSIBLE). Up to sixteen marks; a NULL name clears
* them. Set only while no index runs. */
void cbm_pipeline_site_bind_test_mark(const char *name, const char *target_qn,
cbm_site_verdict_t verdict);
#endif
#endif /* CBM_SITE_BIND_H */
+15
View File
@@ -0,0 +1,15 @@
module CxApp
class CxBase
def label
"base"
end
end
class CxHelper
def assist(text)
widget = CxWidget.new
widget.label
widget.name + text
end
end
end
+14
View File
@@ -0,0 +1,14 @@
# Rails-shaped pair: no require, the constant is found through the global
# namespace, so every call below is a cross-file resolution.
module CxApp
class CxWidget < CxBase
def render
helper = CxHelper.new
helper.assist(name)
end
def name
"widget"
end
end
end
+1 -1
View File
@@ -712,7 +712,7 @@ TEST(repro_call_node_behavior_objectscript_udl_method_call) {
CBM_LANG_OBJECTSCRIPT_UDL,
"Behavior.cls",
OBJECTSCRIPT_METHOD_SOURCE,
"method_call",
"do_parameter",
"a typed ObjectScript receiver resolves one exact instance-method call without "
"consuming its argument usage"};
return run_objectscript_call_behavior(&test_case, "repro.Behavior.Sample.Behavior.run",
+4 -5
View File
@@ -59,9 +59,9 @@ typedef struct {
} CallNodeManifestEntry;
enum {
EXPECTED_HISTORICAL_CALL_NODE_TOTAL = 226,
EXPECTED_ACTIVE_PRIMARY_TOTAL = 196,
EXPECTED_DIRECT_CALLS = 160,
EXPECTED_HISTORICAL_CALL_NODE_TOTAL = 225,
EXPECTED_ACTIVE_PRIMARY_TOTAL = 195,
EXPECTED_DIRECT_CALLS = 159,
EXPECTED_CONSTRUCTOR_CALLS = 22,
EXPECTED_OPERATOR_CALLS = 12,
EXPECTED_IMPLICIT_CALLS = 2,
@@ -70,7 +70,7 @@ enum {
EXPECTED_CALLEE_WRAPPERS = 8,
EXPECTED_ARGUMENT_WRAPPERS = 1,
EXPECTED_CONTROL_OR_DOCUMENT_NONCALLS = 6,
EXPECTED_PRIMARY_OWNERS = 196,
EXPECTED_PRIMARY_OWNERS = 195,
EXPECTED_SYNTHETIC_OWNERS = 10,
EXPECTED_NO_CALL_EDGE_OWNERS = 20,
EXPECTED_PRIMARY_OPERATOR_CALLS = 4,
@@ -310,7 +310,6 @@ static const CallNodeManifestEntry CALL_NODE_MANIFEST[] = {
ENTRY(CBM_LANG_MOJO, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
ENTRY(CBM_LANG_OBJECTSCRIPT_UDL, "class_method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
true),
ENTRY(CBM_LANG_OBJECTSCRIPT_UDL, "method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
ENTRY(CBM_LANG_OBJECTSCRIPT_UDL, "relative_dot_method", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
true),
ENTRY(CBM_LANG_OBJECTSCRIPT_UDL, "macro", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+99
View File
@@ -8,9 +8,17 @@
* Cluster (TIER A, in-process via cbm_extract_file):
* #554 — C++ out-of-line method CALLS source = Module, not enclosing Method
* (more added per wave: #495 #521 #382 #408 #523 #56 #333)
* #2998 — COBOL external scanner livelock at EOF (hang, not a wrong edge)
*/
#include "test_framework.h"
#include "cbm.h"
#include <string.h>
#if !defined(_WIN32)
#include <errno.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
/* Convenience: extract, return result (caller frees). Mirrors test_extraction.c. */
static CBMFileResult *rx(const char *src, CBMLanguage lang, const char *proj, const char *path) {
@@ -87,7 +95,98 @@ TEST(repro_issue554_cpp_out_of_line_method_class_qualified) {
PASS();
}
/* ───────────────────────────────────────────────────────────────────
* #2998 — COBOL external scanner livelocks the parser at EOF.
*
* Root cause: the vendored COBOL scanner's LINE_PREFIX_COMMENT loop advanced
* while get_column() <= 5 without checking lookahead == 0. tree-sitter's
* advance() is a no-op at EOF (the column never increments), so any input that
* reaches EOF at column <= 5 — e.g. a .cob file shorter than 6 bytes, or the
* virtual empty line after a trailing "\n" in the right parser state — spun
* the scanner forever at 100% CPU. A second hazard emitted a zero-length
* COMMENT_ENTRY token when start_with_word() bailed at "\n"/EOF without
* consuming, another livelock class.
*
* Expected: extraction RETURNS (the hang itself is the failure mode; the
* fork + CPU-time-cap harness below turns a regression back into a RED test
* instead of a hung CI job), and the canonical valid-program fixture still
* extracts PROGRAM-ID. Actual (buggy): never returns; last worker-log line
* "pass.start pass=definitions".
* ─────────────────────────────────────────────────────────────────── */
#if !defined(_WIN32)
/* CPU seconds the child may spend. Parsing these few bytes costs microseconds
* even under sanitizers; the livelock spends CPU without bound. */
enum { REPRO2998_CPU_SECONDS = 5 };
/* Parse src in a forked child whose CPU time is capped (RLIMIT_CPU), and wait
* for it with one blocking waitpid. A livelock burns CPU and is stopped by
* SIGXCPU; a busy host only delays the child without spending its CPU time, so
* the verdict does not depend on wall-clock time and nothing polls or sleeps.
* Returns the child's exit code (0 = extraction returned), 128 + the signal
* that stopped it (SIGXCPU/SIGKILL = the livelock reproduced), -2 on fork
* failure, -3 if the child could not be waited for. */
static int repro2998_parse_cpu_capped(const char *src, CBMLanguage lang, const char *path) {
fflush(NULL);
pid_t pid = fork();
if (pid < 0)
return -2;
if (pid == 0) {
struct rlimit no_core = {0, 0};
struct rlimit cpu = {REPRO2998_CPU_SECONDS, REPRO2998_CPU_SECONDS + 1};
(void)setrlimit(RLIMIT_CORE, &no_core);
(void)setrlimit(RLIMIT_CPU, &cpu);
CBMFileResult *r = cbm_extract_file(src, (int)strlen(src), lang, "t", path, 0, NULL, NULL);
if (r)
cbm_free_result(r);
_exit(0); /* reaching _exit at all is what the bug took away */
}
int status = 0;
pid_t got;
do {
got = waitpid(pid, &status, 0);
} while (got < 0 && errno == EINTR);
if (got != pid)
return -3;
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
TEST(repro_issue2998_cobol_scanner_eof_livelock) {
/* EOF lands inside the LINE_PREFIX_COMMENT column scan: shorter than
* column 6, or a trailing newline leaving the lexer at column 0 of the
* virtual empty last line. */
ASSERT_EQ(repro2998_parse_cpu_capped("X", CBM_LANG_COBOL, "m.cob"), 0);
ASSERT_EQ(repro2998_parse_cpu_capped("*<<", CBM_LANG_COBOL, "m.cob"), 0);
ASSERT_EQ(repro2998_parse_cpu_capped("X\n", CBM_LANG_COBOL, "m.cob"), 0);
ASSERT_EQ(repro2998_parse_cpu_capped("display 1.\n", CBM_LANG_COBOL, "m.cob"), 0);
PASS();
}
TEST(repro_issue2998_cobol_valid_program_still_extracts) {
/* The EOF/zero-length guards must not break the happy path: the canonical
* fixed-format fixture (same as the cobol row in grammar_cases.h) still
* yields its PROGRAM-ID definition. */
CBMFileResult *r = rx(" IDENTIFICATION DIVISION.\n"
" PROGRAM-ID. FOO.\n"
" PROCEDURE DIVISION.\n"
" MAIN-PARA.\n"
" STOP RUN.\n",
CBM_LANG_COBOL, "t", "a.cob");
ASSERT_NOT_NULL(r);
int saw_foo = 0;
for (int i = 0; r && i < r->defs.count; i++)
if (r->defs.items[i].name && strcmp(r->defs.items[i].name, "FOO") == 0)
saw_foo = 1;
cbm_free_result(r);
ASSERT_TRUE(saw_foo);
PASS();
}
#endif /* !_WIN32 */
/* ── Suite ──────────────────────────────────────────────────────── */
SUITE(repro_extraction) {
RUN_TEST(repro_issue554_cpp_out_of_line_method_class_qualified);
#if !defined(_WIN32)
RUN_TEST(repro_issue2998_cobol_scanner_eof_livelock);
RUN_TEST(repro_issue2998_cobol_valid_program_still_extracts);
#endif
}
+2 -2
View File
@@ -17130,10 +17130,10 @@ TEST(clsp_issue1527_depth_failure_reports_all_entry_points) {
} else {
CBMLSPStatus status =
mode == 0 ? cbm_run_c_lsp_cross_status(&arena, src, (int)strlen(src), "test", true,
defs, 2, NULL, NULL, 0, NULL, &out)
defs, 2, NULL, NULL, 0, NULL, &out, true)
: cbm_run_c_lsp_cross_with_registry_status(&arena, src, (int)strlen(src),
"test", true, &overlay, NULL,
NULL, 0, NULL, &out);
NULL, 0, NULL, &out, true);
correct = correct && status == CBM_LSP_DEPTH_EXCEEDED;
}
correct = correct && out.count == 0;
+17 -2
View File
@@ -5555,7 +5555,22 @@ TEST(cli_skill_files_content) {
/* Reference capabilities */
ASSERT(strstr(sk[0].content, "query_graph") != NULL);
ASSERT(strstr(sk[0].content, "Cypher") != NULL);
ASSERT(strstr(sk[0].content, "15 MCP Tools") != NULL);
ASSERT(strstr(sk[0].content, "17 MCP Tools") != NULL);
ASSERT(strstr(sk[0].content, "15 MCP Tools") == NULL);
ASSERT(strstr(sk[0].content, "WHERE NOT EXISTS { (f)<-[:CALLS]-() } AND NOT EXISTS { "
"(f)<-[:CALL_REFERENCE]-() }") != NULL);
ASSERT(strstr(sk[0].content, "not natural-language sentences") != NULL);
/* Every tool the server registers is named in the installed skill, so the
* list cannot drift from the server again (it missed get_file_outline and
* compare_graphs). Names are matched with their backticks. */
for (int t = 0; t < cbm_mcp_tool_count(); t++) {
char quoted[96];
snprintf(quoted, sizeof(quoted), "`%s`", cbm_mcp_tool_name(t));
if (!strstr(sk[0].content, quoted)) {
printf(" installed skill does not name the tool %s\n", quoted);
}
ASSERT(strstr(sk[0].content, quoted) != NULL);
}
/* Gotchas section */
ASSERT(strstr(sk[0].content, "Gotchas") != NULL);
@@ -12608,7 +12623,7 @@ TEST(cli_codex_skill_migrates_every_released_legacy_payload) {
cbm_cli_set_client_selection_for_testing("codex");
size_t released_count = cbm_cli_released_skill_content_count();
bool migrated_all = released_count == 4U;
bool migrated_all = released_count == 5U;
for (size_t i = 0U; migrated_all && i < released_count; i++) {
const char *released = cbm_cli_released_skill_content_at(i);
test_mkdirp(legacy_dir);
+111
View File
@@ -1907,6 +1907,49 @@ TEST(cypher_exists_no_callers) {
PASS();
}
TEST(cypher_skill_dead_code_recipe_excludes_referenced_callbacks) {
/* The installed skill's dead-code recipe: no inbound CALLS and no inbound
* CALL_REFERENCE, one edge type per EXISTS. OnEvent is a callback that
* Register passes by reference, so it is not a candidate; HandleOrder and
* Register have neither kind of caller. NOT EXISTS on CALLS alone would
* also list OnEvent. */
cbm_store_t *s = setup_cypher_store();
cbm_node_t reg = {.project = "test",
.label = "Function",
.name = "Register",
.qualified_name = "test.Register",
.file_path = "event.go"};
cbm_node_t cb = {.project = "test",
.label = "Function",
.name = "OnEvent",
.qualified_name = "test.OnEvent",
.file_path = "event.go"};
int64_t reg_id = cbm_store_upsert_node(s, &reg);
int64_t cb_id = cbm_store_upsert_node(s, &cb);
cbm_edge_t ref = {
.project = "test", .source_id = reg_id, .target_id = cb_id, .type = "CALL_REFERENCE"};
cbm_store_insert_edge(s, &ref);
cbm_cypher_result_t r = {0};
int rc = cbm_cypher_execute(s,
"MATCH (f:Function) WHERE NOT EXISTS { (f)<-[:CALLS]-() } AND NOT "
"EXISTS { (f)<-[:CALL_REFERENCE]-() } RETURN f.name",
"test", 0, &r);
ASSERT_EQ(rc, 0);
ASSERT_EQ(r.row_count, 2);
bool handle = false;
bool regd = false;
for (int i = 0; i < r.row_count; i++) {
ASSERT(strcmp(r.rows[i][0], "OnEvent") != 0);
handle = handle || strcmp(r.rows[i][0], "HandleOrder") == 0;
regd = regd || strcmp(r.rows[i][0], "Register") == 0;
}
ASSERT(handle && regd);
cbm_cypher_result_free(&r);
cbm_store_close(s);
PASS();
}
TEST(cypher_exists_has_outgoing_calls) {
/* EXISTS { (f)-[:CALLS]->() } → functions that call something.
* HandleOrder (→ValidateOrder, →LogError) and ValidateOrder (→SubmitOrder). */
@@ -6291,6 +6334,70 @@ TEST(cypher_stream_chunks_match_single_pass) {
PASS();
}
/* WITH and RETURN must agree on nullable node, edge and property counts,
* while COUNT(*) still counts the OPTIONAL MATCH fallback row. */
TEST(cypher_with_count_optional_nulls) {
cbm_store_t *s = setup_cypher_store();
const char *queries[] = {
"MATCH (f:Function) OPTIONAL MATCH (x)-[r:CALLS]->(f) "
"RETURN f.name, count(x), count(r), count(x.name), count(DISTINCT x.name), count(*) "
"ORDER BY f.name",
"MATCH (f:Function) OPTIONAL MATCH (x)-[r:CALLS]->(f) "
"WITH f, count(x) AS c, count(r) AS edges, count(x.name) AS names, "
"count(DISTINCT x.name) AS unique_names, count(*) AS rows "
"RETURN f.name, c, edges, names, unique_names, rows ORDER BY f.name",
};
for (size_t qi = 0; qi < sizeof(queries) / sizeof(queries[0]); qi++) {
cbm_cypher_result_t r = {0};
ASSERT_EQ(cbm_cypher_execute(s, queries[qi], "test", 0, &r), 0);
ASSERT_EQ(r.row_count, 4);
ASSERT_STR_EQ(r.rows[0][0], "HandleOrder");
for (int row = 0; row < r.row_count; row++) {
for (int col = 1; col <= 4; col++) {
ASSERT_STR_EQ(r.rows[row][col], row == 0 ? "0" : "1");
}
ASSERT_STR_EQ(r.rows[row][5], "1");
}
cbm_cypher_result_free(&r);
}
cbm_store_close(s);
PASS();
}
TEST(cypher_with_count_zero_callers) {
cbm_store_t *s = setup_cypher_store();
cbm_cypher_result_t r = {0};
ASSERT_EQ(cbm_cypher_execute(s,
"MATCH (f:Function) OPTIONAL MATCH (x)-[:CALLS]->(f) "
"WITH f, count(x) AS c WHERE c = 0 RETURN f.name, c",
"test", 0, &r),
0);
ASSERT_EQ(r.row_count, 1);
ASSERT_STR_EQ(r.rows[0][0], "HandleOrder");
ASSERT_STR_EQ(r.rows[0][1], "0");
cbm_cypher_result_free(&r);
cbm_store_close(s);
PASS();
}
TEST(cypher_with_count_global_optional_null) {
cbm_store_t *s = setup_cypher_store();
cbm_cypher_result_t r = {0};
ASSERT_EQ(
cbm_cypher_execute(s,
"MATCH (f:Function) WHERE f.name = 'HandleOrder' "
"OPTIONAL MATCH (x)-[:CALLS]->(f) WITH count(x) AS c, count(*) AS rows "
"RETURN c, rows",
"test", 0, &r),
0);
ASSERT_EQ(r.row_count, 1);
ASSERT_STR_EQ(r.rows[0][0], "0");
ASSERT_STR_EQ(r.rows[0][1], "1");
cbm_cypher_result_free(&r);
cbm_store_close(s);
PASS();
}
/* OPTIONAL fallback rows (a start node with no match keeps its row, target
* unbound) sit between the expanded rows of their neighbours in every chunk
* layout; the multi-pattern form keeps its single pass. */
@@ -6542,6 +6649,7 @@ SUITE(cypher) {
RUN_TEST(cypher_issue874_where_unsupported_func_error);
RUN_TEST(cypher_multi_prop_projection_no_alias);
RUN_TEST(cypher_exists_no_callers);
RUN_TEST(cypher_skill_dead_code_recipe_excludes_referenced_callbacks);
RUN_TEST(cypher_exists_has_outgoing_calls);
RUN_TEST(cypher_exec_calls_relationship);
RUN_TEST(cypher_exec_calls_with_where);
@@ -6714,6 +6822,9 @@ SUITE(cypher) {
RUN_TEST(cypher_grouping_keeps_first_seen_groups);
/* Streamed execution: chunked start set == single pass */
RUN_TEST(cypher_stream_chunks_match_single_pass);
RUN_TEST(cypher_with_count_optional_nulls);
RUN_TEST(cypher_with_count_zero_callers);
RUN_TEST(cypher_with_count_global_optional_null);
RUN_TEST(cypher_stream_optional_across_chunks);
RUN_TEST(cypher_stream_limit_and_max_rows_across_chunks);
RUN_TEST(cypher_stream_default_chunk_boundary);
+103
View File
@@ -53,6 +53,15 @@
#include <unistd.h>
#ifdef __linux__
#include <sched.h> /* #1830 userns real smoke: unshare(CLONE_NEWUSER). */
#if defined(__has_include) && __has_include(<linux/landlock.h>)
#include <linux/landlock.h> /* #3014 Landlock real smoke. */
#include <sys/prctl.h>
#include <sys/syscall.h>
#if defined(SYS_landlock_create_ruleset) && defined(SYS_landlock_add_rule) && \
defined(SYS_landlock_restrict_self)
#define IPC_TEST_HAS_LANDLOCK 1
#endif
#endif
#endif
#ifdef __APPLE__
#include <membership.h>
@@ -5394,6 +5403,99 @@ TEST(daemon_ipc_posix_private_directory_rejects_world_writable_ancestor) {
PASS();
}
/* #3014: a process confined by Landlock that may not list "/", or any other
* ancestor of its private directory, must still be able to secure that
* directory. The walk used to open every ancestor O_RDONLY|O_DIRECTORY, which
* Landlock counts as listing, so it failed at "/" in any sandbox that handles
* LANDLOCK_ACCESS_FS_READ_DIR without granting it on the root; the daemon then
* exited with "could not load saved runtime settings".
*
* The child handles READ_DIR only and is granted it beneath this test's own
* parent directory, then creates and secures a private directory below it.
* Exit protocol, as the userns smoke: 0 secured, 1 refused, 2 Landlock is not
* available in this kernel, 3 the harness could not build its sandbox. */
TEST(daemon_ipc_linux_private_directory_secures_inside_landlock_issue3014) {
#ifdef IPC_TEST_HAS_LANDLOCK
char parent[TEST_PATH_CAP] = {0};
char cache[TEST_PATH_CAP] = {0};
bool paths_ok = false;
if (ipc_test_parent_new(parent, "private-cache-landlock")) {
int cache_written = snprintf(cache, sizeof(cache), "%s/cache", parent);
paths_ok = cache_written > 0 && cache_written < (int)sizeof(cache);
}
if (!paths_ok) {
ipc_test_remove_flat_dir(parent);
FAIL("could not create the Landlock smoke's parent directory");
}
pid_t child = fork();
if (child == 0) {
struct landlock_ruleset_attr ruleset = {.handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR};
int ruleset_fd = (int)syscall(SYS_landlock_create_ruleset, &ruleset, sizeof(ruleset), 0U);
if (ruleset_fd < 0) {
/* 2: the kernel has no Landlock; 4: the environment refuses it
* (EPERM, e.g. a container's seccomp filter); 3: anything else. */
_exit(errno == ENOSYS || errno == EOPNOTSUPP ? 2 : errno == EPERM ? 4 : 3);
}
struct landlock_path_beneath_attr beneath = {
.allowed_access = LANDLOCK_ACCESS_FS_READ_DIR,
.parent_fd = open(parent, O_PATH | O_CLOEXEC),
};
if (beneath.parent_fd < 0 ||
syscall(SYS_landlock_add_rule, ruleset_fd, LANDLOCK_RULE_PATH_BENEATH, &beneath, 0U) !=
0 ||
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 ||
syscall(SYS_landlock_restrict_self, ruleset_fd, 0U) != 0) {
_exit(3);
}
/* The sandbox must be real, or a pass below would prove nothing:
* listing "/" is refused from here on. */
int root_fd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (root_fd >= 0 || errno != EACCES) {
_exit(3);
}
_exit(cbm_daemon_ipc_private_directory_secure(cache) ? 0 : 1);
}
int status = 0;
if (child > 0) {
while (waitpid(child, &status, 0) < 0 && errno == EINTR) {}
}
struct stat secured = {0};
bool hardened = lstat(cache, &secured) == 0 && S_ISDIR(secured.st_mode) &&
secured.st_uid == geteuid() && (secured.st_mode & 07777) == 0700;
(void)rmdir(cache);
ipc_test_remove_flat_dir(parent);
if (child < 0) {
FAIL("fork failed for the Landlock smoke");
}
if (!WIFEXITED(status)) {
FAIL("Landlock probe did not exit normally (signalled) -- not a security verdict");
}
if (WEXITSTATUS(status) == 2) {
SKIP_PLATFORM("Landlock is not available in this Linux kernel");
}
if (WEXITSTATUS(status) == 4) {
SKIP_PLATFORM("this environment refuses Landlock (EPERM from landlock_create_ruleset, "
"e.g. a container's seccomp filter); the sandbox cannot be built here");
}
if (WEXITSTATUS(status) == 3) {
FAIL("Landlock smoke could not build a sandbox that refuses listing /");
}
if (WEXITSTATUS(status) != 0 && WEXITSTATUS(status) != 1) {
char unexpected[128];
(void)snprintf(unexpected, sizeof(unexpected),
"Landlock probe exited %d -- not a security verdict", WEXITSTATUS(status));
FAIL(unexpected);
}
ASSERT_EQ(0, WEXITSTATUS(status));
ASSERT_TRUE(hardened);
PASS();
#else
SKIP_PLATFORM("Landlock needs Linux with <linux/landlock.h> and the landlock syscall numbers");
#endif
}
TEST(daemon_ipc_posix_private_log_rejects_symlinks_and_is_owner_only) {
char parent[TEST_PATH_CAP] = {0};
char logs[TEST_PATH_CAP] = {0};
@@ -6240,6 +6342,7 @@ SUITE(daemon_ipc) {
RUN_TEST(daemon_ipc_posix_private_log_creates_first_ever_cache_tree_safely);
RUN_TEST(daemon_ipc_posix_private_directory_hardens_existing_cache_root);
RUN_TEST(daemon_ipc_posix_private_directory_rejects_world_writable_ancestor);
RUN_TEST(daemon_ipc_linux_private_directory_secures_inside_landlock_issue3014);
RUN_TEST(daemon_ipc_posix_private_log_rejects_symlinks_and_is_owner_only);
RUN_TEST(daemon_ipc_posix_rejects_non_socket_and_symlink_endpoints);
#ifndef _WIN32
+184
View File
@@ -884,6 +884,189 @@ TEST(ei_typescript_type_import) {
PASS();
}
/* Edges of `edge_type` from any node of `from_file` into any node of
* `to_file`; -1 on a store error. */
static int ei_file_to_file_edges(cbm_store_t *store, const char *project, const char *from_file,
const char *to_file, const char *edge_type) {
cbm_node_t *targets = NULL;
int target_count = 0;
if (cbm_store_find_nodes_by_file(store, project, to_file, &targets, &target_count) !=
CBM_STORE_OK) {
return -1;
}
int n = 0;
for (int i = 0; i < target_count; i++) {
cbm_edge_t *edges = NULL;
int edge_count = 0;
if (cbm_store_find_edges_by_target_type(store, targets[i].id, edge_type, &edges,
&edge_count) != CBM_STORE_OK) {
continue;
}
for (int j = 0; j < edge_count; j++) {
cbm_node_t source;
memset(&source, 0, sizeof(source));
if (cbm_store_find_node_by_id(store, edges[j].source_id, &source) == CBM_STORE_OK) {
n += source.file_path && strcmp(source.file_path, from_file) == 0;
cbm_node_free_fields(&source);
}
}
cbm_store_free_edges(edges, edge_count);
}
cbm_store_free_nodes(targets, target_count);
return n;
}
/* An ECMAScript import names one file (`./x`, `../x`, a tsconfig/jsconfig
* alias) or a package outside the tree (a `node:` URL, a Node builtin, a
* dependency a package.json declares from a registry). When that file has no
* node, or the package is not in the tree, the import binds nothing. Main's
* name fallbacks bound each of them to an unrelated project definition: the
* symbol-name fallback took a trailing segment of the specifier (`./App.vue`
* absent -> a test's App, `node:assert/strict` -> a spec's assert, `connect`
* -> the project's own connect, a missing `@app/lib/helper.util` -> helper),
* and the sibling-file fallback took the file beside the importer (`ws` ->
* ws.ts, `fs` -> fs.ts). Each such IMPORTS edge then fed an import_map CALLS
* edge. The controls must keep binding: a present dotted alias module (#2975),
* a workspace package declared `workspace:*`, a relative module, a relative
* `.vue` file, and a relative module in a dot-directory (`.theme`, as vite's
* `.vitepress`), whose Module QN drops the dot so Strategy 1 cannot reach it.
* `pad` above MIN_FILES_FOR_PARALLEL(50) runs the same fixture through the
* parallel pipeline. */
static int ei_es_unbound_import_case(int pad) {
enum { EI_ES_BASE = 16, EI_ES_MAX = EI_ES_BASE + 64 };
static char names[EI_ES_MAX][32];
static const char importer[] = "src/server/index.ts";
EILangFile f[EI_ES_MAX];
int n = 0;
f[n++] =
(EILangFile){"package.json", "{\"name\":\"fx-app\",\"private\":true,\"dependencies\":{"
"\"ws\":\"^8.18.0\",\"connect\":\"^3.7.0\",\"@fx/shared\":"
"\"workspace:*\"}}\n"};
f[n++] = (EILangFile){"tsconfig.json",
"{\"compilerOptions\":{\"baseUrl\":\".\",\"paths\":{\"@app/*\":"
"[\"src/*\"]}}}\n"};
f[n++] = (EILangFile){"packages/shared/package.json",
"{\"name\":\"@fx/shared\",\"main\":\"src/index.ts\"}\n"};
f[n++] = (EILangFile){"packages/shared/src/index.ts",
"export function sharedHelper(): number {\n return 1;\n}\n"};
f[n++] = (EILangFile){"src/cats/cat.service.ts",
"export class CatService {\n findAll(): string[] {\n"
" return [];\n }\n}\n"};
f[n++] = (EILangFile){"src/server/ws.ts", "export class WebSocketServer {\n"
" close(): void {}\n}\n"};
f[n++] = (EILangFile){"src/server/fs.ts",
"export function readFileSync(): string {\n return \"\";\n}\n"};
f[n++] = (EILangFile){"src/server/util.ts", "export function local(): number {\n"
" return 3;\n}\n"};
f[n++] =
(EILangFile){"src/server/Widget.vue", "<template><div /></template>\n<script>\n"
"export default { name: \"Widget\" };\n</script>\n"};
f[n++] = (EILangFile){"src/client/client.ts", "export function connect(): void {}\n"};
f[n++] = (EILangFile){"src/tests/app.spec.ts", "export function App(): void {}\n"};
f[n++] = (EILangFile){"src/tests/assert.spec.ts",
"export function assert(value: boolean): void {}\n"};
f[n++] = (EILangFile){"src/other/misc.ts", "export function helper(): number {\n"
" return 2;\n}\n"};
f[n++] = (EILangFile){importer, "import { WebSocketServer } from 'ws';\n"
"import connect from 'connect';\n"
"import { readFileSync } from 'fs';\n"
"import assert from 'node:assert/strict';\n"
"import { helper } from '@app/lib/helper.util';\n"
"import App from './App.vue';\n"
"import { CatService } from '@app/cats/cat.service';\n"
"import { sharedHelper } from '@fx/shared';\n"
"import { local } from './util';\n"
"import Widget from './Widget.vue';\n\n"
"export function start(): number {\n"
" assert(true);\n"
" connect();\n"
" readFileSync();\n"
" helper();\n"
" sharedHelper();\n"
" local();\n"
" new WebSocketServer();\n"
" new CatService();\n"
" return [App, Widget].length;\n"
"}\n"};
f[n++] = (EILangFile){"src/.theme/useTheme.ts", "export function useTheme(): number {\n"
" return 4;\n}\n"};
f[n++] = (EILangFile){"src/.theme/App.ts", "import { useTheme } from './useTheme';\n"
"export const theme = useTheme();\n"};
for (int i = 0; i < pad && n < EI_ES_MAX; i++) {
snprintf(names[n], sizeof(names[n]), "pad/mod_%02d.ts", i);
f[n] = (EILangFile){names[n], "export const filler = 0;\n"};
n++;
}
static const struct {
const char *file;
const char *why;
} decoys[] = {
{"src/tests/app.spec.ts", "missing relative file ./App.vue"},
{"src/other/misc.ts", "missing alias file @app/lib/helper.util"},
{"src/server/ws.ts", "declared npm dependency 'ws' beside ws.ts"},
{"src/client/client.ts", "declared npm dependency 'connect'"},
{"src/server/fs.ts", "Node builtin 'fs' beside fs.ts"},
{"src/tests/assert.spec.ts", "'node:assert/strict'"},
};
static const struct {
const char *importer;
const char *file;
const char *why;
} controls[] = {
{importer, "src/cats/cat.service.ts", "present dotted alias module @app/cats/cat.service"},
{importer, "packages/shared/src/index.ts", "workspace package @fx/shared"},
{importer, "src/server/util.ts", "relative module ./util"},
{importer, "src/server/Widget.vue", "relative file ./Widget.vue"},
{"src/.theme/App.ts", "src/.theme/useTheme.ts", "relative module in a dot-directory"},
};
EILangProj lp;
cbm_store_t *store = ei_index_files(&lp, f, n);
int ok = store != NULL;
for (size_t i = 0; store && i < sizeof(decoys) / sizeof(decoys[0]); i++) {
int imports = ei_file_to_file_edges(store, lp.project, importer, decoys[i].file, "IMPORTS");
int calls = ei_file_to_file_edges(store, lp.project, importer, decoys[i].file, "CALLS");
if (imports != 0 || calls != 0) {
fprintf(stderr, " [es-import pad=%d] %s: IMPORTS=%d CALLS=%d into %s (want 0/0)\n",
pad, decoys[i].why, imports, calls, decoys[i].file);
ok = 0;
}
}
for (size_t i = 0; store && i < sizeof(controls) / sizeof(controls[0]); i++) {
int imports = ei_file_to_file_edges(store, lp.project, controls[i].importer,
controls[i].file, "IMPORTS");
if (imports != 1) {
fprintf(stderr, " [es-import pad=%d] control %s: IMPORTS=%d into %s (want 1)\n", pad,
controls[i].why, imports, controls[i].file);
ok = 0;
}
}
int shared_calls = store ? ei_file_to_file_edges(store, lp.project, importer,
"packages/shared/src/index.ts", "CALLS")
: -1;
if (shared_calls < 1) {
fprintf(stderr, " [es-import pad=%d] control sharedHelper(): CALLS=%d (want >=1)\n", pad,
shared_calls);
ok = 0;
}
int total = store ? cbm_store_count_edges_by_type(store, lp.project, "IMPORTS") : -1;
if (total != (int)(sizeof(controls) / sizeof(controls[0]))) {
fprintf(stderr, " [es-import pad=%d] IMPORTS total=%d (want %d)\n", pad, total,
(int)(sizeof(controls) / sizeof(controls[0])));
ok = 0;
}
ei_cleanup(&lp, store);
return ok;
}
TEST(ei_es_import_of_missing_file_or_external_package_binds_nothing) {
/* Both legs run before asserting so a failure diagnoses both drivers. */
int sequential_ok = ei_es_unbound_import_case(0);
int parallel_ok = ei_es_unbound_import_case(60);
ASSERT_TRUE(sequential_ok);
ASSERT_TRUE(parallel_ok);
PASS();
}
/* ═══════════════════════════════════════════════════════════════════════════
* GREEN GUARD — Go
*
@@ -3275,6 +3458,7 @@ SUITE(edge_imports) {
RUN_TEST(ei_typescript_subdir_import);
RUN_TEST(ei_typescript_re_export);
RUN_TEST(ei_typescript_type_import);
RUN_TEST(ei_es_import_of_missing_file_or_external_package_binds_nothing);
/* ── GREEN GUARDS — Go (must stay passing) ── */
RUN_TEST(ei_go_same_module_import);
+442
View File
@@ -1803,6 +1803,31 @@ static const char *def_return_type(CBMFileResult *r, const char *name) {
return NULL;
}
/* Methods in an `impl` block publish their declared return type like a free
* `fn` does; a method without `->` has none. */
TEST(rust_impl_method_return_type) {
CBMFileResult *r = extract("struct Matcher;\n"
"pub fn free() -> u8 { 0 }\n"
"impl Matcher {\n"
" pub fn build(&self, p: &str) -> Result<Matcher, Error> { todo!() }\n"
" fn name(&self) -> &'static str { \"m\" }\n"
" fn reset(&mut self) {}\n"
"}\n"
"impl Clone for Matcher {\n"
" fn clone(&self) -> Self { Matcher }\n"
"}\n",
CBM_LANG_RUST, "t", "matcher.rs");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_STR_EQ(def_return_type(r, "free"), "u8");
ASSERT_STR_EQ(def_return_type(r, "build"), "Result<Matcher, Error>");
ASSERT_STR_EQ(def_return_type(r, "name"), "&'static str");
ASSERT_STR_EQ(def_return_type(r, "clone"), "Self");
ASSERT_NULL(def_return_type(r, "reset"));
cbm_free_result(r);
PASS();
}
/* A member's name is the identifier at the bottom of its declarator, and its
* type is everything around that identifier, in the canonical spelling of the
* function return types below. Taking the first declarator's first child as
@@ -4830,6 +4855,281 @@ TEST(cpp_gtest_f_unique_name_issue1266) {
PASS();
}
/* A call written in a GoogleTest body belongs to the test's own node. The def
* walk names TEST(Suite, Case) TEST_Suite_Case (#1266), so the three places
* that name the caller of a call must name it the same way: the call-scope
* walk (CBMCall.enclosing_func_qn), the enclosing-function helper behind the
* reference extractors (CBMUsage.enclosing_func_qn) and the C/C++ engine
* (CBMResolvedCall.caller_qn). Under the bare macro name no node exists, and
* the pipeline sources every such call at the file. One row per macro form
* the def walk renames, plus one inside a namespace. */
static const char gtest_caller_src[] =
"int helper_sum(int a, int b) { return a + b; }\n"
"int kLimit = 3;\n"
"TEST(WidgetSuite, Adds) { helper_sum(1, kLimit); }\n"
"TEST_F(WidgetFixture, Runs) { helper_sum(2, kLimit); }\n"
"TEST_P(WidgetParam, Each) { helper_sum(3, kLimit); }\n"
"TYPED_TEST(WidgetTyped, Holds) { helper_sum(4, kLimit); }\n"
"TYPED_TEST_P(WidgetTypedP, Keeps) { helper_sum(5, kLimit); }\n"
"namespace demo {\n"
"TEST(NsSuite, Inside) { helper_sum(6, kLimit); }\n"
"}\n";
static const char *const gtest_caller_names[] = {
"TEST_WidgetSuite_Adds", "TEST_F_WidgetFixture_Runs", "TEST_P_WidgetParam_Each",
"TYPED_TEST_WidgetTyped_Holds", "TYPED_TEST_P_WidgetTypedP_Keeps", "demo.TEST_NsSuite_Inside"};
static int count_resolved_from(const CBMFileResult *r, const char *caller_qn,
const char *callee_suffix) {
int count = 0;
size_t sl = strlen(callee_suffix);
for (int i = 0; i < r->resolved_calls.count; i++) {
const CBMResolvedCall *rc = &r->resolved_calls.items[i];
size_t cl = rc->callee_qn ? strlen(rc->callee_qn) : 0;
if (rc->caller_qn && strcmp(rc->caller_qn, caller_qn) == 0 && cl >= sl &&
strcmp(rc->callee_qn + cl - sl, callee_suffix) == 0) {
count++;
}
}
return count;
}
TEST(cpp_gtest_body_caller_is_test_node) {
CBMFileResult *r = extract(gtest_caller_src, CBM_LANG_CPP, "t", "widget_test.cc");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
/* Inputs reached: every body's call and reference was extracted. */
ASSERT_EQ(count_calls_named(r, "helper_sum"), 6);
ASSERT_EQ(count_usages_named(r, "kLimit"), 6);
for (size_t i = 0; i < sizeof(gtest_caller_names) / sizeof(gtest_caller_names[0]); i++) {
const CBMDefinition *def = find_def_in_module(r, gtest_caller_names[i]);
if (!def) {
printf(" no definition %s\n", gtest_caller_names[i]);
}
ASSERT_NOT_NULL(def);
int calls = count_calls_from(r, "helper_sum", def->qualified_name);
int refs = count_usages_from(r, "kLimit", def->qualified_name);
int lsp = count_resolved_from(r, def->qualified_name, ".helper_sum");
if (calls != 1 || refs != 1 || lsp != 1) {
printf(" %s: calls %d, references %d, engine %d\n", def->qualified_name, calls, refs,
lsp);
}
ASSERT_EQ(calls, 1); /* RED on 08a7a586: the call-scope walk says <module>.TEST */
ASSERT_EQ(refs, 1); /* RED on 08a7a586: cbm_enclosing_func_qn says <module>.TEST */
ASSERT_EQ(lsp, 1); /* RED on 08a7a586: the engine's caller is <module>.TEST */
}
/* Nothing is left on the bare macro names (the positive rows above are the
* partner: the same calls, under the test names). */
static const char *const bare[] = {"TEST", "TEST_F", "TEST_P",
"TYPED_TEST", "TYPED_TEST_P", "demo.TEST"};
for (size_t i = 0; i < sizeof(bare) / sizeof(bare[0]); i++) {
char qn[256];
snprintf(qn, sizeof(qn), "%s.%s", r->module_qn, bare[i]);
ASSERT_EQ(count_calls_from(r, "helper_sum", qn), 0);
ASSERT_EQ(count_usages_from(r, "kLimit", qn), 0);
ASSERT_EQ(count_resolved_from(r, qn, ".helper_sum"), 0);
}
cbm_free_result(r);
PASS();
}
/* Every C++ file is also read a second time after the built-in preprocessor,
* and that view can spell a test's head differently: a project macro among the
* arguments is expanded, comments are gone, and a project's own TEST macro is
* replaced by its expansion. The second view must still name the body as the
* raw view's definition, or the same call is drawn from the test node and, a
* second time, from the File. The definition's name drops comments from the
* head's arguments. Rows of each view are counted per origin, so the second
* view is shown to have run (the positive partner of "no other caller"). */
static int pp_rows(const CBMFileResult *r, const char *callee, const char *ref,
const char *caller_qn, CBMSourceOrigin origin, int *calls, int *engine,
int *refs) {
*calls = *engine = *refs = 0;
for (int i = 0; i < r->calls.count; i++) {
const CBMCall *c = &r->calls.items[i];
*calls += c->callee_name && strcmp(c->callee_name, callee) == 0 &&
c->source_origin == origin && c->enclosing_func_qn &&
(!caller_qn || strcmp(c->enclosing_func_qn, caller_qn) == 0);
}
for (int i = 0; i < r->resolved_calls.count; i++) {
const CBMResolvedCall *rc = &r->resolved_calls.items[i];
size_t cl = rc->callee_qn ? strlen(rc->callee_qn) : 0;
size_t nl = strlen(callee);
*engine += rc->kind == CBM_RESOLVED_INVOCATION && rc->source_origin == origin && cl > nl &&
rc->callee_qn[cl - nl - 1] == '.' &&
strcmp(rc->callee_qn + cl - nl, callee) == 0 && rc->caller_qn &&
(!caller_qn || strcmp(rc->caller_qn, caller_qn) == 0);
}
for (int i = 0; i < r->usages.count; i++) {
const CBMUsage *u = &r->usages.items[i];
*refs += u->ref_name && strcmp(u->ref_name, ref) == 0 && u->source_origin == origin &&
u->enclosing_func_qn &&
(!caller_qn || strcmp(u->enclosing_func_qn, caller_qn) == 0);
}
return *calls + *engine + *refs;
}
/* `callee` and `ref` occur in this test's body only. */
static int assert_pp_view_names_raw_test(const CBMFileResult *r, const char *def_name,
const char *callee, const char *ref) {
const CBMDefinition *def = NULL;
for (int i = 0; i < r->defs.count; i++) {
if (r->defs.items[i].name && strcmp(r->defs.items[i].name, def_name) == 0) {
def = &r->defs.items[i];
}
}
if (!def) {
printf(" no definition named %s\n", def_name);
}
ASSERT_NOT_NULL(def);
int any[3];
int own[3];
for (int origin = 0; origin < 2; origin++) {
CBMSourceOrigin o = origin ? CBM_SOURCE_ORIGIN_PREPROCESSED : CBM_SOURCE_ORIGIN_RAW;
(void)pp_rows(r, callee, ref, NULL, o, &any[0], &any[1], &any[2]);
(void)pp_rows(r, callee, ref, def->qualified_name, o, &own[0], &own[1], &own[2]);
if (any[0] != own[0] || any[1] != own[1] || any[2] != own[2]) {
printf(
" %s, %s view: calls %d of %d, engine %d of %d, references %d of %d at the test\n",
def_name, origin ? "preprocessed" : "raw", own[0], any[0], own[1], any[1], own[2],
any[2]);
}
/* Both views saw the call, its resolution and the reference. */
ASSERT_GTE(any[0], 1);
ASSERT_GTE(any[1], 1);
ASSERT_GTE(any[2], 1);
/* RED on cbm-ctest-caller-c2a10ffd: the preprocessed view names the
* test from its own head text, a name no definition carries. */
ASSERT_EQ(own[0], any[0]);
ASSERT_EQ(own[1], any[1]);
ASSERT_EQ(own[2], any[2]);
}
return 0;
}
TEST(cpp_gtest_preprocessed_view_names_the_raw_test) {
static const char suites[] = "int kVia = 1;\n"
"int kBlock = 2;\n"
"int kLine = 3;\n"
"int via_target(int v) { return v; }\n"
"int block_target(int v) { return v; }\n"
"int line_target(int v) { return v; }\n"
"#define MY_SUITE RealSuite\n"
"TEST(MY_SUITE, ViaMacro) { via_target(kVia); }\n"
"TEST(CommentSuite /* c */, Commented) { block_target(kBlock); }\n"
"TEST(LineCommentSuite, // why\n"
" LineCommented) {\n"
" line_target(kLine);\n"
"}\n";
CBMFileResult *r = extract(suites, CBM_LANG_CPP, "t", "misc_test.cc");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
/* The definitions keep the raw head's names, without its comments
* (RED on cbm-ctest-caller-c2a10ffd: TEST_CommentSuite_/\* c *\/). */
ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_MY_SUITE_ViaMacro", "via_target", "kVia"), 0);
ASSERT_EQ(
assert_pp_view_names_raw_test(r, "TEST_CommentSuite_Commented", "block_target", "kBlock"),
0);
ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_LineCommentSuite_LineCommented", "line_target",
"kLine"),
0);
cbm_free_result(r);
/* A project's own one-argument TEST macro: the def walk names its use
* TEST_alpha, the second view sees `void test_alpha()`. */
static const char own[] = "int kShared = 1;\n"
"int helper_b(int v) { return v; }\n"
"#define TEST(name) void test_##name()\n"
"TEST(alpha) { helper_b(kShared); }\n";
r = extract(own, CBM_LANG_CPP, "t", "own_test_macro.cc");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(assert_pp_view_names_raw_test(r, "TEST_alpha", "helper_b", "kShared"), 0);
cbm_free_result(r);
PASS();
}
/* Two tests on one line share their raw line span, so the second view cannot
* tell them apart by lines: each keeps the name its own head gives, which is
* the raw view's name when the two heads read the same. */
TEST(cpp_gtest_preprocessed_view_one_line_pair) {
static const char src[] = "int kShared = 1;\n"
"int helper_c(int v) { return v; }\n"
"#define UNUSED_MACRO 1\n"
"TEST(PairSuite, First) { helper_c(kShared); } "
"TEST(PairSuite, Second) { helper_c(kShared); }\n";
CBMFileResult *r = extract(src, CBM_LANG_CPP, "t", "pair_test.cc");
ASSERT_NOT_NULL(r);
const CBMDefinition *first = find_def_in_module(r, "TEST_PairSuite_First");
const CBMDefinition *second = find_def_in_module(r, "TEST_PairSuite_Second");
ASSERT_NOT_NULL(first);
ASSERT_NOT_NULL(second);
int any[3];
int a[3];
int b[3];
(void)pp_rows(r, "helper_c", "kShared", NULL, CBM_SOURCE_ORIGIN_PREPROCESSED, &any[0], &any[1],
&any[2]);
(void)pp_rows(r, "helper_c", "kShared", first->qualified_name, CBM_SOURCE_ORIGIN_PREPROCESSED,
&a[0], &a[1], &a[2]);
(void)pp_rows(r, "helper_c", "kShared", second->qualified_name, CBM_SOURCE_ORIGIN_PREPROCESSED,
&b[0], &b[1], &b[2]);
ASSERT_EQ(any[0], 2); /* the second view ran and saw both calls */
ASSERT_EQ(a[0], 1);
ASSERT_EQ(b[0], 1);
ASSERT_EQ(a[1] + b[1], any[1]);
cbm_free_result(r);
PASS();
}
/* The preprocessed view finds the raw test of a body by a binary search over
* the file's test spans, sorted once per file, and over the view's indexed
* top-level definitions: counted work (spans indexed, nodes walked, search
* steps) grows like n log n with the number of tests, never n^2. So it pins
* "not worse than main's growth": main's own calls pass on such a file grows
* faster than n log n (not counted here), and this change adds no growth of
* its own beyond n log n. */
static uint64_t pp_test_span_work(int tests, int *at_tests) {
size_t cap = (size_t)tests * 64 + 256;
char *src = malloc(cap);
if (!src) {
return UINT64_MAX;
}
int off = snprintf(src, cap, "int span_target() { return 0; }\n#define SPAN_UNUSED 1\n");
for (int i = 0; i < tests; i++) {
off += snprintf(src + off, cap - (size_t)off,
"TEST(SpanSuite, Case%d) { span_target(); }\n", i);
}
cbm_test_span_test_reset();
CBMFileResult *r = cbm_extract_file(src, off, CBM_LANG_CPP, "t", "span_test.cc", 0, NULL, NULL);
free(src);
uint64_t work = r ? cbm_test_span_test_work() : UINT64_MAX;
*at_tests = 0;
for (int i = 0; r && i < r->calls.count; i++) {
const CBMCall *c = &r->calls.items[i];
*at_tests += c->source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED && c->callee_name &&
strcmp(c->callee_name, "span_target") == 0 && c->enclosing_func_qn &&
strstr(c->enclosing_func_qn, ".TEST_SpanSuite_Case") != NULL;
}
cbm_free_result(r);
return work;
}
TEST(cpp_gtest_preprocessed_view_lookup_growth) {
enum { SMALL = 100, BIG = 1000, WORK_RATIO_MAX = 20 };
int small_at = 0;
int big_at = 0;
uint64_t small = pp_test_span_work(SMALL, &small_at);
uint64_t big = pp_test_span_work(BIG, &big_at);
fprintf(stderr, " [pp-test-spans] work(%d)=%llu work(%d)=%llu\n", SMALL,
(unsigned long long)small, BIG, (unsigned long long)big);
ASSERT_TRUE(small != UINT64_MAX && big != UINT64_MAX);
ASSERT_EQ(small_at, SMALL); /* the second view ran and placed every body */
ASSERT_EQ(big_at, BIG);
ASSERT_GTE(small, (uint64_t)SMALL);
ASSERT(big <= small * WORK_RATIO_MAX); /* 10x input: n log n is about 15x, n^2 100x */
PASS();
}
/* --- C++ out-of-line method definitions (#428) ---
* A .cpp defining methods of a class declared elsewhere (not in this TU).
* Pre-fix these were recorded as free Functions (label "Function", no
@@ -12891,6 +13191,12 @@ TEST(doc_perl_module_doc_is_the_pod_no_sub_holds) {
ASSERT_NOT_NULL(r);
ASSERT_NULL(r->module_doc);
cbm_free_result(r);
/* POD without any declarations leaves both scope sort inputs empty. */
r = extract("=head1 NAME\n\nStandalone module.\n\n=cut\n", CBM_LANG_PERL, "t", "Standalone.pm");
ASSERT_NOT_NULL(r);
ASSERT_EQ(count_defs_with_label(r, "Function"), 0);
ASSERT_STR_EQ(r->module_doc, "=head1 NAME\n\nStandalone module.\n\n=cut");
cbm_free_result(r);
PASS();
}
@@ -13439,6 +13745,77 @@ TEST(objectscript_udl_methods_after_goto_label) {
PASS();
}
/* #1261: a brace inside a Language = python body (string, comment, triple
* quote) must not desynchronize the body lexer. Before the grammar fix the
* first such body swallowed every later method in the class, together with
* their CALLS, and extraction still reported no error. */
static void assert_python_body_is_contained(const char *py_body, int *failed) {
char src[1024];
snprintf(src, sizeof(src),
"Class My.Brace Extends %%RegisteredObject\n"
"{\n"
"ClassMethod PyBad() As %%String [ Language = python ]\n"
"{\n"
"%s"
"}\n"
"ClassMethod RealOne() As %%String\n"
"{\n"
" Do ##class(My.Tgt).Hit()\n"
" Quit \"one\"\n"
"}\n"
"ClassMethod RealTwo() As %%String\n"
"{\n"
" Do ##class(My.Tgt).Hit()\n"
" Quit \"two\"\n"
"}\n"
"}\n",
py_body);
CBMFileResult *r = extract(src, CBM_LANG_OBJECTSCRIPT_UDL, "t", "Brace.cls");
int ok = r && !r->has_error && has_def(r, "Method", "PyBad") &&
has_def(r, "Method", "RealOne") && has_def(r, "Method", "RealTwo") &&
count_calls_named(r, "My.Tgt.Hit") == 2;
if (ok) {
/* PyBad must end at its own closing brace, before RealOne starts. */
const CBMDefinition *bad = find_def(r, "PyBad");
const CBMDefinition *one = find_def(r, "RealOne");
ok = bad && one && bad->end_line < one->start_line;
}
if (!ok) {
fprintf(stderr, " python body not contained: %s", py_body);
(*failed)++;
}
if (r) {
cbm_free_result(r);
}
}
TEST(objectscript_udl_python_body_braces_do_not_swallow_class) {
int failed = 0;
/* The #1261 repro. */
assert_python_body_is_contained(" s = \"dict literal { unbalanced\"\n"
" return s\n",
&failed);
assert_python_body_is_contained(" s = 'closing } first'\n"
" return s\n",
&failed);
assert_python_body_is_contained(" # a { in a comment\n"
" return 1\n",
&failed);
assert_python_body_is_contained(" s = \"\"\"triple {\n"
" still inside\"\"\"\n"
" return s\n",
&failed);
assert_python_body_is_contained(" s = 'escaped \\' {'\n"
" return s\n",
&failed);
/* Balanced braces in real Python syntax keep working. */
assert_python_body_is_contained(" d = {'k': {'n': 1}}\n"
" return str(d)\n",
&failed);
ASSERT_EQ(failed, 0);
PASS();
}
TEST(objectscript_udl_methods) {
CBMFileResult *r = extract("Class MyApp.Utils Extends %RegisteredObject\n"
"{\n"
@@ -13540,6 +13917,32 @@ TEST(objectscript_routine_tags) {
PASS();
}
/* Each routine call form keeps the callee text it had before the grammar hid
* line_ref under routine_tag_call and extrinsic_function. */
TEST(objectscript_routine_call_forms_callee_text) {
CBMFileResult *r = extract("run(x)\n"
" Do accept(x)\n"
" Do accept\n"
" Do accept^Other(x)\n"
" Do ^Other\n"
" Do accept+2^Other\n"
" Set a = $$accept(x)\n"
" Set b = $$accept^Other(x)\n"
" Set c = $$^Other(1)\n"
" Quit\n"
"accept(value)\n"
" Quit value\n",
CBM_LANG_OBJECTSCRIPT_ROUTINE, "t", "Forms.mac");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_EQ(count_calls_named(r, "accept"), 3);
ASSERT_EQ(count_calls_named(r, "accept^Other"), 2);
ASSERT_EQ(count_calls_named(r, "^Other"), 2);
ASSERT_EQ(count_calls_named(r, "accept+2^Other"), 1);
cbm_free_result(r);
PASS();
}
TEST(objectscript_udl_query_member) {
CBMFileResult *r =
extract("Class MyApp.Repo Extends %Persistent\n"
@@ -13648,6 +14051,37 @@ TEST(objectscript_udl_trigger_body_tokens) {
PASS();
}
TEST(objectscript_udl_storage_docstring) {
CBMFileResult *r = extract("Class MyApp.Patient Extends %Persistent\n"
"{\n"
"Storage Default\n"
"{\n"
"<Data name=\"PatientDefaultData\">\n"
"<Value name=\"1\"><Value>%classname</Value></Value>\n"
"</Data>\n"
"<DataLocation>^MyApp.PatientD</DataLocation>\n"
"<IdLocation>^MyApp.PatientD</IdLocation>\n"
"<Type>%Storage.Persistent</Type>\n"
"}\n"
"}\n",
CBM_LANG_OBJECTSCRIPT_UDL, "t", "Patient.cls");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT(has_def(r, "Storage", "Default"));
for (int i = 0; i < r->defs.count; i++) {
if (strcmp(r->defs.items[i].label, "Storage") == 0 &&
strcmp(r->defs.items[i].name, "Default") == 0) {
ASSERT_NOT_NULL(r->defs.items[i].docstring);
ASSERT(strstr(r->defs.items[i].docstring, "\"data_global\":\"^MyApp.PatientD\"") !=
NULL);
ASSERT(strstr(r->defs.items[i].docstring, "\"id_global\"") != NULL);
break;
}
}
cbm_free_result(r);
PASS();
}
TEST(objectscript_udl_self_call_relative_dot_method) {
CBMFileResult *r =
extract("Class HS.Flash.UpdateManager Extends Ens.BusinessProcess\n"
@@ -15984,17 +16418,20 @@ SUITE(extraction) {
/* InterSystems ObjectScript (UDL / routine / Export XML). */
RUN_TEST(objectscript_udl_class);
RUN_TEST(objectscript_udl_methods_after_goto_label);
RUN_TEST(objectscript_udl_python_body_braces_do_not_swallow_class);
RUN_TEST(objectscript_udl_methods);
RUN_TEST(objectscript_udl_base_classes);
RUN_TEST(objectscript_udl_multiple_bases);
RUN_TEST(objectscript_udl_properties);
RUN_TEST(objectscript_routine_tags);
RUN_TEST(objectscript_routine_call_forms_callee_text);
RUN_TEST(objectscript_udl_query_member);
RUN_TEST(objectscript_udl_index_member);
RUN_TEST(objectscript_udl_xdata_member);
RUN_TEST(objectscript_udl_trigger_member);
RUN_TEST(objectscript_udl_trigger_body_quit);
RUN_TEST(objectscript_udl_trigger_body_tokens);
RUN_TEST(objectscript_udl_storage_docstring);
RUN_TEST(objectscript_udl_ensemble_production_def_parses_items);
RUN_TEST(objectscript_udl_ensemble_production_def_hs_settings);
RUN_TEST(objectscript_udl_ensemble_production_def_absent_no_error);
@@ -16082,6 +16519,7 @@ SUITE(extraction) {
/* Systems */
RUN_TEST(rust_function);
RUN_TEST(rust_struct);
RUN_TEST(rust_impl_method_return_type);
RUN_TEST(go_function);
RUN_TEST(go_struct);
RUN_TEST(go_interface);
@@ -16221,6 +16659,10 @@ SUITE(extraction) {
RUN_TEST(cpp_function);
RUN_TEST(cpp_gtest_same_name_collision_issue1266);
RUN_TEST(cpp_gtest_f_unique_name_issue1266);
RUN_TEST(cpp_gtest_body_caller_is_test_node);
RUN_TEST(cpp_gtest_preprocessed_view_names_the_raw_test);
RUN_TEST(cpp_gtest_preprocessed_view_one_line_pair);
RUN_TEST(cpp_gtest_preprocessed_view_lookup_growth);
RUN_TEST(cpp_out_of_line_method_issue428);
RUN_TEST(cobol_paragraph);
RUN_TEST(verilog_module);
+923
View File
@@ -37,6 +37,8 @@
#include <foundation/log.h>
#include <sqlite3.h>
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
@@ -1878,6 +1880,261 @@ static char *gpf_spawns(const GpfFile *files, int nfiles) {
free(got_); \
} while (0)
/* Every REFERENCES_FILE edge a Dockerfile draws for a COPY / ADD source, as
* "source file -> target file (via:line)", sorted, one per line. */
static char *gpf_copy_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' "
"AND json_extract(e.properties,'$.via') IN ('copy','add') ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
#define GPF_ASSERT_COPY_REFS(files, n, want) \
do { \
char *got_ = gpf_copy_refs(files, n); \
if (!got_ || strcmp(got_, want) != 0) { \
fprintf(stderr, "COPY refs got:\n%s\nwant:\n%s\n", got_ ? got_ : "(null)", want); \
free(got_); \
FAIL("REFERENCES_FILE edge set"); \
} \
free(got_); \
} while (0)
/* A Dockerfile at the repository root has one context. Each plain source of
* a COPY / ADD that is an indexed file is a file the Dockerfile references,
* once, at the first instruction naming it. No edge for a directory, a
* source of another stage or image (--from), a URL, a glob, a source a
* variable supplies (an ARG default can be overridden by the build), a
* source no indexed file is, or the Dockerfile itself. */
TEST(probe_dockerfile_copy_sources_are_file_references) {
static const GpfFile files[] = {
{"Dockerfile", "ARG CONF=conf/app.yaml\n"
"FROM python:3.12 AS build\n"
"WORKDIR /app\n"
"COPY requirements.txt setup.py ./\n"
"COPY src/ ./src/\n"
"COPY . .\n"
"ADD conf/app.yaml /etc/app.yaml\n"
"ADD https://example.com/tool.tgz /tmp/\n"
"COPY ${CONF} /etc/again.yaml\n"
"COPY *.py /all/\n"
"COPY missing.py /missing.py\n"
"COPY Dockerfile /Dockerfile\n"
"FROM python:3.12-slim\n"
"COPY --from=build /app/setup.py /setup.py\n"
"COPY [\"setup.py\", \"run.sh\", \"/opt/\"]\n"},
{"requirements.txt", "flask==3.0.0\n"},
{"setup.py", "from setuptools import setup\n\nsetup(name=\"app\")\n"},
{"run.sh", "#!/bin/sh\nexec python -m app\n"},
{"conf/app.yaml", "name: app\n"},
{"src/app.py", "def main():\n return 0\n"}};
GPF_ASSERT_COPY_REFS(files, 6,
"Dockerfile -> conf/app.yaml (add:7)\n"
"Dockerfile -> requirements.txt (copy:4)\n"
"Dockerfile -> run.sh (copy:15)\n"
"Dockerfile -> setup.py (copy:4)");
PASS();
}
/* A Dockerfile below the root can be built with its own directory or with
* the repository root as context; the build command decides, and it is not
* in the Dockerfile. A source that is a file under exactly one of the two is
* that file. A source that is a file under both is no edge, and neither is
* one that is a file under one and a directory under the other: with the
* other context the instruction copies the directory. */
TEST(probe_dockerfile_copy_source_under_two_contexts_is_no_reference) {
static const GpfFile files[] = {
{"svc/Dockerfile", "FROM alpine:3.20\n"
"COPY entry.sh /entry.sh\n"
"COPY shared/tool.sh /tool.sh\n"
"COPY both.sh /both.sh\n"
"COPY ../outside.sh /outside.sh\n"
"COPY config.yaml /etc/config.yaml\n"},
{"svc/entry.sh", "#!/bin/sh\necho entry\n"},
{"shared/tool.sh", "#!/bin/sh\necho tool\n"},
{"both.sh", "#!/bin/sh\necho root\n"},
{"svc/both.sh", "#!/bin/sh\necho svc\n"},
{"outside.sh", "#!/bin/sh\necho outside\n"},
{"config.yaml", "mode: root\n"},
{"svc/config.yaml/part.yaml", "mode: part\n"}};
GPF_ASSERT_COPY_REFS(files, 8,
"svc/Dockerfile -> shared/tool.sh (copy:3)\n"
"svc/Dockerfile -> svc/entry.sh (copy:2)");
PASS();
}
/* Every REFERENCES_FILE edge a compose service draws, as
* "<service> -> <target file> (via:line)", sorted, one per line. */
static char *gpf_compose_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.name || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND s.label='Resource' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
#define GPF_ASSERT_COMPOSE_REFS(files, n, want) \
do { \
char *got_ = gpf_compose_refs(files, n); \
if (!got_ || strcmp(got_, want) != 0) { \
fprintf(stderr, "compose refs got:\n%s\nwant:\n%s\n", got_ ? got_ : "(null)", want); \
free(got_); \
FAIL("REFERENCES_FILE edge set"); \
} \
free(got_); \
} while (0)
/* A compose service names repository files relative to the compose file's
* directory: a bind mount's host side (short and long form), an env_file, the
* file of a config or secret it lists. Each indexed file is a file the
* service references, once, at the first line naming it. No edge for a
* directory, a named or anonymous volume, an absolute or home path, a
* short-form host side without a leading dot (compose reads it as a volume's
* name), a path out of the repository, a variable without a value, a file the
* index does not hold, or a config without a file. */
TEST(probe_compose_service_files_are_file_references) {
static const GpfFile files[] = {
{"compose.yaml", "services:\n"
" web:\n"
" image: nginx:1.27\n"
" volumes:\n"
" - ./conf/nginx.conf:/etc/nginx/nginx.conf:ro\n"
" - ./src:/app\n"
" - data:/var/lib/data\n"
" - /etc/localtime:/etc/localtime:ro\n"
" - ~/.aws:/root/.aws\n"
" - ../outside.conf:/outside.conf\n"
" - ${CONF_DIR:-./conf}/extra.conf:/etc/extra.conf\n"
" - ${UNSET_DIR}/x.conf:/x.conf\n"
" - conf/nodot.conf:/etc/nodot.conf\n"
" - /anonymous\n"
" - type: bind\n"
" source: ./conf/long.conf\n"
" target: /etc/long.conf\n"
" - type: volume\n"
" source: data\n"
" target: /data\n"
" - ./conf/missing.conf:/etc/missing.conf\n"
" env_file:\n"
" - ./conf/web.env\n"
" - path: ./conf/more.env\n"
" required: false\n"
" configs:\n"
" - app_config\n"
" - source: other_config\n"
" target: /etc/other.yaml\n"
" - external_config\n"
" secrets:\n"
" - db_settings\n"
" worker:\n"
" image: alpine:3.20\n"
" volumes:\n"
" - ./conf/nginx.conf:/a\n"
" - ./conf/nginx.conf:/b\n"
" env_file: ./conf/web.env\n"
"configs:\n"
" app_config:\n"
" file: ./conf/app.yaml\n"
" other_config:\n"
" file: conf/other.yaml\n"
" external_config:\n"
" external: true\n"
"secrets:\n"
" db_settings:\n"
" file: ./conf/db.ini\n"
"volumes:\n"
" data: {}\n"},
{"conf/nginx.conf", "worker_processes 1;\n"},
{"conf/extra.conf", "gzip on;\n"},
{"conf/long.conf", "sendfile on;\n"},
{"conf/nodot.conf", "tcp_nopush on;\n"},
{"conf/web.env", "MODE=web\n"},
{"conf/more.env", "EXTRA=1\n"},
{"conf/app.yaml", "name: app\n"},
{"conf/other.yaml", "name: other\n"},
{"conf/db.ini", "[db]\nname = app\n"},
{"src/app.py", "def main():\n return 0\n"}};
GPF_ASSERT_COMPOSE_REFS(files, 11,
"Service/web -> conf/app.yaml (config:27)\n"
"Service/web -> conf/db.ini (secret:32)\n"
"Service/web -> conf/extra.conf (volume:11)\n"
"Service/web -> conf/long.conf (volume:16)\n"
"Service/web -> conf/more.env (env_file:24)\n"
"Service/web -> conf/nginx.conf (volume:5)\n"
"Service/web -> conf/other.yaml (config:28)\n"
"Service/web -> conf/web.env (env_file:23)\n"
"Service/worker -> conf/nginx.conf (volume:36)\n"
"Service/worker -> conf/web.env (env_file:38)");
PASS();
}
/* The paths are relative to the compose file's directory, not to the
* repository root: a same-named file at the root is not the one, a path may
* climb to a sibling directory, and one that leaves the repository or names
* the compose file itself is no edge. A long-form bind mount says it is a
* path, so its source needs no leading dot. */
TEST(probe_compose_service_files_resolve_from_the_compose_directory) {
static const GpfFile files[] = {
{"deploy/compose.yaml", "services:\n"
" api:\n"
" image: api:1\n"
" volumes:\n"
" - ./app.conf:/etc/app.conf\n"
" - ../shared/base.conf:/etc/base.conf\n"
" - ../../out.conf:/etc/out.conf\n"
" - ./compose.yaml:/self.yaml\n"
" - type: bind\n"
" source: more.conf\n"
" target: /etc/more.conf\n"},
{"deploy/app.conf", "name deploy;\n"},
{"deploy/more.conf", "name more;\n"},
{"app.conf", "name root;\n"},
{"more.conf", "name root-more;\n"},
{"shared/base.conf", "name base;\n"},
{"out.conf", "name out;\n"}};
GPF_ASSERT_COMPOSE_REFS(files, 7,
"Service/api -> deploy/app.conf (volume:5)\n"
"Service/api -> deploy/more.conf (volume:10)\n"
"Service/api -> shared/base.conf (volume:6)");
PASS();
}
/* Every SPAWNS and DEPLOYS edge as "source -> target (TYPE api|via[
* ci[/job]])", sorted, one per line: top-level code as "@<file>"; a script
* as "script:<path>", a Process as "proc:<name>", a Chart as "chart:<name>",
@@ -2841,6 +3098,205 @@ TEST(probe_kustomize_helm_charts_deploy_their_chart) {
PASS();
}
/* The REFERENCES_FILE edges a kustomization draws for the files it reads, as
* "<kustomization> -> <target file> (via:line)", sorted, one per line; then a
* line "imports <files>": the targets of the IMPORTS edges leaving
* kustomization files. */
static char *gpf_kustomize_files(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce((SELECT group_concat(x, char(10)) FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND json_extract(e.properties,'$.via') "
"IN ('configMapGenerator','secretGenerator','configurations') ORDER BY x)), '') "
"|| char(10) || 'imports ' || coalesce((SELECT group_concat(x, ',') FROM (SELECT "
"DISTINCT t.file_path AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='IMPORTS' AND s.file_path LIKE '%kustomization.yaml' "
"ORDER BY x)), '')";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW && sqlite3_column_text(st, 0)) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A kustomization reads files that are input to its build without being a
* member of it: a generator's `files` (a path, or `key=path`) and `envs`, and
* its `configurations`. Each indexed file is a file the kustomization
* references, once, at the first line naming it -- and never an import: an
* import makes a file's objects part of the build. A file the index does not
* hold (one that is missing, and config/settings.json, which is on disk but
* a name discovery skips), a path out of the repository, an absolute path
* (it names a file of the machine, not of the repository, also when the
* repository holds a file at that path below its root or below the
* kustomization) and a generator's literals are none. */
TEST(probe_kustomize_generator_files_are_file_references) {
static const GpfFile files[] = {
{"deploy/kustomization.yaml", "apiVersion: kustomize.config.k8s.io/v1beta1\n"
"kind: Kustomization\n"
"resources:\n"
" - deployment.yaml\n"
"configMapGenerator:\n"
" - name: app-config\n"
" files:\n"
" - app.properties\n"
" - settings=config/settings.json\n"
" - limits=config/limits.json\n"
" - missing.properties\n"
" - abs=/abs.properties\n"
" envs:\n"
" - app.env\n"
" - name: literal-only\n"
" literals:\n"
" - A=1\n"
"secretGenerator:\n"
" - name: tokens\n"
" files:\n"
" - ../../outside.yaml\n"
" - ../shared/token.yaml\n"
"configurations:\n"
" - kustomizeconfig.yaml\n"
" - app.properties\n"
" - /abs.properties\n"},
{"deploy/deployment.yaml", "apiVersion: apps/v1\n"
"kind: Deployment\n"
"metadata:\n"
" name: app\n"
"spec:\n"
" replicas: 1\n"},
{"deploy/app.properties", "mode=prod\n"},
{"deploy/config/settings.json", "{\"mode\": \"prod\"}\n"},
{"deploy/config/limits.json", "{\"max\": 3}\n"},
{"deploy/app.env", "MODE=prod\n"},
{"deploy/kustomizeconfig.yaml", "nameReference: []\n"},
{"deploy/abs.properties", "mode=abs\n"},
{"abs.properties", "mode=root\n"},
{"shared/token.yaml", "token: placeholder\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_kustomize_files(files, n);
static const char want[] =
"deploy/kustomization.yaml -> deploy/app.env (configMapGenerator:14)\n"
"deploy/kustomization.yaml -> deploy/app.properties (configMapGenerator:8)\n"
"deploy/kustomization.yaml -> deploy/config/limits.json (configMapGenerator:10)\n"
"deploy/kustomization.yaml -> deploy/kustomizeconfig.yaml (configurations:24)\n"
"deploy/kustomization.yaml -> shared/token.yaml (secretGenerator:22)\n"
"imports deploy/deployment.yaml";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "kustomize files got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("kustomize file refs");
}
free(got);
PASS();
}
/* Every REFERENCES_FILE edge a local `uses:` draws, as
* "<file> -> <target file> (uses:line)", sorted, one per line. */
static char *gpf_local_uses(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' "
"AND json_extract(e.properties,'$.via')='uses' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A local `uses:` ("./...") is a path from the repository root, wherever the
* workflow or action lies. A step's names an action by its directory: the
* edge goes to that directory's action.yml or action.yaml, the one it holds.
* A job's names a reusable workflow file. Each file once, at the first use.
* No edge for an action of another repository, a path with an expression, a
* directory with no action file, or one holding both spellings. */
TEST(probe_github_actions_local_uses_reference_their_files) {
static const GpfFile files[] = {
{".github/workflows/ci.yml", "name: ci\n"
"on: [push]\n"
"jobs:\n"
" build:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - uses: actions/checkout@v4\n"
" - uses: ./.github/actions/setup\n"
" - uses: ./\n"
" - uses: ./.github/actions/${{ matrix.kind }}\n"
" - uses: ./.github/actions/missing\n"
" - uses: ./.github/actions/both\n"
" - name: again\n"
" uses: ./.github/actions/setup\n"
" - run: echo done\n"
" call:\n"
" uses: ./.github/workflows/reusable.yml\n"
" far:\n"
" uses: org/repo/.github/workflows/x.yml@main\n"},
{".github/workflows/reusable.yml", "on:\n"
" workflow_call: {}\n"
"jobs:\n"
" a:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - run: echo a\n"},
{".github/actions/setup/action.yml", "name: setup\n"
"runs:\n"
" using: composite\n"
" steps:\n"
" - uses: ./.github/actions/inner\n"
" - run: echo setup\n"
" shell: bash\n"},
{".github/actions/inner/action.yaml", "name: inner\n"
"runs:\n"
" using: composite\n"
" steps:\n"
" - run: echo inner\n"
" shell: bash\n"},
{".github/actions/both/action.yml", "name: both\nruns:\n using: composite\n steps: []\n"},
{".github/actions/both/action.yaml", "name: both\nruns:\n using: composite\n steps: []\n"},
{"action.yaml", "name: root\nruns:\n using: composite\n steps: []\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_local_uses(files, n);
static const char want[] =
".github/actions/setup/action.yml -> .github/actions/inner/action.yaml (uses:5)\n"
".github/workflows/ci.yml -> .github/actions/setup/action.yml (uses:8)\n"
".github/workflows/ci.yml -> .github/workflows/reusable.yml (uses:17)\n"
".github/workflows/ci.yml -> action.yaml (uses:9)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "local uses got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("local uses");
}
free(got);
PASS();
}
/* Every Terraform reference edge as
* "<file> <block> -> <file> <block> <type> <ref>:<line>", then a line
* "other tf edges <n>": USAGE / CALLS edges leaving a .tf file that the
@@ -2930,6 +3386,78 @@ TEST(probe_terraform_refs_resolve_in_their_module) {
PASS();
}
/* Every REFERENCES_FILE edge a Terraform block draws for a file function, as
* "<file> <block> -> <target file> (fn:line)", sorted, one per line. */
static char *gpf_tf_file_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' ' || s.name || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND s.file_path LIKE '%.tf' "
"ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A file function whose path begins at ${path.module} reads a file of the
* repository: the block holding the call references that file, once, at its
* first call. A path without ${path.module} is relative to the directory
* Terraform runs in and draws nothing; neither does path.root, a path with
* another interpolation, a variable, a directory read by fileset, or a file
* the index does not hold. */
TEST(probe_terraform_file_functions_reference_their_files) {
static const GpfFile files[] = {
{"infra/main.tf", "variable \"name\" {}\n"
"locals {\n"
" policy = file(\"${path.module}/policies/read.json\")\n"
" again = file(\"${path.module}/policies/read.json\")\n"
" plain = file(\"policies/read.json\")\n"
" rooted = file(\"${path.root}/policies/read.json\")\n"
" named = file(\"${path.module}/policies/${var.name}.json\")\n"
" byvar = file(var.name)\n"
" set = fileset(\"${path.module}/policies\", \"*.json\")\n"
" gone = file(\"${path.module}/policies/missing.json\")\n"
"}\n"
"resource \"aws_instance\" \"web\" {\n"
" user_data = templatefile(\"${path.module}/templates/init.sh\", {\n"
" name = var.name\n"
" })\n"
" hash = filemd5(\"${path.module}/../shared/common.yaml\")\n"
"}\n"},
{"infra/policies/read.json", "{\"Version\": \"2012-10-17\"}\n"},
{"infra/templates/init.sh", "#!/bin/sh\necho ${name}\n"},
{"shared/common.yaml", "name: common\n"},
{"policies/read.json", "{\"Version\": \"2012-10-17\"}\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_tf_file_refs(files, n);
static const char want[] =
"infra/main.tf locals -> infra/policies/read.json (file:3)\n"
"infra/main.tf resource.aws_instance.web -> infra/templates/init.sh (templatefile:13)\n"
"infra/main.tf resource.aws_instance.web -> shared/common.yaml (filemd5:16)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "terraform file refs got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("terraform file refs");
}
free(got);
PASS();
}
/* A Terraform / OpenTofu module file (.tf, .tofu) extracts its blocks but no
* generic calls or usages -- its references are the module resolver's -- while
* any other HCL file (Packer, Nomad, Terragrunt .hcl) keeps them. */
@@ -4220,6 +4748,225 @@ TEST(probe_make_rules_have_a_node_per_target) {
PASS();
}
/* Every DEPENDS_ON edge a Make prerequisite draws, as
* "<file>:<target> -> <file>:<rule> (prerequisite:<line>[ order-only])",
* sorted, one per line. */
static char *gpf_make_prerequisites(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ':' || s.name || ' -> ' || t.file_path || ':' || t.name || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') || "
"CASE WHEN json_extract(e.properties,'$.order_only') IS NULL THEN '' ELSE "
"' order-only' END || ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='DEPENDS_ON' AND s.label='Function' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A prerequisite that names a rule of the same makefile is a dependency of
* each of the rule's targets on that rule: once per pair, at the first line
* stating it (make merges the prerequisites of a target's rules), an
* order-only one marked -- unless another rule of the target lists it as a
* normal one: make then treats it as normal, and the edge carries that
* line. A rule under a conditional, a pattern rule and a
* rule whose target is a variable have their prerequisites like any other.
* No edge for a prerequisite with a variable, a pattern or a glob, one that
* names a file or a rule of another makefile (an included one too), a target
* naming itself, a special target's list (.PHONY), a target-specific
* variable in any spelling, or a static pattern rule. */
TEST(probe_make_prerequisites_depend_on_their_rules) {
static const GpfFile files[] = {
{"Makefile", "include mk/tools.mk\n"
"BIN := bin\n"
"TOOL := $(BIN)/tool\n\n"
"ifeq ($(OS),linux)\n"
"install: build\n"
"\tcp bin/tool /usr/local/bin\n"
"endif\n\n"
".PHONY: all build test\n"
"all: build test\n\n"
"build: generate | dirs\n"
"\tgo build ./...\n\n"
"test lint: build $(TOOL) tool\n"
"\tgo test ./...\n\n"
"generate: \\\n"
" proto \\\n"
" docs\n"
"\techo gen\n\n"
"proto docs dirs:\n"
"\techo $@\n\n"
"$(TOOL): go.mod dirs\n"
"\tgo build -o $@ ./cmd/tool\n\n"
"build: MODE = docs\n"
"build: export KIND := proto\n"
"lint: override FAST = dirs\n\n"
"%.o: %.c generate\n"
"\tcc -c $<\n\n"
"objs: a.o b.o c.o\n\n"
"a.o b.o: %.o: %.c dirs\n"
"\tcc -c $<\n\n"
"release:: build\n"
"\techo one\n"
"release:: test build\n"
"\techo two\n\n"
"deploy: build-$(ENV) *.yaml deploy all\n"
"\techo deploy\n\n"
"stamp: | dirs\n"
"stamp: dirs\n"
"mark: dirs\n"
"mark: | dirs\n"},
{"mk/tools.mk", "tool: build\n"
"\techo tool\n\n"
"tools: tool\n"},
{"go.mod", "module example.com/x\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_make_prerequisites(files, n);
static const char want[] = "Makefile:$(TOOL) -> Makefile:dirs (prerequisite:27)\n"
"Makefile:%.o -> Makefile:generate (prerequisite:34)\n"
"Makefile:all -> Makefile:build (prerequisite:11)\n"
"Makefile:all -> Makefile:test (prerequisite:11)\n"
"Makefile:build -> Makefile:dirs (prerequisite:13 order-only)\n"
"Makefile:build -> Makefile:generate (prerequisite:13)\n"
"Makefile:deploy -> Makefile:all (prerequisite:47)\n"
"Makefile:generate -> Makefile:docs (prerequisite:21)\n"
"Makefile:generate -> Makefile:proto (prerequisite:20)\n"
"Makefile:install -> Makefile:build (prerequisite:6)\n"
"Makefile:lint -> Makefile:build (prerequisite:16)\n"
"Makefile:mark -> Makefile:dirs (prerequisite:52)\n"
"Makefile:objs -> Makefile:a.o (prerequisite:37)\n"
"Makefile:objs -> Makefile:b.o (prerequisite:37)\n"
"Makefile:release -> Makefile:build (prerequisite:42)\n"
"Makefile:release -> Makefile:test (prerequisite:44)\n"
"Makefile:stamp -> Makefile:dirs (prerequisite:51)\n"
"Makefile:test -> Makefile:build (prerequisite:16)\n"
"mk/tools.mk:tools -> mk/tools.mk:tool (prerequisite:4)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "make prerequisites got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("make prerequisites");
}
free(got);
PASS();
}
/* Complexity guard counter of the Make dependency drawing (pass_shell.c). */
extern _Atomic uint64_t g_sh_make_pairs;
/* A rule line that repeats a target or a prerequisite states each pair once:
* the drawing looks at the line's words and at its distinct pairs, not at
* the product of the repeats. One rule with n copies of one target and n
* copies of one prerequisite, counted at 1x, 4x and 16x: one edge each time,
* and work that grows with n. */
TEST(probe_make_repeated_names_cost_linear_work) {
static const int sizes[] = {50, 200, 800};
uint64_t work[3] = {0, 0, 0};
for (int s = 0; s < 3; s++) {
size_t cap = (size_t)sizes[s] * 4 + 64;
char *mk = malloc(cap);
if (!mk) {
FAIL("alloc");
}
size_t n = 0;
for (int i = 0; i < sizes[s]; i++) {
n += (size_t)snprintf(mk + n, cap - n, "t ");
}
n += (size_t)snprintf(mk + n, cap - n, ":");
for (int i = 0; i < sizes[s]; i++) {
n += (size_t)snprintf(mk + n, cap - n, " d");
}
(void)snprintf(mk + n, cap - n, "\n\t@true\n\nd:\n\t@true\n");
const GpfFile files[] = {{"Makefile", mk}};
uint64_t before = atomic_load_explicit(&g_sh_make_pairs, memory_order_relaxed);
char *got = gpf_make_prerequisites(files, 1);
work[s] = atomic_load_explicit(&g_sh_make_pairs, memory_order_relaxed) - before;
bool one = got && strcmp(got, "Makefile:t -> Makefile:d (prerequisite:1)") == 0;
if (!one) {
fprintf(stderr, "repeated names at n=%d got:\n%s\n", sizes[s], got ? got : "(null)");
}
free(got);
free(mk);
if (!one) {
FAIL("a repeated pair is one edge");
}
}
if (work[0] == 0 || work[2] > work[0] * 20) {
fprintf(stderr, "make pair work at 50 / 200 / 800: %llu / %llu / %llu\n",
(unsigned long long)work[0], (unsigned long long)work[1],
(unsigned long long)work[2]);
FAIL("the work of a repeated rule line grows linearly");
}
PASS();
}
/* The Make grammar cannot parse a nested conditional indented with tabs
* inside an indented one (`envs` below): everything from there to the end of
* the file is one error region. The rules after it are still rules, and
* each has its node. A rule standing at the start of its line there has its
* prerequisites like any other. No edge for what the grammar read
* differently inside the region: a rule line indented with spaces, a rule
* under a conditional that follows a recipe; and none for what is no rule
* line at all: a define body, a recipe's continuation line. */
TEST(probe_make_prerequisites_after_a_region_the_grammar_cannot_parse) {
static const GpfFile files[] = {{"Makefile", "all: build pack\n\n"
"envs:\n"
" ifeq ($(A),)\n"
" \t\texport A := 1\n"
" \telse\n"
"\t\tifeq ($(B),)\n"
"\t\t\texport A := 2\n"
"\t\telse\n"
"\t\t\texport A := 3\n"
"\t\tendif\n"
" \tendif\n\n"
"build: envs\n"
"\techo build\n\n"
"pack: build\n"
"\tdocker run \\\n"
"-v out:/out build\n\n"
"define HELP\n"
"usage: build\n"
"endef\n\n"
" check: build\n"
"\techo check\n\n"
"ifeq ($(C),)\n"
"late: pack\n"
"\techo late\n"
"endif\n\n"
"usage:\n"
"\techo \"$(HELP)\"\n\n"
"lint: build | envs\n"
"\techo lint\n"}};
char *got = gpf_make_prerequisites(files, 1);
static const char want[] = "Makefile:all -> Makefile:build (prerequisite:1)\n"
"Makefile:all -> Makefile:pack (prerequisite:1)\n"
"Makefile:build -> Makefile:envs (prerequisite:14)\n"
"Makefile:lint -> Makefile:build (prerequisite:36)\n"
"Makefile:lint -> Makefile:envs (prerequisite:36 order-only)\n"
"Makefile:pack -> Makefile:build (prerequisite:17)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "make prerequisites in an error region got:\n%s\nwant:\n%s\n",
got ? got : "(null)", want);
free(got);
FAIL("make prerequisites in an error region");
}
free(got);
PASS();
}
/* make TARGET SPAWNS the rule of TARGET the makefile reads: the
* directory's Makefile (-C, --directory=), a -f file, a rule of a file it
* includes; from scripts, CI steps and recipes ($(MAKE)), on the line of
@@ -6982,6 +7729,164 @@ TEST(probe_gomod_enables_go_imports) {
PASS();
}
/* ══════════════════════════════════════════════════════════════════
* GROUP 19b — requirements.txt text encodings (#2941)
*
* pip decodes requirements.txt by its BOM. Windows PowerShell 5.1 writes
* `pip freeze > requirements.txt` as UTF-16 LE with a BOM and CRLF, and many
* editors save UTF-8 with a BOM. Each package becomes one Package node.
* ══════════════════════════════════════════════════════════════════ */
/* `ascii` as UTF-16 (little- or big-endian) with a BOM; returns the length. */
static size_t gpf_utf16_with_bom(const char *ascii, int big_endian, unsigned char *out,
size_t cap) {
size_t n = 0;
if (cap < 2) return 0;
out[n++] = big_endian ? 0xFE : 0xFF;
out[n++] = big_endian ? 0xFF : 0xFE;
for (const char *p = ascii; *p && n + 2 <= cap; p++) {
out[n++] = big_endian ? 0 : (unsigned char)*p;
out[n++] = big_endian ? (unsigned char)*p : 0;
}
return n;
}
static int gpf_cmp_str(const void *a, const void *b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
/* Index a project holding only requirements.txt with these raw bytes; write
* the Package node names, sorted and comma-joined, into `out`. */
static int gpf_requirements_packages(const unsigned char *bytes, size_t len, char *out,
size_t out_sz) {
GpfProj lp;
memset(&lp, 0, sizeof(lp));
out[0] = '\0';
snprintf(lp.tmpdir, sizeof(lp.tmpdir), "/tmp/cbm_gpf_XXXXXX");
if (!cbm_mkdtemp(lp.tmpdir)) return 0;
gpf_to_fwd_slashes(lp.tmpdir);
char path[700];
snprintf(path, sizeof(path), "%s/requirements.txt", lp.tmpdir);
FILE *f = fopen(path, "wb");
if (!f) {
th_rmtree(lp.tmpdir);
return 0;
}
size_t wrote = fwrite(bytes, 1, len, f);
fclose(f);
cbm_store_t *store = wrote == len ? gpf_open_indexed(&lp) : NULL;
int ok = 0;
cbm_node_t *nodes = NULL;
int count = 0;
if (store &&
cbm_store_find_nodes_by_label(store, lp.project, "Package", &nodes, &count) ==
CBM_STORE_OK) {
const char *names[64];
int k = 0;
for (int i = 0; i < count && k < 64; i++) names[k++] = nodes[i].name;
qsort(names, (size_t)k, sizeof(names[0]), gpf_cmp_str);
for (int i = 0; i < k; i++) {
if (i) strncat(out, ",", out_sz - strlen(out) - 1);
strncat(out, names[i], out_sz - strlen(out) - 1);
}
cbm_store_free_nodes(nodes, count);
ok = 1;
}
gpf_cleanup(&lp, store);
return ok;
}
static const char GPF_REQS[] = "requests==2.32.3\r\nuvicorn==0.30.0\r\n";
/* RED before #2941: the file read as one bogus package, "\xff\xfe" + "r". */
TEST(probe_requirements_utf16le_bom_issue2941) {
unsigned char buf[256];
size_t n = gpf_utf16_with_bom(GPF_REQS, 0, buf, sizeof(buf));
char names[256];
ASSERT_TRUE(gpf_requirements_packages(buf, n, names, sizeof(names)));
ASSERT_STR_EQ(names, "requests,uvicorn");
PASS();
}
TEST(probe_requirements_utf16be_bom_issue2941) {
unsigned char buf[256];
size_t n = gpf_utf16_with_bom(GPF_REQS, 1, buf, sizeof(buf));
char names[256];
ASSERT_TRUE(gpf_requirements_packages(buf, n, names, sizeof(names)));
ASSERT_STR_EQ(names, "requests,uvicorn");
PASS();
}
/* RED before #2941: the BOM stuck to the first name ("\xEF\xBB\xBFrequests"). */
TEST(probe_requirements_utf8_bom_issue2941) {
unsigned char buf[256];
static const unsigned char bom[] = {0xEF, 0xBB, 0xBF};
memcpy(buf, bom, sizeof(bom));
memcpy(buf + sizeof(bom), GPF_REQS, sizeof(GPF_REQS) - 1);
char names[256];
ASSERT_TRUE(gpf_requirements_packages(buf, sizeof(bom) + sizeof(GPF_REQS) - 1, names,
sizeof(names)));
ASSERT_STR_EQ(names, "requests,uvicorn");
PASS();
}
/* GREEN guard: plain UTF-8 reads as before. */
TEST(probe_requirements_utf8_plain_issue2941) {
char names[256];
ASSERT_TRUE(gpf_requirements_packages((const unsigned char *)GPF_REQS, sizeof(GPF_REQS) - 1,
names, sizeof(names)));
ASSERT_STR_EQ(names, "requests,uvicorn");
PASS();
}
/* UTF-16 bytes from explicit code units (BOM included), so a test can hold
* surrogates. */
static size_t gpf_utf16_units(const uint16_t *units, size_t count, int big_endian,
unsigned char *out, size_t cap) {
size_t n = 0;
for (size_t i = 0; i < count && n + 2 <= cap; i++) {
unsigned char hi = (unsigned char)(units[i] >> 8);
unsigned char lo = (unsigned char)(units[i] & 0xFF);
out[n++] = big_endian ? hi : lo;
out[n++] = big_endian ? lo : hi;
}
return n;
}
/* GREEN guard for the transcoder's multi-byte paths: a 2-byte (U+00E9), a
* 3-byte (U+540D) and a 4-byte code point (U+1F600, a surrogate pair), and an
* unpaired low surrogate (-> U+FFFD), each inside a package name, come out as
* exact UTF-8 from both byte orders. */
TEST(probe_requirements_utf16_non_ascii_issue2941) {
static const uint16_t units[] = {
0xFEFF, 'c', 'a', 'f', 0x00E9, '=', '=', '1', '\r', '\n', 0x540D,
'=', '=', '1', '\r', '\n', 0xD83D, 0xDE00, '=', '=', '1', '\r',
'\n', 'x', 0xDC00, 'y', '=', '=', '1', '\r', '\n',
};
for (int big_endian = 0; big_endian <= 1; big_endian++) {
unsigned char buf[256];
size_t n = gpf_utf16_units(units, sizeof(units) / sizeof(units[0]), big_endian, buf,
sizeof(buf));
char names[256];
ASSERT_TRUE(gpf_requirements_packages(buf, n, names, sizeof(names)));
ASSERT_STR_EQ(names, "caf\xC3\xA9,x\xEF\xBF\xBDy,\xE5\x90\x8D,\xF0\x9F\x98\x80");
}
PASS();
}
/* GREEN guard: a file that is only a BOM (UTF-8, UTF-16 LE, UTF-16 BE)
* decodes to empty text and yields no Package. */
TEST(probe_requirements_bom_only_issue2941) {
static const unsigned char boms[3][3] = {{0xEF, 0xBB, 0xBF}, {0xFF, 0xFE, 0}, {0xFE, 0xFF, 0}};
static const size_t lens[3] = {3, 2, 2};
for (int k = 0; k < 3; k++) {
char names[256];
ASSERT_TRUE(gpf_requirements_packages(boms[k], lens[k], names, sizeof(names)));
ASSERT_STR_EQ(names, "");
}
PASS();
}
/* ══════════════════════════════════════════════════════════════════
* SUITE wiring
* ══════════════════════════════════════════════════════════════════ */
@@ -7013,6 +7918,7 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_kustomize_module_node);
RUN_TEST(probe_kustomize_imports_edges);
RUN_TEST(probe_kustomize_with_patches);
RUN_TEST(probe_kustomize_generator_files_are_file_references);
RUN_TEST(probe_k8s_manifest_after_leading_comment);
RUN_TEST(probe_kustomize_imports_after_leading_comment);
RUN_TEST(probe_k8s_selector_after_leading_separator);
@@ -7061,6 +7967,10 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_mcp_trace_topology);
RUN_TEST(probe_mcp_trace_topology_follows_deploys);
RUN_TEST(probe_mcp_trace_run);
RUN_TEST(probe_dockerfile_copy_sources_are_file_references);
RUN_TEST(probe_dockerfile_copy_source_under_two_contexts_is_no_reference);
RUN_TEST(probe_compose_service_files_are_file_references);
RUN_TEST(probe_compose_service_files_resolve_from_the_compose_directory);
RUN_TEST(probe_mcp_trace_deploy);
RUN_TEST(probe_dockerfile_bases_are_images);
RUN_TEST(probe_image_without_registry_host_stays_unknown);
@@ -7077,6 +7987,7 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_kustomize_patches_override_their_base);
RUN_TEST(probe_kustomize_helm_charts_deploy_their_chart);
RUN_TEST(probe_terraform_refs_resolve_in_their_module);
RUN_TEST(probe_terraform_file_functions_reference_their_files);
RUN_TEST(probe_terraform_module_files_extract_no_generic_refs);
RUN_TEST(probe_terraform_module_calls_import_their_source);
RUN_TEST(probe_terraform_tfvars_override_their_variables);
@@ -7095,8 +8006,12 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_shell_programs_by_path_spawn);
RUN_TEST(probe_make_programs_by_path_spawn);
RUN_TEST(probe_ci_and_scripts_run_scripts);
RUN_TEST(probe_github_actions_local_uses_reference_their_files);
RUN_TEST(probe_make_targets_spawn_their_rules);
RUN_TEST(probe_make_rules_have_a_node_per_target);
RUN_TEST(probe_make_prerequisites_depend_on_their_rules);
RUN_TEST(probe_make_repeated_names_cost_linear_work);
RUN_TEST(probe_make_prerequisites_after_a_region_the_grammar_cannot_parse);
RUN_TEST(probe_helmrelease_chartref_deploys_its_oci_chart);
RUN_TEST(probe_go_installer_deploys_charts);
RUN_TEST(probe_terraform_helm_release_deploys_its_chart);
@@ -7208,4 +8123,12 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_gomod_simple);
RUN_TEST(probe_gomod_depends_on_edges);
RUN_TEST(probe_gomod_enables_go_imports);
/* requirements.txt encodings (#2941) */
RUN_TEST(probe_requirements_utf16le_bom_issue2941);
RUN_TEST(probe_requirements_utf16be_bom_issue2941);
RUN_TEST(probe_requirements_utf8_bom_issue2941);
RUN_TEST(probe_requirements_utf8_plain_issue2941);
RUN_TEST(probe_requirements_utf16_non_ascii_issue2941);
RUN_TEST(probe_requirements_bom_only_issue2941);
}
+372
View File
@@ -0,0 +1,372 @@
/*
* test_include_path.c -- the path rule (src/pipeline/include_path.h): which
* indexed file a Protobuf or Make import names.
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
#include "test_helpers.h"
#include "../src/pipeline/include_path.h"
#include "pipeline/pipeline.h"
#include "sqlite3.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* A universe of the given indexed paths (NULL-terminated). */
static cbm_include_universe_t *ip_universe(const char *const *paths) {
cbm_file_info_t files[64];
int n = 0;
for (; paths[n] && n < 64; n++) {
memset(&files[n], 0, sizeof(files[n]));
files[n].rel_path = (char *)paths[n];
}
return cbm_include_universe_new(files, n);
}
/* The verdict for an import `path` of the file `rel`, the file in *out. */
static cbm_include_path_verdict_t ip_ask(cbm_include_universe_t *u, CBMLanguage lang,
const char *rel, const char *path, char *out,
size_t out_sz) {
CBMImport imp;
memset(&imp, 0, sizeof(imp));
imp.module_path = path;
out[0] = '\0';
return cbm_include_path_resolve(u, NULL, NULL, rel, lang, &imp, out, out_sz);
}
TEST(include_path_proto_tail_guess_and_ambiguity) {
static const char *const files[] = {"api/a.proto", "x/common.proto", "y/z/shared.proto",
"w/shared.proto", "api/shared.proto", "main.go",
NULL};
cbm_include_universe_t *u = ip_universe(files);
ASSERT_NOT_NULL(u);
char got[1024];
/* the whole path, and a tail only one file ends with */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "x/common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "x/common.proto");
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "x/common.proto");
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "z/shared.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "y/z/shared.proto");
/* three files end with the tail: the one beside the importer is a guess
* (protoc -I . and -I api read different files), never FILE */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "shared.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_GUESS);
ASSERT_STR_EQ(got, "api/shared.proto");
/* ... and none from a directory without one */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "x/common.proto", "shared.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
/* no such file (proven); only a case variant exists (a case-insensitive
* disk opens it, so not proven); absolute */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "nope/none.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NO_FILE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "X/Common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "/abs/common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
/* paths protoc refuses ("Backslashes, consecutive slashes, \".\", or \"..\"
* are not allowed in the virtual path"): not read, never normalised */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "a.proto", "../common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "./x/common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "x//common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "x\\common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "x/./common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
/* a row that names no .proto file is not read as a path */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "x.common", got, sizeof(got)),
CBM_INCLUDE_PATH_NOT_A_PATH);
/* a language without a row */
ASSERT_EQ(ip_ask(u, CBM_LANG_GO, "api/a.go", "x/common.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NOT_A_PATH);
cbm_include_universe_free(u);
PASS();
}
/* GNU make reads a relative include from the directory it runs in (then -I
* dirs): a root makefile decides, a makefile below the root only guesses
* (GNU make 4.3: `include b.mk` in sub/a.mk, included from the root, does not
* read sub/b.mk). */
TEST(include_path_make_root_decides_below_is_guess) {
static const char *const files[] = {"Makefile", "sub/Makefile", "sub/local.mk",
"rules.mk", "both.mk", "sub/both.mk",
"other/elsewhere.mk", "sub/a.mk", "sub/b.mk",
NULL};
cbm_include_universe_t *u = ip_universe(files);
ASSERT_NOT_NULL(u);
char got[1024];
/* the root makefile: its own directory is the root */
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "rules.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "rules.mk");
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "sub/local.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "sub/local.mk");
/* below the root: beside it, or at the root, depends on where make runs */
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/Makefile", "local.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_GUESS);
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/Makefile", "rules.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_GUESS);
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/a.mk", "b.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_GUESS);
/* both: none */
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/Makefile", "both.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
/* none (proven); climbing out of its directory, from any directory make
* runs in it still names a file ending in the rest (none); a name with a
* variable */
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "missing.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_NO_FILE);
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/x/Makefile", "../../gone.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_NO_FILE);
/* not at either base, but elsewhere (make may run there): not proven absent */
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "sub/Makefile", "elsewhere.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "$(TOP)/rules.mk", got, sizeof(got)),
CBM_INCLUDE_PATH_NONE);
cbm_include_universe_free(u);
PASS();
}
/* The universe is the indexed list: a file the run did not index (an ignored
* or skipped directory) is not seen, whatever is on the disk. */
TEST(include_path_universe_is_the_indexed_files) {
static const char *const files[] = {"a.proto", "common/t.proto", "real/l.proto", NULL};
cbm_include_universe_t *u = ip_universe(files);
ASSERT_NOT_NULL(u);
char got[1024];
/* node_modules/pkg/common/t.proto exists on a disk, not in the index: the
* indexed one is the only file the tail names */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "a.proto", "common/t.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "common/t.proto");
/* only under an ignored directory: no indexed file, proven */
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "a.proto", "only.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_NO_FILE);
ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "a.proto", "l.proto", got, sizeof(got)),
CBM_INCLUDE_PATH_FILE);
ASSERT_STR_EQ(got, "real/l.proto");
cbm_include_universe_free(u);
PASS();
}
/* The manifest key follows the set of indexed names a row keeps: not their
* order, nor files no row names. */
TEST(include_path_inventory_digest_follows_indexed_names) {
cbm_file_info_t f[4];
memset(f, 0, sizeof(f));
char d0[CBM_SHA256_HEX_LEN + 1];
char d1[CBM_SHA256_HEX_LEN + 1];
char d2[CBM_SHA256_HEX_LEN + 1];
char d3[CBM_SHA256_HEX_LEN + 1];
f[0].rel_path = "a.proto";
f[1].rel_path = "main.go";
ASSERT_EQ(cbm_include_path_inventory_digest(f, 1, d0), 0);
ASSERT_EQ(cbm_include_path_inventory_digest(f, 2, d1), 0);
f[2].rel_path = "b/rules.mk";
ASSERT_EQ(cbm_include_path_inventory_digest(f, 3, d2), 0);
f[0].rel_path = "b/rules.mk";
f[2].rel_path = "a.proto";
ASSERT_EQ(cbm_include_path_inventory_digest(f, 3, d3), 0);
ASSERT_STR_EQ(d1, d0);
ASSERT_STR_NEQ(d2, d1);
ASSERT_STR_EQ(d3, d2);
PASS();
}
/* Counted work of building the tail index: n files at 1x, 4x, 16x (a
* question makes no work the universe keeps). */
static bool ip_work(int n, uint64_t *steps) {
cbm_file_info_t *files = calloc((size_t)n * 2, sizeof(*files));
char (*names)[64] = calloc((size_t)n * 2, sizeof(*names));
if (!files || !names) {
free(files);
free(names);
return false;
}
for (int i = 0; i < n; i++) {
snprintf(names[2 * i], 64, "d%d/e%d/f%d.proto", i % 10, i % 7, i);
snprintf(names[2 * i + 1], 64, "d%d/src%d.go", i % 10, i);
files[2 * i].rel_path = names[2 * i];
files[2 * i + 1].rel_path = names[2 * i + 1];
}
cbm_include_universe_t *u = cbm_include_universe_new(files, n * 2);
char got[1024];
bool ok = u != NULL;
for (int i = 0; ok && i < n; i++) {
char want[64];
snprintf(want, sizeof(want), "f%d.proto", i);
ok = ip_ask(u, CBM_LANG_PROTOBUF, "top.proto", want, got, sizeof(got)) ==
CBM_INCLUDE_PATH_FILE;
}
*steps = cbm_include_universe_tail_steps(u);
cbm_include_universe_free(u);
free(files);
free(names);
return ok;
}
TEST(include_path_universe_grows_linearly) {
uint64_t s1, s4, s16;
ASSERT_TRUE(ip_work(50, &s1));
ASSERT_TRUE(ip_work(200, &s4));
ASSERT_TRUE(ip_work(800, &s16));
/* index steps: at most 4.5 times per 4 times */
ASSERT_TRUE(s4 * 2 <= s1 * 9 && s16 * 2 <= s4 * 9);
ASSERT_GT(s16, s4);
PASS();
}
/* The IMPORTS decision: a statement that names a file is decided by the path
* rule when it names one indexed file (its node) or provably none (no edge: a
* symbol of the name is never its target); with several candidate files, or
* a guess, main's strategies decide. */
TEST(include_path_names_no_file_decides_no_target) {
static const char *const files[] = {"a.proto", "x/common.proto", "y/dup.proto",
"z/dup.proto", "Makefile", NULL};
cbm_gbuf_t *gb = cbm_gbuf_new("p", "/tmp/p");
char *file_qn = cbm_pipeline_fqn_compute("p", "x/common.proto", "__file__");
ASSERT_GT(
cbm_gbuf_upsert_node(gb, "File", "common.proto", file_qn, "x/common.proto", 1, 1, "{}"), 0);
cbm_pipeline_ctx_t ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.gbuf = gb;
ctx.project_name = "p";
ctx.include_universe = ip_universe(files);
CBMImport imp;
memset(&imp, 0, sizeof(imp));
const cbm_gbuf_node_t *out = NULL;
imp.module_path = "google/protobuf/empty.proto"; /* no indexed file ends with it */
ASSERT_TRUE(cbm_include_path_decides(&ctx, "a.proto", CBM_LANG_PROTOBUF, &imp, &out));
ASSERT_NULL(out);
imp.module_path = "skipped/only.proto"; /* only in a directory the run did not index */
ASSERT_TRUE(cbm_include_path_decides(&ctx, "a.proto", CBM_LANG_PROTOBUF, &imp, &out));
ASSERT_NULL(out);
imp.module_path = "missing.mk";
ASSERT_TRUE(cbm_include_path_decides(&ctx, "Makefile", CBM_LANG_MAKEFILE, &imp, &out));
ASSERT_NULL(out);
/* partners: the named file's node; several files: main decides; a guess:
* main decides */
imp.module_path = "x/common.proto";
ASSERT_TRUE(cbm_include_path_decides(&ctx, "a.proto", CBM_LANG_PROTOBUF, &imp, &out));
ASSERT_NOT_NULL(out);
ASSERT_STR_EQ(out->qualified_name, file_qn);
imp.module_path = "dup.proto";
ASSERT_FALSE(cbm_include_path_decides(&ctx, "a.proto", CBM_LANG_PROTOBUF, &imp, &out));
ASSERT_FALSE(cbm_include_path_decides(&ctx, "y/b.proto", CBM_LANG_PROTOBUF, &imp, &out));
cbm_include_universe_free(ctx.include_universe);
free(file_qn);
cbm_gbuf_free(gb);
PASS();
}
/* ── IMPORTS edges of a real index ───────────────────────────────────────── */
/* How many IMPORTS edges go from the node whose QN ends in `.src` to the node
* whose QN ends in `.tgt`. */
static int ip_imports(const char *db, const char *src, const char *tgt) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int n = -1;
if (sqlite3_prepare_v2(h,
"SELECT count(*) FROM edges e JOIN nodes s ON s.id = e.source_id "
"JOIN nodes t ON t.id = e.target_id WHERE e.type = 'IMPORTS' "
"AND s.qualified_name LIKE '%.' || ?1 AND t.qualified_name LIKE '%.' || ?2",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, src, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 2, tgt, -1, SQLITE_TRANSIENT);
if (sqlite3_step(st) == SQLITE_ROW) {
n = sqlite3_column_int(st, 0);
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return n;
}
/* Red on main: an import that names no repository file got main's edge to a
* same-named symbol (here the Go module mvccpb/kv); it has none now, and the
* import of a real file keeps its edge. A copy under node_modules (not
* indexed) is not seen: alone it names no file, beside an indexed copy the
* indexed one is the only file. Several files and a guess keep main's edge. */
TEST(include_path_edges_name_only_indexed_files) {
char *tmp = th_mktempdir("cbm_ip_edges");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(th_write_file(TH_PATH(dir, "api/rpc.proto"),
"syntax = \"proto3\";\npackage api;\nimport \"etcd/api/mvccpb/kv.proto\";\n"
"import \"kvs/real.proto\";\nimport \"only.proto\";\n"
"import \"common/t.proto\";\nmessage R { int32 a = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "kvs/real.proto"),
"syntax = \"proto3\";\npackage kvs;\nmessage Real { int32 a = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "common/t.proto"),
"syntax = \"proto3\";\npackage common;\nmessage T { int32 a = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "mvccpb/kv.go"),
"package mvccpb\n\ntype KeyValue struct{}\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "node_modules/pkg/only.proto"),
"syntax = \"proto3\";\npackage only;\nmessage O { int32 a = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "node_modules/pkg/common/t.proto"),
"syntax = \"proto3\";\npackage common;\nmessage T { int32 b = 1; }\n"),
0);
/* B1: two files end with common.proto; protoc -I . reads the root one, -I
* svc the other: main's edge (to the root file) stays, never svc/'s */
ASSERT_EQ(th_write_file(TH_PATH(dir, "status.proto"),
"syntax = \"proto3\";\nmessage Status { int32 root_field = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "svc/status.proto"),
"syntax = \"proto3\";\nmessage Status { int32 svc_field = 1; }\n"),
0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "svc/api.proto"),
"syntax = \"proto3\";\npackage api;\nimport \"status.proto\";\n"
"message Req { Status s = 1; }\n"),
0);
char db[512];
snprintf(db, sizeof(db), "%s/ip.db", tmp);
cbm_pipeline_t *p = cbm_pipeline_new(dir, db, CBM_MODE_FULL);
ASSERT_NOT_NULL(p);
ASSERT_EQ(cbm_pipeline_run(p), 0);
cbm_pipeline_free(p);
/* main drew api/rpc.proto -> mvccpb.kv for the etcd path */
ASSERT_EQ(ip_imports(db, "api.rpc.proto.__file__", "mvccpb.kv"), 0);
ASSERT_EQ(ip_imports(db, "api.rpc.proto.__file__", "kvs.real"), 1);
ASSERT_EQ(ip_imports(db, "api.rpc.proto.__file__", "common.t"), 1);
ASSERT_EQ(ip_imports(db, "api.rpc.proto.__file__", "pkg.only"), 0);
ASSERT_EQ(ip_imports(db, "api.rpc.proto.__file__", "pkg.common.t"), 0);
ASSERT_EQ(ip_imports(db, "svc.api.proto.__file__", "svc.status"), 0);
th_cleanup(tmp);
PASS();
}
SUITE(include_path) {
RUN_TEST(include_path_names_no_file_decides_no_target);
RUN_TEST(include_path_proto_tail_guess_and_ambiguity);
RUN_TEST(include_path_make_root_decides_below_is_guess);
RUN_TEST(include_path_universe_is_the_indexed_files);
RUN_TEST(include_path_inventory_digest_follows_indexed_names);
RUN_TEST(include_path_universe_grows_linearly);
RUN_TEST(include_path_edges_name_only_indexed_files);
}
+95
View File
@@ -1896,6 +1896,97 @@ TEST(lrp_python_subclass_constructor_own_init_only) {
PASS();
}
/* ── Ruby: cross-file through the prebuilt project registry ──────────
* Rails/Zeitwerk code names classes in other files with no require, and a
* class may be reopened in a third file. Both edges must come out of the
* Ruby resolver (ruby_* strategy), not the name-based one. */
TEST(lrp_ruby_cross_file_zeitwerk) {
const LRP_File files[] = {
{"app/widget.rb", "class Widget\n"
" def run\n"
" h = Helper.new\n"
" h.assist\n"
" h.extra_step\n"
" end\n"
"end\n"},
{"app/helper.rb", "class Helper\n"
" def assist\n"
" 1\n"
" end\n"
"end\n"},
{"lib/helper_ext.rb", "class Helper\n"
" def extra_step\n"
" 2\n"
" end\n"
"end\n"},
};
LRP_Proj lp;
cbm_store_t *store = lrp_index(&lp, files, 3);
int assist = lrp_exact_calls_by_name(store, lp.project, "run", "assist");
int extra = lrp_exact_calls_by_name(store, lp.project, "run", "extra_step");
int typed = lrp_count_calls_with_strategy(store, lp.project, "ruby_method_typed");
if (assist < 1 || extra < 1 || typed < 2) {
fprintf(stderr, " [LRP] ruby cross-file FAIL assist=%d extra_step=%d typed_edges=%d\n",
assist, extra, typed);
lrp_diag(store, lp.project, "ruby cross-file");
cbm_edge_t *edges = NULL;
int n = 0;
if (store &&
cbm_store_find_edges_by_type(store, lp.project, "CALLS", &edges, &n) == CBM_STORE_OK) {
for (int i = 0; i < n; i++)
fprintf(stderr, " [LRP] CALLS %s\n",
edges[i].properties_json ? edges[i].properties_json : "(none)");
cbm_store_free_edges(edges, n);
}
}
lrp_cleanup(&lp, store);
ASSERT_TRUE(assist >= 1);
ASSERT_TRUE(extra >= 1);
ASSERT_TRUE(typed >= 2);
PASS();
}
/* ── Ruby: singleton side and cross-file mixins, through real extraction ──
* The hand-built-def rows pass the singleton flag and mixin macros in
* themselves; this one has the extractor produce them. `Child.run` is a
* `def self.run`, `Child.new.run` is Base's instance `run`, and `Widget`
* includes a module that overrides Base#greet, all from a caller in a fifth
* file. */
TEST(lrp_ruby_cross_file_singleton_and_mixin) {
const LRP_File files[] = {
{"app/base.rb", "class Base\n def run\n 1\n end\n def greet\n 2\n end\nend\n"},
{"app/overrides.rb", "module Overrides\n def greet\n 3\n end\nend\n"},
{"app/child.rb", "class Child < Base\n def self.run\n 4\n end\nend\n"},
{"app/widget.rb", "class Widget < Base\n include Overrides\nend\n"},
{"app/caller.rb", "class Caller\n"
" def go\n"
" Child.new.run\n"
" Child.run\n"
" Widget.new.greet\n"
" end\n"
"end\n"},
};
LRP_Proj lp;
cbm_store_t *store = lrp_index(&lp, files, 5);
const char *p = store ? lp.project : NULL;
int inst = lrp_exact_edge_by_qn_suffix(store, p, "CALLS", "caller.Caller.go", "base.Base.run");
int klass =
lrp_exact_edge_by_qn_suffix(store, p, "CALLS", "caller.Caller.go", "child.Child.run");
int mixin = lrp_exact_edge_by_qn_suffix(store, p, "CALLS", "caller.Caller.go",
"overrides.Overrides.greet");
int base_greet =
lrp_exact_edge_by_qn_suffix(store, p, "CALLS", "caller.Caller.go", "base.Base.greet");
if (inst != 1 || klass != 1 || mixin != 1 || base_greet != 0)
fprintf(stderr, " [LRP] ruby singleton/mixin FAIL instance=%d class=%d mixin=%d base=%d\n",
inst, klass, mixin, base_greet);
lrp_cleanup(&lp, store);
ASSERT_EQ(inst, 1);
ASSERT_EQ(klass, 1);
ASSERT_EQ(mixin, 1);
ASSERT_EQ(base_greet, 0);
PASS();
}
/* ══════════════════════════════════════════════════════════════════════
* SUITE registration
* ══════════════════════════════════════════════════════════════════════ */
@@ -2014,4 +2105,8 @@ SUITE(lsp_resolution_probe) {
RUN_TEST(lrp_tsx_usage_import_type_with_decoy);
RUN_TEST(lrp_python_usage_instantiation);
RUN_TEST(lrp_python_subclass_constructor_own_init_only);
/* ── Ruby (project registry built once) ── */
RUN_TEST(lrp_ruby_cross_file_zeitwerk);
RUN_TEST(lrp_ruby_cross_file_singleton_and_mixin);
}
+9 -7
View File
@@ -210,14 +210,12 @@ static void tf_cleanup_cache_sentinel(void) {
}
}
/* Client home overrides the CLI honours BEFORE $HOME, so redirecting HOME alone
* does not isolate them: cbm_codex_config_dir() and its siblings return the
* ambient path and the suite resolves against the developer's real config —
* reading its state and writing to it. Same inventory the shell fixtures are
* already required to neutralize (tests/test_smoke_fixture_contract.sh), kept
* in one place so a new client cannot be isolated in the smoke scripts and
* forgotten here. A test that exercises one of these sets it after setup. */
/* These paths take precedence over HOME and can escape the private fixture.
* A test that exercises an override sets it after setup. */
static const char *const tf_client_home_overrides[] = {
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_CACHE_HOME",
"CLAUDE_CONFIG_DIR",
"CODEX_HOME",
"KIRO_HOME",
@@ -1678,6 +1676,8 @@ extern void suite_route_canon(void);
extern void suite_path_alias(void);
extern void suite_site_bind(void);
extern void suite_scope_facts(void);
extern void suite_include_path(void);
extern void suite_scope_closure(void);
extern void suite_svn_state(void);
extern void suite_watcher(void);
extern void suite_lz4(void);
@@ -2545,6 +2545,8 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(path_alias);
RUN_SELECTED_SUITE(site_bind);
RUN_SELECTED_SUITE(scope_facts);
RUN_SELECTED_SUITE(include_path);
RUN_SELECTED_SUITE(scope_closure);
/* Watcher (M10) */
RUN_SELECTED_SUITE(svn_state);
+4 -2
View File
@@ -1349,6 +1349,7 @@ TEST(mcp_tools_list_latest_metadata) {
ASSERT_NOT_NULL(strstr(json, "INHERITS"));
ASSERT_NOT_NULL(strstr(json, "IMPLEMENTS"));
ASSERT_NULL(strstr(json, "TOTAL degree across ALL edge types"));
ASSERT_NOT_NULL(strstr(json, "Keywords; [] ignored; else omit query."));
free(json);
PASS();
}
@@ -5203,7 +5204,7 @@ TEST(tool_search_graph_rejects_bm25_and_semantic_query_together) {
char *tools = cbm_mcp_tools_list();
ASSERT_NOT_NULL(tools);
ASSERT_NOT_NULL(strstr(tools, "[] ignored; otherwise omit query."));
ASSERT_NOT_NULL(strstr(tools, "Keywords; [] ignored; else omit query."));
free(tools);
cbm_mcp_server_free(srv);
@@ -20537,7 +20538,8 @@ static bool dc_walk_fixture_open(dc_walk_fixture_t *fx) {
}
/* Same git invocation rules as the #1363 fixture above. */
char cmd[1200];
const char *steps[] = {"init -q", "add -A", "commit -q -m init"};
const char *steps[] = {"init -q", "config diff.mnemonicPrefix true", "add -A",
"commit -q -m init"};
for (size_t s = 0; s < sizeof(steps) / sizeof(steps[0]); s++) {
snprintf(cmd, sizeof(cmd),
"git -C \"%s\" -c user.name=t -c user.email=t@t.io -c init.defaultBranch=main "
+74
View File
@@ -147,6 +147,44 @@ static const char *PERL_MALFORMED = "package Broken;\n"
"} ] } ]\n"
"sub after_error { return 2; }\n";
/* #1261: a `Language = python` method body is lexed by the ObjectScript
* grammar's external scanner. Up to intersystems/tree-sitter-objectscript
* a7ffcdf it only balanced braces, so a brace inside a Python string, comment
* or docstring ran the body past its closing `}` and the following methods were
* lost in an ERROR region. Since upstream v1.9.15 the scanner lexes these
* bodies with Python's string, triple-quote and `#`-comment rules. */
static const char *OBJECTSCRIPT_PYTHON_BODY_BRACES =
"Class Demo.Py Extends %RegisteredObject\n"
"{\n"
"ClassMethod Fmt() As %String [ Language = python ]\n"
"{\n"
" s = \"open { only\"\n"
" return s\n"
"}\n"
"ClassMethod Note() As %String [ Language = python ]\n"
"{\n"
" # a } in a comment\n"
" return 'x'\n"
"}\n"
"ClassMethod Doc() As %String [ Language = python ]\n"
"{\n"
" \"\"\"docstring with { and no close\"\"\"\n"
" return 'y'\n"
"}\n"
"ClassMethod After() As %String\n"
"{\n"
" Quit \"after\"\n"
"}\n"
"}\n";
/* The refreshed scanner must still report a Python body that never closes. */
static const char *OBJECTSCRIPT_PYTHON_BODY_UNCLOSED =
"Class Demo.Broken Extends %RegisteredObject\n"
"{\n"
"ClassMethod Fmt() As %String [ Language = python ]\n"
"{\n"
" return \"x\"\n";
/* ── Tests ────────────────────────────────────────────────────────────────── */
TEST(c_ifdef_split_brace_sets_parse_incomplete) {
@@ -576,6 +614,40 @@ TEST(perl_malformed_source_remains_partial_issue1838) {
PASS();
}
TEST(objectscript_python_body_braces_parse_completely_issue1261) {
CBMFileResult *r =
do_extract(OBJECTSCRIPT_PYTHON_BODY_BRACES, CBM_LANG_OBJECTSCRIPT_UDL, "Py.cls");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
bool partial = r->parse_incomplete;
int error_regions = r->error_region_count;
bool all_methods =
has_def(r, "Fmt") && has_def(r, "Note") && has_def(r, "Doc") && has_def(r, "After");
if (partial || error_regions != 0 || !all_methods) {
fprintf(stderr,
" ObjectScript Python-body result: partial=%d regions=%d ranges=%s "
"Fmt=%d Note=%d Doc=%d After=%d\n",
partial, error_regions, r->error_ranges ? r->error_ranges : "(none)",
has_def(r, "Fmt"), has_def(r, "Note"), has_def(r, "Doc"), has_def(r, "After"));
cbm_free_result(r);
FAIL("braces inside Python strings, comments and docstrings must not run a "
"Language = python body past its closing brace");
}
cbm_free_result(r);
PASS();
}
TEST(objectscript_unclosed_python_body_remains_partial_issue1261) {
CBMFileResult *r =
do_extract(OBJECTSCRIPT_PYTHON_BODY_UNCLOSED, CBM_LANG_OBJECTSCRIPT_UDL, "Broken.cls");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_TRUE(r->parse_incomplete);
ASSERT_GTE(r->error_region_count, 1);
cbm_free_result(r);
PASS();
}
/* ── #1746: trailing blanks before EOF are still just an absent newline ───────
*
* #1610 suppressed the zero-width MISSING terminator but tested for it with
@@ -2712,6 +2784,8 @@ SUITE(parse_coverage) {
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(objectscript_python_body_braces_parse_completely_issue1261);
RUN_TEST(objectscript_unclosed_python_body_remains_partial_issue1261);
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);
File diff suppressed because it is too large Load Diff
+37
View File
@@ -1887,6 +1887,42 @@ TEST(registry_receiver_gate_judges_type_roots_at_import_fallback) {
PASS();
}
/* Scala: a method declared in the calling file outranks an imported namesake.
* Since Scala imports resolve (#2360), Strategy 4 keeps only the
* import-reachable candidates, and a method of the calling file itself is
* never import-reachable: in typelevel/cats a bare `bimap` in EitherT.scala
* bound Bifunctor's syntax class instead of EitherT's own bimap. */
TEST(registry_scala_same_file_candidate_outranks_imported_namesake) {
const char *mod = "proj.core.src.main.scala.data.Pair";
const char *own = "proj.core.src.main.scala.data.Pair.Pair.bimap";
const char *imported = "proj.core.src.main.scala.other.Bi.Bi.bimap";
const char *keys[] = {"Bi"};
const char *vals[] = {"proj.core.src.main.scala.other.Bi.Bi"};
cbm_registry_t *r = cbm_registry_new();
cbm_registry_add_lang(r, "bimap", own, "Method", CBM_LANG_SCALA, false);
cbm_registry_add_lang(r, "bimap", imported, "Method", CBM_LANG_SCALA, false);
cbm_resolution_t res =
cbm_registry_resolve_call_lang(r, "bimap", mod, keys, vals, 1, CBM_LANG_SCALA);
ASSERT_TRUE(gate_bound(&res, own));
res = cbm_registry_resolve_call_lang(r, "fab.bimap", mod, keys, vals, 1, CBM_LANG_SCALA);
ASSERT_TRUE(gate_bound(&res, own));
/* A caller with no namesake of its own still binds the imported one. */
res = cbm_registry_resolve_call_lang(r, "bimap", "proj.core.src.main.scala.app.Use", keys, vals,
1, CBM_LANG_SCALA);
ASSERT_TRUE(gate_bound(&res, imported));
cbm_registry_free(r);
/* Scala only: the shared path still keeps the import-reachable pick. */
r = cbm_registry_new();
cbm_registry_add_lang(r, "bimap", own, "Method", CBM_LANG_KOTLIN, false);
cbm_registry_add_lang(r, "bimap", imported, "Method", CBM_LANG_KOTLIN, false);
res = cbm_registry_resolve_call_lang(r, "bimap", mod, keys, vals, 1, CBM_LANG_KOTLIN);
ASSERT_TRUE(gate_bound(&res, imported));
cbm_registry_free(r);
PASS();
}
TEST(call_onto_field_follows_language_and_shape) {
/* A call the registry resolved onto a Field node. */
/* Another language: only the spelling connects them. */
@@ -3702,6 +3738,7 @@ SUITE(registry) {
RUN_TEST(registry_receiver_gate_judges_value_receivers);
RUN_TEST(registry_receiver_gate_runs_by_measured_language);
RUN_TEST(registry_receiver_gate_judges_type_roots_at_import_fallback);
RUN_TEST(registry_scala_same_file_candidate_outranks_imported_namesake);
RUN_TEST(call_onto_field_follows_language_and_shape);
RUN_TEST(c_bare_call_does_not_weigh_field_namesakes);
RUN_TEST(c_arrow_member_call_is_c_family_and_arrow_only);
+823 -4
View File
@@ -23,12 +23,18 @@
* 15b. Scope gates (def, params, blocks, reassignment)
* 16. send() / the whole dynamic-dispatch family emits NO edge (negative)
* 16c. Blocks that rebind self emit NO self edge (negative)
* 17. Cross-file: defs from another file resolve
* 18. Cross-file: ActiveRecord repro mirroring the Rails-shaped e2e fixture
* 19. Cross-file: a class reopened in a second file
* 20. Cross-file: compact `class A::B` in another file
* 21. Cross-file: one prebuilt registry serves many files unchanged
* Fail-closed ancestry (7c) and block-nested defs (7d) sit with mixins.
*
* Scope: every row here is SINGLE-FILE, driven through cbm_extract_file so it
* exercises the per-file resolver exactly as the extraction pipeline calls it.
* Cross-file resolution (cbm_run_ruby_lsp_cross, wired through
* pass_lsp_cross.c) is a separate tier and is covered by its own rows.
* Scope: rows 1-16 are SINGLE-FILE, driven through cbm_extract_file so they
* exercise the per-file resolver exactly as the extraction pipeline calls it.
* Rows 17-18 drive cbm_run_ruby_lsp_cross directly with a hand-built
* CBMLSPDef[], which is the shape pass_lsp_cross.c hands it on the
* cbm_pxc_run_one fallback path.
*
* The resolver populates result->resolved_calls with CBMResolvedCall rows.
* The pipeline joins a row to its caller def by EXACT QN equality, so every
@@ -1524,6 +1530,803 @@ TEST(rubylsp_stdlib_seed_survives_alloc_failure) {
PASS();
}
/* ── 17. Cross-file: defs from another file resolve ─────────────── */
TEST(rubylsp_cross_file_defs) {
/* models/user.rb (other file) provides the class; this file calls it.
* Simulates the fallback cbm_pxc_run_one path with a combined def
* list. */
CBMLSPDef defs[3];
memset(defs, 0, sizeof(defs));
defs[0].qualified_name = "test.models.user.User";
defs[0].short_name = "User";
defs[0].label = "Class";
defs[0].def_module_qn = "test.models.user";
defs[0].embedded_types = "ApplicationRecord";
defs[0].lang = CBM_LANG_RUBY;
defs[1].qualified_name = "test.models.user.User.full_name";
defs[1].short_name = "full_name";
defs[1].label = "Method";
defs[1].receiver_type = "test.models.user.User";
defs[1].def_module_qn = "test.models.user";
defs[1].lang = CBM_LANG_RUBY;
defs[2].qualified_name = "test.models.user.User.admin?";
defs[2].short_name = "admin?";
defs[2].label = "Method";
defs[2].receiver_type = "test.models.user.User";
defs[2].def_module_qn = "test.models.user";
defs[2].lang = CBM_LANG_RUBY;
const char *src = "class UsersController\n"
" def show\n"
" u = User.new\n"
" u.full_name\n"
" f = User.find(3)\n"
" f.admin?\n"
" end\n"
"end\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
/* `f = User.find(3)` with User in another file needs the cross-file half
* of the finder rule, which is off by default (ruby_ar_finder_cross_file). */
bool prev = cbm_ruby_set_ar_finder_cross_file(true);
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.controller", defs, 3, NULL,
NULL, 0, NULL, &out);
(void)cbm_ruby_set_ar_finder_cross_file(prev);
bool ctor = false;
bool full_name = false;
bool admin = false;
for (int i = 0; i < out.count; i++) {
if (!out.items[i].callee_qn || !out.items[i].caller_qn)
continue;
if (strcmp(out.items[i].caller_qn, "test.app.controller.UsersController.show") != 0)
continue;
if (strcmp(out.items[i].callee_qn, "test.models.user.User") == 0)
ctor = true;
if (strcmp(out.items[i].callee_qn, "test.models.user.User.full_name") == 0)
full_name = true;
if (strcmp(out.items[i].callee_qn, "test.models.user.User.admin?") == 0)
admin = true;
}
if (!(ctor && full_name && admin)) {
printf(" cross-file rows (%d):\n", out.count);
for (int i = 0; i < out.count; i++)
printf(" %s -> %s [%s]\n", out.items[i].caller_qn, out.items[i].callee_qn,
out.items[i].strategy);
}
cbm_arena_destroy(&arena);
ASSERT(ctor);
ASSERT(full_name);
ASSERT(admin);
PASS();
}
/* ── 18. Cross-file: AR repro mirroring the e2e fixture exactly ── */
TEST(rubylsp_cross_file_ar_repro) {
CBMLSPDef defs[6];
memset(defs, 0, sizeof(defs));
defs[0].qualified_name = "e2e.app.models.user.User";
defs[0].short_name = "User";
defs[0].label = "Class";
defs[0].def_module_qn = "e2e.app.models.user";
defs[0].embedded_types = "ApplicationRecord";
defs[0].lang = CBM_LANG_RUBY;
defs[1].qualified_name = "e2e.app.models.user.User.full_name";
defs[1].short_name = "full_name";
defs[1].label = "Method";
defs[1].receiver_type = "e2e.app.models.user.User";
defs[1].def_module_qn = "e2e.app.models.user";
defs[1].lang = CBM_LANG_RUBY;
defs[2].qualified_name = "e2e.app.models.user.User.deactivate!";
defs[2].short_name = "deactivate!";
defs[2].label = "Method";
defs[2].receiver_type = "e2e.app.models.user.User";
defs[2].def_module_qn = "e2e.app.models.user";
defs[2].lang = CBM_LANG_RUBY;
defs[3].qualified_name = "e2e.app.models.application_record.ApplicationRecord";
defs[3].short_name = "ApplicationRecord";
defs[3].label = "Class";
defs[3].def_module_qn = "e2e.app.models.application_record";
defs[3].embedded_types = "ActiveRecord::Base";
defs[3].lang = CBM_LANG_RUBY;
defs[4].qualified_name = "e2e.app.services.greeter.Greeter";
defs[4].short_name = "Greeter";
defs[4].label = "Class";
defs[4].def_module_qn = "e2e.app.services.greeter";
defs[4].lang = CBM_LANG_RUBY;
defs[5].qualified_name = "e2e.app.services.greeter.Greeter.greet";
defs[5].short_name = "greet";
defs[5].label = "Method";
defs[5].receiver_type = "e2e.app.services.greeter.Greeter";
defs[5].def_module_qn = "e2e.app.services.greeter";
defs[5].lang = CBM_LANG_RUBY;
const char *src = "class Report\n"
" def generate(id)\n"
" user = User.find(id)\n"
" name = user.full_name\n"
" greeter = Greeter.new(user)\n"
" greeter.greet\n"
" user.deactivate!\n"
" name\n"
" end\n"
"end\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
/* `user = User.find(id)` with User in another file: cross-file finder rule. */
bool prev = cbm_ruby_set_ar_finder_cross_file(true);
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "e2e.app.services.report", defs, 6, NULL,
NULL, 0, NULL, &out);
(void)cbm_ruby_set_ar_finder_cross_file(prev);
bool full_name = false;
bool deact = false;
bool greet = false;
for (int i = 0; i < out.count; i++) {
if (!out.items[i].callee_qn)
continue;
if (strcmp(out.items[i].callee_qn, "e2e.app.models.user.User.full_name") == 0)
full_name = true;
if (strcmp(out.items[i].callee_qn, "e2e.app.models.user.User.deactivate!") == 0)
deact = true;
if (strcmp(out.items[i].callee_qn, "e2e.app.services.greeter.Greeter.greet") == 0)
greet = true;
}
if (!(full_name && deact && greet)) {
printf(" AR-repro rows (%d):\n", out.count);
for (int i = 0; i < out.count; i++)
printf(" %s -> %s [%s]\n", out.items[i].caller_qn, out.items[i].callee_qn,
out.items[i].strategy);
}
cbm_arena_destroy(&arena);
ASSERT(greet);
ASSERT(full_name);
ASSERT(deact);
PASS();
}
/* ── 19-21. Cross-file: the shared project registry ─────────────── */
static void cross_def(CBMLSPDef *d, const char *qn, const char *short_name, const char *label,
const char *module_qn, const char *receiver, const char *embedded) {
memset(d, 0, sizeof(*d));
d->qualified_name = qn;
d->short_name = short_name;
d->label = label;
d->def_module_qn = module_qn;
d->receiver_type = receiver;
d->embedded_types = embedded;
d->lang = CBM_LANG_RUBY;
}
/* Caller and callee both match exactly, as find_resolved_exact does for the
* single-file rows: a substring match would let a row pass on the wrong caller. */
static bool out_has(const CBMResolvedCallArray *out, const char *caller, const char *callee) {
for (int i = 0; i < out->count; i++) {
if (out->items[i].caller_qn && out->items[i].callee_qn &&
strcmp(out->items[i].caller_qn, caller) == 0 &&
strcmp(out->items[i].callee_qn, callee) == 0)
return true;
}
return false;
}
static void out_dump(const CBMResolvedCallArray *out) {
for (int i = 0; i < out->count; i++)
printf(" %s -> %s [%s]\n", out->items[i].caller_qn, out->items[i].callee_qn,
out->items[i].strategy);
}
TEST(rubylsp_cross_reopened_class_across_files) {
/* `class User` is reopened in a second file. Each file's class has its
* own QN (it carries the file's module QN) but one constant path, so a
* method defined in either reopening must be found, and the constructor
* edge lands on the first declaration. */
CBMLSPDef defs[4];
cross_def(&defs[0], "test.a.User", "User", "Class", "test.a", NULL, NULL);
cross_def(&defs[1], "test.a.User.name", "name", "Method", "test.a", "test.a.User", NULL);
cross_def(&defs[2], "test.b.User", "User", "Class", "test.b", NULL, NULL);
cross_def(&defs[3], "test.b.User.email", "email", "Method", "test.b", "test.b.User", NULL);
const char *src = "class Report\n"
" def run\n"
" u = User.new\n"
" u.name\n"
" u.email\n"
" end\n"
"end\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.report", defs, 4, NULL, NULL, 0,
NULL, &out);
bool ctor = out_has(&out, "test.app.report.Report.run", "test.a.User");
bool name = out_has(&out, "test.app.report.Report.run", "test.a.User.name");
bool email = out_has(&out, "test.app.report.Report.run", "test.b.User.email");
if (!(ctor && name && email))
out_dump(&out);
cbm_arena_destroy(&arena);
ASSERT(ctor);
ASSERT(name);
ASSERT(email);
PASS();
}
TEST(rubylsp_cross_compact_class_name) {
/* A compact `class Admin::User` in another file has QN
* "<module>.Admin::User" but is found through the dotted path
* "Admin.User". */
CBMLSPDef defs[2];
cross_def(&defs[0], "test.admin.Admin::User", "User", "Class", "test.admin", NULL, NULL);
cross_def(&defs[1], "test.admin.Admin::User.greet", "greet", "Method", "test.admin",
"test.admin.Admin::User", NULL);
const char *src = "class Welcome\n"
" def run\n"
" Admin::User.new.greet\n"
" end\n"
"end\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.welcome", defs, 2, NULL, NULL,
0, NULL, &out);
bool ctor = out_has(&out, "test.app.welcome.Welcome.run", "test.admin.Admin::User");
bool greet = out_has(&out, "test.app.welcome.Welcome.run", "test.admin.Admin::User.greet");
if (!(ctor && greet))
out_dump(&out);
cbm_arena_destroy(&arena);
ASSERT(ctor);
ASSERT(greet);
PASS();
}
TEST(rubylsp_cross_registry_built_once_serves_many_files) {
/* One registry, several files, superclass chain across files: the shared
* registry is read-only, so later files see exactly what earlier ones did
* and nothing a file declares leaks into it. */
CBMLSPDef defs[4];
cross_def(&defs[0], "test.base.Base", "Base", "Class", "test.base", NULL, NULL);
cross_def(&defs[1], "test.base.Base.shared_m", "shared_m", "Method", "test.base",
"test.base.Base", NULL);
cross_def(&defs[2], "test.child.Child", "Child", "Class", "test.child", NULL, "Base");
cross_def(&defs[3], "test.child.Child.own_m", "own_m", "Method", "test.child",
"test.child.Child", NULL);
CBMArena build;
cbm_arena_init(&build);
CBMRubyCrossRegistry *sh = cbm_ruby_build_cross_registry(&build, defs, 4);
ASSERT(sh != NULL);
int classes_before = sh->class_count;
int funcs_before = sh->reg.func_count;
/* The counts cannot see a written field (a visit mark on a shared entry,
* say), so keep a byte copy of the class array and both hash indexes and
* compare them after the resolves. */
size_t classes_bytes = (size_t)sh->class_count * sizeof(RubyClassInfo);
size_t slots_bytes = ((size_t)sh->slot_mask + 1) * sizeof(int);
char *snap_classes = (char *)malloc(classes_bytes);
char *snap_by_qn = (char *)malloc(slots_bytes);
char *snap_by_path = (char *)malloc(slots_bytes);
char *snap_by_pp = (char *)malloc(slots_bytes);
ASSERT(snap_classes && snap_by_qn && snap_by_path && snap_by_pp);
memcpy(snap_classes, sh->classes, classes_bytes);
memcpy(snap_by_qn, sh->by_qn, slots_bytes);
memcpy(snap_by_path, sh->by_path, slots_bytes);
memcpy(snap_by_pp, sh->by_pp, slots_bytes);
const char *src1 =
"class One\n def run\n c = Child.new\n c.shared_m\n c.own_m\n end\nend\n";
const char *src2 = "class Two\n def run\n Child.new.shared_m\n end\nend\n";
const char *src3 = "class Three\n def run\n Local.new.shared_m\n end\nend\n";
CBMArena a1;
CBMArena a2;
CBMArena a3;
cbm_arena_init(&a1);
cbm_arena_init(&a2);
cbm_arena_init(&a3);
CBMResolvedCallArray o1;
CBMResolvedCallArray o2;
CBMResolvedCallArray o3;
memset(&o1, 0, sizeof(o1));
memset(&o2, 0, sizeof(o2));
memset(&o3, 0, sizeof(o3));
cbm_run_ruby_lsp_cross_with_registry(&a1, src1, (int)strlen(src1), "test.app.one", sh, NULL,
NULL, 0, NULL, &o1);
cbm_run_ruby_lsp_cross_with_registry(&a2, src2, (int)strlen(src2), "test.app.two", sh, NULL,
NULL, 0, NULL, &o2);
cbm_run_ruby_lsp_cross_with_registry(&a3, src3, (int)strlen(src3), "test.app.three", sh, NULL,
NULL, 0, NULL, &o3);
bool one_inherited = out_has(&o1, "test.app.one.One.run", "test.base.Base.shared_m");
bool one_own = out_has(&o1, "test.app.one.One.run", "test.child.Child.own_m");
bool two_inherited = out_has(&o2, "test.app.two.Two.run", "test.base.Base.shared_m");
bool three_none = !out_has(&o3, "test.app.three.Three.run", "test.base.Base.shared_m");
bool untouched = sh->class_count == classes_before && sh->reg.func_count == funcs_before &&
memcmp(snap_classes, sh->classes, classes_bytes) == 0 &&
memcmp(snap_by_qn, sh->by_qn, slots_bytes) == 0 &&
memcmp(snap_by_path, sh->by_path, slots_bytes) == 0 &&
memcmp(snap_by_pp, sh->by_pp, slots_bytes) == 0;
free(snap_by_pp);
free(snap_classes);
free(snap_by_qn);
free(snap_by_path);
if (!(one_inherited && one_own && two_inherited && three_none && untouched)) {
out_dump(&o1);
out_dump(&o2);
out_dump(&o3);
}
cbm_arena_destroy(&a1);
cbm_arena_destroy(&a2);
cbm_arena_destroy(&a3);
cbm_arena_destroy(&build);
ASSERT(one_inherited);
ASSERT(one_own);
ASSERT(two_inherited);
ASSERT(three_none);
ASSERT(untouched);
PASS();
}
/* A class reopened in `reopenings` files (`Widget`, one module each, the first
* declaring `< CxBase`), plus the base. Work is counted for the registry build
* and for resolving one fixed file whose call sites all miss on the head's own
* methods (`label` is inherited from CxBase). */
static bool rubylsp_reopen_work(int reopenings, uint64_t *build_work, uint64_t *resolve_work) {
int n = reopenings * 2 + 2;
CBMLSPDef *defs = (CBMLSPDef *)calloc((size_t)n, sizeof(CBMLSPDef));
char (*names)[64] = (char (*)[64])calloc((size_t)n * 3, sizeof(*names));
if (!defs || !names) {
free(defs);
free(names);
return false;
}
int d = 0;
int nm = 0;
cross_def(&defs[d++], "test.base.CxBase", "CxBase", "Class", "test.base", NULL, NULL);
cross_def(&defs[d++], "test.base.CxBase.label", "label", "Method", "test.base",
"test.base.CxBase", NULL);
for (int i = 0; i < reopenings; i++) {
char *mod = names[nm++];
char *cls = names[nm++];
char *meth = names[nm++];
snprintf(mod, 64, "test.m%d", i);
snprintf(cls, 64, "test.m%d.CxWidget", i);
snprintf(meth, 64, "test.m%d.CxWidget.own%d", i, i);
cross_def(&defs[d++], cls, "CxWidget", "Class", mod, NULL, i == 0 ? "CxBase" : NULL);
cross_def(&defs[d++], meth, "own", "Method", mod, cls, NULL);
}
CBMArena build;
cbm_arena_init(&build);
(void)cbm_lsp_work_take();
CBMRubyCrossRegistry *sh = cbm_ruby_build_cross_registry(&build, defs, d);
*build_work = cbm_lsp_work_take();
const char *src = "class CxCaller\n def run\n w = CxWidget.new\n w.label\n"
" w.label\n w.label\n w.label\n w.label\n w.label\n"
" w.label\n w.label\n end\nend\n";
CBMArena a;
cbm_arena_init(&a);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
(void)cbm_lsp_work_take();
if (sh)
cbm_run_ruby_lsp_cross_with_registry(&a, src, (int)strlen(src), "test.app.caller", sh, NULL,
NULL, 0, NULL, &out);
*resolve_work = cbm_lsp_work_take();
bool resolved = out_has(&out, "test.app.caller.CxCaller.run", "test.base.CxBase.label");
cbm_arena_destroy(&a);
cbm_arena_destroy(&build);
free(defs);
free(names);
return sh && resolved;
}
/* Review items 2b / 2c / 3. Constants are global, so a namespace module or a
* model is reopened in many files. Doubling the reopenings must at most double
* the registry build (a per-reopening tail walk makes it R^2/2, ratio 4), and
* must not change what resolving one fixed file costs at all: a lookup is one
* probe however many files reopen the class (a group walk per miss makes it
* grow with R). The resolve gate is therefore 1.5, not the build gate of 3. */
TEST(rubylsp_cross_reopened_class_work_is_bounded) {
uint64_t build_r = 0;
uint64_t resolve_r = 0;
uint64_t build_2r = 0;
uint64_t resolve_2r = 0;
ASSERT(rubylsp_reopen_work(64, &build_r, &resolve_r));
ASSERT(rubylsp_reopen_work(128, &build_2r, &resolve_2r));
printf(" reopened-class work: build R=64 %llu, 2R %llu; resolve R=64 %llu, 2R %llu\n",
(unsigned long long)build_r, (unsigned long long)build_2r, (unsigned long long)resolve_r,
(unsigned long long)resolve_2r);
ASSERT(build_2r < 3 * (build_r ? build_r : 1));
ASSERT(2 * resolve_2r < 3 * (resolve_r ? resolve_r : 1));
PASS();
}
/* Review item 4: the merged record must not depend on def order. A full build
* orders defs by file index; the incremental closure route appends fresh defs
* to the persisted ones, so the same project can arrive in any order. The head
* is the smallest QN, the superclass comes from the smallest-QN declaration
* that has one, and a method defined by two reopenings resolves to the smaller
* QN. Built forwards and reversed, the resolved edges must be identical. */
static void rubylsp_order_defs(CBMLSPDef *defs, bool reversed) {
CBMLSPDef t[10];
cross_def(&t[0], "test.m2.CxWidget", "CxWidget", "Class", "test.m2", NULL, "CxOther");
cross_def(&t[1], "test.m2.CxWidget.dup_m", "dup_m", "Method", "test.m2", "test.m2.CxWidget",
NULL);
cross_def(&t[2], "test.m1.CxWidget", "CxWidget", "Class", "test.m1", NULL, "CxBase");
cross_def(&t[3], "test.m1.CxWidget.dup_m", "dup_m", "Method", "test.m1", "test.m1.CxWidget",
NULL);
cross_def(&t[4], "test.m0.CxWidget", "CxWidget", "Class", "test.m0", NULL, NULL);
cross_def(&t[5], "test.m0.CxWidget.own", "own", "Method", "test.m0", "test.m0.CxWidget", NULL);
cross_def(&t[6], "test.base.CxBase", "CxBase", "Class", "test.base", NULL, NULL);
cross_def(&t[7], "test.base.CxBase.label", "label", "Method", "test.base", "test.base.CxBase",
NULL);
cross_def(&t[8], "test.base.CxOther", "CxOther", "Class", "test.base", NULL, NULL);
cross_def(&t[9], "test.base.CxOther.label", "label", "Method", "test.base", "test.base.CxOther",
NULL);
for (int i = 0; i < 10; i++)
defs[i] = reversed ? t[9 - i] : t[i];
}
static bool rubylsp_order_edges(bool reversed, bool *ctor, bool *label, bool *dup, bool *own) {
CBMLSPDef defs[10];
rubylsp_order_defs(defs, reversed);
const char *src = "class CxCaller\n def run\n w = CxWidget.new\n w.label\n"
" w.dup_m\n w.own\n end\nend\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.caller", defs, 10, NULL, NULL,
0, NULL, &out);
*ctor = out_has(&out, "test.app.caller.CxCaller.run", "test.m0.CxWidget");
*label = out_has(&out, "test.app.caller.CxCaller.run", "test.base.CxBase.label");
*dup = out_has(&out, "test.app.caller.CxCaller.run", "test.m1.CxWidget.dup_m");
*own = out_has(&out, "test.app.caller.CxCaller.run", "test.m0.CxWidget.own");
if (!(*ctor && *label && *dup && *own))
out_dump(&out);
cbm_arena_destroy(&arena);
return true;
}
TEST(rubylsp_cross_same_named_classes_stay_in_their_package) {
/* Two packages of one repository each declare their own Topic. A call
* from inside a package reaches that package's Topic, never the other's;
* a caller in a third package, where the constant is declared under
* several roots and none is its own, resolves nothing; a constant
* declared under one root only still resolves from anywhere. */
CBMLSPDef defs[7];
cross_def(&defs[0], "proj.alpha.test.models.topic.Topic", "Topic", "Class",
"proj.alpha.test.models.topic", NULL, NULL);
cross_def(&defs[1], "proj.alpha.test.models.topic.Topic.hello", "hello", "Method",
"proj.alpha.test.models.topic", "proj.alpha.test.models.topic.Topic", NULL);
cross_def(&defs[2], "proj.beta.test.models.topic.Topic", "Topic", "Class",
"proj.beta.test.models.topic", NULL, NULL);
cross_def(&defs[3], "proj.beta.test.models.topic.Topic.hello", "hello", "Method",
"proj.beta.test.models.topic", "proj.beta.test.models.topic.Topic", NULL);
cross_def(&defs[4], "proj.beta.lib.only.Only", "Only", "Class", "proj.beta.lib.only", NULL,
NULL);
cross_def(&defs[5], "proj.beta.lib.only.Only.ping", "ping", "Method", "proj.beta.lib.only",
"proj.beta.lib.only.Only", NULL);
cross_def(&defs[6], "proj.alpha.lib.x.X", "X", "Class", "proj.alpha.lib.x", NULL, NULL);
CBMArena build;
cbm_arena_init(&build);
CBMRubyCrossRegistry *sh = cbm_ruby_build_cross_registry(&build, defs, 7);
ASSERT(sh != NULL);
const char *src =
"class Caller\n def run\n Topic.new.hello\n Only.new.ping\n end\nend\n";
const char *mods[3] = {"proj.alpha.test.cases.caller", "proj.beta.test.cases.caller",
"proj.gamma.test.cases.caller"};
const char *callers[3] = {"proj.alpha.test.cases.caller.Caller.run",
"proj.beta.test.cases.caller.Caller.run",
"proj.gamma.test.cases.caller.Caller.run"};
bool alpha_ok = false;
bool beta_ok = false;
bool gamma_none = false;
bool only_all = true;
for (int i = 0; i < 3; i++) {
CBMArena a;
cbm_arena_init(&a);
CBMResolvedCallArray o;
memset(&o, 0, sizeof(o));
cbm_run_ruby_lsp_cross_with_registry(&a, src, (int)strlen(src), mods[i], sh, NULL, NULL, 0,
NULL, &o);
bool alpha = out_has(&o, callers[i], "proj.alpha.test.models.topic.Topic.hello");
bool beta = out_has(&o, callers[i], "proj.beta.test.models.topic.Topic.hello");
if (i == 0)
alpha_ok = alpha && !beta;
else if (i == 1)
beta_ok = beta && !alpha;
else
gamma_none = !alpha && !beta;
only_all = only_all && out_has(&o, callers[i], "proj.beta.lib.only.Only.ping");
if (!(only_all && (i != 0 || alpha_ok)))
out_dump(&o);
cbm_arena_destroy(&a);
}
cbm_arena_destroy(&build);
ASSERT(alpha_ok);
ASSERT(beta_ok);
ASSERT(gamma_none);
ASSERT(only_all);
PASS();
}
TEST(rubylsp_cross_ambiguous_nested_constant_does_not_fall_through) {
/* Inside `module M`, `X` names M::X when M::X exists. Two packages
* declare M::X and a third declares a top-level X. A caller in a fourth
* package, inside module M, must not land on the top-level X (Ruby binds
* M::X there; which package's is unknown, so nothing). A caller in
* alpha binds alpha's M::X. Three packages share M::X so the per-path
* chain holds more than two heads. */
CBMLSPDef defs[8];
cross_def(&defs[0], "proj.alpha.lib.mx.M.X", "X", "Class", "proj.alpha.lib.mx", NULL, NULL);
cross_def(&defs[1], "proj.alpha.lib.mx.M.X.hello", "hello", "Method", "proj.alpha.lib.mx",
"proj.alpha.lib.mx.M.X", NULL);
cross_def(&defs[2], "proj.beta.lib.mx.M.X", "X", "Class", "proj.beta.lib.mx", NULL, NULL);
cross_def(&defs[3], "proj.beta.lib.mx.M.X.hello", "hello", "Method", "proj.beta.lib.mx",
"proj.beta.lib.mx.M.X", NULL);
cross_def(&defs[4], "proj.eta.lib.mx.M.X", "X", "Class", "proj.eta.lib.mx", NULL, NULL);
cross_def(&defs[5], "proj.eta.lib.mx.M.X.hello", "hello", "Method", "proj.eta.lib.mx",
"proj.eta.lib.mx.M.X", NULL);
cross_def(&defs[6], "proj.gamma.lib.x.X", "X", "Class", "proj.gamma.lib.x", NULL, NULL);
cross_def(&defs[7], "proj.gamma.lib.x.X.hello", "hello", "Method", "proj.gamma.lib.x",
"proj.gamma.lib.x.X", NULL);
CBMArena build;
cbm_arena_init(&build);
CBMRubyCrossRegistry *sh = cbm_ruby_build_cross_registry(&build, defs, 8);
ASSERT(sh != NULL);
const char *src =
"module M\n class Caller\n def run\n X.new.hello\n end\n end\nend\n";
const char *mods[2] = {"proj.delta.lib.caller", "proj.alpha.lib.caller"};
const char *callers[2] = {"proj.delta.lib.caller.M.Caller.run",
"proj.alpha.lib.caller.M.Caller.run"};
bool delta_none = false;
bool alpha_own = false;
for (int i = 0; i < 2; i++) {
CBMArena a;
cbm_arena_init(&a);
CBMResolvedCallArray o;
memset(&o, 0, sizeof(o));
cbm_run_ruby_lsp_cross_with_registry(&a, src, (int)strlen(src), mods[i], sh, NULL, NULL, 0,
NULL, &o);
bool top = out_has(&o, callers[i], "proj.gamma.lib.x.X.hello");
bool alpha = out_has(&o, callers[i], "proj.alpha.lib.mx.M.X.hello");
bool beta = out_has(&o, callers[i], "proj.beta.lib.mx.M.X.hello");
bool eta = out_has(&o, callers[i], "proj.eta.lib.mx.M.X.hello");
if (i == 0)
delta_none = !top && !alpha && !beta && !eta;
else
alpha_own = alpha && !top && !beta && !eta;
if (!(i == 0 ? delta_none : alpha_own))
out_dump(&o);
cbm_arena_destroy(&a);
}
cbm_arena_destroy(&build);
ASSERT(delta_none);
ASSERT(alpha_own);
PASS();
}
TEST(rubylsp_cross_registry_is_def_order_independent) {
bool f[4];
bool r[4];
ASSERT(rubylsp_order_edges(false, &f[0], &f[1], &f[2], &f[3]));
ASSERT(rubylsp_order_edges(true, &r[0], &r[1], &r[2], &r[3]));
/* head = smallest QN (m0), superclass from the smallest-QN declaration
* that has one (m1's CxBase, not m2's CxOther), duplicate method from the
* smaller QN (m1) — in both orders. */
for (int i = 0; i < 4; i++) {
ASSERT(f[i]);
ASSERT(r[i]);
}
PASS();
}
/* ── cross-file: singleton side and mixins (review items 5, 6) ───── */
static const CBMDefinition *rubylsp_find_def(const CBMFileResult *r, const char *name) {
for (int i = 0; i < r->defs.count; i++) {
if (r->defs.items[i].name && strcmp(r->defs.items[i].name, name) == 0)
return &r->defs.items[i];
}
return NULL;
}
/* The extractor knows what CBMLSPDef used to lose: which methods sit on the
* singleton side (`def self.m`, `class << self`) and which mixin macros a
* class body holds. Only constants count; `extend self` is not one. */
TEST(rubylsp_extractor_flags_singleton_methods_and_mixins) {
const char *src = "class Widget < Base\n"
" include Auditable\n"
" prepend Admin::Guard\n"
" extend Finders\n"
" extend self\n"
" def inst\n end\n"
" def self.make\n end\n"
" class << self\n"
" def build\n end\n"
" end\n"
"end\n";
CBMFileResult *r = extract_ruby(src);
ASSERT(r != NULL);
const CBMDefinition *w = rubylsp_find_def(r, "Widget");
const CBMDefinition *inst = rubylsp_find_def(r, "inst");
const CBMDefinition *make = rubylsp_find_def(r, "make");
const CBMDefinition *build = rubylsp_find_def(r, "build");
bool ok = w && inst && make;
bool mixins =
ok && w->mixin_refs && strcmp(w->mixin_refs, "i:Auditable|p:Admin::Guard|e:Finders") == 0;
/* A method inside `class << self`, when the extractor emits one at all,
* must be on the singleton side. */
bool flags = ok && !inst->is_singleton && make->is_singleton && (!build || build->is_singleton);
printf(" defs: Widget=%d inst=%d make=%d build=%d (class << self def emitted: %s)\n",
w != NULL, inst != NULL, make != NULL, build != NULL, build ? "yes" : "no");
if (!(mixins && flags))
printf(" mixin_refs=%s\n", ok && w->mixin_refs ? w->mixin_refs : "(null)");
cbm_free_result(r);
ASSERT(ok);
ASSERT(mixins);
ASSERT(flags);
PASS();
}
/* Review item 5. `Child` defines `def self.run` and inherits instance `run`
* from Base. An instance call must reach Base#run, the one Ruby would call; a
* class-side call must reach Child.run. Registering each method on both keys
* made the instance call stop at the singleton. */
TEST(rubylsp_cross_singleton_and_instance_do_not_shadow) {
CBMLSPDef defs[4];
cross_def(&defs[0], "test.base.Base", "Base", "Class", "test.base", NULL, NULL);
cross_def(&defs[1], "test.base.Base.run", "run", "Method", "test.base", "test.base.Base", NULL);
cross_def(&defs[2], "test.child.Child", "Child", "Class", "test.child", NULL, "Base");
cross_def(&defs[3], "test.child.Child.run", "run", "Method", "test.child", "test.child.Child",
NULL);
defs[3].is_singleton = true;
const char *src = "class Caller\n def go\n Child.new.run\n Child.run\n end\nend\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.caller", defs, 4, NULL, NULL, 0,
NULL, &out);
bool instance = out_has(&out, "test.app.caller.Caller.go", "test.base.Base.run");
bool klass = out_has(&out, "test.app.caller.Caller.go", "test.child.Child.run");
if (!(instance && klass))
out_dump(&out);
cbm_arena_destroy(&arena);
ASSERT(instance);
ASSERT(klass);
PASS();
}
static bool rubylsp_mixin_call(const char *decl_mixin, bool reopen_elsewhere, bool *module_hit,
bool *base_hit) {
CBMLSPDef defs[8];
int n = 0;
cross_def(&defs[n++], "test.base.Base", "Base", "Class", "test.base", NULL, NULL);
cross_def(&defs[n++], "test.base.Base.greet", "greet", "Method", "test.base", "test.base.Base",
NULL);
cross_def(&defs[n++], "test.mod.Overrides", "Overrides", "Module", "test.mod", NULL, NULL);
cross_def(&defs[n++], "test.mod.Overrides.greet", "greet", "Method", "test.mod",
"test.mod.Overrides", NULL);
/* The class is declared in file A (the head); the include is in A, or in
* a reopening in a later file Z. */
cross_def(&defs[n++], "test.a.Widget", "Widget", "Class", "test.a", NULL, "Base");
if (!reopen_elsewhere)
defs[n - 1].mixin_refs = decl_mixin;
if (reopen_elsewhere) {
cross_def(&defs[n++], "test.z.Widget", "Widget", "Class", "test.z", NULL, NULL);
defs[n - 1].mixin_refs = decl_mixin;
}
const char *src = "class Caller\n def go\n Widget.new.greet\n end\nend\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.caller", defs, n, NULL, NULL, 0,
NULL, &out);
*module_hit = out_has(&out, "test.app.caller.Caller.go", "test.mod.Overrides.greet");
*base_hit = out_has(&out, "test.app.caller.Caller.go", "test.base.Base.greet");
if (!*module_hit && !*base_hit && out.count > 1)
out_dump(&out);
cbm_arena_destroy(&arena);
return true;
}
/* Review item 6. A module the class includes shadows the superclass's method,
* whichever file the class and the include are in. A call from file B must not
* resolve to Base#greet, and an include of a module the table cannot see must
* block the walk rather than fall through to the superclass. */
TEST(rubylsp_cross_mixin_shadows_superclass_across_files) {
bool module_hit;
bool base_hit;
ASSERT(rubylsp_mixin_call("i:Overrides", false, &module_hit, &base_hit));
ASSERT(module_hit);
ASSERT(!base_hit);
PASS();
}
TEST(rubylsp_cross_mixin_in_reopening_shadows_superclass) {
bool module_hit;
bool base_hit;
ASSERT(rubylsp_mixin_call("i:Overrides", true, &module_hit, &base_hit));
ASSERT(module_hit);
ASSERT(!base_hit);
PASS();
}
TEST(rubylsp_cross_unseen_mixin_blocks_superclass) {
bool module_hit;
bool base_hit;
ASSERT(rubylsp_mixin_call("i:Missing", false, &module_hit, &base_hit));
ASSERT(!module_hit);
ASSERT(!base_hit);
PASS();
}
/* The finder rule (`User.find` -> User, relation chains keep the model) for a
* model declared in ANOTHER file, the usual Rails layout. It is one switch
* (ruby_ar_finder_cross_file): off by default, which keeps the rule to models
* declared in the file being resolved, with nothing else changed; on, it also
* types models from other files. */
static bool rubylsp_ar_finder_cross_edge(void) {
CBMLSPDef defs[2];
cross_def(&defs[0], "test.models.user.User", "User", "Class", "test.models.user", NULL,
"ApplicationRecord");
cross_def(&defs[1], "test.models.user.User.full_name", "full_name", "Method",
"test.models.user", "test.models.user.User", NULL);
const char *src = "class Svc\n def go\n User.find(1).full_name\n "
"User.where(active: true).first.full_name\n end\nend\n";
CBMArena arena;
cbm_arena_init(&arena);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
cbm_run_ruby_lsp_cross(&arena, src, (int)strlen(src), "test.app.svc", defs, 2, NULL, NULL, 0,
NULL, &out);
bool edge = out_has(&out, "test.app.svc.Svc.go", "test.models.user.User.full_name");
cbm_arena_destroy(&arena);
return edge;
}
TEST(rubylsp_cross_ar_finder_same_file_only_by_default) {
/* Default: a model from another file gets no finder typing, while a model
* declared in the file being resolved still does. */
bool cross = rubylsp_ar_finder_cross_edge();
const char *src = "class User < ApplicationRecord\n def full_name\n 'x'\n end\nend\n"
"class UsersController < ApplicationController\n def show\n"
" User.find(1).full_name\n end\nend\n";
CBMFileResult *r = extract_ruby(src);
bool same = r && find_resolved(r, "UsersController.show", "User.full_name") >= 0;
if (r)
cbm_free_result(r);
ASSERT(!cross);
ASSERT(same);
PASS();
}
TEST(rubylsp_cross_ar_finder_crosses_files_when_switched_on) {
bool prev = cbm_ruby_set_ar_finder_cross_file(true);
bool cross = rubylsp_ar_finder_cross_edge();
(void)cbm_ruby_set_ar_finder_cross_file(prev);
ASSERT(cross);
PASS();
}
/* ── suite ──────────────────────────────────────────────────────── */
void suite_ruby_lsp(void) {
@@ -1563,4 +2366,20 @@ void suite_ruby_lsp(void) {
RUN_TEST(rubylsp_mixin_walk_visits_each_module_once);
RUN_TEST(rubylsp_const_path_is_linear);
RUN_TEST(rubylsp_stdlib_seed_survives_alloc_failure);
RUN_TEST(rubylsp_cross_file_defs);
RUN_TEST(rubylsp_cross_file_ar_repro);
RUN_TEST(rubylsp_cross_reopened_class_across_files);
RUN_TEST(rubylsp_cross_compact_class_name);
RUN_TEST(rubylsp_cross_registry_built_once_serves_many_files);
RUN_TEST(rubylsp_cross_reopened_class_work_is_bounded);
RUN_TEST(rubylsp_cross_same_named_classes_stay_in_their_package);
RUN_TEST(rubylsp_cross_ambiguous_nested_constant_does_not_fall_through);
RUN_TEST(rubylsp_cross_registry_is_def_order_independent);
RUN_TEST(rubylsp_extractor_flags_singleton_methods_and_mixins);
RUN_TEST(rubylsp_cross_singleton_and_instance_do_not_shadow);
RUN_TEST(rubylsp_cross_mixin_shadows_superclass_across_files);
RUN_TEST(rubylsp_cross_mixin_in_reopening_shadows_superclass);
RUN_TEST(rubylsp_cross_unseen_mixin_blocks_superclass);
RUN_TEST(rubylsp_cross_ar_finder_same_file_only_by_default);
RUN_TEST(rubylsp_cross_ar_finder_crosses_files_when_switched_on);
}
+593
View File
@@ -0,0 +1,593 @@
/*
* test_scope_closure.c -- the unordered closure and lookup of the shared
* cross-file layer (src/pipeline/scope_closure.h), on scopes built by hand.
*/
#include "test_framework.h"
#include "../src/pipeline/scope_closure.h"
#include <stdio.h>
#include <string.h>
static const cbm_closure_lang_t ROW = {.lang = CBM_LANG_PROTOBUF};
static const cbm_closure_lang_t ROW_QUAL = {.lang = CBM_LANG_PROTOBUF, .qualified_refs = true};
static const cbm_closure_lang_t ROW_PKG = {.lang = CBM_LANG_GO, .package_visible = true};
static const cbm_closure_lang_t ROW_PRELUDE = {.lang = CBM_LANG_SCALA, .prelude_external = true};
static const cbm_closure_lang_t ROW_STRICT = {.lang = CBM_LANG_SCALA, .ambiguity_is_error = true};
/* `written`: the reference as written, NULL for the bare name. No memo: each
* answer computed afresh (sc_ask_memo shares one). */
static cbm_closure_answer_t sc_ask(cbm_closure_t *s, int file, const char *name,
const char *written, uint8_t flags) {
cbm_closure_ref_t ref = {.name = name, .written = written, .flags = flags};
return cbm_closure_lookup(s, NULL, file, &ref);
}
static cbm_closure_answer_t sc_ask_memo(cbm_closure_t *s, cbm_closure_memo_t *m, int file,
const char *name, const char *written) {
cbm_closure_ref_t ref = {.name = name, .written = written};
return cbm_closure_lookup(s, m, file, &ref);
}
/* user includes lib, which defines T: the one T, proven */
TEST(scope_closure_one_definition_through_an_include_is_proven) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "u");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW, "l");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "l.T", "p.lib.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t a = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(a.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(a.qn, "p.lib.T");
ASSERT_EQ(a.file, lib);
ASSERT_EQ(a.visible, 1);
ASSERT_TRUE(a.complete);
ASSERT_EQ(a.via, CBM_CLOSURE_VIA_INCLUDE);
/* a name nobody defines, closure complete: proven absent (counted only) */
ASSERT_EQ(sc_ask(s, user, "Nope", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
/* bound locally: no answer */
cbm_closure_answer_t local = sc_ask(s, user, "T", NULL, CBM_CLOSURE_REF_LOCAL);
ASSERT_EQ(local.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(local.why, CBM_CLOSURE_WHY_LOCAL);
cbm_closure_free(s);
PASS();
}
/* a plain include is not passed on; a re-exporting one is, along a chain;
* an import cycle (public or plain) is a file protoc refuses ("File
* recursively imports itself"): nothing through it or in it is proven */
TEST(scope_closure_reexport_chain_and_cycle) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int mid = cbm_closure_add_file(s, "mid.proto", &ROW, "");
int deep = cbm_closure_add_file(s, "deep.proto", &ROW, "");
int user2 = cbm_closure_add_file(s, "user2.proto", &ROW, "");
int a = cbm_closure_add_file(s, "a.proto", &ROW, "");
int b = cbm_closure_add_file(s, "b.proto", &ROW, "");
int pub = cbm_closure_add_file(s, "pub.proto", &ROW, "");
int x = cbm_closure_add_file(s, "x.proto", &ROW, "");
int y = cbm_closure_add_file(s, "y.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, deep, "D", NULL, "q.D", false));
ASSERT_TRUE(cbm_closure_add_def(s, b, "B", NULL, "q.B", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "Y", NULL, "q.Y", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, mid, false));
ASSERT_TRUE(cbm_closure_add_include(s, mid, deep, false)); /* plain: not passed on */
ASSERT_TRUE(cbm_closure_add_include(s, user, pub, false));
ASSERT_TRUE(cbm_closure_add_include(s, pub, deep, true)); /* public: passed on */
ASSERT_TRUE(cbm_closure_add_include(s, user2, a, false));
ASSERT_TRUE(cbm_closure_add_include(s, a, b, true)); /* public, and back: a cycle */
ASSERT_TRUE(cbm_closure_add_include(s, b, a, true));
ASSERT_TRUE(cbm_closure_add_include(s, x, y, false)); /* plain, and back: a cycle too */
ASSERT_TRUE(cbm_closure_add_include(s, y, x, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
ASSERT_EQ(sc_ask(s, mid, "D", NULL, 0).verdict, CBM_CLOSURE_PROVEN);
cbm_closure_answer_t chain = sc_ask(s, user, "D", NULL, 0);
ASSERT_EQ(chain.verdict, CBM_CLOSURE_PROVEN); /* through pub's re-export, not mid's */
ASSERT_STR_EQ(chain.qn, "q.D");
cbm_closure_t *s2 = cbm_closure_new(); /* the plain include alone */
int u2 = cbm_closure_add_file(s2, "user.proto", &ROW, "");
int m2 = cbm_closure_add_file(s2, "mid.proto", &ROW, "");
int d2 = cbm_closure_add_file(s2, "deep.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s2, d2, "D", NULL, "q.D", false));
ASSERT_TRUE(cbm_closure_add_include(s2, u2, m2, false));
ASSERT_TRUE(cbm_closure_add_include(s2, m2, d2, false));
ASSERT_EQ(cbm_closure_seal(s2), 0);
ASSERT_EQ(sc_ask(s2, u2, "D", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
cbm_closure_free(s2);
/* the cycles: possible at most, opaque */
cbm_closure_answer_t through = sc_ask(s, user2, "B", NULL, 0);
ASSERT_EQ(through.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(through.qn, "q.B");
ASSERT_EQ(through.why & CBM_CLOSURE_WHY_OPAQUE, CBM_CLOSURE_WHY_OPAQUE);
ASSERT_EQ(sc_ask(s, a, "B", NULL, 0).verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(sc_ask(s, x, "Y", NULL, 0).verdict, CBM_CLOSURE_POSSIBLE);
cbm_closure_free(s);
PASS();
}
/* incomplete closures: an unresolved include, an opaque file on the way */
TEST(scope_closure_incomplete_is_possible_or_no_answer) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW, "");
int dark = cbm_closure_add_file(s, "dark.proto", &ROW, "");
int user2 = cbm_closure_add_file(s, "user2.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", NULL, "q.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, -1, false)); /* names no repository file */
ASSERT_TRUE(cbm_closure_add_def(s, dark, "U", NULL, "q.U", false));
ASSERT_TRUE(cbm_closure_add_opaque(s, dark));
ASSERT_TRUE(cbm_closure_add_include(s, user2, dark, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t t = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(t.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(t.qn, "q.T");
ASSERT_FALSE(t.complete);
ASSERT_EQ(t.why & CBM_CLOSURE_WHY_UNRESOLVED, CBM_CLOSURE_WHY_UNRESOLVED);
ASSERT_EQ(sc_ask(s, user, "Gone", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER);
cbm_closure_answer_t u = sc_ask(s, user2, "U", NULL, 0);
ASSERT_EQ(u.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(u.why & CBM_CLOSURE_WHY_OPAQUE, CBM_CLOSURE_WHY_OPAQUE);
cbm_closure_free(s);
PASS();
}
/* two visible definitions: no answer; a conditional one: possible; one
* without a node: no answer */
TEST(scope_closure_ambiguous_conditional_and_nodeless) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int x = cbm_closure_add_file(s, "x.proto", &ROW, "");
int y = cbm_closure_add_file(s, "y.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, x, "T", NULL, "q.x.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "T", NULL, "q.y.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, x, "C", NULL, "q.x.C", true));
ASSERT_TRUE(cbm_closure_add_def(s, y, "N", NULL, NULL, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, x, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, y, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t two = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(two.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(two.visible, 2);
ASSERT_EQ(two.why & CBM_CLOSURE_WHY_AMBIGUOUS, CBM_CLOSURE_WHY_AMBIGUOUS);
cbm_closure_answer_t cond = sc_ask(s, user, "C", NULL, 0);
ASSERT_EQ(cond.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(cond.why & CBM_CLOSURE_WHY_CONDITIONAL, CBM_CLOSURE_WHY_CONDITIONAL);
cbm_closure_answer_t none = sc_ask(s, user, "N", NULL, 0);
ASSERT_EQ(none.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(none.why & CBM_CLOSURE_WHY_NO_NODE, CBM_CLOSURE_WHY_NO_NODE);
cbm_closure_free(s);
PASS();
}
/* protoc's scope walk: the innermost scope around the site in which the FIRST
* component names a symbol decides, the rest must be there, no backtracking;
* the enclosing message is not known, so a name a message of the file holds
* is at most possible (protoc takes a bare nested name only inside it) */
TEST(scope_closure_qualified_reference) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "a/b/user.proto", &ROW_QUAL, "a.b");
int common = cbm_closure_add_file(s, "common.proto", &ROW_QUAL, "common");
int y = cbm_closure_add_file(s, "y.proto", &ROW_QUAL, "y");
int near = cbm_closure_add_file(s, "a/n.proto", &ROW_QUAL, "a.n");
int xc = cbm_closure_add_file(s, "x/y.proto", &ROW_QUAL, "x.common");
ASSERT_TRUE(
cbm_closure_add_def(s, common, "Status", "common.Status", "q.common.Status", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "Status", "y.Status", "q.y.Status", false));
ASSERT_TRUE(cbm_closure_add_def(s, near, "Kind", "a.n.Kind", "q.a.n.Kind", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, common, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, y, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, near, false));
ASSERT_TRUE(cbm_closure_add_include(s, xc, common, false));
/* the user's own messages, top-level and nested */
ASSERT_TRUE(cbm_closure_add_def(s, user, "Outer", "a.b.Outer", "q.Outer", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Inner", "a.b.Outer.Inner", "q.Outer.Inner", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Mid", "a.b.Outer.Mid", "q.Mid", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Deep", "a.b.Outer.Mid.Deep", "q.Deep", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "One", "a.b.One", "q.One", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Two", "a.b.Two", "q.Two", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Twin", "a.b.One.Twin", "q.One.Twin", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Twin", "a.b.Two.Twin", "q.Two.Twin", false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t c = sc_ask(s, user, "Status", "common.Status", 0);
ASSERT_EQ(c.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(c.qn, "q.common.Status");
ASSERT_STR_EQ(sc_ask(s, user, "Status", ".y.Status", 0).qn, "q.y.Status");
/* bare `Status` inside package a.b reads a.b.Status, a.Status, Status:
* neither common.Status nor y.Status */
ASSERT_EQ(sc_ask(s, user, "Status", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
/* `n.Kind` inside package a.b: `n` first names the package a.n */
ASSERT_STR_EQ(sc_ask(s, user, "Kind", "n.Kind", 0).qn, "q.a.n.Kind");
/* `common.Status` inside package x.common: `common` first names x.common,
* so protoc reads x.common.Status, which is not defined: no answer */
cbm_closure_answer_t pre = sc_ask(s, xc, "Status", "common.Status", 0);
ASSERT_TRUE(pre.verdict != CBM_CLOSURE_PROVEN && pre.verdict != CBM_CLOSURE_POSSIBLE);
/* a message of the file holds the name: only inside it does protoc take
* it, and the site's message is unknown: possible */
cbm_closure_answer_t inner = sc_ask(s, user, "Inner", NULL, 0);
ASSERT_EQ(inner.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(inner.qn, "q.Outer.Inner");
ASSERT_EQ(inner.why & CBM_CLOSURE_WHY_SCOPE, CBM_CLOSURE_WHY_SCOPE);
cbm_closure_answer_t deep = sc_ask(s, user, "Deep", "Mid.Deep", 0);
ASSERT_EQ(deep.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(deep.qn, "q.Deep");
/* from the root, or through a top-level message: proven */
cbm_closure_answer_t lead = sc_ask(s, user, "Inner", ".a.b.Outer.Inner", 0);
ASSERT_EQ(lead.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(sc_ask(s, user, "Inner", "Outer.Inner", 0).qn, "q.Outer.Inner");
ASSERT_EQ(sc_ask(s, user, "Inner", "Outer.Inner", 0).verdict, CBM_CLOSURE_PROVEN);
/* `Twin` from inside One is One.Twin, from inside Two is Two.Twin: the
* enclosing message is not known here, so no answer */
cbm_closure_answer_t twin = sc_ask(s, user, "Twin", NULL, 0);
ASSERT_EQ(twin.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(twin.why & CBM_CLOSURE_WHY_AMBIGUOUS, CBM_CLOSURE_WHY_AMBIGUOUS);
ASSERT_STR_EQ(sc_ask(s, user, "Twin", "Two.Twin", 0).qn, "q.Two.Twin");
cbm_closure_free(s);
PASS();
}
/* a file whose package is unknown (no fact names it) reads every scope as
* possibly around its sites: more candidates, never fewer */
TEST(scope_closure_unknown_package_reads_every_scope) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW_QUAL, NULL);
int lib = cbm_closure_add_file(s, "lib.proto", &ROW_QUAL, "l");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "l.T", "q.l.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "T", "x.M.T", "q.x.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
ASSERT_EQ(sc_ask(s, user, "T", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER); /* l.T and x.M.T */
ASSERT_STR_EQ(sc_ask(s, user, "T", "l.T", 0).qn, "q.l.T");
cbm_closure_free(s);
PASS();
}
/* Answers do not depend on the memo: none, a fresh one, or one filled by
* other lookups (in any order) give the same. */
TEST(scope_closure_answers_do_not_depend_on_the_memo) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW_QUAL, "u");
int pub = cbm_closure_add_file(s, "pub.proto", &ROW_QUAL, "u");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW_QUAL, "u");
int far = cbm_closure_add_file(s, "far.proto", &ROW_QUAL, "f");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "u.T", "q.u.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, far, "T", "f.T", "q.f.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, far, "V", "f.V", "q.f.V", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, pub, false));
ASSERT_TRUE(cbm_closure_add_include(s, pub, lib, true));
ASSERT_TRUE(cbm_closure_add_include(s, pub, far, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
const struct {
int file;
const char *name;
const char *written;
} asks[] = {{user, "T", NULL}, {pub, "T", NULL}, {user, "V", NULL},
{pub, "V", "f.V"}, {far, "T", NULL}, {user, "T", "u.T"},
{lib, "T", ".u.T"}, {pub, "T", ".f.T"}, {user, "Nope", NULL}};
enum { N_ASKS = sizeof(asks) / sizeof(asks[0]) };
cbm_closure_answer_t fresh[N_ASKS];
for (int i = 0; i < N_ASKS; i++) {
fresh[i] = sc_ask(s, asks[i].file, asks[i].name, asks[i].written, 0);
}
for (int round = 0; round < 2; round++) {
cbm_closure_memo_t *m = cbm_closure_memo_new();
ASSERT_NOT_NULL(m);
for (int k = 0; k < N_ASKS; k++) {
int i = round == 0 ? k : N_ASKS - 1 - k; /* forward, then backward */
cbm_closure_answer_t a = sc_ask_memo(s, m, asks[i].file, asks[i].name, asks[i].written);
ASSERT_EQ(a.verdict, fresh[i].verdict);
ASSERT_EQ(a.visible, fresh[i].visible);
ASSERT_EQ(a.why, fresh[i].why);
ASSERT_EQ(a.file, fresh[i].file);
ASSERT_TRUE((a.qn == NULL) == (fresh[i].qn == NULL));
if (a.qn) {
ASSERT_STR_EQ(a.qn, fresh[i].qn);
}
}
cbm_closure_memo_free(m);
}
ASSERT_STR_EQ(fresh[0].qn, "q.u.T"); /* through pub's re-export */
ASSERT_STR_EQ(fresh[1].qn, "q.u.T"); /* f.T is no bare T in package u */
ASSERT_EQ(fresh[2].verdict, CBM_CLOSURE_PROVEN_ABSENT); /* far is not passed on */
ASSERT_STR_EQ(fresh[3].qn, "q.f.V");
ASSERT_EQ(cbm_closure_file(s, "pub.proto"), pub);
ASSERT_EQ(cbm_closure_file(s, "nope.proto"), -1);
ASSERT_EQ(cbm_closure_add_file(s, "late.proto", &ROW_QUAL, ""), -1); /* sealed */
cbm_closure_free(s);
PASS();
}
/* rows: package mates, a prelude, ambiguity as an error */
TEST(scope_closure_rows) {
cbm_closure_t *s = cbm_closure_new();
int p1 = cbm_closure_add_file(s, "pkg/a.go", &ROW_PKG, "pkg");
int p2 = cbm_closure_add_file(s, "pkg/b.go", &ROW_PKG, "pkg");
int other = cbm_closure_add_file(s, "other/c.go", &ROW_PKG, "other");
ASSERT_TRUE(cbm_closure_add_def(s, p2, "F", NULL, "q.pkg.F", false));
int pre = cbm_closure_add_file(s, "s/a.scala", &ROW_PRELUDE, "s");
int pre_lib = cbm_closure_add_file(s, "s/l.scala", &ROW_PRELUDE, "s");
ASSERT_TRUE(cbm_closure_add_def(s, pre_lib, "G", NULL, "q.s.G", false));
ASSERT_TRUE(cbm_closure_add_include(s, pre, pre_lib, false));
int strict = cbm_closure_add_file(s, "t/a.scala", &ROW_STRICT, "t");
int strict_lib = cbm_closure_add_file(s, "t/l.scala", &ROW_STRICT, "t");
ASSERT_TRUE(cbm_closure_add_def(s, strict_lib, "H", NULL, "q.t.H", false));
ASSERT_TRUE(cbm_closure_add_include(s, strict, strict_lib, false));
ASSERT_TRUE(cbm_closure_add_include(s, strict, -1, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t mate = sc_ask(s, p1, "F", NULL, 0);
ASSERT_EQ(mate.verdict, CBM_CLOSURE_PROVEN);
ASSERT_EQ(mate.via, CBM_CLOSURE_VIA_PACKAGE);
ASSERT_EQ(sc_ask(s, other, "F", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
cbm_closure_answer_t prelude = sc_ask(s, pre, "G", NULL, 0);
ASSERT_EQ(prelude.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(prelude.why & CBM_CLOSURE_WHY_PRELUDE, CBM_CLOSURE_WHY_PRELUDE);
ASSERT_EQ(sc_ask(s, pre, "Absent", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER);
cbm_closure_answer_t one = sc_ask(s, strict, "H", NULL, 0);
ASSERT_EQ(one.verdict, CBM_CLOSURE_PROVEN);
ASSERT_FALSE(one.complete);
cbm_closure_free(s);
PASS();
}
/* Counted work of a header-heavy shape at n: (fan) one file defining N
* included by n files, each asking N and one undefined name; (chain) n files
* each re-exporting the next, the last defining N, each asking N. `lookups`:
* the lookups' work (one memo for all, as one resolver thread), else the
* build's (files, definitions, includes, components). */
static uint64_t sc_work(int n, bool chain, bool lookups) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
int shared = cbm_closure_add_file(s, "shared.proto", &ROW, "");
int first = -1;
for (int i = 0; i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
int f = cbm_closure_add_file(s, rel, &ROW, "");
first = first < 0 ? f : first;
}
for (int i = 0; i < n; i++) { /* every file exists before an include names it */
int f = first + i;
bool ok = chain ? cbm_closure_add_include(s, f, i + 1 < n ? f + 1 : shared, true)
: cbm_closure_add_include(s, f, shared, false);
if (!ok) {
cbm_closure_free(s);
return 0;
}
}
if (!cbm_closure_add_def(s, shared, "N", NULL, "q.N", false) || cbm_closure_seal(s) != 0) {
cbm_closure_free(s);
return 0;
}
/* one memo, as one resolver thread has */
cbm_closure_memo_t *m = cbm_closure_memo_new();
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
right = sc_ask_memo(s, m, first + i, "N", NULL).verdict == CBM_CLOSURE_PROVEN &&
sc_ask_memo(s, m, first + i, "Unknown", NULL).verdict == CBM_CLOSURE_PROVEN_ABSENT;
}
uint64_t w = lookups ? cbm_closure_memo_work(m) : cbm_closure_work(s);
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
/* Counted lookup work of review 1's three shapes at n (one memo, as one
* resolver thread): (0, chain) f_i `import public` f_{i+1}, each defines T_i,
* a top file includes f_0 and asks every T_i; (1, fan) a top file includes n
* files and asks each one's T_i; (2, hub) n files `package p_i; Status`, a hub
* re-exports all, n users each include the hub and ask p_i.Status. */
static uint64_t sc_shape_work(int n, int shape) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
char name[32];
char full[32];
char pkg[32];
int top = cbm_closure_add_file(s, "top.proto", &ROW_QUAL, "u");
int hub = cbm_closure_add_file(s, "hub.proto", &ROW_QUAL, "h");
int first = -1;
bool ok = true;
for (int i = 0; ok && i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
snprintf(pkg, sizeof(pkg), "p%d", i);
int f = cbm_closure_add_file(s, rel, &ROW_QUAL, shape == 2 ? pkg : "u");
first = first < 0 ? f : first;
if (shape == 2) {
snprintf(rel, sizeof(rel), "user%d.proto", i);
ok = cbm_closure_add_file(s, rel, &ROW_QUAL, "u") >= 0;
}
}
for (int i = 0; ok && i < n; i++) {
int f = first + i * (shape == 2 ? 2 : 1);
snprintf(name, sizeof(name), "T%d", i);
snprintf(full, sizeof(full), shape == 2 ? "p%d.Status" : "u.T%d", i);
ok = cbm_closure_add_def(s, f, shape == 2 ? "Status" : name, full, full, false);
if (shape == 0) {
ok = ok && (i + 1 >= n || cbm_closure_add_include(s, f, f + 1, true));
} else if (shape == 1) {
ok = ok && cbm_closure_add_include(s, top, f, false);
} else {
ok = ok && cbm_closure_add_include(s, hub, f, true) &&
cbm_closure_add_include(s, f + 1, hub, false);
}
}
if (shape == 0) {
ok = ok && cbm_closure_add_include(s, top, first, false);
}
ok = ok && cbm_closure_seal(s) == 0;
cbm_closure_memo_t *m = ok ? cbm_closure_memo_new() : NULL;
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
snprintf(name, sizeof(name), "T%d", i);
snprintf(full, sizeof(full), "p%d.Status", i);
cbm_closure_answer_t a = shape == 2 ? sc_ask_memo(s, m, first + i * 2 + 1, "Status", full)
: sc_ask_memo(s, m, top, name, NULL);
right = a.verdict == CBM_CLOSURE_PROVEN;
}
uint64_t w = m ? cbm_closure_memo_work(m) : 0;
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
TEST(scope_closure_review_shapes_grow_linearly) {
static const char *const names[] = {"chain", "fan", "hub"};
for (int shape = 0; shape < 3; shape++) {
uint64_t w1 = sc_shape_work(100, shape);
uint64_t w4 = sc_shape_work(400, shape);
uint64_t w16 = sc_shape_work(1600, shape);
printf("\n %s lookups: %llu / %llu / %llu at 1x / 4x / 16x", names[shape],
(unsigned long long)w1, (unsigned long long)w4, (unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
printf("\n");
PASS();
}
/* Counted lookup work of review 3's R2 shape at n (one memo): n files
* `package p_i; message M { enum Type {..} Type t = 1; }`, each asking its
* own Type. `scoped`: the reference carries its enclosing message (proven
* p_i.M.Type); otherwise the scope is unknown and the file's own nested Type
* may decide (possible). */
static uint64_t sc_nested_work(int n, bool scoped) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
char pkg[32];
char msg[32];
char full[48];
int first = -1;
bool ok = true;
for (int i = 0; ok && i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
snprintf(pkg, sizeof(pkg), "p%d", i);
snprintf(msg, sizeof(msg), "p%d.M", i);
snprintf(full, sizeof(full), "p%d.M.Type", i);
int f = cbm_closure_add_file(s, rel, &ROW_QUAL, pkg);
first = first < 0 ? f : first;
ok = f >= 0 && cbm_closure_add_def(s, f, "M", msg, msg, false) &&
cbm_closure_add_def(s, f, "Type", full, full, false);
}
ok = ok && cbm_closure_seal(s) == 0;
cbm_closure_memo_t *m = ok ? cbm_closure_memo_new() : NULL;
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
snprintf(msg, sizeof(msg), "p%d.M", i);
snprintf(full, sizeof(full), "p%d.M.Type", i);
cbm_closure_ref_t ref = {.name = "Type", .scope = scoped ? msg : NULL};
cbm_closure_answer_t a = cbm_closure_lookup(s, m, first + i, &ref);
right = a.verdict == (scoped ? CBM_CLOSURE_PROVEN : CBM_CLOSURE_POSSIBLE) && a.qn &&
strcmp(a.qn, full) == 0;
}
uint64_t w = m ? cbm_closure_memo_work(m) : 0;
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
TEST(scope_closure_nested_name_in_every_file_grows_linearly) {
for (int scoped = 0; scoped < 2; scoped++) {
uint64_t w1 = sc_nested_work(250, scoped);
uint64_t w4 = sc_nested_work(1000, scoped);
uint64_t w16 = sc_nested_work(4000, scoped);
printf("\n nested %s: %llu / %llu / %llu at 250 / 1,000 / 4,000", scoped ? "scoped" : "unscoped",
(unsigned long long)w1, (unsigned long long)w4, (unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
printf("\n");
PASS();
}
/* protoc on review 3's fx4/scope: `package p; import "t.proto"; message A {
* enum Type {..} Type t = 1; } message B { Type t = 1; }` with t.proto's
* `package p; enum Type {..}` gives A's field .p.A.Type and B's .p.Type. The
* reference's own scope decides innermost first; an outer Type is never the
* answer where an inner one is around the site. */
TEST(scope_closure_reference_scope_decides_innermost_first) {
cbm_closure_t *s = cbm_closure_new();
int a = cbm_closure_add_file(s, "a.proto", &ROW_QUAL, "p");
int t = cbm_closure_add_file(s, "t.proto", &ROW_QUAL, "p");
ASSERT_TRUE(cbm_closure_add_def(s, t, "Type", "p.Type", "t.Type", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "A", "p.A", "a.A", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "Type", "p.A.Type", "a.A.Type", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "B", "p.B", "a.B", false));
ASSERT_TRUE(cbm_closure_add_include(s, a, t, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
static const struct {
const char *scope;
const char *written;
const char *want; /* the proven node */
} cases[] = {
{"p.A", NULL, "a.A.Type"}, /* A's field: the enclosing message first */
{"p.B", NULL, "t.Type"}, /* B's field: B holds no Type, the package's */
{"p", NULL, "t.Type"}, /* outside any message */
{"p.B", "A.Type", "a.A.Type"}, /* qualified from B: A decides at p */
{"", "p.Type", "t.Type"}, /* from the root */
};
for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
cbm_closure_ref_t ref = {.name = "Type", .written = cases[i].written, .scope = cases[i].scope};
cbm_closure_answer_t x = cbm_closure_lookup(s, NULL, a, &ref);
if (x.verdict != CBM_CLOSURE_PROVEN || !x.qn || strcmp(x.qn, cases[i].want) != 0) {
printf("\n scope %s written %s: verdict %d qn %s, want proven %s\n", cases[i].scope,
cases[i].written ? cases[i].written : "-", (int)x.verdict, x.qn ? x.qn : "-",
cases[i].want);
cbm_closure_free(s);
FAIL("the reference's own scope did not decide");
}
}
/* `B.Type` from A: B is found at p and holds no Type, no backtracking */
cbm_closure_ref_t miss = {.name = "Type", .written = "B.Type", .scope = "p.A"};
ASSERT_NEQ(cbm_closure_lookup(s, NULL, a, &miss).verdict, CBM_CLOSURE_PROVEN);
cbm_closure_free(s);
PASS();
}
TEST(scope_closure_work_grows_linearly) {
for (int chain = 0; chain < 2; chain++) {
for (int lookups = 0; lookups < 2; lookups++) { /* the build, then the lookups */
uint64_t w1 = sc_work(100, chain, lookups);
uint64_t w4 = sc_work(400, chain, lookups);
uint64_t w16 = sc_work(1600, chain, lookups);
printf("\n %s %s: %llu / %llu / %llu at 1x / 4x / 16x", chain ? "chain" : "fan",
lookups ? "lookups" : "build", (unsigned long long)w1, (unsigned long long)w4,
(unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
/* at most 4.5 times the work per 4 times the files */
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
}
printf("\n");
PASS();
}
SUITE(scope_closure) {
RUN_TEST(scope_closure_review_shapes_grow_linearly);
RUN_TEST(scope_closure_nested_name_in_every_file_grows_linearly);
RUN_TEST(scope_closure_reference_scope_decides_innermost_first);
RUN_TEST(scope_closure_one_definition_through_an_include_is_proven);
RUN_TEST(scope_closure_reexport_chain_and_cycle);
RUN_TEST(scope_closure_incomplete_is_possible_or_no_answer);
RUN_TEST(scope_closure_ambiguous_conditional_and_nodeless);
RUN_TEST(scope_closure_qualified_reference);
RUN_TEST(scope_closure_unknown_package_reads_every_scope);
RUN_TEST(scope_closure_answers_do_not_depend_on_the_memo);
RUN_TEST(scope_closure_rows);
RUN_TEST(scope_closure_work_grows_linearly);
}
+37
View File
@@ -177,6 +177,42 @@ TEST(scope_facts_survive_compaction) {
PASS();
}
/* Compaction leaves every array at its exact count in one exact-size block,
* so an event appended afterwards must grow the array into new memory. With a
* capacity left at its extraction value, the append would write in place,
* over whatever the block holds next. */
TEST(scope_facts_append_after_compaction_grows_the_array) {
CBMFileResult *r = sf_extract(SF_PROTO, CBM_LANG_PROTOBUF, "proto/a.proto");
ASSERT_NOT_NULL(r);
cbm_result_compact(r);
int n = r->scope.count;
ASSERT_GT(n, 0);
ASSERT_EQ(r->scope.cap, n); /* exactly sized: no headroom to append into */
char before[4096];
size_t off = 0;
for (int i = 0; i < n; i++) {
const CBMScopeEvent *e = &r->scope.items[i];
off += (size_t)snprintf(before + off, sizeof(before) - off, "%u|%d|%u|%s|%s\n", e->kind,
e->index, e->pos, e->name ? e->name : "-", e->qual ? e->qual : "-");
}
const CBMScopeEvent *old = r->scope.items;
CBMScopeEvent ev = {.pos = UINT32_MAX, .index = -1, .kind = CBM_SCOPE_OPAQUE};
cbm_scope_events_push(&r->scope, &r->arena, ev);
ASSERT_EQ(r->scope.count, n + 1);
ASSERT_TRUE(r->scope.items != old); /* grown, not written in place */
char after[4096];
off = 0;
for (int i = 0; i < n; i++) {
const CBMScopeEvent *e = &r->scope.items[i];
off += (size_t)snprintf(after + off, sizeof(after) - off, "%u|%d|%u|%s|%s\n", e->kind,
e->index, e->pos, e->name ? e->name : "-", e->qual ? e->qual : "-");
}
ASSERT_STR_EQ(after, before);
ASSERT_EQ(r->scope.items[n].kind, CBM_SCOPE_OPAQUE);
cbm_free_result(r);
PASS();
}
/* One file's stored surface row (cbm_lsp_surface_build_rows, no LSP defs). */
static bool sf_row(CBMFileResult *r, const char *rel, CBMLanguage lang, char **json, char **sha) {
cbm_file_info_t file = {.rel_path = (char *)rel, .language = lang};
@@ -325,6 +361,7 @@ SUITE(scope_facts) {
RUN_TEST(scope_facts_language_without_row_records_nothing);
RUN_TEST(scope_facts_parse_error_is_opaque);
RUN_TEST(scope_facts_survive_compaction);
RUN_TEST(scope_facts_append_after_compaction_grows_the_array);
RUN_TEST(scope_facts_surface_round_trip);
RUN_TEST(scope_facts_surface_hash_follows_facts_not_bytes);
RUN_TEST(scope_facts_work_grows_linearly);
+684 -1
View File
@@ -6,12 +6,25 @@
* of it gets NO_ANSWER (main's name chain decides, unchanged) and the end
* step draws no edge. Go has an engine and never gets a row of this layer,
* so these hold as rows for other languages arrive.
*
* Protobuf has a row: a type reference names the definition the scope facts
* prove it names (protoc's scope walk over the file's imports), on both
* resolver routes and incrementally as in a full index. The expected targets
* were decided by protoc 3.21.12 (descriptor set of the fixture, see
* resolver-evidence/.../shared/scope.md, A3b).
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
#include "test_helpers.h"
#include "../src/pipeline/site_bind.h"
#include "../src/graph_buffer/graph_buffer.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "sqlite3.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
TEST(site_bind_language_without_row_answers_nothing) {
@@ -39,8 +52,9 @@ TEST(site_bind_language_without_row_answers_nothing) {
result.usages.items = usages;
result.usages.count = 1;
cbm_site_memo_t *memo = NULL;
cbm_site_file_t sf;
cbm_pipeline_site_bind_begin(&sf, NULL, gb, "a.go", CBM_LANG_GO, &result);
cbm_pipeline_site_bind_begin(&sf, NULL, gb, "a.go", CBM_LANG_GO, &result, &memo, NULL);
ASSERT_FALSE(sf.active);
cbm_site_answer_t at_call = cbm_pipeline_site_bind_call(&sf, &calls[0], source);
@@ -56,11 +70,680 @@ TEST(site_bind_language_without_row_answers_nothing) {
int edges_before = cbm_gbuf_edge_count(gb);
cbm_pipeline_site_bind_end(&sf, gb);
ASSERT_EQ(cbm_gbuf_edge_count(gb), edges_before);
ASSERT_NULL(memo); /* nothing was looked up */
cbm_gbuf_free(gb);
PASS();
}
/* ── Indexing helpers ────────────────────────────────────────────────── */
/* Index `repo` into `db` (a second call on the same database takes the
* incremental route) with `workers` workers (0: leave CBM_WORKERS as it is);
* `marks` (test seam, NULL-terminated name/target-suffix/verdict triples)
* are set once the project name is known. */
typedef struct {
const char *name;
const char *rel; /* the target's file */
const char *symbol; /* the target's name in it */
cbm_site_verdict_t verdict;
} sb_mark_t;
static int sb_index(const char *repo, const char *db, int workers, const sb_mark_t *marks) {
const char *saved = getenv("CBM_WORKERS");
char *saved_copy = saved ? strdup(saved) : NULL;
if (workers > 0) {
char w[8];
snprintf(w, sizeof(w), "%d", workers);
cbm_setenv("CBM_WORKERS", w, 1);
}
int rc = -1;
cbm_pipeline_t *p = cbm_pipeline_new(repo, db, CBM_MODE_FULL);
if (p) {
for (int i = 0; marks && marks[i].name; i++) {
char *qn = cbm_pipeline_fqn_compute(cbm_pipeline_project_name(p), marks[i].rel,
marks[i].symbol);
cbm_pipeline_site_bind_test_mark(marks[i].name, qn, marks[i].verdict);
free(qn);
}
rc = cbm_pipeline_run(p);
cbm_pipeline_site_bind_test_mark(NULL, NULL, CBM_SITE_NO_ANSWER);
cbm_pipeline_free(p);
}
if (saved_copy) {
cbm_setenv("CBM_WORKERS", saved_copy, 1);
free(saved_copy);
} else {
cbm_unsetenv("CBM_WORKERS");
}
return rc;
}
static void sb_unlink_db(const char *db) {
char side[600];
unlink(db);
snprintf(side, sizeof(side), "%s-wal", db);
unlink(side);
snprintf(side, sizeof(side), "%s-shm", db);
unlink(side);
}
/* The edges of the given types as "type source -> target [strategy]" lines,
* sorted: what two indexes of one tree must agree on (D1: property text left
* out). The caller frees it; NULL when the database cannot be read. */
static char *sb_state(const char *db) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return NULL;
}
size_t cap = 4096;
size_t len = 0;
char *buf = malloc(cap);
buf[0] = '\0';
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT e.type || ' ' || s.qualified_name || ' -> ' || t.qualified_name || ' [' || "
"coalesce(json_extract(e.properties, '$.strategy'), '') || ']' FROM edges e "
"JOIN nodes s ON s.id = e.source_id JOIN nodes t ON t.id = e.target_id "
"WHERE e.type IN ('USAGE', 'IMPORTS', 'CALLS', 'HTTP_CALLS', 'ASYNC_CALLS', "
"'CALL_REFERENCE', 'SPAWNS') ORDER BY 1";
if (sqlite3_prepare_v2(h, sql, -1, &st, NULL) == SQLITE_OK) {
while (sqlite3_step(st) == SQLITE_ROW) {
const char *line = (const char *)sqlite3_column_text(st, 0);
size_t l = strlen(line);
if (len + l + 2 > cap) {
cap = (len + l + 2) * 2;
buf = realloc(buf, cap);
}
memcpy(buf + len, line, l);
len += l;
buf[len++] = '\n';
buf[len] = '\0';
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return buf;
}
/* The strategy of the `type` edge from the node whose QN ends in `.<src>`
* to the node whose QN ends in `.<tgt>` ("" when it has none) into out;
* returns how many such edges there are. */
static int sb_edge(const char *db, const char *type, const char *src, const char *tgt, char *out,
size_t cap) {
out[0] = '\0';
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int n = 0;
const char *sql = "SELECT coalesce(json_extract(e.properties, '$.strategy'), '') FROM edges e "
"JOIN nodes s ON s.id = e.source_id JOIN nodes t ON t.id = e.target_id "
"WHERE e.type = ?1 AND s.qualified_name LIKE '%.' || ?2 "
"AND t.qualified_name LIKE '%.' || ?3";
if (sqlite3_prepare_v2(h, sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, type, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 2, src, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 3, tgt, -1, SQLITE_TRANSIENT);
while (sqlite3_step(st) == SQLITE_ROW) {
n++;
snprintf(out, cap, "%s", (const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return n;
}
/* One edge with this strategy ("*": any; want NULL: no such edge at all). */
static int sb_expect(const char *db, const char *venue, const char *type, const char *src,
const char *tgt, const char *want) {
char got[64];
int n = sb_edge(db, type, src, tgt, got, sizeof(got));
if (!want && n == 0) {
return 1;
}
if (want && n == 1 && (strcmp(want, "*") == 0 || strcmp(got, want) == 0)) {
return 1;
}
printf("\n [%s] %s %s -> %s: want %s%s%s, have %d edge(s), strategy '%s'\n", venue, type, src,
tgt, want ? "one edge, strategy '" : "no edge", want ? want : "", want ? "'" : "", n,
got);
return 0;
}
/* ── The Protobuf fixture ────────────────────────────────────────────── */
static const char *const SB_PROTO[][2] = {
{"x/common.proto", "syntax = \"proto3\";\npackage common;\n\n"
"message Status { int32 code = 1; }\nmessage Only { int32 v = 1; }\n"},
{"y/twin.proto", "syntax = \"proto3\";\npackage y;\n\nmessage Status { string y = 1; }\n"},
{"x/shared.proto",
"syntax = \"proto3\";\npackage shared;\n\nimport public \"x/common.proto\";\n\n"
"message Shared { int32 s = 1; }\n"},
/* two imported Status messages: the qualifier decides (protoc: y.Status,
* common.Status, common.Only); main's name chain gives both the same */
{"u/user.proto", "syntax = \"proto3\";\npackage u;\n\nimport \"x/common.proto\";\n"
"import \"y/twin.proto\";\n\nmessage User {\n y.Status st = 1;\n"
" common.Status cs = 2;\n common.Only only = 3;\n}\n"},
/* common.Status through shared's `import public` */
{"u/via.proto", "syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n\n"
"message Via {\n common.Status st = 1;\n shared.Shared sh = 2;\n}\n"},
/* nested messages; rpc request and response */
{"n/nested.proto", "syntax = \"proto3\";\npackage n.m;\n\nmessage L1 {\n message L2 {\n"
" message L3 { int32 v = 1; }\n }\n L2.L3 deep = 1;\n}\n\n"
"service S { rpc Get(L1) returns (L1.L2.L3); }\n"},
/* an import outside the repository: one candidate, not proven (main's
* chain names the same target: nothing added) */
{"p/outside.proto",
"syntax = \"proto3\";\npackage p;\n\nimport \"google/protobuf/empty.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Outside {\n y.Status st = 1;\n"
" google.protobuf.Empty e = 2;\n}\n"},
/* the same, with common imported too: main's chain names common.Status,
* the possible answer y.Status; main's edge stays alone */
{"p/outside2.proto", "syntax = \"proto3\";\npackage p;\n\n"
"import \"google/protobuf/empty.proto\";\nimport \"x/common.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Outside2 {\n y.Status st = 1;\n"
" google.protobuf.Empty e = 2;\n}\n"},
};
static int sb_write_proto(const char *dir, int pad) {
for (size_t i = 0; i < sizeof(SB_PROTO) / sizeof(SB_PROTO[0]); i++) {
if (th_write_file(TH_PATH(dir, SB_PROTO[i][0]), SB_PROTO[i][1]) != 0) {
return -1;
}
}
for (int i = 0; i < pad; i++) { /* past MIN_FILES_FOR_PARALLEL (50) */
char rel[64];
char body[128];
snprintf(rel, sizeof(rel), "pad/p%02d.proto", i);
snprintf(body, sizeof(body),
"syntax = \"proto3\";\npackage pad;\n\nmessage P%02d { int32 v = 1; }\n", i);
if (th_write_file(TH_PATH(dir, rel), body) != 0) {
return -1;
}
}
return 0;
}
static int sb_check_proto(const char *db, const char *venue) {
int ok = 1;
ok &= sb_expect(db, venue, "USAGE", "u.user", "y.twin.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.user", "x.common.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.user", "x.common.Only", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.via", "x.common.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.via", "x.shared.Shared", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "n.nested.Get", "n.nested.L1", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "n.nested.Get", "n.nested.L3", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "p.outside", "y.twin.Status", "");
ok &= sb_expect(db, venue, "USAGE", "p.outside2", "x.common.Status", "");
ok &= sb_expect(db, venue, "USAGE", "p.outside2", "y.twin.Status", NULL);
return ok;
}
/* A type reference binds the definition its qualifier names, on both
* routes, and the routes agree edge for edge. */
TEST(site_bind_protobuf_reference_binds_what_protoc_resolves) {
char *tmp = th_mktempdir("sb_proto");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_proto(dir, 55), 0);
char seq_db[512];
char par_db[512];
snprintf(seq_db, sizeof(seq_db), "%s/seq.db", tmp);
snprintf(par_db, sizeof(par_db), "%s/par.db", tmp);
ASSERT_EQ(sb_index(dir, seq_db, 1, NULL), 0);
ASSERT_EQ(sb_index(dir, par_db, 4, NULL), 0);
int ok = sb_check_proto(seq_db, "sequential") & sb_check_proto(par_db, "parallel");
char *seq = sb_state(seq_db);
char *par = sb_state(par_db);
bool same = seq && par && strcmp(seq, par) == 0;
if (!same) {
printf("\n parallel != sequential\n--- parallel\n%s--- sequential\n%s", par ? par : "",
seq ? seq : "");
}
free(seq);
free(par);
th_cleanup(tmp);
ASSERT_TRUE(ok);
ASSERT_TRUE(same);
PASS();
}
/* ── Incremental equals full ─────────────────────────────────────────── */
/* After the caller edited the tree: index incrementally into `inc_db`, then
* fully into a fresh `full_db`; the edges must be the same and the route the
* expected one. Returns 0, or -1 after printing what differs. */
static int sb_step(const char *repo, const char *inc_db, const char *full_db, const char *what,
cbm_incremental_route_t want_route, const char *want_decline) {
cbm_pipeline_incremental_test_reset_faults();
if (sb_index(repo, inc_db, 0, NULL) != 0) {
printf(" %s: incremental index failed\n", what);
return -1;
}
cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
cbm_incremental_closure_plan_t plan = cbm_pipeline_incremental_test_last_closure_plan();
sb_unlink_db(full_db);
if (sb_index(repo, full_db, 0, NULL) != 0) {
printf(" %s: full index failed\n", what);
return -1;
}
char *inc = sb_state(inc_db);
char *full = sb_state(full_db);
int rc = 0;
if (!inc || !full || strcmp(inc, full) != 0) {
printf(" %s: incremental != full\n--- incremental (route %d)\n%s--- full\n%s", what,
(int)route, inc ? inc : "(null)", full ? full : "(null)");
rc = -1;
} else if (route != want_route) {
printf(" %s: route %d (decline %s), expected %d\n", what, (int)route,
plan.decline ? plan.decline : "-", (int)want_route);
rc = -1;
} else if (want_decline && (!plan.decline || strcmp(plan.decline, want_decline) != 0)) {
printf(" %s: decline %s, expected %s\n", what, plan.decline ? plan.decline : "(none)",
want_decline);
rc = -1;
}
free(inc);
free(full);
return rc;
}
/* Remove the stored scope facts of one file (a row an older binary wrote). */
static int sb_strip_facts(const char *db, const char *rel) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int rc = -1;
if (sqlite3_prepare_v2(h,
"UPDATE lsp_surface SET defs_json = json_remove(defs_json, '$.is') "
"WHERE rel_path = ?1",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, rel, -1, SQLITE_TRANSIENT);
rc = sqlite3_step(st) == SQLITE_DONE && sqlite3_changes(h) == 1 ? 0 : -1;
}
sqlite3_finalize(st);
sqlite3_close(h);
return rc;
}
/* An import added or removed repairs incrementally to what a full index
* draws; a stored row without scope facts declines to a full index. */
TEST(site_bind_protobuf_incremental_equals_full) {
char *tmp = th_mktempdir("sb_proto_incr");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_proto(dir, 0), 0);
char inc_db[512];
char full_db[512];
snprintf(inc_db, sizeof(inc_db), "%s/inc.db", tmp);
snprintf(full_db, sizeof(full_db), "%s/full.db", tmp);
ASSERT_EQ(sb_index(dir, inc_db, 0, NULL), 0);
ASSERT_TRUE(sb_check_proto(inc_db, "full"));
/* via imports twin and names y.Status */
ASSERT_EQ(th_write_file(TH_PATH(dir, "u/via.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Via {\n common.Status st = 1;\n"
" shared.Shared sh = 2;\n y.Status ys = 3;\n}\n"),
0);
ASSERT_EQ(
sb_step(dir, inc_db, full_db, "import added", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, NULL),
0);
ASSERT_TRUE(
sb_expect(inc_db, "import added", "USAGE", "u.via", "y.twin.Status", "include_scope"));
/* user drops twin: its y.Status is no longer seen, common.Status is */
ASSERT_EQ(
th_write_file(TH_PATH(dir, "u/user.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/common.proto\";\n\n"
"message User {\n common.Status cs = 2;\n common.Only only = 3;\n}\n"),
0);
ASSERT_EQ(
sb_step(dir, inc_db, full_db, "import removed", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, NULL),
0);
ASSERT_TRUE(sb_expect(inc_db, "import removed", "USAGE", "u.user", "y.twin.Status", NULL));
ASSERT_TRUE(
sb_expect(inc_db, "import removed", "USAGE", "u.user", "x.common.Status", "include_scope"));
/* a re-exported file's surface changes (shared re-exports common): the
* re-exporter's includers have no edge into it, so the repair declines */
ASSERT_EQ(th_write_file(TH_PATH(dir, "x/common.proto"),
"syntax = \"proto3\";\npackage common;\n\n"
"message Status { int32 code = 1; }\n"),
0);
ASSERT_EQ(sb_step(dir, inc_db, full_db, "re-exported file changed",
CBM_INCREMENTAL_ROUTE_FORCED_FULL, "scope_reexport_changed"),
0);
/* a stored row without facts: the repair cannot read that file's scope */
ASSERT_EQ(sb_strip_facts(inc_db, "x/common.proto"), 0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "u/via.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n\n"
"message Via {\n common.Status st = 1;\n shared.Shared sh = 2;\n}\n"),
0);
ASSERT_EQ(sb_step(dir, inc_db, full_db, "stored row without facts",
CBM_INCREMENTAL_ROUTE_FORCED_FULL, "scope_facts_missing"),
0);
th_cleanup(tmp);
PASS();
}
/* ── The guarded call shapes, through the test seam ──────────────────── */
/* Every mark has its own target, so an edge shows which site it came from. */
static const char *const SB_SEAM[][2] = {
{"lib.lua", "function target_fn()\n return 1\nend\n\nfunction other_fn()\n return 2\nend\n\n"
"function third_fn()\n return 3\nend\n\nfunction svc_fn()\n return 5\nend\n\n"
"function swift_fn()\n return 6\nend\n\nfunction php_fn()\n return 7\nend\n\n"
"function rust_fn()\n return 8\nend\n\nfunction java_fn()\n return 9\nend\n"},
/* markd proven, markp possible where main draws nothing, markq possible
* where main draws another target; markv a proven usage; a service call */
{"app.lua", "function markq()\n return 4\nend\n\nfunction run()\n markd()\n markp()\n"
" markq()\n local v = markv\n requests.get(\"http://svc/api/items\")\n"
" return v\nend\n"},
/* Swift label candidates: one compatible overload, and none */
{"s/Labels.swift", "func marks(a: Int) {}\nfunc marks(b: Int) {}\n\n"
"func use() {\n marks(a: 1)\n marks(c: 2)\n}\n"},
/* a PHP call on a vendor class */
{"php/Go.php", "<?php\nuse GuzzleHttp\\Client;\n\nfunction go() {\n $c = new Client();\n"
" $c->markh();\n}\n"},
/* a Rust call the engine places on an external type */
{"r/main.rs", "use std::path::Path;\n\nfn main() {\n let p = Path::new(\"x\");\n"
" p.markr();\n}\n"},
/* a Java call on a JDK type */
{"j/J.java", "import java.util.List;\n\nclass J {\n void f(List<String> l) {\n"
" l.markj();\n }\n}\n"},
};
static int sb_write_seam(const char *dir) {
for (size_t i = 0; i < sizeof(SB_SEAM) / sizeof(SB_SEAM[0]); i++) {
if (th_write_file(TH_PATH(dir, SB_SEAM[i][0]), SB_SEAM[i][1]) != 0) {
return -1;
}
}
for (int i = 0; i < 55; i++) {
char rel[64];
char body[128];
snprintf(rel, sizeof(rel), "pad/p%02d.lua", i);
snprintf(body, sizeof(body), "function pad%02d()\n return %d\nend\n", i, i);
if (th_write_file(TH_PATH(dir, rel), body) != 0) {
return -1;
}
}
return 0;
}
static const sb_mark_t SB_MARKS[] = {
{"markd", "lib.lua", "target_fn", CBM_SITE_PROVEN},
{"markp", "lib.lua", "other_fn", CBM_SITE_POSSIBLE},
{"markq", "lib.lua", "third_fn", CBM_SITE_POSSIBLE},
{"markv", "lib.lua", "target_fn", CBM_SITE_PROVEN},
{"requests.get", "lib.lua", "svc_fn", CBM_SITE_PROVEN},
{"marks", "lib.lua", "swift_fn", CBM_SITE_PROVEN},
{"markh", "lib.lua", "php_fn", CBM_SITE_PROVEN},
{"markr", "lib.lua", "rust_fn", CBM_SITE_PROVEN},
{"markj", "lib.lua", "java_fn", CBM_SITE_PROVEN},
{NULL, NULL, NULL, CBM_SITE_NO_ANSWER},
};
static int sb_check_seam(const char *db, const char *venue) {
int ok = 1;
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.target_fn", "include_scope");
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.other_fn", "include_scope_may");
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.third_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "app.run", "app.markq", "*");
ok &= sb_expect(db, venue, "USAGE", "app.run", "lib.target_fn", "include_scope");
/* the guards keep main's answer: a service call is classified as such, a
* Swift label set, a vendor call and an engine-placed call bind nothing
* of the layer */
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.svc_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "Labels.use", "lib.swift_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "Go.go", "lib.php_fn", NULL);
return ok;
}
/* A proven call answer is applied the same way on both routes at every
* guarded shape (Swift label candidates, a vendor call, an engine-placed
* external call, a service call); a possible one is drawn only where main
* drew nothing at the site. */
TEST(site_bind_seam_answers_agree_on_both_routes) {
char *tmp = th_mktempdir("sb_seam");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_seam(dir), 0);
char seq_db[512];
char par_db[512];
snprintf(seq_db, sizeof(seq_db), "%s/seq.db", tmp);
snprintf(par_db, sizeof(par_db), "%s/par.db", tmp);
ASSERT_EQ(sb_index(dir, seq_db, 1, SB_MARKS), 0);
ASSERT_EQ(sb_index(dir, par_db, 4, SB_MARKS), 0);
int ok = sb_check_seam(seq_db, "sequential") & sb_check_seam(par_db, "parallel");
char *seq = sb_state(seq_db);
char *par = sb_state(par_db);
bool same = seq && par && strcmp(seq, par) == 0;
if (!same) {
printf("\n parallel != sequential\n--- parallel\n%s--- sequential\n%s", par ? par : "",
seq ? seq : "");
}
free(seq);
free(par);
th_cleanup(tmp);
ASSERT_TRUE(ok);
ASSERT_TRUE(same);
PASS();
}
/* USAGE edges proven by the layer (strategy include_scope) into a node whose
* QN ends in `.tgt`. */
static int sb_proven_to(const char *db, const char *tgt) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int n = -1;
if (sqlite3_prepare_v2(h,
"SELECT count(*) FROM edges e JOIN nodes t ON t.id = e.target_id "
"WHERE e.type = 'USAGE' AND t.qualified_name LIKE '%.' || ?1 "
"AND json_extract(e.properties, '$.strategy') = 'include_scope'",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, tgt, -1, SQLITE_TRANSIENT);
if (sqlite3_step(st) == SQLITE_ROW) {
n = sqlite3_column_int(st, 0);
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return n;
}
/* One tree of the protoc fixtures (review 1, B2), indexed on one route; the
* proven USAGE edges into `tgt`. */
static int sb_protoc_case(const char *const files[][2], int nfiles, const char *tgt) {
char *tmp = th_mktempdir("sb_protoc");
if (!tmp) {
return -1;
}
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
int rc = 0;
for (int i = 0; i < nfiles && rc == 0; i++) {
rc = th_write_file(TH_PATH(dir, files[i][0]), files[i][1]);
}
char db[512];
snprintf(db, sizeof(db), "%s/p.db", tmp);
int n = rc == 0 && sb_index(dir, db, 1, NULL) == 0 ? sb_proven_to(db, tgt) : -1;
th_cleanup(tmp);
return n;
}
/* One protoc case: the proven edges it should have; a miss is printed, so
* every shape is reported. */
static int sb_protoc_expect(const char *shape, int got, int want) {
if (got != want) {
printf("\n protoc case %s: %d proven edge(s), want %d\n", shape, got, want);
}
return got == want;
}
/* Proven never where protoc resolves nothing (protoc 3.21.12 on each tree,
* review 1 fixtures, messages quoted): the first component decides the scope
* with no backtracking; a MISSING token; an import cycle; one file under two
* spellings; a path protoc refuses. The compiling partner stays proven. */
TEST(site_bind_protobuf_never_proven_where_protoc_rejects) {
int ok = 1;
/* "common.Status" is resolved to "x.common.Status", which is not defined */
static const char *const prefix[][2] = {
{"common.proto", "syntax = \"proto3\";\npackage common;\nmessage Status { int32 a = 1; }\n"},
{"x/y.proto", "syntax = \"proto3\";\npackage x.common;\nimport \"common.proto\";\n"
"message M { common.Status s = 1; }\n"}};
ok &= sb_protoc_expect("prefix", sb_protoc_case(prefix, 2, "common.Status"), 0);
/* "b.C" is resolved to "a.b.C", which is not defined */
static const char *const pk2[][2] = {
{"c2.proto", "syntax = \"proto3\";\npackage b;\nmessage C { int32 a = 1; }\n"},
{"pk2.proto", "syntax = \"proto3\";\npackage a.b;\nimport \"c2.proto\";\n"
"message M2 { b.C x = 1; }\n"}};
ok &= sb_protoc_expect("pk2", sb_protoc_case(pk2, 2, "c2.C"), 0);
/* compiles: b.D is .a.b.b.D (the innermost scope holding `b`) */
static const char *const pk[][2] = {
{"pk.proto", "syntax = \"proto3\";\npackage a.b;\nmessage b { message D {} }\n"
"message M { b.D x = 1; }\n"}};
ok &= sb_protoc_expect("pk", sb_protoc_case(pk, 1, "pk.D"), 1); /* node pk.D: the file and its name */
/* Expected ";" (a MISSING token after the field), Expected field number */
static const char *const missing[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage t;\nmessage T { int32 a = 1; }\n"},
{"u.proto", "syntax = \"proto3\";\npackage u;\nimport \"t.proto\";\n"
"message M { t.T x = 1 }\n"},
{"w.proto", "syntax = \"proto3\";\npackage w;\nimport \"t.proto\";\n"
"message P { int32 y = ; t.T x = 1; }\n"}};
ok &= sb_protoc_expect("missing", sb_protoc_case(missing, 3, "t.T"), 0);
/* File recursively imports itself */
static const char *const cycle[][2] = {
{"k1.proto", "syntax = \"proto3\";\npackage k;\nimport public \"k2.proto\";\n"
"message K1 { int32 a = 1; }\n"},
{"k2.proto", "syntax = \"proto3\";\npackage k;\nimport public \"k1.proto\";\n"
"message K2 { K1 a = 1; }\n"}};
ok &= sb_protoc_expect("cycle", sb_protoc_case(cycle, 2, "k1.K1"), 0);
/* "cc.T" is already defined in file "common/c.proto" (two spellings) */
static const char *const spell[][2] = {
{"proto/common/c.proto", "syntax = \"proto3\";\npackage cc;\nmessage T { int32 a = 1; }\n"},
{"x.proto", "syntax = \"proto3\";\nimport public \"common/c.proto\";\n"},
{"y.proto", "syntax = \"proto3\";\nimport public \"proto/common/c.proto\";\n"},
{"z.proto", "syntax = \"proto3\";\nimport \"x.proto\";\nimport \"y.proto\";\n"
"message Z { cc.T t = 1; }\n"}};
ok &= sb_protoc_expect("spell", sb_protoc_case(spell, 4, "c.T"), 0);
/* Backslashes, consecutive slashes, ".", or ".." are not allowed in the
* virtual path */
static const char *const dot[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage t;\nmessage T { int32 a = 1; }\n"},
{"dot.proto", "syntax = \"proto3\";\npackage dot;\nimport \"./t.proto\";\n"
"message D { t.T x = 1; }\n"}};
ok &= sb_protoc_expect("dot", sb_protoc_case(dot, 2, "t.T"), 0);
ASSERT_TRUE(ok);
PASS();
}
/* protoc 3.21.12 on rpc types (scope-evidence/review-3/rpc): protoc searches
* an rpc's types from its service, so a method named like the type is found
* first: `rpc Foo(Foo)` gives "Foo" is not a message type, as does a method
* named like an imported message and a response named like its method.
* `.p.Foo` from the root and a method named unlike every type compile. In
* the graph the method Foo and the message Foo are one node (`s.Foo`, the
* method's), so `rpc Foo(.p.Foo)` has no node of protoc's target and nothing
* is proven there; `rpc Get(.p.Foo)` is the root reference's partner. The
* same collision leaves nothing to prove in `same` and `response` before the
* fix too: the imported cases (method and message in two files) are the ones
* the walk proved wrong. */
TEST(site_bind_protobuf_rpc_type_a_method_hides_is_never_proven) {
static const char *const same[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Foo(Foo) returns (Bar);\n}\n"}};
static const char *const dotted[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Foo(.p.Foo) returns (Bar);\n}\n"}};
static const char *const dotted_get[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Get(.p.Foo) returns (Bar);\n}\n"}};
static const char *const partner[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Get(Foo) returns (Bar);\n}\n"}};
static const char *const imported[][2] = {
{"q.proto", "syntax = \"proto3\";\npackage p;\nmessage Baz { int32 a = 1; }\n"},
{"s.proto", "syntax = \"proto3\";\npackage p;\nimport \"q.proto\";\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Baz(Baz) returns (Bar);\n}\n"}};
static const char *const imported_response[][2] = {
{"q.proto", "syntax = \"proto3\";\npackage p;\nmessage Baz { int32 a = 1; }\n"},
{"s.proto", "syntax = \"proto3\";\npackage p;\nimport \"q.proto\";\n"
"message Foo { int32 b = 1; }\nservice S {\n rpc Baz(Foo) returns (Baz);\n}\n"}};
static const char *const response[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Bar(Foo) returns (Bar);\n}\n"}};
int ok = 1;
ok &= sb_protoc_expect("rpc same", sb_protoc_case(same, 1, "s.Foo"), 0);
ok &= sb_protoc_expect("rpc dotted", sb_protoc_case(dotted, 1, "s.Foo"), 0);
ok &= sb_protoc_expect("rpc dotted get", sb_protoc_case(dotted_get, 1, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc partner request", sb_protoc_case(partner, 1, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc partner response", sb_protoc_case(partner, 1, "s.Bar"), 1);
ok &= sb_protoc_expect("rpc imported", sb_protoc_case(imported, 2, "q.Baz"), 0);
ok &= sb_protoc_expect("rpc imported response", sb_protoc_case(imported_response, 2, "q.Baz"),
0);
ok &= sb_protoc_expect("rpc imported response request",
sb_protoc_case(imported_response, 2, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc response", sb_protoc_case(response, 1, "s.Bar"), 0);
ok &= sb_protoc_expect("rpc response request", sb_protoc_case(response, 1, "s.Foo"), 1);
ASSERT_TRUE(ok);
PASS();
}
/* protoc 3.21.12 on review 3's fx4/scope: A's field is .p.A.Type (the
* enclosing message is searched first), B's is .p.Type. Both are proven to
* those, and the outer Type never at A's site, where the inner one shadows
* it. */
TEST(site_bind_protobuf_enclosing_message_decides_first) {
static const char *const scope[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage p;\nenum Type { T0 = 0; }\n"},
{"a.proto", "syntax = \"proto3\";\npackage p;\nimport \"t.proto\";\n"
"message A {\n enum Type { A0 = 0; }\n Type t = 1;\n}\n"
"message B {\n Type t = 1;\n}\n"}};
char *tmp = th_mktempdir("sb_scope");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
int rc = 0;
for (int i = 0; i < 2 && rc == 0; i++) {
rc = th_write_file(TH_PATH(dir, scope[i][0]), scope[i][1]);
}
char db[512];
snprintf(db, sizeof(db), "%s/p.db", tmp);
int indexed = rc == 0 ? sb_index(dir, db, 1, NULL) : -1;
int inner = indexed == 0 ? sb_proven_to(db, "a.Type") : -1; /* A's site */
int outer = indexed == 0 ? sb_proven_to(db, "t.Type") : -1; /* B's site only */
th_cleanup(tmp);
printf("\n proven: a.Type %d, t.Type %d\n", inner, outer);
ASSERT_EQ(indexed, 0);
ASSERT_EQ(inner, 1);
ASSERT_EQ(outer, 1);
PASS();
}
SUITE(site_bind) {
RUN_TEST(site_bind_protobuf_never_proven_where_protoc_rejects);
RUN_TEST(site_bind_protobuf_enclosing_message_decides_first);
RUN_TEST(site_bind_protobuf_rpc_type_a_method_hides_is_never_proven);
RUN_TEST(site_bind_language_without_row_answers_nothing);
RUN_TEST(site_bind_protobuf_reference_binds_what_protoc_resolves);
RUN_TEST(site_bind_protobuf_incremental_equals_full);
RUN_TEST(site_bind_seam_answers_agree_on_both_routes);
}
+3 -1
View File
@@ -118,7 +118,9 @@ CLIENT_HOME_OVERRIDES = (
# so it needs the same neutralization — otherwise a green run on a developer
# machine only proves the ambient config happened to be writable.
test_main = read("tests/test_main.c")
for variable in CLIENT_HOME_OVERRIDES:
for variable in CLIENT_HOME_OVERRIDES + (
"XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME"
):
require(
f'"{variable}"' in test_main,
f"tests/test_main.c must neutralize ambient {variable}",
+99
View File
@@ -0,0 +1,99 @@
"""The smoke watchdog reports hangs separately and cleans the command tree."""
import importlib.util
import pathlib
import queue
import subprocess
import sys
import threading
import unittest
from unittest import mock
SPEC = importlib.util.spec_from_file_location(
"smoke_wrapper_run",
pathlib.Path(__file__).resolve().parents[1] / "scripts/smoke-wrapper-run.py",
)
runner = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(runner)
class WrapperWatchdogTest(unittest.TestCase):
def test_preserves_actual_exit(self):
for code in (0, 7):
with self.subTest(code=code):
self.assertEqual(runner.run([sys.executable, "-c", f"raise SystemExit({code})"]), code)
def test_start_failure(self):
with self.assertRaises(FileNotFoundError):
runner.run([str(pathlib.Path(__file__).resolve().parent / "missing-wrapper-2877")])
def test_hang_stops_real_process(self):
# Inject the outer expiry only after the child is ready, without sleeps.
real_popen = subprocess.Popen
child = None
def start(command, **options):
nonlocal child
child = real_popen(command, stdout=subprocess.PIPE, text=True, **options)
ready = queue.Queue()
threading.Thread(target=lambda: ready.put(child.stdout.readline()), daemon=True).start()
self.assertEqual(ready.get(timeout=30), "ready\n")
real_wait = child.wait
expired = False
def wait(timeout):
nonlocal expired
if not expired:
expired = True
raise subprocess.TimeoutExpired(command, timeout)
return real_wait(timeout=timeout)
child.wait = wait
return child
try:
# taskkill uses Popen too; let that separate command run normally.
def spawn(command, **options):
return real_popen(command, **options) if command[0] == "taskkill" else start(command, **options)
with mock.patch.object(runner.subprocess, "Popen", side_effect=spawn), \
mock.patch.object(runner.sys, "stderr"):
self.assertEqual(runner.run([
sys.executable, "-u", "-c",
"import sys, threading; sys.stdout.buffer.write(b'ready\\r\\n'); "
"sys.stdout.buffer.flush(); threading.Event().wait()",
]), 124)
self.assertIsNotNone(child.poll())
finally:
if child is not None:
if child.poll() is None:
child.kill()
child.wait(timeout=30)
child.stdout.close()
def test_hang_kills_tree_and_reaps(self):
for platform in ("posix", "nt"):
with self.subTest(platform=platform), \
mock.patch.object(runner.os, "name", platform), \
mock.patch.object(runner.subprocess, "Popen") as popen, \
mock.patch.object(runner.subprocess, "run") as taskkill, \
mock.patch.object(runner.os, "killpg", create=True) as killpg, \
mock.patch.object(runner.signal, "SIGKILL", 9, create=True), \
mock.patch.object(runner.sys, "stderr") as diagnostic:
process = popen.return_value
process.pid = 123
process.wait.side_effect = [subprocess.TimeoutExpired("candidate", 600), 0]
self.assertEqual(runner.run(["candidate"]), 124)
popen.assert_called_once_with(["candidate"], start_new_session=platform != "nt")
self.assertEqual(process.wait.call_args_list, [mock.call(timeout=600), mock.call(timeout=30)])
if platform == "nt":
taskkill.assert_called_once_with(
["taskkill", "/PID", "123", "/T", "/F"], check=True, timeout=30)
killpg.assert_not_called()
else:
killpg.assert_called_once_with(123, runner.signal.SIGKILL)
taskkill.assert_not_called()
self.assertIn("HANG go", "".join(call.args[0] for call in diagnostic.write.call_args_list))
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More