Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix: preserve semantic graph relationships

Martin Vogel87a0e3f74ffb
diff --git a/Makefile.cbm b/Makefile.cbm
index d54b01460..33a79e4e7 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -66,13 +66,19 @@ SANITIZE = -fsanitize=address,undefined -fno-omit-frame-pointer
EDITOR_TEST_DEFINES = -DCBM_JSON_LIKE_ENABLE_TEST_API=1 \
-DCBM_TOML_EDIT_ENABLE_TEST_API=1 -DCBM_YAML_ENABLE_TEST_API=1 \
-DCBM_TEXT_EDIT_ENABLE_TEST_API=1 -DCBM_CLI_ENABLE_TEST_API=1
-CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) -g -O1 $(SANITIZE)
+KOTLIN_DEDUP_TEST_DEFINE = -DCBM_KOTLIN_DEDUP_TEST_API=1
+CALL_REFERENCE_LOOKUP_TEST_DEFINE = -DCBM_CALL_REFERENCE_LOOKUP_TEST_API=1
+INCREMENTAL_TEST_DEFINE = -DCBM_INCREMENTAL_TEST_API=1
+CFLAGS_TEST = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(KOTLIN_DEDUP_TEST_DEFINE) \
+ $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) $(INCREMENTAL_TEST_DEFINE) \
+ -g -O1 $(SANITIZE)
CXXFLAGS_TEST = $(CXXFLAGS_COMMON) -g -O1 $(SANITIZE)
# TSan (can't combine with ASan)
TSAN_SANITIZE = -fsanitize=thread -fno-omit-frame-pointer
-CFLAGS_TSAN = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) -g -O1 \
- $(TSAN_SANITIZE)
+CFLAGS_TSAN = $(CFLAGS_COMMON) $(EDITOR_TEST_DEFINES) $(KOTLIN_DEDUP_TEST_DEFINE) \
+ $(CALL_REFERENCE_LOOKUP_TEST_DEFINE) $(INCREMENTAL_TEST_DEFINE) \
+ -g -O1 $(TSAN_SANITIZE)
CXXFLAGS_TSAN = $(CXXFLAGS_COMMON) -g -O1 \
$(TSAN_SANITIZE)
@@ -156,6 +162,14 @@ LSP_UNITY_DEPS = $(CBM_DIR)/lsp_all.c \
# Tree-sitter runtime
TS_RUNTIME_SRC = $(CBM_DIR)/ts_runtime.c
+# ts_runtime.c is a unity wrapper that textually includes the vendored runtime.
+# Track those included sources and headers explicitly: without compiler-generated
+# dependencies, changing stack.c (including its GLR recursion cap) otherwise
+# leaves every runtime object stale while the final binary is merely relinked.
+TS_RUNTIME_DEPS = $(TS_RUNTIME_SRC) \
+ $(wildcard $(TS_SRC)/*.c $(TS_SRC)/*.h \
+ $(TS_SRC)/portable/*.h $(TS_SRC)/unicode/*.h \
+ $(TS_INCLUDE)/tree_sitter/*.h)
# All 64 grammar shim files
GRAMMAR_SRCS = $(wildcard $(CBM_DIR)/grammar_*.c)
@@ -357,7 +371,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_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c
+TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c
TEST_WATCHER_SRCS = tests/test_watcher.c
@@ -423,12 +437,26 @@ TEST_SIMHASH_SRCS = tests/test_simhash.c
TEST_STACK_OVERFLOW_SRCS = tests/test_stack_overflow.c
# Cumulative BUG-REPRODUCTION suite (separate runner, NOT in ALL_TEST_SRCS).
-# These cases are RED by design (one open bug each) — see tests/repro/repro_main.c.
+# Contains RED reproductions plus GREEN controls — see tests/repro/repro_main.c.
# Kept out of the gating `make test` so `ci-ok` stays green; run via `make test-repro`.
TEST_REPRO_SRCS = \
tests/repro/repro_main.c \
tests/repro/repro_parallel_determinism.c \
tests/repro/repro_extraction.c \
+ tests/repro/repro_runner_filter.c \
+ tests/repro/repro_harness_cleanup.c \
+ tests/repro/repro_language_registry.c \
+ tests/repro/repro_call_node_manifest.c \
+ tests/repro/repro_call_scope_usages.c \
+ tests/repro/repro_call_argument_usages.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_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_issue495.c \
tests/repro/repro_issue521.c \
tests/repro/repro_issue382.c \
@@ -485,6 +513,11 @@ TEST_REPRO_SRCS = \
tests/repro/repro_lsp_java_cs.c \
tests/repro/repro_lsp_kt_php_rust.c
+TEST_SHARED_HEADERS = tests/test_framework.h tests/test_helpers.h tests/grammar_cases.h \
+ tests/repro/repro_harness.h tests/repro/repro_runner.h
+TEST_REPRO_HEADERS = $(wildcard tests/repro/*.h) tests/test_framework.h tests/test_helpers.h
+PROD_HEADERS = $(wildcard src/*.h src/*/*.h $(CBM_DIR)/*.h $(CBM_DIR)/lsp/*.h)
+
ALL_TEST_SRCS =$(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_ZSTD_SRCS) $(TEST_ARTIFACT_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_PHP_LSP_SRCS) $(TEST_CS_LSP_SRCS) $(TEST_CS_LSP_BENCH_SRCS) $(TEST_PERL_LSP_SRCS) $(TEST_SCOPE_SRCS) $(TEST_TYPE_REP_SRCS) $(TEST_PY_LSP_SRCS) $(TEST_PY_LSP_BENCH_SRCS) $(TEST_PY_LSP_STRESS_SRCS) $(TEST_PY_LSP_SCALE_SRCS) $(TEST_TS_LSP_SRCS) $(TEST_JAVA_LSP_SRCS) $(TEST_KOTLIN_LSP_SRCS) $(TEST_RUST_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_HTTPD_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SEMANTIC_SRCS) $(TEST_AST_PROFILE_SRCS) $(TEST_SLAB_ALLOC_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)
@@ -531,7 +564,7 @@ test-foundation: $(BUILD_DIR)/test-foundation
$(BUILD_DIR)/%.o: $(CBM_DIR)/%.c | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS_TEST) -c -o $@ $<
-$(BUILD_DIR)/ts_runtime.o: $(CBM_DIR)/ts_runtime.c | $(BUILD_DIR)
+$(BUILD_DIR)/ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS_TEST) -c -o $@ $<
$(BUILD_DIR)/lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR)
@@ -543,7 +576,7 @@ $(BUILD_DIR)/preprocessor.o: $(CBM_DIR)/preprocessor.cpp | $(BUILD_DIR)
$(BUILD_DIR)/tsan_%.o: $(CBM_DIR)/%.c | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS_TSAN) -c -o $@ $<
-$(BUILD_DIR)/tsan_ts_runtime.o: $(CBM_DIR)/ts_runtime.c | $(BUILD_DIR)
+$(BUILD_DIR)/tsan_ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS_TSAN) -c -o $@ $<
$(BUILD_DIR)/tsan_lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR)
@@ -629,7 +662,7 @@ $(UNIXCODER_OBJ): $(UNIXCODER_BLOB_SRC) vendored/nomic/code_vectors.bin | $(BUIL
OBJS_VENDORED_TEST = $(MIMALLOC_OBJ_TEST) $(SQLITE3_OBJ_TEST) $(TRE_OBJ_TEST) $(GRAMMAR_OBJS_TEST) $(TS_RUNTIME_OBJ_TEST) $(LSP_OBJ_TEST) $(PP_OBJ_TEST) $(LZ4_OBJ_TEST) $(ZSTD_OBJ_TEST) $(UNIXCODER_OBJ)
OBJS_VENDORED_TSAN = $(MIMALLOC_OBJ_TSAN) $(SQLITE3_OBJ_TSAN) $(TRE_OBJ_TSAN) $(GRAMMAR_OBJS_TSAN) $(TS_RUNTIME_OBJ_TSAN) $(LSP_OBJ_TSAN) $(PP_OBJ_TSAN) $(LZ4_OBJ_TSAN) $(ZSTD_OBJ_TSAN) $(UNIXCODER_OBJ)
-$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) | $(BUILD_DIR)
+$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(TEST_SHARED_HEADERS) $(PROD_HEADERS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) | $(BUILD_DIR)
$(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \
$(ALL_TEST_SRCS) $(PROD_SRCS) \
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
@@ -653,11 +686,11 @@ test-focused: $(BUILD_DIR)/test-runner
(echo "TEST_SUITES is required for test-focused"; exit 2)
cd $(CURDIR) && $(BUILD_DIR)/test-runner $(TEST_SUITES)
-# ── Cumulative bug-reproduction runner (RED by design, non-gating) ──
+# ── Cumulative bug-reproduction runner (RED board by design, non-gating) ──
# Mirrors test-runner's link line but uses repro_main.c (own main + counters)
# and TEST_REPRO_SRCS instead of ALL_TEST_SRCS. Exits non-zero while any bug is
# still reproduced (the expected state); bug-repro.yml surfaces it as a board.
-$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) | $(BUILD_DIR)
+$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(TEST_REPRO_HEADERS) $(PROD_HEADERS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) | $(BUILD_DIR)
$(CC) $(CFLAGS_TEST) -Itests -o $@ \
$(TEST_REPRO_SRCS) $(PROD_SRCS) \
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
@@ -665,6 +698,15 @@ $(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(PROD_SRCS) $(EXTRACTION_SRC
$(LDFLAGS_TEST)
test-repro: $(BUILD_DIR)/test-repro-runner
+ cd $(CURDIR) && bash tests/repro/repro_script_summary.sh
+ cd $(CURDIR) && bash tests/repro/repro_script_zero_selection.sh
+ cd $(CURDIR) && bash tests/repro/repro_script_missing_summary.sh
+ cd $(CURDIR) && bash tests/repro/repro_script_skipped_summary.sh
+ cd $(CURDIR) && bash tests/repro/repro_runner_zero_selection.sh
+ cd $(CURDIR) && bash tests/repro/repro_runner_passing_semantics.sh
+ cd $(CURDIR) && bash tests/repro/repro_script_no_workspace_artifact.sh
+ cd $(CURDIR) && bash tests/repro/repro_script_stderr_summary.sh
+ cd $(CURDIR) && bash tests/repro/repro_make_tracks_headers.sh
cd $(CURDIR) && $(BUILD_DIR)/test-repro-runner
# ── TSan full test ───────────────────────────────────────────────
@@ -672,7 +714,7 @@ test-repro: $(BUILD_DIR)/test-repro-runner
TEST_TSAN_SUITES ?= mem slab_alloc parallel
TSAN_OPTIONS ?= halt_on_error=1
-$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) | $(BUILD_DIR)
+$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(TEST_SHARED_HEADERS) $(PROD_HEADERS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) | $(BUILD_DIR)
$(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -o $@ \
$(ALL_TEST_SRCS) $(PROD_SRCS) \
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
@@ -693,7 +735,7 @@ PP_OBJ_PROD = $(BUILD_DIR)/prod_preprocessor.o
$(BUILD_DIR)/prod_%.o: $(CBM_DIR)/%.c | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS) -c -o $@ $<
-$(BUILD_DIR)/prod_ts_runtime.o: $(CBM_DIR)/ts_runtime.c | $(BUILD_DIR)
+$(BUILD_DIR)/prod_ts_runtime.o: $(TS_RUNTIME_DEPS) | $(BUILD_DIR)
$(CC) $(GRAMMAR_CFLAGS) -c -o $@ $<
$(BUILD_DIR)/prod_lsp_all.o: $(LSP_UNITY_DEPS) | $(BUILD_DIR)
@@ -718,7 +760,7 @@ OBJS_VENDORED_PROD = $(MIMALLOC_OBJ_PROD) $(SQLITE3_OBJ_PROD) $(TRE_OBJ_PROD) $(
MAIN_SRC = src/main.c
-$(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_PROD) | $(BUILD_DIR)
+$(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_HEADERS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_PROD) | $(BUILD_DIR)
$(CC) $(CFLAGS_PROD) -o $@ \
$(MAIN_SRC) $(PROD_SRCS) \
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
diff --git a/README.md b/README.md
index bb4919ed5..7aa9c1edb 100644
--- a/README.md
+++ b/README.md
@@ -175,7 +175,10 @@ Removes owned agent config entries, skills, hooks, instructions, and the install
- **Cross-repo architecture summary** combining services, routes, and dependencies across the indexed fleet
### Edge types (selected)
-- `CALLS`, `IMPORTS`, `DEFINES`, `IMPLEMENTS`, `INHERITS`
+- `CALLS` — a callable is invoked at the source site
+- `CALL_REFERENCE` — a callable is used at a supported reference site (for example, a direct value argument) and resolves to one exact target
+- `USAGE` — an identifier is used, but a unique callable target is not proven (including ambiguous or complex expressions)
+- `IMPORTS`, `DEFINES`, `IMPLEMENTS`, `INHERITS`
- `HTTP_CALLS`, `ASYNC_CALLS` (cross-service)
- `EMITS`, `LISTENS_ON` (channels)
- `DATA_FLOWS` with arg-to-param mapping + field access chains
@@ -568,7 +571,7 @@ codebase-memory-mcp cli --raw search_graph '{"project": "my-project", "label": "
### Edge Types
-`CONTAINS_PACKAGE`, `CONTAINS_FOLDER`, `CONTAINS_FILE`, `DEFINES`, `DEFINES_METHOD`, `IMPORTS`, `CALLS`, `HTTP_CALLS`, `ASYNC_CALLS`, `IMPLEMENTS`, `HANDLES`, `USAGE`, `CONFIGURES`, `WRITES`, `MEMBER_OF`, `TESTS`, `USES_TYPE`, `FILE_CHANGES_WITH`
+`CONTAINS_PACKAGE`, `CONTAINS_FOLDER`, `CONTAINS_FILE`, `DEFINES`, `DEFINES_METHOD`, `IMPORTS`, `CALLS`, `CALL_REFERENCE`, `HTTP_CALLS`, `ASYNC_CALLS`, `IMPLEMENTS`, `HANDLES`, `USAGE`, `CONFIGURES`, `WRITES`, `MEMBER_OF`, `TESTS`, `USES_TYPE`, `FILE_CHANGES_WITH`
### Qualified Names
@@ -665,7 +668,7 @@ SQLite databases stored at `~/.cache/codebase-memory-mcp/`. Persists across rest
Tree-sitter alone gives a syntactic AST. That handles naming, structure, and call sites well, but it can't tell you that `user.profile.display_name()` resolves to `Profile.display_name` declared three modules away — tree-sitter doesn't track imports, generics, inheritance, or stdlib types.
-codebase-memory-mcp ships a **lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers** (tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, rust-analyzer), embedded directly into the static binary. No language server process, no per-project setup, no API key. We call this layer **Hybrid LSP**: it runs alongside tree-sitter on every parse and refines `CALLS`, `USAGE`, and `RESOLVED_CALLS` edges with type information, so the resulting graph mirrors what an IDE "Go to Definition" would resolve.
+codebase-memory-mcp ships a **lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers** (tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, rust-analyzer), embedded directly into the static binary. No language server process, no per-project setup, no API key. We call this layer **Hybrid LSP**: it runs alongside tree-sitter on every parse and refines invocation resolution (`CALLS` / `RESOLVED_CALLS`) and callable-value resolution (`CALL_REFERENCE`, with ambiguous values retained as `USAGE`) using type information, so the resulting graph mirrors what an IDE "Go to Definition" would resolve.
**Languages with full Hybrid LSP:**
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c
index 40a1ef9f4..e246ce305 100644
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@ -1229,7 +1229,8 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
cbm_run_go_lsp(a, result, source, source_len, root);
}
if (language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA) {
- cbm_run_c_lsp(a, result, source, source_len, root, language != CBM_LANG_C);
+ cbm_run_c_lsp(a, result, source, source_len, root, language != CBM_LANG_C,
+ CBM_SOURCE_ORIGIN_RAW);
}
if (language == CBM_LANG_PHP) {
cbm_run_php_lsp(a, result, source, source_len, root);
@@ -1289,8 +1290,11 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
if (preprocessed && preprocessed->source) {
char *expanded = preprocessed->source;
int expanded_len = (int)strlen(expanded);
- // Record calls count before second pass
+ // Record every site-bearing array boundary before the second pass.
+ // Numeric byte spans in `expanded` are not raw-source coordinates.
int calls_before = result->calls.count;
+ int usages_before = result->usages.count;
+ int resolved_before = result->resolved_calls.count;
// Parse expanded source with fresh tree
TSParser *pp_parser = get_thread_parser(ts_lang, language);
@@ -1326,11 +1330,30 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
// harmless (pipeline deduplicates by caller+callee).
cbm_extract_unified(&pp_ctx);
+ /* Stamp parser carriers before C-LSP performs any
+ * origin-sensitive rewrite. Numeric spans in the expanded
+ * buffer may collide with unrelated raw-source spans. */
+ for (int i = calls_before; i < result->calls.count; i++) {
+ result->calls.items[i].source_origin = CBM_SOURCE_ORIGIN_PREPROCESSED;
+ }
+ for (int i = usages_before; i < result->usages.count; i++) {
+ result->usages.items[i].source_origin = CBM_SOURCE_ORIGIN_PREPROCESSED;
+ }
+
// Also run LSP on expanded source for additional type-resolved
// calls (language is already C/C++/CUDA — checked in enclosing
// block). Runs in every mode.
cbm_run_c_lsp(a, result, expanded, expanded_len, pp_root,
- language != CBM_LANG_C);
+ language != CBM_LANG_C, CBM_SOURCE_ORIGIN_PREPROCESSED);
+
+ /* All C-LSP emitters stamp origin directly so rewrite-time
+ * comparisons are already safe. Keep this boundary sweep as
+ * a defensive invariant for any future emitter added to the
+ * C resolver. */
+ for (int i = resolved_before; i < result->resolved_calls.count; i++) {
+ result->resolved_calls.items[i].source_origin =
+ CBM_SOURCE_ORIGIN_PREPROCESSED;
+ }
/* #961: a def whose body braces are split across
* #ifdef/#else branches parses as an ERROR region on the
@@ -1537,6 +1560,12 @@ void cbm_free_result(CBMFileResult *result) {
ts_tree_delete(result->cached_tree);
result->cached_tree = NULL;
}
+ for (int i = 0; i < result->owned_result_count; i++) {
+ cbm_free_result(result->owned_results[i]);
+ }
+ free(result->owned_results);
+ result->owned_results = NULL;
+ result->owned_result_count = 0;
cbm_arena_destroy(&result->arena);
free(result);
}
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h
index 28de37fb7..c4095d7dd 100644
--- a/internal/cbm/cbm.h
+++ b/internal/cbm/cbm.h
@@ -186,38 +186,44 @@ typedef struct {
const char *file_path; // relative path
uint32_t start_line;
uint32_t end_line;
- const char *signature; // parameter text (NULL if none)
- const char *return_type; // return type text (NULL if none)
- const char *receiver; // Go method receiver (NULL if none)
- const char *docstring; // leading doc comment (NULL if none)
- const char *parent_class; // enclosing class QN for methods (NULL if none)
- const char **decorators; // NULL-terminated array (NULL if none)
- const char **base_classes; // NULL-terminated array (NULL if none)
- const char **param_names; // NULL-terminated array (NULL if none)
- const char **param_types; // NULL-terminated array (NULL if none)
- const char **return_types; // NULL-terminated array (NULL if none)
- const char *route_path; // HTTP route path from decorator (e.g., "/api/users") or NULL
- const char *route_method; // HTTP method from decorator (e.g., "POST") or NULL
- int complexity; // cyclomatic complexity
- int cognitive; // cognitive complexity (nesting-weighted)
- int loop_count; // number of loop constructs in the body
- int loop_depth; // max nested-loop depth (bottleneck proxy)
- bool is_recursive; // body contains a direct self-call (seed for "recursive")
- int param_count; // number of parameters (large = complexity smell)
- int max_access_depth; // deepest chained member/subscript access (a.b.c.d)
- int linear_scan_in_loop; // count of linear-scan calls (find/contains/indexOf) inside loops
- int alloc_in_loop; // count of allocation/append calls inside loops
- bool recursion_in_loop; // a self-call occurs inside a loop body
- bool unguarded_recursion; // recursive with no self-call guarded by a conditional
- int lines; // body line count
- uint32_t *fingerprint; // MinHash fingerprint (arena-allocated, K values) or NULL
- int fingerprint_k; // number of hash values (CBM_MINHASH_K or 0)
+ const char *signature; // parameter text (NULL if none)
+ const char *return_type; // return type text (NULL if none)
+ const char *receiver; // Go method receiver (NULL if none)
+ const char *docstring; // leading doc comment (NULL if none)
+ const char *parent_class; // enclosing class QN for methods (NULL if none)
+ const char **decorators; // NULL-terminated array (NULL if none)
+ const char **base_classes; // NULL-terminated array (NULL if none)
+ const char **param_names; // NULL-terminated array (NULL if none)
+ const char **param_types; // NULL-terminated array (NULL if none)
+ const char **signature_param_types; // ordered internal signature types; "?" means unknown
+ int signature_param_count; // number of entries in signature_param_types
+ const char **return_types; // NULL-terminated array (NULL if none)
+ const char *route_path; // HTTP route path from decorator (e.g., "/api/users") or NULL
+ const char *route_method; // HTTP method from decorator (e.g., "POST") or NULL
+ int complexity; // cyclomatic complexity
+ int cognitive; // cognitive complexity (nesting-weighted)
+ int loop_count; // number of loop constructs in the body
+ int loop_depth; // max nested-loop depth (bottleneck proxy)
+ bool is_recursive; // body contains a direct self-call (seed for "recursive")
+ int param_count; // number of parameters (large = complexity smell)
+ int max_access_depth; // deepest chained member/subscript access (a.b.c.d)
+ int linear_scan_in_loop; // count of linear-scan calls (find/contains/indexOf) inside loops
+ int alloc_in_loop; // count of allocation/append calls inside loops
+ bool recursion_in_loop; // a self-call occurs inside a loop body
+ bool unguarded_recursion; // recursive with no self-call guarded by a conditional
+ int lines; // body line count
+ uint32_t *fingerprint; // MinHash fingerprint (arena-allocated, K values) or NULL
+ int fingerprint_k; // number of hash values (CBM_MINHASH_K or 0)
bool is_exported;
bool is_abstract;
bool is_test;
bool is_entry_point;
const char *structural_profile; // AST structural profile (arena-allocated) or NULL
const char *body_tokens; // space-separated raw identifier tokens from body (arena) or NULL
+ /* Rust only: raw trait path from the exact `impl Trait for Type` block
+ * that declared this method. Kept at the tail so zero-initialised
+ * callers in every other language remain ABI/source compatible. */
+ const char *impl_trait;
} CBMDefinition;
/* Argument captured from a call expression */
@@ -230,6 +236,14 @@ typedef struct {
#define CBM_MAX_CALL_ARGS 8
+/* Byte offsets are meaningful only within the source buffer that produced
+ * them. C/C++/CUDA run both raw and preprocessed extraction passes, and those
+ * buffers can contain unrelated occurrences at the same numeric span. */
+typedef enum {
+ CBM_SOURCE_ORIGIN_RAW = 0,
+ CBM_SOURCE_ORIGIN_PREPROCESSED,
+} CBMSourceOrigin;
+
typedef struct {
const char *callee_name; // raw callee text ("pkg.Func", "foo")
const char *enclosing_func_qn; // QN of enclosing function (or module QN)
@@ -240,9 +254,14 @@ typedef struct {
int loop_depth; // enclosing loop nesting at the call site
int branch_depth; // enclosing branch nesting at the call site
int start_line; // 1-based source line of the call (for def range-match)
+ uint32_t site_start_byte; // exact AST occurrence span; end > start when present
+ uint32_t site_end_byte; // exclusive byte offset in the source file
+ CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
bool is_method; // method/member call with a non-self receiver. Perl:
// arrow/method call ($obj->m). TS/JS/TSX: member call
// x.foo() whose receiver is not this/super. Default false.
+ bool requires_lsp_resolution; // synthetic semantic candidate (for example an implicit
+ // C++ operator). Never fall back to textual resolution.
} CBMCall;
typedef struct {
@@ -250,9 +269,22 @@ typedef struct {
const char *module_path; // resolved module path / QN
} CBMImport;
-typedef struct {
- const char *ref_name; // referenced identifier
- const char *enclosing_func_qn; // QN of enclosing function (or module QN)
+typedef enum {
+ CBM_USAGE_VALUE = 0,
+ CBM_USAGE_CALL_REFERENCE,
+} CBMUsageKind;
+
+typedef struct {
+ const char *ref_name; // referenced identifier
+ const char *enclosing_func_qn; // QN of enclosing function (or module QN)
+ CBMUsageKind kind; // ordinary USAGE or explicit callable reference
+ bool may_be_call_reference; // syntactic candidate; exact LSP proof may upgrade its edge
+ bool semantic_reference_blocked; // lexical evidence blocks only unproven textual fallback
+ bool semantic_reference_local_shadow; // blocker belongs to a non-module lexical scope
+ uint32_t lexical_scope_id; // extraction-local scope instance; never graph identity
+ uint32_t site_start_byte; // exact reference-token span; end > start when present
+ uint32_t site_end_byte; // exclusive byte offset in the source file
+ CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
} CBMUsage;
typedef struct {
@@ -327,15 +359,28 @@ typedef struct {
typedef struct {
const char *trait_name; // trait name (raw text)
const char *struct_name; // struct/type name (raw text)
+ /* Exact extracted QN of the implementing type. Unlike struct_name this
+ * does not need a later leaf-name guess, and the relation exists even for
+ * an empty `impl Trait for Type {}` block. */
+ const char *struct_qn;
} CBMImplTrait;
-// LSP-resolved call: high-confidence type-aware call resolution
-typedef struct {
- const char *caller_qn; // enclosing function QN
- const char *callee_qn; // resolved target QN (fully qualified)
- const char *strategy; // "lsp_type_dispatch", "lsp_direct", etc.
- float confidence; // 0.90-0.95
- const char *reason; // diagnostic label for unresolved calls (NULL if resolved)
+typedef enum {
+ CBM_RESOLVED_INVOCATION = 0,
+ CBM_RESOLVED_CALL_REFERENCE,
+} CBMResolvedKind;
+
+// LSP-resolved invocation/reference: high-confidence type-aware resolution.
+typedef struct {
+ const char *caller_qn; // enclosing function QN
+ const char *callee_qn; // resolved target QN (fully qualified)
+ const char *strategy; // "lsp_type_dispatch", "lsp_direct", etc.
+ float confidence; // 0.90-0.95
+ const char *reason; // diagnostic label for unresolved calls (NULL if resolved)
+ CBMResolvedKind kind; // invocation (CALLS) or explicit callable reference
+ uint32_t site_start_byte; // exact source occurrence; end > start when present
+ uint32_t site_end_byte; // exclusive byte offset in the source file
+ CBMSourceOrigin source_origin; // raw source or C-family preprocessed buffer
} CBMResolvedCall;
typedef struct {
@@ -424,8 +469,8 @@ typedef struct {
} CBMChannelArray;
// Full extraction result for one file.
-typedef struct {
- CBMArena arena; // owns all string memory
+typedef struct CBMFileResult {
+ CBMArena arena; // owns local memory; composites may also retain child arenas below
CBMDefArray defs;
CBMCallArray calls;
@@ -437,7 +482,7 @@ typedef struct {
CBMEnvAccessArray env_accesses;
CBMTypeAssignArray type_assigns;
CBMImplTraitArray impl_traits; // Rust: impl Trait for Struct pairs
- CBMResolvedCallArray resolved_calls; // LSP-resolved calls (high confidence)
+ CBMResolvedCallArray resolved_calls; // LSP-resolved invocations/references (high confidence)
CBMStringRefArray string_refs; // URL/config string literals from AST
CBMInfraBindingArray infra_bindings; // topic→URL pairs from IaC configs
CBMChannelArray channels; // Socket.IO / EventEmitter pub/sub participation
@@ -474,6 +519,13 @@ typedef struct {
// file (defs/calls already extracted are unaffected).
const char *source;
int source_len;
+
+ // Composite extraction results (currently ObjectScript Studio Export)
+ // retain their per-unit results so shallow-copied carrier strings remain
+ // valid for the composite's full lifetime. Owned and recursively released
+ // by cbm_free_result(); ordinary single-file results leave these zeroed.
+ struct CBMFileResult **owned_results;
+ int owned_result_count;
} CBMFileResult;
// --- Enclosing function cache ---
@@ -628,6 +680,21 @@ uint64_t cbm_get_preprocess_ns(void);
uint64_t cbm_get_files_preprocessed(void);
void cbm_reset_profile(void);
+#if defined(CBM_KOTLIN_DEDUP_TEST_API) && CBM_KOTLIN_DEDUP_TEST_API
+// Test-build-only operation counter for Kotlin operator-carrier deduplication.
+// Production builds do not expose or retain this instrumentation.
+void cbm_kotlin_operator_dedup_test_reset(void);
+uint64_t cbm_kotlin_operator_dedup_test_comparisons(void);
+#endif
+
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+// Test-build-only work counter for resolving a node's field role while
+// classifying value references. Production builds retain no instrumentation.
+void cbm_usage_field_lookup_test_reset(void);
+uint64_t cbm_usage_field_lookup_test_work(void);
+uint64_t cbm_usage_slow_parent_fallback_test_count(void);
+#endif
+
// Toggle C/C++ preprocessor Macro-node extraction (#375). The pipeline enables
// it only for full/advanced index modes (it dominates extraction on macro-dense
// codebases). Default ON. Set before extraction; read-only during.
diff --git a/internal/cbm/extract_calls.c b/internal/cbm/extract_calls.c
index ea0fb8b94..e771e9ed0 100644
--- a/internal/cbm/extract_calls.c
+++ b/internal/cbm/extract_calls.c
@@ -13,6 +13,9 @@
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
+#if defined(CBM_KOTLIN_DEDUP_TEST_API) && CBM_KOTLIN_DEDUP_TEST_API
+#include <stdatomic.h>
+#endif
/* Max ancestor depth for Lean type-position check. */
enum { LEAN_MAX_PARENT_DEPTH = 20 };
@@ -432,6 +435,22 @@ static bool perl_is_identifier_callee(const char *name) {
// Callee extraction for scripting languages (Elixir, Perl, PHP, Kotlin, MATLAB).
static char *extract_scripting_callee(CBMArena *a, TSNode node, const char *source,
CBMLanguage lang, const char *nk) {
+ if (lang == CBM_LANG_ELIXIR && strcmp(nk, "binary_operator") == 0) {
+ /* The grammar exposes the operator as an exact field. Reading the bytes
+ * between operands also captured binding punctuation in definition
+ * heads; those containers are not invocations. */
+ TSNode op = ts_node_child_by_field_name(node, TS_FIELD("operator"));
+ if (ts_node_is_null(op)) {
+ return NULL;
+ }
+ char *operator_name = cbm_node_text(a, op, source);
+ if (!operator_name || strcmp(operator_name, "=") == 0 || strcmp(operator_name, "<-") == 0 ||
+ strcmp(operator_name, "->") == 0 || strcmp(operator_name, "\\\\") == 0 ||
+ strcmp(operator_name, "::") == 0 || strcmp(operator_name, "when") == 0) {
+ return NULL;
+ }
+ return operator_name;
+ }
if (lang == CBM_LANG_ELIXIR && strcmp(nk, "call") == 0 && ts_node_child_count(node) > 0) {
TSNode first = ts_node_child(node, 0);
const char *fk = ts_node_type(first);
@@ -494,6 +513,200 @@ static char *extract_erlang_callee(CBMArena *a, TSNode node, const char *source,
return cbm_node_text(a, ts_node_child(node, 0), source);
}
+static bool call_node_contains(TSNode outer, TSNode inner) {
+ return !ts_node_is_null(outer) && !ts_node_is_null(inner) &&
+ ts_node_start_byte(outer) <= ts_node_start_byte(inner) &&
+ ts_node_end_byte(outer) >= ts_node_end_byte(inner);
+}
+
+static bool call_node_text_equals(const char *source, TSNode node, const char *expected) {
+ if (!source || ts_node_is_null(node) || !expected) {
+ return false;
+ }
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ size_t expected_len = strlen(expected);
+ return end >= start && (size_t)(end - start) == expected_len &&
+ memcmp(source + start, expected, expected_len) == 0;
+}
+
+static bool call_node_text_in(TSNode node, const char *source, const char *const *values) {
+ for (const char *const *value = values; *value; value++) {
+ if (call_node_text_equals(source, node, *value)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool lisp_definition_head(CBMLanguage lang, TSNode head, const char *source) {
+ static const char *const clojure_scheme_racket_heads[] = {"defn",
+ "defn-",
+ "def",
+ "defmacro",
+ "defmulti",
+ "defmethod",
+ "defprotocol",
+ "defrecord",
+ "deftype",
+ "definterface",
+ "defonce",
+ "define",
+ "define-syntax",
+ "define-values",
+ "define-syntax-rule",
+ "define-struct",
+ "define-record-type",
+ "define/contract",
+ "struct",
+ NULL};
+ static const char *const common_lisp_heads[] = {
+ "defun", "defmacro", "defgeneric", "defmethod", "defvar", "defparameter",
+ "defconstant", "deftype", "defstruct", "defclass", NULL};
+
+ return call_node_text_in(head, source,
+ lang == CBM_LANG_COMMONLISP ? common_lisp_heads
+ : clojure_scheme_racket_heads);
+}
+
+static bool lisp_list_is_definition_role(CBMLanguage lang, TSNode node, const char *source) {
+ uint32_t count = ts_node_named_child_count(node);
+ if (count > 0 && lisp_definition_head(lang, ts_node_named_child(node, 0), source)) {
+ return true;
+ }
+
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *parent_kind = ts_node_type(parent);
+ if (lang == CBM_LANG_COMMONLISP &&
+ (strcmp(parent_kind, "defun_header") == 0 || strcmp(parent_kind, "lambda_list") == 0)) {
+ return true;
+ }
+ if (lang == CBM_LANG_EMACSLISP && (strcmp(parent_kind, "function_definition") == 0 ||
+ strcmp(parent_kind, "macro_definition") == 0)) {
+ TSNode parameters = ts_node_child_by_field_name(parent, TS_FIELD("parameters"));
+ return call_node_contains(parameters, node);
+ }
+ if ((strcmp(parent_kind, "list") == 0 || strcmp(parent_kind, "list_lit") == 0) &&
+ ts_node_named_child_count(parent) >= 2 &&
+ lisp_definition_head(lang, ts_node_named_child(parent, 0), source)) {
+ /* `(define (name args) body)` nests the signature list in the
+ * definition's second form. Body lists remain genuine calls. */
+ return call_node_contains(ts_node_named_child(parent, 1), node);
+ }
+ }
+ return false;
+}
+
+static bool call_node_has_direct_token(TSNode node, const char *token) {
+ uint32_t count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ if (strcmp(ts_node_type(ts_node_child(node, i)), token) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool julia_call_is_definition_head(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "assignment") == 0 || strcmp(kind, "function_definition") == 0 ||
+ strcmp(kind, "short_function_definition") == 0) {
+ return ts_node_named_child_count(parent) > 0 &&
+ call_node_contains(ts_node_named_child(parent, 0), node);
+ }
+ }
+ return false;
+}
+
+static bool typst_call_is_let_pattern(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "let") == 0) {
+ TSNode pattern = ts_node_child_by_field_name(parent, TS_FIELD("pattern"));
+ return call_node_contains(pattern, node);
+ }
+ }
+ return false;
+}
+
+static bool agda_expr_is_definition_role(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "lhs") == 0 || strcmp(kind, "typed_binding") == 0 ||
+ strcmp(kind, "signature") == 0 || strcmp(kind, "type_signature") == 0 ||
+ strcmp(kind, "data_signature") == 0 || strcmp(kind, "record_signature") == 0) {
+ return true;
+ }
+ if (strcmp(kind, "function") == 0) {
+ /* A ':' function line is a type signature. In an '=' definition,
+ * lhs expressions were rejected above and rhs applications remain
+ * executable calls. */
+ return call_node_has_direct_token(parent, ":");
+ }
+ }
+ return false;
+}
+
+static TSNode elixir_call_arguments(TSNode call) {
+ TSNode arguments = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
+ if (ts_node_is_null(arguments) && ts_node_child_count(call) > 1) {
+ arguments = ts_node_child(call, 1);
+ }
+ return arguments;
+}
+
+static bool elixir_call_head_in(TSNode call, const char *source, const char *const *heads) {
+ return ts_node_child_count(call) > 0 &&
+ call_node_text_in(ts_node_child(call, 0), source, heads);
+}
+
+static bool elixir_call_is_definition_role(TSNode node, const char *source) {
+ static const char *const structural_heads[] = {"def", "defp", "defmacro", "defmodule", NULL};
+ static const char *const function_heads[] = {"def", "defp", "defmacro", NULL};
+ if (elixir_call_head_in(node, source, structural_heads)) {
+ return true;
+ }
+
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "call") != 0 ||
+ !elixir_call_head_in(parent, source, function_heads)) {
+ continue;
+ }
+ TSNode arguments = elixir_call_arguments(parent);
+ TSNode signature = ts_node_named_child_count(arguments) > 0
+ ? ts_node_named_child(arguments, 0)
+ : arguments;
+ return ts_node_eq(signature, node);
+ }
+ return false;
+}
+
+static bool call_node_is_definition_container(CBMLanguage lang, TSNode node, const char *source) {
+ const char *kind = ts_node_type(node);
+ if ((lang == CBM_LANG_CLOJURE || lang == CBM_LANG_SCHEME || lang == CBM_LANG_RACKET ||
+ lang == CBM_LANG_COMMONLISP || lang == CBM_LANG_EMACSLISP) &&
+ (strcmp(kind, "list") == 0 || strcmp(kind, "list_lit") == 0)) {
+ return lisp_list_is_definition_role(lang, node, source);
+ }
+ if (lang == CBM_LANG_JULIA &&
+ (strcmp(kind, "call_expression") == 0 || strcmp(kind, "broadcast_call_expression") == 0)) {
+ return julia_call_is_definition_head(node);
+ }
+ if (lang == CBM_LANG_TYPST && strcmp(kind, "call") == 0) {
+ return typst_call_is_let_pattern(node);
+ }
+ if (lang == CBM_LANG_AGDA && strcmp(kind, "expr") == 0) {
+ return agda_expr_is_definition_role(node);
+ }
+ return lang == CBM_LANG_ELIXIR && strcmp(kind, "call") == 0 &&
+ elixir_call_is_definition_role(node, source);
+}
+
// Lisp dialects: a call is a list (`list` / `list_lit`) whose head (first named
// child) is the function symbol (`symbol` / `sym_lit`). Generic field/first-child
// extraction misses it because the head is not an `identifier` node.
@@ -538,6 +751,21 @@ static char *extract_css_callee(CBMArena *a, TSNode node, const char *source, co
return ts_node_is_null(fn) ? NULL : cbm_node_text(a, fn, source);
}
+// Linker scripts expose the builtin in the exact `function:` field as a
+// `symbol`. Keep the `arguments:` subtree separate so symbols passed to the
+// builtin remain value usages.
+static char *extract_linkerscript_callee(CBMArena *a, TSNode node, const char *source,
+ const char *nk) {
+ if (strcmp(nk, "call_expression") != 0) {
+ return NULL;
+ }
+ TSNode function = ts_node_child_by_field_name(node, TS_FIELD("function"));
+ if (ts_node_is_null(function) || strcmp(ts_node_type(function), "symbol") != 0) {
+ return NULL;
+ }
+ return cbm_node_text(a, function, source);
+}
+
// PowerShell: a `command` node's callee is its `command_name` child.
static char *extract_powershell_callee(CBMArena *a, TSNode node, const char *source,
const char *nk) {
@@ -864,6 +1092,10 @@ static char *extract_vhdl_callee(CBMArena *a, TSNode node, const char *source, c
// target label. Only treat call/jump mnemonics as calls; everything else (add,
// mov, ret, ...) is plain data-flow, not a call.
static char *extract_nasm_callee(CBMArena *a, TSNode node, const char *source, const char *nk) {
+ if (strcmp(nk, "call_syntax_expression") == 0) {
+ TSNode base = ts_node_child_by_field_name(node, TS_FIELD("base"));
+ return ts_node_is_null(base) ? NULL : first_leaf_identifier(a, base, source);
+ }
if (strcmp(nk, "actual_instruction") != 0) {
return NULL;
}
@@ -941,18 +1173,43 @@ static char *extract_nix_callee(CBMArena *a, TSNode node, const char *source, co
return NULL;
}
-// Agda: function application `f x y` parses as an `expr` whose named children are
-// `atom`s (no dedicated application node). Treat an `expr` with >= 2 atom children
-// as a call whose callee is the head atom's identifier.
-static char *extract_agda_callee(CBMArena *a, TSNode node, const char *source, const char *nk) {
- if (strcmp(nk, "expr") != 0 || ts_node_named_child_count(node) < 2) {
- return NULL;
+// Agda has no fields. A plain application is the exact adjacency shape
+// `expr(atom, atom, ...)`; operator/type expressions also have multiple named
+// children, but include an anonymous operator token and must not become calls.
+static TSNode agda_application_head_atom(TSNode node) {
+ if (strcmp(ts_node_type(node), "expr") != 0 || ts_node_named_child_count(node) < 2 ||
+ ts_node_child_count(node) != ts_node_named_child_count(node)) {
+ return (TSNode){0};
}
- TSNode head = ts_node_named_child(node, 0);
- if (strcmp(ts_node_type(head), "atom") != 0) {
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ if (strcmp(ts_node_type(ts_node_named_child(node, i)), "atom") != 0) {
+ return (TSNode){0};
+ }
+ }
+ return ts_node_named_child(node, 0);
+}
+
+static TSNode agda_head_qid(TSNode head) {
+ TSNode current = head;
+ for (int depth = 0; depth < 8 && !ts_node_is_null(current); depth++) {
+ if (strcmp(ts_node_type(current), "qid") == 0) {
+ return current;
+ }
+ if (ts_node_named_child_count(current) == 0) {
+ break;
+ }
+ current = ts_node_named_child(current, 0);
+ }
+ return (TSNode){0};
+}
+
+static char *extract_agda_callee(CBMArena *a, TSNode node, const char *source, const char *nk) {
+ if (strcmp(nk, "expr") != 0) {
return NULL;
}
- return first_leaf_identifier(a, head, source);
+ TSNode qid = agda_head_qid(agda_application_head_atom(node));
+ return ts_node_is_null(qid) ? NULL : cbm_node_text(a, qid, source);
}
// Make: `$(shell ...)` is a `shell_function` node; the callee is the literal
@@ -1006,6 +1263,13 @@ static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *
CBMLanguage lang) {
const char *nk = ts_node_type(node);
+ if (lang == CBM_LANG_FORTRAN && strcmp(nk, "subroutine_call") == 0) {
+ TSNode subroutine = ts_node_child_by_field_name(node, TS_FIELD("subroutine"));
+ if (!ts_node_is_null(subroutine)) {
+ return cbm_node_text(a, subroutine, source);
+ }
+ }
+
/* Python dict-dispatch call `funcs["a"](v)`: the call's `function` field is a
* subscript whose base is the identifier holding the dispatch table. Emit the
* base identifier ("funcs") as the textual callee so a CALLS edge exists; the
@@ -1050,6 +1314,10 @@ static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *
char *c = extract_css_callee(a, node, source, nk);
return c ? c : extract_scripting_callee(a, node, source, lang, nk);
}
+ if (lang == CBM_LANG_LINKERSCRIPT) {
+ char *c = extract_linkerscript_callee(a, node, source, nk);
+ return c ? c : extract_scripting_callee(a, node, source, lang, nk);
+ }
if (lang == CBM_LANG_SQL) {
char *c = extract_sql_callee(a, node, source, nk);
return c ? c : extract_scripting_callee(a, node, source, lang, nk);
@@ -1094,7 +1362,8 @@ static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *
if (lang == CBM_LANG_ERLANG) {
return extract_erlang_callee(a, node, source, nk);
}
- if (lang == CBM_LANG_HASKELL || lang == CBM_LANG_OCAML || lang == CBM_LANG_PURESCRIPT) {
+ if (lang == CBM_LANG_HASKELL || lang == CBM_LANG_OCAML || lang == CBM_LANG_PURESCRIPT ||
+ lang == CBM_LANG_SCALA) {
return extract_fp_callee(a, node, source, nk);
}
if (lang == CBM_LANG_WOLFRAM && strcmp(nk, "apply") == 0) {
@@ -1191,8 +1460,10 @@ static char *extract_callee_lang_specific(CBMArena *a, TSNode node, const char *
}
return NULL;
}
- // $$label^routine extrinsic / routine tag call -> the line_ref text
- if (strcmp(nk, "routine_tag_call") == 0) {
+ // $$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.
+ 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);
@@ -1342,7 +1613,24 @@ static const char *php_group_prefix_for_call(CBMArena *a, TSNode node, const cha
return pos ? cbm_arena_strndup(a, buf, pos) : NULL;
}
+static bool is_nested_verilog_call_wrapper(CBMLanguage lang, TSNode node) {
+ if (lang != CBM_LANG_VERILOG || strcmp(ts_node_type(node), "subroutine_call") != 0) {
+ return false;
+ }
+
+ TSNode parent = ts_node_parent(node);
+ return !ts_node_is_null(parent) &&
+ strcmp(ts_node_type(parent), "function_subroutine_call") == 0;
+}
+
static char *extract_callee_name(CBMArena *a, TSNode node, const char *source, CBMLanguage lang) {
+ if (call_node_is_definition_container(lang, node, source)) {
+ return NULL;
+ }
+ if (is_nested_verilog_call_wrapper(lang, node)) {
+ return NULL;
+ }
+
// Lean 4: skip type-position applies
if (lang == CBM_LANG_LEAN && strcmp(ts_node_type(node), "apply") == 0) {
if (lean_is_in_type_position(node)) {
@@ -1821,77 +2109,205 @@ static void extract_jsx_component_ref(CBMExtractCtx *ctx, TSNode node, const cha
CBMCall call = {0};
call.callee_name = name;
call.enclosing_func_qn = enclosing_func_qn;
+ call.site_start_byte = ts_node_start_byte(node);
+ call.site_end_byte = ts_node_end_byte(node);
+ /* An uppercase tag is only a component invocation when the TS resolver
+ * proves which lexical value owns it. In particular, a parameter or
+ * local named like a module component must not fall through to the
+ * textual call resolver. */
+ call.requires_lsp_resolution = true;
cbm_calls_push(&ctx->result->calls, ctx->arena, call);
}
}
-// Kotlin: `a OP b` desugars to an operator-method call `a.<method>(b)`. The
-// generic call walk keys on call_expression nodes and so never sees these
-// precedence-specific binary-expression nodes, leaving the type-aware LSP
-// operator resolution (lsp_kt_operator -> the user `operator fun`) with no call
-// site to attach to. Record a textual call to the operator method's bare name;
-// the operator-token -> method mapping mirrors kotlin_lsp.c's binary handler so
-// the names join. Builtin operands (Int+Int) resolve to a stdlib type with no
-// graph node and drop, exactly as before — only user `operator fun`s gain edges.
-static void extract_kotlin_operator_call(CBMExtractCtx *ctx, TSNode node, const char *kind,
- const char *enclosing_func_qn) {
- if (strcmp(kind, "binary_expression") != 0 && strcmp(kind, "additive_expression") != 0 &&
- strcmp(kind, "multiplicative_expression") != 0 &&
- strcmp(kind, "comparison_expression") != 0 && strcmp(kind, "equality_expression") != 0 &&
- strcmp(kind, "range_expression") != 0) {
- return;
- }
- uint32_t ncc = ts_node_named_child_count(node);
- TSNode lhs = ts_node_child_by_field_name(node, TS_FIELD("left"));
- TSNode rhs = ts_node_child_by_field_name(node, TS_FIELD("right"));
- if (ts_node_is_null(lhs) && ncc >= 1) {
- lhs = ts_node_named_child(node, 0);
- }
- if (ts_node_is_null(rhs) && ncc >= 2) {
- rhs = ts_node_named_child(node, ncc - 1);
- }
- if (ts_node_is_null(lhs) || ts_node_is_null(rhs)) {
- return;
+static bool kotlin_direct_unnamed_token(TSNode node, const char *token) {
+ uint32_t count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child) && strcmp(ts_node_type(child), token) == 0) {
+ return true;
+ }
}
- uint32_t lhs_end = ts_node_end_byte(lhs);
- uint32_t rhs_start = ts_node_start_byte(rhs);
- if (rhs_start <= lhs_end) {
- return;
+ return false;
+}
+
+static const char *kotlin_binary_operator_method(TSNode node) {
+ if (kotlin_direct_unnamed_token(node, "===") || kotlin_direct_unnamed_token(node, "!==")) {
+ return NULL; /* identity comparison has no operator method */
+ }
+ if (kotlin_direct_unnamed_token(node, "==") || kotlin_direct_unnamed_token(node, "!=")) {
+ return "equals";
+ }
+ if (kotlin_direct_unnamed_token(node, "..<"))
+ return "rangeUntil";
+ if (kotlin_direct_unnamed_token(node, ".."))
+ return "rangeTo";
+ if (kotlin_direct_unnamed_token(node, "<=") || kotlin_direct_unnamed_token(node, ">=") ||
+ kotlin_direct_unnamed_token(node, "<") || kotlin_direct_unnamed_token(node, ">")) {
+ return "compareTo";
+ }
+ if (kotlin_direct_unnamed_token(node, "+"))
+ return "plus";
+ if (kotlin_direct_unnamed_token(node, "-"))
+ return "minus";
+ if (kotlin_direct_unnamed_token(node, "*"))
+ return "times";
+ if (kotlin_direct_unnamed_token(node, "/"))
+ return "div";
+ if (kotlin_direct_unnamed_token(node, "%"))
+ return "rem";
+ return NULL;
+}
+
+static const char *kotlin_unary_operator_method(TSNode node, const char *kind) {
+ if (strcmp(kind, "postfix_expression") == 0) {
+ if (kotlin_direct_unnamed_token(node, "++"))
+ return "inc";
+ if (kotlin_direct_unnamed_token(node, "--"))
+ return "dec";
+ return NULL; /* `!!` and call/navigation suffixes are not operator calls */
+ }
+ if (kotlin_direct_unnamed_token(node, "++"))
+ return "inc";
+ if (kotlin_direct_unnamed_token(node, "--"))
+ return "dec";
+ if (kotlin_direct_unnamed_token(node, "!"))
+ return "not";
+ if (kotlin_direct_unnamed_token(node, "-"))
+ return "unaryMinus";
+ if (kotlin_direct_unnamed_token(node, "+"))
+ return "unaryPlus";
+ return NULL;
+}
+
+static bool kotlin_node_is_update(TSNode node) {
+ const char *kind = ts_node_type(node);
+ return (strcmp(kind, "prefix_expression") == 0 || strcmp(kind, "postfix_expression") == 0 ||
+ strcmp(kind, "unary_expression") == 0) &&
+ (kotlin_direct_unnamed_token(node, "++") || kotlin_direct_unnamed_token(node, "--"));
+}
+
+static bool kotlin_index_is_write_lhs(TSNode index) {
+ for (TSNode parent = ts_node_parent(index); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "assignment") == 0) {
+ TSNode lhs = ts_node_child_by_field_name(parent, TS_FIELD("left"));
+ if (ts_node_is_null(lhs) && ts_node_named_child_count(parent) > 0) {
+ lhs = ts_node_named_child(parent, 0);
+ }
+ return call_node_contains(lhs, index);
+ }
+ if (kotlin_node_is_update(parent)) {
+ return call_node_contains(parent, index);
+ }
+ if (strcmp(kind, "parenthesized_expression") != 0 &&
+ strcmp(kind, "directly_assignable_expression") != 0 &&
+ strcmp(kind, "assignable_expression") != 0 &&
+ strcmp(kind, "parenthesized_directly_assignable_expression") != 0 &&
+ strcmp(kind, "expression") != 0) {
+ break;
+ }
}
- const char *between = ctx->source + lhs_end;
- size_t blen = (size_t)(rhs_start - lhs_end);
- const char *op_method = NULL;
- if (cbm_memmem(between, blen, "===", 3) || cbm_memmem(between, blen, "!==", 3)) {
- return; // identity comparison: no operator method
- } else if (cbm_memmem(between, blen, "==", 2) || cbm_memmem(between, blen, "!=", 2)) {
- op_method = "equals";
- } else if (cbm_memmem(between, blen, "..<", 3)) {
- op_method = "rangeUntil";
- } else if (cbm_memmem(between, blen, "..", 2)) {
- op_method = "rangeTo";
- } else if (cbm_memmem(between, blen, "<", 1) || cbm_memmem(between, blen, ">", 1)) {
- op_method = "compareTo"; // covers <, >, <=, >=
- } else if (cbm_memmem(between, blen, "+", 1)) {
- op_method = "plus";
- } else if (cbm_memmem(between, blen, "-", 1)) {
- op_method = "minus";
- } else if (cbm_memmem(between, blen, "*", 1)) {
- op_method = "times";
- } else if (cbm_memmem(between, blen, "/", 1)) {
- op_method = "div";
- } else if (cbm_memmem(between, blen, "%", 1)) {
- op_method = "rem";
- }
- if (!op_method) {
+ return false;
+}
+
+static bool kotlin_same_call_owner(const char *left, const char *right) {
+ return left == right || (left && right && strcmp(left, right) == 0);
+}
+
+#if defined(CBM_KOTLIN_DEDUP_TEST_API) && CBM_KOTLIN_DEDUP_TEST_API
+static _Atomic uint64_t g_kotlin_operator_dedup_comparisons = 0;
+
+void cbm_kotlin_operator_dedup_test_reset(void) {
+ atomic_store_explicit(&g_kotlin_operator_dedup_comparisons, 0, memory_order_relaxed);
+}
+
+uint64_t cbm_kotlin_operator_dedup_test_comparisons(void) {
+ return atomic_load_explicit(&g_kotlin_operator_dedup_comparisons, memory_order_relaxed);
+}
+
+static void count_kotlin_operator_dedup_comparison(void) {
+ atomic_fetch_add_explicit(&g_kotlin_operator_dedup_comparisons, 1, memory_order_relaxed);
+}
+#else
+static void count_kotlin_operator_dedup_comparison(void) {}
+#endif
+
+static bool kotlin_operator_call_matches(const CBMCall *existing, const char *callee_name,
+ const char *enclosing_func_qn, uint32_t start,
+ uint32_t end) {
+ count_kotlin_operator_dedup_comparison();
+ return existing->callee_name && strcmp(existing->callee_name, callee_name) == 0 &&
+ kotlin_same_call_owner(existing->enclosing_func_qn, enclosing_func_qn) &&
+ existing->site_start_byte == start && existing->site_end_byte == end;
+}
+
+static void push_kotlin_operator_call(CBMExtractCtx *ctx, TSNode node, const char *callee_name,
+ const char *enclosing_func_qn) {
+ if (!callee_name || !callee_name[0])
return;
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ /* Equal-span Kotlin grammar wrappers are visited consecutively by the
+ * unified preorder walk. Only the last emitted carrier can therefore be
+ * the wrapper duplicate for this node; scanning every prior call made a
+ * file with N operator expressions perform O(N^2) comparisons. */
+ if (ctx->result->calls.count > 0) {
+ const CBMCall *existing = &ctx->result->calls.items[ctx->result->calls.count - SKIP_ONE];
+ if (kotlin_operator_call_matches(existing, callee_name, enclosing_func_qn, start, end)) {
+ return;
+ }
}
CBMCall call = {0};
- call.callee_name = op_method;
+ call.callee_name = callee_name;
call.enclosing_func_qn = enclosing_func_qn;
call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
+ call.site_start_byte = start;
+ call.site_end_byte = end;
+ call.requires_lsp_resolution = true;
cbm_calls_push(&ctx->result->calls, ctx->arena, call);
}
+// Kotlin operator syntax desugars to method calls, but these expressions are
+// not call_expression nodes. Emit an exact-span, LSP-guarded carrier whose bare
+// name can join only the semantic row for the same expression. Operator tokens
+// come from direct unnamed AST children, so comments/operand text cannot alter
+// the mapping. Writes through an index stay fail-closed until set/compound-set
+// semantics are implemented.
+static void extract_kotlin_operator_call(CBMExtractCtx *ctx, TSNode node, const char *kind,
+ const char *enclosing_func_qn) {
+ const char *op_method = NULL;
+ if (strcmp(kind, "binary_expression") == 0 || strcmp(kind, "additive_expression") == 0 ||
+ strcmp(kind, "multiplicative_expression") == 0 ||
+ strcmp(kind, "comparison_expression") == 0 || strcmp(kind, "equality_expression") == 0 ||
+ strcmp(kind, "range_expression") == 0) {
+ if (ts_node_named_child_count(node) < 2)
+ return;
+ op_method = kotlin_binary_operator_method(node);
+ } else if (strcmp(kind, "unary_expression") == 0 || strcmp(kind, "prefix_expression") == 0 ||
+ strcmp(kind, "postfix_expression") == 0) {
+ if (ts_node_named_child_count(node) < 1)
+ return;
+ op_method = kotlin_unary_operator_method(node, kind);
+ } else if (strcmp(kind, "in_expression") == 0 || strcmp(kind, "check_expression") == 0) {
+ if (ts_node_named_child_count(node) < 2 ||
+ (!kotlin_direct_unnamed_token(node, "in") &&
+ !kotlin_direct_unnamed_token(node, "!in")) ||
+ kotlin_direct_unnamed_token(node, "is")) {
+ return;
+ }
+ op_method = "contains";
+ } else if (strcmp(kind, "index_expression") == 0 || strcmp(kind, "indexing_expression") == 0) {
+ if (ts_node_named_child_count(node) < 1 || kotlin_index_is_write_lhs(node))
+ return;
+ op_method = "get";
+ } else {
+ return;
+ }
+ push_kotlin_operator_call(ctx, node, op_method, enclosing_func_qn);
+}
+
// Kotlin convention-desugared calls that the call walk never sees as
// call_expressions: `val (a,b) = e` -> e.component1()/e.component2(); and
// `for (x in e)` -> e.iterator()/hasNext()/next(). Record textual calls to those
@@ -1903,41 +2319,131 @@ static void kt_push_implicit_call(CBMExtractCtx *ctx, TSNode node, const char *c
call.callee_name = callee;
call.enclosing_func_qn = enclosing_func_qn;
call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
+ call.site_start_byte = ts_node_start_byte(node);
+ call.site_end_byte = ts_node_end_byte(node);
+ call.requires_lsp_resolution = true;
cbm_calls_push(&ctx->result->calls, ctx->arena, call);
}
-// C++ overloaded binary operator `a + b`: the operator method (`operator+`) is
-// invoked implicitly, so the call walk never sees a call node. Synthesize a
-// textual call to the bare operator name so the c-LSP's lsp_operator resolution
-// (which keys the same `operator<tok>` member on the lhs type) has a call site to
-// join. The operator token is the first unnamed child, mirroring c_lsp.c's binary
-// handling. Builtin-operand expressions (int + int) synthesize an `operator+`
-// callee too, but no such member exists so the call resolves to nothing and is
-// dropped — no spurious edge.
+static void push_cpp_semantic_call_candidate(CBMExtractCtx *ctx, TSNode node,
+ const char *callee_name,
+ const char *enclosing_func_qn) {
+ if (!callee_name || !callee_name[0] || !enclosing_func_qn) {
+ return;
+ }
+ CBMCall call = {0};
+ call.callee_name = callee_name;
+ call.enclosing_func_qn = enclosing_func_qn;
+ call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
+ call.site_start_byte = ts_node_start_byte(node);
+ call.site_end_byte = ts_node_end_byte(node);
+ call.requires_lsp_resolution = true;
+ cbm_calls_push(&ctx->result->calls, ctx->arena, call);
+}
+
+static const char *cpp_operator_token(CBMExtractCtx *ctx, TSNode node) {
+ for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child)) {
+ const char *token = cbm_node_text(ctx->arena, child, ctx->source);
+ if (token && token[0]) {
+ return token;
+ }
+ }
+ }
+ return NULL;
+}
+
+static bool cpp_is_compound_assignment_token(const char *token) {
+ return token &&
+ (strcmp(token, "+=") == 0 || strcmp(token, "-=") == 0 || strcmp(token, "*=") == 0 ||
+ strcmp(token, "/=") == 0 || strcmp(token, "%=") == 0 || strcmp(token, "<<=") == 0 ||
+ strcmp(token, ">>=") == 0 || strcmp(token, "&=") == 0 || strcmp(token, "|=") == 0 ||
+ strcmp(token, "^=") == 0);
+}
+
+// C++ operators represented by expression nodes are real invocations only when
+// overload resolution finds a concrete function. Emit exact-occurrence raw
+// candidates here; requires_lsp_resolution keeps primitive/pointer syntax from
+// falling through to textual registry lookup and fabricating CALLS edges.
static void extract_cpp_operator_call(CBMExtractCtx *ctx, TSNode node, const char *kind,
const char *enclosing_func_qn) {
- if (strcmp(kind, "binary_expression") != 0) {
+ if (strcmp(kind, "subscript_expression") == 0) {
+ TSNode receiver = ts_node_child_by_field_name(node, TS_FIELD("argument"));
+ TSNode index = ts_node_child_by_field_name(node, TS_FIELD("index"));
+ if (ts_node_is_null(receiver) && ts_node_named_child_count(node) > 0) {
+ receiver = ts_node_named_child(node, 0);
+ }
+ if (ts_node_is_null(index) && ts_node_named_child_count(node) > 1) {
+ index = ts_node_named_child(node, 1);
+ }
+ if (!ts_node_is_null(receiver) && !ts_node_is_null(index)) {
+ push_cpp_semantic_call_candidate(ctx, node, "operator[]", enclosing_func_qn);
+ }
return;
}
- TSNode lhs = ts_node_child_by_field_name(node, TS_FIELD("left"));
- TSNode rhs = ts_node_child_by_field_name(node, TS_FIELD("right"));
- if (ts_node_is_null(lhs) || ts_node_is_null(rhs)) {
+
+ if (strcmp(kind, "unary_expression") == 0 || strcmp(kind, "pointer_expression") == 0 ||
+ strcmp(kind, "update_expression") == 0) {
+ TSNode operand = ts_node_child_by_field_name(node, TS_FIELD("argument"));
+ if (ts_node_is_null(operand)) {
+ operand = ts_node_child_by_field_name(node, TS_FIELD("operand"));
+ }
+ if (ts_node_is_null(operand) && ts_node_named_child_count(node) > 0) {
+ operand = ts_node_named_child(node, 0);
+ }
+ const char *token = cpp_operator_token(ctx, node);
+ bool unary_token = token && (strcmp(token, "-") == 0 || strcmp(token, "*") == 0 ||
+ strcmp(token, "!") == 0);
+ bool update_token = token && (strcmp(token, "++") == 0 || strcmp(token, "--") == 0);
+ /* `this` has the built-in pointer type in C++. Consequently `*this` is
+ * always pointer dereference and can never dispatch an overloaded
+ * operator*. Do not manufacture a semantic candidate for it. */
+ if (!ts_node_is_null(operand) && token && strcmp(token, "*") == 0 &&
+ strcmp(ts_node_type(operand), "this") == 0) {
+ return;
+ }
+ if (!ts_node_is_null(operand) &&
+ ((strcmp(kind, "update_expression") == 0 && update_token) ||
+ (strcmp(kind, "update_expression") != 0 && unary_token))) {
+ push_cpp_semantic_call_candidate(
+ ctx, node, cbm_arena_sprintf(ctx->arena, "operator%s", token), enclosing_func_qn);
+ }
return;
}
- for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
- TSNode child = ts_node_child(node, i);
- if (ts_node_is_named(child)) {
- continue;
+
+ if (strcmp(kind, "field_expression") == 0) {
+ TSNode receiver = ts_node_child_by_field_name(node, TS_FIELD("argument"));
+ TSNode member = ts_node_child_by_field_name(node, TS_FIELD("field"));
+ const char *token = cpp_operator_token(ctx, node);
+ if (!ts_node_is_null(receiver) && !ts_node_is_null(member) && token &&
+ strcmp(token, "->") == 0) {
+ push_cpp_semantic_call_candidate(ctx, node, "operator->", enclosing_func_qn);
}
- char *op = cbm_node_text(ctx->arena, child, ctx->source);
- if (op && op[0]) {
- CBMCall call = {0};
- call.callee_name = cbm_arena_sprintf(ctx->arena, "operator%s", op);
- call.enclosing_func_qn = enclosing_func_qn;
- call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
- cbm_calls_push(&ctx->result->calls, ctx->arena, call);
+ return;
+ }
+
+ if (strcmp(kind, "assignment_expression") == 0) {
+ TSNode lhs = ts_node_child_by_field_name(node, TS_FIELD("left"));
+ TSNode rhs = ts_node_child_by_field_name(node, TS_FIELD("right"));
+ const char *token = cpp_operator_token(ctx, node);
+ if (!ts_node_is_null(lhs) && !ts_node_is_null(rhs) &&
+ cpp_is_compound_assignment_token(token)) {
+ push_cpp_semantic_call_candidate(
+ ctx, node, cbm_arena_sprintf(ctx->arena, "operator%s", token), enclosing_func_qn);
}
- break;
+ return;
+ }
+
+ if (strcmp(kind, "binary_expression") != 0) {
+ return;
+ }
+ TSNode lhs = ts_node_child_by_field_name(node, TS_FIELD("left"));
+ TSNode rhs = ts_node_child_by_field_name(node, TS_FIELD("right"));
+ const char *token = cpp_operator_token(ctx, node);
+ if (!ts_node_is_null(lhs) && !ts_node_is_null(rhs) && token) {
+ push_cpp_semantic_call_candidate(
+ ctx, node, cbm_arena_sprintf(ctx->arena, "operator%s", token), enclosing_func_qn);
}
}
@@ -1949,8 +2455,9 @@ static void extract_cpp_operator_call(CBMExtractCtx *ctx, TSNode node, const cha
// so the lsp_{destructor,copy_constructor,conversion} resolution binds.
//
// - destructor: the callee QN embeds the type (`T.~T`), which is not textually
-// available from `delete p`, so it joins via the reason gate — c_lsp stashes
-// the operand text in `reason` and the synthesized callee is that same text.
+// available from `delete p`. Use a non-textual destructor marker; the exact
+// occurrence is joined only to an LSP-proved, materialized destructor and is
+// rewritten to `~T` when the same-file pass can prove it.
// - copy constructor: the callee short-name is the constructed type (`T`),
// which IS textually present as the declaration's type — join by short-name.
// - conversion: the callee short-name is the type-independent `operator bool`.
@@ -1966,7 +2473,7 @@ static void extract_cpp_implicit_calls(CBMExtractCtx *ctx, TSNode node, const ch
operand = ts_node_named_child(node, 0);
}
if (!ts_node_is_null(operand)) {
- callee = cbm_node_text(ctx->arena, operand, ctx->source);
+ callee = "~";
}
} else if (strcmp(kind, "if_statement") == 0 || strcmp(kind, "while_statement") == 0 ||
strcmp(kind, "do_statement") == 0) {
@@ -2000,11 +2507,7 @@ static void extract_cpp_implicit_calls(CBMExtractCtx *ctx, TSNode node, const ch
}
}
if (callee && callee[0]) {
- CBMCall call = {0};
- call.callee_name = callee;
- call.enclosing_func_qn = enclosing_func_qn;
- call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
- cbm_calls_push(&ctx->result->calls, ctx->arena, call);
+ push_cpp_semantic_call_candidate(ctx, node, callee, enclosing_func_qn);
}
}
@@ -2038,34 +2541,21 @@ static void extract_kotlin_desugared_calls(CBMExtractCtx *ctx, TSNode node, cons
}
}
-// Java method reference `Lhs::name` (e.g. `String::length`, `Foo::new`). The
-// call walk only visits call_expression-like nodes, so a method_reference never
-// becomes a call and the LSP's lsp_method_ref resolution has no call site to
-// attach to. Record a textual call to the referenced method's bare name (the
-// constructor ref `Lhs::new` uses the unnamed `new` token); the LSP join then
-// matches on the bare name. The referenced method IS invoked indirectly, so
-// this is an accurate call edge (mirrors java_lsp.c resolve_method_reference).
-static void extract_java_method_reference(CBMExtractCtx *ctx, TSNode node, const char *kind,
- const char *enclosing_func_qn) {
- if (strcmp(kind, "method_reference") != 0) {
- return;
- }
- uint32_t nc = ts_node_named_child_count(node);
- if (nc < 1) {
- return;
+static bool php_is_first_class_callable(TSNode node) {
+ TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
+ if (ts_node_is_null(args)) {
+ return false;
}
- char *mname = NULL;
- if (nc >= 2) {
- mname = cbm_node_text(ctx->arena, ts_node_named_child(node, nc - 1), ctx->source);
+ if (strcmp(ts_node_type(args), "variadic_placeholder") == 0) {
+ return true;
}
- if (!mname || !mname[0]) {
- mname = "new"; // constructor reference `Lhs::new` — `new` is unnamed
+ uint32_t count = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < count; i++) {
+ if (strcmp(ts_node_type(ts_node_named_child(args, i)), "variadic_placeholder") == 0) {
+ return true;
+ }
}
- CBMCall call = {0};
- call.callee_name = mname;
- call.enclosing_func_qn = enclosing_func_qn;
- call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
- cbm_calls_push(&ctx->result->calls, ctx->arena, call);
+ return false;
}
// ObjectScript: resolve `var.Method(...)` / `..Property.Method(...)` instance
@@ -2134,74 +2624,615 @@ static char *resolve_objectscript_instance_call(CBMArena *a, TSNode node, const
return NULL;
}
-void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state) {
- if (!spec->call_node_types || !spec->call_node_types[0]) {
- return;
+static bool is_objectscript_language(CBMLanguage language) {
+ return language == CBM_LANG_OBJECTSCRIPT_UDL || language == CBM_LANG_OBJECTSCRIPT_ROUTINE;
+}
+
+// Preserve ObjectScript's grammar/type-map resolution while feeding the
+// invocation descriptor used by the exact callee-usage suppression pass.
+static const char *resolve_objectscript_callee(CBMExtractCtx *ctx, TSNode node, WalkState *state,
+ const char *callee) {
+ if (!is_objectscript_language(ctx->language)) {
+ return callee;
}
- if (cbm_kind_in_set(node, spec->call_node_types)) {
- char *callee = extract_callee_name(ctx->arena, node, ctx->source, ctx->language);
-
- // ObjectScript: var.Method() / ..Property.Method() instance dispatch.
- if (!callee &&
- (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
- ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) &&
- strcmp(ts_node_type(node), "method_call") == 0) {
- callee = resolve_objectscript_instance_call(ctx->arena, node, ctx->source,
- &state->os_type_map);
- }
-
- // ObjectScript: ..Method() oref self-call resolves against the enclosing class.
- if (!callee &&
- (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
- ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) &&
- strcmp(ts_node_type(node), "relative_dot_method") == 0 && state->enclosing_class_qn &&
- state->enclosing_class_qn[0]) {
- TSNode oref = cbm_find_child_by_kind(node, "oref_method");
- if (!ts_node_is_null(oref)) {
- TSNode mname_node = cbm_find_child_by_kind(oref, "method_name");
- if (!ts_node_is_null(mname_node)) {
- TSNode ident = ts_node_named_child_count(mname_node) > 0
- ? ts_node_named_child(mname_node, 0)
- : (TSNode){0};
- if (!ts_node_is_null(ident)) {
- char *mname = cbm_node_text(ctx->arena, ident, ctx->source);
- if (mname && mname[0]) {
- callee = cbm_arena_sprintf(ctx->arena, "%s.%s",
- state->enclosing_class_qn, mname);
- }
- }
- }
+ const char *kind = ts_node_type(node);
+ if ((!callee || !callee[0]) && strcmp(kind, "method_call") == 0) {
+ callee =
+ resolve_objectscript_instance_call(ctx->arena, node, ctx->source, &state->os_type_map);
+ }
+
+ if ((!callee || !callee[0]) && strcmp(kind, "relative_dot_method") == 0 &&
+ state->enclosing_class_qn && state->enclosing_class_qn[0]) {
+ TSNode oref = cbm_find_child_by_kind(node, "oref_method");
+ TSNode method_name =
+ ts_node_is_null(oref) ? (TSNode){0} : cbm_find_child_by_kind(oref, "method_name");
+ TSNode identifier =
+ !ts_node_is_null(method_name) && ts_node_named_child_count(method_name) > 0
+ ? ts_node_named_child(method_name, 0)
+ : (TSNode){0};
+ if (!ts_node_is_null(identifier)) {
+ char *method = cbm_node_text(ctx->arena, identifier, ctx->source);
+ if (method && method[0]) {
+ callee = cbm_arena_sprintf(ctx->arena, "%s.%s", state->enclosing_class_qn, method);
}
}
+ }
- // ObjectScript: expand a $$$Macro callee via the macro table.
- if (callee && callee[0] == '$' && callee[1] == '$' && callee[2] == '$' &&
- ctx->macro_table) {
- const char *macro_name = callee + 3;
- const CBMMacroEntry *entry = cbm_macro_table_find(ctx->macro_table, macro_name);
- if (entry) {
- if (entry->resolved_callee) {
- callee = cbm_arena_strdup(ctx->arena, entry->resolved_callee);
- } else if (entry->expansion) {
- callee = cbm_macro_extract_callee(ctx->arena, entry->expansion);
- } else {
- callee = NULL;
- }
+ if (callee && strncmp(callee, "$$$", 3) == 0 && ctx->macro_table) {
+ const CBMMacroEntry *entry = cbm_macro_table_find(ctx->macro_table, callee + 3);
+ if (entry) {
+ if (entry->resolved_callee) {
+ callee = cbm_arena_strdup(ctx->arena, entry->resolved_callee);
+ } else if (entry->expansion) {
+ callee = cbm_macro_extract_callee(ctx->arena, entry->expansion);
+ } else {
+ callee = NULL;
}
}
+ }
+ return callee;
+}
+
+static TSNode objectscript_call_args(TSNode node) {
+ TSNode oref = cbm_find_child_by_kind(node, "oref_method");
+ if (!ts_node_is_null(oref)) {
+ TSNode args = cbm_find_child_by_kind(oref, "method_args");
+ if (!ts_node_is_null(args)) {
+ return args;
+ }
+ }
+
+ TSNode args = cbm_find_child_by_kind(node, "method_args");
+ if (!ts_node_is_null(args)) {
+ return args;
+ }
+
+ /* A macro's optional arguments live below macro_function rather than as a
+ * direct child of macro. Keep them as call arguments/data-flow inputs; the
+ * macro name is an unnamed token and is handled separately. */
+ TSNode macro_function = cbm_find_child_by_kind(node, "macro_function");
+ return ts_node_is_null(macro_function) ? (TSNode){0}
+ : cbm_find_child_by_kind(macro_function, "method_args");
+}
+
+static bool node_has_token(TSNode node, const char *token) {
+ uint32_t count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ if (strcmp(ts_node_type(ts_node_child(node, i)), token) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+static bool is_callable_reference_value(CBMLanguage language, TSNode node) {
+ const char *kind = ts_node_type(node);
+ if (language == CBM_LANG_JAVA && strcmp(kind, "method_reference") == 0) {
+ return true;
+ }
+ if (language == CBM_LANG_KOTLIN && strcmp(kind, "callable_reference") == 0) {
+ // `Type::class` shares the callable-reference grammar node but denotes
+ // a class literal, not a reference to executable code.
+ return !node_has_token(node, "class");
+ }
+ return language == CBM_LANG_PHP && php_is_first_class_callable(node);
+}
+
+static TSNode first_present_field(TSNode node, const char *const *fields) {
+ for (const char *const *field = fields; *field; field++) {
+ TSNode child = ts_node_child_by_field_name(node, *field, (uint32_t)strlen(*field));
+ if (!ts_node_is_null(child)) {
+ return child;
+ }
+ }
+ return (TSNode){0};
+}
+
+static bool is_constructor_kind(const char *kind) {
+ return strcmp(kind, "new_expression") == 0 || strcmp(kind, "object_creation_expression") == 0 ||
+ strcmp(kind, "instance_expression") == 0 || strcmp(kind, "constructor_expression") == 0;
+}
+
+static bool is_dynamic_callee_expr(const CBMExtractCtx *ctx, TSNode expr) {
+ if (ts_node_is_null(expr)) {
+ return false;
+ }
+ const char *kind = ts_node_type(expr);
+ if (strstr(kind, "subscript") || strstr(kind, "element_access") ||
+ strstr(kind, "index_expression") || strstr(kind, "computed")) {
+ return true;
+ }
+
+ // JS/TS use member_expression for both `obj.method` and `obj[key]`.
+ // A bracketed property is an evaluated value, not a static terminal name.
+ static const char *const terminal_fields[] = {"property", "field", "attribute",
+ "name", "method", NULL};
+ TSNode terminal = first_present_field(expr, terminal_fields);
+ if (!ts_node_is_null(terminal)) {
+ uint32_t start = ts_node_start_byte(terminal);
+ uint32_t expr_start = ts_node_start_byte(expr);
+ while (start > expr_start && isspace((unsigned char)ctx->source[start - 1])) {
+ start--;
+ }
+ if (start > expr_start && ctx->source[start - 1] == '[') {
+ return true;
+ }
+ }
+ return false;
+}
+
+static TSNode primary_callee_expr(TSNode node) {
+ const char *kind = ts_node_type(node);
+ if (is_constructor_kind(kind)) {
+ static const char *const constructor_fields[] = {"constructor", "type", "name", NULL};
+ TSNode constructor = first_present_field(node, constructor_fields);
+ if (!ts_node_is_null(constructor)) {
+ return constructor;
+ }
+ }
+
+ static const char *const callee_fields[] = {"function", "name", "method", "target",
+ "macro", "subroutine", NULL};
+ TSNode callee = first_present_field(node, callee_fields);
+ if (!ts_node_is_null(callee)) {
+ return callee;
+ }
+ if (ts_node_named_child_count(node) > 0) {
+ return ts_node_named_child(node, 0);
+ }
+ return (TSNode){0};
+}
+
+static TSNode terminal_callee_leaf(const CBMExtractCtx *ctx, TSNode expr) {
+ if (ts_node_is_null(expr) || is_dynamic_callee_expr(ctx, expr)) {
+ return (TSNode){0};
+ }
+
+ static const char *const terminal_fields[] = {"property", "field", "attribute",
+ "method", "name", NULL};
+ TSNode terminal = first_present_field(expr, terminal_fields);
+ if (!ts_node_is_null(terminal)) {
+ if (is_dynamic_callee_expr(ctx, expr)) {
+ return (TSNode){0};
+ }
+ return terminal_callee_leaf(ctx, terminal);
+ }
+
+ const char *kind = ts_node_type(expr);
+ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ||
+ strcmp(kind, "type_identifier") == 0 || strcmp(kind, "field_identifier") == 0 ||
+ strcmp(kind, "property_identifier") == 0 || strcmp(kind, "name") == 0 ||
+ strcmp(kind, "variable_name") == 0 || strcmp(kind, "attribute") == 0 ||
+ strcmp(kind, "symbol") == 0 || strcmp(kind, "sym_lit") == 0 ||
+ strcmp(kind, "user_symbol") == 0) {
+ return expr;
+ }
+
+ // Known wrappers keep their static terminal in one of their named children.
+ // Prefer the last child for qualified/member/navigation forms and the first
+ // for transparent parentheses and generic wrappers whose name field was not
+ // exposed by the grammar.
+ uint32_t count = ts_node_named_child_count(expr);
+ if (count == 0) {
+ return (TSNode){0};
+ }
+ bool terminal_is_last = strstr(kind, "qualified") || strstr(kind, "scoped") ||
+ strstr(kind, "member") || strstr(kind, "selector") ||
+ strstr(kind, "navigation") || strstr(kind, "field_expression");
+ TSNode child = ts_node_named_child(expr, terminal_is_last ? count - 1 : 0);
+ return terminal_callee_leaf(ctx, child);
+}
+
+typedef struct {
+ const char *name;
+ TSNode expr;
+ TSNode leaf;
+} CBMPrimaryCalleeSelection;
+
+static bool node_kind_is_one_of(TSNode node, const char *const *kinds) {
+ const char *kind = ts_node_type(node);
+ for (const char *const *candidate = kinds; *candidate; candidate++) {
+ if (strcmp(kind, *candidate) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static TSNode first_named_descendant_of_kind(TSNode node, const char *const *kinds,
+ int remaining_depth) {
+ if (ts_node_is_null(node) || remaining_depth < 0) {
+ return (TSNode){0};
+ }
+ if (node_kind_is_one_of(node, kinds)) {
+ return node;
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode found = first_named_descendant_of_kind(ts_node_named_child(node, i), kinds,
+ remaining_depth - 1);
+ if (!ts_node_is_null(found)) {
+ return found;
+ }
+ }
+ return (TSNode){0};
+}
+
+static TSNode last_named_descendant_of_kind(TSNode node, const char *const *kinds,
+ int remaining_depth) {
+ if (ts_node_is_null(node) || remaining_depth < 0) {
+ return (TSNode){0};
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = count; i > 0; i--) {
+ TSNode found = last_named_descendant_of_kind(ts_node_named_child(node, i - 1), kinds,
+ remaining_depth - 1);
+ if (!ts_node_is_null(found)) {
+ return found;
+ }
+ }
+ return node_kind_is_one_of(node, kinds) ? node : (TSNode){0};
+}
+
+/* ObjectScript call nodes do not expose generic `function`/`name` fields. Keep
+ * the descriptor on the grammar-proven callee occurrence instead of falling
+ * back to the first named child (which is a receiver for method_call and an
+ * argument container for macro). The macro spelling itself is unnamed, so it
+ * intentionally has no named callee occurrence to consume. */
+static TSNode objectscript_callee_expr(TSNode node) {
+ const char *kind = ts_node_type(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) {
+ 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 (TSNode){0};
+}
+
+static TSNode objectscript_callee_leaf(TSNode expr) {
+ if (ts_node_is_null(expr)) {
+ return (TSNode){0};
+ }
+ const char *kind = ts_node_type(expr);
+ if (strcmp(kind, "method_name") == 0 && ts_node_named_child_count(expr) > 0) {
+ return ts_node_named_child(expr, 0);
+ }
+ if (strcmp(kind, "line_ref") == 0) {
+ static const char *const identifier_kinds[] = {"objectscript_identifier",
+ "objectscript_identifier_special", NULL};
+ return first_named_descendant_of_kind(expr, identifier_kinds, 4);
+ }
+ return (TSNode){0};
+}
+
+static TSNode language_specific_callee_expr(CBMLanguage language, TSNode node) {
+ const char *kind = ts_node_type(node);
+
+ if (is_objectscript_language(language)) {
+ return objectscript_callee_expr(node);
+ }
+
+ if (language == CBM_LANG_SCALA && strcmp(kind, "infix_expression") == 0) {
+ /* Scala exposes `lhs merge rhs` as left/operator/right fields. Consume
+ * only the operator occurrence; both operands remain ordinary usages. */
+ return ts_node_child_by_field_name(node, TS_FIELD("operator"));
+ }
+
+ if (language == CBM_LANG_DART) {
+ if (strcmp(kind, "selector") == 0) {
+ TSNode previous = ts_node_prev_named_sibling(node);
+ return !ts_node_is_null(previous) && strcmp(ts_node_type(previous), "identifier") == 0
+ ? previous
+ : (TSNode){0};
+ }
+ if (strcmp(kind, "new_expression") == 0) {
+ return primary_callee_expr(node);
+ }
+ }
+
+ if (language == CBM_LANG_VHDL && strcmp(kind, "parenthesis_group") == 0) {
+ TSNode previous = ts_node_prev_named_sibling(node);
+ if (!ts_node_is_null(previous)) {
+ const char *previous_kind = ts_node_type(previous);
+ if (strcmp(previous_kind, "library_function") == 0 ||
+ strcmp(previous_kind, "identifier") == 0 || strcmp(previous_kind, "name") == 0 ||
+ strcmp(previous_kind, "simple_name") == 0) {
+ return previous;
+ }
+ }
+ return (TSNode){0};
+ }
+
+ if (language == CBM_LANG_CSS && strcmp(kind, "call_expression") == 0) {
+ return cbm_find_child_by_kind(node, "function_name");
+ }
+
+ if (language == CBM_LANG_NASM) {
+ if (strcmp(kind, "call_syntax_expression") == 0) {
+ return ts_node_child_by_field_name(node, TS_FIELD("base"));
+ }
+ if (strcmp(kind, "actual_instruction") == 0) {
+ TSNode operands = ts_node_child_by_field_name(node, TS_FIELD("operands"));
+ return !ts_node_is_null(operands) && ts_node_named_child_count(operands) > 0
+ ? ts_node_named_child(operands, 0)
+ : (TSNode){0};
+ }
+ }
+
+ if (language == CBM_LANG_LLVM_IR) {
+ return ts_node_child_by_field_name(node, TS_FIELD("callee"));
+ }
+
+ if (language == CBM_LANG_AGDA && strcmp(kind, "expr") == 0) {
+ return agda_application_head_atom(node);
+ }
+
+ if (language == CBM_LANG_ADA &&
+ (strcmp(kind, "procedure_call_statement") == 0 || strcmp(kind, "function_call") == 0)) {
+ TSNode name = ts_node_child_by_field_name(node, TS_FIELD("name"));
+ if (!ts_node_is_null(name)) {
+ return name;
+ }
+ if (ts_node_named_child_count(node) > 0) {
+ TSNode head = ts_node_named_child(node, 0);
+ const char *head_kind = ts_node_type(head);
+ if (strcmp(head_kind, "name") == 0 || strcmp(head_kind, "identifier") == 0) {
+ return head;
+ }
+ }
+ return (TSNode){0};
+ }
+
+ if (language == CBM_LANG_MAKEFILE) {
+ // `shell` is a literal keyword minted by the extractor, not an AST
+ // identifier. It must not consume the command/argument child.
+ if (strcmp(kind, "shell_function") == 0) {
+ return (TSNode){0};
+ }
+ if (strcmp(kind, "function_call") == 0) {
+ TSNode function = ts_node_child_by_field_name(node, TS_FIELD("function"));
+ if (ts_node_is_null(function) && ts_node_named_child_count(node) > 0) {
+ function = ts_node_named_child(node, 0);
+ }
+ return function;
+ }
+ }
+
+ // A Just dependency is build-graph metadata. It deliberately emits the
+ // legacy raw call while retaining the recipe name as an ordinary USAGE.
+ if (language == CBM_LANG_JUST && strcmp(kind, "dependency") == 0) {
+ return (TSNode){0};
+ }
+
+ // Puppet `include` is another synthetic literal callee; its named child is
+ // the included class and must remain a value/reference occurrence.
+ if (language == CBM_LANG_PUPPET && strcmp(kind, "include_statement") == 0) {
+ return (TSNode){0};
+ }
+
+ return primary_callee_expr(node);
+}
+
+static TSNode language_specific_callee_leaf(CBMLanguage language, TSNode expr,
+ const CBMExtractCtx *ctx) {
+ if (ts_node_is_null(expr)) {
+ return (TSNode){0};
+ }
+
+ if (language == CBM_LANG_LLVM_IR) {
+ static const char *const llvm_leaf_kinds[] = {"global_var", "local_var", NULL};
+ return first_named_descendant_of_kind(expr, llvm_leaf_kinds, 8);
+ }
+ if (is_objectscript_language(language)) {
+ return objectscript_callee_leaf(expr);
+ }
+ if (language == CBM_LANG_CSS && strcmp(ts_node_type(expr), "function_name") == 0) {
+ return expr;
+ }
+ if (language == CBM_LANG_NASM) {
+ static const char *const nasm_leaf_kinds[] = {"word", NULL};
+ return first_named_descendant_of_kind(expr, nasm_leaf_kinds, 8);
+ }
+ if (language == CBM_LANG_AGDA) {
+ return agda_head_qid(expr);
+ }
+ if (language == CBM_LANG_ELM) {
+ static const char *const elm_leaf_kinds[] = {"lower_case_identifier", NULL};
+ return first_named_descendant_of_kind(expr, elm_leaf_kinds, 8);
+ }
+ if (language == CBM_LANG_PURESCRIPT) {
+ static const char *const purescript_leaf_kinds[] = {"variable", NULL};
+ return first_named_descendant_of_kind(expr, purescript_leaf_kinds, 8);
+ }
+ if (language == CBM_LANG_NICKEL) {
+ static const char *const nickel_leaf_kinds[] = {"ident", NULL};
+ return first_named_descendant_of_kind(expr, nickel_leaf_kinds, 8);
+ }
+ if (language == CBM_LANG_ADA) {
+ static const char *const ada_leaf_kinds[] = {"identifier", "simple_identifier", NULL};
+ TSNode leaf = last_named_descendant_of_kind(expr, ada_leaf_kinds, 8);
+ if (!ts_node_is_null(leaf)) {
+ return leaf;
+ }
+ }
+ if (language == CBM_LANG_VHDL) {
+ static const char *const vhdl_leaf_kinds[] = {"identifier", "simple_identifier", NULL};
+ TSNode leaf = last_named_descendant_of_kind(expr, vhdl_leaf_kinds, 8);
+ if (!ts_node_is_null(leaf)) {
+ return leaf;
+ }
+ }
+ return terminal_callee_leaf(ctx, expr);
+}
+
+// Produce the textual callee and the AST occurrence from one operation. The
+// generic fallback retains the former field/terminal behavior, while grammars
+// whose extractor uses a sibling, a special field, or a synthetic literal are
+// selected explicitly above. This prevents the descriptor from independently
+// guessing that the first named child is the callee (often an argument).
+static CBMPrimaryCalleeSelection select_primary_callee(CBMExtractCtx *ctx, TSNode node,
+ WalkState *state) {
+ CBMPrimaryCalleeSelection selection = {0};
+ selection.name = extract_callee_name(ctx->arena, node, ctx->source, ctx->language);
+ selection.name = resolve_objectscript_callee(ctx, node, state, selection.name);
+ if (!selection.name || !selection.name[0]) {
+ return selection;
+ }
+
+ const char *site_kind = ts_node_type(node);
+ bool scala_named_infix =
+ ctx->language == CBM_LANG_SCALA && strcmp(site_kind, "infix_expression") == 0;
+ if (!scala_named_infix && (strstr(site_kind, "binary") || strstr(site_kind, "infix"))) {
+ return selection;
+ }
+
+ selection.expr = language_specific_callee_expr(ctx->language, node);
+ if (is_dynamic_callee_expr(ctx, selection.expr)) {
+ selection.expr = (TSNode){0};
+ return selection;
+ }
+ selection.leaf = language_specific_callee_leaf(ctx->language, selection.expr, ctx);
+ return selection;
+}
+
+static bool primary_callee_name_is_allowed(const CBMExtractCtx *ctx,
+ const CBMPrimaryCalleeSelection *callee) {
+ if (!callee->name || !callee->name[0]) {
+ return false;
+ }
+ if (!cbm_is_keyword(callee->name, ctx->language) ||
+ cbm_is_resolvable_builtin(callee->name, ctx->language)) {
+ return true;
+ }
+ /* CSS function names occupy a grammar-proven callable role. Generic keyword
+ * vocabulary includes `var`, but that must not erase `var(...)`. */
+ return ctx->language == CBM_LANG_CSS && !ts_node_is_null(callee->expr) &&
+ strcmp(ts_node_type(callee->expr), "function_name") == 0;
+}
+
+static bool php_callable_reference_has_dynamic_member_name(TSNode call, TSNode callee_expr) {
+ if (ts_node_is_null(callee_expr)) {
+ return false;
+ }
+
+ const char *call_kind = ts_node_type(call);
+ if (strcmp(call_kind, "member_call_expression") != 0 &&
+ strcmp(call_kind, "nullsafe_member_call_expression") != 0 &&
+ strcmp(call_kind, "scoped_call_expression") != 0) {
+ return false;
+ }
+
+ const char *callee_kind = ts_node_type(callee_expr);
+ return strcmp(callee_kind, "variable_name") == 0 ||
+ strcmp(callee_kind, "dynamic_variable_name") == 0;
+}
+
+/* A callable-reference token inside a branch expression names a possible value,
+ * not one statically selected value at that occurrence. Do not consume its leaf
+ * as explicit CALL_REFERENCE syntax; the usage walker will retain each named
+ * alternative as ordinary USAGE. */
+static bool callable_reference_is_branch_alternative(TSNode reference) {
+ for (TSNode parent = ts_node_parent(reference); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "ternary_expression") == 0 ||
+ strcmp(kind, "conditional_expression") == 0 || strcmp(kind, "if_expression") == 0) {
+ return true;
+ }
+ if (strcmp(kind, "arguments") == 0 || strcmp(kind, "argument_list") == 0 ||
+ strcmp(kind, "assignment_expression") == 0 || strcmp(kind, "assignment") == 0 ||
+ strcmp(kind, "variable_declarator") == 0) {
+ return false;
+ }
+ }
+ return false;
+}
+
+static CBMInvocationDescriptor describe_callable_reference(CBMExtractCtx *ctx, TSNode node) {
+ CBMInvocationDescriptor descriptor = {0};
+ descriptor.kind = CBM_INVOCATION_CALLABLE_REFERENCE;
+ descriptor.site = node;
+
+ if (callable_reference_is_branch_alternative(node)) {
+ return descriptor;
+ }
+
+ uint32_t count = ts_node_named_child_count(node);
+ if (ctx->language == CBM_LANG_JAVA && count > 0) {
+ // In `Type::new`, `new` is an unnamed token, so the referenced
+ // constructor is represented by the left-hand type. For ordinary
+ // method references, the final named child is the referenced method.
+ descriptor.callee_expr =
+ ts_node_named_child(node, node_has_token(node, "new") ? 0 : count - 1);
+ } else if (ctx->language == CBM_LANG_KOTLIN && count > 0) {
+ descriptor.callee_expr = ts_node_named_child(node, count - 1);
+ } else if (ctx->language == CBM_LANG_PHP) {
+ descriptor.callee_expr = primary_callee_expr(node);
+ /* `$obj->$method(...)` and its nullsafe/static equivalents evaluate the
+ * member-name variable; the syntax alone does not prove a callable
+ * target. Leave the terminal unconsumed so the usage pass records it as
+ * an ordinary value instead of a CALL_REFERENCE. A bare typed
+ * `$handler(...)` remains eligible for PHP-LSP `__invoke` resolution. */
+ if (php_callable_reference_has_dynamic_member_name(node, descriptor.callee_expr)) {
+ descriptor.callee_expr = (TSNode){0};
+ return descriptor;
+ }
+ }
+
+ if (is_dynamic_callee_expr(ctx, descriptor.callee_expr)) {
+ descriptor.callee_expr = (TSNode){0};
+ return descriptor;
+ }
+ descriptor.callee_leaf = terminal_callee_leaf(ctx, descriptor.callee_expr);
+ TSNode name_node =
+ !ts_node_is_null(descriptor.callee_leaf) ? descriptor.callee_leaf : descriptor.callee_expr;
+ if (!ts_node_is_null(name_node)) {
+ descriptor.callee_name = cbm_node_text(ctx->arena, name_node, ctx->source);
+ }
+ return descriptor;
+}
+
+static CBMInvocationDescriptor describe_emitted_primary_call(
+ TSNode node, const CBMPrimaryCalleeSelection *callee) {
+ CBMInvocationDescriptor descriptor = {0};
+ descriptor.kind = CBM_INVOCATION_PRIMARY;
+ descriptor.site = node;
+ descriptor.callee_name = callee->name;
+ descriptor.raw_call_emitted = true;
+ descriptor.callee_expr = callee->expr;
+ descriptor.callee_leaf = callee->leaf;
+ return descriptor;
+}
+
+CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
+ WalkState *state) {
+ CBMInvocationDescriptor invocation = {0};
+ bool callable_reference = is_callable_reference_value(ctx->language, node);
+ if (callable_reference) {
+ invocation = describe_callable_reference(ctx, node);
+ }
+
+ if (!callable_reference && spec->call_node_types && spec->call_node_types[0] &&
+ cbm_kind_in_set(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.
- if (callee && callee[0] &&
- (!cbm_is_keyword(callee, ctx->language) ||
- cbm_is_resolvable_builtin(callee, ctx->language))) {
+ if (primary_callee_name_is_allowed(ctx, &callee)) {
CBMCall call = {0};
- call.callee_name = callee;
+ call.callee_name = callee.name;
call.enclosing_func_qn = state->enclosing_func_qn;
call.loop_depth = state->loop_depth; // enclosing loop nesting at this call
call.branch_depth = state->branch_depth; // enclosing branch nesting at this call
call.start_line = (int)ts_node_start_point(node).row + TS_LINE_OFFSET;
+ call.site_start_byte = ts_node_start_byte(node);
+ call.site_end_byte = ts_node_end_byte(node);
// Perl-only: flag arrow/method calls ($obj->m / Class->m). The
// generic short-name resolver cannot place a method without a known
// receiver type, so the call-resolution pass suppresses those edges.
@@ -2236,16 +3267,9 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
TSNode args = ts_node_child_by_field_name(node, TS_FIELD("arguments"));
// ObjectScript stores args under oref_method/method_args, not the
- // generic "arguments" field.
- if (ts_node_is_null(args) && (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
- ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE)) {
- TSNode oref = cbm_find_child_by_kind(node, "oref_method");
- if (!ts_node_is_null(oref)) {
- args = cbm_find_child_by_kind(oref, "method_args");
- }
- if (ts_node_is_null(args)) {
- args = cbm_find_child_by_kind(node, "method_args");
- }
+ // generic "arguments" field; macro arguments add one wrapper.
+ if (ts_node_is_null(args) && is_objectscript_language(ctx->language)) {
+ args = objectscript_call_args(node);
}
if (!ts_node_is_null(args)) {
call.first_string_arg = extract_url_or_topic_arg(ctx, args);
@@ -2297,6 +3321,7 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
}
cbm_calls_push(&ctx->result->calls, ctx->arena, call);
+ invocation = describe_emitted_primary_call(node, &callee);
const char **dispatch_suffixes = cbm_string_dispatch_suffixes(ctx->language);
if (dispatch_suffixes && !ts_node_is_null(args)) {
@@ -2311,6 +3336,8 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
CBMCall xcall = {0};
xcall.callee_name = cbm_arena_sprintf(ctx->arena, "%s.%s", cls, mth);
xcall.enclosing_func_qn = call.enclosing_func_qn;
+ xcall.site_start_byte = call.site_start_byte;
+ xcall.site_end_byte = call.site_end_byte;
cbm_calls_push(&ctx->result->calls, ctx->arena, xcall);
}
break;
@@ -2324,10 +3351,6 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
extract_jsx_component_ref(ctx, node, ts_node_type(node), state->enclosing_func_qn);
}
- if (ctx->language == CBM_LANG_JAVA) {
- extract_java_method_reference(ctx, node, ts_node_type(node), state->enclosing_func_qn);
- }
-
if (ctx->language == CBM_LANG_KOTLIN) {
extract_kotlin_operator_call(ctx, node, ts_node_type(node), state->enclosing_func_qn);
extract_kotlin_desugared_calls(ctx, node, ts_node_type(node), state->enclosing_func_qn);
@@ -2337,4 +3360,5 @@ void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, Walk
extract_cpp_operator_call(ctx, node, ts_node_type(node), state->enclosing_func_qn);
extract_cpp_implicit_calls(ctx, node, ts_node_type(node), state->enclosing_func_qn);
}
+ return invocation;
}
diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c
index 7cc4177ef..cf0c5b10f 100644
--- a/internal/cbm/extract_defs.c
+++ b/internal/cbm/extract_defs.c
@@ -684,9 +684,12 @@ TSNode cbm_resolve_func_name(TSNode node, CBMLanguage lang) {
return null_node;
}
- // ObjectScript routine tag is its own name node.
- if (lang == CBM_LANG_OBJECTSCRIPT_ROUTINE && strcmp(kind, "tag") == 0) {
- return node;
+ // A parameterized ObjectScript routine wraps its tag and body in a
+ // procedure node. Use the direct tag as the callable name so the
+ // definition spans the complete procedure instead of only its label.
+ if (lang == CBM_LANG_OBJECTSCRIPT_ROUTINE &&
+ (strcmp(kind, "tag") == 0 || strcmp(kind, "procedure") == 0)) {
+ return strcmp(kind, "tag") == 0 ? node : cbm_find_child_by_kind(node, "tag");
}
// ObjectScript method/classmethod: name lives under method_definition ->
// method_name -> first named child.
@@ -702,6 +705,9 @@ TSNode cbm_resolve_func_name(TSNode node, CBMLanguage lang) {
TSNode null_node = {0};
return null_node;
}
+ if (lang == CBM_LANG_OBJECTSCRIPT_UDL && strcmp(kind, "query") == 0) {
+ return cbm_find_child_by_kind(node, "query_name");
+ }
TSNode name = func_name_node(node);
@@ -2821,6 +2827,14 @@ static char *clean_type_name(CBMArena *a, const char *raw) {
static char *resolve_param_name(CBMArena *a, TSNode param, const char *source) {
const char *pk = ts_node_type(param);
+ if (strcmp(pk, "argument") == 0 || strcmp(pk, "tag_parameter") == 0) {
+ TSNode name = find_first_descendant_by_kind(param, "objectscript_identifier", 6);
+ if (ts_node_is_null(name)) {
+ name = find_first_descendant_by_kind(param, "objectscript_identifier_special", 6);
+ }
+ return ts_node_is_null(name) ? NULL : cbm_node_text(a, name, source);
+ }
+
if (strcmp(pk, "parameter_declaration") == 0) {
TSNode nm = ts_node_child_by_field_name(param, TS_FIELD("name"));
if (!ts_node_is_null(nm)) {
@@ -3024,6 +3038,15 @@ static char *resolve_param_type_text(CBMArena *a, TSNode param, const char *sour
CBMLanguage lang) {
const char *pk = ts_node_type(param);
+ if ((lang == CBM_LANG_OBJECTSCRIPT_UDL || lang == CBM_LANG_OBJECTSCRIPT_ROUTINE) &&
+ (strcmp(pk, "argument") == 0 || strcmp(pk, "tag_parameter") == 0)) {
+ TSNode return_type = cbm_find_child_by_kind(param, "return_type");
+ TSNode typename = ts_node_is_null(return_type)
+ ? (TSNode){0}
+ : cbm_find_child_by_kind(return_type, "typename");
+ return ts_node_is_null(typename) ? NULL : cbm_node_text(a, typename, source);
+ }
+
if (lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX) {
if (strcmp(pk, "required_parameter") == 0 || strcmp(pk, "optional_parameter") == 0) {
return extract_ts_param_type(a, param, source);
@@ -3094,6 +3117,226 @@ static const char **extract_param_types(CBMArena *a, TSNode params, const char *
return result;
}
+/* Internal, occurrence-preserving signature extraction. `param_types` above is
+ * the legacy USES_TYPE projection: it intentionally drops builtins and
+ * duplicate types. Semantic call resolution needs a different contract — one
+ * type entry per source-level call argument, in declaration order. */
+static const char signature_unknown_type[] = "?";
+
+static char *signature_receiver_name(CBMArena *a, TSNode param, const char *source,
+ bool unwrap_wrappers) {
+ char *name = resolve_param_name(a, param, source);
+ if (name && name[0]) {
+ return name;
+ }
+
+ TSNode candidate = ts_node_child_by_field_name(param, TS_FIELD("pattern"));
+ if (ts_node_is_null(candidate)) {
+ candidate = ts_node_child_by_field_name(param, TS_FIELD("name"));
+ }
+ if (ts_node_is_null(candidate)) {
+ uint32_t nc = ts_node_named_child_count(param);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_named_child(param, i);
+ const char *ck = ts_node_type(child);
+ if (strcmp(ck, "type_annotation") == 0 || strcmp(ck, "decorator") == 0 ||
+ strcmp(ck, "attribute_item") == 0) {
+ continue;
+ }
+ candidate = child;
+ break;
+ }
+ }
+
+ /* Python typed/splat wrappers and TS pattern wrappers place the actual
+ * receiver identifier at the first named leaf. */
+ for (int depth = 0; depth < 4 && !ts_node_is_null(candidate); depth++) {
+ if (ts_node_named_child_count(candidate) == 0) {
+ return cbm_node_text(a, candidate, source);
+ }
+ if (!unwrap_wrappers) {
+ return NULL;
+ }
+ TSNode next = ts_node_child_by_field_name(candidate, TS_FIELD("pattern"));
+ if (ts_node_is_null(next)) {
+ next = ts_node_child_by_field_name(candidate, TS_FIELD("name"));
+ }
+ if (ts_node_is_null(next)) {
+ next = ts_node_named_child(candidate, 0);
+ }
+ candidate = next;
+ }
+ return NULL;
+}
+
+static bool is_signature_implicit_receiver(CBMArena *a, TSNode param, const char *source,
+ CBMLanguage lang, bool method, bool first_parameter) {
+ const char *pk = ts_node_type(param);
+
+ /* These grammar nodes describe a receiver supplied by member-call syntax,
+ * not an argument at the call site. */
+ if (strcmp(pk, "self_parameter") == 0 || strcmp(pk, "receiver_parameter") == 0 ||
+ strcmp(pk, "explicit_object_parameter_declaration") == 0) {
+ return true;
+ }
+
+ if (lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX) {
+ char *name = signature_receiver_name(a, param, source, false);
+ return name && strcmp(name, "this") == 0;
+ }
+
+ /* Python instance/class receivers are conventional identifiers rather than
+ * distinct AST nodes. Only exclude the leading slot on a method path. */
+ if (method && first_parameter && lang == CBM_LANG_PYTHON) {
+ char *name = signature_receiver_name(a, param, source, true);
+ return name && (strcmp(name, "self") == 0 || strcmp(name, "cls") == 0);
+ }
+ return false;
+}
+
+static bool is_signature_non_parameter(TSNode param, const char *source, CBMLanguage lang) {
+ const char *pk = ts_node_type(param);
+ if (strcmp(pk, "comment") == 0 || strcmp(pk, "line_comment") == 0 ||
+ strcmp(pk, "block_comment") == 0 || strcmp(pk, "attribute_item") == 0 ||
+ strcmp(pk, "inner_attribute_item") == 0 || strcmp(pk, "attribute_specifier") == 0 ||
+ strcmp(pk, "attribute_declaration") == 0 || strcmp(pk, "annotation") == 0 ||
+ strcmp(pk, "decorator") == 0 || strcmp(pk, "modifiers") == 0 ||
+ strcmp(pk, "positional_separator") == 0 || strcmp(pk, "keyword_separator") == 0 ||
+ strcmp(pk, "type_parameters") == 0 || strcmp(pk, "type_parameter_declaration") == 0) {
+ return true;
+ }
+
+ /* In C-family declarations `(void)` means zero parameters. The grammar
+ * exposes `void` as a named primitive_type child rather than a parameter. */
+ if ((lang == CBM_LANG_C || lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA ||
+ lang == CBM_LANG_GLSL) &&
+ strcmp(pk, "primitive_type") == 0) {
+ uint32_t start = ts_node_start_byte(param);
+ uint32_t end = ts_node_end_byte(param);
+ return end - start == 4 && strncmp(source + start, "void", 4) == 0;
+ }
+ return false;
+}
+
+/* Go permits one declaration node to introduce several positional parameters:
+ * `func f(a, b T)`. Count its direct name identifiers; unnamed parameter
+ * declarations still represent one position. */
+static int signature_param_multiplicity(TSNode param, CBMLanguage lang) {
+ if (lang != CBM_LANG_GO) {
+ return 1;
+ }
+ const char *pk = ts_node_type(param);
+ if (strcmp(pk, "parameter_declaration") != 0 &&
+ strcmp(pk, "variadic_parameter_declaration") != 0) {
+ return 1;
+ }
+
+ int field_names = 0;
+ int identifier_names = 0;
+ uint32_t nc = ts_node_child_count(param);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(param, i);
+ if (ts_node_is_null(child) || !ts_node_is_named(child)) {
+ continue;
+ }
+ const char *field = ts_node_field_name_for_child(param, i);
+ if (field && strcmp(field, "name") == 0) {
+ field_names++;
+ }
+ if (strcmp(ts_node_type(child), "identifier") == 0) {
+ identifier_names++;
+ }
+ }
+ int names = field_names > 0 ? field_names : identifier_names;
+ return names > 0 ? names : 1;
+}
+
+/* Resolve the full source spelling where the legacy resolver has no supported
+ * case (defaulted C++ parameters, Python annotations, complex TS types, etc.).
+ * This deliberately does not clean or deduplicate the text. */
+static char *resolve_signature_param_type_text(CBMArena *a, TSNode param, const char *source,
+ CBMLanguage lang) {
+ TSNode type_node = ts_node_child_by_field_name(param, TS_FIELD("type"));
+ if (!ts_node_is_null(type_node)) {
+ /* TypeScript-family grammars may expose the `type_annotation` wrapper
+ * (including its colon) through the field. Store the actual type node. */
+ if (strcmp(ts_node_type(type_node), "type_annotation") == 0 &&
+ ts_node_named_child_count(type_node) > 0) {
+ type_node = ts_node_named_child(type_node, 0);
+ }
+ char *type_text = cbm_node_text(a, type_node, source);
+ if (type_text && type_text[0]) {
+ return type_text;
+ }
+ }
+
+ TSNode annotation = cbm_find_child_by_kind(param, "type_annotation");
+ if (!ts_node_is_null(annotation)) {
+ uint32_t nc = ts_node_named_child_count(annotation);
+ if (nc > 0) {
+ char *type_text = cbm_node_text(a, ts_node_named_child(annotation, 0), source);
+ if (type_text && type_text[0]) {
+ return type_text;
+ }
+ }
+ }
+
+ TSNode typed_pattern = cbm_find_child_by_kind(param, "typed_pattern");
+ if (!ts_node_is_null(typed_pattern)) {
+ type_node = ts_node_child_by_field_name(typed_pattern, TS_FIELD("type"));
+ if (!ts_node_is_null(type_node)) {
+ char *type_text = cbm_node_text(a, type_node, source);
+ if (type_text && type_text[0]) {
+ return type_text;
+ }
+ }
+ }
+ return resolve_param_type_text(a, param, source, lang);
+}
+
+static const char **extract_signature_param_types(CBMArena *a, TSNode params, const char *source,
+ CBMLanguage lang, bool method, int *out_count) {
+ *out_count = 0;
+ if (ts_node_is_null(params)) {
+ return NULL;
+ }
+
+ const char *types[MAX_PARAMS];
+ uint32_t nc = ts_node_child_count(params);
+ for (uint32_t i = 0; i < nc && *out_count < MAX_PARAMS_MINUS_1; i++) {
+ TSNode param = ts_node_child(params, i);
+ if (ts_node_is_null(param) || !ts_node_is_named(param) ||
+ is_signature_non_parameter(param, source, lang)) {
+ continue;
+ }
+ if (is_signature_implicit_receiver(a, param, source, lang, method, *out_count == 0)) {
+ continue;
+ }
+
+ char *type_text = resolve_signature_param_type_text(a, param, source, lang);
+ const char *entry = type_text && type_text[0] ? type_text : signature_unknown_type;
+ int multiplicity = signature_param_multiplicity(param, lang);
+ for (int n = 0; n < multiplicity && *out_count < MAX_PARAMS_MINUS_1; n++) {
+ types[(*out_count)++] = entry;
+ }
+ }
+
+ if (*out_count == 0) {
+ return NULL;
+ }
+ const char **result =
+ (const char **)cbm_arena_alloc(a, (size_t)(*out_count + NULL_TERM) * sizeof(const char *));
+ if (!result) {
+ *out_count = 0;
+ return NULL;
+ }
+ for (int i = 0; i < *out_count; i++) {
+ result[i] = types[i];
+ }
+ result[*out_count] = NULL;
+ return result;
+}
+
// --- Function definition extraction ---
// For C++/CUDA template_declaration, find the inner function_definition or declaration.
@@ -3108,17 +3351,57 @@ static TSNode unwrap_template_inner(TSNode node, CBMLanguage lang) {
// C/C++/CUDA/GLSL: parameters live on function_declarator inside declarator chain.
static TSNode find_c_params(TSNode func_node) {
TSNode decl = ts_node_child_by_field_name(func_node, TS_FIELD("declarator"));
- for (int d = 0; d < C_RETURN_WALK_DEPTH && !ts_node_is_null(decl); d++) {
+ for (int d = 0; d < DECLARATOR_DEPTH_LIMIT && !ts_node_is_null(decl); d++) {
TSNode params = ts_node_child_by_field_name(decl, TS_FIELD("parameters"));
if (!ts_node_is_null(params)) {
return params;
}
- decl = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
+ TSNode nested = ts_node_child_by_field_name(decl, TS_FIELD("declarator"));
+ /* tree-sitter-cpp and tree-sitter-cuda do not assign the nested
+ * function declarator a `declarator` field when a reference return
+ * wraps it (`Item& operator[](int)`). That wrapper has one named child;
+ * descend only for this reproduced grammar shape. */
+ if (ts_node_is_null(nested) && strcmp(ts_node_type(decl), "reference_declarator") == 0 &&
+ ts_node_named_child_count(decl) > 0) {
+ nested = ts_node_named_child(decl, 0);
+ }
+ decl = nested;
}
TSNode null_node = {0};
return null_node;
}
+/* Resolve the parameter-list node across the grammars used by the generic
+ * definition extractor. Newer tree-sitter-kotlin exposes
+ * `function_value_parameters` as a direct child rather than a `parameters`
+ * field. Keep the legacy and ordered signature extractors on the same node so
+ * adding positional metadata does not replace or reinterpret `param_types`. */
+static TSNode find_function_params(TSNode func_node, CBMLanguage lang) {
+ TSNode params = ts_node_child_by_field_name(func_node, TS_FIELD("parameters"));
+ // ObjectScript exposes the parameter list under a `parameter_list` field.
+ if (ts_node_is_null(params) &&
+ (lang == CBM_LANG_OBJECTSCRIPT_UDL || lang == CBM_LANG_OBJECTSCRIPT_ROUTINE)) {
+ params = ts_node_child_by_field_name(func_node, TS_FIELD("parameter_list"));
+ }
+ if (ts_node_is_null(params) && lang == CBM_LANG_OBJECTSCRIPT_ROUTINE) {
+ params = cbm_find_child_by_kind(func_node, "parameter_list");
+ }
+ if (ts_node_is_null(params) && lang == CBM_LANG_OBJECTSCRIPT_UDL) {
+ TSNode method_definition = cbm_find_child_by_kind(func_node, "method_definition");
+ if (!ts_node_is_null(method_definition)) {
+ params = cbm_find_child_by_kind(method_definition, "arguments");
+ }
+ }
+ if (ts_node_is_null(params) && lang == CBM_LANG_KOTLIN) {
+ params = cbm_find_child_by_kind(func_node, "function_value_parameters");
+ }
+ if (ts_node_is_null(params) && (lang == CBM_LANG_C || lang == CBM_LANG_CPP ||
+ lang == CBM_LANG_CUDA || lang == CBM_LANG_GLSL)) {
+ params = find_c_params(func_node);
+ }
+ return params;
+}
+
// C++: resolve trailing return type (auto f() -> Type) on a declarator node.
// Updates def->return_type and def->return_types if trailing type found.
static void resolve_cpp_trailing_return(CBMArena *a, TSNode func_node, const char *source,
@@ -3237,7 +3520,8 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
* enclosing scope here is always a namespace. The out-of-line method path
* below overrides this for `Ns::Cls::method` definitions. */
if (ctx->enclosing_class_qn &&
- (ctx->language == CBM_LANG_CPP || ctx->language == CBM_LANG_CUDA)) {
+ (ctx->language == CBM_LANG_CPP || ctx->language == CBM_LANG_CUDA ||
+ ctx->language == CBM_LANG_TYPESCRIPT || ctx->language == CBM_LANG_TSX)) {
def.qualified_name = cbm_arena_sprintf(a, "%s.%s", ctx->enclosing_class_qn, name);
}
def.label = "Function";
@@ -3246,18 +3530,19 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
def.is_exported = cbm_is_exported(name, ctx->language);
+ if (ctx->language == CBM_LANG_RUST &&
+ strcmp(ts_node_type(node), "function_signature_item") == 0) {
+ def.is_abstract = true;
+ }
// Parameters — use func_node (inner function for templates)
- TSNode params = ts_node_child_by_field_name(func_node, TS_FIELD("parameters"));
- if (ts_node_is_null(params) &&
- (ctx->language == CBM_LANG_C || ctx->language == CBM_LANG_CPP ||
- ctx->language == CBM_LANG_CUDA || ctx->language == CBM_LANG_GLSL)) {
- params = find_c_params(func_node);
- }
+ TSNode params = find_function_params(func_node, ctx->language);
if (!ts_node_is_null(params)) {
def.signature = cbm_node_text(a, params, ctx->source);
def.param_names = extract_param_names(a, params, ctx->source, ctx->language);
def.param_types = extract_param_types(a, params, ctx->source, ctx->language);
+ def.signature_param_types = extract_signature_param_types(
+ a, params, ctx->source, ctx->language, false, &def.signature_param_count);
}
// Return type — use func_node (inner function for templates)
@@ -4110,6 +4395,22 @@ static TSNode find_class_body(TSNode class_node, CBMLanguage lang) {
return null_node;
}
+/* Java keeps enum constants directly in enum_body, but declarations that
+ * follow the semicolon (methods, fields, and nested types) inside a dedicated
+ * enum_body_declarations child. Keep find_class_body() returning the raw body
+ * so enum-member extraction still sees the constants, and normalize only the
+ * consumers that walk declaration members. */
+static TSNode find_class_member_body(TSNode class_node, CBMLanguage lang) {
+ TSNode body = find_class_body(class_node, lang);
+ if (ts_node_is_null(body) || lang != CBM_LANG_JAVA ||
+ strcmp(ts_node_type(body), "enum_body") != 0) {
+ return body;
+ }
+
+ TSNode declarations = cbm_find_child_by_kind(body, "enum_body_declarations");
+ return ts_node_is_null(declarations) ? body : declarations;
+}
+
// Dart: resolve method name from method_signature/function_signature.
static TSNode resolve_dart_method_name(TSNode child, const char *ck) {
if (strcmp(ck, "method_signature") == 0) {
@@ -4247,16 +4548,17 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node,
def.end_line = ts_node_end_point(child).row + TS_LINE_OFFSET;
def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
def.is_exported = cbm_is_exported(name, ctx->language);
-
- TSNode params = ts_node_child_by_field_name(child, TS_FIELD("parameters"));
- // ObjectScript exposes the parameter list under a `parameter_list` field.
- if (ts_node_is_null(params) && (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
- ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE)) {
- params = ts_node_child_by_field_name(child, TS_FIELD("parameter_list"));
+ if (ctx->language == CBM_LANG_RUST &&
+ strcmp(ts_node_type(child), "function_signature_item") == 0) {
+ def.is_abstract = true;
}
+
+ TSNode params = find_function_params(child, ctx->language);
if (!ts_node_is_null(params)) {
def.signature = cbm_node_text(a, params, ctx->source);
def.param_types = extract_param_types(a, params, ctx->source, ctx->language);
+ def.signature_param_types = extract_signature_param_types(
+ a, params, ctx->source, ctx->language, true, &def.signature_param_count);
}
// Return type (same fields as extract_func_def)
@@ -4332,7 +4634,7 @@ static void extract_objc_impl_methods(CBMExtractCtx *ctx, TSNode impl_node, cons
// Extract methods inside a class body
static void extract_class_methods(CBMExtractCtx *ctx, TSNode class_node, const char *class_qn,
const CBMLangSpec *spec) {
- TSNode body = find_class_body(class_node, ctx->language);
+ TSNode body = find_class_member_body(class_node, ctx->language);
if (ts_node_is_null(body)) {
return;
}
@@ -4407,6 +4709,23 @@ static void extract_class_methods(CBMExtractCtx *ctx, TSNode class_node, const c
continue;
}
+ /* Kotlin secondary constructors have no source-level name node. They
+ * are nevertheless concrete callable declarations, so materialize one
+ * under the owning class using the class name (`Explicit.Explicit`).
+ * Classes with only an implicit constructor do not enter this branch
+ * and therefore do not gain a fabricated callable target. */
+ if (ctx->language == CBM_LANG_KOTLIN &&
+ strcmp(ts_node_type(method_node), "secondary_constructor") == 0) {
+ TSNode constructor_name = ts_node_child_by_field_name(class_node, TS_FIELD("name"));
+ if (ts_node_is_null(constructor_name)) {
+ constructor_name = cbm_find_child_by_kind(class_node, "type_identifier");
+ }
+ if (!ts_node_is_null(constructor_name)) {
+ push_method_def(ctx, method_node, class_node, class_qn, spec, constructor_name);
+ }
+ continue;
+ }
+
TSNode name_node = resolve_method_name(method_node, ctx->language);
if (ts_node_is_null(name_node)) {
continue;
@@ -4439,7 +4758,10 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
}
+ const char *type_qn = cbm_fqn_compute(a, ctx->project, ctx->rel_path, type_name);
+
// Check for "impl Trait for Struct" pattern
+ const char *impl_trait = NULL;
TSNode trait_node = ts_node_child_by_field_name(node, TS_FIELD("trait"));
if (!ts_node_is_null(trait_node)) {
char *trait_name = cbm_node_text(a, trait_node, ctx->source);
@@ -4453,15 +4775,15 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
}
}
if (trait_name && trait_name[0]) {
- CBMImplTrait it;
+ CBMImplTrait it = {0};
it.trait_name = trait_name;
it.struct_name = type_name;
+ it.struct_qn = type_qn;
cbm_impltrait_push(&ctx->result->impl_traits, a, it);
+ impl_trait = trait_name;
}
}
- const char *type_qn = cbm_fqn_compute(a, ctx->project, ctx->rel_path, type_name);
-
// Extract methods inside impl body
TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
if (ts_node_is_null(body)) {
@@ -4497,6 +4819,7 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
def.label = "Method";
def.file_path = ctx->rel_path;
def.parent_class = type_qn;
+ def.impl_trait = impl_trait;
def.start_line = ts_node_start_point(child).row + TS_LINE_OFFSET;
def.end_line = ts_node_end_point(child).row + TS_LINE_OFFSET;
def.is_exported = cbm_is_exported(name, ctx->language);
@@ -4505,6 +4828,8 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
if (!ts_node_is_null(params)) {
def.signature = cbm_node_text(a, params, ctx->source);
def.param_types = extract_param_types(a, params, ctx->source, ctx->language);
+ def.signature_param_types = extract_signature_param_types(
+ a, params, ctx->source, ctx->language, true, &def.signature_param_count);
}
if (spec->branching_node_types && spec->branching_node_types[0]) {
@@ -5723,7 +6048,7 @@ static void extract_class_fields(CBMExtractCtx *ctx, TSNode class_node, const ch
return;
}
- TSNode body = find_class_body(class_node, ctx->language);
+ TSNode body = find_class_member_body(class_node, ctx->language);
if (ts_node_is_null(body)) {
return;
}
@@ -6038,7 +6363,7 @@ static void extract_class_variables(CBMExtractCtx *ctx, TSNode class_node,
return;
}
- TSNode body = find_class_body(class_node, ctx->language);
+ TSNode body = find_class_member_body(class_node, ctx->language);
if (ts_node_is_null(body)) {
return;
}
@@ -6218,20 +6543,14 @@ static bool is_template_class_node(TSNode node, CBMLanguage lang) {
return false;
}
-// Compute the enclosing class QN for a class node (for nested class context).
+// Compute the enclosing class/namespace QN for a scoped node.
/* A namespace contributes a QN segment so a symbol declared in `namespace ns`
* is `proj.file.ns.sym`, not a top-level `proj.file.sym`. Without the namespace
* in the QN, namespace-aware resolution (C++ ADL) is starved: a bare call
* collapses to the file scope and resolves directly instead. Unlike a class, a
- * namespace emits no def of its own — it only extends the enclosing scope for
- * its members. C#/PHP need the same treatment paired with their LSP resolvers
- * (a def-only change breaks their existing namespace handling), done separately. */
-static bool is_namespace_scope_kind(CBMLanguage lang, const char *kind) {
- if (lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA) {
- return strcmp(kind, "namespace_definition") == 0;
- }
- return false;
-}
+ * namespace extends the enclosing scope for its members. C#/PHP need the same
+ * treatment paired with their LSP resolvers (a def-only change breaks their
+ * existing namespace handling), done separately. */
static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const char *saved_enclosing) {
TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
@@ -6259,26 +6578,53 @@ static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const char
return saved_enclosing;
}
+static void extract_typescript_namespace_def(CBMExtractCtx *ctx, TSNode node,
+ const char *saved_enclosing) {
+ TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
+ if (ts_node_is_null(name_node)) {
+ return;
+ }
+ char *name = cbm_node_text(ctx->arena, name_node, ctx->source);
+ const char *namespace_qn = compute_class_qn(ctx, node, saved_enclosing);
+ if (!name || !name[0] || !namespace_qn || !namespace_qn[0]) {
+ return;
+ }
+ CBMDefinition def = {0};
+ def.name = name;
+ def.qualified_name = namespace_qn;
+ def.label = "Module";
+ def.file_path = ctx->rel_path;
+ def.start_line = ts_node_start_point(node).row + TS_LINE_OFFSET;
+ def.end_line = ts_node_end_point(node).row + TS_LINE_OFFSET;
+ def.lines = (int)(def.end_line - def.start_line + TS_LINE_OFFSET);
+ def.is_exported = true;
+ cbm_defs_push(&ctx->result->defs, ctx->arena, def);
+}
+
// Push nested class children from a class body container onto the walk stack.
static void push_class_body_children(TSNode node, const CBMLangSpec *spec, wd_stack_t *s,
const char *new_enclosing, CBMArena *arena) {
- uint32_t nc = ts_node_child_count(node);
- for (uint32_t ci = 0; ci < nc; ci++) {
- TSNode child = ts_node_child(node, ci);
- const char *ck = ts_node_type(child);
- if (strcmp(ck, "field_declaration_list") == 0 || strcmp(ck, "class_body") == 0 ||
- strcmp(ck, "declaration_list") == 0 || strcmp(ck, "body") == 0 ||
- strcmp(ck, "block") == 0 || strcmp(ck, "suite") == 0 ||
- // Groovy class bodies are a `closure` node; routing through the
- // nested-class path keeps methods from being re-walked (and thus
- // double-extracted) as top-level functions. Gated to Groovy so other
- // grammars that also name a node "closure" are unaffected.
- (strcmp(ck, "closure") == 0 && spec->language == CBM_LANG_GROOVY)) {
- push_nested_class_nodes(child, spec, s, new_enclosing, arena);
- return;
- }
+ /* Use the same language-aware body selection as method extraction. The old
+ * independent spelling list omitted valid containers such as Scala's
+ * `template_body` and Solidity's contract body. Methods were extracted
+ * once by extract_class_methods(), then the generic walk descended through
+ * the unrecognized body and extracted them again as free functions. */
+ /* Smali's class node is itself the member container. Method extraction
+ * currently preserves Smali's established file-level Function contract,
+ * so the generic walk must still visit those direct method_definition
+ * children. Treating the class itself as a completed body here would only
+ * scan it for nested classes and silently drop every method. */
+ TSNode body = {0};
+ if (spec->language != CBM_LANG_SMALI) {
+ body = find_class_member_body(node, spec->language);
+ }
+ if (!ts_node_is_null(body)) {
+ push_nested_class_nodes(body, spec, s, new_enclosing, arena);
+ return;
}
+
// No body found — push all children directly
+ uint32_t nc = ts_node_child_count(node);
for (int ci = (int)nc - SKIP_CHAR; ci >= 0; ci--) {
wd_push(s, ts_node_child(node, (uint32_t)ci), new_enclosing);
}
@@ -6779,8 +7125,11 @@ static void walk_defs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec,
* is walked normally — functions AND classes, unlike a class body which
* routes methods through extract_class_methods. Do NOT emit a def or run
* the class/func paths on the namespace node itself. */
- if (is_namespace_scope_kind(ctx->language, kind)) {
+ if (cbm_is_namespace_scope_kind(ctx->language, kind)) {
const char *new_enclosing = compute_class_qn(ctx, node, frame.enclosing_class_qn);
+ if (ctx->language == CBM_LANG_TYPESCRIPT || ctx->language == CBM_LANG_TSX) {
+ extract_typescript_namespace_def(ctx, node, frame.enclosing_class_qn);
+ }
wd_push_children_reverse(&s, node, new_enclosing);
continue;
}
diff --git a/internal/cbm/extract_imports.c b/internal/cbm/extract_imports.c
index 717068a2b..8696e4b30 100644
--- a/internal/cbm/extract_imports.c
+++ b/internal/cbm/extract_imports.c
@@ -107,6 +107,17 @@ static const char *path_last(CBMArena *a, const char *path) {
return path;
}
+/* An unaliased dotted Python import binds its first component, not its last:
+ * `import xml.etree` introduces `xml`. Keep module_path intact for dependency
+ * resolution while recording the language-correct local spelling. */
+static const char *python_import_root(CBMArena *a, const char *path) {
+ if (!path) {
+ return NULL;
+ }
+ const char *dot = strchr(path, '.');
+ return dot ? cbm_arena_strndup(a, path, (size_t)(dot - path)) : path;
+}
+
// --- Go imports ---
// import_declaration -> import_spec_list -> import_spec -> (name, path)
@@ -197,7 +208,7 @@ static void process_py_import_stmt(CBMExtractCtx *ctx, TSNode node) {
if (strcmp(ck, "dotted_name") == 0 || strcmp(ck, "identifier") == 0) {
char *mod = cbm_node_text(a, child, ctx->source);
if (mod && mod[0]) {
- CBMImport imp = {.local_name = path_last(a, mod), .module_path = mod};
+ CBMImport imp = {.local_name = python_import_root(a, mod), .module_path = mod};
cbm_imports_push(&ctx->result->imports, a, imp);
}
} else if (strcmp(ck, "aliased_import") == 0) {
@@ -211,7 +222,7 @@ static void process_py_import_stmt(CBMExtractCtx *ctx, TSNode node) {
} else {
char *mod = cbm_node_text(a, name_node, ctx->source);
if (mod && mod[0]) {
- CBMImport imp = {.local_name = path_last(a, mod), .module_path = mod};
+ CBMImport imp = {.local_name = python_import_root(a, mod), .module_path = mod};
cbm_imports_push(&ctx->result->imports, a, imp);
}
}
diff --git a/internal/cbm/extract_unified.c b/internal/cbm/extract_unified.c
index d6f2380e2..f9b07881c 100644
--- a/internal/cbm/extract_unified.c
+++ b/internal/cbm/extract_unified.c
@@ -14,14 +14,195 @@ enum { MAX_INFRA_BINDINGS = 8 };
// --- Scope stack management ---
-static void push_scope(WalkState *state, uint8_t kind, uint32_t depth, const char *qn) {
- if (state->scope_top >= MAX_SCOPES) {
- return;
+static bool ensure_scope_capacity(WalkState *state) {
+ if (state->scope_top < state->scope_capacity) {
+ return true;
+ }
+ int new_capacity = state->scope_capacity > 0 ? state->scope_capacity * 2 : MAX_SCOPES;
+ CBMWalkScope *grown =
+ (CBMWalkScope *)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ return false;
+ }
+ memcpy(grown, state->scopes, (size_t)state->scope_top * sizeof(*grown));
+ state->scopes = grown;
+ state->scope_capacity = new_capacity;
+ return true;
+}
+
+static const CBMLexicalScope *lexical_scope_by_id(const WalkState *state, uint32_t id) {
+ return state && id > 0 && id <= (uint32_t)state->lexical_scope_count
+ ? &state->lexical_scopes[id - 1U]
+ : NULL;
+}
+
+static CBMLexicalScope *mutable_lexical_scope_by_id(WalkState *state, uint32_t id) {
+ return state && id > 0 && id <= (uint32_t)state->lexical_scope_count
+ ? &state->lexical_scopes[id - 1U]
+ : NULL;
+}
+
+static uint32_t current_lexical_scope_id(const WalkState *state) {
+ if (!state) {
+ return 0;
+ }
+ for (int i = state->scope_top - 1; i >= 0; i--) {
+ if (state->scopes[i].lexical_scope_id != 0) {
+ return state->scopes[i].lexical_scope_id;
+ }
+ }
+ return state->root_lexical_scope_id;
+}
+
+static bool ensure_lexical_scope_capacity(WalkState *state) {
+ if (state->lexical_scope_count < state->lexical_scope_capacity) {
+ return true;
+ }
+ if (state->lexical_scope_capacity > INT32_MAX / PAIR_LEN) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ int new_capacity = state->lexical_scope_capacity * PAIR_LEN;
+ CBMLexicalScope *grown =
+ (CBMLexicalScope *)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ memcpy(grown, state->lexical_scopes, (size_t)state->lexical_scope_count * sizeof(*grown));
+ state->lexical_scopes = grown;
+ state->lexical_scope_capacity = new_capacity;
+ return true;
+}
+
+static uint32_t python_function_lookup_parent(const WalkState *state,
+ uint32_t structural_parent_id) {
+ uint32_t id = structural_parent_id;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = lexical_scope_by_id(state, id);
+ if (!scope) {
+ return structural_parent_id;
+ }
+ if (scope->kind == CBM_LEXICAL_SCOPE_CLASS) {
+ return scope->lookup_parent_id;
+ }
+ if (scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION ||
+ scope->kind == CBM_LEXICAL_SCOPE_MODULE) {
+ return structural_parent_id;
+ }
+ id = scope->parent_id;
+ }
+ return structural_parent_id;
+}
+
+static uint32_t add_lexical_scope(WalkState *state, TSNode node, CBMLexicalScopeKind kind) {
+ if (!state || ts_node_is_null(node) || !ensure_lexical_scope_capacity(state)) {
+ return 0;
+ }
+ uint32_t parent_id = current_lexical_scope_id(state);
+ uint32_t lookup_parent_id = parent_id;
+ /* Python method/function lookup bypasses the containing class namespace;
+ * class attributes require qualification (`self.x`/`Cls.x`). */
+ if (kind == CBM_LEXICAL_SCOPE_FUNCTION && state->language == CBM_LANG_PYTHON) {
+ lookup_parent_id = python_function_lookup_parent(state, parent_id);
+ }
+ CBMLexicalScope *scope = &state->lexical_scopes[state->lexical_scope_count];
+ scope->id = (uint32_t)state->lexical_scope_count + 1U;
+ scope->parent_id = parent_id;
+ scope->lookup_parent_id = lookup_parent_id;
+ scope->start_byte = ts_node_start_byte(node);
+ scope->end_byte = ts_node_end_byte(node);
+ scope->kind = (uint8_t)kind;
+ state->lexical_scope_count++;
+ return scope->id;
+}
+
+static bool push_scope(WalkState *state, uint8_t kind, uint32_t depth, const char *qn) {
+ if (!ensure_scope_capacity(state)) {
+ return false;
}
state->scopes[state->scope_top].kind = kind;
state->scopes[state->scope_top].depth = depth;
state->scopes[state->scope_top].qn = qn;
+ state->scopes[state->scope_top].lexical_scope_id = 0;
+ state->scopes[state->scope_top].invocation_kind = CBM_INVOCATION_NONE;
+ state->scopes[state->scope_top].callee_expr = (TSNode){0};
+ state->scopes[state->scope_top].callee_leaf = (TSNode){0};
state->scope_top++;
+ return true;
+}
+
+static bool push_lexical_scope(WalkState *state, uint8_t walk_kind, uint32_t depth, const char *qn,
+ TSNode node, CBMLexicalScopeKind lexical_kind) {
+ if (!push_scope(state, walk_kind, depth, qn)) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ state->scopes[state->scope_top - SKIP_ONE].lexical_scope_id =
+ add_lexical_scope(state, node, lexical_kind);
+ return true;
+}
+
+static bool push_existing_lexical_scope(WalkState *state, uint8_t walk_kind, uint32_t depth,
+ const char *qn, uint32_t lexical_scope_id, TSNode node) {
+ CBMLexicalScope *scope = mutable_lexical_scope_by_id(state, lexical_scope_id);
+ if (!scope || !push_scope(state, walk_kind, depth, qn)) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ state->scopes[state->scope_top - SKIP_ONE].lexical_scope_id = lexical_scope_id;
+ uint32_t end_byte = ts_node_end_byte(node);
+ if (end_byte > scope->end_byte) {
+ scope->end_byte = end_byte;
+ }
+ return true;
+}
+
+static uint32_t active_same_function_scope_id(const WalkState *state, const char *function_qn,
+ TSNode node) {
+ if (!state || !function_qn) {
+ return 0;
+ }
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ for (int i = state->scope_top - 1; i >= 0; i--) {
+ if (state->scopes[i].kind != SCOPE_FUNC || !state->scopes[i].qn ||
+ strcmp(state->scopes[i].qn, function_qn) != 0) {
+ continue;
+ }
+ const CBMLexicalScope *scope =
+ lexical_scope_by_id(state, state->scopes[i].lexical_scope_id);
+ if (scope && scope->start_byte <= start && end <= scope->end_byte) {
+ return scope->id;
+ }
+ }
+ return 0;
+}
+
+static bool push_function_scope(WalkState *state, uint32_t depth, const char *function_qn,
+ TSNode node) {
+ uint32_t existing_id = active_same_function_scope_id(state, function_qn, node);
+ return existing_id ? push_existing_lexical_scope(state, SCOPE_FUNC, depth, function_qn,
+ existing_id, node)
+ : push_lexical_scope(state, SCOPE_FUNC, depth, function_qn, node,
+ CBM_LEXICAL_SCOPE_FUNCTION);
+}
+
+static void push_call_scope(WalkState *state, uint32_t depth,
+ const CBMInvocationDescriptor *invocation) {
+ if (!invocation ||
+ (invocation->kind != CBM_INVOCATION_CALLABLE_REFERENCE && !invocation->raw_call_emitted) ||
+ (ts_node_is_null(invocation->callee_expr) && ts_node_is_null(invocation->callee_leaf))) {
+ return;
+ }
+ if (!push_scope(state, SCOPE_CALL, depth, NULL)) {
+ return;
+ }
+ state->scopes[state->scope_top - SKIP_ONE].invocation_kind = invocation->kind;
+ state->scopes[state->scope_top - SKIP_ONE].callee_expr = invocation->callee_expr;
+ state->scopes[state->scope_top - SKIP_ONE].callee_leaf = invocation->callee_leaf;
}
// Pop scopes that we've ascended out of (depth >= current cursor depth).
@@ -35,7 +216,9 @@ static void pop_expired_scopes(WalkState *state, uint32_t cur_depth) {
static void recompute_state(WalkState *state, const char *module_qn) {
state->enclosing_func_qn = module_qn;
state->enclosing_class_qn = NULL;
- state->inside_call = false;
+ state->invocation_kind = CBM_INVOCATION_NONE;
+ state->callee_expr = (TSNode){0};
+ state->callee_leaf = (TSNode){0};
state->inside_import = false;
state->loop_depth = 0;
state->branch_depth = 0;
@@ -46,10 +229,13 @@ static void recompute_state(WalkState *state, const char *module_qn) {
state->enclosing_func_qn = state->scopes[i].qn;
break;
case SCOPE_CLASS:
+ case SCOPE_NAMESPACE:
state->enclosing_class_qn = state->scopes[i].qn;
break;
case SCOPE_CALL:
- state->inside_call = true;
+ state->invocation_kind = state->scopes[i].invocation_kind;
+ state->callee_expr = state->scopes[i].callee_expr;
+ state->callee_leaf = state->scopes[i].callee_leaf;
break;
case SCOPE_IMPORT:
state->inside_import = true;
@@ -453,10 +639,22 @@ static const char *objectscript_get_class_name(CBMExtractCtx *ctx, TSNode node)
return NULL;
}
-// Resolve the QN of an ObjectScript method/classmethod node for scope tracking.
+// Resolve the QN of an ObjectScript method/classmethod/query node for scope tracking.
static const char *objectscript_get_method_qn(CBMExtractCtx *ctx, TSNode node,
const char *enclosing_class_qn) {
const char *nk = ts_node_type(node);
+ if (strcmp(nk, "query") == 0) {
+ TSNode query_name = cbm_find_child_by_kind(node, "query_name");
+ if (ts_node_is_null(query_name)) {
+ return NULL;
+ }
+ char *name = cbm_node_text(ctx->arena, query_name, ctx->source);
+ if (!name || !name[0]) {
+ return NULL;
+ }
+ return enclosing_class_qn ? cbm_arena_sprintf(ctx->arena, "%s.%s", enclosing_class_qn, name)
+ : cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, name);
+ }
if (strcmp(nk, "method") != 0 && strcmp(nk, "classmethod") != 0) {
return NULL;
}
@@ -495,8 +693,20 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan
return objectscript_get_method_qn(ctx, node, state->enclosing_class_qn);
}
if (ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) {
- if (strcmp(ts_node_type(node), "tag") == 0) {
- char *name = cbm_node_text(ctx->arena, node, ctx->source);
+ const char *kind = ts_node_type(node);
+ TSNode tag = {0};
+ if (strcmp(kind, "procedure") == 0) {
+ tag = cbm_find_child_by_kind(node, "tag");
+ } else if (strcmp(kind, "tag") == 0) {
+ /* The enclosing procedure owns the full callable range and already
+ * pushed this QN. Do not create a nested label-only function scope. */
+ TSNode parent = ts_node_parent(node);
+ if (ts_node_is_null(parent) || strcmp(ts_node_type(parent), "procedure") != 0) {
+ tag = node;
+ }
+ }
+ if (!ts_node_is_null(tag)) {
+ char *name = cbm_node_text(ctx->arena, tag, ctx->source);
if (name && name[0]) {
return cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, name);
}
@@ -1315,6 +1525,15 @@ static void scan_infra_bindings(CBMExtractCtx *ctx, TSNode node) {
}
}
+/* Extra nodes are grammar-declared trivia (most commonly comments). They still
+ * participate in cursor traversal and scope expiry, but none of the unified
+ * semantic handlers consumes their contents; documentation is collected by
+ * the definition/LSP passes. The grammar predicate covers every language
+ * without confusing structured syntax such as SQL COMMENT statements. */
+static bool is_unified_trivia_node(TSNode node) {
+ return ts_node_is_extra(node);
+}
+
// JS/TS `export_statement` appears in import_node_types so re-exports
// (`export { X } from './m'`) are treated as an import boundary. But it also
// wraps exported *declarations* (`export function f(cfg: Config) {}`), and
@@ -1341,9 +1560,280 @@ static bool is_export_of_declaration(TSNode node) {
return false;
}
+// Some languages encode imports with the same generic AST node used by every
+// ordinary invocation. Static node-kind membership is therefore not enough to
+// make the whole subtree an import scope.
+static bool is_actual_import_boundary(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
+ bool direct_import = spec->import_node_types && cbm_kind_in_set(node, spec->import_node_types);
+ bool from_import = spec->import_from_types && cbm_kind_in_set(node, spec->import_from_types);
+ if (!direct_import && !from_import) {
+ return false;
+ }
+
+ const char *kind = ts_node_type(node);
+ TSNode head = ts_node_child_by_field_name(node, TS_FIELD("function"));
+ if (ts_node_is_null(head)) {
+ head = ts_node_child_by_field_name(node, TS_FIELD("method"));
+ }
+ if (ts_node_is_null(head)) {
+ head = ts_node_child_by_field_name(node, TS_FIELD("command_name"));
+ }
+ if (ts_node_is_null(head)) {
+ head = ts_node_child_by_field_name(node, TS_FIELD("name"));
+ }
+ if (ts_node_is_null(head) && ts_node_named_child_count(node) > 0) {
+ head = ts_node_named_child(node, 0);
+ }
+ char *name = ts_node_is_null(head) ? NULL : cbm_node_text(ctx->arena, head, ctx->source);
+
+ switch (ctx->language) {
+ case CBM_LANG_ELIXIR:
+ return strcmp(kind, "call") != 0 ||
+ (name && (strcmp(name, "import") == 0 || strcmp(name, "alias") == 0 ||
+ strcmp(name, "require") == 0 || strcmp(name, "use") == 0));
+ case CBM_LANG_LUA:
+ return strcmp(kind, "function_call") != 0 || (name && strcmp(name, "require") == 0);
+ case CBM_LANG_RUBY:
+ return strcmp(kind, "call") != 0 ||
+ (name && (strcmp(name, "require") == 0 || strcmp(name, "require_relative") == 0));
+ case CBM_LANG_BASH:
+ return strcmp(kind, "command") != 0 ||
+ (name && (strcmp(name, "source") == 0 || strcmp(name, ".") == 0));
+ case CBM_LANG_R:
+ if (strcmp(kind, "call") != 0 || !name) {
+ return strcmp(kind, "call") != 0;
+ }
+ return strcmp(name, "library") == 0 || strcmp(name, "require") == 0 ||
+ strcmp(name, "requireNamespace") == 0 || strcmp(name, "loadNamespace") == 0 ||
+ strcmp(name, "source") == 0 || strcmp(name, "box::use") == 0;
+ case CBM_LANG_ZIG: {
+ if (strcmp(kind, "builtin_function") != 0) {
+ return true;
+ }
+ char *text = cbm_node_text(ctx->arena, node, ctx->source);
+ return text && (strncmp(text, "@import", sizeof("@import") - 1) == 0 ||
+ strncmp(text, "@cImport", sizeof("@cImport") - 1) == 0);
+ }
+ case CBM_LANG_SCSS:
+ /* `@include` is an executable mixin invocation, not a module import. */
+ return strcmp(kind, "include_statement") != 0;
+ default:
+ return true;
+ }
+}
+
+/* NASM labels and instructions are flat siblings. For an actual instruction,
+ * find the nearest preceding label at the first ancestor level that has one.
+ * This is structural scope recovery; the instruction mnemonic is not used. */
+static TSNode nasm_wrapped_label(TSNode node, int remaining_depth) {
+ if (ts_node_is_null(node) || remaining_depth < 0) {
+ return (TSNode){0};
+ }
+ if (strcmp(ts_node_type(node), "label") == 0) {
+ return node;
+ }
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "instruction") != 0 && strcmp(kind, "source_line") != 0) {
+ return (TSNode){0};
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode label = nasm_wrapped_label(ts_node_named_child(node, i), remaining_depth - 1);
+ if (!ts_node_is_null(label)) {
+ return label;
+ }
+ }
+ return (TSNode){0};
+}
+
+static TSNode nasm_preceding_label(TSNode node) {
+ TSNode current = node;
+ for (int level = 0; level < 4 && !ts_node_is_null(current); level++) {
+ TSNode previous = ts_node_prev_named_sibling(current);
+ while (!ts_node_is_null(previous)) {
+ TSNode label = nasm_wrapped_label(previous, 2);
+ if (!ts_node_is_null(label)) {
+ return label;
+ }
+ previous = ts_node_prev_named_sibling(previous);
+ }
+ TSNode parent = ts_node_parent(current);
+ if (ts_node_is_null(parent) || strcmp(ts_node_type(current), "source_file") == 0) {
+ break;
+ }
+ current = parent;
+ }
+ return (TSNode){0};
+}
+
+/* Traditional ObjectScript routines are flat: a tag statement is followed by
+ * sibling command statements until the next tag. Re-anchor each top-level
+ * command statement to its nearest preceding tag, just as NASM instructions
+ * are re-anchored to flat labels. Braced `procedure` nodes already provide a
+ * real lexical boundary and deliberately bypass this recovery path. */
+static TSNode objectscript_routine_statement_tag(TSNode statement) {
+ TSNode tag_statement = cbm_find_child_by_kind(statement, "tag_statement");
+ return ts_node_is_null(tag_statement) ? (TSNode){0}
+ : cbm_find_child_by_kind(tag_statement, "tag");
+}
+
+static TSNode objectscript_routine_preceding_tag(TSNode node) {
+ if (strcmp(ts_node_type(node), "statement") != 0) {
+ return (TSNode){0};
+ }
+ TSNode parent = ts_node_parent(node);
+ if (ts_node_is_null(parent) || strcmp(ts_node_type(parent), "source_file") != 0 ||
+ !ts_node_is_null(cbm_find_child_by_kind(node, "tag_statement")) ||
+ !ts_node_is_null(cbm_find_child_by_kind(node, "procedure"))) {
+ return (TSNode){0};
+ }
+ for (TSNode previous = ts_node_prev_named_sibling(node); !ts_node_is_null(previous);
+ previous = ts_node_prev_named_sibling(previous)) {
+ TSNode tag = objectscript_routine_statement_tag(previous);
+ if (!ts_node_is_null(tag)) {
+ return tag;
+ }
+ }
+ return (TSNode){0};
+}
+
+static bool push_pre_node_scope(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
+ WalkState *state, uint32_t depth) {
+ for (int i = 0; i < state->scope_top; i++) {
+ if (state->scopes[i].kind == SCOPE_FUNC) {
+ return false;
+ }
+ }
+
+ TSNode label = {0};
+ if (ctx->language == CBM_LANG_NASM && strcmp(ts_node_type(node), "actual_instruction") == 0) {
+ label = nasm_preceding_label(node);
+ } else if (ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) {
+ if (strcmp(ts_node_type(node), "tag_statement") == 0) {
+ /* A parameterized flat tag owns its header as well as the following
+ * sibling command statements. Anchor before descending so its
+ * parameter_list records lexical bindings under the same tag QN. */
+ label = cbm_find_child_by_kind(node, "tag");
+ } else {
+ label = objectscript_routine_preceding_tag(node);
+ }
+ }
+ if (ts_node_is_null(label)) {
+ return false;
+ }
+ const char *fqn = compute_func_qn(ctx, label, spec, state);
+ if (!fqn) {
+ return false;
+ }
+ uint32_t anchor_start = ts_node_start_byte(label);
+ uint32_t anchor_end = ts_node_end_byte(label);
+ bool same_flat_callable = state->flat_function_scope_id != 0 &&
+ state->flat_anchor_start_byte == anchor_start &&
+ state->flat_anchor_end_byte == anchor_end &&
+ state->flat_function_qn && strcmp(state->flat_function_qn, fqn) == 0;
+ bool pushed = same_flat_callable
+ ? push_existing_lexical_scope(state, SCOPE_FUNC, depth, fqn,
+ state->flat_function_scope_id, node)
+ : push_function_scope(state, depth, fqn, node);
+ if (pushed && !same_flat_callable) {
+ state->flat_function_scope_id = state->scopes[state->scope_top - SKIP_ONE].lexical_scope_id;
+ state->flat_anchor_start_byte = anchor_start;
+ state->flat_anchor_end_byte = anchor_end;
+ state->flat_function_qn = fqn;
+ }
+ return pushed;
+}
+
+static bool unified_kind_in_set(const char *kind, const char *const *set) {
+ for (int i = 0; kind && set && set[i]; i++) {
+ if (strcmp(kind, set[i]) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool lexical_boundary_kind(TSNode node, CBMLexicalScopeKind *out_kind) {
+ const char *kind = ts_node_type(node);
+ static const char *const block_kinds[] = {"block",
+ "statement_block",
+ "compound_statement",
+ "switch_body",
+ "catch_clause",
+ "except_clause",
+ "finally_clause",
+ "for_statement",
+ "for_in_statement",
+ "for_of_statement",
+ "enhanced_for_statement",
+ "foreach_statement",
+ "foreach_clause",
+ "loop_expression",
+ "match_block",
+ "case_block",
+ "script_block",
+ "do_block",
+ NULL};
+ static const char *const comprehension_kinds[] = {
+ "list_comprehension", "set_comprehension", "dictionary_comprehension",
+ "generator_expression", "comprehension_expression", NULL};
+ static const char *const anonymous_function_kinds[] = {"lambda",
+ "lambda_expression",
+ "anonymous_function",
+ "anonymous_function_creation_expression",
+ "anonymous_method_expression",
+ "arrow_function",
+ "closure_expression",
+ "func_literal",
+ "function_expression",
+ "function_literal",
+ NULL};
+ /* Rust inline modules own independent item/import namespaces. Without a
+ * concrete module scope, `mod inner { use ... as x; }` leaks x into every
+ * sibling function in the file. */
+ if (strcmp(kind, "mod_item") == 0) {
+ *out_kind = CBM_LEXICAL_SCOPE_MODULE;
+ return true;
+ }
+ if (unified_kind_in_set(kind, comprehension_kinds)) {
+ *out_kind = CBM_LEXICAL_SCOPE_COMPREHENSION;
+ return true;
+ }
+ if (unified_kind_in_set(kind, anonymous_function_kinds)) {
+ *out_kind = CBM_LEXICAL_SCOPE_FUNCTION;
+ return true;
+ }
+ if (unified_kind_in_set(kind, block_kinds)) {
+ *out_kind = CBM_LEXICAL_SCOPE_BLOCK;
+ return true;
+ }
+ return false;
+}
+
+static bool node_already_has_lexical_scope(const WalkState *state, TSNode node) {
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ for (int i = state->scope_top - 1; i >= 0; i--) {
+ const CBMLexicalScope *scope =
+ lexical_scope_by_id(state, state->scopes[i].lexical_scope_id);
+ if (scope && scope->start_byte == start && scope->end_byte == end) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void push_lexical_boundary(TSNode node, WalkState *state, uint32_t depth) {
+ CBMLexicalScopeKind kind;
+ if (!node_already_has_lexical_scope(state, node) && lexical_boundary_kind(node, &kind)) {
+ (void)push_lexical_scope(state, SCOPE_LEXICAL, depth, NULL, node, kind);
+ }
+}
+
// Push scope markers for function, class, call, and import boundary nodes.
static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
- WalkState *state, uint32_t depth) {
+ WalkState *state, uint32_t depth,
+ const CBMInvocationDescriptor *invocation) {
if (spec->function_node_types && cbm_kind_in_set(node, spec->function_node_types)) {
/* OCaml: a nested local `let x = e in ...` is itself a value_definition,
* but the def walk does not descend into function bodies, so it emits no
@@ -1362,8 +1852,20 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
}
if (!skip_nested) {
const char *fqn = compute_func_qn(ctx, node, spec, state);
- if (fqn) {
- push_scope(state, SCOPE_FUNC, depth, fqn);
+ if (fqn && push_function_scope(state, depth, fqn, node)) {
+ const char *node_kind = ts_node_type(node);
+ bool split_signature = (ctx->language == CBM_LANG_DART &&
+ (strcmp(node_kind, "function_signature") == 0 ||
+ strcmp(node_kind, "method_signature") == 0)) ||
+ (ctx->language == CBM_LANG_LLVM_IR &&
+ strcmp(node_kind, "function_header") == 0);
+ if (split_signature) {
+ state->split_function_scope_id =
+ state->scopes[state->scope_top - SKIP_ONE].lexical_scope_id;
+ state->split_signature_start_byte = ts_node_start_byte(node);
+ state->split_signature_end_byte = ts_node_end_byte(node);
+ state->split_function_qn = fqn;
+ }
// ObjectScript: entering a method resets local var types (keeping
// class-level property types) and seeds the declared parameter types.
if (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
@@ -1407,10 +1909,16 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
}
}
}
+ } else if (cbm_is_namespace_scope_kind(ctx->language, ts_node_type(node))) {
+ const char *namespace_qn = compute_class_qn(ctx, node, state);
+ if (namespace_qn) {
+ push_lexical_scope(state, SCOPE_NAMESPACE, depth, namespace_qn, node,
+ CBM_LEXICAL_SCOPE_MODULE);
+ }
} else if (spec->class_node_types && cbm_kind_in_set(node, spec->class_node_types)) {
const char *cqn = compute_class_qn(ctx, node, state);
if (cqn) {
- push_scope(state, SCOPE_CLASS, depth, cqn);
+ push_lexical_scope(state, SCOPE_CLASS, depth, cqn, node, CBM_LEXICAL_SCOPE_CLASS);
// ObjectScript: a new class clears the type map entirely.
if (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) {
@@ -1425,7 +1933,7 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
if (type_name && type_name[0]) {
const char *tqn =
cbm_fqn_compute(ctx->arena, ctx->project, ctx->rel_path, type_name);
- push_scope(state, SCOPE_CLASS, depth, tqn);
+ push_lexical_scope(state, SCOPE_CLASS, depth, tqn, node, CBM_LEXICAL_SCOPE_CLASS);
}
}
} else if (ctx->language == CBM_LANG_DART && strcmp(ts_node_type(node), "function_body") == 0) {
@@ -1442,16 +1950,54 @@ static void push_boundary_scopes(CBMExtractCtx *ctx, TSNode node, const CBMLangS
if (!ts_node_is_null(prev)) {
const char *fqn = compute_func_qn(ctx, prev, spec, state);
if (fqn) {
- push_scope(state, SCOPE_FUNC, depth, fqn);
+ bool exact_pending =
+ state->split_function_scope_id != 0 && state->split_function_qn &&
+ strcmp(state->split_function_qn, fqn) == 0 &&
+ state->split_signature_start_byte == ts_node_start_byte(prev) &&
+ state->split_signature_end_byte == ts_node_end_byte(prev);
+ if (exact_pending) {
+ push_existing_lexical_scope(state, SCOPE_FUNC, depth, fqn,
+ state->split_function_scope_id, node);
+ } else {
+ push_function_scope(state, depth, fqn, node);
+ }
+ state->split_function_scope_id = 0;
+ state->split_function_qn = NULL;
+ }
+ }
+ } else if (ctx->language == CBM_LANG_LLVM_IR &&
+ strcmp(ts_node_type(node), "function_body") == 0) {
+ /* LLVM's function_header and function_body are siblings under
+ * fn_define. Re-anchor the already-extracted header definition across
+ * its body so instruction_call nodes inherit that routine. */
+ TSNode previous = ts_node_prev_sibling(node);
+ while (!ts_node_is_null(previous) &&
+ strcmp(ts_node_type(previous), "function_header") != 0) {
+ previous = ts_node_prev_sibling(previous);
+ }
+ if (!ts_node_is_null(previous)) {
+ const char *fqn = compute_func_qn(ctx, previous, spec, state);
+ if (fqn) {
+ bool exact_pending =
+ state->split_function_scope_id != 0 && state->split_function_qn &&
+ strcmp(state->split_function_qn, fqn) == 0 &&
+ state->split_signature_start_byte == ts_node_start_byte(previous) &&
+ state->split_signature_end_byte == ts_node_end_byte(previous);
+ if (exact_pending) {
+ push_existing_lexical_scope(state, SCOPE_FUNC, depth, fqn,
+ state->split_function_scope_id, node);
+ } else {
+ push_function_scope(state, depth, fqn, node);
+ }
+ state->split_function_scope_id = 0;
+ state->split_function_qn = NULL;
}
}
}
- if (spec->call_node_types && cbm_kind_in_set(node, spec->call_node_types)) {
- push_scope(state, SCOPE_CALL, depth, NULL);
- }
- if (spec->import_node_types && cbm_kind_in_set(node, spec->import_node_types) &&
- !is_export_of_declaration(node)) {
+ push_lexical_boundary(node, state, depth);
+ push_call_scope(state, depth, invocation);
+ if (is_actual_import_boundary(ctx, node, spec) && !is_export_of_declaration(node)) {
push_scope(state, SCOPE_IMPORT, depth, NULL);
}
/* Loop / branch nesting for bottleneck metrics. Loops are gated on named
@@ -1472,33 +2018,56 @@ void cbm_extract_unified(CBMExtractCtx *ctx) {
}
TSTreeCursor cursor = ts_tree_cursor_new(ctx->root);
+ TSTreeCursor occurrence_cursor = ts_tree_cursor_copy(&cursor);
WalkState state;
memset(&state, 0, sizeof(state));
+ state.current_cursor = &cursor;
+ state.occurrence_cursor = &occurrence_cursor;
+ state.arena = ctx->arena;
+ state.language = ctx->language;
+ state.scopes = state.inline_scopes;
+ state.scope_capacity = MAX_SCOPES;
+ state.lexical_scopes = state.inline_lexical_scopes;
+ state.lexical_scope_capacity = INLINE_LEXICAL_SCOPES;
+ state.usage_start_index = ctx->result->usages.count;
+ state.root_lexical_scope_id = add_lexical_scope(&state, ctx->root, CBM_LEXICAL_SCOPE_MODULE);
uint32_t depth = 0;
for (;;) {
TSNode node = ts_tree_cursor_current_node(&cursor);
+ bool trivia = is_unified_trivia_node(node);
+ if (!trivia) {
+ /* Trivia consumes no semantic state. Scope expiry may be deferred
+ * until the next code-bearing node, which recomputes before use. */
+ pop_expired_scopes(&state, depth);
+ recompute_state(&state, ctx->module_qn);
+ if (push_pre_node_scope(ctx, node, spec, &state, depth)) {
+ recompute_state(&state, ctx->module_qn);
+ }
+
+ handle_string_constants(ctx, node, &state);
+ handle_objectscript_type_map(ctx, node, &state);
+ CBMInvocationDescriptor invocation = handle_calls(ctx, node, spec, &state);
+ handle_usages(ctx, node, spec, &state);
+ handle_throws(ctx, node, spec, &state);
+ handle_readwrites(ctx, node, spec, &state);
+ handle_type_refs(ctx, node, spec, &state);
+ handle_env_accesses(ctx, node, spec, &state);
+ handle_type_assigns(ctx, node, spec, &state);
+ handle_string_refs(ctx, node, &state);
+ handle_yaml_nested(ctx, node);
+ scan_infra_bindings(ctx, node);
+
+ push_boundary_scopes(ctx, node, spec, &state, depth, &invocation);
+ }
- pop_expired_scopes(&state, depth);
- recompute_state(&state, ctx->module_qn);
-
- handle_string_constants(ctx, node, &state);
- handle_objectscript_type_map(ctx, node, &state);
- handle_calls(ctx, node, spec, &state);
- handle_usages(ctx, node, spec, &state);
- handle_throws(ctx, node, spec, &state);
- handle_readwrites(ctx, node, spec, &state);
- handle_type_refs(ctx, node, spec, &state);
- handle_env_accesses(ctx, node, spec, &state);
- handle_type_assigns(ctx, node, spec, &state);
- handle_string_refs(ctx, node, &state);
- handle_yaml_nested(ctx, node);
- scan_infra_bindings(ctx, node);
-
- push_boundary_scopes(ctx, node, spec, &state, depth);
-
- if (ts_tree_cursor_goto_first_child(&cursor)) {
+ /* Lexer-terminal trivia has no semantic work and no descendants. Avoid
+ * asking the cursor to construct a child iterator for every one of
+ * hundreds of thousands of flat comment siblings. Structured extras
+ * still descend normally. */
+ if ((!trivia || ts_node_child_count(node) > 0) &&
+ ts_tree_cursor_goto_first_child(&cursor)) {
depth++;
continue;
}
@@ -1518,5 +2087,7 @@ void cbm_extract_unified(CBMExtractCtx *ctx) {
}
}
+ cbm_finalize_lexical_usages(ctx, &state);
+ ts_tree_cursor_delete(&occurrence_cursor);
ts_tree_cursor_delete(&cursor);
}
diff --git a/internal/cbm/extract_unified.h b/internal/cbm/extract_unified.h
index ac9d6b64d..1122db729 100644
--- a/internal/cbm/extract_unified.h
+++ b/internal/cbm/extract_unified.h
@@ -11,8 +11,13 @@
#define SCOPE_IMPORT 4
#define SCOPE_LOOP 5
#define SCOPE_BRANCH 6
+#define SCOPE_LEXICAL 7
+#define SCOPE_NAMESPACE 8
#define MAX_SCOPES 64
+#define INLINE_LEXICAL_SCOPES 64
+#define INLINE_LEXICAL_BINDINGS 64
+#define INLINE_PYTHON_DIRECTIVES 16
// ObjectScript type map: variable name → class name (for instance_method_call
// resolution). Stack-allocated, per-method scope. Overflow is silent (no crash).
@@ -28,30 +33,128 @@ typedef struct {
int class_base_count; // entries [0,class_base_count) survive method-scope resets
} os_type_map_t;
+// A call consumes only the exact AST occurrence that denotes its callee. The
+// rest of the call subtree (receiver, computed key, arguments, callback body)
+// remains ordinary expression input and is eligible for USAGE extraction.
+typedef enum {
+ CBM_INVOCATION_NONE = 0,
+ CBM_INVOCATION_PRIMARY,
+ CBM_INVOCATION_CALLABLE_REFERENCE,
+} CBMInvocationKind;
+
+typedef struct {
+ CBMInvocationKind kind;
+ TSNode site;
+ TSNode callee_expr;
+ TSNode callee_leaf;
+ const char *callee_name;
+ bool raw_call_emitted;
+} CBMInvocationDescriptor;
+
+typedef struct {
+ const char *qn;
+ uint32_t depth;
+ uint32_t lexical_scope_id;
+ uint8_t kind;
+ CBMInvocationKind invocation_kind;
+ TSNode callee_expr;
+ TSNode callee_leaf;
+} CBMWalkScope;
+
+typedef enum {
+ CBM_LEXICAL_SCOPE_MODULE = 0,
+ CBM_LEXICAL_SCOPE_CLASS,
+ CBM_LEXICAL_SCOPE_FUNCTION,
+ CBM_LEXICAL_SCOPE_BLOCK,
+ CBM_LEXICAL_SCOPE_COMPREHENSION,
+} CBMLexicalScopeKind;
+
+/* Concrete AST scope identity. QNs remain graph-attribution metadata only;
+ * overloads, lambdas and sibling blocks therefore never share binding facts. */
+typedef struct {
+ uint32_t id;
+ uint32_t parent_id;
+ uint32_t lookup_parent_id;
+ uint32_t start_byte;
+ uint32_t end_byte;
+ uint8_t kind;
+} CBMLexicalScope;
+
+/* Deferred binding event. Applying these after the walk represents hoisted
+ * and whole-scope rules without depending on traversal order. */
+typedef struct {
+ uint32_t scope_id;
+ uint32_t active_start;
+ uint32_t active_end;
+ const char *name;
+} CBMLexicalBinding;
+
+typedef enum {
+ CBM_PYTHON_DIRECTIVE_GLOBAL = 1,
+ CBM_PYTHON_DIRECTIVE_NONLOCAL,
+} CBMPythonDirectiveKind;
+
+typedef struct {
+ uint32_t function_scope_id;
+ const char *name;
+ uint8_t kind;
+} CBMPythonDirective;
+
// WalkState tracks scope context during the unified cursor walk.
-// Replaces parent-chain walks for enclosing_func_qn, inside_call, etc.
+// Replaces parent-chain walks for enclosing_func_qn, import context, etc.
typedef struct {
- const char *enclosing_func_qn; // current function QN (module_qn at top level)
- const char *enclosing_class_qn; // current class QN (NULL outside class)
- bool inside_call; // within a call_node_types subtree
- bool inside_import; // within an import_node_types subtree
- int loop_depth; // count of enclosing loop scopes (for bottleneck metrics)
- int branch_depth; // count of enclosing branch scopes
-
- struct {
- const char *qn;
- uint32_t depth;
- uint8_t kind;
- } scopes[MAX_SCOPES];
+ const char *enclosing_func_qn; // current function QN (module_qn at top level)
+ const char *enclosing_class_qn; // current class QN (NULL outside class)
+ const TSTreeCursor *current_cursor; // unified walk cursor at the current node
+ TSTreeCursor *occurrence_cursor; // reusable parent-preserving classifier cursor
+ CBMInvocationKind invocation_kind; // exact active invocation/reference role
+ TSNode callee_expr; // exact active callee expression, if any
+ TSNode callee_leaf; // exact active terminal callee, if any
+ bool inside_import; // within an import_node_types subtree
+ int loop_depth; // count of enclosing loop scopes (for bottleneck metrics)
+ int branch_depth; // count of enclosing branch scopes
+
+ CBMArena *arena;
+ CBMWalkScope *scopes;
+ CBMWalkScope inline_scopes[MAX_SCOPES];
+ int scope_capacity;
int scope_top;
+ CBMLexicalScope *lexical_scopes;
+ CBMLexicalScope inline_lexical_scopes[INLINE_LEXICAL_SCOPES];
+ int lexical_scope_capacity;
+ int lexical_scope_count;
+ uint32_t root_lexical_scope_id;
+ uint32_t split_function_scope_id;
+ uint32_t split_signature_start_byte;
+ uint32_t split_signature_end_byte;
+ const char *split_function_qn;
+ uint32_t flat_function_scope_id;
+ uint32_t flat_anchor_start_byte;
+ uint32_t flat_anchor_end_byte;
+ const char *flat_function_qn;
+
+ CBMLexicalBinding *lexical_bindings;
+ CBMLexicalBinding inline_lexical_bindings[INLINE_LEXICAL_BINDINGS];
+ int lexical_binding_capacity;
+ int lexical_binding_count;
+ int usage_start_index;
+ bool lexical_binding_tracking_failed;
+ CBMPythonDirective *python_directives;
+ CBMPythonDirective inline_python_directives[INLINE_PYTHON_DIRECTIVES];
+ int python_directive_capacity;
+ int python_directive_count;
+ CBMLanguage language;
+
os_type_map_t os_type_map; // ObjectScript variable → type mapping
} WalkState;
// Per-node handler prototypes. Each is called once per node during the
// unified cursor walk, replacing the old recursive walk_* functions.
-void handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state);
+CBMInvocationDescriptor handle_calls(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
+ WalkState *state);
void handle_usages(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state);
+void cbm_finalize_lexical_usages(CBMExtractCtx *ctx, WalkState *state);
void handle_throws(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state);
void handle_readwrites(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state);
void handle_type_refs(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state);
diff --git a/internal/cbm/extract_usages.c b/internal/cbm/extract_usages.c
index 16105dce9..9879cd00b 100644
--- a/internal/cbm/extract_usages.c
+++ b/internal/cbm/extract_usages.c
@@ -6,102 +6,2371 @@
#include "foundation/constants.h"
#include "extract_node_stack.h"
-enum { MAX_PARENT_DEPTH = 10, LAST_IDX = 1 };
+enum { LAST_IDX = 1 };
#include <stdint.h> // uint32_t
+#include <stdlib.h> // qsort
#include <string.h>
+#include <strings.h>
#include <ctype.h>
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+#include <stdatomic.h>
+
+static _Atomic uint64_t g_usage_field_lookup_work = 0;
+static _Atomic uint64_t g_usage_slow_parent_fallbacks = 0;
+
+void cbm_usage_field_lookup_test_reset(void) {
+ atomic_store_explicit(&g_usage_field_lookup_work, 0, memory_order_relaxed);
+ atomic_store_explicit(&g_usage_slow_parent_fallbacks, 0, memory_order_relaxed);
+}
+
+uint64_t cbm_usage_field_lookup_test_work(void) {
+ return atomic_load_explicit(&g_usage_field_lookup_work, memory_order_relaxed);
+}
+
+uint64_t cbm_usage_slow_parent_fallback_test_count(void) {
+ return atomic_load_explicit(&g_usage_slow_parent_fallbacks, memory_order_relaxed);
+}
+
+static void usage_field_lookup_test_note_work(void) {
+ atomic_fetch_add_explicit(&g_usage_field_lookup_work, 1, memory_order_relaxed);
+}
+
+static void usage_slow_parent_fallback_test_note(void) {
+ atomic_fetch_add_explicit(&g_usage_slow_parent_fallbacks, 1, memory_order_relaxed);
+}
+#else
+static void usage_field_lookup_test_note_work(void) {}
+static void usage_slow_parent_fallback_test_note(void) {}
+#endif
+
// Forward declaration
static void walk_usages(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec);
+static bool is_direct_argument_value(TSNode node);
+static TSNode python_direct_callable_attribute_site(TSNode node);
+
+// Check if a node is inside a call expression (to avoid double-counting as usage)
+static bool is_inside_call(TSNode node, const CBMLangSpec *spec) {
+ TSNode cur = ts_node_parent(node);
+ while (!ts_node_is_null(cur)) {
+ if (cbm_kind_in_set(cur, spec->call_node_types)) {
+ return true;
+ }
+ cur = ts_node_parent(cur);
+ }
+ return false;
+}
+
+// Check if a node is inside an import statement
+static bool is_inside_import(TSNode node, const CBMLangSpec *spec) {
+ bool has_imports = spec->import_node_types && spec->import_node_types[0];
+ bool has_from_imports = spec->import_from_types && spec->import_from_types[0];
+ if (!has_imports && !has_from_imports) {
+ return false;
+ }
+ TSNode cur = ts_node_parent(node);
+ while (!ts_node_is_null(cur)) {
+ if ((has_imports && cbm_kind_in_set(cur, spec->import_node_types)) ||
+ (has_from_imports && cbm_kind_in_set(cur, spec->import_from_types))) {
+ return true;
+ }
+ cur = ts_node_parent(cur);
+ }
+ return false;
+}
+
+// Is this an identifier-like node that represents a reference?
+static bool is_reference_node(TSNode node, CBMLanguage lang) {
+ const char *kind = ts_node_type(node);
+
+ /* Python's attribute node and its terminal identifier describe the same
+ * source occurrence. For a direct callable-value argument, keep the leaf
+ * as the raw carrier (so unresolved cases retain a useful short-name
+ * USAGE) and stamp it with the full attribute span below. Receivers remain
+ * independent value references. */
+ if (lang == CBM_LANG_PYTHON && strcmp(kind, "attribute") == 0 &&
+ !ts_node_is_null(python_direct_callable_attribute_site(node))) {
+ return false;
+ }
+
+ /* A Rust scoped_identifier owns the complete path occurrence. Its nested
+ * path/identifier children are grammar structure, not additional value
+ * references; keeping them would let a short-name fallback bind a decoy. */
+ if (lang == CBM_LANG_RUST &&
+ (strcmp(kind, "identifier") == 0 || strcmp(kind, "scoped_identifier") == 0)) {
+ TSNode parent = ts_node_parent(node);
+ if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "scoped_identifier") == 0) {
+ return false;
+ }
+ }
+
+ /* Some grammars expose the sigil/scope as a named wrapper around a generic
+ * identifier. Keep exactly one occurrence: the wrapper carries the source
+ * spelling that resolution needs (`$watched`, `a:watched`). */
+ if (strcmp(kind, "identifier") == 0) {
+ TSNode parent = ts_node_parent(node);
+ if (!ts_node_is_null(parent) &&
+ ((lang == CBM_LANG_PUPPET && strcmp(ts_node_type(parent), "variable") == 0) ||
+ (lang == CBM_LANG_VIMSCRIPT && strcmp(ts_node_type(parent), "argument") == 0))) {
+ return false;
+ }
+ }
+
+ // Common identifier types across languages
+ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ||
+ strcmp(kind, "type_identifier") == 0) {
+ return true;
+ }
+
+ // Language-specific reference types
+ switch (lang) {
+ case CBM_LANG_JAVASCRIPT:
+ case CBM_LANG_TYPESCRIPT:
+ case CBM_LANG_TSX:
+ case CBM_LANG_QML:
+ case CBM_LANG_CFSCRIPT:
+ return strcmp(kind, "property_identifier") == 0 ||
+ strcmp(kind, "private_property_identifier") == 0;
+ case CBM_LANG_GO:
+ return strcmp(kind, "field_identifier") == 0 || strcmp(kind, "package_identifier") == 0;
+ case CBM_LANG_PYTHON:
+ return strcmp(kind, "attribute") == 0;
+ case CBM_LANG_RUST:
+ return strcmp(kind, "field_identifier") == 0 || strcmp(kind, "scoped_identifier") == 0;
+ case CBM_LANG_C:
+ case CBM_LANG_CPP:
+ case CBM_LANG_CUDA:
+ return strcmp(kind, "field_identifier") == 0;
+ case CBM_LANG_PHP:
+ return strcmp(kind, "name") == 0 || strcmp(kind, "variable_name") == 0;
+ case CBM_LANG_HASKELL:
+ return strcmp(kind, "variable") == 0 || strcmp(kind, "constructor") == 0;
+ case CBM_LANG_OCAML:
+ return strcmp(kind, "value_path") == 0 || strcmp(kind, "constructor_path") == 0;
+ case CBM_LANG_ERLANG:
+ return strcmp(kind, "atom") == 0 || strcmp(kind, "var") == 0;
+ case CBM_LANG_CSS:
+ /* Custom-property reads inside `var(...)` are exposed as plain_value;
+ * declarations use the separate property_name alias. */
+ return strcmp(kind, "plain_value") == 0;
+ case CBM_LANG_SCSS:
+ /* SCSS value occurrences retain their `$` spelling in variable_value;
+ * declaration parameters use the distinct variable_name node. */
+ return strcmp(kind, "variable_value") == 0;
+ case CBM_LANG_LLVM_IR:
+ return strcmp(kind, "local_var") == 0 || strcmp(kind, "global_var") == 0;
+ case CBM_LANG_PUPPET:
+ case CBM_LANG_POWERSHELL:
+ /* Puppet keeps the sigil in a dedicated `variable` node (`$watched`). */
+ return strcmp(kind, "variable") == 0;
+ case CBM_LANG_BASH:
+ case CBM_LANG_FISH:
+ case CBM_LANG_ZSH:
+ /* Expansion wrappers retain `$`; their named leaf is the bare variable name. */
+ return strcmp(kind, "variable_name") == 0;
+ case CBM_LANG_PERL:
+ /* Perl's named scalar node retains its sigil (`$watched`). */
+ return strcmp(kind, "scalar") == 0;
+ case CBM_LANG_CLOJURE:
+ case CBM_LANG_COMMONLISP:
+ return strcmp(kind, "sym_lit") == 0;
+ case CBM_LANG_VIMSCRIPT:
+ return strcmp(kind, "scoped_identifier") == 0 || strcmp(kind, "argument") == 0;
+ case CBM_LANG_ELM:
+ return strcmp(kind, "lower_case_identifier") == 0;
+ case CBM_LANG_COBOL:
+ return strcmp(kind, "qualified_word") == 0;
+ case CBM_LANG_EMACSLISP:
+ case CBM_LANG_SCHEME:
+ case CBM_LANG_FENNEL:
+ case CBM_LANG_RACKET:
+ case CBM_LANG_LINKERSCRIPT:
+ return strcmp(kind, "symbol") == 0;
+ case CBM_LANG_MAKEFILE:
+ return strcmp(kind, "variable_reference") == 0;
+ case CBM_LANG_CMAKE:
+ /* `${watched}` contains a named `variable` leaf spanning only `watched`. */
+ return strcmp(kind, "variable") == 0;
+ case CBM_LANG_WOLFRAM:
+ return strcmp(kind, "user_symbol") == 0;
+ case CBM_LANG_TYPST:
+ return strcmp(kind, "ident") == 0;
+ case CBM_LANG_TCL:
+ /* Tcl's value spelling includes the sigil, so retain the substitution wrapper. */
+ return strcmp(kind, "variable_substitution") == 0;
+ case CBM_LANG_TLAPLUS:
+ /* Definition-side names/parameters are `identifier`; expression-side
+ * values and operator arguments use the distinct `identifier_ref`. */
+ return strcmp(kind, "identifier_ref") == 0;
+ case CBM_LANG_AGDA:
+ /* `_qid` is hidden and aliases its public expression leaf to `qid`. */
+ return strcmp(kind, "qid") == 0;
+ case CBM_LANG_RESCRIPT:
+ return strcmp(kind, "value_identifier") == 0;
+ case CBM_LANG_PURESCRIPT:
+ return strcmp(kind, "variable") == 0;
+ case CBM_LANG_NICKEL:
+ return strcmp(kind, "ident") == 0;
+ case CBM_LANG_JSONNET:
+ return strcmp(kind, "id") == 0;
+ case CBM_LANG_CFML:
+ return strcmp(kind, "property_identifier") == 0;
+ case CBM_LANG_OBJECTSCRIPT_UDL:
+ case CBM_LANG_OBJECTSCRIPT_ROUTINE:
+ return strcmp(kind, "objectscript_identifier") == 0 ||
+ strcmp(kind, "objectscript_identifier_special") == 0;
+ default:
+ return false;
+ }
+}
+
+static bool node_contains(TSNode outer, TSNode inner) {
+ return !ts_node_is_null(outer) && !ts_node_is_null(inner) &&
+ ts_node_start_byte(outer) <= ts_node_start_byte(inner) &&
+ ts_node_end_byte(outer) >= ts_node_end_byte(inner);
+}
+
+static bool vhdl_forward_callee_wrapper(TSNode node) {
+ const char *kind = ts_node_type(node);
+ return strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ||
+ strcmp(kind, "library_function") == 0 || strcmp(kind, "name") == 0 ||
+ strcmp(kind, "simple_name") == 0;
+}
+
+static TSNode terminal_vhdl_identifier(TSNode node, int remaining_depth) {
+ if (ts_node_is_null(node) || remaining_depth < 0) {
+ return (TSNode){0};
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = count; i > 0; i--) {
+ TSNode found =
+ terminal_vhdl_identifier(ts_node_named_child(node, i - 1), remaining_depth - 1);
+ if (!ts_node_is_null(found)) {
+ return found;
+ }
+ }
+ const char *kind = ts_node_type(node);
+ return strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ? node
+ : (TSNode){0};
+}
+
+// Dart and VHDL represent some calls as a callee node immediately followed by
+// the invocation node. The unified pre-order walk has already visited that
+// callee when the call descriptor is created, so suppress only the exact
+// language-specific preceding occurrence. Do not generalize this to arbitrary
+// identifiers: a sibling selector/parenthesis group is the grammar contract.
+static bool is_forward_sibling_callee(CBMLanguage language, TSNode node) {
+ if (language == CBM_LANG_DART && strcmp(ts_node_type(node), "identifier") == 0) {
+ TSNode next = ts_node_next_named_sibling(node);
+ return !ts_node_is_null(next) && strcmp(ts_node_type(next), "selector") == 0;
+ }
+
+ if (language != CBM_LANG_VHDL) {
+ return false;
+ }
+
+ TSNode owner = node;
+ for (int depth = 0; depth < 4 && vhdl_forward_callee_wrapper(owner); depth++) {
+ TSNode next = ts_node_next_named_sibling(owner);
+ if (!ts_node_is_null(next) && strcmp(ts_node_type(next), "parenthesis_group") == 0) {
+ TSNode leaf = terminal_vhdl_identifier(owner, 8);
+ return !ts_node_is_null(leaf) && ts_node_eq(node, leaf);
+ }
+ TSNode parent = ts_node_parent(owner);
+ if (ts_node_is_null(parent) || !vhdl_forward_callee_wrapper(parent)) {
+ break;
+ }
+ owner = parent;
+ }
+ return false;
+}
+
+static const char *field_name_for_node(TSNode parent, TSNode child) {
+ const char *field = NULL;
+ TSTreeCursor cursor = ts_tree_cursor_new(parent);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ usage_field_lookup_test_note_work();
+ if (ts_node_eq(ts_tree_cursor_current_node(&cursor), child)) {
+ field = ts_tree_cursor_current_field_name(&cursor);
+ break;
+ }
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
+ return field;
+}
+
+/* The unified walk already owns the exact cursor path to the current node.
+ * Reset one reusable scratch cursor to that path before each occurrence
+ * classifier, then walk its parents without restarting a sibling scan at
+ * every level. Legacy extraction callers retain the node-based fallback. */
+static TSTreeCursor *reset_occurrence_cursor(WalkState *state, TSNode node) {
+ if (!state || !state->current_cursor || !state->occurrence_cursor ||
+ !ts_node_eq(ts_tree_cursor_current_node(state->current_cursor), node)) {
+ return NULL;
+ }
+ ts_tree_cursor_reset_to(state->occurrence_cursor, state->current_cursor);
+ return state->occurrence_cursor;
+}
+
+static bool occurrence_parent(TSTreeCursor *cursor, TSNode current, TSNode *parent,
+ const char **field) {
+ if (cursor) {
+ *field = ts_tree_cursor_current_field_name(cursor);
+ usage_field_lookup_test_note_work();
+ if (!ts_tree_cursor_goto_parent(cursor)) {
+ *parent = (TSNode){0};
+ return false;
+ }
+ *parent = ts_tree_cursor_current_node(cursor);
+ return true;
+ }
+
+ *parent = ts_node_parent(current);
+ if (ts_node_is_null(*parent)) {
+ *field = NULL;
+ return false;
+ }
+ *field = field_name_for_node(*parent, current);
+ return true;
+}
+
+static const char *field_name_for_walk_node(WalkState *state, TSNode parent, TSNode node) {
+ if (state && state->current_cursor &&
+ ts_node_eq(ts_tree_cursor_current_node(state->current_cursor), node)) {
+ usage_field_lookup_test_note_work();
+ return ts_tree_cursor_current_field_name(state->current_cursor);
+ }
+ return field_name_for_node(parent, node);
+}
+
+static bool is_value_field(const char *field) {
+ return field && (strcmp(field, "value") == 0 || strcmp(field, "right") == 0 ||
+ strcmp(field, "initializer") == 0 || strcmp(field, "default") == 0 ||
+ strcmp(field, "default_value") == 0 || strcmp(field, "body") == 0 ||
+ strcmp(field, "arguments") == 0 || strcmp(field, "condition") == 0 ||
+ strcmp(field, "consequence") == 0 || strcmp(field, "alternative") == 0 ||
+ strcmp(field, "expression") == 0 || strcmp(field, "result") == 0);
+}
+
+static bool kind_in_exact_set(const char *kind, const char *const *set) {
+ if (!kind || !set) {
+ return false;
+ }
+ for (const char *const *candidate = set; *candidate; candidate++) {
+ if (strcmp(kind, *candidate) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool field_contains_node(TSNode parent, const char *field, TSNode node) {
+ TSNode value = ts_node_child_by_field_name(parent, field, (uint32_t)strlen(field));
+ return node_contains(value, node);
+}
+
+typedef enum {
+ CBM_OCCURRENCE_STANDARD = 0,
+ CBM_OCCURRENCE_LISP_DEF,
+ CBM_OCCURRENCE_COMMONLISP_DEFUN,
+ CBM_OCCURRENCE_FENNEL_FN,
+ CBM_OCCURRENCE_ELIXIR_DEF,
+ CBM_OCCURRENCE_JULIA_FUNCTION,
+ CBM_OCCURRENCE_WOLFRAM_SET,
+ CBM_OCCURRENCE_TYPST_LET,
+ CBM_OCCURRENCE_AGDA_FUNCTION,
+ CBM_OCCURRENCE_TLAPLUS_OPERATOR,
+ CBM_OCCURRENCE_COBOL_MOVE,
+ CBM_OCCURRENCE_HCL_ATTRIBUTE,
+ CBM_OCCURRENCE_ELM_VALUE,
+ CBM_OCCURRENCE_RESCRIPT_LET,
+ CBM_OCCURRENCE_PURESCRIPT_LHS,
+ CBM_OCCURRENCE_NICKEL_LET,
+ CBM_OCCURRENCE_ERLANG_CLAUSE,
+ CBM_OCCURRENCE_NIX_FUNCTION,
+ CBM_OCCURRENCE_MATLAB_ARGUMENTS,
+ CBM_OCCURRENCE_LEAN_BINDER,
+ CBM_OCCURRENCE_PASCAL_PROC,
+ CBM_OCCURRENCE_TEAL_FUNCTION,
+ CBM_OCCURRENCE_VHDL_INTERFACE,
+ CBM_OCCURRENCE_PINE_FUNCTION,
+ CBM_OCCURRENCE_LLVM_FUNCTION,
+} CBMOccurrencePolicy;
+
+typedef struct {
+ const char *const *whole_binding_nodes;
+ const char *const *write_nodes;
+ CBMOccurrencePolicy policy;
+ bool first_named_child_is_write;
+} CBMOccurrenceSpec;
+
+/* These are exact grammar roles, not name fragments. Default/value/body
+ * fields are barriers, so an initializer nested below one of these containers
+ * remains a read. */
+static const char *const common_whole_binding_nodes[] = {"formal_parameter",
+ "formal_parameters",
+ "parameter",
+ "parameters",
+ "parameter_list",
+ "parameter_declaration",
+ "parameter_specification",
+ "required_parameter",
+ "optional_parameter",
+ "default_parameter",
+ "typed_parameter",
+ "function_value_parameter",
+ "function_value_parameters",
+ "lambda_parameter",
+ "lambda_parameters",
+ "function_parameter_declaration",
+ "closure_parameters",
+ "block_parameters",
+ "receiver",
+ NULL};
+
+static const char *const field_binding_nodes[] = {"variable_declarator",
+ "init_declarator",
+ "variable_declaration",
+ "const_declaration",
+ "lexical_declaration",
+ "short_var_declaration",
+ "local_variable_declaration",
+ "property_declaration",
+ "field_declaration",
+ "value_declaration",
+ "val_definition",
+ "var_definition",
+ "let_declaration",
+ "local_bind",
+ "let_binding",
+ "data_declaration",
+ "net_declaration",
+ "object_declaration",
+ "number_declaration",
+ "typed_binding",
+ "variable_assignment",
+ NULL};
+
+static const char *const binding_fields[] = {"name", "pattern", "declarator", "parameter",
+ "parameters", "left", "variable", "variables",
+ "key", NULL};
+
+static const char *const sql_binding_nodes[] = {"function_argument", NULL};
+static const char *const haskell_binding_nodes[] = {"patterns", NULL};
+static const char *const fsharp_binding_nodes[] = {
+ "function_declaration_left", "value_declaration_left", "argument_patterns", NULL};
+static const char *const crystal_binding_nodes[] = {"param_list", NULL};
+static const char *const awk_binding_nodes[] = {"param_list", NULL};
+static const char *const teal_binding_nodes[] = {"function_signature", NULL};
+static const char *const systemverilog_binding_nodes[] = {"tf_port_item", "tf_port_item1", NULL};
+static const char *const rescript_binding_nodes[] = {"formal_parameters", "labeled_parameter",
+ "parameter", NULL};
+static const char *const purescript_binding_nodes[] = {"bind_pattern", "pattern", "patterns", NULL};
+static const char *const nickel_binding_nodes[] = {"pattern_fun", NULL};
+static const char *const jsonnet_binding_nodes[] = {"param", NULL};
+static const char *const llvm_binding_nodes[] = {"function_header", NULL};
+static const char *const linkerscript_write_nodes[] = {"assignment", NULL};
+static const char *const meson_write_nodes[] = {"operatorunit", NULL};
+static const char *const gn_write_nodes[] = {"assignment_statement", NULL};
+static const char *const objectscript_binding_nodes[] = {"argument", "tag_parameter", NULL};
+static const char *const objectscript_write_nodes[] = {"set_argument", NULL};
+
+/* Parallel to lang_specs: occurrence semantics evolve without adding fields to
+ * the positional CBMLangSpec initializer used by every language. */
+static const CBMOccurrenceSpec occurrence_specs[CBM_LANG_COUNT] = {
+ [CBM_LANG_SQL] = {sql_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_CLOJURE] = {NULL, NULL, CBM_OCCURRENCE_LISP_DEF, false},
+ [CBM_LANG_SCHEME] = {NULL, NULL, CBM_OCCURRENCE_LISP_DEF, false},
+ [CBM_LANG_RACKET] = {NULL, NULL, CBM_OCCURRENCE_LISP_DEF, false},
+ [CBM_LANG_COMMONLISP] = {NULL, NULL, CBM_OCCURRENCE_COMMONLISP_DEFUN, false},
+ [CBM_LANG_FENNEL] = {NULL, NULL, CBM_OCCURRENCE_FENNEL_FN, false},
+ [CBM_LANG_ELIXIR] = {NULL, NULL, CBM_OCCURRENCE_ELIXIR_DEF, false},
+ [CBM_LANG_JULIA] = {NULL, NULL, CBM_OCCURRENCE_JULIA_FUNCTION, false},
+ [CBM_LANG_WOLFRAM] = {NULL, NULL, CBM_OCCURRENCE_WOLFRAM_SET, false},
+ [CBM_LANG_TYPST] = {NULL, NULL, CBM_OCCURRENCE_TYPST_LET, false},
+ [CBM_LANG_AGDA] = {NULL, NULL, CBM_OCCURRENCE_AGDA_FUNCTION, false},
+ [CBM_LANG_TLAPLUS] = {NULL, NULL, CBM_OCCURRENCE_TLAPLUS_OPERATOR, false},
+ [CBM_LANG_COBOL] = {NULL, NULL, CBM_OCCURRENCE_COBOL_MOVE, false},
+ [CBM_LANG_HCL] = {NULL, NULL, CBM_OCCURRENCE_HCL_ATTRIBUTE, false},
+ [CBM_LANG_ELM] = {NULL, NULL, CBM_OCCURRENCE_ELM_VALUE, false},
+ [CBM_LANG_RESCRIPT] = {rescript_binding_nodes, NULL, CBM_OCCURRENCE_RESCRIPT_LET, false},
+ [CBM_LANG_PURESCRIPT] = {purescript_binding_nodes, NULL, CBM_OCCURRENCE_PURESCRIPT_LHS, false},
+ [CBM_LANG_NICKEL] = {nickel_binding_nodes, NULL, CBM_OCCURRENCE_NICKEL_LET, false},
+ [CBM_LANG_JSONNET] = {jsonnet_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_HASKELL] = {haskell_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_ERLANG] = {NULL, NULL, CBM_OCCURRENCE_ERLANG_CLAUSE, false},
+ [CBM_LANG_FSHARP] = {fsharp_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_NIX] = {NULL, NULL, CBM_OCCURRENCE_NIX_FUNCTION, false},
+ [CBM_LANG_MATLAB] = {NULL, NULL, CBM_OCCURRENCE_MATLAB_ARGUMENTS, false},
+ [CBM_LANG_LEAN] = {NULL, NULL, CBM_OCCURRENCE_LEAN_BINDER, false},
+ [CBM_LANG_PASCAL] = {NULL, NULL, CBM_OCCURRENCE_PASCAL_PROC, false},
+ [CBM_LANG_VERILOG] = {systemverilog_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_AWK] = {awk_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_CRYSTAL] = {crystal_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_TEAL] = {teal_binding_nodes, NULL, CBM_OCCURRENCE_TEAL_FUNCTION, false},
+ [CBM_LANG_VHDL] = {NULL, NULL, CBM_OCCURRENCE_VHDL_INTERFACE, false},
+ [CBM_LANG_SYSTEMVERILOG] = {systemverilog_binding_nodes, NULL, CBM_OCCURRENCE_STANDARD, false},
+ [CBM_LANG_PINE] = {NULL, NULL, CBM_OCCURRENCE_PINE_FUNCTION, false},
+ [CBM_LANG_PUPPET] = {NULL, NULL, CBM_OCCURRENCE_STANDARD, true},
+ [CBM_LANG_LLVM_IR] = {llvm_binding_nodes, NULL, CBM_OCCURRENCE_LLVM_FUNCTION, false},
+ [CBM_LANG_MESON] = {NULL, meson_write_nodes, CBM_OCCURRENCE_STANDARD, true},
+ [CBM_LANG_GN] = {NULL, gn_write_nodes, CBM_OCCURRENCE_STANDARD, true},
+ [CBM_LANG_LINKERSCRIPT] = {NULL, linkerscript_write_nodes, CBM_OCCURRENCE_STANDARD, true},
+ [CBM_LANG_OBJECTSCRIPT_UDL] = {objectscript_binding_nodes, objectscript_write_nodes,
+ CBM_OCCURRENCE_STANDARD, true},
+ [CBM_LANG_OBJECTSCRIPT_ROUTINE] = {objectscript_binding_nodes, objectscript_write_nodes,
+ CBM_OCCURRENCE_STANDARD, true},
+};
+
+static bool text_equals(CBMExtractCtx *ctx, TSNode node, const char *expected) {
+ char *text = cbm_node_text(ctx->arena, node, ctx->source);
+ return text && strcmp(text, expected) == 0;
+}
+
+static bool named_child_contains(TSNode parent, uint32_t index, TSNode node) {
+ return ts_node_named_child_count(parent) > index &&
+ node_contains(ts_node_named_child(parent, index), node);
+}
+
+static bool lisp_def_head(const char *text) {
+ static const char *const heads[] = {"defn",
+ "defn-",
+ "def",
+ "defmacro",
+ "defmulti",
+ "defmethod",
+ "defprotocol",
+ "defrecord",
+ "deftype",
+ "definterface",
+ "defonce",
+ "define",
+ "define-syntax",
+ "define-values",
+ "define-struct",
+ "define-record-type",
+ "define/contract",
+ "struct",
+ NULL};
+ return kind_in_exact_set(text, heads);
+}
+
+static bool is_lisp_def_binding(CBMExtractCtx *ctx, TSNode node) {
+ for (TSNode form = ts_node_parent(node); !ts_node_is_null(form); form = ts_node_parent(form)) {
+ const char *kind = ts_node_type(form);
+ if ((strcmp(kind, "list") != 0 && strcmp(kind, "list_lit") != 0) ||
+ ts_node_named_child_count(form) < 2) {
+ continue;
+ }
+ TSNode head_node = ts_node_named_child(form, 0);
+ char *head = cbm_node_text(ctx->arena, head_node, ctx->source);
+ if (!lisp_def_head(head)) {
+ continue;
+ }
+ if (node_contains(head_node, node) || named_child_contains(form, 1, node)) {
+ return true;
+ }
+ if (ctx->language == CBM_LANG_CLOJURE && ts_node_named_child_count(form) > 2 &&
+ named_child_contains(form, 2, node)) {
+ return true;
+ }
+ return false;
+ }
+ return false;
+}
+
+static bool is_fennel_fn_binding(CBMExtractCtx *ctx, TSNode node) {
+ for (TSNode form = ts_node_parent(node); !ts_node_is_null(form); form = ts_node_parent(form)) {
+ if (strcmp(ts_node_type(form), "list") != 0 || ts_node_named_child_count(form) < 2 ||
+ !text_equals(ctx, ts_node_named_child(form, 0), "fn")) {
+ continue;
+ }
+ TSNode first = ts_node_named_child(form, 1);
+ const char *first_kind = ts_node_type(first);
+ bool anonymous = strcmp(first_kind, "sequence") == 0 || strcmp(first_kind, "table") == 0 ||
+ strcmp(first_kind, "vector") == 0;
+ if (anonymous) {
+ return named_child_contains(form, 0, node) || node_contains(first, node);
+ }
+ return named_child_contains(form, 0, node) || node_contains(first, node) ||
+ (ts_node_named_child_count(form) > 2 && named_child_contains(form, 2, node));
+ }
+ return false;
+}
+
+static bool is_elixir_def_binding(CBMExtractCtx *ctx, TSNode node) {
+ for (TSNode form = ts_node_parent(node); !ts_node_is_null(form); form = ts_node_parent(form)) {
+ if (strcmp(ts_node_type(form), "call") != 0 || ts_node_named_child_count(form) < 2) {
+ continue;
+ }
+ TSNode head = ts_node_named_child(form, 0);
+ if (!text_equals(ctx, head, "def") && !text_equals(ctx, head, "defp") &&
+ !text_equals(ctx, head, "defmacro")) {
+ continue;
+ }
+ TSNode arguments = ts_node_child_by_field_name(form, TS_FIELD("arguments"));
+ if (ts_node_is_null(arguments) || ts_node_named_child_count(arguments) == 0) {
+ arguments = ts_node_named_child(form, 1);
+ }
+ TSNode signature = ts_node_named_child_count(arguments) > 0
+ ? ts_node_named_child(arguments, 0)
+ : arguments;
+ return node_contains(head, node) || node_contains(signature, node);
+ }
+ return false;
+}
+
+static bool is_first_named_part_of(TSNode node, const char *container_kind) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), container_kind) == 0) {
+ return named_child_contains(parent, 0, node);
+ }
+ }
+ return false;
+}
+
+static bool is_wolfram_lhs(TSNode node) {
+ static const char *const set_nodes[] = {
+ "set", "set_top", "set_delayed", "set_delayed_top",
+ "tag_set", "tag_set_top", "tag_set_delayed", "tag_set_delayed_top",
+ "up_set", "up_set_top", "up_set_delayed", "up_set_delayed_top",
+ NULL};
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (kind_in_exact_set(ts_node_type(parent), set_nodes)) {
+ return named_child_contains(parent, 0, node);
+ }
+ }
+ return false;
+}
+
+static bool any_field_contains_node(TSNode parent, const char *field, TSNode node);
+
+static bool is_tlaplus_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "operator_definition") == 0) {
+ /* `name:` is the callable declaration, while every repeated
+ * `parameter:` field is a function-wide lexical binder. */
+ return any_field_contains_node(parent, "parameter", node);
+ }
+ if (strcmp(kind, "function_definition") == 0) {
+ /* `F[x \in S] == ...`: only quantifier_bound.intro binds. The set
+ * expression S remains an ordinary identifier_ref usage. */
+ for (TSNode bound = ts_node_parent(node);
+ !ts_node_is_null(bound) && !ts_node_eq(bound, parent);
+ bound = ts_node_parent(bound)) {
+ if (strcmp(ts_node_type(bound), "quantifier_bound") == 0) {
+ return any_field_contains_node(bound, "intro", node);
+ }
+ }
+ return false;
+ }
+ if (strcmp(kind, "bounded_quantification") == 0) {
+ for (TSNode bound = ts_node_parent(node);
+ !ts_node_is_null(bound) && !ts_node_eq(bound, parent);
+ bound = ts_node_parent(bound)) {
+ if (strcmp(ts_node_type(bound), "quantifier_bound") == 0) {
+ return any_field_contains_node(bound, "intro", node);
+ }
+ }
+ return false;
+ }
+ if (strcmp(kind, "unbounded_quantification") == 0) {
+ return any_field_contains_node(parent, "intro", node);
+ }
+ }
+ return false;
+}
+
+static bool is_cobol_move_destination(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "move_statement") != 0) {
+ continue;
+ }
+ if (field_contains_node(parent, "destination", node) ||
+ field_contains_node(parent, "target", node)) {
+ return true;
+ }
+ uint32_t count = ts_node_named_child_count(parent);
+ return count > 1 && named_child_contains(parent, count - 1, node);
+ }
+ return false;
+}
+
+/* Some grammars expose declaration roles as repeated/inherited fields. The
+ * public child-by-field helper returns only one match, so inspect every direct
+ * child and preserve the exact field role while allowing nested wrappers. */
+static bool any_field_contains_node(TSNode parent, const char *field, TSNode node) {
+ uint32_t count = ts_node_child_count(parent);
+ for (uint32_t i = 0; i < count; i++) {
+ const char *child_field = ts_node_field_name_for_child(parent, i);
+ if (child_field && strcmp(child_field, field) == 0 &&
+ node_contains(ts_node_child(parent, i), node)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool is_perl_lexical_declaration_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "variable_declaration") == 0) {
+ /* Perl permits repeated `variables:` fields for `my ($a, $b)`;
+ * inspect all direct field instances, not only the first. */
+ return any_field_contains_node(parent, "variables", node);
+ }
+ if (strcmp(ts_node_type(parent), "assignment_expression") == 0) {
+ return false;
+ }
+ }
+ return false;
+}
+
+static bool is_cmake_function_parameter(TSNode node) {
+ if (strcmp(ts_node_type(node), "unquoted_argument") != 0) {
+ return false;
+ }
+ TSNode argument = ts_node_parent(node);
+ TSNode arguments = ts_node_parent(argument);
+ TSNode command = ts_node_parent(arguments);
+ if (ts_node_is_null(argument) || strcmp(ts_node_type(argument), "argument") != 0 ||
+ ts_node_is_null(arguments) || strcmp(ts_node_type(arguments), "argument_list") != 0 ||
+ ts_node_is_null(command) ||
+ (strcmp(ts_node_type(command), "function_command") != 0 &&
+ strcmp(ts_node_type(command), "macro_command") != 0)) {
+ return false;
+ }
+ uint32_t count = ts_node_named_child_count(arguments);
+ for (uint32_t i = 1; i < count; i++) {
+ if (node_contains(ts_node_named_child(arguments, i), node)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool fish_argument_marker(CBMExtractCtx *ctx, TSNode node) {
+ char *text = cbm_node_text(ctx->arena, node, ctx->source);
+ return text && (strcmp(text, "-a") == 0 || strcmp(text, "--argument") == 0 ||
+ strcmp(text, "--argument-names") == 0);
+}
+
+static bool is_fish_function_parameter(CBMExtractCtx *ctx, TSNode node, WalkState *state) {
+ if (strcmp(ts_node_type(node), "word") != 0) {
+ return false;
+ }
+ TSNode definition = ts_node_parent(node);
+ const char *field =
+ ts_node_is_null(definition) ? NULL : field_name_for_walk_node(state, definition, node);
+ if (!field || strcmp(field, "option") != 0 ||
+ strcmp(ts_node_type(definition), "function_definition") != 0) {
+ return false;
+ }
+ for (TSNode previous = ts_node_prev_named_sibling(node); !ts_node_is_null(previous);
+ previous = ts_node_prev_named_sibling(previous)) {
+ char *text = cbm_node_text(ctx->arena, previous, ctx->source);
+ if (!text || text[0] != '-') {
+ continue;
+ }
+ return fish_argument_marker(ctx, previous);
+ }
+ return false;
+}
+
+static bool is_tcl_procedure_parameter(TSNode node) {
+ TSNode argument = ts_node_parent(node);
+ if (ts_node_is_null(argument) || strcmp(ts_node_type(argument), "argument") != 0 ||
+ !any_field_contains_node(argument, "name", node)) {
+ return false;
+ }
+ TSNode arguments = ts_node_parent(argument);
+ TSNode procedure = ts_node_parent(arguments);
+ return !ts_node_is_null(arguments) && strcmp(ts_node_type(arguments), "arguments") == 0 &&
+ !ts_node_is_null(procedure) && strcmp(ts_node_type(procedure), "procedure") == 0 &&
+ any_field_contains_node(procedure, "arguments", node);
+}
+
+static bool cfml_argument_tag_name_binding(CBMExtractCtx *ctx, TSNode node) {
+ if (strcmp(ts_node_type(node), "attribute_value") != 0) {
+ return false;
+ }
+ TSNode quoted = ts_node_parent(node);
+ TSNode attribute = ts_node_parent(quoted);
+ if (ts_node_is_null(attribute) || strcmp(ts_node_type(attribute), "cf_attribute") != 0) {
+ return false;
+ }
+ TSNode attribute_name = cbm_find_child_by_kind(attribute, "cf_attribute_name");
+ char *name_text = cbm_node_text(ctx->arena, attribute_name, ctx->source);
+ if (!name_text || strcasecmp(name_text, "name") != 0) {
+ return false;
+ }
+ TSNode tag = ts_node_parent(attribute);
+ if (ts_node_is_null(tag) || strcmp(ts_node_type(tag), "cf_selfclose_tag") != 0) {
+ return false;
+ }
+ char *tag_text = cbm_node_text(ctx->arena, tag, ctx->source);
+ static const char argument_tag[] = "<cfargument";
+ size_t prefix_length = sizeof(argument_tag) - 1U;
+ if (!tag_text || strncasecmp(tag_text, argument_tag, prefix_length) != 0 ||
+ (tag_text[prefix_length] != '\0' && !isspace((unsigned char)tag_text[prefix_length]) &&
+ tag_text[prefix_length] != '>' && tag_text[prefix_length] != '/')) {
+ return false;
+ }
+ for (TSNode parent = ts_node_parent(tag); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "cf_function_tag") == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool is_exact_language_binding(CBMExtractCtx *ctx, TSNode node, WalkState *state) {
+ const char *kind = ts_node_type(node);
+ switch (ctx->language) {
+ case CBM_LANG_OCAML: {
+ if (strcmp(kind, "value_pattern") != 0) {
+ return false;
+ }
+ TSNode parameter = ts_node_parent(node);
+ return !ts_node_is_null(parameter) && strcmp(ts_node_type(parameter), "parameter") == 0 &&
+ field_contains_node(parameter, "pattern", node);
+ }
+ case CBM_LANG_SCSS: {
+ if (strcmp(kind, "variable_name") != 0) {
+ return false;
+ }
+ TSNode parameter = ts_node_parent(node);
+ return !ts_node_is_null(parameter) && strcmp(ts_node_type(parameter), "parameter") == 0;
+ }
+ case CBM_LANG_FORM: {
+ if (strcmp(kind, "parameter") != 0) {
+ return false;
+ }
+ TSNode parameters = ts_node_parent(node);
+ return !ts_node_is_null(parameters) &&
+ strcmp(ts_node_type(parameters), "parameter_list") == 0;
+ }
+ case CBM_LANG_FUNC: {
+ if (strcmp(kind, "parameter") != 0) {
+ return false;
+ }
+ TSNode declaration = ts_node_parent(node);
+ return !ts_node_is_null(declaration) &&
+ strcmp(ts_node_type(declaration), "parameter_declaration") == 0 &&
+ field_contains_node(declaration, "name", node);
+ }
+ case CBM_LANG_PERL:
+ return is_perl_lexical_declaration_binding(node);
+ case CBM_LANG_CMAKE:
+ return is_cmake_function_parameter(node);
+ case CBM_LANG_FISH:
+ return is_fish_function_parameter(ctx, node, state);
+ case CBM_LANG_TCL:
+ return is_tcl_procedure_parameter(node);
+ case CBM_LANG_CFML:
+ return cfml_argument_tag_name_binding(ctx, node);
+ default:
+ return false;
+ }
+}
+
+static bool ancestor_field_binds(TSNode node, const char *container_kind,
+ const char *const *fields) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), container_kind) != 0) {
+ continue;
+ }
+ for (const char *const *field = fields; *field; field++) {
+ if (any_field_contains_node(parent, *field, node)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return false;
+}
+
+static bool is_erlang_clause_binding(TSNode node) {
+ static const char *const fields[] = {"args", NULL};
+ return ancestor_field_binds(node, "function_clause", fields);
+}
+
+static bool is_nix_function_binding(TSNode node) {
+ /* tree-sitter-nix names a simple `x: body` binder `universal`; set
+ * destructuring uses the distinct `formals` field. */
+ static const char *const fields[] = {"universal", "formals", NULL};
+ return ancestor_field_binds(node, "function_expression", fields);
+}
+
+static bool is_lean_binder_name(TSNode node) {
+ static const char *const binder_kinds[] = {"explicit_binder", "implicit_binder",
+ "instance_binder", NULL};
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (kind_in_exact_set(ts_node_type(parent), binder_kinds)) {
+ return any_field_contains_node(parent, "name", node);
+ }
+ }
+ return false;
+}
+
+static bool is_pascal_proc_binding(TSNode node) {
+ static const char *const fields[] = {"args", NULL};
+ return ancestor_field_binds(node, "declProc", fields) ||
+ ancestor_field_binds(node, "defProc", fields);
+}
+
+static bool is_teal_function_binding(TSNode node) {
+ TSNode arguments = {0};
+ for (TSNode current = ts_node_parent(node); !ts_node_is_null(current);
+ current = ts_node_parent(current)) {
+ const char *kind = ts_node_type(current);
+ if (ts_node_is_null(arguments) && strcmp(kind, "arguments") == 0) {
+ arguments = current;
+ continue;
+ }
+ if (strcmp(kind, "function_signature") == 0) {
+ return !ts_node_is_null(arguments) &&
+ any_field_contains_node(current, "arguments", node);
+ }
+ if (strcmp(kind, "function_statement") == 0) {
+ if (ts_node_is_null(arguments)) {
+ return false;
+ }
+ TSNode signature = ts_node_child_by_field_name(current, TS_FIELD("signature"));
+ return node_contains(signature, arguments);
+ }
+ }
+ return false;
+}
+
+static bool is_commonlisp_defun_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "defun_header") != 0) {
+ continue;
+ }
+ return field_contains_node(parent, "function_name", node) ||
+ field_contains_node(parent, "lambda_list", node);
+ }
+ return false;
+}
+
+static bool is_hcl_attribute_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "attribute") == 0) {
+ /* HCL's attribute production exposes no fields. The first named
+ * child is its key; the expression is the second named child. */
+ return named_child_contains(parent, 0, node);
+ }
+ }
+ return false;
+}
+
+static bool is_matlab_argument_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "function_arguments") == 0 || strcmp(kind, "lambda_arguments") == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool is_vhdl_interface_binding(TSNode node) {
+ static const char *const interface_kinds[] = {
+ "interface_constant_declaration", "interface_signal_declaration",
+ "interface_variable_declaration", "interface_declaration", NULL};
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (kind_in_exact_set(ts_node_type(parent), interface_kinds)) {
+ /* FIELD_COUNT does not name this role; every interface production
+ * starts with its identifier_list before mode/type/default. */
+ return named_child_contains(parent, 0, node);
+ }
+ }
+ return false;
+}
+
+static bool is_pine_function_binding(TSNode node) {
+ static const char *const fields[] = {"argument", NULL};
+ return ancestor_field_binds(node, "function_declaration_statement", fields);
+}
+
+static bool is_policy_binding(CBMExtractCtx *ctx, TSNode node,
+ const CBMOccurrenceSpec *occurrence) {
+ switch (occurrence->policy) {
+ case CBM_OCCURRENCE_LISP_DEF:
+ return is_lisp_def_binding(ctx, node);
+ case CBM_OCCURRENCE_COMMONLISP_DEFUN:
+ return is_commonlisp_defun_binding(node);
+ case CBM_OCCURRENCE_FENNEL_FN:
+ return is_fennel_fn_binding(ctx, node);
+ case CBM_OCCURRENCE_ELIXIR_DEF:
+ return is_elixir_def_binding(ctx, node);
+ case CBM_OCCURRENCE_JULIA_FUNCTION:
+ return is_first_named_part_of(node, "function_definition");
+ case CBM_OCCURRENCE_WOLFRAM_SET:
+ return is_wolfram_lhs(node);
+ case CBM_OCCURRENCE_TYPST_LET:
+ return is_first_named_part_of(node, "let");
+ case CBM_OCCURRENCE_AGDA_FUNCTION:
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "lhs") == 0) {
+ return true;
+ }
+ }
+ return false;
+ case CBM_OCCURRENCE_TLAPLUS_OPERATOR:
+ return is_tlaplus_binding(node);
+ case CBM_OCCURRENCE_COBOL_MOVE:
+ return is_cobol_move_destination(node);
+ case CBM_OCCURRENCE_HCL_ATTRIBUTE:
+ return is_hcl_attribute_binding(node);
+ case CBM_OCCURRENCE_ELM_VALUE:
+ return is_first_named_part_of(node, "value_declaration");
+ case CBM_OCCURRENCE_RESCRIPT_LET:
+ return is_first_named_part_of(node, "let_binding");
+ case CBM_OCCURRENCE_PURESCRIPT_LHS:
+ return is_first_named_part_of(node, "function");
+ case CBM_OCCURRENCE_NICKEL_LET:
+ return is_first_named_part_of(node, "let_binding") ||
+ is_first_named_part_of(node, "pattern_fun");
+ case CBM_OCCURRENCE_ERLANG_CLAUSE:
+ return is_erlang_clause_binding(node);
+ case CBM_OCCURRENCE_NIX_FUNCTION:
+ return is_nix_function_binding(node);
+ case CBM_OCCURRENCE_MATLAB_ARGUMENTS:
+ return is_matlab_argument_binding(node);
+ case CBM_OCCURRENCE_LEAN_BINDER:
+ return is_lean_binder_name(node);
+ case CBM_OCCURRENCE_PASCAL_PROC:
+ return is_pascal_proc_binding(node);
+ case CBM_OCCURRENCE_TEAL_FUNCTION:
+ return is_teal_function_binding(node);
+ case CBM_OCCURRENCE_VHDL_INTERFACE:
+ return is_vhdl_interface_binding(node);
+ case CBM_OCCURRENCE_PINE_FUNCTION:
+ return is_pine_function_binding(node);
+ case CBM_OCCURRENCE_LLVM_FUNCTION:
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "function_header") == 0) {
+ return field_contains_node(parent, "arguments", node);
+ }
+ }
+ return false;
+ case CBM_OCCURRENCE_STANDARD:
+ default:
+ return false;
+ }
+}
+
+static bool elixir_binary_operator_binds(CBMExtractCtx *ctx, TSNode node) {
+ if (ctx->language != CBM_LANG_ELIXIR || strcmp(ts_node_type(node), "binary_operator") != 0) {
+ return false;
+ }
+ TSNode operator_node = ts_node_child_by_field_name(node, TS_FIELD("operator"));
+ return text_equals(ctx, operator_node, "=") || text_equals(ctx, operator_node, "<-") ||
+ text_equals(ctx, operator_node, "->") || text_equals(ctx, operator_node, "\\\\");
+}
+
+static bool is_binding_occurrence(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
+ WalkState *state) {
+ const CBMOccurrenceSpec *occurrence = &occurrence_specs[ctx->language];
+ if (is_exact_language_binding(ctx, node, state)) {
+ return true;
+ }
+ if (is_policy_binding(ctx, node, occurrence)) {
+ return true;
+ }
+
+ TSNode current = node;
+ TSTreeCursor *cursor = reset_occurrence_cursor(state, node);
+ while (!ts_node_is_null(current)) {
+ TSNode parent;
+ const char *field;
+ if (!occurrence_parent(cursor, current, &parent, &field)) {
+ break;
+ }
+ if (is_value_field(field)) {
+ return false;
+ }
+ /* A declaration container binds its name/pattern, not the symbols used
+ * by its type annotation. Both TypeScript (`cfg: Config`) and Go
+ * (`cfg Config`) expose that annotation through the exact `type` field;
+ * stop before the whole-parameter binding rule can swallow `Config`.
+ * The emitted occurrence remains an ordinary USAGE, never a callable
+ * reference merely because the target happens to be a type. */
+ if (field && strcmp(field, "type") == 0) {
+ return false;
+ }
+
+ const char *kind = ts_node_type(parent);
+ if (kind_in_exact_set(kind, common_whole_binding_nodes) ||
+ kind_in_exact_set(kind, occurrence->whole_binding_nodes)) {
+ return true;
+ }
+
+ bool variable_container =
+ spec->variable_node_types && cbm_kind_in_set(parent, spec->variable_node_types);
+ if (ctx->language == CBM_LANG_ELIXIR && strcmp(kind, "binary_operator") == 0) {
+ variable_container = elixir_binary_operator_binds(ctx, parent);
+ }
+ bool declared_container =
+ kind_in_exact_set(kind, field_binding_nodes) ||
+ (spec->function_node_types && cbm_kind_in_set(parent, spec->function_node_types)) ||
+ (spec->class_node_types && cbm_kind_in_set(parent, spec->class_node_types)) ||
+ (spec->field_node_types && cbm_kind_in_set(parent, spec->field_node_types)) ||
+ variable_container;
+ if (declared_container) {
+ for (const char *const *binding_field = binding_fields; *binding_field;
+ binding_field++) {
+ if (field_contains_node(parent, *binding_field, node)) {
+ return true;
+ }
+ }
+ }
+ current = parent;
+ }
+ return false;
+}
+
+static bool assignment_reads_target(TSNode assignment) {
+ static const char *const read_write_nodes[] = {"augmented_assignment",
+ "augmented_assignment_expression",
+ "compound_assignment_expr",
+ "compound_assignment_expression",
+ "operator_assignment",
+ "operator_assign",
+ "update_exp",
+ "postfix_unary_expression",
+ "prefix_unary_expression",
+ NULL};
+ if (kind_in_exact_set(ts_node_type(assignment), read_write_nodes)) {
+ return true;
+ }
+ static const char *const read_write_operators[] = {"+=",
+ "-=",
+ "*=",
+ "/=",
+ "%=",
+ "&=",
+ "|=",
+ "^=",
+ "<<=",
+ ">>=",
+ "?"
+ "?=",
+ "++",
+ "--",
+ NULL};
+ uint32_t count = ts_node_child_count(assignment);
+ for (uint32_t i = 0; i < count; i++) {
+ if (kind_in_exact_set(ts_node_type(ts_node_child(assignment, i)), read_write_operators)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool is_write_occurrence(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
+ WalkState *state) {
+ const CBMOccurrenceSpec *occurrence = &occurrence_specs[ctx->language];
+ TSNode current = node;
+ TSTreeCursor *cursor = reset_occurrence_cursor(state, node);
+ while (!ts_node_is_null(current)) {
+ TSNode parent;
+ const char *field;
+ if (!occurrence_parent(cursor, current, &parent, &field)) {
+ break;
+ }
+ if (is_value_field(field)) {
+ return false;
+ }
+ bool assignment =
+ (spec->assignment_node_types && cbm_kind_in_set(parent, spec->assignment_node_types)) ||
+ kind_in_exact_set(ts_node_type(parent), occurrence->write_nodes);
+ if (ctx->language == CBM_LANG_ELIXIR &&
+ strcmp(ts_node_type(parent), "binary_operator") == 0) {
+ assignment = elixir_binary_operator_binds(ctx, parent);
+ }
+ if (assignment) {
+ if (assignment_reads_target(parent)) {
+ return false;
+ }
+ if (ctx->language == CBM_LANG_LINKERSCRIPT &&
+ strcmp(ts_node_type(parent), "assignment") == 0) {
+ /* This grammar's assignment production has no field map. Its
+ * first direct child is the lhs, even when that child is the
+ * anonymous location-counter token `.`. */
+ return ts_node_child_count(parent) > 0 &&
+ node_contains(ts_node_child(parent, 0), node);
+ }
+ TSNode left = ts_node_child_by_field_name(parent, TS_FIELD("left"));
+ if (node_contains(left, node) || field_contains_node(parent, "target", node) ||
+ field_contains_node(parent, "destination", node)) {
+ return true;
+ }
+ return occurrence->first_named_child_is_write && named_child_contains(parent, 0, node);
+ }
+ current = parent;
+ }
+ return false;
+}
+
+static bool is_argument_container_kind(const char *kind) {
+ return kind && (strcmp(kind, "arguments") == 0 || strcmp(kind, "argument_list") == 0 ||
+ strcmp(kind, "value_arguments") == 0);
+}
+
+static bool is_labeled_argument_kind(const char *kind) {
+ return kind && (strcmp(kind, "keyword_argument") == 0 || strcmp(kind, "named_argument") == 0 ||
+ strcmp(kind, "labeled_argument") == 0);
+}
+
+/* A named/labeled argument's key describes the callee parameter; it is not a
+ * value read in the caller. Keep this separate from binding detection: the
+ * label must neither emit USAGE nor create a caller-local lexical binding. */
+static bool is_call_argument_label(TSNode node) {
+ usage_slow_parent_fallback_test_note();
+ for (TSNode current = node; !ts_node_is_null(current);) {
+ TSNode parent = ts_node_parent(current);
+ if (ts_node_is_null(parent)) {
+ return false;
+ }
+ const char *parent_kind = ts_node_type(parent);
+ if (is_labeled_argument_kind(parent_kind)) {
+ return field_contains_node(parent, "name", node) ||
+ field_contains_node(parent, "label", node) ||
+ field_contains_node(parent, "key", node);
+ }
+ if (is_argument_container_kind(parent_kind)) {
+ return false;
+ }
+ current = parent;
+ }
+ return false;
+}
+
+static bool is_call_argument_label_walk(TSNode node, WalkState *state) {
+ TSTreeCursor *cursor = reset_occurrence_cursor(state, node);
+ if (!cursor)
+ return is_call_argument_label(node);
+ TSNode current = node;
+ while (!ts_node_is_null(current)) {
+ TSNode parent;
+ const char *field;
+ if (!occurrence_parent(cursor, current, &parent, &field))
+ return false;
+ const char *parent_kind = ts_node_type(parent);
+ if (is_labeled_argument_kind(parent_kind)) {
+ return field && (strcmp(field, "name") == 0 || strcmp(field, "label") == 0 ||
+ strcmp(field, "key") == 0);
+ }
+ if (is_argument_container_kind(parent_kind))
+ return false;
+ current = parent;
+ }
+ return false;
+}
+
+static bool is_direct_argument_value(TSNode node) {
+ usage_slow_parent_fallback_test_note();
+ TSNode parent = ts_node_parent(node);
+ if (ts_node_is_null(parent)) {
+ return false;
+ }
+ if (is_labeled_argument_kind(ts_node_type(parent))) {
+ TSNode value = ts_node_child_by_field_name(parent, TS_FIELD("value"));
+ return !ts_node_is_null(value) && ts_node_eq(value, node) &&
+ is_direct_argument_value(parent);
+ }
+ TSNode direct_arguments = ts_node_child_by_field_name(parent, TS_FIELD("arguments"));
+ if (!ts_node_is_null(direct_arguments) && ts_node_eq(direct_arguments, node)) {
+ return true;
+ }
+ if (is_argument_container_kind(ts_node_type(parent))) {
+ return true;
+ }
+ const char *parent_kind = ts_node_type(parent);
+ if (strcmp(parent_kind, "list_expression") == 0) {
+ TSNode call = ts_node_parent(parent);
+ if (!ts_node_is_null(call)) {
+ TSNode arguments = ts_node_child_by_field_name(call, TS_FIELD("arguments"));
+ return !ts_node_is_null(arguments) && ts_node_eq(arguments, parent);
+ }
+ return false;
+ }
+ if (strcmp(parent_kind, "argument") != 0 && strcmp(parent_kind, "value_argument") != 0) {
+ return false;
+ }
+ TSNode grandparent = ts_node_parent(parent);
+ return !ts_node_is_null(grandparent) && is_argument_container_kind(ts_node_type(grandparent));
+}
+
+/* Cursor-backed counterpart for the unified walker. `cursor` must currently
+ * point at `node`; it is consumed while walking toward the argument owner. */
+static bool is_direct_argument_value_cursor(TSNode node, TSTreeCursor *cursor) {
+ TSNode current = node;
+ while (!ts_node_is_null(current)) {
+ TSNode parent;
+ const char *field;
+ if (!occurrence_parent(cursor, current, &parent, &field))
+ return false;
+ const char *parent_kind = ts_node_type(parent);
+ if (is_labeled_argument_kind(parent_kind)) {
+ if (!field || strcmp(field, "value") != 0)
+ return false;
+ current = parent;
+ continue;
+ }
+ if (field && strcmp(field, "arguments") == 0)
+ return true;
+ if (is_argument_container_kind(parent_kind))
+ return true;
+ if (strcmp(parent_kind, "list_expression") == 0) {
+ TSNode call;
+ const char *list_field;
+ return occurrence_parent(cursor, parent, &call, &list_field) && list_field &&
+ strcmp(list_field, "arguments") == 0;
+ }
+ if (strcmp(parent_kind, "argument") != 0 && strcmp(parent_kind, "value_argument") != 0) {
+ return false;
+ }
+ TSNode grandparent;
+ const char *argument_field;
+ return occurrence_parent(cursor, parent, &grandparent, &argument_field) &&
+ is_argument_container_kind(ts_node_type(grandparent));
+ }
+ return false;
+}
+
+static bool is_direct_argument_value_walk(TSNode node, WalkState *state) {
+ TSTreeCursor *cursor = reset_occurrence_cursor(state, node);
+ return cursor ? is_direct_argument_value_cursor(node, cursor) : is_direct_argument_value(node);
+}
+
+static TSNode python_direct_callable_attribute_site(TSNode node) {
+ usage_slow_parent_fallback_test_note();
+ if (ts_node_is_null(node) || strcmp(ts_node_type(node), "attribute") != 0) {
+ return (TSNode){0};
+ }
+ TSNode site = node;
+ TSNode parent = ts_node_parent(site);
+ while (!ts_node_is_null(parent) &&
+ strcmp(ts_node_type(parent), "parenthesized_expression") == 0) {
+ TSNode inner = ts_node_child_by_field_name(parent, TS_FIELD("expression"));
+ if (ts_node_is_null(inner) && ts_node_named_child_count(parent) == 1) {
+ inner = ts_node_named_child(parent, 0);
+ }
+ if (ts_node_is_null(inner) || !ts_node_eq(inner, site)) {
+ return (TSNode){0};
+ }
+ site = parent;
+ parent = ts_node_parent(site);
+ }
+ return is_direct_argument_value(site) ? site : (TSNode){0};
+}
+
+static bool language_may_stamp_exact_callable_value_candidate(CBMLanguage language) {
+ switch (language) {
+ case CBM_LANG_JAVASCRIPT:
+ case CBM_LANG_TYPESCRIPT:
+ case CBM_LANG_TSX:
+ case CBM_LANG_GO:
+ case CBM_LANG_PYTHON:
+ case CBM_LANG_C:
+ case CBM_LANG_CPP:
+ case CBM_LANG_CUDA:
+ case CBM_LANG_RUST:
+ case CBM_LANG_CSHARP:
+ case CBM_LANG_KOTLIN:
+ return true;
+ default:
+ return false;
+ }
+}
+
+/* Direct identifiers and direct, statically-named TS member values passed as
+ * arguments are narrow syntactic candidates only. A language LSP must still
+ * prove one target at this exact occurrence before the graph upgrades USAGE to
+ * CALL_REFERENCE; unresolved, reassigned, and composite expressions stay USAGE. */
+static TSNode csharp_callable_value_site(TSNode node) {
+ usage_slow_parent_fallback_test_note();
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "identifier") != 0 && strcmp(kind, "simple_identifier") != 0) {
+ return (TSNode){0};
+ }
+
+ TSNode site = node;
+ TSNode parent = ts_node_parent(site);
+ if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "generic_name") == 0) {
+ TSNode name = ts_node_child_by_field_name(parent, TS_FIELD("name"));
+ if (ts_node_is_null(name) && ts_node_named_child_count(parent) > 0) {
+ name = ts_node_named_child(parent, 0);
+ }
+ if (ts_node_is_null(name) || !ts_node_eq(name, node)) {
+ return (TSNode){0};
+ }
+ site = parent;
+ parent = ts_node_parent(site);
+ }
+
+ if (!ts_node_is_null(parent) && strcmp(ts_node_type(parent), "member_access_expression") == 0) {
+ TSNode member = ts_node_child_by_field_name(parent, TS_FIELD("name"));
+ if (ts_node_is_null(member) || !ts_node_eq(member, site)) {
+ return (TSNode){0};
+ }
+ site = parent;
+ parent = ts_node_parent(site);
+ }
+
+ while (!ts_node_is_null(parent) &&
+ strcmp(ts_node_type(parent), "parenthesized_expression") == 0) {
+ TSNode inner = ts_node_child_by_field_name(parent, TS_FIELD("expression"));
+ if (ts_node_is_null(inner) && ts_node_named_child_count(parent) == 1) {
+ inner = ts_node_named_child(parent, 0);
+ }
+ if (ts_node_is_null(inner) || !ts_node_eq(inner, site)) {
+ return (TSNode){0};
+ }
+ site = parent;
+ parent = ts_node_parent(site);
+ }
+
+ /* The wrapper chain proves admission, but the semantic row is keyed to the
+ * terminal method-name identifier. Keep the raw carrier on that leaf. */
+ return is_direct_argument_value(site) ? node : (TSNode){0};
+}
+
+static TSNode call_reference_candidate_site(CBMExtractCtx *ctx, TSNode node, const char *name,
+ WalkState *state) {
+ if (!ctx || !name || !language_may_stamp_exact_callable_value_candidate(ctx->language)) {
+ return (TSNode){0};
+ }
+ const char *kind = ts_node_type(node);
+ TSTreeCursor *cursor = reset_occurrence_cursor(state, node);
+ TSNode parent = {0};
+ const char *parent_field = NULL;
+ if (!cursor) {
+ usage_slow_parent_fallback_test_note();
+ parent = ts_node_parent(node);
+ } else {
+ (void)occurrence_parent(cursor, node, &parent, &parent_field);
+ }
+ bool ts_family = ctx->language == CBM_LANG_JAVASCRIPT || ctx->language == CBM_LANG_TYPESCRIPT ||
+ ctx->language == CBM_LANG_TSX;
+ if (ts_family && strcmp(kind, "property_identifier") == 0 && !ts_node_is_null(parent) &&
+ strcmp(ts_node_type(parent), "member_expression") == 0) {
+ TSNode property = ts_node_child_by_field_name(parent, TS_FIELD("property"));
+ TSNode arguments = {0};
+ const char *member_field = NULL;
+ if (cursor) {
+ (void)occurrence_parent(cursor, parent, &arguments, &member_field);
+ } else {
+ usage_slow_parent_fallback_test_note();
+ arguments = ts_node_parent(parent);
+ }
+ return !ts_node_is_null(property) && ts_node_eq(property, node) &&
+ !ts_node_is_null(arguments) &&
+ strcmp(ts_node_type(arguments), "arguments") == 0
+ ? node
+ : (TSNode){0};
+ }
+ if (ctx->language == CBM_LANG_PYTHON && strcmp(kind, "identifier") == 0 &&
+ !ts_node_is_null(parent) && strcmp(ts_node_type(parent), "attribute") == 0) {
+ TSNode attribute = ts_node_child_by_field_name(parent, TS_FIELD("attribute"));
+ return !ts_node_is_null(attribute) && ts_node_eq(attribute, node)
+ ? python_direct_callable_attribute_site(parent)
+ : (TSNode){0};
+ }
+ if (ctx->language == CBM_LANG_GO && strcmp(kind, "field_identifier") == 0 &&
+ !ts_node_is_null(parent) && strcmp(ts_node_type(parent), "selector_expression") == 0) {
+ TSNode field = ts_node_child_by_field_name(parent, TS_FIELD("field"));
+ return !ts_node_is_null(field) && ts_node_eq(field, node) &&
+ (cursor ? is_direct_argument_value_cursor(parent, cursor)
+ : is_direct_argument_value(parent))
+ ? parent
+ : (TSNode){0};
+ }
+ if (ctx->language == CBM_LANG_RUST && strcmp(kind, "scoped_identifier") == 0) {
+ return is_direct_argument_value_walk(node, state) ? node : (TSNode){0};
+ }
+ if (ctx->language == CBM_LANG_CSHARP) {
+ return csharp_callable_value_site(node);
+ }
+ return (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0) &&
+ is_direct_argument_value_walk(node, state)
+ ? node
+ : (TSNode){0};
+}
+
+static char *reference_name(CBMExtractCtx *ctx, TSNode node) {
+ char *name = cbm_node_text(ctx->arena, node, ctx->source);
+ if (!name || ctx->language != CBM_LANG_MAKEFILE ||
+ strcmp(ts_node_type(node), "variable_reference") != 0) {
+ return name;
+ }
+
+ /* Make exposes `$(watched)` as one named reference node.
+ * Normalize only that grammar wrapper; the recorded site still spans the
+ * exact source occurrence for occurrence-sensitive resolution. */
+ size_t length = strlen(name);
+ bool parenthesized = length > 3 && name[0] == '$' && name[1] == '(' && name[length - 1] == ')';
+ return parenthesized ? cbm_arena_strndup(ctx->arena, name + 2, length - 3) : name;
+}
+
+static bool lexical_identifier_case_insensitive(CBMLanguage language) {
+ switch (language) {
+ case CBM_LANG_POWERSHELL:
+ case CBM_LANG_FORTRAN:
+ case CBM_LANG_ADA:
+ case CBM_LANG_PASCAL:
+ case CBM_LANG_COBOL:
+ case CBM_LANG_VHDL:
+ return true;
+ default:
+ return false;
+ }
+}
+
+static const char *lexical_binding_key(CBMExtractCtx *ctx, WalkState *state, const char *name) {
+ if (!ctx || !name) {
+ return name;
+ }
+ /* Preserve language namespaces: Perl sigils and Vim prefixes distinguish
+ * different variables. Tcl's grammar is asymmetric (`name` versus
+ * `$name`), so unwrap only that language-defined reference sigil. */
+ if (ctx->language == CBM_LANG_TCL && name[0] == '$') {
+ name++;
+ }
+ if (!lexical_identifier_case_insensitive(ctx->language)) {
+ return name;
+ }
+ size_t n = strlen(name);
+ char *folded = (char *)cbm_arena_alloc(ctx->arena, n + 1U);
+ if (!folded) {
+ if (state) {
+ state->lexical_binding_tracking_failed = true;
+ }
+ return NULL;
+ }
+ for (size_t i = 0; i < n; i++) {
+ folded[i] = (char)tolower((unsigned char)name[i]);
+ }
+ folded[n] = '\0';
+ return folded;
+}
+
+static void stamp_usage_site(CBMExtractCtx *ctx, CBMUsage *usage, TSNode node, const char *name,
+ WalkState *state) {
+ TSNode candidate_site = call_reference_candidate_site(ctx, node, name, state);
+ TSNode site = ts_node_is_null(candidate_site) ? node : candidate_site;
+ usage->site_start_byte = ts_node_start_byte(site);
+ usage->site_end_byte = ts_node_end_byte(site);
+ usage->may_be_call_reference = !ts_node_is_null(candidate_site);
+}
+
+static const CBMLexicalScope *usage_lexical_scope(const WalkState *state, uint32_t id) {
+ return state && id > 0 && id <= (uint32_t)state->lexical_scope_count
+ ? &state->lexical_scopes[id - 1U]
+ : NULL;
+}
-// Check if a node is inside a call expression (to avoid double-counting as usage)
-static bool is_inside_call(TSNode node, const CBMLangSpec *spec) {
- TSNode cur = ts_node_parent(node);
- int depth = 0;
- while (!ts_node_is_null(cur) && depth < MAX_PARENT_DEPTH) {
- if (cbm_kind_in_set(cur, spec->call_node_types)) {
+static uint32_t active_lexical_scope_id(const WalkState *state) {
+ if (!state) {
+ return 0;
+ }
+ for (int i = state->scope_top - 1; i >= 0; i--) {
+ if (state->scopes[i].lexical_scope_id != 0) {
+ return state->scopes[i].lexical_scope_id;
+ }
+ }
+ return state->root_lexical_scope_id;
+}
+
+static uint32_t lexical_ancestor_of_kind(const WalkState *state, uint32_t start_id,
+ bool want_function, bool want_block);
+
+static bool python_default_value_reference(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ /* A nested executable scope inside the default owns its own lookups;
+ * only a direct default expression is evaluated in the declaring
+ * function's structural parent namespace. */
+ if (strcmp(kind, "lambda") == 0 || strcmp(kind, "list_comprehension") == 0 ||
+ strcmp(kind, "set_comprehension") == 0 ||
+ strcmp(kind, "dictionary_comprehension") == 0 ||
+ strcmp(kind, "generator_expression") == 0) {
+ return false;
+ }
+ if ((strcmp(kind, "default_parameter") == 0 ||
+ strcmp(kind, "typed_default_parameter") == 0) &&
+ (field_contains_node(parent, "value", node) ||
+ field_contains_node(parent, "default", node))) {
return true;
}
- cur = ts_node_parent(cur);
- depth++;
}
return false;
}
-// Check if a node is inside an import statement
-static bool is_inside_import(TSNode node, const CBMLangSpec *spec) {
- if (!spec->import_node_types || !spec->import_node_types[0]) {
+static uint32_t usage_lexical_scope_id_for_node(CBMExtractCtx *ctx, const WalkState *state,
+ TSNode node) {
+ uint32_t scope_id = active_lexical_scope_id(state);
+ if (!ctx || ctx->language != CBM_LANG_PYTHON || !python_default_value_reference(node)) {
+ return scope_id;
+ }
+ uint32_t function_id = lexical_ancestor_of_kind(state, scope_id, true, false);
+ const CBMLexicalScope *function_scope = usage_lexical_scope(state, function_id);
+ /* Method bodies intentionally skip their class lookup parent, but Python
+ * evaluates the method's default expressions while the class namespace is
+ * executing. Use structural ownership here, not body lookup ownership. */
+ return function_scope ? function_scope->parent_id : scope_id;
+}
+
+static uint32_t lexical_ancestor_of_kind(const WalkState *state, uint32_t start_id,
+ bool want_function, bool want_block) {
+ uint32_t id = start_id;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, id);
+ if (!scope) {
+ return 0;
+ }
+ bool function_scope = scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION;
+ bool block_scope = scope->kind == CBM_LEXICAL_SCOPE_BLOCK;
+ if ((want_function && function_scope) || (want_block && block_scope)) {
+ return id;
+ }
+ id = scope->parent_id;
+ }
+ return 0;
+}
+
+static uint32_t python_nearest_namespace(const WalkState *state, uint32_t start_id) {
+ uint32_t id = start_id;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, id);
+ if (!scope) {
+ return 0;
+ }
+ if (scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION ||
+ scope->kind == CBM_LEXICAL_SCOPE_CLASS || scope->kind == CBM_LEXICAL_SCOPE_MODULE) {
+ return id;
+ }
+ id = scope->parent_id;
+ }
+ return 0;
+}
+
+static bool ensure_lexical_binding_capacity(WalkState *state) {
+ if (!state->lexical_bindings) {
+ state->lexical_bindings = state->inline_lexical_bindings;
+ state->lexical_binding_capacity = INLINE_LEXICAL_BINDINGS;
+ memset(state->inline_lexical_bindings, 0, sizeof(state->inline_lexical_bindings));
+ }
+ if (state->lexical_binding_count < state->lexical_binding_capacity) {
+ return true;
+ }
+ if (state->lexical_binding_capacity > INT32_MAX / PAIR_LEN) {
+ state->lexical_binding_tracking_failed = true;
return false;
}
- TSNode cur = ts_node_parent(node);
- int depth = 0;
- while (!ts_node_is_null(cur) && depth < MAX_PARENT_DEPTH) {
- if (cbm_kind_in_set(cur, spec->import_node_types)) {
+ int new_capacity = state->lexical_binding_capacity * PAIR_LEN;
+ CBMLexicalBinding *grown =
+ (CBMLexicalBinding *)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ memcpy(grown, state->lexical_bindings, (size_t)state->lexical_binding_count * sizeof(*grown));
+ state->lexical_bindings = grown;
+ state->lexical_binding_capacity = new_capacity;
+ return true;
+}
+
+static bool lexical_ancestor_kind(TSNode node, const char *kind) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), kind) == 0) {
return true;
}
- cur = ts_node_parent(cur);
- depth++;
}
return false;
}
-// Is this an identifier-like node that represents a reference?
-static bool is_reference_node(TSNode node, CBMLanguage lang) {
- const char *kind = ts_node_type(node);
+static TSNode declared_function_name_owner(TSNode node, const CBMLangSpec *spec) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (spec->function_node_types && cbm_kind_in_set(parent, spec->function_node_types)) {
+ return field_contains_node(parent, "name", node) ? parent : (TSNode){0};
+ }
+ }
+ return (TSNode){0};
+}
- // Common identifier types across languages
- if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ||
- strcmp(kind, "type_identifier") == 0) {
+static TSNode declared_class_name_owner(TSNode node, const CBMLangSpec *spec) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (spec->class_node_types && cbm_kind_in_set(parent, spec->class_node_types)) {
+ return field_contains_node(parent, "name", node) ? parent : (TSNode){0};
+ }
+ }
+ return (TSNode){0};
+}
+
+static bool ensure_python_directive_capacity(WalkState *state) {
+ if (!state->python_directives) {
+ state->python_directives = state->inline_python_directives;
+ state->python_directive_capacity = INLINE_PYTHON_DIRECTIVES;
+ memset(state->inline_python_directives, 0, sizeof(state->inline_python_directives));
+ }
+ if (state->python_directive_count < state->python_directive_capacity) {
return true;
}
+ if (state->python_directive_capacity > INT32_MAX / PAIR_LEN) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ int new_capacity = state->python_directive_capacity * PAIR_LEN;
+ CBMPythonDirective *grown =
+ (CBMPythonDirective *)cbm_arena_alloc(state->arena, (size_t)new_capacity * sizeof(*grown));
+ if (!grown) {
+ state->lexical_binding_tracking_failed = true;
+ return false;
+ }
+ memcpy(grown, state->python_directives, (size_t)state->python_directive_count * sizeof(*grown));
+ state->python_directives = grown;
+ state->python_directive_capacity = new_capacity;
+ return true;
+}
- // Language-specific reference types
- switch (lang) {
- case CBM_LANG_GO:
- return strcmp(kind, "field_identifier") == 0 || strcmp(kind, "package_identifier") == 0;
- case CBM_LANG_PYTHON:
- return strcmp(kind, "attribute") == 0;
- case CBM_LANG_RUST:
- return strcmp(kind, "field_identifier") == 0 || strcmp(kind, "scoped_identifier") == 0;
- case CBM_LANG_HASKELL:
- return strcmp(kind, "variable") == 0 || strcmp(kind, "constructor") == 0;
- case CBM_LANG_OCAML:
- return strcmp(kind, "value_path") == 0 || strcmp(kind, "constructor_path") == 0;
- case CBM_LANG_ERLANG:
- return strcmp(kind, "atom") == 0 || strcmp(kind, "var") == 0;
+static void record_python_directive(WalkState *state, uint32_t function_scope_id, const char *name,
+ CBMPythonDirectiveKind kind) {
+ if (!function_scope_id || !name || !ensure_python_directive_capacity(state)) {
+ return;
+ }
+ for (int i = 0; i < state->python_directive_count; i++) {
+ CBMPythonDirective *directive = &state->python_directives[i];
+ if (directive->function_scope_id == function_scope_id &&
+ strcmp(directive->name, name) == 0) {
+ directive->kind = (uint8_t)kind;
+ return;
+ }
+ }
+ CBMPythonDirective *directive = &state->python_directives[state->python_directive_count++];
+ directive->function_scope_id = function_scope_id;
+ directive->name = name;
+ directive->kind = (uint8_t)kind;
+}
+
+static CBMPythonDirectiveKind python_directive_for(const WalkState *state,
+ uint32_t function_scope_id, const char *name) {
+ for (int i = state ? state->python_directive_count - 1 : -1; i >= 0; i--) {
+ const CBMPythonDirective *directive = &state->python_directives[i];
+ if (directive->function_scope_id == function_scope_id && directive->name &&
+ strcmp(directive->name, name) == 0) {
+ return (CBMPythonDirectiveKind)directive->kind;
+ }
+ }
+ return 0;
+}
+
+static uint32_t python_enclosing_function_namespace(const WalkState *state,
+ uint32_t inner_function_id) {
+ const CBMLexicalScope *inner = usage_lexical_scope(state, inner_function_id);
+ uint32_t id = inner ? inner->parent_id : 0;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, id);
+ if (!scope) {
+ return 0;
+ }
+ if (scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION) {
+ return id;
+ }
+ id = scope->parent_id;
+ }
+ return 0;
+}
+
+static bool binding_is_parameter(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
+ const CBMOccurrenceSpec *occurrence = &occurrence_specs[ctx->language];
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (kind_in_exact_set(kind, common_whole_binding_nodes) ||
+ kind_in_exact_set(kind, occurrence->whole_binding_nodes)) {
+ return true;
+ }
+ if (spec->function_node_types && cbm_kind_in_set(parent, spec->function_node_types)) {
+ return field_contains_node(parent, "parameter", node) ||
+ field_contains_node(parent, "parameters", node);
+ }
+ }
+ return false;
+}
+
+static bool js_var_binding(TSNode node) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "variable_declaration") == 0) {
+ return true;
+ }
+ if (strcmp(kind, "lexical_declaration") == 0) {
+ return false;
+ }
+ }
+ return false;
+}
+
+static bool import_kind_matches(TSNode node, const CBMLangSpec *spec) {
+ return (spec->import_node_types && cbm_kind_in_set(node, spec->import_node_types)) ||
+ (spec->import_from_types && cbm_kind_in_set(node, spec->import_from_types));
+}
+
+static TSNode nearest_import_ancestor(TSNode node, const CBMLangSpec *spec) {
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (import_kind_matches(parent, spec)) {
+ return parent;
+ }
+ }
+ return (TSNode){0};
+}
+
+static TSNode first_named_leaf(TSNode node) {
+ while (!ts_node_is_null(node) && ts_node_named_child_count(node) > 0) {
+ node = ts_node_named_child(node, 0);
+ }
+ return node;
+}
+
+static bool import_alias_contains(TSNode node, TSNode boundary) {
+ for (TSNode parent = ts_node_parent(node);
+ !ts_node_is_null(parent) && !ts_node_eq(parent, boundary);
+ parent = ts_node_parent(parent)) {
+ if (field_contains_node(parent, "alias", node)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool rust_use_list_has_direct_self(TSNode list) {
+ uint32_t count = ts_node_named_child_count(list);
+ for (uint32_t i = 0; i < count; i++) {
+ if (strcmp(ts_node_type(ts_node_named_child(list, i)), "self") == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/* Import subtrees are excluded from ordinary usage emission, but their local
+ * names still participate in lexical lookup. Keep this classifier narrow: it
+ * identifies only the binding side, never a module path or imported source
+ * name. */
+static bool is_import_binding_occurrence(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
+ TSNode boundary = nearest_import_ancestor(node, spec);
+ if (ts_node_is_null(boundary)) {
+ return false;
+ }
+ /* Rust's extern-crate alias is a direct field of the import boundary,
+ * unlike the nested alias containers used by Python and ES imports. */
+ if (field_contains_node(boundary, "alias", node)) {
+ return true;
+ }
+ if (import_alias_contains(node, boundary)) {
+ return true;
+ }
+
+ switch (ctx->language) {
+ case CBM_LANG_PYTHON: {
+ const char *boundary_kind = ts_node_type(boundary);
+ if (strcmp(boundary_kind, "future_import_statement") == 0) {
+ return false;
+ }
+ for (TSNode parent = ts_node_parent(node);
+ !ts_node_is_null(parent) && !ts_node_eq(parent, boundary);
+ parent = ts_node_parent(parent)) {
+ /* In an aliased import, only the alias binds. */
+ if (strcmp(ts_node_type(parent), "aliased_import") == 0) {
+ return false;
+ }
+ }
+ bool from_import = strcmp(boundary_kind, "import_from_statement") == 0;
+ if (from_import) {
+ if (field_contains_node(boundary, "module_name", node) ||
+ field_contains_node(boundary, "module", node)) {
+ return false;
+ }
+ /* Older Python grammar variants omit the module field. Their first
+ * named child is still the source module, never a local binding. */
+ if (ts_node_named_child_count(boundary) > 1 &&
+ node_contains(ts_node_named_child(boundary, 0), node)) {
+ return false;
+ }
+ return strcmp(ts_node_type(node), "identifier") == 0;
+ }
+
+ TSNode entry = node;
+ TSNode parent = ts_node_parent(entry);
+ while (!ts_node_is_null(parent) && !ts_node_eq(parent, boundary)) {
+ entry = parent;
+ parent = ts_node_parent(parent);
+ }
+ TSNode first = first_named_leaf(entry);
+ return !ts_node_is_null(first) && ts_node_eq(first, node);
+ }
+ case CBM_LANG_JAVASCRIPT:
+ case CBM_LANG_TYPESCRIPT:
+ case CBM_LANG_TSX: {
+ if (strcmp(ts_node_type(boundary), "import_statement") != 0) {
+ return false;
+ }
+ for (TSNode parent = ts_node_parent(node);
+ !ts_node_is_null(parent) && !ts_node_eq(parent, boundary);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "import_specifier") == 0) {
+ TSNode alias = ts_node_child_by_field_name(parent, TS_FIELD("alias"));
+ if (!ts_node_is_null(alias)) {
+ return false;
+ }
+ return field_contains_node(parent, "name", node) ||
+ ts_node_eq(first_named_leaf(parent), node);
+ }
+ if (strcmp(kind, "namespace_import") == 0) {
+ return field_contains_node(parent, "name", node) ||
+ ts_node_eq(first_named_leaf(parent), node);
+ }
+ if (strcmp(kind, "import_clause") == 0) {
+ /* A direct identifier is the default import. Named and
+ * namespace imports were handled by their inner containers. */
+ return ts_node_eq(first_named_leaf(parent), node);
+ }
+ if (strcmp(kind, "import_require_clause") == 0) {
+ /* TypeScript `import local = require("module")` and
+ * `import local = Namespace.member` put the binding first.
+ * Current grammar variants expose only the source field, so
+ * retain the first-leaf fallback as the exact role check. */
+ return field_contains_node(parent, "name", node) ||
+ ts_node_eq(first_named_leaf(parent), node);
+ }
+ }
+ return false;
+ }
+ case CBM_LANG_RUST: {
+ TSNode boundary_alias = ts_node_child_by_field_name(boundary, TS_FIELD("alias"));
+ if (!ts_node_is_null(boundary_alias) && field_contains_node(boundary, "name", node)) {
+ /* `extern crate source as local` binds only local. */
+ return false;
+ }
+ bool terminal = false;
+ for (TSNode parent = ts_node_parent(node);
+ !ts_node_is_null(parent) && !ts_node_eq(parent, boundary);
+ parent = ts_node_parent(parent)) {
+ if (field_contains_node(parent, "path", node)) {
+ /* `use foo::{self}` imports the module itself under the final
+ * segment of the prefix (`foo`). An aliased `self as x` is a
+ * use_as_clause child rather than a direct self entry and is
+ * already handled by the alias rule above. */
+ if (strcmp(ts_node_type(parent), "scoped_use_list") == 0 &&
+ strcmp(ts_node_type(node), "identifier") == 0) {
+ TSNode path = ts_node_child_by_field_name(parent, TS_FIELD("path"));
+ TSNode list = ts_node_child_by_field_name(parent, TS_FIELD("list"));
+ bool terminal_path = terminal || ts_node_eq(path, node);
+ if (terminal_path && !ts_node_is_null(list) &&
+ rust_use_list_has_direct_self(list)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ if (field_contains_node(parent, "name", node)) {
+ terminal = true;
+ }
+ }
+ return terminal || strcmp(ts_node_type(node), "identifier") == 0;
+ }
default:
return false;
}
}
-// Check if a reference node is a definition name (the "name" field of its parent).
-static bool is_definition_name(TSNode node) {
- TSNode parent = ts_node_parent(node);
- if (ts_node_is_null(parent)) {
+static uint32_t lexical_import_scope(const WalkState *state, uint32_t start_id) {
+ uint32_t id = start_id;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, id);
+ if (!scope) {
+ return 0;
+ }
+ if (scope->kind == CBM_LEXICAL_SCOPE_MODULE || scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION ||
+ scope->kind == CBM_LEXICAL_SCOPE_BLOCK) {
+ return id;
+ }
+ id = scope->parent_id;
+ }
+ return 0;
+}
+
+static void record_lexical_binding(CBMExtractCtx *ctx, WalkState *state, TSNode node,
+ const CBMLangSpec *spec, const char *raw_name,
+ bool import_binding) {
+ if (!ctx || !state || !raw_name || !raw_name[0] || state->lexical_binding_tracking_failed) {
+ return;
+ }
+ bool parameter = binding_is_parameter(ctx, node, spec);
+ if (ctx->language == CBM_LANG_VIMSCRIPT && parameter && !strchr(raw_name, ':')) {
+ raw_name = cbm_arena_sprintf(ctx->arena, "a:%s", raw_name);
+ if (!raw_name) {
+ state->lexical_binding_tracking_failed = true;
+ return;
+ }
+ }
+ const char *name = lexical_binding_key(ctx, state, raw_name);
+ if (!name || !name[0]) {
+ return;
+ }
+
+ uint32_t current_id = active_lexical_scope_id(state);
+ uint32_t scope_id = 0;
+ bool whole_scope = false;
+ TSNode function_declaration = declared_function_name_owner(node, spec);
+ TSNode class_declaration = declared_class_name_owner(node, spec);
+
+ if (ctx->language == CBM_LANG_PYTHON && (lexical_ancestor_kind(node, "global_statement") ||
+ lexical_ancestor_kind(node, "nonlocal_statement"))) {
+ uint32_t function_id = lexical_ancestor_of_kind(state, current_id, true, false);
+ CBMPythonDirectiveKind directive = lexical_ancestor_kind(node, "global_statement")
+ ? CBM_PYTHON_DIRECTIVE_GLOBAL
+ : CBM_PYTHON_DIRECTIVE_NONLOCAL;
+ record_python_directive(state, function_id, name, directive);
+ return;
+ }
+
+ if (!ts_node_is_null(function_declaration)) {
+ uint32_t function_id = lexical_ancestor_of_kind(state, current_id, true, false);
+ const CBMLexicalScope *function_scope = usage_lexical_scope(state, function_id);
+ uint32_t parent_id = function_scope ? function_scope->parent_id : 0;
+ if (ctx->language == CBM_LANG_PYTHON) {
+ scope_id = python_nearest_namespace(state, parent_id);
+ const CBMLexicalScope *owner = usage_lexical_scope(state, scope_id);
+ if (!owner || (owner->kind != CBM_LEXICAL_SCOPE_FUNCTION &&
+ owner->kind != CBM_LEXICAL_SCOPE_COMPREHENSION)) {
+ return;
+ }
+ } else {
+ scope_id = lexical_ancestor_of_kind(state, parent_id, true, true);
+ }
+ /* Top-level/class callable declarations are themselves semantic
+ * targets, not local-value blockers. Nested declarations still bind
+ * their enclosing executable scope and must block raw-name fallback. */
+ if (scope_id == 0) {
+ return;
+ }
+ whole_scope = true;
+ } else if (ctx->language == CBM_LANG_PYTHON && !ts_node_is_null(class_declaration)) {
+ uint32_t class_id = python_nearest_namespace(state, current_id);
+ const CBMLexicalScope *class_scope = usage_lexical_scope(state, class_id);
+ scope_id = python_nearest_namespace(state, class_scope ? class_scope->parent_id : 0);
+ const CBMLexicalScope *owner = usage_lexical_scope(state, scope_id);
+ if (!owner || (owner->kind != CBM_LEXICAL_SCOPE_FUNCTION &&
+ owner->kind != CBM_LEXICAL_SCOPE_COMPREHENSION)) {
+ return;
+ }
+ whole_scope = true;
+ } else if (parameter) {
+ scope_id = lexical_ancestor_of_kind(state, current_id, true, false);
+ whole_scope = true;
+ } else if (ctx->language == CBM_LANG_PYTHON) {
+ uint32_t namespace_id = python_nearest_namespace(state, current_id);
+ const CBMLexicalScope *namespace_scope = usage_lexical_scope(state, namespace_id);
+ uint32_t function_id =
+ namespace_scope && (namespace_scope->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ namespace_scope->kind == CBM_LEXICAL_SCOPE_COMPREHENSION)
+ ? namespace_id
+ : lexical_ancestor_of_kind(state, current_id, true, false);
+ CBMPythonDirectiveKind directive = python_directive_for(state, function_id, name);
+ if (directive == CBM_PYTHON_DIRECTIVE_GLOBAL) {
+ scope_id = state->root_lexical_scope_id;
+ } else if (directive == CBM_PYTHON_DIRECTIVE_NONLOCAL) {
+ scope_id = python_enclosing_function_namespace(state, function_id);
+ } else {
+ scope_id = namespace_id;
+ }
+ const CBMLexicalScope *owner = usage_lexical_scope(state, scope_id);
+ if (!owner) {
+ return;
+ }
+ whole_scope = directive == 0 && (owner->kind == CBM_LEXICAL_SCOPE_FUNCTION ||
+ owner->kind == CBM_LEXICAL_SCOPE_COMPREHENSION);
+ } else if (ctx->language == CBM_LANG_POWERSHELL) {
+ scope_id = lexical_ancestor_of_kind(state, current_id, true, false);
+ whole_scope = true;
+ } else if (ctx->language == CBM_LANG_JAVASCRIPT || ctx->language == CBM_LANG_TYPESCRIPT ||
+ ctx->language == CBM_LANG_TSX) {
+ bool is_var = js_var_binding(node);
+ scope_id = lexical_ancestor_of_kind(state, current_id, is_var, !is_var);
+ if (scope_id == 0) {
+ scope_id = lexical_ancestor_of_kind(state, current_id, true, false);
+ }
+ if (scope_id == 0) {
+ scope_id = state->root_lexical_scope_id;
+ }
+ whole_scope = true; /* var hoisting and let/const TDZ */
+ } else if (ctx->language == CBM_LANG_RUST && import_binding) {
+ scope_id = lexical_import_scope(state, current_id);
+ if (scope_id == 0) {
+ scope_id = state->root_lexical_scope_id;
+ }
+ /* A Rust use/extern-crate declaration is an item whose name is in
+ * scope for the complete containing block or module, independent of
+ * textual declaration order. */
+ whole_scope = true;
+ } else {
+ scope_id = lexical_ancestor_of_kind(state, current_id, true, true);
+ if (scope_id == 0) {
+ scope_id = state->root_lexical_scope_id;
+ }
+ }
+ const CBMLexicalScope *scope = usage_lexical_scope(state, scope_id);
+ if (!scope || !ensure_lexical_binding_capacity(state)) {
+ return;
+ }
+ CBMLexicalBinding *binding = &state->lexical_bindings[state->lexical_binding_count++];
+ binding->scope_id = scope_id;
+ binding->active_start = whole_scope ? scope->start_byte : ts_node_end_byte(node);
+ /* Zero means "the finalized end of this concrete scope". Split
+ * signature/body languages extend the scope after parameters are seen. */
+ binding->active_end = 0;
+ binding->name = name;
+}
+
+static int compare_lexical_bindings(const void *left_ptr, const void *right_ptr) {
+ const CBMLexicalBinding *left = (const CBMLexicalBinding *)left_ptr;
+ const CBMLexicalBinding *right = (const CBMLexicalBinding *)right_ptr;
+ if (left->scope_id != right->scope_id) {
+ return left->scope_id < right->scope_id ? -1 : 1;
+ }
+ int name_order = strcmp(left->name, right->name);
+ if (name_order != 0) {
+ return name_order;
+ }
+ if (left->active_start != right->active_start) {
+ return left->active_start < right->active_start ? -1 : 1;
+ }
+ if (left->active_end != right->active_end) {
+ return left->active_end < right->active_end ? -1 : 1;
+ }
+ return 0;
+}
+
+static int compare_binding_key(const CBMLexicalBinding *binding, uint32_t scope_id,
+ const char *name) {
+ if (binding->scope_id != scope_id) {
+ return binding->scope_id < scope_id ? -1 : 1;
+ }
+ return strcmp(binding->name, name);
+}
+
+static int lexical_binding_lower_bound(const WalkState *state, uint32_t scope_id,
+ const char *name) {
+ int low = 0;
+ int high = state->lexical_binding_count;
+ while (low < high) {
+ int middle = low + (high - low) / PAIR_LEN;
+ if (compare_binding_key(&state->lexical_bindings[middle], scope_id, name) < 0) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ return low;
+}
+
+static bool lexical_binding_active_at(const WalkState *state, uint32_t scope_id, const char *name,
+ uint32_t position) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, scope_id);
+ if (!scope) {
+ return false;
+ }
+ int index = lexical_binding_lower_bound(state, scope_id, name);
+ while (index < state->lexical_binding_count) {
+ const CBMLexicalBinding *binding = &state->lexical_bindings[index++];
+ if (binding->scope_id != scope_id || strcmp(binding->name, name) != 0) {
+ break;
+ }
+ uint32_t active_end = binding->active_end ? binding->active_end : scope->end_byte;
+ if (binding->active_start <= position && position < active_end) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static const CBMLexicalScope *lexical_binding_scope_for_usage(const WalkState *state,
+ const CBMUsage *usage,
+ const char *name) {
+ uint32_t scope_id = usage->lexical_scope_id;
+ int remaining = state ? state->lexical_scope_count : 0;
+ while (scope_id != 0 && remaining-- > 0) {
+ const CBMLexicalScope *scope = usage_lexical_scope(state, scope_id);
+ if (!scope) {
+ return NULL;
+ }
+ if (lexical_binding_active_at(state, scope_id, name, usage->site_start_byte)) {
+ return scope;
+ }
+ scope_id = scope->lookup_parent_id;
+ }
+ return NULL;
+}
+
+void cbm_finalize_lexical_usages(CBMExtractCtx *ctx, WalkState *state) {
+ if (!ctx || !state) {
+ return;
+ }
+ if (state->lexical_binding_count > 1) {
+ qsort(state->lexical_bindings, (size_t)state->lexical_binding_count,
+ sizeof(*state->lexical_bindings), compare_lexical_bindings);
+ }
+ for (int i = state->usage_start_index; i < ctx->result->usages.count; i++) {
+ CBMUsage *usage = &ctx->result->usages.items[i];
+ if (!usage->ref_name || !usage->ref_name[0]) {
+ continue;
+ }
+ const char *name = lexical_binding_key(ctx, state, usage->ref_name);
+ if (!name) {
+ continue;
+ }
+ const CBMLexicalScope *binding_scope = lexical_binding_scope_for_usage(state, usage, name);
+ if (!binding_scope) {
+ continue;
+ }
+ usage->semantic_reference_blocked = true;
+ usage->semantic_reference_local_shadow = binding_scope->kind != CBM_LEXICAL_SCOPE_MODULE;
+ }
+
+ /* Allocation failure must never widen textual fallback. Exact semantic
+ * occurrence proof still runs first, but every unproven value fails closed
+ * until the next clean extraction. */
+ if (state->lexical_binding_tracking_failed) {
+ for (int i = state->usage_start_index; i < ctx->result->usages.count; i++) {
+ CBMUsage *usage = &ctx->result->usages.items[i];
+ usage->semantic_reference_blocked = true;
+ const CBMLexicalScope *scope = usage_lexical_scope(state, usage->lexical_scope_id);
+ usage->semantic_reference_local_shadow =
+ scope && scope->kind != CBM_LEXICAL_SCOPE_MODULE;
+ }
+ }
+}
+
+static char *perl_direct_coderef_name(CBMExtractCtx *ctx, TSNode node) {
+ if (!ctx || ctx->language != CBM_LANG_PERL ||
+ strcmp(ts_node_type(node), "refgen_expression") != 0 || !is_direct_argument_value(node)) {
+ return NULL;
+ }
+ char *text = cbm_node_text(ctx->arena, node, ctx->source);
+ const char *amp = text ? strchr(text, '&') : NULL;
+ if (!amp) {
+ return NULL;
+ }
+ const char *start = amp + 1;
+ while (*start && isspace((unsigned char)*start)) {
+ start++;
+ }
+ const char *end = start;
+ while (*end && (isalnum((unsigned char)*end) || *end == '_' || *end == ':')) {
+ end++;
+ }
+ return end > start ? cbm_arena_strndup(ctx->arena, start, (size_t)(end - start)) : NULL;
+}
+
+static bool inside_direct_perl_coderef(CBMExtractCtx *ctx, TSNode node) {
+ if (!ctx || ctx->language != CBM_LANG_PERL) {
+ return false;
+ }
+ for (TSNode parent = ts_node_parent(node); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ if (strcmp(ts_node_type(parent), "refgen_expression") == 0) {
+ return is_direct_argument_value(parent);
+ }
+ if (is_argument_container_kind(ts_node_type(parent))) {
+ return false;
+ }
+ }
+ return false;
+}
+
+static bool emit_direct_perl_coderef_usage(CBMExtractCtx *ctx, TSNode node,
+ const char *enclosing_func_qn,
+ uint32_t lexical_scope_id) {
+ char *name = perl_direct_coderef_name(ctx, node);
+ if (!name || !name[0]) {
return false;
}
- TSNode name_field = ts_node_child_by_field_name(parent, TS_FIELD("name"));
- return !ts_node_is_null(name_field) &&
- ts_node_start_byte(name_field) == ts_node_start_byte(node) &&
- ts_node_end_byte(name_field) == ts_node_end_byte(node);
+ CBMUsage usage = {0};
+ usage.ref_name = name;
+ usage.enclosing_func_qn = enclosing_func_qn;
+ usage.kind = CBM_USAGE_CALL_REFERENCE;
+ usage.may_be_call_reference = true;
+ usage.lexical_scope_id = lexical_scope_id;
+ usage.site_start_byte = ts_node_start_byte(node);
+ usage.site_end_byte = ts_node_end_byte(node);
+ cbm_usages_push(&ctx->result->usages, ctx->arena, usage);
+ return true;
}
// Try to emit a usage for a reference node. Returns early if the node should be skipped.
static void try_emit_usage(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
+ if (emit_direct_perl_coderef_usage(ctx, node, cbm_enclosing_func_qn_cached(ctx, node), 0)) {
+ return;
+ }
+ if (inside_direct_perl_coderef(ctx, node)) {
+ return;
+ }
if (!is_reference_node(node, ctx->language)) {
return;
}
+ if (is_call_argument_label(node)) {
+ return;
+ }
if (is_inside_call(node, spec) || is_inside_import(node, spec)) {
return;
}
- if (is_definition_name(node)) {
+ if (is_binding_occurrence(ctx, node, spec, NULL) ||
+ is_write_occurrence(ctx, node, spec, NULL)) {
return;
}
- char *name = cbm_node_text(ctx->arena, node, ctx->source);
+ char *name = reference_name(ctx, node);
if (name && name[0] && !cbm_is_keyword(name, ctx->language)) {
- CBMUsage usage;
+ CBMUsage usage = {0};
usage.ref_name = name;
usage.enclosing_func_qn = cbm_enclosing_func_qn_cached(ctx, node);
+ stamp_usage_site(ctx, &usage, node, name, NULL);
cbm_usages_push(&ctx->result->usages, ctx->arena, usage);
}
}
@@ -135,36 +2404,104 @@ void cbm_extract_usages(CBMExtractCtx *ctx) {
// Uses WalkState flags instead of parent-chain walks for O(1) context checks.
void handle_usages(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec, WalkState *state) {
- (void)spec;
- if (!is_reference_node(node, ctx->language)) {
+ if (emit_direct_perl_coderef_usage(ctx, node, state->enclosing_func_qn,
+ active_lexical_scope_id(state))) {
+ return;
+ }
+ if (inside_direct_perl_coderef(ctx, node)) {
+ return;
+ }
+ bool reference_node = is_reference_node(node, ctx->language);
+ const CBMOccurrenceSpec *occurrence = &occurrence_specs[ctx->language];
+ bool possible_binding_leaf =
+ ts_node_is_named(node) && ts_node_named_child_count(node) == 0 &&
+ (state->inside_import || is_exact_language_binding(ctx, node, state) ||
+ is_policy_binding(ctx, node, occurrence));
+ if (!reference_node && !possible_binding_leaf) {
return;
}
- // Skip if inside a call (already counted as CALLS edge) — O(1) via state
- if (state->inside_call) {
+ // An invocation relationship replaces only the exact AST occurrence it
+ // consumes. Receivers, qualifiers, computed keys, arguments, and nested
+ // bodies remain ordinary value references. Explicit callable syntax keeps
+ // that exact occurrence as a typed reference instead of erasing it.
+ bool exact_callee =
+ (!ts_node_is_null(state->callee_expr) && ts_node_eq(node, state->callee_expr)) ||
+ (!ts_node_is_null(state->callee_leaf) && ts_node_eq(node, state->callee_leaf));
+ if (exact_callee) {
+ if (reference_node && state->invocation_kind == CBM_INVOCATION_CALLABLE_REFERENCE) {
+ char *name = reference_name(ctx, node);
+ if (name && name[0] && !cbm_is_keyword(name, ctx->language)) {
+ CBMUsage usage = {0};
+ usage.ref_name = name;
+ usage.enclosing_func_qn = state->enclosing_func_qn;
+ usage.lexical_scope_id = usage_lexical_scope_id_for_node(ctx, state, node);
+ /* Kotlin callable-reference syntax is only a precision
+ * candidate. The semantic pass decides whether `::name`
+ * denotes one exact callable; unresolved properties and
+ * ambiguous values must remain ordinary USAGE. */
+ if (ctx->language == CBM_LANG_KOTLIN) {
+ usage.kind = CBM_USAGE_VALUE;
+ usage.may_be_call_reference = true;
+ } else {
+ usage.kind = CBM_USAGE_CALL_REFERENCE;
+ }
+ usage.site_start_byte = ts_node_start_byte(node);
+ usage.site_end_byte = ts_node_end_byte(node);
+ cbm_usages_push(&ctx->result->usages, ctx->arena, usage);
+ }
+ }
+ return;
+ }
+ if (is_forward_sibling_callee(ctx->language, node)) {
return;
}
- // Skip if inside an import
+ if (is_call_argument_label_walk(node, state)) {
+ return;
+ }
+ // Imports do not emit ordinary usages, but their binding occurrence must
+ // be recorded before the subtree is skipped.
if (state->inside_import) {
+ if (is_import_binding_occurrence(ctx, node, spec)) {
+ char *binding_name = reference_name(ctx, node);
+ if (binding_name && binding_name[0] && !cbm_is_keyword(binding_name, ctx->language)) {
+ record_lexical_binding(ctx, state, node, spec, binding_name, true);
+ }
+ }
return;
}
- // Skip if it's a definition name (left side of assignment, function name)
- TSNode parent = ts_node_parent(node);
- if (!ts_node_is_null(parent)) {
- TSNode name_field = ts_node_child_by_field_name(parent, TS_FIELD("name"));
- if (!ts_node_is_null(name_field) &&
- ts_node_start_byte(name_field) == ts_node_start_byte(node) &&
- ts_node_end_byte(name_field) == ts_node_end_byte(node)) {
- return;
+ bool python_scope_directive =
+ ctx->language == CBM_LANG_PYTHON && (lexical_ancestor_kind(node, "global_statement") ||
+ lexical_ancestor_kind(node, "nonlocal_statement"));
+ if (python_scope_directive || is_binding_occurrence(ctx, node, spec, state)) {
+ char *binding_name = reference_name(ctx, node);
+ if (binding_name && binding_name[0] && !cbm_is_keyword(binding_name, ctx->language)) {
+ record_lexical_binding(ctx, state, node, spec, binding_name, false);
+ }
+ return;
+ }
+ if (!reference_node) {
+ return;
+ }
+ if (is_write_occurrence(ctx, node, spec, state)) {
+ if (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL ||
+ ctx->language == CBM_LANG_OBJECTSCRIPT_ROUTINE) {
+ char *binding_name = reference_name(ctx, node);
+ if (binding_name && binding_name[0] && !cbm_is_keyword(binding_name, ctx->language)) {
+ record_lexical_binding(ctx, state, node, spec, binding_name, false);
+ }
}
+ return;
}
- char *name = cbm_node_text(ctx->arena, node, ctx->source);
+ char *name = reference_name(ctx, node);
if (name && name[0] && !cbm_is_keyword(name, ctx->language)) {
- CBMUsage usage;
+ CBMUsage usage = {0};
usage.ref_name = name;
usage.enclosing_func_qn = state->enclosing_func_qn;
+ usage.lexical_scope_id = usage_lexical_scope_id_for_node(ctx, state, node);
+ stamp_usage_site(ctx, &usage, node, name, state);
cbm_usages_push(&ctx->result->usages, ctx->arena, usage);
}
}
diff --git a/internal/cbm/helpers.c b/internal/cbm/helpers.c
index 3cea43ab3..8c9ffdfc0 100644
--- a/internal/cbm/helpers.c
+++ b/internal/cbm/helpers.c
@@ -460,6 +460,19 @@ bool cbm_kind_in_set(TSNode node, const char **types) {
return kind_in_set_strcmp(node, (const char *const *)types);
}
+bool cbm_is_namespace_scope_kind(CBMLanguage lang, const char *kind) {
+ if (!kind) {
+ return false;
+ }
+ if (lang == CBM_LANG_CPP || lang == CBM_LANG_CUDA) {
+ return strcmp(kind, "namespace_definition") == 0;
+ }
+ if (lang == CBM_LANG_TYPESCRIPT || lang == CBM_LANG_TSX) {
+ return strcmp(kind, "internal_module") == 0;
+ }
+ return false;
+}
+
/* Free the calling thread's node-type bitset cache (the calloc'd `bits` arrays
* that cbm_kind_in_set builds lazily). The cache is thread-local, so each worker
* thread and the main thread must call this at teardown (worker exit / process
@@ -917,7 +930,8 @@ const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, co
const char *class_chain = NULL;
for (TSNode cur = ts_node_parent(func_node); !ts_node_is_null(cur);
cur = ts_node_parent(cur)) {
- if (!cbm_kind_in_set(cur, spec->class_node_types)) {
+ if (!cbm_kind_in_set(cur, spec->class_node_types) &&
+ !cbm_is_namespace_scope_kind(lang, ts_node_type(cur))) {
continue;
}
TSNode class_name = ts_node_child_by_field_name(cur, TS_FIELD("name"));
diff --git a/internal/cbm/helpers.h b/internal/cbm/helpers.h
index 6fb136294..492dc0552 100644
--- a/internal/cbm/helpers.h
+++ b/internal/cbm/helpers.h
@@ -86,6 +86,11 @@ TSNode cbm_find_child_by_kind(TSNode parent, const char *kind);
// Check if node kind matches a set of types (NULL-terminated array of strings).
bool cbm_kind_in_set(TSNode node, const char **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. */
+bool cbm_is_namespace_scope_kind(CBMLanguage lang, const char *kind);
+
// Free the calling thread's cbm_kind_in_set bitset cache (call at thread/process
// teardown so the thread-local cache is not reported as a leak).
void cbm_kind_in_set_free_cache(void);
diff --git a/internal/cbm/lang_specs.c b/internal/cbm/lang_specs.c
index bcc4b5548..2bc1fe1e7 100644
--- a/internal/cbm/lang_specs.c
+++ b/internal/cbm/lang_specs.c
@@ -198,9 +198,10 @@ static const char *go_assign_types[] = {"assignment_statement", "short_var_decla
static const char *py_func_types[] = {"function_definition", NULL};
static const char *py_class_types[] = {"class_definition", NULL};
static const char *py_module_types[] = {"module", NULL};
-static const char *py_call_types[] = {"call", "with_statement", NULL};
+static const char *py_call_types[] = {"call", NULL};
static const char *py_import_types[] = {"import_statement", "import", NULL};
-static const char *py_import_from_types[] = {"import_from_statement", NULL};
+static const char *py_import_from_types[] = {"import_from_statement", "future_import_statement",
+ NULL};
static const char *py_branch_types[] = {
"if_statement", "for_statement", "while_statement", "try_statement",
"except_clause", "with_statement", "elif_clause", NULL};
@@ -215,13 +216,8 @@ static const char *js_func_types[] = {"function_declaration", "generator_functio
static const char *js_class_types[] = {"class_declaration", "class", NULL};
static const char *js_module_types[] = {"program", NULL};
static const char *js_call_types[] = {"call_expression", "new_expression", NULL};
-static const char *js_import_types[] = {"import_statement",
- "lexical_declaration",
- "export_statement",
- "import",
- "extends",
- "require",
- NULL};
+static const char *js_import_types[] = {"import_statement", "export_statement", "import",
+ "extends", "require", NULL};
static const char *js_branch_types[] = {"if_statement",
"for_statement",
"for_in_statement",
@@ -343,12 +339,8 @@ static const char *cpp_class_types[] = {"class_specifier", "struct_specifier", "
static const char *cpp_field_types[] = {"field_declaration", NULL};
static const char *cpp_module_types[] = {"translation_unit", "namespace_definition",
"linkage_specification", "declaration", NULL};
-static const char *cpp_call_types[] = {
- "call_expression", "field_expression", "subscript_expression",
- "new_expression", "delete_expression", "binary_expression",
- "unary_expression", "update_expression", NULL};
-static const char *cpp_import_types[] = {"preproc_include", "template_function", "declaration",
- NULL};
+static const char *cpp_call_types[] = {"call_expression", "new_expression", NULL};
+static const char *cpp_import_types[] = {"preproc_include", NULL};
static const char *cpp_branch_types[] = {"if_statement", "for_statement", "for_range_loop",
"while_statement", "switch_statement", "case_statement",
"try_statement", "catch_clause", NULL};
@@ -422,8 +414,7 @@ static const char *scala_class_types[] = {"class_definition", "object_definition
"trait_definition", "enum_definition",
"type_definition", NULL};
static const char *scala_module_types[] = {"compilation_unit", NULL};
-static const char *scala_call_types[] = {"call_expression", "generic_function",
- "field_expression", "infix_expression",
+static const char *scala_call_types[] = {"call_expression", "infix_expression",
"instance_expression", NULL};
static const char *scala_import_types[] = {"import_declaration", "extends", "import",
"using_directive", NULL};
@@ -442,7 +433,7 @@ static const char *kotlin_func_types[] = {"function_declaration", "secondary_con
static const char *kotlin_class_types[] = {"class_declaration", "object_declaration",
"companion_object", "type_alias", NULL};
static const char *kotlin_module_types[] = {"source_file", NULL};
-static const char *kotlin_call_types[] = {"call_expression", "navigation_expression", NULL};
+static const char *kotlin_call_types[] = {"call_expression", NULL};
static const char *kotlin_import_types[] = {"import", NULL};
static const char *kotlin_branch_types[] = {
"if_expression", "for_statement", "while_statement", "when_expression",
@@ -456,7 +447,7 @@ static const char *kotlin_decorator_types[] = {"annotation", NULL};
static const char *ruby_func_types[] = {"method", "singleton_method", NULL};
static const char *ruby_class_types[] = {"class", "module", NULL};
static const char *ruby_module_types[] = {"program", NULL};
-static const char *ruby_call_types[] = {"call", "command_call", NULL};
+static const char *ruby_call_types[] = {"call", NULL};
static const char *ruby_import_types[] = {"call", NULL};
static const char *ruby_branch_types[] = {"if", "unless", "while", "until", "for",
"case", "when", "rescue", "elsif", NULL};
@@ -507,7 +498,7 @@ static const char *zig_assign_types[] = {"assignment_expression", NULL};
// ==================== ELIXIR ====================
static const char *elixir_func_types[] = {"call", "anonymous_function", NULL};
static const char *elixir_module_types[] = {"source", NULL};
-static const char *elixir_call_types[] = {"call", "dot", "binary_operator", NULL};
+static const char *elixir_call_types[] = {"call", "binary_operator", NULL};
static const char *elixir_import_types[] = {"call", NULL};
static const char *elixir_branch_types[] = {"call", NULL};
static const char *elixir_var_types[] = {"binary_operator", NULL};
@@ -562,7 +553,7 @@ static const char *swift_class_types[] = {"class_declaration", "protocol_declara
static const char *swift_field_types[] = {"property_declaration", NULL};
static const char *swift_module_types[] = {"source_file", NULL};
static const char *swift_call_types[] = {"call_expression", "constructor_expression",
- "macro_invocation", "navigation_expression", NULL};
+ "macro_invocation", NULL};
static const char *swift_import_types[] = {"import_declaration", "import", NULL};
static const char *swift_branch_types[] = {"if_statement", "guard_statement", "for_statement",
"while_statement", "switch_statement", NULL};
@@ -669,7 +660,7 @@ static const char *sql_func_types[] = {"create_function", "function_declaration"
static const char *sql_field_types[] = {"column_definition", NULL};
static const char *sql_class_types[] = {"custom_type", NULL};
static const char *sql_module_types[] = {"program", NULL};
-static const char *sql_call_types[] = {"function_call", "invocation", "command", NULL};
+static const char *sql_call_types[] = {"invocation", NULL};
static const char *sql_branch_types[] = {"if_statement", "case_expression", NULL};
static const char *sql_var_types[] = {"create_table", "create_view", NULL};
@@ -717,7 +708,7 @@ static const char *fsharp_func_types[] = {"function_declaration", "value_declara
"function_or_value_defn", NULL};
static const char *fsharp_class_types[] = {"type_definition", "exception_definition", NULL};
static const char *fsharp_module_types[] = {"file", NULL};
-static const char *fsharp_call_types[] = {"application_expression", "dot_expression", NULL};
+static const char *fsharp_call_types[] = {"application_expression", NULL};
static const char *fsharp_import_types[] = {"import_decl", "open_expression", "instance", NULL};
static const char *fsharp_branch_types[] = {"if_expression", "for_expression",
"while_expression", "match_expression",
@@ -770,7 +761,7 @@ static const char *elm_func_types[] = {"value_declaration", "function_declaratio
static const char *elm_class_types[] = {"type_declaration", "type_alias_declaration",
"module_declaration", NULL};
static const char *elm_module_types[] = {"file", NULL};
-static const char *elm_call_types[] = {"function_call", "function_call_expr", NULL};
+static const char *elm_call_types[] = {"function_call_expr", NULL};
static const char *elm_import_types[] = {"import", NULL};
static const char *elm_branch_types[] = {"case_of_expr", "if_else_expr", NULL};
@@ -781,7 +772,7 @@ static const char *fortran_func_types[] = {"function", "subroutine", "function_s
"subroutine_statement", NULL};
static const char *fortran_class_types[] = {"derived_type_definition", "enum_statement", NULL};
static const char *fortran_module_types[] = {"translation_unit", NULL};
-static const char *fortran_call_types[] = {"call_expression", "keyword_argument", "call", NULL};
+static const char *fortran_call_types[] = {"call_expression", "subroutine_call", NULL};
static const char *fortran_import_types[] = {"use_statement", "include_statement", "extends",
"import", "import_statement", "include",
"open_statement", "preproc_include", NULL};
@@ -926,7 +917,7 @@ static const char *matlab_var_types[] = {"assignment", NULL};
static const char *lean_func_types[] = {"def", "theorem", "instance", "abbrev", NULL};
static const char *lean_class_types[] = {"structure", "class_inductive", "inductive", NULL};
static const char *lean_module_types[] = {"module", NULL};
-static const char *lean_call_types[] = {"apply", "command", NULL};
+static const char *lean_call_types[] = {"apply", NULL};
static const char *lean_import_types[] = {"import", "extends", "instance", NULL};
static const char *lean_branch_types[] = {"if", "match", "do", NULL};
@@ -973,8 +964,7 @@ static const char *d_class_types[] = {"class_declaration",
"module_def",
NULL};
static const char *d_field_types[] = {"variable_declaration", NULL};
-static const char *d_call_types[] = {"call_expression", "function_call_expression",
- "new_expression", NULL};
+static const char *d_call_types[] = {"call_expression", "new_expression", NULL};
static const char *d_import_types[] = {"import_declaration", "import", NULL};
static const char *d_branch_types[] = {"if_statement", "for_statement", "foreach_statement",
"while_statement", "do_statement", "switch_statement",
@@ -1094,7 +1084,7 @@ static const char *fish_module_types[] = {"program", NULL};
* called by name, so a call inside a rule is legitimately Module-sourced, and a
* rule must NOT be treated as a function boundary. */
static const char *awk_func_types[] = {"func_def", NULL};
-static const char *awk_call_types[] = {"func_call", "command", NULL};
+static const char *awk_call_types[] = {"func_call", NULL};
static const char *awk_branch_types[] = {"if_statement",
"for_statement",
"for_in_statement",
@@ -1309,7 +1299,7 @@ static const char *prisma_call_types[] = {"call_expression", NULL};
static const char *prisma_module_types[] = {"program", NULL};
static const char *hyprlang_module_types[] = {"source_file", NULL};
static const char *dotenv_module_types[] = {"source_file", NULL};
-static const char *diff_call_types[] = {"command", NULL};
+static const char *diff_call_types[] = {NULL};
static const char *diff_module_types[] = {"source", NULL};
static const char *wgsl_func_types[] = {"function_declaration", NULL};
static const char *wgsl_class_types[] = {"struct_declaration", "type_alias_declaration",
@@ -1352,7 +1342,7 @@ static const char *properties_var_types[] = {"property", NULL};
/* tree-sitter-properties roots the tree at `file`, not `source_file`. */
static const char *properties_module_types[] = {"file", "source_file", NULL};
static const char *sshconfig_module_types[] = {"source_file", NULL};
-static const char *bibtex_call_types[] = {"command", NULL};
+static const char *bibtex_call_types[] = {NULL};
static const char *bibtex_module_types[] = {"document", NULL};
static const char *starlark_func_types[] = {"function_definition", "lambda", NULL};
static const char *starlark_call_types[] = {"call", NULL};
@@ -1423,7 +1413,7 @@ static const char *devicetree_call_types[] = {"call_expression", NULL};
static const char *devicetree_import_types[] = {"dtsi_include", "preproc_include", NULL};
static const char *devicetree_module_types[] = {"document", NULL};
static const char *linkerscript_call_types[] = {"call_expression", NULL};
-static const char *linkerscript_module_types[] = {"source_file", NULL};
+static const char *linkerscript_module_types[] = {"linkerscript", NULL};
static const char *gn_call_types[] = {"call_expression", NULL};
static const char *gn_import_types[] = {"import_statement", "import", NULL};
static const char *gn_branch_types[] = {"if_statement", "foreach_statement", NULL};
@@ -1510,8 +1500,7 @@ static const char *mermaid_module_types[] = {"source_file", NULL};
static const char *puppet_func_types[] = {"function_declaration", "lambda", NULL};
static const char *puppet_class_types[] = {"class_definition", "node_definition",
"resource_declaration", "type_declaration", NULL};
-static const char *puppet_call_types[] = {"function_call", "resource_declaration",
- "include_statement", NULL};
+static const char *puppet_call_types[] = {"function_call", "include_statement", NULL};
static const char *puppet_import_types[] = {"include_statement", "require_statement", "include",
"require", NULL};
static const char *puppet_branch_types[] = {"if_statement", "unless_statement", "case_statement",
@@ -1628,7 +1617,9 @@ static const char *objectscript_udl_module_types[] = {"source_file", NULL};
static const char *objectscript_udl_branch_types[] = {
"command_if", "command_for", "command_while", "elseif_block", "catch_block", NULL};
-static const char *objectscript_routine_func_types[] = {"tag", NULL};
+/* Parameterized entries are `procedure` nodes whose direct `tag` child names
+ * the callable; bare labels remain standalone `tag` nodes. */
+static const char *objectscript_routine_func_types[] = {"procedure", "tag", NULL};
static const char *objectscript_routine_call_types[] = {"extrinsic_function", "routine_tag_call",
NULL};
static const char *objectscript_routine_module_types[] = {"source_file", NULL};
@@ -2645,7 +2636,11 @@ const CBMLangSpec *cbm_lang_spec(CBMLanguage lang) {
if (lang < 0 || lang >= CBM_LANG_COUNT) {
return NULL;
}
- return &lang_specs[lang];
+ const CBMLangSpec *spec = &lang_specs[lang];
+ if (spec->language != lang || !spec->function_node_types) {
+ return NULL;
+ }
+ return spec;
}
const TSLanguage *cbm_ts_language(CBMLanguage lang) {
diff --git a/internal/cbm/lsp/c_lsp.c b/internal/cbm/lsp/c_lsp.c
index 3915dcb8b..a680d56d2 100644
--- a/internal/cbm/lsp/c_lsp.c
+++ b/internal/cbm/lsp/c_lsp.c
@@ -65,8 +65,10 @@ void c_lsp_init(CLSPContext *ctx, CBMArena *arena, const char *source, int sourc
ctx->registry = registry;
ctx->module_qn = module_qn;
ctx->module_qn_len = module_qn ? strlen(module_qn) : 0;
+ ctx->enclosing_func_qn = module_qn;
ctx->cpp_mode = cpp_mode;
ctx->resolved_calls = out;
+ ctx->source_origin = CBM_SOURCE_ORIGIN_RAW;
ctx->current_scope = cbm_scope_push(arena, NULL);
const char *debug_env = getenv("CBM_LSP_DEBUG");
@@ -164,28 +166,79 @@ static void c_add_fp_target(CLSPContext *ctx, const char *var_name, const char *
(const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
const char **new_qns =
(const char **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const char *));
- if (!new_names || !new_qns)
+ const CBMScope **new_scopes =
+ (const CBMScope **)cbm_arena_alloc(ctx->arena, new_cap * sizeof(const CBMScope *));
+ if (!new_names || !new_qns || !new_scopes)
return;
if (ctx->fp_var_names && ctx->fp_count > 0) {
memcpy(new_names, ctx->fp_var_names, ctx->fp_count * sizeof(const char *));
memcpy(new_qns, ctx->fp_target_qns, ctx->fp_count * sizeof(const char *));
+ memcpy(new_scopes, ctx->fp_binding_scopes, ctx->fp_count * sizeof(const CBMScope *));
}
ctx->fp_var_names = new_names;
ctx->fp_target_qns = new_qns;
+ ctx->fp_binding_scopes = new_scopes;
ctx->fp_cap = new_cap;
}
ctx->fp_var_names[ctx->fp_count] = cbm_arena_strdup(ctx->arena, var_name);
- ctx->fp_target_qns[ctx->fp_count] = cbm_arena_strdup(ctx->arena, target_qn);
+ ctx->fp_target_qns[ctx->fp_count] = target_qn ? cbm_arena_strdup(ctx->arena, target_qn) : NULL;
+ ctx->fp_binding_scopes[ctx->fp_count] = ctx->current_scope;
ctx->fp_count++;
}
-// Look up function pointer target
-static const char *c_lookup_fp_target(CLSPContext *ctx, const char *var_name) {
+static bool c_scope_declares_name(const CBMScope *scope, const char *var_name) {
+ if (!scope || !var_name) {
+ return false;
+ }
+ for (const CBMScopeChunk *chunk = scope->chunks; chunk; chunk = chunk->next) {
+ for (int i = 0; i < chunk->used; i++) {
+ if (chunk->bindings[i].name && strcmp(chunk->bindings[i].name, var_name) == 0) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+/* Return the exact fp-state entry for the nearest lexical declaration. An
+ * ordinary declaration in an intervening scope blocks an outer fp target even
+ * though it has no fp-state entry of its own. */
+static int c_find_fp_binding_index(CLSPContext *ctx, const char *var_name) {
+ if (!ctx || !var_name) {
+ return -1;
+ }
for (int i = ctx->fp_count - 1; i >= 0; i--) {
- if (strcmp(ctx->fp_var_names[i], var_name) == 0)
- return ctx->fp_target_qns[i];
+ if (!ctx->fp_var_names[i] || strcmp(ctx->fp_var_names[i], var_name) != 0) {
+ continue;
+ }
+ const CBMScope *binding_scope = ctx->fp_binding_scopes[i];
+ for (const CBMScope *scope = ctx->current_scope; scope; scope = scope->parent) {
+ if (scope == binding_scope) {
+ return i;
+ }
+ if (c_scope_declares_name(scope, var_name)) {
+ return -1;
+ }
+ }
+ }
+ return -1;
+}
+
+// Look up an exact target; NULL also represents a present but ambiguous binding.
+static const char *c_lookup_fp_target(CLSPContext *ctx, const char *var_name) {
+ int index = c_find_fp_binding_index(ctx, var_name);
+ return index >= 0 ? ctx->fp_target_qns[index] : NULL;
+}
+
+// Reassignment updates the nearest visible fp binding. `target_qn == NULL`
+// records an explicit unknown state rather than leaking the previous target.
+static void c_update_fp_target(CLSPContext *ctx, const char *var_name, const char *target_qn) {
+ if (!ctx || !var_name)
+ return;
+ int index = c_find_fp_binding_index(ctx, var_name);
+ if (index >= 0) {
+ ctx->fp_target_qns[index] = target_qn ? cbm_arena_strdup(ctx->arena, target_qn) : NULL;
}
- return NULL;
}
// --- Helper: extract function name from DLL/dynamic resolver call ---
@@ -827,6 +880,60 @@ static const char *c_resolve_name_to_func_qn(CLSPContext *ctx, const char *name)
return NULL;
}
+/* Resolve only the two C-family expression shapes that denote one named
+ * function without evaluation: `handler` and `&handler`. Casts, conditionals,
+ * comma expressions, dereferences, and calls are intentionally non-exact. */
+static const char *c_exact_function_target_from_expr(CLSPContext *ctx, TSNode expr) {
+ if (!ctx || ts_node_is_null(expr)) {
+ return NULL;
+ }
+ const char *kind = ts_node_type(expr);
+ if (strcmp(kind, "identifier") == 0) {
+ char *name = c_node_text(ctx, expr);
+ if (!name) {
+ return NULL;
+ }
+ int fp_index = c_find_fp_binding_index(ctx, name);
+ if (fp_index >= 0) {
+ return ctx->fp_target_qns[fp_index];
+ }
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ return NULL;
+ }
+ return c_resolve_name_to_func_qn(ctx, name);
+ }
+ if (strcmp(kind, "pointer_expression") != 0 && strcmp(kind, "unary_expression") != 0) {
+ return NULL;
+ }
+
+ bool address_of = false;
+ TSNode operand = (TSNode){0};
+ uint32_t child_count = ts_node_child_count(expr);
+ for (uint32_t i = 0; i < child_count; i++) {
+ TSNode child = ts_node_child(expr, i);
+ if (ts_node_is_named(child)) {
+ if (!ts_node_is_null(operand)) {
+ return NULL;
+ }
+ operand = child;
+ continue;
+ }
+ char *token = c_node_text(ctx, child);
+ if (token && strcmp(token, "&") == 0) {
+ address_of = true;
+ }
+ }
+ if (!address_of || ts_node_is_null(operand) ||
+ strcmp(ts_node_type(operand), "identifier") != 0) {
+ return NULL;
+ }
+ char *name = c_node_text(ctx, operand);
+ if (!name || cbm_scope_contains(ctx->current_scope, name)) {
+ return NULL;
+ }
+ return c_resolve_name_to_func_qn(ctx, name);
+}
+
// Resolve a name to a type (for identifiers used as types)
static const CBMType *c_resolve_name_to_type(CLSPContext *ctx, const char *name) {
if (!name)
@@ -1646,7 +1753,7 @@ static const CBMType *c_eval_expr_type_inner(CLSPContext *ctx, TSNode node) {
(const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
rets[0] = base_ret;
rets[1] = NULL;
- return cbm_type_func(ctx->arena, NULL, NULL, rets);
+ return cbm_type_func_replace_returns(ctx->arena, f->signature, rets);
}
return f->signature;
}
@@ -1796,7 +1903,7 @@ static const CBMType *c_eval_expr_type_inner(CLSPContext *ctx, TSNode node) {
const CBMType **rets = cbm_arena_alloc(ctx->arena, 2 * sizeof(CBMType *));
rets[0] = base_ret;
rets[1] = NULL;
- return cbm_type_func(ctx->arena, NULL, NULL, rets);
+ return cbm_type_func_replace_returns(ctx->arena, f->signature, rets);
}
// --- call_expression: f(args) ---
@@ -3043,68 +3150,24 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
if (var_name && var_name[0] && strcmp(var_name, "_") != 0) {
cbm_scope_bind(ctx->current_scope, var_name, var_type);
- // Track function pointer targets: fp = &foo or fp = foo
- // Accept pointer, func, or named types (typedef function pointers
- // like fn_t appear as CBM_TYPE_NAMED, not FUNC/POINTER).
- if (var_type && (var_type->kind == CBM_TYPE_FUNC ||
- var_type->kind == CBM_TYPE_POINTER ||
- var_type->kind == CBM_TYPE_NAMED)) {
- if (!ts_node_is_null(value)) {
- const char *vk = ts_node_type(value);
- // pointer_expression with & operator: &foo
- if (strcmp(vk, "pointer_expression") == 0 ||
- strcmp(vk, "unary_expression") == 0) {
- uint32_t vnc = ts_node_named_child_count(value);
- for (uint32_t vi = 0; vi < vnc; vi++) {
- TSNode vch = ts_node_named_child(value, vi);
- if (strcmp(ts_node_type(vch), "identifier") == 0) {
- char *target_name = c_node_text(ctx, vch);
- if (target_name) {
- const char *target_qn =
- c_resolve_name_to_func_qn(ctx, target_name);
- if (target_qn) {
- c_add_fp_target(ctx, var_name, target_qn);
- }
- }
- break;
- }
- }
- }
- // Direct identifier: fp = foo (function decays to pointer)
- else if (strcmp(vk, "identifier") == 0) {
- char *target_name = c_node_text(ctx, value);
- if (target_name) {
- const char *target_qn =
- c_resolve_name_to_func_qn(ctx, target_name);
- if (target_qn) {
- c_add_fp_target(ctx, var_name, target_qn);
- }
- }
- }
- }
- }
-
- // Fallback: if RHS is an identifier resolving to a known function,
- // track as fp target even when var_type is unknown (typedef func ptrs).
- if (!c_lookup_fp_target(ctx, var_name) && !ts_node_is_null(value)) {
- const char *vk = ts_node_type(value);
- if (strcmp(vk, "identifier") == 0) {
- char *target_name = c_node_text(ctx, value);
- if (target_name) {
- const char *target_qn =
- c_resolve_name_to_func_qn(ctx, target_name);
- if (target_qn) {
- c_add_fp_target(ctx, var_name, target_qn);
- }
- }
- }
- }
+ /* Record one lexical fp state, including an explicit
+ * NULL state for callable-looking declarations whose
+ * initializer is dynamic/ambiguous. The NULL entry is
+ * important: it shadows an outer exact fp of the same
+ * name and can later become exact after an unconditional
+ * direct assignment. */
+ bool function_pointer_like =
+ var_type &&
+ (var_type->kind == CBM_TYPE_FUNC || var_type->kind == CBM_TYPE_POINTER);
+ const char *fp_target = ts_node_is_null(value)
+ ? NULL
+ : c_exact_function_target_from_expr(ctx, value);
// DLL/dynamic resolver heuristic: fp = (FuncType)Resolve("FuncName")
// If RHS is a call (possibly cast-wrapped) with a string literal arg,
// and variable has function-pointer-like type or RHS has a cast,
// treat the string as an external function name.
- if (!c_lookup_fp_target(ctx, var_name) && !ts_node_is_null(value)) {
+ if (!fp_target && !ts_node_is_null(value)) {
bool has_cast = false;
const char *dll_func =
c_extract_dll_resolve_name(ctx, value, &has_cast);
@@ -3112,12 +3175,14 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
bool is_fp_type = var_type && (var_type->kind == CBM_TYPE_FUNC ||
var_type->kind == CBM_TYPE_POINTER);
if (is_fp_type || has_cast) {
- const char *target_qn =
+ fp_target =
cbm_arena_sprintf(ctx->arena, "external.%s", dll_func);
- c_add_fp_target(ctx, var_name, target_qn);
}
}
}
+ if (function_pointer_like || fp_target) {
+ c_add_fp_target(ctx, var_name, fp_target);
+ }
}
}
} else if (strcmp(ck, "identifier") == 0) {
@@ -3145,6 +3210,36 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
cbm_scope_bind(ctx->current_scope, var_name, vt);
}
}
+ } else if (strcmp(ck, "function_declarator") == 0) {
+ /* Bare function-pointer declaration: `int (*fp)(void);`.
+ * Ordinary function prototypes have no pointer in the nested
+ * declarator and are intentionally ignored here. */
+ TSNode inner = ts_node_child_by_field_name(child, "declarator", 10);
+ bool saw_pointer = false;
+ while (!ts_node_is_null(inner)) {
+ const char *inner_kind = ts_node_type(inner);
+ if (strcmp(inner_kind, "pointer_declarator") == 0) {
+ saw_pointer = true;
+ }
+ if (strcmp(inner_kind, "identifier") == 0) {
+ if (saw_pointer) {
+ char *var_name = c_node_text(ctx, inner);
+ if (var_name && var_name[0]) {
+ const CBMType *var_type = cbm_type_pointer(ctx->arena, base_type);
+ cbm_scope_bind(ctx->current_scope, var_name, var_type);
+ c_add_fp_target(ctx, var_name, NULL);
+ }
+ }
+ break;
+ }
+ if ((strcmp(inner_kind, "parenthesized_declarator") != 0 &&
+ strcmp(inner_kind, "pointer_declarator") != 0 &&
+ strcmp(inner_kind, "reference_declarator") != 0) ||
+ ts_node_named_child_count(inner) == 0) {
+ break;
+ }
+ inner = ts_node_named_child(inner, ts_node_named_child_count(inner) - 1);
+ }
} else if (strcmp(ck, "array_declarator") == 0) {
// Type var[N]; without initializer
TSNode inner = ts_node_child_by_field_name(child, "declarator", 10);
@@ -3160,6 +3255,37 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
return;
}
+ /* Function-pointer reassignment. Only a plain, unconditional assignment to
+ * one named function preserves exact identity. Every other assignment to a
+ * tracked fp explicitly invalidates the old target. Inside control flow we
+ * also invalidate after an exact-looking assignment: without path merging,
+ * the pre-branch value remains a possible runtime target. */
+ if (strcmp(kind, "assignment_expression") == 0) {
+ bool simple_assignment = false;
+ for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child)) {
+ char *op = c_node_text(ctx, child);
+ if (op && strcmp(op, "=") == 0) {
+ simple_assignment = true;
+ break;
+ }
+ }
+ }
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(left) && strcmp(ts_node_type(left), "identifier") == 0) {
+ char *var_name = c_node_text(ctx, left);
+ if (var_name && c_find_fp_binding_index(ctx, var_name) >= 0) {
+ const char *target_qn = simple_assignment && !ts_node_is_null(right)
+ ? c_exact_function_target_from_expr(ctx, right)
+ : NULL;
+ c_update_fp_target(ctx, var_name, ctx->control_flow_depth == 0 ? target_qn : NULL);
+ }
+ }
+ return;
+ }
+
// using_declaration: using namespace std; or using std::cout;
if (strcmp(kind, "using_declaration") == 0) {
char *text = c_node_text(ctx, node);
@@ -3486,11 +3612,186 @@ void c_process_statement(CLSPContext *ctx, TSNode node) {
// Emit helpers
// ============================================================================
-static void c_emit_resolved_call_orig(CLSPContext *ctx, const char *callee_qn, const char *orig,
- const char *strategy, float confidence) {
+static bool c_qn_has_exact_scope(const char *qualified_name, const char *scope) {
+ if (!qualified_name || !scope || !scope[0])
+ return false;
+ const char *dot = strrchr(qualified_name, '.');
+ size_t qn_scope_len = dot ? (size_t)(dot - qualified_name) : 0;
+ return qn_scope_len == strlen(scope) && strncmp(qualified_name, scope, qn_scope_len) == 0;
+}
+
+static int c_operator_param_count(const CBMRegisteredFunc *candidate) {
+ if (!candidate || !candidate->signature || candidate->signature->kind != CBM_TYPE_FUNC) {
+ return -1;
+ }
+ int count = 0;
+ const CBMType *const *params = candidate->signature->data.func.param_types;
+ while (params && params[count]) {
+ count++;
+ }
+ return count;
+}
+
+static bool c_operator_signature_matches(CLSPContext *ctx, const CBMRegisteredFunc *candidate,
+ const CBMType *const *actuals, int actual_count) {
+ if (!candidate || candidate->receiver_type || !candidate->signature ||
+ candidate->signature->kind != CBM_TYPE_FUNC || actual_count < 0 ||
+ c_operator_param_count(candidate) != actual_count) {
+ return false;
+ }
+ const CBMType *const *params = candidate->signature->data.func.param_types;
+ for (int i = 0; i < actual_count; i++) {
+ const CBMType *expected = c_simplify_type(ctx, params[i], false);
+ const CBMType *actual = c_simplify_type(ctx, actuals[i], false);
+ const char *expected_qn = type_to_qn(expected);
+ const char *actual_qn = type_to_qn(actual);
+ if (!expected_qn || !actual_qn || strcmp(expected_qn, actual_qn) != 0) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/* Resolve a non-member C++ operator only when both operand types exactly match
+ * a unique free overload in the current/associated namespace. Ambiguous,
+ * templated, or otherwise unprovable cases deliberately stay unresolved. */
+static const CBMRegisteredFunc *c_lookup_free_operator(CLSPContext *ctx, const char *operator_name,
+ const CBMType *left_type,
+ const CBMType *right_type) {
+ if (!ctx || !ctx->registry || !operator_name || !left_type || !right_type)
+ return NULL;
+
+ const char *left_qn = type_to_qn(c_simplify_type(ctx, left_type, false));
+ const char *right_qn = type_to_qn(c_simplify_type(ctx, right_type, false));
+ const char *left_ns = extract_namespace_from_qn(ctx->arena, left_qn);
+ const char *right_ns = extract_namespace_from_qn(ctx->arena, right_qn);
+ const CBMRegisteredFunc *match = NULL;
+ CBMFreeFuncIter it;
+ cbm_registry_free_funcs_by_short_name(ctx->registry, operator_name, &it);
+ for (int index = cbm_free_func_iter_next(&it); index >= 0;
+ index = cbm_free_func_iter_next(&it)) {
+ if (index >= ctx->registry->func_count)
+ continue;
+ const CBMRegisteredFunc *candidate = &ctx->registry->funcs[index];
+ if (candidate->receiver_type || !candidate->short_name ||
+ strcmp(candidate->short_name, operator_name) != 0 || !candidate->qualified_name) {
+ continue;
+ }
+ bool associated = c_qn_has_exact_scope(candidate->qualified_name, ctx->current_namespace) ||
+ c_qn_has_exact_scope(candidate->qualified_name, ctx->module_qn) ||
+ c_qn_has_exact_scope(candidate->qualified_name, left_ns) ||
+ c_qn_has_exact_scope(candidate->qualified_name, right_ns);
+ const CBMType *actuals[2] = {left_type, right_type};
+ bool signature_matches = c_operator_signature_matches(ctx, candidate, actuals, 2);
+ if (ctx->debug) {
+ const CBMType *const *params =
+ candidate->signature && candidate->signature->kind == CBM_TYPE_FUNC
+ ? candidate->signature->data.func.param_types
+ : NULL;
+ int param_count = 0;
+ while (params && params[param_count]) {
+ param_count++;
+ }
+ const char *p0 =
+ param_count > 0 ? type_to_qn(c_simplify_type(ctx, params[0], false)) : NULL;
+ const char *p1 =
+ param_count > 1 ? type_to_qn(c_simplify_type(ctx, params[1], false)) : NULL;
+ fprintf(stderr,
+ " [clsp] free operator candidate=%s lhs=%s rhs=%s associated=%d "
+ "signature=%d p0=%s p1=%s extra=%d\n",
+ candidate->qualified_name, left_qn ? left_qn : "?", right_qn ? right_qn : "?",
+ associated, signature_matches, p0 ? p0 : "?", p1 ? p1 : "?", param_count > 2);
+ }
+ if (!associated || !signature_matches) {
+ continue;
+ }
+ if (match && strcmp(match->qualified_name, candidate->qualified_name) != 0) {
+ return NULL;
+ }
+ match = candidate;
+ }
+ return match;
+}
+
+/* Unary ADL is intentionally narrower than ordinary free-function lookup: the
+ * operand type must exactly match a single one-parameter overload in the
+ * current or associated namespace. Unknown/ambiguous cases stay unresolved. */
+static const CBMRegisteredFunc *c_lookup_free_unary_operator(CLSPContext *ctx,
+ const char *operator_name,
+ const CBMType *operand_type) {
+ if (!ctx || !ctx->registry || !operator_name || !operand_type) {
+ return NULL;
+ }
+ const char *operand_qn = type_to_qn(c_simplify_type(ctx, operand_type, false));
+ const char *operand_ns = extract_namespace_from_qn(ctx->arena, operand_qn);
+ const CBMRegisteredFunc *match = NULL;
+ const CBMType *actuals[1] = {operand_type};
+ CBMFreeFuncIter it;
+ cbm_registry_free_funcs_by_short_name(ctx->registry, operator_name, &it);
+ for (int index = cbm_free_func_iter_next(&it); index >= 0;
+ index = cbm_free_func_iter_next(&it)) {
+ if (index >= ctx->registry->func_count) {
+ continue;
+ }
+ const CBMRegisteredFunc *candidate = &ctx->registry->funcs[index];
+ if (candidate->receiver_type || !candidate->short_name ||
+ strcmp(candidate->short_name, operator_name) != 0 || !candidate->qualified_name) {
+ continue;
+ }
+ bool associated = c_qn_has_exact_scope(candidate->qualified_name, ctx->current_namespace) ||
+ c_qn_has_exact_scope(candidate->qualified_name, ctx->module_qn) ||
+ c_qn_has_exact_scope(candidate->qualified_name, operand_ns);
+ if (!associated || !c_operator_signature_matches(ctx, candidate, actuals, 1)) {
+ continue;
+ }
+ if (match && strcmp(match->qualified_name, candidate->qualified_name) != 0) {
+ return NULL;
+ }
+ match = candidate;
+ }
+ return match;
+}
+
+/* Operator syntax has a fixed explicit arity. Refuse the registry API's
+ * permissive "any overload" fallback when no exact-arity method exists. */
+static const CBMRegisteredFunc *c_lookup_member_operator_by_arity(CLSPContext *ctx,
+ const char *type_qn,
+ const char *operator_name,
+ int explicit_arg_count) {
+ if (!ctx || !ctx->registry || !type_qn || !operator_name) {
+ return NULL;
+ }
+ const CBMRegisteredFunc *candidate = cbm_registry_lookup_method_by_args(
+ ctx->registry, type_qn, operator_name, explicit_arg_count);
+ if (candidate && c_operator_param_count(candidate) == explicit_arg_count) {
+ return candidate;
+ }
+ if (ctx->module_qn) {
+ const char *prefixed = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, type_qn);
+ candidate = cbm_registry_lookup_method_by_args(ctx->registry, prefixed, operator_name,
+ explicit_arg_count);
+ if (candidate && c_operator_param_count(candidate) == explicit_arg_count) {
+ return candidate;
+ }
+ }
+ candidate = c_lookup_member(ctx, type_qn, operator_name);
+ return candidate && c_operator_param_count(candidate) == explicit_arg_count ? candidate : NULL;
+}
+
+static bool c_is_compound_assignment_operator(const char *operator_token) {
+ return operator_token &&
+ (strcmp(operator_token, "+=") == 0 || strcmp(operator_token, "-=") == 0 ||
+ strcmp(operator_token, "*=") == 0 || strcmp(operator_token, "/=") == 0 ||
+ strcmp(operator_token, "%=") == 0 || strcmp(operator_token, "<<=") == 0 ||
+ strcmp(operator_token, ">>=") == 0 || strcmp(operator_token, "&=") == 0 ||
+ strcmp(operator_token, "|=") == 0 || strcmp(operator_token, "^=") == 0);
+}
+
+static void c_emit_resolved_call_orig_at(CLSPContext *ctx, const char *callee_qn, const char *orig,
+ const char *strategy, float confidence, TSNode site) {
if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
@@ -3502,23 +3803,92 @@ static void c_emit_resolved_call_orig(CLSPContext *ctx, const char *callee_qn, c
// is otherwise NULL for resolved calls and is never read for them by the
// pipeline consumers, so this overload is side-effect-free.
rc.reason = orig;
+ rc.source_origin = ctx->source_origin;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+static void c_emit_resolved_call_orig(CLSPContext *ctx, const char *callee_qn, const char *orig,
+ const char *strategy, float confidence) {
+ c_emit_resolved_call_orig_at(ctx, callee_qn, orig, strategy, confidence, (TSNode){0});
+}
+
static void c_emit_resolved_call(CLSPContext *ctx, const char *callee_qn, const char *strategy,
float confidence) {
c_emit_resolved_call_orig(ctx, callee_qn, NULL, strategy, confidence);
}
+static void c_emit_resolved_call_at(CLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site) {
+ c_emit_resolved_call_orig_at(ctx, callee_qn, NULL, strategy, confidence, site);
+}
+
+static void c_emit_resolved_reference_at(CLSPContext *ctx, const char *callee_qn,
+ const char *source_name, TSNode site) {
+ if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn || ts_node_is_null(site)) {
+ return;
+ }
+ const char *target_leaf = strrchr(callee_qn, '.');
+ target_leaf = target_leaf ? target_leaf + 1 : callee_qn;
+ CBMResolvedCall resolved = {0};
+ resolved.caller_qn = ctx->enclosing_func_qn;
+ resolved.callee_qn = callee_qn;
+ resolved.strategy = source_name && strcmp(source_name, target_leaf) != 0 ? "lsp_callable_alias"
+ : "lsp_callable_value";
+ resolved.confidence = 0.95f;
+ resolved.reason = source_name;
+ resolved.kind = CBM_RESOLVED_CALL_REFERENCE;
+ resolved.site_start_byte = ts_node_start_byte(site);
+ resolved.site_end_byte = ts_node_end_byte(site);
+ resolved.source_origin = ctx->source_origin;
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, resolved);
+}
+
+/* A direct identifier argument denotes a precise callable value only when its
+ * nearest lexical binding is a tracked function pointer target, or when no
+ * lexical value shadows one exact registered function. Conditional/composite
+ * expressions are intentionally not walked here and remain ordinary USAGE. */
+static void c_resolve_callable_argument_references(CLSPContext *ctx, TSNode call) {
+ TSNode arguments = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(arguments)) {
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(arguments);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode argument = ts_node_named_child(arguments, i);
+ if (strcmp(ts_node_type(argument), "identifier") != 0) {
+ continue;
+ }
+ char *name = c_node_text(ctx, argument);
+ if (!name || !name[0]) {
+ continue;
+ }
+ const char *target = c_lookup_fp_target(ctx, name);
+ if (!target && cbm_scope_contains(ctx->current_scope, name)) {
+ continue;
+ }
+ if (!target) {
+ target = c_resolve_name_to_func_qn(ctx, name);
+ }
+ if (target) {
+ c_emit_resolved_reference_at(ctx, target, name, argument);
+ }
+ }
+}
+
static void c_emit_unresolved_call(CLSPContext *ctx, const char *expr_text, const char *reason) {
if (!ctx->resolved_calls || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
rc.strategy = "lsp_unresolved";
rc.confidence = 0.0f;
rc.reason = reason;
+ rc.source_origin = ctx->source_origin;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
@@ -3553,6 +3923,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// --- Resolve call expressions ---
if (strcmp(kind, "call_expression") == 0) {
+ c_resolve_callable_argument_references(ctx, node);
TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
if (!ts_node_is_null(func_node)) {
const char *fk = ts_node_type(func_node);
@@ -3625,7 +3996,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
if (is_arrow && obj_type->kind == CBM_TYPE_TEMPLATE &&
is_smart_ptr(obj_type->data.template_type.template_name))
strategy = "lsp_smart_ptr_dispatch";
- c_emit_resolved_call(ctx, method->qualified_name, strategy, 0.95f);
+ c_emit_resolved_call_at(ctx, method->qualified_name, strategy,
+ 0.95f, node);
goto recurse;
}
}
@@ -3704,7 +4076,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
if (!f)
f = cbm_registry_lookup_func(ctx->registry, qn);
if (f) {
- c_emit_resolved_call(ctx, f->qualified_name, "lsp_scoped", 0.95f);
+ c_emit_resolved_call_at(ctx, f->qualified_name, "lsp_scoped", 0.95f, node);
goto recurse;
}
// Try as method (Class::method) with type-aware overload resolution
@@ -3724,7 +4096,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
dot + 1, arg_types, arg_count);
}
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_scoped", 0.95f);
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_scoped", 0.95f,
+ node);
goto recurse;
}
}
@@ -3740,7 +4113,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, bare_name));
}
if (nf) {
- c_emit_resolved_call(ctx, nf->qualified_name, "lsp_scoped", 0.90f);
+ c_emit_resolved_call_at(ctx, nf->qualified_name, "lsp_scoped", 0.90f,
+ node);
goto recurse;
}
}
@@ -3791,7 +4165,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
f = cbm_registry_lookup_func(ctx->registry, fqn);
}
if (f) {
- c_emit_resolved_call(ctx, f->qualified_name, "lsp_template", 0.95f);
+ c_emit_resolved_call_at(ctx, f->qualified_name, "lsp_template", 0.95f,
+ node);
// Resolve pending template calls at this call site
if (ctx->pending_tc_count > 0 && f->type_param_names) {
int ac = 0;
@@ -3822,9 +4197,9 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// The textual callee is the pointer variable `name` (e.g.
// `fp`), resolved to a differently named target. Pass it
// as orig so the join matches the call on the pointer name.
- c_emit_resolved_call_orig(ctx, fp_target, name,
- is_dll ? "lsp_dll_resolve" : "lsp_func_ptr",
- is_dll ? 0.80f : 0.85f);
+ c_emit_resolved_call_orig_at(ctx, fp_target, name,
+ is_dll ? "lsp_dll_resolve" : "lsp_func_ptr",
+ is_dll ? 0.80f : 0.85f, node);
goto recurse;
}
@@ -3842,8 +4217,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
const CBMRegisteredFunc *op =
c_lookup_member(ctx, type_qn, "operator()");
if (op) {
- c_emit_resolved_call(ctx, op->qualified_name, "lsp_operator",
- 0.90f);
+ c_emit_resolved_call_at(ctx, op->qualified_name, "lsp_operator",
+ 0.90f, node);
goto recurse;
}
}
@@ -3859,7 +4234,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// Constructor call
const char *ctor_qn =
cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn_str, name);
- c_emit_resolved_call(ctx, ctor_qn, "lsp_constructor", 0.95f);
+ c_emit_resolved_call_at(ctx, ctor_qn, "lsp_constructor", 0.95f, node);
goto recurse;
}
}
@@ -3876,7 +4251,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
strategy = "lsp_implicit_this";
}
}
- c_emit_resolved_call(ctx, fqn, strategy, 0.95f);
+ c_emit_resolved_call_at(ctx, fqn, strategy, 0.95f, node);
// Resolve pending template calls at this call site
if (ctx->pending_tc_count > 0) {
const CBMRegisteredFunc *called =
@@ -3892,7 +4267,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// ADL: search namespaces of argument types
const char *adl_qn = c_adl_resolve(ctx, name, node);
if (adl_qn) {
- c_emit_resolved_call(ctx, adl_qn, "lsp_adl", 0.90f);
+ c_emit_resolved_call_at(ctx, adl_qn, "lsp_adl", 0.90f, node);
} else {
c_emit_unresolved_call(ctx, name, "function_not_in_registry");
}
@@ -3963,7 +4338,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
const char *ctor_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
- c_emit_resolved_call(ctx, ctor_qn, "lsp_constructor", 0.95f);
+ c_emit_resolved_call_at(ctx, ctor_qn, "lsp_constructor", 0.95f, node);
}
}
}
@@ -3982,13 +4357,13 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
if (type_qn) {
const char *short_name = strrchr(type_qn, '.');
short_name = short_name ? short_name + 1 : type_qn;
- const char *dtor_qn = cbm_arena_sprintf(ctx->arena, "%s.~%s", type_qn, short_name);
- // The destructor callee QN (`T.~T`) is not textually available
- // from `delete p` — the call walk can only synthesize a call to
- // the operand text. Stash that operand text in `reason` so the
- // pipeline join binds the synthesized call via the reason gate.
- c_emit_resolved_call_orig(ctx, dtor_qn, c_node_text(ctx, operand), "lsp_destructor",
- 0.90f);
+ const char *dtor_name = cbm_arena_sprintf(ctx->arena, "~%s", short_name);
+ const CBMRegisteredFunc *dtor =
+ c_lookup_member_operator_by_arity(ctx, type_qn, dtor_name, 0);
+ if (dtor) {
+ c_emit_resolved_call_at(ctx, dtor->qualified_name, "lsp_destructor", 0.90f,
+ node);
+ }
}
}
}
@@ -3996,29 +4371,38 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// --- Operator calls (C++ only) ---
if (ctx->cpp_mode && strcmp(kind, "binary_expression") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", 4);
- if (!ts_node_is_null(left)) {
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
const CBMType *lhs_type = c_eval_expr_type(ctx, left);
+ const CBMType *rhs_type = c_eval_expr_type(ctx, right);
const CBMType *base = c_simplify_type(ctx, lhs_type, false);
- if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
- const char *type_qn = type_to_qn(base);
- if (type_qn) {
- // Extract operator
- for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
- TSNode child = ts_node_child(node, i);
- if (!ts_node_is_named(child)) {
- char *op = c_node_text(ctx, child);
- if (op) {
- const char *op_name =
- cbm_arena_sprintf(ctx->arena, "operator%s", op);
- const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
- if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator",
- 0.90f);
- }
+ // Extract operator. Prefer a member overload on the lhs type, then
+ // perform exact argument-dependent lookup for a free overload.
+ for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child)) {
+ char *op = c_node_text(ctx, child);
+ if (op) {
+ const char *op_name = cbm_arena_sprintf(ctx->arena, "operator%s", op);
+ const CBMRegisteredFunc *m = NULL;
+ if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
+ const char *type_qn = type_to_qn(base);
+ if (type_qn) {
+ m = c_lookup_member(ctx, type_qn, op_name);
+ if (m)
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator",
+ 0.90f, node);
+ }
+ }
+ if (!m) {
+ m = c_lookup_free_operator(ctx, op_name, lhs_type, rhs_type);
+ if (m) {
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator_adl",
+ 0.90f, node);
}
- break;
}
}
+ break;
}
}
}
@@ -4027,30 +4411,71 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
// --- Compound assignment operator calls (C++ only): a += b, a -= b, etc. ---
if (ctx->cpp_mode && strcmp(kind, "assignment_expression") == 0) {
TSNode left = ts_node_child_by_field_name(node, "left", 4);
- if (!ts_node_is_null(left)) {
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(left) && !ts_node_is_null(right)) {
const CBMType *lhs_type = c_eval_expr_type(ctx, left);
+ const CBMType *rhs_type = c_eval_expr_type(ctx, right);
const CBMType *base = c_simplify_type(ctx, lhs_type, false);
- if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
- const char *type_qn = type_to_qn(base);
- if (type_qn) {
- // Extract operator (+=, -=, *=, /=, etc.)
- for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
- TSNode child = ts_node_child(node, i);
- if (!ts_node_is_named(child)) {
- char *op = c_node_text(ctx, child);
- if (op && strlen(op) >= 2 && op[strlen(op) - 1] == '=') {
- // Compound assignment: +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ^=
- const char *op_name =
- cbm_arena_sprintf(ctx->arena, "operator%s", op);
- const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
+ // Extract only the compound-assignment operators. Plain `=` is
+ // never an overload candidate at this occurrence.
+ for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child)) {
+ char *op = c_node_text(ctx, child);
+ if (c_is_compound_assignment_operator(op)) {
+ const char *op_name = cbm_arena_sprintf(ctx->arena, "operator%s", op);
+ const CBMRegisteredFunc *m = NULL;
+ if (base && base->kind != CBM_TYPE_BUILTIN && !cbm_type_is_unknown(base)) {
+ const char *type_qn = type_to_qn(base);
+ if (type_qn) {
+ m = c_lookup_member_operator_by_arity(ctx, type_qn, op_name, 1);
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator",
- 0.90f);
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator",
+ 0.90f, node);
}
}
- break;
+ }
+ if (!m) {
+ m = c_lookup_free_operator(ctx, op_name, lhs_type, rhs_type);
+ if (m) {
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator_adl",
+ 0.90f, node);
+ }
}
}
+ break;
+ }
+ }
+ }
+ }
+
+ // --- field_expression operator-> ---
+ if (ctx->cpp_mode && strcmp(kind, "field_expression") == 0) {
+ TSNode receiver = ts_node_child_by_field_name(node, "argument", 8);
+ TSNode member = ts_node_child_by_field_name(node, "field", 5);
+ bool is_arrow = false;
+ for (uint32_t i = 0; i < ts_node_child_count(node); i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child)) {
+ const char *token = c_node_text(ctx, child);
+ if (token && strcmp(token, "->") == 0) {
+ is_arrow = true;
+ break;
+ }
+ }
+ }
+ if (is_arrow && !ts_node_is_null(receiver) && !ts_node_is_null(member)) {
+ const CBMType *receiver_type = c_eval_expr_type(ctx, receiver);
+ const CBMType *base = c_simplify_type(ctx, receiver_type, false);
+ if (base && base->kind != CBM_TYPE_BUILTIN && base->kind != CBM_TYPE_POINTER &&
+ !cbm_type_is_unknown(base)) {
+ const char *type_qn = type_to_qn(base);
+ const CBMRegisteredFunc *method =
+ type_qn ? c_lookup_member_operator_by_arity(ctx, type_qn, "operator->", 0)
+ : NULL;
+ if (method) {
+ c_emit_resolved_call_at(ctx, method->qualified_name, "lsp_operator", 0.90f,
+ node);
}
}
}
@@ -4066,9 +4491,11 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
base->kind != CBM_TYPE_POINTER && base->kind != CBM_TYPE_SLICE) {
const char *type_qn = type_to_qn(base);
if (type_qn) {
- const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, "operator[]");
+ const CBMRegisteredFunc *m =
+ c_lookup_member_operator_by_arity(ctx, type_qn, "operator[]", 1);
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator", 0.90f,
+ node);
}
}
}
@@ -4092,6 +4519,7 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
if (type_qn) {
// Determine which operator
const char *op_name = NULL;
+ TSNode operator_node = {0};
for (uint32_t ui = 0; ui < ts_node_child_count(node); ui++) {
TSNode ch = ts_node_child(node, ui);
if (!ts_node_is_named(ch)) {
@@ -4100,19 +4528,36 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
continue;
if (strcmp(op, "*") == 0)
op_name = "operator*";
+ else if (strcmp(op, "-") == 0)
+ op_name = "operator-";
else if (strcmp(op, "++") == 0)
op_name = "operator++";
else if (strcmp(op, "--") == 0)
op_name = "operator--";
else if (strcmp(op, "!") == 0)
op_name = "operator!";
+ operator_node = ch;
break;
}
}
if (op_name) {
- const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, op_name);
+ int explicit_arg_count = 0;
+ if (strcmp(kind, "update_expression") == 0 &&
+ !ts_node_is_null(operator_node) &&
+ ts_node_start_byte(operator_node) >= ts_node_end_byte(operand)) {
+ explicit_arg_count = 1; // postfix ++/-- carries the dummy int
+ }
+ const CBMRegisteredFunc *m = c_lookup_member_operator_by_arity(
+ ctx, type_qn, op_name, explicit_arg_count);
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_operator", 0.90f);
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator", 0.90f,
+ node);
+ } else if (explicit_arg_count == 0) {
+ m = c_lookup_free_unary_operator(ctx, op_name, op_type);
+ if (m) {
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_operator_adl",
+ 0.90f, node);
+ }
}
}
}
@@ -4145,7 +4590,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
short_name = short_name ? short_name + 1 : type_qn;
const char *ctor_qn =
cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, short_name);
- c_emit_resolved_call(ctx, ctor_qn, "lsp_copy_constructor", 0.85f);
+ c_emit_resolved_call_at(ctx, ctor_qn, "lsp_copy_constructor", 0.85f,
+ node);
}
}
}
@@ -4176,7 +4622,8 @@ static void c_resolve_calls_in_node_inner(CLSPContext *ctx, TSNode node) {
if (type_qn) {
const CBMRegisteredFunc *m = c_lookup_member(ctx, type_qn, "operator bool");
if (m) {
- c_emit_resolved_call(ctx, m->qualified_name, "lsp_conversion", 0.85f);
+ c_emit_resolved_call_at(ctx, m->qualified_name, "lsp_conversion", 0.85f,
+ node);
}
}
}
@@ -4223,10 +4670,19 @@ recurse:;
strcmp(kind, "while_statement") == 0 || strcmp(kind, "do_statement") == 0 ||
strcmp(kind, "switch_statement") == 0 || strcmp(kind, "catch_clause") == 0 ||
strcmp(kind, "lambda_expression") == 0);
+ bool control_flow_scope =
+ strcmp(kind, "if_statement") == 0 || strcmp(kind, "for_statement") == 0 ||
+ strcmp(kind, "for_range_loop") == 0 || strcmp(kind, "while_statement") == 0 ||
+ strcmp(kind, "do_statement") == 0 || strcmp(kind, "switch_statement") == 0 ||
+ strcmp(kind, "catch_clause") == 0;
+ int saved_fp_count = ctx->fp_count;
if (push_scope) {
ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);
}
+ if (control_flow_scope) {
+ ctx->control_flow_depth++;
+ }
// Process catch clause parameter
if (strcmp(kind, "catch_clause") == 0) {
@@ -4291,6 +4747,10 @@ recurse:;
if (push_scope) {
ctx->current_scope = cbm_scope_pop(ctx->current_scope);
+ ctx->fp_count = saved_fp_count;
+ }
+ if (control_flow_scope) {
+ ctx->control_flow_depth--;
}
}
@@ -4306,6 +4766,7 @@ static void c_process_function(CLSPContext *ctx, TSNode func_node) {
// Extract function name from declarator chain
char *func_name = NULL;
const char *saved_class_qn = ctx->enclosing_class_qn;
+ const char *saved_func_qn = ctx->enclosing_func_qn;
TSNode params_node = (TSNode){0};
// Navigate declarator to find name and parameters
@@ -4483,6 +4944,7 @@ static void c_process_function(CLSPContext *ctx, TSNode func_node) {
// Restore
ctx->current_scope = saved_scope;
ctx->enclosing_class_qn = saved_class_qn;
+ ctx->enclosing_func_qn = saved_func_qn;
}
// ============================================================================
@@ -4882,8 +5344,8 @@ static void c_process_class(CLSPContext *ctx, TSNode class_node) {
new_rets[0] = actual_ret;
new_rets[1] = NULL;
CBMRegisteredFunc *mut = (CBMRegisteredFunc *)existing;
- mut->signature =
- cbm_type_func(ctx->arena, NULL, NULL, new_rets);
+ mut->signature = cbm_type_func_replace_returns(
+ ctx->arena, existing->signature, new_rets);
}
break;
}
@@ -5140,12 +5602,65 @@ static const CBMType *c_parse_return_type_text(CBMArena *a, const char *text,
return cbm_type_named(a, text);
}
+/* Materialize the extractor's counted, positional parameter-type carrier.
+ * A NULL slot is meaningful (unknown), so never scan for a NULL terminator
+ * before `count` and never leave an interior hole in the CBMType array. */
+static const CBMType **c_parse_signature_param_types(CBMArena *arena, const char **type_texts,
+ int count, const char *module_qn) {
+ if (!arena || count <= 0)
+ return NULL;
+ const CBMType **types =
+ (const CBMType **)cbm_arena_alloc(arena, (size_t)(count + 1) * sizeof(const CBMType *));
+ if (!types)
+ return NULL;
+ for (int i = 0; i < count; i++) {
+ const char *text = type_texts ? type_texts[i] : NULL;
+ const CBMType *type = NULL;
+ if (text && text[0] && !(text[0] == '?' && text[1] == '\0')) {
+ type = c_parse_return_type_text(arena, text, module_qn);
+ }
+ types[i] = type ? type : cbm_type_unknown();
+ }
+ types[count] = NULL;
+ return types;
+}
+
// ============================================================================
// Entry point: single-file LSP
// ============================================================================
+static void c_rewrite_proved_destructor_candidates(CBMFileResult *result) {
+ if (!result) {
+ return;
+ }
+ for (int ci = 0; ci < result->calls.count; ci++) {
+ CBMCall *call = &result->calls.items[ci];
+ if (!call->requires_lsp_resolution || !call->callee_name ||
+ strcmp(call->callee_name, "~") != 0 || call->site_end_byte <= call->site_start_byte) {
+ continue;
+ }
+ for (int ri = 0; ri < result->resolved_calls.count; ri++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[ri];
+ if (!resolved->strategy || strcmp(resolved->strategy, "lsp_destructor") != 0 ||
+ !resolved->callee_qn || !resolved->caller_qn || !call->enclosing_func_qn ||
+ strcmp(resolved->caller_qn, call->enclosing_func_qn) != 0 ||
+ resolved->site_start_byte != call->site_start_byte ||
+ resolved->site_end_byte != call->site_end_byte ||
+ resolved->source_origin != call->source_origin) {
+ continue;
+ }
+ const char *leaf = strrchr(resolved->callee_qn, '.');
+ leaf = leaf ? leaf + 1 : resolved->callee_qn;
+ if (leaf[0] == '~' && leaf[1]) {
+ call->callee_name = leaf;
+ }
+ break;
+ }
+ }
+}
+
void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
- TSNode root, bool cpp_mode) {
+ TSNode root, bool cpp_mode, CBMSourceOrigin source_origin) {
CBMTypeRegistry reg;
cbm_registry_init(&reg, arena);
@@ -5259,23 +5774,11 @@ void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, i
}
}
- // Build param types
- const CBMType **param_types_arr = NULL;
- if (d->param_types) {
- int count = 0;
- while (d->param_types[count])
- count++;
- if (count > 0) {
- param_types_arr = (const CBMType **)cbm_arena_alloc(
- arena, (count + 1) * sizeof(const CBMType *));
- for (int j = 0; j < count; j++)
- param_types_arr[j] =
- c_parse_return_type_text(arena, d->param_types[j], module_qn);
- param_types_arr[count] = NULL;
- }
- }
+ // Build positional param types from the internal signature carrier.
+ const CBMType **param_types_arr = c_parse_signature_param_types(
+ arena, d->signature_param_types, d->signature_param_count, module_qn);
- rf.signature = cbm_type_func(arena, d->param_names, param_types_arr, ret_types);
+ rf.signature = cbm_type_func(arena, NULL, param_types_arr, ret_types);
// Method receiver
if (strcmp(d->label, "Method") == 0 && d->parent_class) {
@@ -5299,8 +5802,10 @@ void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, i
// Initialize context and run
CLSPContext ctx;
c_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, cpp_mode, &result->resolved_calls);
+ ctx.source_origin = source_origin;
c_lsp_process_file(&ctx, root);
+ c_rewrite_proved_destructor_candidates(result);
}
// ============================================================================
@@ -5430,6 +5935,12 @@ static void c_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const cha
if (!rf.signature)
rf.signature = cbm_type_func(arena, NULL, NULL, NULL);
+ const CBMType **param_types_arr = c_parse_signature_param_types(
+ arena, d->signature_param_types, d->signature_param_count, def_module);
+ const CBMType **return_types_arr =
+ rf.signature ? rf.signature->data.func.return_types : NULL;
+ rf.signature = cbm_type_func(arena, NULL, param_types_arr, return_types_arr);
+
if (d->receiver_type) {
rf.receiver_type = d->receiver_type; /* borrowed */
}
@@ -5596,11 +6107,16 @@ void cbm_batch_c_lsp_cross(CBMArena *arena, CBMBatchCLSPFile *files, int file_co
for (int j = 0; j < file_out.count; j++) {
CBMResolvedCall *src = &file_out.items[j];
CBMResolvedCall *dst = &out[f].items[j];
+ memset(dst, 0, sizeof(*dst));
dst->caller_qn = src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn = src->callee_qn ? cbm_arena_strdup(arena, src->callee_qn) : NULL;
dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
+ dst->source_origin = src->source_origin;
}
}
diff --git a/internal/cbm/lsp/c_lsp.h b/internal/cbm/lsp/c_lsp.h
index 02e4f591e..9aa936960 100644
--- a/internal/cbm/lsp/c_lsp.h
+++ b/internal/cbm/lsp/c_lsp.h
@@ -60,10 +60,14 @@ typedef struct {
// Output
CBMResolvedCallArray *resolved_calls;
+ CBMSourceOrigin source_origin; // source buffer represented by emitted occurrence spans
- // Function pointer targets: var_name -> target function QN
+ // Function pointer targets: lexical binding -> exact target function QN.
+ // A NULL target is an explicitly unknown/ambiguous binding and must shadow
+ // any outer exact target of the same name.
const char **fp_var_names;
const char **fp_target_qns;
+ const CBMScope **fp_binding_scopes;
int fp_count;
int fp_cap;
@@ -93,6 +97,7 @@ typedef struct {
int eval_depth; // recursion depth for c_eval_expr_type (crash guard)
int eval_steps; // total expression eval calls for current file (hang guard)
int walk_depth; // c_resolve_calls_in_node self-recursion (AST nesting)
+ int control_flow_depth; // if/loop/switch/catch nesting; assignments merge fail-closed
} CLSPContext;
// --- API ---
@@ -120,7 +125,7 @@ const CBMType *c_simplify_type(CLSPContext *ctx, const CBMType *t, bool unwrap_p
// Single-file LSP: build registry from file defs + stdlib, run resolution.
void cbm_run_c_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
- TSNode root, bool cpp_mode);
+ TSNode root, bool cpp_mode, CBMSourceOrigin source_origin);
// Cross-file LSP: build registry from defs + stdlib, re-parse and resolve.
void cbm_run_c_lsp_cross(CBMArena *arena, const char *source, int source_len, const char *module_qn,
diff --git a/internal/cbm/lsp/cs_lsp.c b/internal/cbm/lsp/cs_lsp.c
index bac42378c..e5667165f 100644
--- a/internal/cbm/lsp/cs_lsp.c
+++ b/internal/cbm/lsp/cs_lsp.c
@@ -73,6 +73,7 @@ static void cs_register_type_decls(CSLSPContext *ctx, CBMTypeRegistry *reg, TSNo
static char *cs_node_text_cached(CSLSPContext *ctx, TSNode node);
static const CBMType *cs_unwrap_task(CSLSPContext *ctx, const CBMType *t);
static const CBMType *cs_unwrap_nullable(const CBMType *t);
+static const char *cs_resolve_callable_value(CSLSPContext *ctx, TSNode node, TSNode *callable_leaf);
/* ── small helpers ──────────────────────────────────────────────── */
@@ -499,6 +500,38 @@ const CBMRegisteredFunc *cs_lookup_method(CSLSPContext *ctx, const char *type_qn
return NULL;
}
+/* A static import is precise only when every matching directive reaches the
+ * same method. Repeated imports of one type are harmless, but selecting the
+ * first of two distinct targets would make resolution declaration-order
+ * dependent. */
+static const CBMRegisteredFunc *cs_lookup_using_static_method(CSLSPContext *ctx,
+ const char *method_name,
+ bool *ambiguous) {
+ if (ambiguous)
+ *ambiguous = false;
+ if (!ctx || !method_name)
+ return NULL;
+
+ const CBMRegisteredFunc *only = NULL;
+ for (int i = 0; i < ctx->using_count; i++) {
+ const CBMCSUsing *u = &ctx->usings[i];
+ if (u->kind != CBM_CS_USING_STATIC)
+ continue;
+ const char *host = cs_resolve_type_name(ctx, u->target_qn);
+ const CBMRegisteredFunc *candidate =
+ cs_lookup_method(ctx, host ? host : u->target_qn, method_name);
+ if (!candidate || !candidate->qualified_name)
+ continue;
+ if (only && strcmp(only->qualified_name, candidate->qualified_name) != 0) {
+ if (ambiguous)
+ *ambiguous = true;
+ return NULL;
+ }
+ only = candidate;
+ }
+ return only;
+}
+
/* ── extension methods ──────────────────────────────────────────── */
/* Search for a static extension method `M(this U self, ...)` accessible
@@ -1041,15 +1074,13 @@ static const CBMType *cs_eval_invocation_type(CSLSPContext *ctx, TSNode call) {
return f->signature->data.func.return_types[0];
}
}
- for (int i = 0; i < ctx->using_count; i++) {
- const CBMCSUsing *u = &ctx->usings[i];
- if (u->kind != CBM_CS_USING_STATIC) continue;
- const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", u->target_qn, bare);
- const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, qn);
- if (f && f->signature && f->signature->data.func.return_types &&
- f->signature->data.func.return_types[0]) {
- return f->signature->data.func.return_types[0];
- }
+ bool ambiguous = false;
+ const CBMRegisteredFunc *f = cs_lookup_using_static_method(ctx, bare, &ambiguous);
+ if (ambiguous)
+ return cbm_type_unknown();
+ if (f && f->signature && f->signature->data.func.return_types &&
+ f->signature->data.func.return_types[0]) {
+ return f->signature->data.func.return_types[0];
}
}
@@ -1255,6 +1286,166 @@ static void cs_bind_parameters(CSLSPContext *ctx, TSNode params_node, bool is_ex
/* ── statement processing ───────────────────────────────────────── */
+/* Resolve a source expression only when it denotes one exact callable value.
+ * This deliberately accepts just direct method groups (bare or member access):
+ * conditional/switch/lambda expressions remain ordinary usages because they
+ * do not prove one target at this occurrence. */
+static const char *cs_resolve_callable_name(CSLSPContext *ctx, const char *name) {
+ if (!ctx || !name || !name[0])
+ return NULL;
+
+ /* A lexical binding always wins, including an UNKNOWN ordinary binding:
+ * a nearer non-callable value must suppress a same-named class method. */
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ return cbm_scope_lookup_callable(ctx->current_scope, name);
+ }
+
+ if (ctx->enclosing_class_qn) {
+ const CBMRegisteredFunc *f = cs_lookup_method(ctx, ctx->enclosing_class_qn, name);
+ if (f && f->qualified_name)
+ return f->qualified_name;
+ }
+ if (ctx->enclosing_base_qn) {
+ const CBMRegisteredFunc *f = cs_lookup_method(ctx, ctx->enclosing_base_qn, name);
+ if (f && f->qualified_name)
+ return f->qualified_name;
+ }
+
+ bool using_static_ambiguous = false;
+ const CBMRegisteredFunc *using_static =
+ cs_lookup_using_static_method(ctx, name, &using_static_ambiguous);
+ if (using_static_ambiguous)
+ return NULL;
+ if (using_static)
+ return using_static->qualified_name;
+
+ const char *ns = cs_namespace_qn(ctx);
+ if (ns && ns[0]) {
+ const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ns, name);
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, qn);
+ if (f && f->qualified_name)
+ return f->qualified_name;
+ }
+
+ /* C# has no true namespace-level functions, but error-tolerant parses and
+ * generated fixtures can register receiverless callables. Only accept a
+ * unique short-name match; ambiguity is intentionally not guessed. */
+ const CBMRegisteredFunc *only = NULL;
+ for (int i = 0; ctx->registry && i < ctx->registry->func_count; i++) {
+ const CBMRegisteredFunc *candidate = &ctx->registry->funcs[i];
+ if (candidate->receiver_type || !candidate->short_name ||
+ strcmp(candidate->short_name, name) != 0) {
+ continue;
+ }
+ if (only && strcmp(only->qualified_name, candidate->qualified_name) != 0) {
+ return NULL;
+ }
+ only = candidate;
+ }
+ return only ? only->qualified_name : NULL;
+}
+
+static TSNode cs_callable_name_leaf(TSNode node) {
+ if (ts_node_is_null(node) || strcmp(ts_node_type(node), "generic_name") != 0) {
+ return node;
+ }
+
+ TSNode leaf = ts_node_child_by_field_name(node, "name", 4);
+ if (!ts_node_is_null(leaf))
+ return leaf;
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_null(child) && ts_node_is_named(child) &&
+ strcmp(ts_node_type(child), "identifier") == 0) {
+ return child;
+ }
+ }
+ return node;
+}
+
+static const char *cs_resolve_callable_value(CSLSPContext *ctx, TSNode node,
+ TSNode *callable_leaf) {
+ if (callable_leaf)
+ memset(callable_leaf, 0, sizeof(*callable_leaf));
+ if (!ctx || ts_node_is_null(node))
+ return NULL;
+ const char *kind = ts_node_type(node);
+
+ if (strcmp(kind, "argument") == 0 || strcmp(kind, "parenthesized_expression") == 0 ||
+ strcmp(kind, "equals_value_clause") == 0) {
+ TSNode inner = ts_node_child_by_field_name(node, "expression", 10);
+ if (ts_node_is_null(inner))
+ inner = ts_node_child_by_field_name(node, "value", 5);
+ if (ts_node_is_null(inner))
+ inner = cs_first_named_child(node);
+ return ts_node_is_null(inner) ? NULL : cs_resolve_callable_value(ctx, inner, callable_leaf);
+ }
+
+ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "generic_name") == 0) {
+ char *raw = cs_node_text(ctx, node);
+ char *bare = raw ? cs_strip_generic_args(ctx->arena, raw) : NULL;
+ const char *target = bare ? cs_resolve_callable_name(ctx, bare) : NULL;
+ if (target && callable_leaf)
+ *callable_leaf = cs_callable_name_leaf(node);
+ return target;
+ }
+
+ if (strcmp(kind, "member_access_expression") != 0)
+ return NULL;
+ TSNode receiver = ts_node_child_by_field_name(node, "expression", 10);
+ TSNode member = ts_node_child_by_field_name(node, "name", 4);
+ if (ts_node_is_null(receiver))
+ receiver = cs_first_named_child(node);
+ if (ts_node_is_null(member)) {
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ if (ts_node_is_null(child) || !ts_node_is_named(child) || ts_node_eq(child, receiver)) {
+ continue;
+ }
+ const char *child_kind = ts_node_type(child);
+ if (strcmp(child_kind, "identifier") == 0 || strcmp(child_kind, "generic_name") == 0) {
+ member = child;
+ }
+ }
+ }
+ if (ts_node_is_null(receiver) || ts_node_is_null(member))
+ return NULL;
+
+ char *member_raw = cs_node_text(ctx, member);
+ char *member_name = member_raw ? cs_strip_generic_args(ctx->arena, member_raw) : NULL;
+ if (!member_name)
+ return NULL;
+
+ char *receiver_text = cs_node_text(ctx, receiver);
+ if (receiver_text) {
+ const char *type_qn = cs_resolve_type_name(ctx, receiver_text);
+ if (type_qn && cs_lookup_type_qn(ctx, type_qn)) {
+ const CBMRegisteredFunc *f = cs_lookup_method(ctx, type_qn, member_name);
+ if (f && callable_leaf)
+ *callable_leaf = cs_callable_name_leaf(member);
+ return f ? f->qualified_name : NULL;
+ }
+ }
+
+ const CBMType *receiver_type = cs_unwrap_nullable(cs_eval_expr_type(ctx, receiver));
+ const char *type_qn = NULL;
+ if (receiver_type && receiver_type->kind == CBM_TYPE_NAMED) {
+ type_qn = receiver_type->data.named.qualified_name;
+ } else if (receiver_type && receiver_type->kind == CBM_TYPE_TEMPLATE) {
+ type_qn = receiver_type->data.template_type.template_name;
+ }
+ if (!type_qn)
+ return NULL;
+ const CBMRegisteredFunc *f = cs_lookup_method(ctx, type_qn, member_name);
+ if (!f)
+ f = cs_lookup_extension(ctx, type_qn, member_name);
+ if (f && callable_leaf)
+ *callable_leaf = cs_callable_name_leaf(member);
+ return f ? f->qualified_name : NULL;
+}
+
static void cs_process_local_decl(CSLSPContext *ctx, TSNode node) {
/* local_declaration_statement -> variable_declaration */
TSNode vd = cs_child_named_kind(node, "variable_declaration");
@@ -1291,12 +1482,18 @@ static void cs_process_local_decl(CSLSPContext *ctx, TSNode node) {
* variants. Try the field-name path first, then fall back to
* walking named children for any expression after the identifier. */
TSNode init = ts_node_child_by_field_name(c, "value", 5);
+ TSNode rhs_node;
+ memset(&rhs_node, 0, sizeof(rhs_node));
const CBMType *rhs_t = NULL;
if (!ts_node_is_null(init)) {
if (strcmp(ts_node_type(init), "equals_value_clause") == 0) {
TSNode rhs = cs_first_named_child(init);
- if (!ts_node_is_null(rhs)) rhs_t = cs_eval_expr_type(ctx, rhs);
+ if (!ts_node_is_null(rhs)) {
+ rhs_node = rhs;
+ rhs_t = cs_eval_expr_type(ctx, rhs);
+ }
} else {
+ rhs_node = init;
rhs_t = cs_eval_expr_type(ctx, init);
}
}
@@ -1313,6 +1510,7 @@ static void cs_process_local_decl(CSLSPContext *ctx, TSNode node) {
if (strcmp(ck, "equals_value_clause") == 0) {
TSNode rhs = cs_first_named_child(cn);
if (!ts_node_is_null(rhs)) {
+ rhs_node = rhs;
const CBMType *t = cs_eval_expr_type(ctx, rhs);
if (t && t->kind != CBM_TYPE_UNKNOWN) rhs_t = t;
}
@@ -1323,6 +1521,7 @@ static void cs_process_local_decl(CSLSPContext *ctx, TSNode node) {
continue; /* the identifier name */
}
if (seen_named >= 1) {
+ rhs_node = cn;
const CBMType *t = cs_eval_expr_type(ctx, cn);
if (t && t->kind != CBM_TYPE_UNKNOWN) {
rhs_t = t;
@@ -1333,7 +1532,13 @@ static void cs_process_local_decl(CSLSPContext *ctx, TSNode node) {
}
const CBMType *bind = is_var ? (rhs_t ? rhs_t : declared_type) : declared_type;
if (!bind) bind = cbm_type_unknown();
- cbm_scope_bind(ctx->current_scope, vname, bind);
+ const char *callable_qn =
+ ts_node_is_null(rhs_node) ? NULL : cs_resolve_callable_value(ctx, rhs_node, NULL);
+ if (callable_qn) {
+ cbm_scope_bind_callable(ctx->current_scope, vname, bind, callable_qn);
+ } else {
+ cbm_scope_bind(ctx->current_scope, vname, bind);
+ }
}
}
@@ -1398,28 +1603,163 @@ static void cs_process_assignment(CSLSPContext *ctx, TSNode node) {
if (!cs_node_is(lhs, "identifier")) return;
char *vname = cs_node_text(ctx, lhs);
if (!vname) return;
- const CBMType *t = cs_eval_expr_type(ctx, rhs);
- if (!t || t->kind == CBM_TYPE_UNKNOWN) return;
- /* Don't override more-specific bindings with weaker ones. */
- const CBMType *existing = cbm_scope_lookup(ctx->current_scope, vname);
- if (existing && existing->kind == CBM_TYPE_NAMED && t->kind == CBM_TYPE_UNKNOWN) return;
- cbm_scope_bind(ctx->current_scope, vname, t);
+ const char *callable_qn = cs_resolve_callable_value(ctx, rhs, NULL);
+ (void)cs_eval_expr_type(ctx, rhs);
+ if (callable_qn) {
+ cbm_scope_update_callable(ctx->current_scope, vname, callable_qn);
+ } else {
+ /* An ordinary or ambiguous reassignment clears stale callable identity
+ * while retaining the best type already known for the variable. */
+ cbm_scope_update_callable(ctx->current_scope, vname, NULL);
+ }
}
/* ── call resolution + emit ─────────────────────────────────────── */
-static void cs_emit_resolved(CSLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
+static void cs_invalidate_conditionally_assigned_callables(CSLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "method_declaration") == 0 || strcmp(kind, "local_function_statement") == 0 ||
+ strcmp(kind, "lambda_expression") == 0 ||
+ strcmp(kind, "anonymous_method_expression") == 0 ||
+ strcmp(kind, "class_declaration") == 0 || strcmp(kind, "struct_declaration") == 0) {
+ return;
+ }
+ if (strcmp(kind, "assignment_expression") == 0) {
+ TSNode lhs = ts_node_child_by_field_name(node, "left", 4);
+ if (ts_node_is_null(lhs))
+ lhs = cs_first_named_child(node);
+ if (cs_node_is(lhs, "identifier")) {
+ char *name = cs_node_text(ctx, lhs);
+ if (name)
+ cbm_scope_update_callable(ctx->current_scope, name, NULL);
+ }
+ return;
+ }
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_null(child) && ts_node_is_named(child)) {
+ cs_invalidate_conditionally_assigned_callables(ctx, child);
+ }
+ }
+}
+
+static void cs_emit_resolved_kind_reason(CSLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence,
+ CBMResolvedKind kind, const char *reason) {
if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn) return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
rc.confidence = confidence;
- rc.reason = NULL;
+ rc.reason = reason;
+ rc.kind = kind;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+static void cs_emit_resolved_kind(CSLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, CBMResolvedKind kind) {
+ cs_emit_resolved_kind_reason(ctx, callee_qn, strategy, confidence, kind, NULL);
+}
+
+static void cs_emit_resolved(CSLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence) {
+ cs_emit_resolved_kind(ctx, callee_qn, strategy, confidence, CBM_RESOLVED_INVOCATION);
+}
+
+static void cs_emit_resolved_reason(CSLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, const char *reason) {
+ cs_emit_resolved_kind_reason(ctx, callee_qn, strategy, confidence, CBM_RESOLVED_INVOCATION,
+ reason);
+}
+
+static void cs_stamp_resolved_site(CSLSPContext *ctx, int first, TSNode site) {
+ if (!ctx->resolved_calls || ts_node_is_null(site) || first < 0)
+ return;
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].site_start_byte = ts_node_start_byte(site);
+ ctx->resolved_calls->items[i].site_end_byte = ts_node_end_byte(site);
+ }
+}
+
+static void cs_emit_resolved_kind_reason_at(CSLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence,
+ CBMResolvedKind kind, const char *reason, TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ cs_emit_resolved_kind_reason(ctx, callee_qn, strategy, confidence, kind, reason);
+ cs_stamp_resolved_site(ctx, first, site);
+}
+
+static void cs_retarget_callable_carrier(CSLSPContext *ctx, TSNode site, const char *source_name,
+ const char *target_qn) {
+ if (!ctx || !ctx->call_carriers || ts_node_is_null(site) || !source_name || !target_qn ||
+ !ctx->enclosing_func_qn) {
+ return;
+ }
+ const char *target_name = cs_short_name(target_qn);
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ for (int i = 0; i < ctx->call_carriers->count; i++) {
+ CBMCall *call = &ctx->call_carriers->items[i];
+ if (!call->callee_name || !call->enclosing_func_qn ||
+ strcmp(call->callee_name, source_name) != 0 ||
+ strcmp(call->enclosing_func_qn, ctx->enclosing_func_qn) != 0 ||
+ call->site_start_byte < start || call->site_end_byte > end) {
+ continue;
+ }
+ call->callee_name = cbm_arena_strdup(ctx->arena, target_name);
+ call->requires_lsp_resolution = true;
+ }
+}
+
+/* Promote only direct argument expressions whose value resolves to one exact
+ * method group. Wrappers are peeled, but conditionals/switches/lambdas are not
+ * traversed, so complex values retain parser-produced USAGE edges. */
+static void cs_resolve_callable_arguments(CSLSPContext *ctx, TSNode call) {
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(args))
+ args = cs_child_named_kind(call, "argument_list");
+ if (ts_node_is_null(args))
+ return;
+
+ uint32_t nc = ts_node_child_count(args);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode argument = ts_node_child(args, i);
+ if (ts_node_is_null(argument) || !ts_node_is_named(argument) ||
+ strcmp(ts_node_type(argument), "argument") != 0) {
+ continue;
+ }
+ TSNode value = ts_node_child_by_field_name(argument, "expression", 10);
+ if (ts_node_is_null(value))
+ value = ts_node_child_by_field_name(argument, "value", 5);
+ if (ts_node_is_null(value)) {
+ uint32_t ac = ts_node_child_count(argument);
+ for (uint32_t j = ac; j > 0; j--) {
+ TSNode child = ts_node_child(argument, j - 1);
+ if (!ts_node_is_null(child) && ts_node_is_named(child)) {
+ value = child;
+ break;
+ }
+ }
+ }
+ if (ts_node_is_null(value))
+ continue;
+ TSNode callable_leaf;
+ memset(&callable_leaf, 0, sizeof(callable_leaf));
+ const char *target = cs_resolve_callable_value(ctx, value, &callable_leaf);
+ if (!target)
+ continue;
+ if (ts_node_is_null(callable_leaf))
+ continue;
+ char *source_name = cs_node_text(ctx, callable_leaf);
+ cs_emit_resolved_kind_reason_at(ctx, target, "lsp_callable_value_reference", 0.95f,
+ CBM_RESOLVED_CALL_REFERENCE, source_name, callable_leaf);
+ }
+}
+
static void cs_resolve_invocation(CSLSPContext *ctx, TSNode call) {
TSNode fn = ts_node_child_by_field_name(call, "function", 8);
if (ts_node_is_null(fn)) {
@@ -1516,6 +1856,18 @@ static void cs_resolve_invocation(CSLSPContext *ctx, TSNode call) {
if (!fname) return;
char *bare = cs_strip_generic_args(ctx->arena, fname);
+ /* Callable-valued locals and parameters shadow class/static methods.
+ * An exact alias carries its real target; an ordinary lexical value
+ * suppresses all same-name fallbacks so we never fabricate a call. */
+ if (cbm_scope_contains(ctx->current_scope, bare)) {
+ const char *target = cbm_scope_lookup_callable(ctx->current_scope, bare);
+ if (target) {
+ cs_emit_resolved_reason(ctx, target, "lsp_callable_alias", 0.98f, bare);
+ cs_retarget_callable_carrier(ctx, call, bare, target);
+ }
+ return;
+ }
+
/* Try enclosing class member. cs_lookup_method walks the base chain, so
* a bare call may resolve to an INHERITED method. Distinguish, exactly
* as the instance-call path does: a method actually declared on the
@@ -1547,15 +1899,14 @@ static void cs_resolve_invocation(CSLSPContext *ctx, TSNode call) {
* the file-stem QN ("proj.Client.MathUtil"); resolve the target through
* the type-name resolver (its short-name fallback bridges the two)
* before the method lookup. */
- for (int i = 0; i < ctx->using_count; i++) {
- const CBMCSUsing *u = &ctx->usings[i];
- if (u->kind != CBM_CS_USING_STATIC) continue;
- const char *host = cs_resolve_type_name(ctx, u->target_qn);
- const CBMRegisteredFunc *f = cs_lookup_method(ctx, host ? host : u->target_qn, bare);
- if (f) {
- cs_emit_resolved(ctx, f->qualified_name, "cs_using_static", 0.90f);
- return;
- }
+ bool using_static_ambiguous = false;
+ const CBMRegisteredFunc *using_static =
+ cs_lookup_using_static_method(ctx, bare, &using_static_ambiguous);
+ if (using_static_ambiguous)
+ return;
+ if (using_static) {
+ cs_emit_resolved(ctx, using_static->qualified_name, "cs_using_static", 0.90f);
+ return;
}
/* Free function in current namespace. */
@@ -1656,9 +2007,14 @@ static void cs_resolve_calls_in_node(CSLSPContext *ctx, TSNode node) {
} else if (strcmp(kind, "assignment_expression") == 0) {
cs_process_assignment(ctx, node);
} else if (strcmp(kind, "invocation_expression") == 0) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
cs_resolve_invocation(ctx, node);
+ cs_stamp_resolved_site(ctx, first, node);
+ cs_resolve_callable_arguments(ctx, node);
} else if (strcmp(kind, "object_creation_expression") == 0) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
cs_resolve_object_creation(ctx, node);
+ cs_stamp_resolved_site(ctx, first, node);
}
/* Recurse into children. We do NOT pre-bind anything that would only be
@@ -1692,6 +2048,13 @@ static void cs_resolve_calls_in_node(CSLSPContext *ctx, TSNode node) {
cs_resolve_calls_in_node(ctx, c);
} while (ts_tree_cursor_goto_next_sibling(&cursor));
ts_tree_cursor_delete(&cursor);
+ if (strcmp(kind, "if_statement") == 0 || strcmp(kind, "switch_statement") == 0 ||
+ strcmp(kind, "switch_expression") == 0 || strcmp(kind, "for_statement") == 0 ||
+ strcmp(kind, "for_each_statement") == 0 || strcmp(kind, "foreach_statement") == 0 ||
+ strcmp(kind, "while_statement") == 0 || strcmp(kind, "do_statement") == 0 ||
+ strcmp(kind, "try_statement") == 0) {
+ cs_invalidate_conditionally_assigned_callables(ctx, node);
+ }
}
/* ── method/constructor processing ──────────────────────────────── */
@@ -2690,6 +3053,34 @@ static void cs_collect_method_return_types(CSLSPContext *ctx, TSNode root,
}
}
+void cbm_cs_refine_ast_return_types(CSLSPContext *ctx, CBMTypeRegistry *reg, TSNode root) {
+ if (!ctx || !reg || ts_node_is_null(root))
+ return;
+
+ cs_method_rt_table_t mtab = {0};
+ cs_collect_method_return_types(ctx, root, &mtab);
+ for (int i = 0; i < mtab.count; i++) {
+ const char *qn = mtab.items[i].qn;
+ const CBMType *rt = mtab.items[i].rt;
+ bool patched = false;
+ for (int j = 0; j < reg->func_count; j++) {
+ if (strcmp(reg->funcs[j].qualified_name, qn) == 0) {
+ const CBMType **rets =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
+ if (rets) {
+ rets[0] = rt;
+ rets[1] = NULL;
+ reg->funcs[j].signature =
+ cbm_type_func_replace_returns(ctx->arena, reg->funcs[j].signature, rets);
+ }
+ patched = true;
+ break;
+ }
+ }
+ (void)patched;
+ }
+}
+
/* ── parse return type from CBMDefinition.return_type ──────────── */
static const CBMType *cs_parse_return_type_text(CSLSPContext *ctx, const char *text) {
@@ -2709,6 +3100,13 @@ static const CBMType *cs_parse_return_type_text(CSLSPContext *ctx, const char *t
return cbm_type_named(ctx->arena, resolved);
}
+static const CBMType *cs_signature_param_type_adapter(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ (void)arena;
+ CSLSPContext *ctx = (CSLSPContext *)parser_ctx;
+ return ctx ? cs_parse_return_type_text(ctx, text) : cbm_type_unknown();
+}
+
/* ── single-file entry: cbm_run_cs_lsp ──────────────────────────── */
void cbm_run_cs_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
@@ -2785,10 +3183,37 @@ void cbm_run_cs_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
/* Phase C: build context for type resolution + run the resolver. */
CSLSPContext ctx;
cs_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, &result->resolved_calls);
+ ctx.call_carriers = &result->calls;
/* Pass 1: collect imports + namespaces (for type-resolution context). */
cs_collect_imports(&ctx, root);
+ /* The counted carrier is authoritative even when count is zero. Install it
+ * only after imports are available so textual types use the same local
+ * resolution context as declared returns. A truly absent carrier keeps the
+ * legacy zero-parameter behavior. */
+ for (int i = 0; i < result->defs.count; i++) {
+ CBMDefinition *d = &result->defs.items[i];
+ if (!d->qualified_name || !d->label ||
+ (strcmp(d->label, "Function") != 0 && strcmp(d->label, "Method") != 0) ||
+ (!d->signature_param_types && d->signature_param_count <= 0)) {
+ continue;
+ }
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cs_signature_param_type_adapter, &ctx);
+ for (int j = 0; j < reg.func_count; j++) {
+ if (strcmp(reg.funcs[j].qualified_name, d->qualified_name) != 0)
+ continue;
+ const CBMType **return_types = NULL;
+ if (reg.funcs[j].signature && reg.funcs[j].signature->kind == CBM_TYPE_FUNC) {
+ return_types = reg.funcs[j].signature->data.func.return_types;
+ }
+ reg.funcs[j].signature = cbm_type_func(arena, NULL, param_types, return_types);
+ break;
+ }
+ }
+
/* Now refine return types of registered funcs using ctx (which has using
* directives). Also refine field types via collect_class_fields. */
for (int i = 0; i < result->defs.count; i++) {
@@ -2804,7 +3229,8 @@ void cbm_run_cs_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
if (rets) {
rets[0] = rt;
rets[1] = NULL;
- reg.funcs[j].signature = cbm_type_func(arena, NULL, NULL, rets);
+ reg.funcs[j].signature =
+ cbm_type_func_replace_returns(arena, reg.funcs[j].signature, rets);
}
break;
}
@@ -2814,29 +3240,7 @@ void cbm_run_cs_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
/* Phase B.1.5: AST-driven return-type patch. The unified extractor
* leaves CBMDefinition.return_type NULL for C# methods, so we walk the
* AST ourselves to recover declared return types. */
- {
- cs_method_rt_table_t mtab = {0};
- cs_collect_method_return_types(&ctx, root, &mtab);
- for (int i = 0; i < mtab.count; i++) {
- const char *qn = mtab.items[i].qn;
- const CBMType *rt = mtab.items[i].rt;
- bool patched = false;
- for (int j = 0; j < reg.func_count; j++) {
- if (strcmp(reg.funcs[j].qualified_name, qn) == 0) {
- const CBMType **rets =
- (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
- if (rets) {
- rets[0] = rt;
- rets[1] = NULL;
- reg.funcs[j].signature = cbm_type_func(arena, NULL, NULL, rets);
- }
- patched = true;
- break;
- }
- }
- (void)patched;
- }
- }
+ cbm_cs_refine_ast_return_types(&ctx, &reg, root);
/* Phase B.1: collect typed properties + fields. */
{
@@ -2928,13 +3332,22 @@ static void cs_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg,
if (strcmp(d->label, "Method") == 0 && d->receiver_type) {
rf.receiver_type = d->receiver_type;
}
+ CSLSPContext parser_ctx = {0};
+ parser_ctx.arena = arena;
+ parser_ctx.registry = reg;
+ parser_ctx.module_qn = d->def_module_qn;
const CBMType **rets =
(const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
if (rets) {
- rets[0] = cbm_type_unknown();
+ rets[0] = d->return_types && d->return_types[0]
+ ? cs_parse_return_type_text(&parser_ctx, d->return_types)
+ : cbm_type_unknown();
rets[1] = NULL;
}
- rf.signature = cbm_type_func(arena, NULL, NULL, rets);
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cs_signature_param_type_adapter, &parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, param_types, rets);
cbm_registry_add_func(reg, rf);
}
}
diff --git a/internal/cbm/lsp/cs_lsp.h b/internal/cbm/lsp/cs_lsp.h
index 2f1995b56..27cc233a5 100644
--- a/internal/cbm/lsp/cs_lsp.h
+++ b/internal/cbm/lsp/cs_lsp.h
@@ -97,6 +97,10 @@ typedef struct {
/* Output: resolved calls accumulate here. */
CBMResolvedCallArray *resolved_calls;
+ /* Existing parser call carriers for this file. Exact callable aliases
+ * retarget their occurrence and require the semantic result, preventing a
+ * same-named definition from winning through textual fallback. */
+ CBMCallArray *call_carriers;
/* Active type-parameter substitution map (for generic methods/types).
* Parallel arrays. NULL-terminated. */
@@ -138,6 +142,11 @@ const char *cs_resolve_type_name(CSLSPContext *ctx, const char *name);
const CBMRegisteredFunc *cs_lookup_method(CSLSPContext *ctx, const char *type_qn,
const char *method_name);
+/* Apply the local AST-declared return-type refinement to an already populated
+ * registry. Kept as a production-used seam so post-registration signature
+ * preservation can be regression-tested directly. */
+void cbm_cs_refine_ast_return_types(CSLSPContext *ctx, CBMTypeRegistry *reg, TSNode root);
+
/* Single-file entry: build registry from file defs + stdlib, run resolution. */
void cbm_run_cs_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root);
diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c
index 7162eb27e..7dd1c9c78 100644
--- a/internal/cbm/lsp/go_lsp.c
+++ b/internal/cbm/lsp/go_lsp.c
@@ -22,7 +22,9 @@ static void resolve_calls_in_node(GoLSPContext* ctx, TSNode node) {
resolve_calls_in_node_inner(ctx, node);
ctx->walk_depth--;
}
-static void emit_resolved_call(GoLSPContext* ctx, const char* callee_qn, const char* strategy, float confidence);
+static void emit_resolved_call(GoLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site);
+static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node);
static const CBMType* go_lookup_field(GoLSPContext* ctx, const char* type_qn, const char* field_name, int depth);
static void extract_type_params_from_ast(CBMArena* arena, CBMTypeRegistry* reg,
TSNode root, const char* source, const char* module_qn);
@@ -336,7 +338,8 @@ const CBMType* go_eval_expr_type(GoLSPContext* ctx, TSNode node) {
// Check scope first
const CBMType* t = cbm_scope_lookup(ctx->current_scope, name);
- if (!cbm_type_is_unknown(t)) return t;
+ if (cbm_scope_contains(ctx->current_scope, name))
+ return t ? t : cbm_type_unknown();
// Check if it's a package-level function
const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name);
@@ -929,6 +932,76 @@ const CBMRegisteredFunc* go_lookup_field_or_method(GoLSPContext* ctx,
return go_lookup_field_or_method_depth(ctx, type_qn, member_name, 0);
}
+/* Resolve only source forms that prove one callable identity. This is
+ * intentionally narrower than go_eval_expr_type: conditional expressions,
+ * indexed dispatch tables, interfaces with several implementers, and unknown
+ * locals remain ordinary values. */
+static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return NULL;
+ const char *kind = ts_node_type(node);
+
+ if (strcmp(kind, "parenthesized_expression") == 0 && ts_node_named_child_count(node) == 1) {
+ return go_exact_callable_target(ctx, ts_node_named_child(node, 0));
+ }
+
+ if (strcmp(kind, "identifier") == 0) {
+ char *name = lsp_node_text(ctx, node);
+ if (!name)
+ return NULL;
+ /* A local value shadows the package declaration even when its type is
+ * UNKNOWN. Only an explicitly tracked callable alias may pass. */
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ return cbm_scope_lookup_callable(ctx->current_scope, name);
+ }
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name);
+ return f ? f->qualified_name : NULL;
+ }
+
+ if (strcmp(kind, "selector_expression") == 0) {
+ TSNode operand = ts_node_child_by_field_name(node, "operand", 7);
+ TSNode field = ts_node_child_by_field_name(node, "field", 5);
+ if (ts_node_is_null(operand) || ts_node_is_null(field))
+ return NULL;
+ char *member = lsp_node_text(ctx, field);
+ if (!member)
+ return NULL;
+
+ if (strcmp(ts_node_type(operand), "identifier") == 0) {
+ char *local = lsp_node_text(ctx, operand);
+ const char *package_qn = local ? resolve_import(ctx, local) : NULL;
+ if (package_qn) {
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, package_qn, member);
+ return f ? f->qualified_name : NULL;
+ }
+ }
+
+ const CBMType *recv = go_eval_expr_type(ctx, operand);
+ if (recv && recv->kind == CBM_TYPE_POINTER)
+ recv = cbm_type_deref(recv);
+ if (recv && recv->kind == CBM_TYPE_NAMED) {
+ /* A direct method name is unique in a valid Go method set.
+ * Promoted lookup through embedded types can be ambiguous; without
+ * full selector-depth resolution, fail closed and retain USAGE. */
+ const CBMRegisteredFunc *method =
+ cbm_registry_lookup_method(ctx->registry, recv->data.named.qualified_name, member);
+ return method ? method->qualified_name : NULL;
+ }
+ }
+ return NULL;
+}
+
+static void go_scope_bind_value(GoLSPContext *ctx, const char *name, const CBMType *type,
+ const char *callable_qn) {
+ if (callable_qn) {
+ cbm_scope_bind_callable(ctx->current_scope, name, type, callable_qn);
+ } else {
+ cbm_scope_bind(ctx->current_scope, name, type);
+ }
+}
+
// --- go_process_statement: bind variables from statements ---
void go_process_statement(GoLSPContext* ctx, TSNode node) {
@@ -942,17 +1015,22 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
if (ts_node_is_null(left) || ts_node_is_null(right)) return;
const CBMType* rhs_type = NULL;
+ TSNode single_rhs = {0};
// Check if RHS is an expression_list (multiple values)
if (strcmp(ts_node_type(right), "expression_list") == 0) {
uint32_t rhs_count = ts_node_named_child_count(right);
if (rhs_count == 1) {
// Single expression that might return a tuple (multi-return)
- rhs_type = go_eval_expr_type(ctx, ts_node_named_child(right, 0));
+ single_rhs = ts_node_named_child(right, 0);
+ rhs_type = go_eval_expr_type(ctx, single_rhs);
}
} else {
+ single_rhs = right;
rhs_type = go_eval_expr_type(ctx, right);
}
+ const char *rhs_callable =
+ ts_node_is_null(single_rhs) ? NULL : go_exact_callable_target(ctx, single_rhs);
// Bind left-hand side variables
if (strcmp(ts_node_type(left), "expression_list") == 0) {
@@ -971,23 +1049,67 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
var_type = rhs_type;
}
}
- cbm_scope_bind(ctx->current_scope, var_name, var_type);
+ go_scope_bind_value(ctx, var_name, var_type, i == 0 ? rhs_callable : NULL);
}
} else if (strcmp(ts_node_type(left), "identifier") == 0) {
char* var_name = lsp_node_text(ctx, left);
if (var_name && strcmp(var_name, "_") != 0 && rhs_type) {
- cbm_scope_bind(ctx->current_scope, var_name, rhs_type);
+ go_scope_bind_value(ctx, var_name, rhs_type, rhs_callable);
}
}
return;
}
+ /* Reassignment must update (or clear) callable identity just like :=.
+ * Without this, `alias := target; alias = dynamic; alias()` would retain a
+ * stale exact target and fabricate a call. */
+ if (strcmp(kind, "assignment_statement") == 0) {
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (ts_node_is_null(left) || ts_node_is_null(right))
+ return;
+ uint32_t lhs_count = strcmp(ts_node_type(left), "expression_list") == 0
+ ? ts_node_named_child_count(left)
+ : 1;
+ uint32_t rhs_count = strcmp(ts_node_type(right), "expression_list") == 0
+ ? ts_node_named_child_count(right)
+ : 1;
+ for (uint32_t i = 0; i < lhs_count; i++) {
+ TSNode lhs = lhs_count == 1 && strcmp(ts_node_type(left), "expression_list") != 0
+ ? left
+ : ts_node_named_child(left, i);
+ if (ts_node_is_null(lhs) || strcmp(ts_node_type(lhs), "identifier") != 0)
+ continue;
+ char *name = lsp_node_text(ctx, lhs);
+ if (!name || strcmp(name, "_") == 0)
+ continue;
+ TSNode rhs = {0};
+ if (rhs_count == lhs_count) {
+ rhs = rhs_count == 1 && strcmp(ts_node_type(right), "expression_list") != 0
+ ? right
+ : ts_node_named_child(right, i);
+ }
+ const CBMType *type =
+ ts_node_is_null(rhs) ? cbm_type_unknown() : go_eval_expr_type(ctx, rhs);
+ const char *callable = ts_node_is_null(rhs) ? NULL : go_exact_callable_target(ctx, rhs);
+ go_scope_bind_value(ctx, name, type, callable);
+ }
+ return;
+ }
+
// var_spec: var x Type = expr OR var a, b, c Type = expr
if (strcmp(kind, "var_spec") == 0) {
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
TSNode value_node = ts_node_child_by_field_name(node, "value", 5);
const CBMType* var_type = cbm_type_unknown();
+ TSNode callable_value = value_node;
+ if (!ts_node_is_null(value_node) &&
+ strcmp(ts_node_type(value_node), "expression_list") == 0) {
+ callable_value = ts_node_named_child_count(value_node) == 1
+ ? ts_node_named_child(value_node, 0)
+ : (TSNode){0};
+ }
if (!ts_node_is_null(type_node)) {
var_type = go_parse_type_node(ctx, type_node);
} else if (!ts_node_is_null(value_node)) {
@@ -998,6 +1120,8 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
var_type = go_eval_expr_type(ctx, value_node);
}
}
+ const char *callable_qn =
+ ts_node_is_null(callable_value) ? NULL : go_exact_callable_target(ctx, callable_value);
// Bind all name identifiers (handles: var a, b, c int)
uint32_t vnc = ts_node_child_count(node);
@@ -1007,7 +1131,7 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
if (strcmp(ts_node_type(ch), "identifier") == 0) {
char* var_name = lsp_node_text(ctx, ch);
if (var_name && strcmp(var_name, "_") != 0) {
- cbm_scope_bind(ctx->current_scope, var_name, var_type);
+ go_scope_bind_value(ctx, var_name, var_type, callable_qn);
}
}
}
@@ -1022,6 +1146,13 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
if (ts_node_is_null(name_node)) return;
const CBMType* const_type = cbm_type_unknown();
+ TSNode callable_value = value_node;
+ if (!ts_node_is_null(value_node) &&
+ strcmp(ts_node_type(value_node), "expression_list") == 0) {
+ callable_value = ts_node_named_child_count(value_node) == 1
+ ? ts_node_named_child(value_node, 0)
+ : (TSNode){0};
+ }
if (!ts_node_is_null(type_node)) {
const_type = go_parse_type_node(ctx, type_node);
} else if (!ts_node_is_null(value_node)) {
@@ -1033,11 +1164,13 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
const_type = go_eval_expr_type(ctx, value_node);
}
}
+ const char *callable_qn =
+ ts_node_is_null(callable_value) ? NULL : go_exact_callable_target(ctx, callable_value);
if (strcmp(ts_node_type(name_node), "identifier") == 0) {
char* name = lsp_node_text(ctx, name_node);
if (name && strcmp(name, "_") != 0)
- cbm_scope_bind(ctx->current_scope, name, const_type);
+ go_scope_bind_value(ctx, name, const_type, callable_qn);
}
return;
}
@@ -1094,33 +1227,151 @@ void go_process_statement(GoLSPContext* ctx, TSNode node) {
// (needs per-case scope narrowing, not just variable binding)
}
-// --- Emit a resolved call ---
+// --- Emit a resolved call/reference ---
-static void emit_resolved_call(GoLSPContext* ctx, const char* callee_qn, const char* strategy, float confidence) {
+static void go_emit_resolved_kind(GoLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, const char *source_name, CBMResolvedKind kind,
+ TSNode site) {
if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn) return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
rc.confidence = confidence;
- rc.reason = NULL;
+ /* When a callable alias has a different textual leaf, retain that source
+ * name for the exact-site join. */
+ rc.reason = source_name;
+ rc.kind = kind;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+static void emit_resolved_call(GoLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site) {
+ go_emit_resolved_kind(ctx, callee_qn, strategy, confidence, NULL, CBM_RESOLVED_INVOCATION,
+ site);
+}
+
+static void emit_resolved_alias_call(GoLSPContext *ctx, const char *callee_qn,
+ const char *source_name, TSNode site) {
+ go_emit_resolved_kind(ctx, callee_qn, "lsp_callable_alias", 0.97f, source_name,
+ CBM_RESOLVED_INVOCATION, site);
+}
+
+static void emit_resolved_reference(GoLSPContext *ctx, const char *callee_qn,
+ const char *source_name, TSNode site) {
+ const char *leaf = strrchr(callee_qn, '.');
+ leaf = leaf ? leaf + 1 : callee_qn;
+ const char *join_name = source_name && strcmp(source_name, leaf) != 0 ? source_name : NULL;
+ go_emit_resolved_kind(ctx, callee_qn, "lsp_callable_value_reference", 0.97f, join_name,
+ CBM_RESOLVED_CALL_REFERENCE, site);
+}
+
+static void emit_unresolved_reference(GoLSPContext *ctx, const char *source_name, TSNode site) {
+ if (!ctx || !ctx->resolved_calls || !ctx->enclosing_func_qn || !source_name ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = source_name;
+ rc.strategy = "lsp_unresolved";
+ rc.confidence = 0.0f;
+ rc.reason = "callable_value_not_in_registry";
+ rc.kind = CBM_RESOLVED_CALL_REFERENCE;
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
// Emit a diagnostic for an unresolved call (confidence 0.0).
-static void emit_unresolved_call(GoLSPContext* ctx, const char* expr_text, const char* reason) {
+static void emit_unresolved_call(GoLSPContext *ctx, const char *expr_text, const char *reason,
+ TSNode site) {
if (!ctx->resolved_calls || !ctx->enclosing_func_qn) return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
rc.strategy = "lsp_unresolved";
rc.confidence = 0.0f;
rc.reason = reason;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+/* Only direct argument expressions are candidates. Descending into a
+ * conditional/map/index expression would promote its constituent names even
+ * though the runtime callable is not statically unique. */
+static void go_resolve_value_references_at(GoLSPContext *ctx, TSNode call) {
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(args))
+ return;
+ uint32_t count = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode arg = ts_node_named_child(args, i);
+ const char *kind = ts_node_type(arg);
+ if (strcmp(kind, "identifier") != 0 && strcmp(kind, "selector_expression") != 0 &&
+ strcmp(kind, "parenthesized_expression") != 0)
+ continue;
+ const char *target = go_exact_callable_target(ctx, arg);
+ char *source_name = lsp_node_text(ctx, arg);
+ if (target) {
+ emit_resolved_reference(ctx, target, source_name, arg);
+ } else if (strcmp(kind, "identifier") == 0 && source_name &&
+ !cbm_scope_contains(ctx->current_scope, source_name)) {
+ /* The per-file registry cannot see an unqualified function from
+ * another file in the same Go package. Preserve the exact source
+ * occurrence for the metadata-only project pass. */
+ emit_unresolved_reference(ctx, source_name, arg);
+ }
+ }
+}
+
+/* Any assignment that is guarded by a branch/loop makes the post-construct
+ * callable identity a join of at least two paths. Clear the outer exact
+ * identity before walking the construct; assignments inside its temporary
+ * scope may still be exact locally, but cannot leak past the join. */
+static void go_invalidate_control_flow_aliases(GoLSPContext *ctx, TSNode node, int depth) {
+ if (!ctx || ts_node_is_null(node) || depth > 64)
+ return;
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "func_literal") == 0)
+ return;
+ if (strcmp(kind, "assignment_statement") == 0) {
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ if (!ts_node_is_null(left)) {
+ uint32_t count = strcmp(ts_node_type(left), "expression_list") == 0
+ ? ts_node_named_child_count(left)
+ : 1;
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode target = count == 1 && strcmp(ts_node_type(left), "expression_list") != 0
+ ? left
+ : ts_node_named_child(left, i);
+ if (ts_node_is_null(target) || strcmp(ts_node_type(target), "identifier") != 0) {
+ continue;
+ }
+ char *name = lsp_node_text(ctx, target);
+ if (name && cbm_scope_lookup_callable(ctx->current_scope, name)) {
+ cbm_scope_update_callable(ctx->current_scope, name, NULL);
+ }
+ }
+ }
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ go_invalidate_control_flow_aliases(ctx, ts_node_named_child(node, i), depth + 1);
+ }
+}
+
// --- Walk call expressions and resolve them ---
static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
@@ -1130,8 +1381,15 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
// Process statements to build scope
go_process_statement(ctx, node);
+ if (strcmp(kind, "if_statement") == 0 || strcmp(kind, "for_statement") == 0 ||
+ strcmp(kind, "expression_switch_statement") == 0 ||
+ strcmp(kind, "type_switch_statement") == 0 || strcmp(kind, "select_statement") == 0) {
+ go_invalidate_control_flow_aliases(ctx, node, 0);
+ }
+
// Resolve call expressions
if (strcmp(kind, "call_expression") == 0) {
+ go_resolve_value_references_at(ctx, node);
TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
if (!ts_node_is_null(func_node)) {
const char* fk = ts_node_type(func_node);
@@ -1151,13 +1409,15 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
if (pkg_qn && field_name) {
const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name);
if (f) {
- emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f);
+ emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f,
+ node);
goto recurse;
}
// Package found but symbol not in registry
- emit_unresolved_call(ctx,
+ emit_unresolved_call(
+ ctx,
cbm_arena_sprintf(ctx->arena, "%s.%s", pkg_name, field_name),
- "symbol_not_in_registry");
+ "symbol_not_in_registry", node);
goto recurse;
}
}
@@ -1170,16 +1430,26 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
if (base && base->kind == CBM_TYPE_POINTER) base = cbm_type_deref(base);
if (base && base->kind == CBM_TYPE_NAMED) {
- const CBMRegisteredFunc* method = go_lookup_field_or_method(ctx,
- base->data.named.qualified_name, field_name);
- if (method) {
- const char* strategy = "lsp_type_dispatch";
- if (method->receiver_type &&
- strcmp(method->receiver_type, base->data.named.qualified_name) != 0) {
- strategy = "lsp_embed_dispatch";
+ const CBMRegisteredType *receiver_type = cbm_registry_lookup_type(
+ ctx->registry, base->data.named.qualified_name);
+ /* Registered interface receivers must reach the
+ * interface-resolution branch below. Their semantic
+ * method registrations are signatures, not concrete
+ * dispatch targets. */
+ if (!receiver_type || !receiver_type->is_interface) {
+ const CBMRegisteredFunc *method = go_lookup_field_or_method(
+ ctx, base->data.named.qualified_name, field_name);
+ if (method) {
+ const char *strategy = "lsp_type_dispatch";
+ if (method->receiver_type &&
+ strcmp(method->receiver_type,
+ base->data.named.qualified_name) != 0) {
+ strategy = "lsp_embed_dispatch";
+ }
+ emit_resolved_call(ctx, method->qualified_name, strategy, 0.95f,
+ node);
+ goto recurse;
}
- emit_resolved_call(ctx, method->qualified_name, strategy, 0.95f);
- goto recurse;
}
}
@@ -1243,17 +1513,20 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
// `Type.method` wins over the interface-method type_dispatch
// for the same call site.
emit_resolved_call(ctx, concrete_method->qualified_name,
- "lsp_interface_resolve", 0.95f);
+ "lsp_interface_resolve", 0.95f,
+ node);
goto recurse;
}
}
}
// Fallback: generic interface dispatch
- emit_resolved_call(ctx,
+ emit_resolved_call(
+ ctx,
cbm_arena_sprintf(ctx->arena, "%s.%s",
- iface_qn ? iface_qn : "interface", field_name),
- "lsp_interface_dispatch", 0.85f);
+ iface_qn ? iface_qn : "interface",
+ field_name),
+ "lsp_interface_dispatch", 0.85f, node);
goto recurse;
}
}
@@ -1261,15 +1534,17 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
// Type resolved to NAMED but neither method nor interface matched
if (base && base->kind == CBM_TYPE_NAMED) {
emit_unresolved_call(ctx,
- cbm_arena_sprintf(ctx->arena, "%s.%s",
- base->data.named.qualified_name, field_name),
- "method_not_found");
+ cbm_arena_sprintf(ctx->arena, "%s.%s",
+ base->data.named.qualified_name,
+ field_name),
+ "method_not_found", node);
} else if (cbm_type_is_unknown(recv_type)) {
char* operand_text = lsp_node_text(ctx, operand);
- emit_unresolved_call(ctx,
+ emit_unresolved_call(
+ ctx,
cbm_arena_sprintf(ctx->arena, "%s.%s",
- operand_text ? operand_text : "?", field_name),
- "unknown_receiver_type");
+ operand_text ? operand_text : "?", field_name),
+ "unknown_receiver_type", node);
}
}
}
@@ -1279,12 +1554,23 @@ static void resolve_calls_in_node_inner(GoLSPContext* ctx, TSNode node) {
if (strcmp(fk, "identifier") == 0) {
char* name = lsp_node_text(ctx, func_node);
if (name && !is_go_builtin_func(name)) {
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ const char *alias_target =
+ cbm_scope_lookup_callable(ctx->current_scope, name);
+ if (alias_target) {
+ emit_resolved_alias_call(ctx, alias_target, name, node);
+ } else {
+ emit_unresolved_call(ctx, name, "lexical_value_not_exact_callable",
+ node);
+ }
+ goto recurse;
+ }
// Package-local function
const CBMRegisteredFunc* f = cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name);
if (f) {
- emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f);
+ emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, node);
} else {
- emit_unresolved_call(ctx, name, "function_not_in_registry");
+ emit_unresolved_call(ctx, name, "function_not_in_registry", node);
}
}
}
@@ -1715,6 +2001,17 @@ const CBMType* cbm_parse_return_type_text(CBMArena* a, const char* text, const c
return cbm_type_named(a, cbm_arena_sprintf(a, "%s.%s", module_qn, text));
}
+typedef struct {
+ const char *module_qn;
+} CBMGoLSPSignatureParserContext;
+
+static const CBMType *cbm_go_lsp_parse_signature_param_text(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const CBMGoLSPSignatureParserContext *ctx = (const CBMGoLSPSignatureParserContext *)parser_ctx;
+ const char *module_qn = ctx && ctx->module_qn ? ctx->module_qn : "";
+ return cbm_parse_return_type_text(arena, text, module_qn);
+}
+
// --- Entry point: build registry from file defs + run LSP ---
void cbm_run_go_lsp(CBMArena* arena, CBMFileResult* result,
@@ -1790,9 +2087,21 @@ void cbm_run_go_lsp(CBMArena* arena, CBMFileResult* result,
ret_types[1] = NULL;
}
- // Build param types from param_types array
+ /* The occurrence-preserving carrier is authoritative whenever it
+ * is present, including a non-NULL carrier with an explicit zero
+ * count. Its slots deliberately have no names because legacy name
+ * extraction is not guaranteed to have the same multiplicity. */
const CBMType** param_types_arr = NULL;
- if (d->param_types) {
+ const char **param_names_arr = NULL;
+ bool has_ordered_params =
+ d->signature_param_types != NULL || d->signature_param_count > 0;
+ CBMGoLSPSignatureParserContext param_parser_ctx = {module_qn};
+ if (has_ordered_params) {
+ param_types_arr = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_go_lsp_parse_signature_param_text, &param_parser_ctx);
+ } else if (d->param_types) {
+ param_names_arr = d->param_names;
int count = 0;
while (d->param_types[count]) count++;
if (count > 0) {
@@ -1802,37 +2111,44 @@ void cbm_run_go_lsp(CBMArena* arena, CBMFileResult* result,
}
param_types_arr[count] = NULL;
}
- }
-
- rf.signature = cbm_type_func(arena, d->param_names, param_types_arr, ret_types);
-
- // For methods, extract receiver type from receiver text
- if (strcmp(d->label, "Method") == 0 && d->receiver && d->receiver[0]) {
- // Receiver format: "(name *Type)" or "(name Type)"
- // Extract type name: skip parens, skip first identifier, strip *
- const char* r = d->receiver;
- while (*r == '(' || *r == ' ') r++;
- // Skip receiver name
- while (*r && *r != ' ' && *r != '*') r++;
- while (*r == ' ' || *r == '*') r++;
- // Now r points to the type name
- const char* end = r;
- while (*end && *end != ')' && *end != ' ') end++;
- if (end > r) {
- char* type_name = cbm_arena_strndup(arena, r, end - r);
- rf.receiver_type = cbm_arena_sprintf(arena, "%s.%s", module_qn, type_name);
-
- // Also register this method under the type
- const CBMRegisteredType* existing = cbm_registry_lookup_type(&reg, rf.receiver_type);
- if (!existing) {
- // Auto-create the type entry
- CBMRegisteredType auto_type;
- memset(&auto_type, 0, sizeof(auto_type));
- auto_type.qualified_name = rf.receiver_type;
- auto_type.short_name = type_name;
- cbm_registry_add_type(&reg, auto_type);
+ } else {
+ param_names_arr = d->param_names;
+ }
+
+ rf.signature = cbm_type_func(arena, param_names_arr, param_types_arr, ret_types);
+
+ // Prefer the extractor's semantic receiver QN. Raw receiver text is
+ // retained only as a compatibility fallback for hand-built defs;
+ // reparsing it alone loses valid unnamed receivers such as `(Right)`.
+ if (strcmp(d->label, "Method") == 0) {
+ if (d->parent_class && d->parent_class[0]) {
+ rf.receiver_type = d->parent_class;
+ } else if (d->receiver && d->receiver[0]) {
+ // Legacy named receiver formats: "(name *Type)" / "(name Type)".
+ const char *r = d->receiver;
+ while (*r == '(' || *r == ' ')
+ r++;
+ while (*r && *r != ' ' && *r != '*')
+ r++;
+ while (*r == ' ' || *r == '*')
+ r++;
+ const char *end = r;
+ while (*end && *end != ')' && *end != ' ')
+ end++;
+ if (end > r) {
+ char *type_name = cbm_arena_strndup(arena, r, (size_t)(end - r));
+ rf.receiver_type = cbm_arena_sprintf(arena, "%s.%s", module_qn, type_name);
}
}
+
+ if (rf.receiver_type && !cbm_registry_lookup_type(&reg, rf.receiver_type)) {
+ const char *dot = strrchr(rf.receiver_type, '.');
+ CBMRegisteredType auto_type;
+ memset(&auto_type, 0, sizeof(auto_type));
+ auto_type.qualified_name = rf.receiver_type;
+ auto_type.short_name = dot ? dot + 1 : rf.receiver_type;
+ cbm_registry_add_type(&reg, auto_type);
+ }
}
cbm_registry_add_func(&reg, rf);
@@ -2343,6 +2659,42 @@ static const CBMType* parse_type_node_with_params(CBMArena* arena, TSNode node,
return cbm_type_unknown();
}
+/* Go permits one AST parameter declaration to introduce several call
+ * positions: `first, second T`. Count direct names without exposing or
+ * rewriting the legacy public param_names projection. */
+static int cbm_go_lsp_signature_param_multiplicity(TSNode param) {
+ const char *kind = ts_node_type(param);
+ if (strcmp(kind, "parameter_declaration") != 0 &&
+ strcmp(kind, "variadic_parameter_declaration") != 0) {
+ return 1;
+ }
+
+ int field_names = 0;
+ int identifier_names = 0;
+ uint32_t child_count = ts_node_child_count(param);
+ for (uint32_t i = 0; i < child_count; i++) {
+ TSNode child = ts_node_child(param, i);
+ if (ts_node_is_null(child) || !ts_node_is_named(child))
+ continue;
+ const char *field = ts_node_field_name_for_child(param, i);
+ if (field && strcmp(field, "name") == 0)
+ field_names++;
+ if (strcmp(ts_node_type(child), "identifier") == 0)
+ identifier_names++;
+ }
+
+ int names = field_names > 0 ? field_names : identifier_names;
+ return names > 0 ? names : 1;
+}
+
+static const CBMType *cbm_go_lsp_keep_known_refinement(const CBMType *candidate,
+ const CBMType *existing) {
+ if (cbm_type_is_unknown(candidate) && !cbm_type_is_unknown(existing)) {
+ return existing;
+ }
+ return candidate ? candidate : cbm_type_unknown();
+}
+
// Scan AST for generic function declarations and set type_param_names + re-parse
// return types on matching registered functions.
static void extract_type_params_from_ast(CBMArena* arena, CBMTypeRegistry* reg,
@@ -2450,20 +2802,32 @@ static void extract_type_params_from_ast(CBMArena* arena, CBMTypeRegistry* reg,
if (ts_node_is_null(rchild) || !ts_node_is_named(rchild)) continue;
TSNode rtype = ts_node_child_by_field_name(rchild, "type", 4);
if (ts_node_is_null(rtype)) rtype = rchild;
- new_rets[idx++] = parse_type_node_with_params(arena,
- rtype, source, module_qn, tp_names);
+ const CBMType *parsed = parse_type_node_with_params(
+ arena, rtype, source, module_qn, tp_names);
+ new_rets[idx] =
+ cbm_go_lsp_keep_known_refinement(parsed, old_rets[idx]);
+ idx++;
}
- new_rets[idx] = NULL;
+ while (idx < ret_count) {
+ new_rets[idx] = old_rets[idx];
+ idx++;
+ }
+ new_rets[ret_count] = NULL;
} else {
- new_rets[0] = parse_type_node_with_params(arena,
- result_node, source, module_qn, tp_names);
- new_rets[1] = NULL;
+ const CBMType *parsed = parse_type_node_with_params(
+ arena, result_node, source, module_qn, tp_names);
+ new_rets[0] = cbm_go_lsp_keep_known_refinement(parsed, old_rets[0]);
+ for (int idx = 1; idx < ret_count; idx++) {
+ new_rets[idx] = old_rets[idx];
+ }
+ new_rets[ret_count] = NULL;
}
- CBMType* new_sig = (CBMType*)cbm_arena_alloc(arena, sizeof(CBMType));
- *new_sig = *(CBMType*)reg->funcs[fi].signature;
- new_sig->data.func.return_types = new_rets;
- reg->funcs[fi].signature = new_sig;
+ const CBMType *new_sig = cbm_type_func_replace_returns(
+ arena, reg->funcs[fi].signature, new_rets);
+ if (new_sig && new_sig->kind == CBM_TYPE_FUNC) {
+ reg->funcs[fi].signature = new_sig;
+ }
}
}
}
@@ -2480,26 +2844,40 @@ static void extract_type_params_from_ast(CBMArena* arena, CBMTypeRegistry* reg,
const CBMType** new_params = (const CBMType**)cbm_arena_alloc(arena,
(pc + 1) * sizeof(const CBMType*));
int idx = 0;
+ bool overflow = false;
uint32_t pnc = ts_node_child_count(params_node);
- for (uint32_t pi = 0; pi < pnc && idx < pc; pi++) {
+ for (uint32_t pi = 0; pi < pnc && !overflow; pi++) {
TSNode pchild = ts_node_child(params_node, pi);
if (ts_node_is_null(pchild) || !ts_node_is_named(pchild)) continue;
- if (strcmp(ts_node_type(pchild), "parameter_declaration") != 0) continue;
+ const char *param_kind = ts_node_type(pchild);
+ if (strcmp(param_kind, "parameter_declaration") != 0 &&
+ strcmp(param_kind, "variadic_parameter_declaration") != 0) {
+ continue;
+ }
TSNode ptype = ts_node_child_by_field_name(pchild, "type", 4);
- if (ts_node_is_null(ptype)) continue;
- new_params[idx++] = parse_type_node_with_params(arena,
- ptype, source, module_qn, tp_names);
+ const CBMType *parsed =
+ ts_node_is_null(ptype)
+ ? cbm_type_unknown()
+ : parse_type_node_with_params(arena, ptype, source, module_qn,
+ tp_names);
+ int multiplicity = cbm_go_lsp_signature_param_multiplicity(pchild);
+ for (int occurrence = 0; occurrence < multiplicity; occurrence++) {
+ if (idx >= pc) {
+ overflow = true;
+ break;
+ }
+ new_params[idx] =
+ cbm_go_lsp_keep_known_refinement(parsed, old_params[idx]);
+ idx++;
+ }
}
new_params[idx] = NULL;
- if (idx > 0) {
- CBMType* sig = (CBMType*)reg->funcs[fi].signature;
- if (sig != reg->funcs[fi].signature) {
- // Already rebuilt — update in place
- ((CBMType*)reg->funcs[fi].signature)->data.func.param_types = new_params;
- } else {
- CBMType* new_sig = (CBMType*)cbm_arena_alloc(arena, sizeof(CBMType));
- *new_sig = *sig;
- new_sig->data.func.param_types = new_params;
+ if (!overflow && idx == pc) {
+ const CBMType *old_sig = reg->funcs[fi].signature;
+ const CBMType *new_sig =
+ cbm_type_func(arena, old_sig->data.func.param_names, new_params,
+ old_sig->data.func.return_types);
+ if (new_sig && new_sig->kind == CBM_TYPE_FUNC) {
reg->funcs[fi].signature = new_sig;
}
}
@@ -2587,7 +2965,11 @@ void cbm_run_go_lsp_cross(
// Build FUNC type from return_types text
const CBMType** ret_types = split_pipe_types(arena, d->return_types, def_mod);
- rf.signature = cbm_type_func(arena, NULL, NULL, ret_types);
+ CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod};
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_go_lsp_parse_signature_param_text, &param_parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
// Method receiver
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
@@ -2833,7 +3215,11 @@ CBMTypeRegistry* cbm_go_build_cross_registry(
rf.qualified_name = d->qualified_name; /* borrowed */
rf.short_name = d->short_name;
const CBMType** ret_types = split_pipe_types(arena, d->return_types, def_mod);
- rf.signature = cbm_type_func(arena, NULL, NULL, ret_types);
+ CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod};
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_go_lsp_parse_signature_param_text, &param_parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
rf.receiver_type = d->receiver_type;
if (!cbm_registry_lookup_type(reg, rf.receiver_type)) {
@@ -2972,17 +3358,28 @@ int cbm_go_fast_resolve_qualified_calls(
}
}
+ /* Case 3: an unqualified function value from another source file in
+ * the same Go package. Go module QNs are directory-based, so this is
+ * an exact package-local lookup rather than a project-wide short-name
+ * guess. */
+ if (!f && !strchr(uc->callee_qn, '.') && result->module_qn) {
+ f = cbm_registry_lookup_symbol(reg, result->module_qn, uc->callee_qn);
+ }
+
if (!f) continue;
/* Emit a resolved entry. cbm_pipeline_find_lsp_resolution
* picks the highest-confidence match, so the unresolved entry
* stays (harmless duplicate) but our resolved entry wins. */
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = uc->caller_qn;
rc.callee_qn = f->qualified_name; /* borrowed from pipeline arena */
rc.strategy = "lsp_strategy_cross_file";
rc.confidence = 0.92f;
rc.reason = NULL;
+ rc.kind = uc->kind;
+ rc.site_start_byte = uc->site_start_byte;
+ rc.site_end_byte = uc->site_end_byte;
cbm_resolvedcall_push(&result->resolved_calls, &result->arena, rc);
newly_resolved++;
}
@@ -3034,11 +3431,15 @@ void cbm_batch_go_lsp_cross(
for (int j = 0; j < file_out.count; j++) {
CBMResolvedCall* src = &file_out.items[j];
CBMResolvedCall* dst = &out[f].items[j];
+ memset(dst, 0, sizeof(*dst));
dst->caller_qn = src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn = src->callee_qn ? cbm_arena_strdup(arena, src->callee_qn) : NULL;
dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
}
}
diff --git a/internal/cbm/lsp/go_lsp.h b/internal/cbm/lsp/go_lsp.h
index 0948d4510..65e97675c 100644
--- a/internal/cbm/lsp/go_lsp.h
+++ b/internal/cbm/lsp/go_lsp.h
@@ -84,9 +84,21 @@ typedef struct {
const char* embedded_types; // "|"-separated embedded type QNs (for struct embedding)
const char* field_defs; // "|"-separated "name:type" pairs (for struct fields, e.g. "Binder:Binder|Name:string")
const char* method_names_str; // "|"-separated method names for interfaces (e.g. "Get|Put|Delete")
+ const char **signature_param_types; // borrowed ordered parameter type texts; "?" means unknown
+ int signature_param_count; // number of positional entries above
bool is_interface;
CBMLanguage lang; // language of the file that defined this — used by Tier 2 per-language registry build to filter all_defs
const char* namespace_name; // declared namespace/package for source-root-independent JVM filtering
+ /* Rust-only raw trait spelling. The Rust registry canonicalizes this
+ * only when it has one exact/unique trait target. */
+ const char *trait_qn;
+ bool is_rust_impl_relation; // independent type-level impl record (empty impls survive)
+ bool is_abstract; // Rust required trait method; false for defaults
+ /* Python-only raw decorator syntax, borrowed from CBMDefinition. The
+ * resolver must retain it across fused/cross-file registry construction:
+ * a decorator rebinds the function name, so the undecorated definition is
+ * not automatically an exact callable-value target. */
+ const char **decorators;
} CBMLSPDef;
// Parse source, build registry from defs + stdlib, run LSP.
diff --git a/internal/cbm/lsp/java_lsp.c b/internal/cbm/lsp/java_lsp.c
index c692d9a6a..a24a93cc5 100644
--- a/internal/cbm/lsp/java_lsp.c
+++ b/internal/cbm/lsp/java_lsp.c
@@ -1632,6 +1632,24 @@ static const char *class_super_qn(JavaLSPContext *ctx, TSNode class_node) {
return NULL;
}
+/* Java enum constants are direct enum_body children, while declarations after
+ * the semicolon live in enum_body_declarations. LSP class processing only
+ * wants declarations, so expose the nested container for enums and the normal
+ * body for every other type declaration. */
+static TSNode java_type_declaration_body(TSNode node) {
+ TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ if (ts_node_is_null(body) || strcmp(ts_node_type(body), "enum_body") != 0)
+ return body;
+
+ uint32_t count = ts_node_named_child_count(body);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode child = ts_node_named_child(body, i);
+ if (strcmp(ts_node_type(child), "enum_body_declarations") == 0)
+ return child;
+ }
+ return body;
+}
+
static void java_process_class_decl(JavaLSPContext *ctx, TSNode node) {
TSNode name_node = ts_node_child_by_field_name(node, "name", 4);
if (ts_node_is_null(name_node))
@@ -1664,7 +1682,7 @@ static void java_process_class_decl(JavaLSPContext *ctx, TSNode node) {
ctx->enclosing_super_qn = super_qn;
ctx->enclosing_class_short = cname;
- TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ TSNode body = java_type_declaration_body(node);
if (!ts_node_is_null(body)) {
CBMScope *saved_scope = ctx->current_scope;
ctx->current_scope = cbm_scope_push(ctx->arena, saved_scope);
@@ -1779,40 +1797,87 @@ void java_lsp_process_file(JavaLSPContext *ctx, TSNode root) {
/* ── Call-edge resolution ─────────────────────────────────────────── */
-static void java_emit_resolved_orig(JavaLSPContext *ctx, const char *callee_qn, const char *orig,
- const char *strategy, float confidence) {
+static void java_emit_resolved_orig_kind(JavaLSPContext *ctx, const char *callee_qn,
+ const char *orig, const char *strategy, float confidence,
+ CBMResolvedKind kind) {
if (!ctx->resolved_calls || !ctx->enclosing_method_qn || !callee_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_method_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
rc.confidence = confidence;
- // For a data-flow resolution (constructor reference `Lhs::new` resolved to
- // the Lhs class), `reason` carries the ORIGINAL textual callee (`new`) so the
- // pipeline join can match the textual call site even though the resolved
- // callee_qn's short name differs. NULL/unread for normal resolved calls.
+ rc.kind = kind;
+ // For data-flow resolutions, `reason` may carry the original textual
+ // callee when it differs from the resolved target. NULL for normal calls.
rc.reason = orig;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+static void java_emit_resolved_orig(JavaLSPContext *ctx, const char *callee_qn, const char *orig,
+ const char *strategy, float confidence) {
+ java_emit_resolved_orig_kind(ctx, callee_qn, orig, strategy, confidence,
+ CBM_RESOLVED_INVOCATION);
+}
+
static void java_emit_resolved(JavaLSPContext *ctx, const char *callee_qn, const char *strategy,
float confidence) {
java_emit_resolved_orig(ctx, callee_qn, NULL, strategy, confidence);
}
-static void java_emit_unresolved(JavaLSPContext *ctx, const char *expr_text, const char *reason) {
+static void java_emit_resolved_reference(JavaLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence) {
+ java_emit_resolved_orig_kind(ctx, callee_qn, NULL, strategy, confidence,
+ CBM_RESOLVED_CALL_REFERENCE);
+}
+
+static void java_stamp_resolved_site(JavaLSPContext *ctx, int first, TSNode site) {
+ if (!ctx->resolved_calls || ts_node_is_null(site) || first < 0) {
+ return;
+ }
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].site_start_byte = ts_node_start_byte(site);
+ ctx->resolved_calls->items[i].site_end_byte = ts_node_end_byte(site);
+ }
+}
+
+static void java_emit_resolved_reference_at(JavaLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence, TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ java_emit_resolved_reference(ctx, callee_qn, strategy, confidence);
+ java_stamp_resolved_site(ctx, first, site);
+}
+
+static void java_emit_unresolved_kind(JavaLSPContext *ctx, const char *expr_text,
+ const char *reason, CBMResolvedKind kind) {
if (!ctx->resolved_calls || !ctx->enclosing_method_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_method_qn;
rc.callee_qn = expr_text ? expr_text : "?";
rc.strategy = "lsp_unresolved";
rc.confidence = 0.0f;
rc.reason = reason;
+ rc.kind = kind;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+static void java_emit_unresolved(JavaLSPContext *ctx, const char *expr_text, const char *reason) {
+ java_emit_unresolved_kind(ctx, expr_text, reason, CBM_RESOLVED_INVOCATION);
+}
+
+static void java_emit_unresolved_reference(JavaLSPContext *ctx, const char *expr_text,
+ const char *reason) {
+ java_emit_unresolved_kind(ctx, expr_text, reason, CBM_RESOLVED_CALL_REFERENCE);
+}
+
+static void java_emit_unresolved_reference_at(JavaLSPContext *ctx, const char *expr_text,
+ const char *reason, TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ java_emit_unresolved_reference(ctx, expr_text, reason);
+ java_stamp_resolved_site(ctx, first, site);
+}
+
/* Find a sole concrete in-project implementer of interface `iface_qn` that
* declares method `mname`. Returns the implementer's QN when exactly ONE
* exists (else NULL), and sets *out_count to the number found (capped at 2,
@@ -2590,8 +2655,9 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
/* Try the last named child first; if it's the same as the LHS (only one
* named child total), we have a constructor ref where `new` is unnamed. */
char *mname = NULL;
+ TSNode name_node = {0};
if (nc_named >= 2) {
- TSNode name_node = ts_node_named_child(mref, nc_named - 1);
+ name_node = ts_node_named_child(mref, nc_named - 1);
mname = java_node_text(ctx, name_node);
}
if (!mname || !mname[0]) {
@@ -2603,6 +2669,10 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
const char *ck = ts_node_type(c);
if (strcmp(ck, "new") == 0) {
mname = "new";
+ /* Usage extraction represents `Type::new` by its type leaf,
+ * because `new` is an unnamed grammar token. Keep the LSP
+ * occurrence on that same leaf so the two passes join. */
+ name_node = lhs;
break;
}
if (strcmp(ck, "identifier") == 0) {
@@ -2610,8 +2680,10 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
if (ts_node_eq(c, lhs))
continue;
mname = java_node_text(ctx, c);
- if (mname && mname[0])
+ if (mname && mname[0]) {
+ name_node = c;
break;
+ }
}
}
}
@@ -2667,7 +2739,7 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
type_qn = lhs_t->data.template_type.template_name;
}
if (!type_qn) {
- java_emit_unresolved(ctx, mname, "method_reference_unknown_lhs");
+ java_emit_unresolved_reference_at(ctx, mname, "method_reference_unknown_lhs", name_node);
return;
}
@@ -2677,15 +2749,17 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
short_name = short_name ? short_name + 1 : type_qn;
const CBMRegisteredFunc *cf =
cbm_registry_lookup_method(ctx->registry, type_qn, short_name);
- // A `ClassName::new` reference constructs ClassName: resolve to the
- // ClassName CLASS node (which the textual extractor stored), not the
- // synthetic constructor QN that has no graph node. orig=mname ("new")
- // lets the join match the textual `new` call site (the constructor
- // reference is extracted as a call to `new`). cf distinguishes an
- // indexed constructor (higher confidence) from a synthesized one.
- java_emit_resolved_orig(ctx, type_qn, mname,
- cf ? "lsp_method_ref_ctor" : "lsp_method_ref_ctor_synth",
- cf ? 0.90f : 0.80f);
+ /* A constructor reference is precise only when a concrete constructor
+ * callable exists in the registry. Never relabel the class node itself
+ * as a callable target; if the constructor is absent/unmaterialized,
+ * the usage pass will retain the type occurrence as ordinary USAGE. */
+ if (cf && cf->qualified_name) {
+ java_emit_resolved_reference_at(ctx, cf->qualified_name, "lsp_method_ref_ctor", 0.90f,
+ name_node);
+ } else {
+ java_emit_unresolved_reference_at(
+ ctx, type_qn, "method_reference_constructor_not_materialized", name_node);
+ }
return;
}
@@ -2704,10 +2778,11 @@ static void resolve_method_reference(JavaLSPContext *ctx, TSNode mref,
if (!m)
m = java_lookup_method(ctx, type_qn, mname, 0);
if (m) {
- java_emit_resolved(ctx, m->qualified_name, "lsp_method_ref", 0.90f);
+ java_emit_resolved_reference_at(ctx, m->qualified_name, "lsp_method_ref", 0.90f, name_node);
} else {
- java_emit_unresolved(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, mname),
- "method_reference_no_match");
+ java_emit_unresolved_reference_at(ctx,
+ cbm_arena_sprintf(ctx->arena, "%s.%s", type_qn, mname),
+ "method_reference_no_match", name_node);
}
}
@@ -2825,7 +2900,13 @@ static void java_resolve_calls_in_node_inner(JavaLSPContext *ctx, TSNode node) {
}
if (strcmp(kind, "method_invocation") == 0) {
+ int first_resolution = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
resolve_method_call(ctx, node);
+ /* Raw CALL extraction records the full method_invocation span. Stamp
+ * the semantic record with that identical occurrence so two calls to
+ * the same method name in one caller retain receiver identity at the
+ * pipeline join (for example alpha.handle(); beta.handle();). */
+ java_stamp_resolved_site(ctx, first_resolution, node);
/* Lambda / method-reference args: re-walk with the SAM-bound scope.
* This is the central piece that turns chained streams + forEach
@@ -2859,6 +2940,7 @@ static void java_resolve_calls_in_node_inner(JavaLSPContext *ctx, TSNode node) {
}
} else if (strcmp(kind, "object_creation_expression") == 0) {
/* Resolve constructor as a method. */
+ int first_resolution = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
TSNode type_node = ts_node_child_by_field_name(node, "type", 4);
if (!ts_node_is_null(type_node)) {
const CBMType *t = java_parse_type_node(ctx, type_node);
@@ -2889,6 +2971,7 @@ static void java_resolve_calls_in_node_inner(JavaLSPContext *ctx, TSNode node) {
}
}
}
+ java_stamp_resolved_site(ctx, first_resolution, node);
}
/* catch_clause: push a fresh scope so the bound exception variable is
@@ -3095,6 +3178,19 @@ static const CBMType *parse_param_text(CBMArena *a, const char *text, const char
return parse_param_text_full(a, text, NULL, module_qn, NULL);
}
+typedef struct {
+ const char *parent_class;
+ const char *module_qn;
+ const CBMTypeRegistry *registry;
+} JavaSignatureParseContext;
+
+static const CBMType *java_signature_parse_type(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const JavaSignatureParseContext *ctx = (const JavaSignatureParseContext *)parser_ctx;
+ return parse_param_text_full(arena, text, ctx ? ctx->parent_class : NULL,
+ ctx ? ctx->module_qn : NULL, ctx ? ctx->registry : NULL);
+}
+
static void register_local_func_or_type_from_file(JavaLSPContext *ctx, CBMTypeRegistry *reg,
CBMFileResult *result) {
CBMArena *a = ctx->arena;
@@ -3259,17 +3355,35 @@ static void register_local_func_or_type_from_file(JavaLSPContext *ctx, CBMTypeRe
* not "test.Main.Box". */
const char *parent = d->parent_class;
const CBMType **ptypes = NULL;
- if (d->param_types) {
- int pc = 0;
- while (d->param_types[pc])
- pc++;
- if (pc > 0) {
- ptypes = (const CBMType **)cbm_arena_alloc(a, (size_t)(pc + 1) * sizeof(*ptypes));
- for (int j = 0; j < pc; j++) {
- ptypes[j] = parse_param_text_full(a, d->param_types[j], parent, module_qn, reg);
+ const char **param_names = NULL;
+ if (d->signature_param_types || d->signature_param_count > 0) {
+ JavaSignatureParseContext parse_ctx = {
+ .parent_class = parent,
+ .module_qn = module_qn,
+ .registry = reg,
+ };
+ ptypes = cbm_type_materialize_signature_params(a, d->signature_param_types,
+ d->signature_param_count,
+ java_signature_parse_type, &parse_ctx);
+ } else if (!d->signature_param_types && d->signature_param_count == 0) {
+ /* Compatibility for callers that still construct CBMDefinition by
+ * hand. The legacy projection is deduplicated/non-positional, so
+ * it is consulted only when the counted carrier is wholly absent. */
+ if (d->param_types) {
+ int pc = 0;
+ while (d->param_types[pc])
+ pc++;
+ if (pc > 0) {
+ ptypes =
+ (const CBMType **)cbm_arena_alloc(a, (size_t)(pc + 1) * sizeof(*ptypes));
+ for (int j = 0; j < pc; j++) {
+ ptypes[j] =
+ parse_param_text_full(a, d->param_types[j], parent, module_qn, reg);
+ }
+ ptypes[pc] = NULL;
}
- ptypes[pc] = NULL;
}
+ param_names = d->param_names;
}
/* Build return types — single return only in Java. */
const CBMType **rtypes = NULL;
@@ -3282,7 +3396,7 @@ static void register_local_func_or_type_from_file(JavaLSPContext *ctx, CBMTypeRe
rtypes[0] = parse_param_text_full(a, d->return_types[0], parent, module_qn, reg);
rtypes[1] = NULL;
}
- rf.signature = cbm_type_func(a, d->param_names, ptypes, rtypes);
+ rf.signature = cbm_type_func(a, param_names, ptypes, rtypes);
if (d->parent_class) {
rf.receiver_type = d->parent_class;
}
@@ -3316,29 +3430,17 @@ static void patch_one_method(JavaLSPContext *ctx, CBMTypeRegistry *reg, TSNode m
return;
char *method_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mname);
- /* Find the registered func by exact QN. */
- CBMRegisteredFunc *slot = NULL;
- for (int fi = 0; fi < reg->func_count; fi++) {
- if (reg->funcs[fi].qualified_name &&
- strcmp(reg->funcs[fi].qualified_name, method_qn) == 0) {
- slot = &reg->funcs[fi];
- break;
- }
- }
- if (!slot)
- return;
-
/* Re-extract param types from the AST. */
TSNode params = ts_node_child_by_field_name(method_node, "parameters", 10);
if (ts_node_is_null(params))
return;
uint32_t pn = ts_node_named_child_count(params);
- if (pn == 0)
- return;
- const CBMType **ptypes =
- (const CBMType **)cbm_arena_alloc(ctx->arena, (size_t)(pn + 1) * sizeof(*ptypes));
- if (!ptypes)
- return;
+ const CBMType **ptypes = NULL;
+ if (pn > 0) {
+ ptypes = (const CBMType **)cbm_arena_alloc(ctx->arena, (size_t)(pn + 1) * sizeof(*ptypes));
+ if (!ptypes)
+ return;
+ }
int idx = 0;
for (uint32_t i = 0; i < pn; i++) {
TSNode p = ts_node_named_child(params, i);
@@ -3355,7 +3457,37 @@ static void patch_one_method(JavaLSPContext *ctx, CBMTypeRegistry *reg, TSNode m
}
ptypes[idx++] = pt;
}
- ptypes[idx] = NULL;
+ if (ptypes)
+ ptypes[idx] = NULL;
+
+ /* Java overloads share a graph QN. Select the registry slot whose counted
+ * signature has the same arity as this AST declaration; falling back to the
+ * first QN match keeps the legacy no-signature path best-effort. */
+ CBMRegisteredFunc *slot = NULL;
+ CBMRegisteredFunc *first_qn_match = NULL;
+ for (int fi = 0; fi < reg->func_count; fi++) {
+ CBMRegisteredFunc *candidate = &reg->funcs[fi];
+ if (!candidate->qualified_name || strcmp(candidate->qualified_name, method_qn) != 0)
+ continue;
+ if (!first_qn_match)
+ first_qn_match = candidate;
+ if (!candidate->signature || candidate->signature->kind != CBM_TYPE_FUNC)
+ continue;
+ int candidate_arity = 0;
+ const CBMType *const *candidate_params = candidate->signature->data.func.param_types;
+ if (candidate_params) {
+ while (candidate_params[candidate_arity])
+ candidate_arity++;
+ }
+ if (candidate_arity == idx) {
+ slot = candidate;
+ break;
+ }
+ }
+ if (!slot)
+ slot = first_qn_match;
+ if (!slot)
+ return;
/* Re-extract return type from AST (only for methods, not constructors). */
const CBMType **rtypes = NULL;
@@ -3401,7 +3533,7 @@ static void patch_method_signatures_from_ast(JavaLSPContext *ctx, CBMTypeRegistr
class_qn = cbm_arena_strdup(ctx->arena, cname);
}
- TSNode body = ts_node_child_by_field_name(class_node, "body", 4);
+ TSNode body = java_type_declaration_body(class_node);
if (ts_node_is_null(body))
return;
@@ -3495,7 +3627,7 @@ static void populate_class_fields_from_ast(JavaLSPContext *ctx, CBMTypeRegistry
class_qn = cbm_arena_strdup(ctx->arena, cname);
}
- TSNode body = ts_node_child_by_field_name(class_node, "body", 4);
+ TSNode body = java_type_declaration_body(class_node);
if (ts_node_is_null(body))
return;
/* Snapshot enclosing-class stack so java_parse_type_node sees inner-class
@@ -3595,20 +3727,10 @@ void cbm_run_java_lsp(CBMArena *arena, CBMFileResult *result, const char *source
/* ── Cross-file LSP ───────────────────────────────────────────────── */
-void cbm_run_java_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)
- return;
-
- CBMTypeRegistry reg;
- cbm_registry_init(&reg, arena);
- cbm_java_stdlib_register(&reg, arena);
-
- /* Register cross-file defs. */
+void cbm_java_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const CBMLSPDef *defs,
+ int def_count) {
for (int i = 0; i < def_count; i++) {
- CBMLSPDef *d = &defs[i];
+ const CBMLSPDef *d = &defs[i];
if (!d->qualified_name || !d->short_name || !d->label)
continue;
if (strcmp(d->label, "Class") == 0 || strcmp(d->label, "Interface") == 0 ||
@@ -3642,7 +3764,7 @@ void cbm_run_java_lsp_cross(CBMArena *arena, const char *source, int source_len,
emb[idx] = NULL;
rt.embedded_types = emb;
}
- cbm_registry_add_type(&reg, rt);
+ cbm_registry_add_type(reg, rt);
} else if (strcmp(d->label, "Method") == 0 || strcmp(d->label, "Function") == 0 ||
strcmp(d->label, "Constructor") == 0) {
CBMRegisteredFunc rf;
@@ -3651,6 +3773,14 @@ void cbm_run_java_lsp_cross(CBMArena *arena, const char *source, int source_len,
rf.short_name = d->short_name;
rf.min_params = -1;
rf.receiver_type = d->receiver_type;
+ JavaSignatureParseContext parse_ctx = {
+ .parent_class = d->receiver_type,
+ .module_qn = d->def_module_qn,
+ .registry = reg,
+ };
+ const CBMType **ptypes = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ java_signature_parse_type, &parse_ctx);
/* Build single-return signature from return_types text. */
const CBMType *ret = NULL;
if (d->return_types && d->return_types[0]) {
@@ -3670,10 +3800,25 @@ void cbm_run_java_lsp_cross(CBMArena *arena, const char *source, int source_len,
rtypes[0] = ret;
rtypes[1] = NULL;
}
- rf.signature = cbm_type_func(arena, NULL, NULL, rtypes);
- cbm_registry_add_func(&reg, rf);
+ rf.signature = cbm_type_func(arena, NULL, ptypes, rtypes);
+ cbm_registry_add_func(reg, rf);
}
}
+}
+
+void cbm_run_java_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)
+ return;
+
+ CBMTypeRegistry reg;
+ cbm_registry_init(&reg, arena);
+ cbm_java_stdlib_register(&reg, arena);
+
+ /* Register cross-file defs. */
+ cbm_java_register_lsp_defs(arena, &reg, defs, def_count);
/* Build the hash indexes: without this every lookup_type/func/method in
* the walk below is a LINEAR scan over the whole cross registry —
diff --git a/internal/cbm/lsp/java_lsp.h b/internal/cbm/lsp/java_lsp.h
index f8b149494..fd1a16c75 100644
--- a/internal/cbm/lsp/java_lsp.h
+++ b/internal/cbm/lsp/java_lsp.h
@@ -139,6 +139,9 @@ void cbm_run_java_lsp(CBMArena *arena, CBMFileResult *result, const char *source
/* Cross-file LSP: build registry from defs + stdlib, re-parse if needed,
* walk and resolve. defs include both local + cross-file definitions. */
+void cbm_java_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const CBMLSPDef *defs,
+ int def_count);
+
void cbm_run_java_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,
diff --git a/internal/cbm/lsp/kotlin_lsp.c b/internal/cbm/lsp/kotlin_lsp.c
index dea241459..e67659005 100644
--- a/internal/cbm/lsp/kotlin_lsp.c
+++ b/internal/cbm/lsp/kotlin_lsp.c
@@ -87,6 +87,8 @@ static void kt_register_class_members(KotlinLSPContext *ctx, const char *class_q
bool is_object);
static const CBMType *kt_eval_call_expression_type(KotlinLSPContext *ctx, TSNode node);
static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx, TSNode node);
+static const CBMType *kt_eval_navigation_expression_type_at(KotlinLSPContext *ctx, TSNode node,
+ TSNode site);
static const CBMType *kt_eval_user_type(KotlinLSPContext *ctx, TSNode node);
static void kt_process_block_stmts(KotlinLSPContext *ctx, TSNode block);
static void kt_bind_function_params(KotlinLSPContext *ctx, TSNode func_node);
@@ -151,6 +153,104 @@ static bool kt_node_kind_in(TSNode n, const char *const *kinds) {
return false;
}
+static bool kt_direct_unnamed_token(TSNode node, const char *token) {
+ uint32_t count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode child = ts_node_child(node, i);
+ if (!ts_node_is_named(child) && strcmp(ts_node_type(child), token) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static const char *kt_binary_operator_method(TSNode node) {
+ if (kt_direct_unnamed_token(node, "===") || kt_direct_unnamed_token(node, "!==")) {
+ return NULL;
+ }
+ if (kt_direct_unnamed_token(node, "==") || kt_direct_unnamed_token(node, "!=")) {
+ return "equals";
+ }
+ if (kt_direct_unnamed_token(node, "..<"))
+ return "rangeUntil";
+ if (kt_direct_unnamed_token(node, ".."))
+ return "rangeTo";
+ if (kt_direct_unnamed_token(node, "<=") || kt_direct_unnamed_token(node, ">=") ||
+ kt_direct_unnamed_token(node, "<") || kt_direct_unnamed_token(node, ">")) {
+ return "compareTo";
+ }
+ if (kt_direct_unnamed_token(node, "+"))
+ return "plus";
+ if (kt_direct_unnamed_token(node, "-"))
+ return "minus";
+ if (kt_direct_unnamed_token(node, "*"))
+ return "times";
+ if (kt_direct_unnamed_token(node, "/"))
+ return "div";
+ if (kt_direct_unnamed_token(node, "%"))
+ return "rem";
+ return NULL;
+}
+
+static const char *kt_unary_operator_method(TSNode node, const char *kind) {
+ if (strcmp(kind, "postfix_expression") == 0) {
+ if (kt_direct_unnamed_token(node, "++"))
+ return "inc";
+ if (kt_direct_unnamed_token(node, "--"))
+ return "dec";
+ return NULL;
+ }
+ if (kt_direct_unnamed_token(node, "++"))
+ return "inc";
+ if (kt_direct_unnamed_token(node, "--"))
+ return "dec";
+ if (kt_direct_unnamed_token(node, "!"))
+ return "not";
+ if (kt_direct_unnamed_token(node, "-"))
+ return "unaryMinus";
+ if (kt_direct_unnamed_token(node, "+"))
+ return "unaryPlus";
+ return NULL;
+}
+
+static bool kt_node_contains(TSNode outer, TSNode inner) {
+ return !ts_node_is_null(outer) && !ts_node_is_null(inner) &&
+ ts_node_start_byte(outer) <= ts_node_start_byte(inner) &&
+ ts_node_end_byte(outer) >= ts_node_end_byte(inner);
+}
+
+static bool kt_node_is_update(TSNode node) {
+ const char *kind = ts_node_type(node);
+ return (strcmp(kind, "prefix_expression") == 0 || strcmp(kind, "postfix_expression") == 0 ||
+ strcmp(kind, "unary_expression") == 0) &&
+ (kt_direct_unnamed_token(node, "++") || kt_direct_unnamed_token(node, "--"));
+}
+
+static bool kt_index_is_write_lhs(TSNode index) {
+ for (TSNode parent = ts_node_parent(index); !ts_node_is_null(parent);
+ parent = ts_node_parent(parent)) {
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "assignment") == 0) {
+ TSNode lhs = kt_field_named(parent, "left");
+ if (ts_node_is_null(lhs) && ts_node_named_child_count(parent) > 0) {
+ lhs = ts_node_named_child(parent, 0);
+ }
+ return kt_node_contains(lhs, index);
+ }
+ if (kt_node_is_update(parent)) {
+ return kt_node_contains(parent, index);
+ }
+ if (strcmp(kind, "parenthesized_expression") != 0 &&
+ strcmp(kind, "directly_assignable_expression") != 0 &&
+ strcmp(kind, "assignable_expression") != 0 &&
+ strcmp(kind, "parenthesized_directly_assignable_expression") != 0 &&
+ strcmp(kind, "expression") != 0) {
+ break;
+ }
+ }
+ return false;
+}
+
static TSNode kt_child_kind(TSNode parent, const char *kind) {
if (ts_node_is_null(parent)) {
return parent;
@@ -280,9 +380,9 @@ static const CBMType *kt_unwrap_nullable(const CBMType *t) {
return t;
}
-/* Append a CBMResolvedCall to the output array. */
-static void kt_emit_resolved(KotlinLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
+/* Append a typed resolution result to the output array. */
+static void kt_emit_resolved_kind(KotlinLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence, CBMResolvedKind kind) {
if (ctx->debug) {
fprintf(stderr, "[kotlin_lsp] EMIT %s -> %s [%s %.2f] (resolved_calls=%p enc=%s)\n",
ctx->enclosing_func_qn ? ctx->enclosing_func_qn : "(null)",
@@ -317,9 +417,312 @@ static void kt_emit_resolved(KotlinLSPContext *ctx, const char *callee_qn, const
rc->callee_qn = cbm_arena_strdup(ctx->arena, callee_qn);
rc->strategy = strategy;
rc->confidence = confidence;
+ rc->kind = kind;
arr->count++;
}
+static void kt_stamp_resolved_site(KotlinLSPContext *ctx, int first, TSNode site) {
+ if (!ctx->resolved_calls || ts_node_is_null(site) || first < 0) {
+ return;
+ }
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].site_start_byte = ts_node_start_byte(site);
+ ctx->resolved_calls->items[i].site_end_byte = ts_node_end_byte(site);
+ }
+}
+
+static void kt_emit_resolved_kind_at(KotlinLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence, CBMResolvedKind kind,
+ TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ kt_emit_resolved_kind(ctx, callee_qn, strategy, confidence, kind);
+ kt_stamp_resolved_site(ctx, first, site);
+}
+
+static void kt_emit_resolved_reference_at(KotlinLSPContext *ctx, const char *callee_qn,
+ const char *strategy, const char *reason,
+ float confidence, TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ kt_emit_resolved_kind(ctx, callee_qn, strategy, confidence, CBM_RESOLVED_CALL_REFERENCE);
+ kt_stamp_resolved_site(ctx, first, site);
+ if (!ctx->resolved_calls || !reason || first < 0)
+ return;
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].reason = cbm_arena_strdup(ctx->arena, reason);
+ }
+}
+
+static void kt_emit_resolved_invocation_reason_at(KotlinLSPContext *ctx, const char *callee_qn,
+ const char *strategy, const char *reason,
+ float confidence, TSNode site) {
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ kt_emit_resolved_kind(ctx, callee_qn, strategy, confidence, CBM_RESOLVED_INVOCATION);
+ kt_stamp_resolved_site(ctx, first, site);
+ if (!ctx->resolved_calls || !reason || first < 0)
+ return;
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].reason = cbm_arena_strdup(ctx->arena, reason);
+ }
+}
+
+static void kt_emit_resolved_at(KotlinLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site) {
+ kt_emit_resolved_kind_at(ctx, callee_qn, strategy, confidence, CBM_RESOLVED_INVOCATION, site);
+}
+
+static const CBMScope *kt_scope_declaring_name(const CBMScope *scope, const char *name) {
+ if (!name)
+ return NULL;
+ for (const CBMScope *current = scope; current; current = current->parent) {
+ for (const CBMScopeChunk *chunk = current->chunks; chunk; chunk = chunk->next) {
+ for (int i = 0; i < chunk->used; i++) {
+ if (chunk->bindings[i].name && strcmp(chunk->bindings[i].name, name) == 0) {
+ return current;
+ }
+ }
+ }
+ }
+ return NULL;
+}
+
+static const CBMKotlinDelegateBinding *kt_find_delegate_binding(const KotlinLSPContext *ctx,
+ const CBMScope *scope,
+ const char *owner_qn,
+ const char *name) {
+ if (!ctx || !name)
+ return NULL;
+ for (int i = ctx->delegate_count - 1; i >= 0; i--) {
+ const CBMKotlinDelegateBinding *binding = &ctx->delegate_bindings[i];
+ if (!binding->name || strcmp(binding->name, name) != 0)
+ continue;
+ if (scope) {
+ if (binding->scope == scope)
+ return binding;
+ } else if (owner_qn && binding->owner_qn && strcmp(binding->owner_qn, owner_qn) == 0) {
+ return binding;
+ }
+ }
+ return NULL;
+}
+
+static void kt_record_delegate_binding(KotlinLSPContext *ctx, const CBMScope *scope,
+ const char *owner_qn, const char *name,
+ const char *getter_qn, const char *setter_qn) {
+ if (!ctx || !name || (!getter_qn && !setter_qn))
+ return;
+ for (int i = 0; i < ctx->delegate_count; i++) {
+ CBMKotlinDelegateBinding *existing = &ctx->delegate_bindings[i];
+ if (existing->scope == scope &&
+ ((!existing->owner_qn && !owner_qn) ||
+ (existing->owner_qn && owner_qn && strcmp(existing->owner_qn, owner_qn) == 0)) &&
+ existing->name && strcmp(existing->name, name) == 0) {
+ existing->getter_qn = getter_qn;
+ existing->setter_qn = setter_qn;
+ return;
+ }
+ }
+ if (ctx->delegate_count >= ctx->delegate_cap) {
+ int new_cap = ctx->delegate_cap == 0 ? 8 : ctx->delegate_cap * 2;
+ CBMKotlinDelegateBinding *grown = (CBMKotlinDelegateBinding *)cbm_arena_alloc(
+ ctx->arena, (size_t)new_cap * sizeof(*grown));
+ if (!grown)
+ return;
+ if (ctx->delegate_bindings && ctx->delegate_count > 0) {
+ memcpy(grown, ctx->delegate_bindings, (size_t)ctx->delegate_count * sizeof(*grown));
+ }
+ ctx->delegate_bindings = grown;
+ ctx->delegate_cap = new_cap;
+ }
+ CBMKotlinDelegateBinding *binding = &ctx->delegate_bindings[ctx->delegate_count++];
+ memset(binding, 0, sizeof(*binding));
+ binding->scope = scope;
+ binding->owner_qn = owner_qn ? cbm_arena_strdup(ctx->arena, owner_qn) : NULL;
+ binding->name = cbm_arena_strdup(ctx->arena, name);
+ binding->getter_qn = getter_qn ? cbm_arena_strdup(ctx->arena, getter_qn) : NULL;
+ binding->setter_qn = setter_qn ? cbm_arena_strdup(ctx->arena, setter_qn) : NULL;
+}
+
+static void kt_clear_lexical_delegate_binding(KotlinLSPContext *ctx, const CBMScope *scope,
+ const char *name) {
+ if (!ctx || !scope || !name)
+ return;
+ for (int i = ctx->delegate_count - 1; i >= 0; i--) {
+ CBMKotlinDelegateBinding *binding = &ctx->delegate_bindings[i];
+ if (binding->scope == scope && !binding->owner_qn && binding->name &&
+ strcmp(binding->name, name) == 0) {
+ /* Keep the frame/name tombstone so lookup cannot fall through to
+ * copied member metadata. A later delegated declaration in this
+ * exact frame may replace it through kt_record_delegate_binding. */
+ binding->getter_qn = NULL;
+ binding->setter_qn = NULL;
+ return;
+ }
+ }
+}
+
+static void kt_inject_delegate_call(KotlinLSPContext *ctx, const char *callee_qn, TSNode site) {
+ if (!ctx || !ctx->synthetic_calls || !ctx->enclosing_func_qn || !callee_qn ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ const char *dot = strrchr(callee_qn, '.');
+ const char *short_name = dot ? dot + 1 : callee_qn;
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ if (!short_name[0] || end <= start)
+ return;
+ for (int i = 0; i < ctx->synthetic_calls->count; i++) {
+ const CBMCall *existing = &ctx->synthetic_calls->items[i];
+ if (existing->requires_lsp_resolution && existing->callee_name &&
+ existing->enclosing_func_qn && strcmp(existing->callee_name, short_name) == 0 &&
+ strcmp(existing->enclosing_func_qn, ctx->enclosing_func_qn) == 0 &&
+ existing->site_start_byte == start && existing->site_end_byte == end) {
+ return;
+ }
+ }
+ CBMCall call = {0};
+ call.callee_name = cbm_arena_strdup(ctx->arena, short_name);
+ call.enclosing_func_qn = ctx->enclosing_func_qn;
+ call.start_line = (int)ts_node_start_point(site).row + 1;
+ call.site_start_byte = start;
+ call.site_end_byte = end;
+ call.requires_lsp_resolution = true;
+ cbm_calls_push(ctx->synthetic_calls, ctx->arena, call);
+}
+
+static void kt_retarget_callable_carrier(KotlinLSPContext *ctx, TSNode site,
+ const char *source_name, const char *target_qn) {
+ if (!ctx || !ctx->synthetic_calls || ts_node_is_null(site) || !source_name || !target_qn ||
+ !ctx->enclosing_func_qn) {
+ return;
+ }
+ const char *target_name = kt_short(target_qn);
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ int line = (int)ts_node_start_point(site).row + 1;
+ const char *caller_leaf = kt_short(ctx->enclosing_func_qn);
+ for (int i = 0; i < ctx->synthetic_calls->count; i++) {
+ CBMCall *call = &ctx->synthetic_calls->items[i];
+ if (!call->callee_name || !call->enclosing_func_qn ||
+ strcmp(call->callee_name, source_name) != 0) {
+ continue;
+ }
+ const char *call_caller_leaf = kt_short(call->enclosing_func_qn);
+ if (strcmp(call->enclosing_func_qn, ctx->enclosing_func_qn) != 0 &&
+ (!caller_leaf || !call_caller_leaf || strcmp(call_caller_leaf, caller_leaf) != 0)) {
+ continue;
+ }
+ bool overlaps = call->site_end_byte > call->site_start_byte &&
+ call->site_start_byte < end && call->site_end_byte > start;
+ if (!overlaps && call->start_line != line)
+ continue;
+ call->callee_name = cbm_arena_strdup(ctx->arena, target_name);
+ call->requires_lsp_resolution = true;
+ }
+}
+
+static void kt_emit_delegate_target(KotlinLSPContext *ctx, const char *callee_qn, TSNode site) {
+ if (!ctx || !callee_qn || ts_node_is_null(site))
+ return;
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ for (int i = 0; ctx->resolved_calls && i < ctx->resolved_calls->count; i++) {
+ const CBMResolvedCall *existing = &ctx->resolved_calls->items[i];
+ if (existing->kind == CBM_RESOLVED_INVOCATION && existing->caller_qn &&
+ existing->callee_qn && ctx->enclosing_func_qn &&
+ strcmp(existing->caller_qn, ctx->enclosing_func_qn) == 0 &&
+ strcmp(existing->callee_qn, callee_qn) == 0 && existing->site_start_byte == start &&
+ existing->site_end_byte == end) {
+ kt_inject_delegate_call(ctx, callee_qn, site);
+ return;
+ }
+ }
+ kt_emit_resolved_at(ctx, callee_qn, "lsp_kt_delegate_access", KT_CONF_METHOD, site);
+ kt_inject_delegate_call(ctx, callee_qn, site);
+}
+
+enum {
+ KT_DELEGATE_READ = 1,
+ KT_DELEGATE_WRITE = 2,
+};
+
+static int kt_delegate_access_mode(KotlinLSPContext *ctx, TSNode expression) {
+ TSNode child = expression;
+ for (int depth = 0; depth < 4; depth++) {
+ TSNode parent = ts_node_parent(child);
+ if (ts_node_is_null(parent))
+ break;
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "assignment") == 0) {
+ uint32_t nc = ts_node_named_child_count(parent);
+ if (nc < 2)
+ return KT_DELEGATE_WRITE;
+ TSNode lhs = ts_node_named_child(parent, 0);
+ TSNode rhs = ts_node_named_child(parent, nc - 1);
+ uint32_t start = ts_node_start_byte(expression);
+ if (start < ts_node_start_byte(lhs) || start >= ts_node_end_byte(lhs)) {
+ return KT_DELEGATE_READ;
+ }
+ uint32_t lhs_end = ts_node_end_byte(lhs);
+ uint32_t rhs_start = ts_node_start_byte(rhs);
+ if (ctx && rhs_start > lhs_end && rhs_start <= (uint32_t)ctx->source_len) {
+ const char *between = ctx->source + lhs_end;
+ size_t length = (size_t)(rhs_start - lhs_end);
+ if (cbm_memmem(between, length, "+=", 2) || cbm_memmem(between, length, "-=", 2) ||
+ cbm_memmem(between, length, "*=", 2) || cbm_memmem(between, length, "/=", 2) ||
+ cbm_memmem(between, length, "%=", 2)) {
+ return KT_DELEGATE_READ | KT_DELEGATE_WRITE;
+ }
+ }
+ return KT_DELEGATE_WRITE;
+ }
+ if (strcmp(kind, "postfix_expression") == 0 || strcmp(kind, "prefix_expression") == 0) {
+ if (kt_direct_unnamed_token(parent, "++") || kt_direct_unnamed_token(parent, "--")) {
+ return KT_DELEGATE_READ | KT_DELEGATE_WRITE;
+ }
+ }
+ if (strcmp(kind, "navigation_expression") != 0 &&
+ strcmp(kind, "parenthesized_expression") != 0 &&
+ strcmp(kind, "directly_assignable_expression") != 0 &&
+ strcmp(kind, "assignable_expression") != 0 &&
+ strcmp(kind, "parenthesized_directly_assignable_expression") != 0 &&
+ strcmp(kind, "expression") != 0) {
+ break;
+ }
+ child = parent;
+ }
+ return KT_DELEGATE_READ;
+}
+
+static void kt_emit_delegate_access(KotlinLSPContext *ctx, const char *name, const char *owner_qn,
+ TSNode expression, TSNode site) {
+ if (!ctx || !name)
+ return;
+ const CBMKotlinDelegateBinding *binding = NULL;
+ if (owner_qn) {
+ binding = kt_find_delegate_binding(ctx, NULL, owner_qn, name);
+ } else {
+ const CBMScope *scope = kt_scope_declaring_name(ctx->current_scope, name);
+ if (scope) {
+ binding = kt_find_delegate_binding(ctx, scope, NULL, name);
+ /* An ordinary nearer binding shadows any class/top-level delegate. */
+ if (!binding)
+ return;
+ } else if (ctx->enclosing_class_qn) {
+ binding = kt_find_delegate_binding(ctx, NULL, ctx->enclosing_class_qn, name);
+ }
+ }
+ if (!binding)
+ return;
+ int mode = kt_delegate_access_mode(ctx, expression);
+ if ((mode & KT_DELEGATE_READ) && binding->getter_qn) {
+ kt_emit_delegate_target(ctx, binding->getter_qn, site);
+ }
+ if ((mode & KT_DELEGATE_WRITE) && binding->setter_qn) {
+ kt_emit_delegate_target(ctx, binding->setter_qn, site);
+ }
+}
+
/* Detect a function_declaration's extension receiver type. The
* tree-sitter Kotlin grammar inlines the rule `_receiver_type` (a hidden
* rule starting with '_'), so the receiver doesn't appear as a named
@@ -415,33 +818,60 @@ static TSNode kt_find_return_type(TSNode func_node) {
return null_node;
}
-/* Build a CBM_TYPE_FUNC signature carrying just the return type, so that
- * cbm_registry_lookup_method's caller can read rf->signature->return_types
- * to determine the chained receiver. param_names/param_types are left
- * empty — we only care about the return type for chain tracking. */
-static const CBMType *kt_build_func_sig_with_return(KotlinLSPContext *ctx,
- const CBMType *return_type) {
- if (!return_type || cbm_type_is_unknown(return_type)) {
+/* Materialize one positional type per explicit value parameter. Extension
+ * receivers live outside function_value_parameters and are therefore excluded. */
+static const CBMType **kt_signature_param_types_from_ast(KotlinLSPContext *ctx, TSNode func_node) {
+ TSNode params = kt_field_named(func_node, "parameters");
+ if (ts_node_is_null(params))
+ params = kt_child_kind(func_node, "function_value_parameters");
+ if (ts_node_is_null(params))
return NULL;
- }
- const char **empty_pn = (const char **)cbm_arena_alloc(ctx->arena, sizeof(const char *));
- if (!empty_pn) {
+
+ uint32_t nc = ts_node_named_child_count(params);
+ if (nc == 0)
return NULL;
- }
- empty_pn[0] = NULL;
- const CBMType **empty_pt =
- (const CBMType **)cbm_arena_alloc(ctx->arena, sizeof(const CBMType *));
- if (!empty_pt) {
+ const CBMType **types =
+ (const CBMType **)cbm_arena_alloc(ctx->arena, (size_t)(nc + 1) * sizeof(*types));
+ if (!types)
return NULL;
- }
- empty_pt[0] = NULL;
- const CBMType **rt = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
- if (!rt) {
+
+ int count = 0;
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode param = ts_node_named_child(params, i);
+ if (!kt_node_is(param, "parameter") && !kt_node_is(param, "class_parameter"))
+ continue;
+ TSNode type_node = kt_field_named(param, "type");
+ if (ts_node_is_null(type_node))
+ type_node = kt_child_kind(param, "type");
+ if (ts_node_is_null(type_node))
+ type_node = kt_child_kind(param, "nullable_type");
+ if (ts_node_is_null(type_node))
+ type_node = kt_child_kind(param, "user_type");
+ if (ts_node_is_null(type_node))
+ type_node = kt_child_kind(param, "function_type");
+ types[count++] = ts_node_is_null(type_node) ? cbm_type_unknown()
+ : kotlin_parse_type_node(ctx, type_node);
+ }
+ if (count == 0)
return NULL;
- }
- rt[0] = return_type;
- rt[1] = NULL;
- return cbm_type_func(ctx->arena, empty_pn, empty_pt, rt);
+ types[count] = NULL;
+ return types;
+}
+
+/* Build a FUNC with positional parameters and, when known, its return type.
+ * Ordered signatures deliberately do not carry parameter names. */
+static const CBMType *kt_build_func_sig_with_return(KotlinLSPContext *ctx,
+ const CBMType **param_types,
+ const CBMType *return_type) {
+ const CBMType **returns = NULL;
+ if (return_type && !cbm_type_is_unknown(return_type)) {
+ returns = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));
+ if (!returns)
+ return NULL;
+ returns[0] = return_type;
+ returns[1] = NULL;
+ }
+ return cbm_type_func(ctx->arena, NULL, param_types, returns);
}
/* ── public API ───────────────────────────────────────────────────── */
@@ -607,14 +1037,30 @@ const char *kotlin_resolve_function_name(KotlinLSPContext *ctx, const char *name
return cbm_arena_strdup(ctx->arena, name);
}
- /* Explicit function import */
+ /* Explicit function import. Import extraction carries use-kind UNKNOWN,
+ * and the project import map may carry the imported MODULE rather than the
+ * symbol itself. Prove that the candidate is a registered top-level
+ * function before accepting it; otherwise `import values.handler` where
+ * handler is a property would fabricate a callable target. */
for (int i = 0; i < ctx->import_count; i++) {
const char *local = ctx->import_locals[i];
if (local && strcmp(local, name) == 0 &&
(ctx->import_kinds[i] == CBM_KT_USE_FUNCTION ||
- ctx->import_kinds[i] == CBM_KT_USE_UNKNOWN ||
- ctx->import_kinds[i] == CBM_KT_USE_TYPE)) {
- return ctx->import_targets[i];
+ ctx->import_kinds[i] == CBM_KT_USE_UNKNOWN)) {
+ const char *target = ctx->import_targets[i];
+ const CBMRegisteredFunc *direct =
+ ctx->registry && target ? cbm_registry_lookup_func(ctx->registry, target) : NULL;
+ if (direct && !direct->receiver_type && direct->qualified_name) {
+ return direct->qualified_name;
+ }
+ if (ctx->registry && target) {
+ char *member = kt_join_dot(ctx->arena, target, name);
+ const CBMRegisteredFunc *from_module =
+ member ? cbm_registry_lookup_func(ctx->registry, member) : NULL;
+ if (from_module && !from_module->receiver_type && from_module->qualified_name) {
+ return from_module->qualified_name;
+ }
+ }
}
}
@@ -895,6 +1341,28 @@ const CBMRegisteredFunc *kotlin_lookup_method(KotlinLSPContext *ctx, const char
return NULL;
}
+/* Return the graph-facing QN of an explicitly declared constructor. Kotlin
+ * constructors are not inherited, so use direct registry lookups rather than
+ * kotlin_lookup_method's alias/super walk. The same-file registrar records a
+ * secondary constructor as `<init>`; the definition extractor materializes it
+ * under the class name so reference-site and graph target share the same leaf. */
+static const char *kt_materialized_constructor_qn(KotlinLSPContext *ctx, const char *class_qn) {
+ if (!ctx || !ctx->registry || !class_qn) {
+ return NULL;
+ }
+ const char *class_name = kt_short(class_qn);
+ if (!class_name || !class_name[0]) {
+ return NULL;
+ }
+ const CBMRegisteredFunc *named =
+ cbm_registry_lookup_method(ctx->registry, class_qn, class_name);
+ if (named && named->qualified_name) {
+ return named->qualified_name;
+ }
+ const CBMRegisteredFunc *init = cbm_registry_lookup_method(ctx->registry, class_qn, "<init>");
+ return init ? kt_join_dot(ctx->arena, class_qn, class_name) : NULL;
+}
+
const CBMType *kotlin_lookup_property_type(KotlinLSPContext *ctx, const char *class_qn,
const char *prop_name) {
if (!ctx || !class_qn || !prop_name || !ctx->registry) {
@@ -1486,12 +1954,14 @@ static void kt_register_class_members(KotlinLSPContext *ctx, const char *class_q
rf.short_name = fname;
rf.receiver_type = class_qn;
rf.min_params = 0;
+ const CBMType **param_types = kt_signature_param_types_from_ast(ctx, c);
+ const CBMType *return_type = NULL;
/* Capture return type for chain tracking. */
TSNode rt_node = kt_find_return_type(c);
if (!ts_node_is_null(rt_node)) {
- const CBMType *rt = kotlin_parse_type_node(ctx, rt_node);
- rf.signature = kt_build_func_sig_with_return(ctx, rt);
+ return_type = kotlin_parse_type_node(ctx, rt_node);
}
+ rf.signature = kt_build_func_sig_with_return(ctx, param_types, return_type);
/* DSL receiver detection: scan the function's parameters for
* a function_type node whose first child is a `user_type`
* (the receiver, as in `Foo.() -> Unit`). Stash the receiver
@@ -1577,6 +2047,8 @@ static void kt_register_class_members(KotlinLSPContext *ctx, const char *class_q
rf.short_name = "<init>";
rf.receiver_type = class_qn;
rf.min_params = 0;
+ rf.signature =
+ kt_build_func_sig_with_return(ctx, kt_signature_param_types_from_ast(ctx, c), NULL);
cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);
} else if (strcmp(kind, "enum_entry") == 0) {
/* Enum entry — register a "field" of the enum class */
@@ -1629,12 +2101,14 @@ static void kt_process_function_decl(KotlinLSPContext *ctx, TSNode node) {
} else {
rf.qualified_name = kt_join_dot(ctx->arena, ctx->package_qn, fname);
}
+ const CBMType **param_types = kt_signature_param_types_from_ast(ctx, node);
+ const CBMType *return_type = NULL;
/* Capture return type for chain tracking. */
TSNode rt_node = kt_find_return_type(node);
if (!ts_node_is_null(rt_node)) {
- const CBMType *rt = kotlin_parse_type_node(ctx, rt_node);
- rf.signature = kt_build_func_sig_with_return(ctx, rt);
+ return_type = kotlin_parse_type_node(ctx, rt_node);
}
+ rf.signature = kt_build_func_sig_with_return(ctx, param_types, return_type);
cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);
}
@@ -1824,6 +2298,149 @@ static const CBMType *kt_eval_literal_type(KotlinLSPContext *ctx, TSNode node) {
return cbm_type_unknown();
}
+static bool kt_callable_reference_has_ambiguous_parent(TSNode node) {
+ TSNode child = node;
+ for (int depth = 0; depth < 8; depth++) {
+ TSNode parent = ts_node_parent(child);
+ if (ts_node_is_null(parent))
+ return false;
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "if_expression") == 0 || strcmp(kind, "when_expression") == 0 ||
+ strcmp(kind, "elvis_expression") == 0) {
+ return true;
+ }
+ /* Stop once the reference is the whole value at a precision-bearing
+ * boundary. A direct property initializer or call argument is exact;
+ * nested branch/map/operator expressions are not. */
+ if (strcmp(kind, "property_declaration") == 0 || strcmp(kind, "value_argument") == 0 ||
+ strcmp(kind, "call_expression") == 0 || strcmp(kind, "return_expression") == 0) {
+ return false;
+ }
+ if (strcmp(kind, "binary_expression") == 0 || strcmp(kind, "additive_expression") == 0 ||
+ strcmp(kind, "multiplicative_expression") == 0) {
+ return true;
+ }
+ child = parent;
+ }
+ return false;
+}
+
+static bool kt_identifier_is_value_occurrence(TSNode node) {
+ TSNode parent = ts_node_parent(node);
+ if (ts_node_is_null(parent))
+ return false;
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "variable_declaration") == 0 || strcmp(kind, "parameter") == 0 ||
+ strcmp(kind, "class_parameter") == 0 || strcmp(kind, "function_declaration") == 0 ||
+ strcmp(kind, "class_declaration") == 0 || strcmp(kind, "object_declaration") == 0 ||
+ strcmp(kind, "import") == 0 || strcmp(kind, "import_header") == 0 ||
+ strcmp(kind, "package_header") == 0 || strcmp(kind, "user_type") == 0 ||
+ strcmp(kind, "callable_reference") == 0) {
+ return false;
+ }
+ if (strcmp(kind, "navigation_expression") == 0) {
+ return ts_node_named_child_count(parent) > 0 &&
+ ts_node_eq(node, ts_node_named_child(parent, 0));
+ }
+ if (strcmp(kind, "call_expression") == 0) {
+ return ts_node_named_child_count(parent) == 0 ||
+ !ts_node_eq(node, ts_node_named_child(parent, 0));
+ }
+ return true;
+}
+
+static bool kt_identifier_is_direct_argument(TSNode node) {
+ TSNode child = node;
+ for (int depth = 0; depth < 5; depth++) {
+ TSNode parent = ts_node_parent(child);
+ if (ts_node_is_null(parent))
+ return false;
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "value_argument") == 0) {
+ return ts_node_named_child_count(parent) == 1 &&
+ ts_node_eq(child, ts_node_named_child(parent, 0));
+ }
+ if (strcmp(kind, "value_arguments") == 0) {
+ /* Older grammar revisions put a bare expression directly under
+ * the argument list. Reaching that list without traversing a
+ * member/operator node still proves a direct value occurrence. */
+ return true;
+ }
+ if (strcmp(kind, "expression") != 0 && strcmp(kind, "primary_expression") != 0 &&
+ strcmp(kind, "parenthesized_expression") != 0 &&
+ strcmp(kind, "annotated_expression") != 0) {
+ return false;
+ }
+ if (ts_node_named_child_count(parent) != 1 ||
+ !ts_node_eq(child, ts_node_named_child(parent, 0))) {
+ return false;
+ }
+ child = parent;
+ }
+ return false;
+}
+
+/* Pure target lookup used by lexical alias binding. It accepts only direct,
+ * unambiguous references whose receiver identity is statically proven:
+ * receiverless `::name`, a registered type `Type::member`, or a lexically
+ * typed value `instance::member`. More complex receiver expressions stay
+ * ordinary usages. */
+static const char *kt_exact_callable_reference_target(KotlinLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return NULL;
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "expression") == 0 || strcmp(kind, "primary_expression") == 0 ||
+ strcmp(kind, "parenthesized_expression") == 0 ||
+ strcmp(kind, "annotated_expression") == 0) {
+ return ts_node_named_child_count(node) == 1
+ ? kt_exact_callable_reference_target(ctx, ts_node_named_child(node, 0))
+ : NULL;
+ }
+ if (strcmp(kind, "callable_reference") != 0 ||
+ kt_callable_reference_has_ambiguous_parent(node)) {
+ return NULL;
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ if (count == 0 || count > 2)
+ return NULL;
+ TSNode member_node = ts_node_named_child(node, count - 1);
+ char *member = kt_node_text(ctx, member_node);
+ if (!member)
+ return NULL;
+
+ if (count == 2) {
+ TSNode receiver_node = ts_node_named_child(node, 0);
+ char *receiver_name = kt_node_text(ctx, receiver_node);
+ if (!receiver_name || !receiver_name[0])
+ return NULL;
+
+ const char *receiver_qn = NULL;
+ if (cbm_scope_contains(ctx->current_scope, receiver_name)) {
+ const CBMType *receiver_type = cbm_scope_lookup(ctx->current_scope, receiver_name);
+ receiver_qn = kt_type_qn_of(receiver_type);
+ } else {
+ const char *candidate = kotlin_resolve_class_name(ctx, receiver_name);
+ if (candidate && ctx->registry && cbm_registry_lookup_type(ctx->registry, candidate)) {
+ receiver_qn = candidate;
+ }
+ }
+ if (!receiver_qn)
+ return NULL;
+ const CBMRegisteredFunc *method = kotlin_lookup_method(ctx, receiver_qn, member);
+ return method ? method->qualified_name : NULL;
+ }
+
+ if (cbm_scope_contains(ctx->current_scope, member)) {
+ return cbm_scope_lookup_callable(ctx->current_scope, member);
+ }
+
+ const char *class_qn = kotlin_resolve_class_name(ctx, member);
+ if (class_qn && ctx->registry && cbm_registry_lookup_type(ctx->registry, class_qn)) {
+ return kt_materialized_constructor_qn(ctx, class_qn);
+ }
+ return kotlin_resolve_function_name(ctx, member);
+}
+
const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
if (ts_node_is_null(node) || !ctx) {
return cbm_type_unknown();
@@ -1869,7 +2486,13 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
}
/* Scope lookup */
const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
- if (!cbm_type_is_unknown(t)) {
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ const char *callable_qn = cbm_scope_lookup_callable(ctx->current_scope, name);
+ if (callable_qn && kt_identifier_is_direct_argument(node)) {
+ kt_emit_resolved_reference_at(ctx, callable_qn, "lsp_callable_value_reference",
+ name, KT_CONF_TOP_LEVEL, node);
+ }
+ kt_emit_delegate_access(ctx, name, NULL, node, node);
result = t;
goto out;
}
@@ -1930,71 +2553,17 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
rhs = ts_node_named_child(node, ts_node_named_child_count(node) - 1);
}
const CBMType *lhs_t = kotlin_eval_expr_type(ctx, lhs);
- /* The operator token is between named children; extract from
- * source range. */
- char *full = kt_node_text(ctx, node);
- const char *op_method = NULL;
- if (full) {
- /* Common operator → method mapping. We check the FIRST
- * occurrence of each token after the lhs end and before
- * the rhs start. As a simple heuristic we check the raw
- * source text for canonical operator strings; the order
- * matters to disambiguate `==` vs `=` and `..` vs `.`. */
- uint32_t lhs_end = ts_node_is_null(lhs) ? 0 : ts_node_end_byte(lhs);
- uint32_t rhs_start =
- ts_node_is_null(rhs) ? ts_node_end_byte(node) : ts_node_start_byte(rhs);
- uint32_t node_start = ts_node_start_byte(node);
- const char *between = ctx->source + lhs_end;
- int between_len = (int)(rhs_start - lhs_end);
- if (between_len > 0 && lhs_end > node_start) {
- /* Check operators in disambiguation order. */
- if (cbm_memmem(between, (size_t)between_len, "===", 3)) {
- op_method = NULL; /* identity, no method */
- } else if (cbm_memmem(between, (size_t)between_len, "!==", 3)) {
- op_method = NULL;
- } else if (cbm_memmem(between, (size_t)between_len, "==", 2)) {
- op_method = "equals";
- } else if (cbm_memmem(between, (size_t)between_len, "!=", 2)) {
- op_method = "equals";
- } else if (cbm_memmem(between, (size_t)between_len, "..<", 3)) {
- op_method = "rangeUntil";
- } else if (cbm_memmem(between, (size_t)between_len, "..", 2)) {
- op_method = "rangeTo";
- } else if (cbm_memmem(between, (size_t)between_len, "+=", 2)) {
- op_method = "plusAssign";
- } else if (cbm_memmem(between, (size_t)between_len, "-=", 2)) {
- op_method = "minusAssign";
- } else if (cbm_memmem(between, (size_t)between_len, "*=", 2)) {
- op_method = "timesAssign";
- } else if (cbm_memmem(between, (size_t)between_len, "/=", 2)) {
- op_method = "divAssign";
- } else if (cbm_memmem(between, (size_t)between_len, "%=", 2)) {
- op_method = "remAssign";
- } else if (cbm_memmem(between, (size_t)between_len, "<=", 2) ||
- cbm_memmem(between, (size_t)between_len, ">=", 2) ||
- cbm_memmem(between, (size_t)between_len, "<", 1) ||
- cbm_memmem(between, (size_t)between_len, ">", 1)) {
- op_method = "compareTo";
- } else if (cbm_memmem(between, (size_t)between_len, "+", 1)) {
- op_method = "plus";
- } else if (cbm_memmem(between, (size_t)between_len, "-", 1)) {
- op_method = "minus";
- } else if (cbm_memmem(between, (size_t)between_len, "*", 1)) {
- op_method = "times";
- } else if (cbm_memmem(between, (size_t)between_len, "/", 1)) {
- op_method = "div";
- } else if (cbm_memmem(between, (size_t)between_len, "%", 1)) {
- op_method = "rem";
- }
- }
- (void)node_start;
- }
+ /* Read only the direct unnamed operator token. Source slices between
+ * operands also contain comments and can accidentally name a different
+ * convention. Assignment operators intentionally remain fail-closed. */
+ const char *op_method = kt_binary_operator_method(node);
if (op_method && lhs_t && !cbm_type_is_unknown(lhs_t)) {
const char *lhs_qn = kt_type_qn_of(lhs_t);
if (lhs_qn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, lhs_qn, op_method);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD,
+ node);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types &&
rf->signature->data.func.return_types[0]) {
@@ -2016,37 +2585,16 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
* Newer tree-sitter-kotlin uses prefix_expression/postfix_expression. */
uint32_t nc = ts_node_named_child_count(node);
if (nc > 0) {
- TSNode operand = ts_node_named_child(node, nc - 1);
+ TSNode operand = ts_node_named_child(node, 0);
const CBMType *t = kotlin_eval_expr_type(ctx, operand);
- char *full = kt_node_text(ctx, node);
- const char *op_method = NULL;
- if (full) {
- /* Look at chars before operand */
- uint32_t op_end = ts_node_start_byte(operand);
- uint32_t node_start = ts_node_start_byte(node);
- if (op_end > node_start) {
- const char *prefix = ctx->source + node_start;
- int prefix_len = (int)(op_end - node_start);
- if (cbm_memmem(prefix, (size_t)prefix_len, "++", 2)) {
- op_method = "inc";
- } else if (cbm_memmem(prefix, (size_t)prefix_len, "--", 2)) {
- op_method = "dec";
- } else if (cbm_memmem(prefix, (size_t)prefix_len, "!", 1)) {
- op_method = "not";
- } else if (cbm_memmem(prefix, (size_t)prefix_len, "-", 1)) {
- op_method = "unaryMinus";
- } else if (cbm_memmem(prefix, (size_t)prefix_len, "+", 1)) {
- op_method = "unaryPlus";
- }
- }
- }
+ const char *op_method = kt_unary_operator_method(node, kind);
if (op_method && t && !cbm_type_is_unknown(t)) {
const char *qn = kt_type_qn_of(t);
if (qn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, qn, op_method);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator",
- KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_operator",
+ KT_CONF_METHOD, node);
}
}
}
@@ -2058,9 +2606,9 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
/* `a in b` desugars to `b.contains(a)`; `a is T` is a Boolean type
* check (no method). Newer tree-sitter-kotlin emits both as
* `check_expression`; disambiguate via the operator token. */
- char *ntext = kt_node_text(ctx, node);
bool is_membership =
- ntext && (cbm_memmem(ntext, strlen(ntext), " in ", 4) || strstr(ntext, "!in") != NULL);
+ (kt_direct_unnamed_token(node, "in") || kt_direct_unnamed_token(node, "!in")) &&
+ !kt_direct_unnamed_token(node, "is");
uint32_t nc = ts_node_named_child_count(node);
if (is_membership && nc >= 2) {
TSNode container = ts_node_named_child(node, nc - 1);
@@ -2069,7 +2617,8 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
if (cqn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, cqn, "contains");
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD,
+ node);
}
}
}
@@ -2078,6 +2627,12 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
}
if (strcmp(kind, "index_expression") == 0 || strcmp(kind, "indexing_expression") == 0) {
/* `a[i]` desugars to `a.get(i)`. */
+ if (kt_index_is_write_lhs(node)) {
+ /* A write/update requires set or compound-set semantics. Do not
+ * emit a misleading read-side get row while those are unproved. */
+ result = cbm_type_unknown();
+ goto out;
+ }
uint32_t nc = ts_node_named_child_count(node);
if (nc >= 1) {
TSNode recv = ts_node_named_child(node, 0);
@@ -2086,7 +2641,8 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
if (rqn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, rqn, "get");
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_operator", KT_CONF_METHOD,
+ node);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types &&
rf->signature->data.func.return_types[0]) {
@@ -2100,6 +2656,12 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
goto out;
}
if (strcmp(kind, "callable_reference") == 0) {
+ if (kt_callable_reference_has_ambiguous_parent(node)) {
+ /* Each branch mention remains an ordinary parser USAGE. Promoting
+ * one branch would falsely claim the expression selects one target. */
+ result = cbm_type_unknown();
+ goto out;
+ }
/* Callable references take three shapes:
* `::topLevelFn` — bound to receiverless top-level function
* `Foo::method` — bound class method or property
@@ -2112,24 +2674,49 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
* The grammar exposes the LHS (optional) and RHS via named
* children — typically two identifiers separated by `::`. */
uint32_t nc = ts_node_named_child_count(node);
+ if (ctx->debug) {
+ char *reference_text = kt_node_text(ctx, node);
+ fprintf(stderr, "[kotlin_lsp] callable_ref text=%s named_children=%u\n",
+ reference_text ? reference_text : "?", nc);
+ }
if (nc >= 1) {
TSNode last = ts_node_named_child(node, nc - 1);
char *member = kt_node_text(ctx, last);
if (member) {
if (nc >= 2) {
TSNode lhs = ts_node_named_child(node, 0);
- /* lhs may be a type or expression. Try type-resolve
- * first (for `Foo::method`), then expression eval
- * (for `obj::method`). */
+ /* lhs may be a type or expression. A textual class-name
+ * resolution has permissive fallbacks, so accept it as a
+ * type only when that type is actually registered. An
+ * unconfirmed lhs must be evaluated as an expression;
+ * otherwise `service::handler` can be misread as a class
+ * named `service`. */
char *lhs_text = kt_node_text(ctx, lhs);
const char *recv_qn = NULL;
if (lhs_text) {
- recv_qn = kotlin_resolve_class_name(ctx, lhs_text);
+ const char *candidate = kotlin_resolve_class_name(ctx, lhs_text);
+ if (candidate && ctx->registry &&
+ cbm_registry_lookup_type(ctx->registry, candidate)) {
+ recv_qn = candidate;
+ }
}
if (!recv_qn) {
- const CBMType *t = kotlin_eval_expr_type(ctx, lhs);
+ /* The grammar uses a type-shaped node for the LHS of
+ * both `Type::member` and `value::member`. For a bound
+ * value, consult the lexical scope by source name
+ * before evaluating the node as a type expression. */
+ const CBMType *t =
+ lhs_text ? cbm_scope_lookup(ctx->current_scope, lhs_text) : NULL;
+ if (!t || cbm_type_is_unknown(t)) {
+ t = kotlin_eval_expr_type(ctx, lhs);
+ }
recv_qn = kt_type_qn_of(t);
}
+ if (ctx->debug) {
+ fprintf(stderr,
+ "[kotlin_lsp] callable_ref member=%s receiver=%s source=%s\n",
+ member, recv_qn ? recv_qn : "?", lhs_text ? lhs_text : "?");
+ }
if (recv_qn) {
if (strcmp(member, "class") == 0) {
/* `Foo::class` produces KClass<Foo>. We track
@@ -2140,15 +2727,57 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
}
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, recv_qn, member);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_callable_ref",
- KT_CONF_METHOD);
+ kt_emit_resolved_kind_at(ctx, rf->qualified_name, "lsp_kt_callable_ref",
+ KT_CONF_METHOD, CBM_RESOLVED_CALL_REFERENCE,
+ last);
}
}
} else {
/* `::name` — bound to top-level fn or local. */
+ if (cbm_scope_contains(ctx->current_scope, member)) {
+ const CBMType *lexical = cbm_scope_lookup(ctx->current_scope, member);
+ const char *lexical_qn =
+ cbm_scope_lookup_callable(ctx->current_scope, member);
+ if (lexical_qn) {
+ kt_emit_resolved_kind_at(ctx, lexical_qn, "lsp_kt_callable_alias_ref",
+ KT_CONF_TOP_LEVEL, CBM_RESOLVED_CALL_REFERENCE,
+ last);
+ }
+ /* An ordinary nearer binding still shadows a top-level
+ * function, but cannot earn a precise reference edge. */
+ result = lexical;
+ goto out;
+ }
+
+ /* `::ClassName` is a constructor reference only when the
+ * source contains a concrete constructor declaration that
+ * the graph materializes. An implicit constructor remains
+ * an ordinary type usage. */
+ const char *class_qn = kotlin_resolve_class_name(ctx, member);
+ const CBMRegisteredType *class_type =
+ class_qn && ctx->registry
+ ? cbm_registry_lookup_type(ctx->registry, class_qn)
+ : NULL;
+ if (class_type) {
+ const char *constructor_qn = kt_materialized_constructor_qn(ctx, class_qn);
+ if (constructor_qn) {
+ kt_emit_resolved_kind_at(ctx, constructor_qn, "lsp_kt_constructor_ref",
+ KT_CONF_CONSTRUCTOR,
+ CBM_RESOLVED_CALL_REFERENCE, last);
+ }
+ result = cbm_type_unknown();
+ goto out;
+ }
+
const char *fn_qn = kotlin_resolve_function_name(ctx, member);
+ if (ctx->debug) {
+ fprintf(stderr, "[kotlin_lsp] callable_ref member=%s top_level=%s\n",
+ member, fn_qn ? fn_qn : "?");
+ }
if (fn_qn) {
- kt_emit_resolved(ctx, fn_qn, "lsp_kt_callable_ref", KT_CONF_TOP_LEVEL);
+ kt_emit_resolved_kind_at(ctx, fn_qn, "lsp_kt_callable_ref",
+ KT_CONF_TOP_LEVEL, CBM_RESOLVED_CALL_REFERENCE,
+ last);
}
}
}
@@ -2241,7 +2870,36 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
if (!callee_text) {
return cbm_type_unknown();
}
- /* 0. `this`-method dispatch: if we're inside a class method or DSL
+
+ /* 0. Lexical callable values shadow implicit receivers and top-level
+ * functions. Exact aliases dispatch to their carried target; an ordinary
+ * local binding fails closed instead of borrowing a same-named function. */
+ if (cbm_scope_contains(ctx->current_scope, callee_text)) {
+ const char *target = cbm_scope_lookup_callable(ctx->current_scope, callee_text);
+ const CBMType *bound = cbm_scope_lookup(ctx->current_scope, callee_text);
+ if (target) {
+ kt_emit_resolved_invocation_reason_at(ctx, target, "lsp_callable_alias", callee_text,
+ 0.98f, call_node);
+ kt_retarget_callable_carrier(ctx, call_node, callee_text, target);
+ const CBMRegisteredFunc *rf =
+ ctx->registry ? cbm_registry_lookup_func(ctx->registry, target) : NULL;
+ if (rf && rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
+ rf->signature->data.func.return_types && rf->signature->data.func.return_types[0]) {
+ return rf->signature->data.func.return_types[0];
+ }
+ }
+ if (bound && bound->kind == CBM_TYPE_CALLABLE) {
+ return bound->data.callable.return_type ? bound->data.callable.return_type
+ : cbm_type_unknown();
+ }
+ if (bound && bound->kind == CBM_TYPE_FUNC && bound->data.func.return_types &&
+ bound->data.func.return_types[0]) {
+ return bound->data.func.return_types[0];
+ }
+ return cbm_type_unknown();
+ }
+
+ /* 1. `this`-method dispatch: if we're inside a class method or DSL
* lambda, bare calls resolve against this_type's members first. This
* matches Kotlin's resolution order: implicit-receiver before global. */
if (ctx->this_type && !cbm_type_is_unknown(ctx->this_type)) {
@@ -2249,7 +2907,8 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
if (this_qn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, this_qn, callee_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS,
+ call_node);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types &&
rf->signature->data.func.return_types[0]) {
@@ -2260,7 +2919,7 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
}
}
- /* 1. Class? */
+ /* 2. Class? */
const char *cls_qn = kotlin_resolve_class_name(ctx, callee_text);
if (cls_qn && ctx->registry) {
const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, cls_qn);
@@ -2270,14 +2929,14 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
* node, and the textual call site's callee is the bare class name
* `Foo` (not `<init>`). Emitting cls_qn (not cls_qn.<init>) makes the
* pipeline join's callee bare-segment match AND resolves the target. */
- kt_emit_resolved(ctx, cls_qn, "lsp_kt_constructor", KT_CONF_CONSTRUCTOR);
+ kt_emit_resolved_at(ctx, cls_qn, "lsp_kt_constructor", KT_CONF_CONSTRUCTOR, call_node);
return cbm_type_named(ctx->arena, cls_qn);
}
}
- /* 2. Top-level fun */
+ /* 3. Top-level fun */
const char *fn_qn = kotlin_resolve_function_name(ctx, callee_text);
if (fn_qn) {
- kt_emit_resolved(ctx, fn_qn, "lsp_kt_top_level", KT_CONF_TOP_LEVEL);
+ kt_emit_resolved_at(ctx, fn_qn, "lsp_kt_top_level", KT_CONF_TOP_LEVEL, call_node);
if (ctx->registry) {
const CBMRegisteredFunc *rf = cbm_registry_lookup_func(ctx->registry, fn_qn);
if (rf && rf->signature && rf->signature->kind == CBM_TYPE_FUNC) {
@@ -2359,7 +3018,7 @@ static const CBMType *kt_eval_call_expression_type(KotlinLSPContext *ctx, TSNode
}
if (strcmp(kind, "navigation_expression") == 0) {
/* obj.method(...) — inner type evaluation handles emission */
- const CBMType *t = kt_eval_navigation_expression_type(ctx, callee);
+ const CBMType *t = kt_eval_navigation_expression_type_at(ctx, callee, node);
return t;
}
/* Could also be `call_expression` for chained calls like foo()(args) */
@@ -2388,6 +3047,11 @@ static TSNode kt_nav_member_node(TSNode nav) {
}
static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx, TSNode node) {
+ return kt_eval_navigation_expression_type_at(ctx, node, node);
+}
+
+static const CBMType *kt_eval_navigation_expression_type_at(KotlinLSPContext *ctx, TSNode node,
+ TSNode site) {
/* navigation_expression: <expr> ('.'|'?.'|'!!.') (simple_identifier | navigation_suffix) */
uint32_t nc = ts_node_named_child_count(node);
if (nc < 2) {
@@ -2406,7 +3070,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
const CBMRegisteredFunc *rf =
kotlin_lookup_method(ctx, ctx->enclosing_super_qn, member_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_super", KT_CONF_SUPER);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_super", KT_CONF_SUPER, site);
return cbm_type_unknown();
}
}
@@ -2419,7 +3083,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
const CBMRegisteredFunc *rf =
kotlin_lookup_method(ctx, ctx->enclosing_class_qn, member_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS, site);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types &&
rf->signature->data.func.return_types[0]) {
@@ -2428,6 +3092,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
return cbm_type_unknown();
}
/* Property access? */
+ kt_emit_delegate_access(ctx, member_text, ctx->enclosing_class_qn, node, selector);
const CBMType *pt =
kotlin_lookup_property_type(ctx, ctx->enclosing_class_qn, member_text);
if (!cbm_type_is_unknown(pt)) {
@@ -2472,7 +3137,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
strat = "lsp_kt_lambda_it";
}
}
- kt_emit_resolved(ctx, rf->qualified_name, strat, KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, strat, KT_CONF_METHOD, site);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types && rf->signature->data.func.return_types[0]) {
return rf->signature->data.func.return_types[0];
@@ -2489,7 +3154,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
char *companion_qn = kt_join_dot(ctx->arena, recv_qn, "Companion");
rf = kotlin_lookup_method(ctx, companion_qn, member_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_static", KT_CONF_STATIC);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_static", KT_CONF_STATIC, site);
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
rf->signature->data.func.return_types && rf->signature->data.func.return_types[0]) {
return rf->signature->data.func.return_types[0];
@@ -2498,6 +3163,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
}
/* Property */
+ kt_emit_delegate_access(ctx, member_text, recv_qn, node, selector);
const CBMType *pt = kotlin_lookup_property_type(ctx, recv_qn, member_text);
if (!cbm_type_is_unknown(pt)) {
return pt;
@@ -2507,7 +3173,8 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
* receiver_type == recv_qn and short_name == member_text. */
rf = cbm_registry_lookup_method(ctx->registry, recv_qn, member_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_extension", KT_CONF_EXTENSION);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_extension", KT_CONF_EXTENSION,
+ site);
return cbm_type_unknown();
}
}
@@ -2520,8 +3187,8 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
if (it_qn) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, it_qn, member_text);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_lambda_it",
- KT_CONF_LAMBDA_IT);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_lambda_it",
+ KT_CONF_LAMBDA_IT, site);
return cbm_type_unknown();
}
}
@@ -2546,7 +3213,7 @@ static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx,
}
if (is_any) {
char *q = kt_join_dot(ctx->arena, "kotlin.Any", member_text);
- kt_emit_resolved(ctx, q, "lsp_kt_any", KT_CONF_PARTIAL);
+ kt_emit_resolved_at(ctx, q, "lsp_kt_any", KT_CONF_PARTIAL, site);
}
}
@@ -2568,6 +3235,57 @@ static void kt_process_block_stmts(KotlinLSPContext *ctx, TSNode block) {
}
}
+static const char *kt_delegated_property_owner(KotlinLSPContext *ctx, TSNode prop) {
+ TSNode child = prop;
+ for (int depth = 0; depth < 12; depth++) {
+ TSNode parent = ts_node_parent(child);
+ if (ts_node_is_null(parent))
+ return NULL;
+ const char *kind = ts_node_type(parent);
+ if (strcmp(kind, "function_declaration") == 0 || strcmp(kind, "lambda_literal") == 0 ||
+ strcmp(kind, "anonymous_function") == 0) {
+ return NULL;
+ }
+ if (strcmp(kind, "class_body") == 0 || strcmp(kind, "enum_class_body") == 0) {
+ return ctx->enclosing_class_qn;
+ }
+ child = parent;
+ }
+ return NULL;
+}
+
+static void kt_register_property_delegate(KotlinLSPContext *ctx, TSNode prop,
+ const char *explicit_owner) {
+ TSNode delegate = kt_child_kind(prop, "property_delegate");
+ TSNode var = kt_child_kind(prop, "variable_declaration");
+ if (ts_node_is_null(delegate) || ts_node_is_null(var))
+ return;
+ TSNode id = kt_name_child(var);
+ if (ts_node_is_null(id))
+ id = kt_child_kind_named(var, "simple_identifier");
+ if (ts_node_is_null(id) || ts_node_named_child_count(delegate) == 0)
+ return;
+ char *name = kt_node_text(ctx, id);
+ if (!name)
+ return;
+
+ TSNode inner = ts_node_named_child(delegate, 0);
+ const CBMType *delegate_type = kotlin_eval_expr_type(ctx, inner);
+ const char *delegate_qn = kt_type_qn_of(delegate_type);
+ if (!delegate_qn)
+ return;
+ const CBMRegisteredFunc *getter = kotlin_lookup_method(ctx, delegate_qn, "getValue");
+ const CBMRegisteredFunc *setter = NULL;
+ char *property_text = kt_node_text(ctx, prop);
+ if (property_text && strstr(property_text, "var ")) {
+ setter = kotlin_lookup_method(ctx, delegate_qn, "setValue");
+ }
+ const char *owner = explicit_owner ? explicit_owner : kt_delegated_property_owner(ctx, prop);
+ const CBMScope *scope = owner ? NULL : ctx->current_scope;
+ kt_record_delegate_binding(ctx, scope, owner, name, getter ? getter->qualified_name : NULL,
+ setter ? setter->qualified_name : NULL);
+}
+
static void kt_bind_property_to_scope(KotlinLSPContext *ctx, TSNode prop) {
/* property_declaration: ('val'|'var') (variable_declaration | multi_variable_declaration)
* ('=' expr | property_delegate)?
@@ -2576,9 +3294,9 @@ static void kt_bind_property_to_scope(KotlinLSPContext *ctx, TSNode prop) {
* 1. `val x: T = expr` — single binding, optional type or initializer
* 2. `val (a, b) = expr` — destructuring; emits expr.component1(),
* expr.component2() per official LSP convention
- * 3. `val x by lazy { ... }` — property delegation; emits delegate.getValue()
- * (and delegate.setValue() for var) per the
- * KProperty contract.
+ * 3. `val x by lazy { ... }` — records the delegate operators; actual
+ * getValue/setValue calls are emitted only
+ * when x is read or written.
*/
/* Multi-variable destructuring */
TSNode multi = kt_child_kind(prop, "multi_variable_declaration");
@@ -2615,8 +3333,8 @@ static void kt_bind_property_to_scope(KotlinLSPContext *ctx, TSNode prop) {
snprintf(comp, sizeof(comp), "component%u", i + 1);
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, iqn, comp);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_destructure",
- KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_destructure",
+ KT_CONF_METHOD, prop);
}
}
/* Bind variable to unknown type for now. */
@@ -2657,59 +3375,135 @@ static void kt_bind_property_to_scope(KotlinLSPContext *ctx, TSNode prop) {
type_node = kt_child_kind(var, "nullable_type");
}
- /* Property delegation: `val x by Foo()` — emit getValue (and setValue
- * for var) on the delegate's type. */
+ /* Property delegation records the proven operators here, but does not emit
+ * declaration-time calls. getValue/setValue are emitted only at actual
+ * read/write occurrences below. */
TSNode delegate = kt_child_kind(prop, "property_delegate");
if (!ts_node_is_null(delegate)) {
- /* Find inner expression of the delegate. */
- uint32_t dnc = ts_node_named_child_count(delegate);
- if (dnc > 0) {
- TSNode inner = ts_node_named_child(delegate, 0);
- const CBMType *dt = kotlin_eval_expr_type(ctx, inner);
- if (dt && !cbm_type_is_unknown(dt)) {
- const char *dqn = kt_type_qn_of(dt);
- if (dqn) {
- const CBMRegisteredFunc *gv = kotlin_lookup_method(ctx, dqn, "getValue");
- if (gv && gv->qualified_name) {
- kt_emit_resolved(ctx, gv->qualified_name, "lsp_kt_delegate",
- KT_CONF_METHOD);
- }
- /* Detect var (mutable) by looking for `var` keyword in
- * the property's source range. */
- char *src_text = kt_node_text(ctx, prop);
- if (src_text && strstr(src_text, "var ")) {
- const CBMRegisteredFunc *sv = kotlin_lookup_method(ctx, dqn, "setValue");
- if (sv && sv->qualified_name) {
- kt_emit_resolved(ctx, sv->qualified_name, "lsp_kt_delegate",
- KT_CONF_METHOD);
- }
- }
- }
- }
- }
+ kt_register_property_delegate(ctx, prop, NULL);
+ } else {
+ /* Class delegate metadata is copied into a method's lexical frame so
+ * bare member reads work. An ordinary local declaration in that same
+ * frame shadows the member and must clear only that copied metadata. */
+ kt_clear_lexical_delegate_binding(ctx, ctx->current_scope, name);
}
+ TSNode initializer;
+ memset(&initializer, 0, sizeof(initializer));
const CBMType *t = cbm_type_unknown();
if (!ts_node_is_null(type_node)) {
t = kotlin_parse_type_node(ctx, type_node);
- } else {
- /* Scan named children of the property_declaration for an
- * initializer expression after the variable_declaration. */
- uint32_t nc = ts_node_named_child_count(prop);
- for (uint32_t i = 0; i < nc; i++) {
- TSNode c = ts_node_named_child(prop, i);
- const char *k = ts_node_type(c);
- if (strcmp(k, "variable_declaration") == 0 || strcmp(k, "modifiers") == 0 ||
- strcmp(k, "property_delegate") == 0) {
- continue;
- }
- t = kotlin_eval_expr_type(ctx, c);
- if (!cbm_type_is_unknown(t)) {
+ }
+ /* Grammar variants can expose wrapper/accessor children before the real
+ * initializer. Preserve the original first-known-type behavior instead of
+ * committing to the first non-declaration child. */
+ uint32_t nc = ts_node_named_child_count(prop);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode child = ts_node_named_child(prop, i);
+ const char *child_kind = ts_node_type(child);
+ if (strcmp(child_kind, "variable_declaration") == 0 ||
+ strcmp(child_kind, "modifiers") == 0 || strcmp(child_kind, "property_delegate") == 0) {
+ continue;
+ }
+ if (ts_node_is_null(initializer) || kt_exact_callable_reference_target(ctx, child)) {
+ initializer = child;
+ }
+ if (ts_node_is_null(type_node)) {
+ const CBMType *candidate = kotlin_eval_expr_type(ctx, child);
+ if (!cbm_type_is_unknown(candidate)) {
+ t = candidate;
break;
}
}
}
- cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t);
+ const char *callable_qn =
+ ts_node_is_null(initializer) ? NULL : kt_exact_callable_reference_target(ctx, initializer);
+ if (callable_qn) {
+ cbm_scope_bind_callable(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t,
+ callable_qn);
+ } else {
+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t);
+ }
+}
+
+static TSNode kt_bare_assignable_identifier(TSNode node) {
+ TSNode none;
+ memset(&none, 0, sizeof(none));
+ for (int depth = 0; depth < 5 && !ts_node_is_null(node); depth++) {
+ if (kt_node_is(node, "identifier") || kt_node_is(node, "simple_identifier")) {
+ return node;
+ }
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "directly_assignable_expression") != 0 &&
+ strcmp(kind, "assignable_expression") != 0 &&
+ strcmp(kind, "parenthesized_directly_assignable_expression") != 0 &&
+ strcmp(kind, "expression") != 0 && strcmp(kind, "primary_expression") != 0 &&
+ strcmp(kind, "parenthesized_expression") != 0) {
+ return none;
+ }
+ if (ts_node_named_child_count(node) != 1)
+ return none;
+ node = ts_node_named_child(node, 0);
+ }
+ return none;
+}
+
+static void kt_bind_assignment_to_scope(KotlinLSPContext *ctx, TSNode assignment) {
+ TSNode lhs = kt_field_named(assignment, "left");
+ TSNode rhs = kt_field_named(assignment, "right");
+ uint32_t nc = ts_node_named_child_count(assignment);
+ if (ts_node_is_null(lhs) && nc > 0)
+ lhs = ts_node_named_child(assignment, 0);
+ if (ts_node_is_null(rhs) && nc > 1)
+ rhs = ts_node_named_child(assignment, nc - 1);
+ lhs = kt_bare_assignable_identifier(lhs);
+ if (ts_node_is_null(lhs) || ts_node_is_null(rhs)) {
+ return;
+ }
+ char *name = kt_node_text(ctx, lhs);
+ if (!name || !cbm_scope_contains(ctx->current_scope, name))
+ return;
+
+ const char *callable_qn = kt_exact_callable_reference_target(ctx, rhs);
+ (void)kotlin_eval_expr_type(ctx, rhs);
+ if (callable_qn) {
+ cbm_scope_update_callable(ctx->current_scope, name, callable_qn);
+ } else {
+ /* Dynamic/branch reassignment invalidates an earlier exact alias. */
+ cbm_scope_update_callable(ctx->current_scope, name, NULL);
+ }
+}
+
+static void kt_invalidate_conditionally_assigned_aliases(KotlinLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return;
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "function_declaration") == 0 || strcmp(kind, "class_declaration") == 0 ||
+ strcmp(kind, "object_declaration") == 0 || strcmp(kind, "lambda_literal") == 0 ||
+ strcmp(kind, "anonymous_function") == 0) {
+ return;
+ }
+ if (strcmp(kind, "assignment") == 0) {
+ TSNode lhs = kt_field_named(node, "left");
+ if (ts_node_is_null(lhs) && ts_node_named_child_count(node) > 0) {
+ lhs = ts_node_named_child(node, 0);
+ }
+ lhs = kt_bare_assignable_identifier(lhs);
+ if (!ts_node_is_null(lhs)) {
+ char *name = kt_node_text(ctx, lhs);
+ if (name) {
+ /* The branch may or may not execute, so the post-merge value
+ * no longer proves either the old or assigned callable. Keep
+ * their occurrence-level references, but clear later alias use. */
+ cbm_scope_update_callable(ctx->current_scope, name, NULL);
+ }
+ }
+ return;
+ }
+ uint32_t nc = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ kt_invalidate_conditionally_assigned_aliases(ctx, ts_node_named_child(node, i));
+ }
}
/* Smart-cast inside `if (x is Foo)`. Detects pattern in stmt and binds
@@ -2791,6 +3585,7 @@ static void kt_process_if_expression(KotlinLSPContext *ctx, TSNode node) {
if (!ts_node_is_null(cond)) {
kt_resolve_calls_in_node(ctx, cond);
}
+ kt_invalidate_conditionally_assigned_aliases(ctx, node);
}
static void kt_process_when_expression(KotlinLSPContext *ctx, TSNode node) {
@@ -2848,6 +3643,7 @@ static void kt_process_when_expression(KotlinLSPContext *ctx, TSNode node) {
}
ctx->current_scope = cbm_scope_pop(ctx->current_scope);
}
+ kt_invalidate_conditionally_assigned_aliases(ctx, node);
(void)subject_type;
}
@@ -2881,7 +3677,8 @@ static void kt_process_for_statement(KotlinLSPContext *ctx, TSNode node) {
for (int i = 0; protocol[i]; i++) {
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, iqn, protocol[i]);
if (rf && rf->qualified_name) {
- kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_iterator", KT_CONF_METHOD);
+ kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_iterator", KT_CONF_METHOD,
+ node);
}
}
}
@@ -2914,6 +3711,7 @@ static void kt_process_for_statement(KotlinLSPContext *ctx, TSNode node) {
}
}
ctx->current_scope = cbm_scope_pop(ctx->current_scope);
+ kt_invalidate_conditionally_assigned_aliases(ctx, node);
}
static void kt_process_lambda(KotlinLSPContext *ctx, TSNode lambda, const CBMType *receiver_type) {
@@ -2980,6 +3778,14 @@ static void kt_process_call_with_lambda(KotlinLSPContext *ctx, TSNode call_node)
uint32_t nc = ts_node_named_child_count(call_node);
/* Resolve callee normally for emission */
(void)kt_eval_call_expression_type(ctx, call_node);
+ /* The outer call resolver does not evaluate value arguments. Walk every
+ * non-callee child so nested calls and callable references such as
+ * `accept(::handler)` receive their own occurrence-exact resolutions.
+ * Lambda nodes are deliberately skipped by the generic walker and are
+ * processed below with their receiver-aware scope. */
+ for (uint32_t i = 1; i < nc; i++) {
+ kt_resolve_calls_in_node(ctx, ts_node_named_child(call_node, i));
+ }
/* Find trailing lambda */
TSNode lambda;
memset(&lambda, 0, sizeof(lambda));
@@ -3078,8 +3884,9 @@ static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt) {
return;
}
if (strcmp(kind, "property_declaration") == 0) {
- kt_bind_property_to_scope(ctx, stmt);
- /* Resolve calls within initializer */
+ /* The generic walker binds the property before descending into its
+ * initializer. Calling the binder here as well evaluates callable
+ * reference initializers twice and emits duplicate resolutions. */
kt_resolve_calls_in_node(ctx, stmt);
return;
}
@@ -3108,6 +3915,12 @@ static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt) {
lrf.short_name = fname;
lrf.min_params = 0;
cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, lrf);
+ /* Preserve lexical shadowing independently of the registry aliases
+ * below. A local function is a callable value, but until local
+ * function definitions are materialized in the graph it cannot be
+ * an exact CALL_REFERENCE target. */
+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, fname),
+ cbm_type_callable(ctx->arena, NULL, 0, cbm_type_unknown()));
/* Also register a same-package alias so bare `inner()` calls
* succeed via the same-package fallback in
* kotlin_resolve_function_name. */
@@ -3157,10 +3970,12 @@ static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt) {
}
if (strcmp(kind, "while_statement") == 0 || strcmp(kind, "do_while_statement") == 0) {
kt_resolve_calls_in_node(ctx, stmt);
+ kt_invalidate_conditionally_assigned_aliases(ctx, stmt);
return;
}
if (strcmp(kind, "try_expression") == 0) {
kt_resolve_calls_in_node(ctx, stmt);
+ kt_invalidate_conditionally_assigned_aliases(ctx, stmt);
return;
}
if (strcmp(kind, "call_expression") == 0) {
@@ -3178,6 +3993,17 @@ static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt) {
return;
}
if (strcmp(kind, "assignment") == 0) {
+ TSNode lhs = kt_field_named(stmt, "left");
+ if (ts_node_is_null(lhs) && ts_node_named_child_count(stmt) > 0) {
+ lhs = ts_node_named_child(stmt, 0);
+ }
+ TSNode bare_lhs = kt_bare_assignable_identifier(lhs);
+ if (!ts_node_is_null(bare_lhs)) {
+ (void)kotlin_eval_expr_type(ctx, bare_lhs);
+ } else if (kt_node_is(lhs, "navigation_expression")) {
+ (void)kt_eval_navigation_expression_type(ctx, lhs);
+ }
+ kt_bind_assignment_to_scope(ctx, stmt);
kt_resolve_calls_in_node(ctx, stmt);
return;
}
@@ -3200,8 +4026,40 @@ static void kt_resolve_calls_in_node_inner(KotlinLSPContext *ctx, TSNode node) {
/* Skip — handled elsewhere */
return;
}
+ if (strcmp(kind, "callable_reference") == 0) {
+ /* Callable references used as arguments are not type-evaluated by the
+ * outer call resolver. Resolve the reference occurrence explicitly,
+ * but avoid duplicating one already emitted while binding a property
+ * initializer. */
+ bool already_resolved = false;
+ if (ctx->resolved_calls) {
+ TSNode site = node;
+ uint32_t named = ts_node_named_child_count(node);
+ if (named > 0) {
+ site = ts_node_named_child(node, named - 1);
+ }
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ for (int i = 0; i < ctx->resolved_calls->count; i++) {
+ const CBMResolvedCall *resolved = &ctx->resolved_calls->items[i];
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE &&
+ resolved->site_start_byte == start && resolved->site_end_byte == end) {
+ already_resolved = true;
+ break;
+ }
+ }
+ }
+ if (!already_resolved) {
+ (void)kotlin_eval_expr_type(ctx, node);
+ }
+ return;
+ }
if (strcmp(kind, "call_expression") == 0) {
kt_process_call_with_lambda(ctx, node);
+ /* The call handler already walks every non-callee child. Descending
+ * again here would visit its navigation-expression callee and emit a
+ * second semantic record for the same source occurrence. */
+ return;
} else if (strcmp(kind, "navigation_expression") == 0) {
kt_eval_navigation_expression_type(ctx, node);
} else if (strcmp(kind, "if_expression") == 0) {
@@ -3215,6 +4073,9 @@ static void kt_resolve_calls_in_node_inner(KotlinLSPContext *ctx, TSNode node) {
return;
} else if (strcmp(kind, "property_declaration") == 0) {
kt_bind_property_to_scope(ctx, node);
+ } else if ((strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0) &&
+ kt_identifier_is_value_occurrence(node)) {
+ (void)kotlin_eval_expr_type(ctx, node);
}
uint32_t nc = ts_node_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
@@ -3300,9 +4161,20 @@ static void kt_process_function_body(KotlinLSPContext *ctx, TSNode func_node, co
* method body resolve to the field's type. */
if (receiver_rt && receiver_rt->field_names && receiver_rt->field_types) {
for (int i = 0; receiver_rt->field_names[i]; i++) {
+ if (kt_scope_declaring_name(ctx->current_scope, receiver_rt->field_names[i]) ==
+ ctx->current_scope) {
+ continue; /* parameter/local binding shadows the member */
+ }
cbm_scope_bind(ctx->current_scope,
cbm_arena_strdup(ctx->arena, receiver_rt->field_names[i]),
receiver_rt->field_types[i]);
+ const CBMKotlinDelegateBinding *member_delegate =
+ kt_find_delegate_binding(ctx, NULL, receiver_class_qn, receiver_rt->field_names[i]);
+ if (member_delegate) {
+ kt_record_delegate_binding(ctx, ctx->current_scope, NULL,
+ receiver_rt->field_names[i], member_delegate->getter_qn,
+ member_delegate->setter_qn);
+ }
}
}
@@ -3396,6 +4268,14 @@ static void kt_walk_top_level_for_resolution(KotlinLSPContext *ctx, TSNode root,
fprintf(stderr, "[kotlin_lsp] walk_top_level enclosing=%s root_kind=%s nc=%u\n",
enclosing_class_qn ? enclosing_class_qn : "(top)", ts_node_type(root), nc);
}
+ /* Register delegated members before resolving any method bodies so source
+ * order cannot decide whether an earlier reader sees getValue/setValue. */
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode candidate = ts_node_named_child(root, i);
+ if (kt_node_is(candidate, "property_declaration")) {
+ kt_register_property_delegate(ctx, candidate, enclosing_class_qn);
+ }
+ }
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(root, i);
const char *kind = ts_node_type(c);
@@ -4133,6 +5013,7 @@ void cbm_run_kotlin_lsp(CBMArena *arena, CBMFileResult *result, const char *sour
KotlinLSPContext ctx;
kotlin_lsp_init(&ctx, arena, use_source, use_source_len, &registry, module_qn, module_qn,
project_name, /*rel_path=*/NULL, &result->resolved_calls);
+ ctx.synthetic_calls = &result->calls;
kotlin_lsp_process_file(&ctx, use_root);
@@ -4191,6 +5072,47 @@ static const char *kt_cross_builtin_return_qn(const char *name) {
return NULL;
}
+typedef struct {
+ const CBMLSPDef *def;
+} KotlinSignatureParseContext;
+
+static const CBMType *kt_signature_parse_type(CBMArena *arena, const char *text, void *parser_ctx) {
+ const KotlinSignatureParseContext *ctx = (const KotlinSignatureParseContext *)parser_ctx;
+ const CBMLSPDef *def = ctx ? ctx->def : NULL;
+ if (!text || !text[0])
+ return cbm_type_unknown();
+
+ char *clean = cbm_arena_strdup(arena, text);
+ if (!clean)
+ return cbm_type_unknown();
+ while (*clean && isspace((unsigned char)*clean))
+ clean++;
+ char *end = clean + strlen(clean);
+ while (end > clean && isspace((unsigned char)end[-1]))
+ *--end = '\0';
+ while (end > clean && end[-1] == '?')
+ *--end = '\0';
+ char *generic = strchr(clean, '<');
+ if (generic)
+ *generic = '\0';
+ if (!clean[0])
+ return cbm_type_unknown();
+
+ const char *qualified = kt_cross_builtin_return_qn(clean);
+ if (!qualified) {
+ if (strchr(clean, '.')) {
+ qualified = clean;
+ } else if (def && def->namespace_name && def->namespace_name[0]) {
+ qualified = kt_join_dot(arena, def->namespace_name, clean);
+ } else if (def && def->def_module_qn && def->def_module_qn[0]) {
+ qualified = kt_join_dot(arena, def->def_module_qn, clean);
+ } else {
+ qualified = clean;
+ }
+ }
+ return cbm_type_named(arena, qualified);
+}
+
static const CBMType *kt_cross_return_type(CBMArena *arena, const CBMLSPDef *d) {
if (!arena || !d || !d->return_types || !d->return_types[0]) {
return NULL;
@@ -4214,20 +5136,19 @@ static const CBMType *kt_cross_return_type(CBMArena *arena, const CBMLSPDef *d)
static const CBMType *kt_cross_func_sig_with_return(CBMArena *arena, const CBMLSPDef *d) {
const CBMType *ret = kt_cross_return_type(arena, d);
- if (!ret || cbm_type_is_unknown(ret)) {
- return NULL;
- }
- const char **empty_pn = (const char **)cbm_arena_alloc(arena, sizeof(*empty_pn));
- const CBMType **empty_pt = (const CBMType **)cbm_arena_alloc(arena, sizeof(*empty_pt));
- const CBMType **rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(*rets));
- if (!empty_pn || !empty_pt || !rets) {
- return NULL;
- }
- empty_pn[0] = NULL;
- empty_pt[0] = NULL;
- rets[0] = ret;
- rets[1] = NULL;
- return cbm_type_func(arena, empty_pn, empty_pt, rets);
+ KotlinSignatureParseContext parse_ctx = {.def = d};
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count, kt_signature_parse_type,
+ &parse_ctx);
+ const CBMType **rets = NULL;
+ if (ret && !cbm_type_is_unknown(ret)) {
+ rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(*rets));
+ if (!rets)
+ return NULL;
+ rets[0] = ret;
+ rets[1] = NULL;
+ }
+ return cbm_type_func(arena, NULL, param_types, rets);
}
static void kt_register_cross_def(CBMTypeRegistry *reg, CBMArena *arena, const CBMLSPDef *d) {
@@ -4284,6 +5205,13 @@ static void kt_register_cross_def(CBMTypeRegistry *reg, CBMArena *arena, const C
}
}
+void cbm_kotlin_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const CBMLSPDef *defs,
+ int def_count) {
+ for (int i = 0; i < def_count; i++) {
+ kt_register_cross_def(reg, arena, &defs[i]);
+ }
+}
+
void cbm_run_kotlin_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,
@@ -4297,9 +5225,7 @@ void cbm_run_kotlin_lsp_cross(CBMArena *arena, const char *source, int source_le
cbm_kotlin_stdlib_register(&reg, arena);
/* Register project-wide defs (local + cross-file) under their graph QNs. */
- for (int i = 0; i < def_count; i++) {
- kt_register_cross_def(&reg, arena, &defs[i]);
- }
+ cbm_kotlin_register_lsp_defs(arena, &reg, defs, def_count);
/* Build the hash indexes: without this every registry lookup in the walk
* is a LINEAR scan over the whole cross registry — O(lookups x defs) per
@@ -4345,8 +5271,11 @@ void cbm_run_kotlin_lsp_cross(CBMArena *arena, const char *source, int source_le
}
KotlinLSPContext ctx;
- kotlin_lsp_init(&ctx, arena, source, source_len, &reg, "", module_qn ? module_qn : "",
- project_name, /*rel_path=*/NULL, out);
+ /* Match the per-file pass: until a source package declaration overrides
+ * it, the path-derived module is the callable-QN prefix. This preserves
+ * exact caller identity for default-package functions across files. */
+ kotlin_lsp_init(&ctx, arena, source, source_len, &reg, module_qn ? module_qn : "",
+ module_qn ? module_qn : "", project_name, /*rel_path=*/NULL, out);
/* Apply caller-supplied imports (resolved IMPORTS edges). */
for (int i = 0; i < import_count; i++) {
diff --git a/internal/cbm/lsp/kotlin_lsp.h b/internal/cbm/lsp/kotlin_lsp.h
index f6471bebd..765088bee 100644
--- a/internal/cbm/lsp/kotlin_lsp.h
+++ b/internal/cbm/lsp/kotlin_lsp.h
@@ -65,6 +65,14 @@ typedef enum {
CBM_KT_USE_WILDCARD, /* import a.b.* — local_name is a.b prefix */
} CBMKotlinUseKind;
+typedef struct {
+ const CBMScope *scope; /* exact lexical declaration frame, NULL for members */
+ const char *owner_qn; /* class/object QN for a member, NULL for lexical values */
+ const char *name;
+ const char *getter_qn;
+ const char *setter_qn;
+} CBMKotlinDelegateBinding;
+
/* KotlinLSPContext — per-file state for Kotlin call resolution. */
typedef struct KotlinLSPContext {
CBMArena *arena;
@@ -107,6 +115,14 @@ typedef struct KotlinLSPContext {
/* Output: resolved calls accumulate here. */
CBMResolvedCallArray *resolved_calls;
+ /* Access-level delegated-property semantics. The declaration records the
+ * proven getValue/setValue targets; actual reads/writes inject exact call
+ * carriers and resolutions at their source occurrences. */
+ CBMCallArray *synthetic_calls;
+ CBMKotlinDelegateBinding *delegate_bindings;
+ int delegate_count;
+ int delegate_cap;
+
/* Recursion guard for kotlin_eval_expr_type. */
int eval_depth;
@@ -167,6 +183,9 @@ void cbm_run_kotlin_lsp(CBMArena *arena, CBMFileResult *result, const char *sour
* Mirrors cbm_run_java_lsp_cross. `defs` carries the graph QNs of every
* project definition so a bare top-level call in file B resolves to the
* definition node living in file A. Output is appended to `out`. */
+void cbm_kotlin_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, const CBMLSPDef *defs,
+ int def_count);
+
void cbm_run_kotlin_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,
diff --git a/internal/cbm/lsp/perl_lsp.c b/internal/cbm/lsp/perl_lsp.c
index ef1534445..6e8d70dea 100644
--- a/internal/cbm/lsp/perl_lsp.c
+++ b/internal/cbm/lsp/perl_lsp.c
@@ -85,7 +85,8 @@ static const CBMType *perl_eval_function_call_type(PerlLSPContext *ctx, TSNode n
static const CBMType *perl_eval_method_call_type(PerlLSPContext *ctx, TSNode node);
static const CBMType *perl_eval_new_type(PerlLSPContext *ctx, TSNode node);
static void perl_emit_resolved(PerlLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence);
+ float confidence, TSNode site);
+static void perl_resolve_direct_coderef_arguments(PerlLSPContext *ctx, TSNode call);
/* ── helpers ────────────────────────────────────────────────────── */
@@ -625,23 +626,168 @@ static const CBMType *perl_eval_method_call_type(PerlLSPContext *ctx, TSNode nod
/* ── emit ───────────────────────────────────────────────────────── */
static void perl_emit_resolved(PerlLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
+ float confidence, TSNode site) {
if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
rc.confidence = confidence;
rc.reason = NULL;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
+static void perl_emit_reference(PerlLSPContext *ctx, const char *callee_qn, TSNode site) {
+ if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = callee_qn;
+ rc.strategy = "perl_coderef";
+ rc.confidence = PERL_CONF_LITERAL;
+ rc.kind = CBM_RESOLVED_CALL_REFERENCE;
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+/* Accept only the exact coderef spelling represented by one direct
+ * refgen_expression. Conditional/list/map expressions are not examined, so
+ * their constituent \&names remain ordinary usages. */
+static char *perl_exact_coderef_name(PerlLSPContext *ctx, TSNode refgen) {
+ if (ts_node_is_null(refgen) || strcmp(ts_node_type(refgen), "refgen_expression") != 0)
+ return NULL;
+ char *text = perl_node_text(ctx, refgen);
+ if (!text)
+ return NULL;
+ const char *p = text;
+ while (isspace((unsigned char)*p))
+ p++;
+ if (p[0] != '\\' || p[1] != '&')
+ return NULL;
+ p += 2;
+ const char *start = p;
+ if (!(isalpha((unsigned char)*p) || *p == '_'))
+ return NULL;
+ while (isalnum((unsigned char)*p) || *p == '_' || *p == ':')
+ p++;
+ const char *end = p;
+ while (isspace((unsigned char)*p))
+ p++;
+ if (*p != '\0' || end == start)
+ return NULL;
+ return cbm_arena_strndup(ctx->arena, start, (size_t)(end - start));
+}
+
+static const CBMRegisteredFunc *perl_resolve_coderef_target(PerlLSPContext *ctx, char *name) {
+ if (!ctx || !name || !name[0])
+ return NULL;
+ char *colons = NULL;
+ for (char *p = strstr(name, "::"); p; p = strstr(p + 2, "::"))
+ colons = p;
+ if (colons) {
+ char *pkg = cbm_arena_strndup(ctx->arena, name, (size_t)(colons - name));
+ const char *short_name = colons + 2;
+ const CBMRegisteredFunc *f = perl_lookup_method(ctx, pkg, short_name);
+ return f ? f : cbm_registry_lookup_symbol(ctx->registry, pkg, short_name);
+ }
+ const char *import_qn = perl_find_import(ctx, name);
+ if (import_qn) {
+ const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, import_qn);
+ if (f)
+ return f;
+ }
+ return cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, name);
+}
+
+static void perl_resolve_one_coderef(PerlLSPContext *ctx, TSNode refgen) {
+ char *name = perl_exact_coderef_name(ctx, refgen);
+ const CBMRegisteredFunc *target = name ? perl_resolve_coderef_target(ctx, name) : NULL;
+ if (target && target->qualified_name)
+ perl_emit_reference(ctx, target->qualified_name, refgen);
+}
+
+static void perl_resolve_direct_coderef_arguments(PerlLSPContext *ctx, TSNode call) {
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(args))
+ return;
+ if (strcmp(ts_node_type(args), "refgen_expression") == 0) {
+ perl_resolve_one_coderef(ctx, args);
+ return;
+ }
+ /* Multiple arguments are exposed through a flat list_expression. Do not
+ * recurse into any other wrapper: in particular, a conditional argument
+ * may contain refgen descendants but does not select one exact target. */
+ if (strcmp(ts_node_type(args), "list_expression") != 0)
+ return;
+ uint32_t count = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode arg = ts_node_named_child(args, i);
+ if (strcmp(ts_node_type(arg), "refgen_expression") == 0)
+ perl_resolve_one_coderef(ctx, arg);
+ }
+}
+
+static bool perl_is_direct_coderef_argument(TSNode refgen) {
+ TSNode container = ts_node_parent(refgen);
+ if (ts_node_is_null(container))
+ return false;
+ if (strcmp(ts_node_type(container), "list_expression") != 0)
+ container = refgen;
+ TSNode call = ts_node_parent(container);
+ if (ts_node_is_null(call))
+ return false;
+ const char *kind = ts_node_type(call);
+ if (strcmp(kind, "function_call_expression") != 0 &&
+ strcmp(kind, "ambiguous_function_call_expression") != 0) {
+ return false;
+ }
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ return !ts_node_is_null(args) && ts_node_eq(args, container);
+}
+
+static void perl_emit_non_direct_coderef_usage(PerlLSPContext *ctx, TSNode refgen) {
+ if (!ctx || !ctx->usages || !ctx->enclosing_func_qn ||
+ perl_is_direct_coderef_argument(refgen)) {
+ return;
+ }
+ char *name = perl_exact_coderef_name(ctx, refgen);
+ if (!name)
+ return;
+ uint32_t start = ts_node_start_byte(refgen);
+ uint32_t end = ts_node_end_byte(refgen);
+ for (int i = 0; i < ctx->usages->count; i++) {
+ const CBMUsage *existing = &ctx->usages->items[i];
+ if (existing->kind == CBM_USAGE_VALUE && existing->ref_name &&
+ existing->enclosing_func_qn && strcmp(existing->ref_name, name) == 0 &&
+ strcmp(existing->enclosing_func_qn, ctx->enclosing_func_qn) == 0 &&
+ existing->site_start_byte == start && existing->site_end_byte == end) {
+ return;
+ }
+ }
+ CBMUsage usage = {0};
+ usage.ref_name = name;
+ usage.enclosing_func_qn = ctx->enclosing_func_qn;
+ usage.kind = CBM_USAGE_VALUE;
+ usage.site_start_byte = start;
+ usage.site_end_byte = end;
+ cbm_usages_push(ctx->usages, ctx->arena, usage);
+}
+
/* ── call/method dispatch (emit edges) ──────────────────────────── */
/* Resolve a function/static call and emit an edge if it lands on a registered
* sub. Bare func(), Exporter func(), and Package::func() static calls. */
static void perl_resolve_function_call(PerlLSPContext *ctx, TSNode call) {
+ perl_resolve_direct_coderef_arguments(ctx, call);
TSNode fn = ts_node_child_by_field_name(call, "function", 8);
if (ts_node_is_null(fn))
return;
@@ -669,7 +815,7 @@ static void perl_resolve_function_call(PerlLSPContext *ctx, TSNode call) {
if (!f)
f = cbm_registry_lookup_symbol(ctx->registry, pkg, shortn);
if (f) {
- perl_emit_resolved(ctx, f->qualified_name, "perl_static_call", PERL_CONF_LITERAL);
+ perl_emit_resolved(ctx, f->qualified_name, "perl_static_call", PERL_CONF_LITERAL, call);
return;
}
} else {
@@ -678,13 +824,14 @@ static void perl_resolve_function_call(PerlLSPContext *ctx, TSNode call) {
f = cbm_registry_lookup_func(ctx->registry, imp);
if (f) {
perl_emit_resolved(ctx, f->qualified_name, "perl_imported_function",
- PERL_CONF_LITERAL);
+ PERL_CONF_LITERAL, call);
return;
}
}
f = cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, name);
if (f) {
- perl_emit_resolved(ctx, f->qualified_name, "perl_function_local", PERL_CONF_LITERAL);
+ perl_emit_resolved(ctx, f->qualified_name, "perl_function_local", PERL_CONF_LITERAL,
+ call);
return;
}
}
@@ -718,7 +865,8 @@ static void perl_resolve_method_call(PerlLSPContext *ctx, TSNode call) {
return;
const CBMRegisteredFunc *sf = perl_lookup_method(ctx, parent_qn, super_method);
if (sf)
- perl_emit_resolved(ctx, sf->qualified_name, "perl_method_super", PERL_CONF_LITERAL);
+ perl_emit_resolved(ctx, sf->qualified_name, "perl_method_super", PERL_CONF_LITERAL,
+ call);
return;
}
@@ -747,7 +895,7 @@ static void perl_resolve_method_call(PerlLSPContext *ctx, TSNode call) {
const char *strat = (f->receiver_type && strcmp(f->receiver_type, class_qn) == 0)
? strategy
: "perl_method_inherited";
- perl_emit_resolved(ctx, f->qualified_name, strat, PERL_CONF_LITERAL);
+ perl_emit_resolved(ctx, f->qualified_name, strat, PERL_CONF_LITERAL, call);
return;
}
/* Receiver typed but method not found in the indexed inheritance chain.
@@ -823,6 +971,9 @@ static void perl_resolve_calls_in_node_inner(PerlLSPContext *ctx, TSNode node) {
perl_process_assignment(ctx, assign);
}
+ if (strcmp(k, "refgen_expression") == 0)
+ perl_emit_non_direct_coderef_usage(ctx, node);
+
/* Call-resolution dispatch. */
if (strcmp(k, "function_call_expression") == 0 ||
strcmp(k, "ambiguous_function_call_expression") == 0) {
@@ -1529,6 +1680,7 @@ void cbm_run_perl_lsp(CBMArena *arena, CBMFileResult *result, const char *source
* finished (const) registry. */
PerlLSPContext ctx;
perl_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, &result->resolved_calls);
+ ctx.usages = &result->usages;
ctx.current_package_qn = "";
ctx.enclosing_package_qn = "";
diff --git a/internal/cbm/lsp/perl_lsp.h b/internal/cbm/lsp/perl_lsp.h
index 53e3cbd8f..c3a165db6 100644
--- a/internal/cbm/lsp/perl_lsp.h
+++ b/internal/cbm/lsp/perl_lsp.h
@@ -61,6 +61,7 @@ typedef struct {
/* Output: resolved calls accumulate here. */
CBMResolvedCallArray *resolved_calls;
+ CBMUsageArray *usages;
/* Recursion guard for perl_eval_expr_type. */
int eval_depth;
diff --git a/internal/cbm/lsp/php_lsp.c b/internal/cbm/lsp/php_lsp.c
index 04d98d01e..4caf5ba0f 100644
--- a/internal/cbm/lsp/php_lsp.c
+++ b/internal/cbm/lsp/php_lsp.c
@@ -825,6 +825,33 @@ static char *fetch_leading_phpdoc(PHPLSPContext *ctx, TSNode node) {
return NULL;
}
+/* PHP 8.1 first-class callable syntax reuses call-expression nodes but its
+ * argument list contains only a `variadic_placeholder`: `target(...)`,
+ * `$obj->method(...)`, or `Type::method(...)`. It creates a Closure; it does
+ * not invoke the target. */
+static bool php_is_first_class_callable(TSNode node) {
+ TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
+ if (ts_node_is_null(args))
+ return false;
+
+ bool saw_placeholder = false;
+ int semantic_children = 0;
+ uint32_t child_count = ts_node_child_count(args);
+ for (uint32_t i = 0; i < child_count; i++) {
+ TSNode child = ts_node_child(args, i);
+ if (ts_node_is_null(child) || !ts_node_is_named(child))
+ continue;
+ const char *kind = ts_node_type(child);
+ if (strcmp(kind, "comment") == 0)
+ continue;
+ semantic_children++;
+ if (strcmp(kind, "variadic_placeholder") != 0)
+ return false;
+ saw_placeholder = true;
+ }
+ return saw_placeholder && semantic_children == 1;
+}
+
/* ── expression evaluation ──────────────────────────────────────── */
/* Returns the type of a tree-sitter PHP expression node.
@@ -868,6 +895,12 @@ const CBMType *php_eval_expr_type(PHPLSPContext *ctx, TSNode node) {
}
} else if (strcmp(kind, "object_creation_expression") == 0) {
result = eval_object_creation_type(ctx, node);
+ } else if ((strcmp(kind, "function_call_expression") == 0 ||
+ strcmp(kind, "member_call_expression") == 0 ||
+ strcmp(kind, "nullsafe_member_call_expression") == 0 ||
+ strcmp(kind, "scoped_call_expression") == 0) &&
+ php_is_first_class_callable(node)) {
+ result = cbm_type_named(ctx->arena, "Closure");
} else if (strcmp(kind, "member_call_expression") == 0 ||
strcmp(kind, "nullsafe_member_call_expression") == 0 ||
strcmp(kind, "scoped_call_expression") == 0) {
@@ -1250,28 +1283,137 @@ static const CBMType *eval_member_call_type(PHPLSPContext *ctx, TSNode call_node
/* ── emit ───────────────────────────────────────────────────────── */
-static void emit_resolved_reason(PHPLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence, const char *reason) {
+static void emit_resolved_reason_kind(PHPLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence, const char *reason,
+ CBMResolvedKind kind) {
if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy;
rc.confidence = confidence;
rc.reason = reason;
+ rc.kind = kind;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
-static void emit_resolved(PHPLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
- emit_resolved_reason(ctx, callee_qn, strategy, confidence, NULL);
+static void emit_resolved_kind(PHPLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, CBMResolvedKind kind) {
+ emit_resolved_reason_kind(ctx, callee_qn, strategy, confidence, NULL, kind);
+}
+
+static bool php_dynamic_reference_expr(PHPLSPContext *ctx, TSNode expr) {
+ if (ts_node_is_null(expr)) {
+ return false;
+ }
+ const char *kind = ts_node_type(expr);
+ if (strstr(kind, "subscript") || strstr(kind, "element_access") ||
+ strstr(kind, "index_expression") || strstr(kind, "computed")) {
+ return true;
+ }
+
+ static const char *const terminal_fields[] = {"property", "field", "attribute",
+ "name", "method", NULL};
+ for (int i = 0; terminal_fields[i]; i++) {
+ TSNode terminal = ts_node_child_by_field_name(expr, terminal_fields[i],
+ (uint32_t)strlen(terminal_fields[i]));
+ if (ts_node_is_null(terminal)) {
+ continue;
+ }
+ uint32_t start = ts_node_start_byte(terminal);
+ uint32_t expr_start = ts_node_start_byte(expr);
+ while (start > expr_start && isspace((unsigned char)ctx->source[start - 1])) {
+ start--;
+ }
+ return start > expr_start && ctx->source[start - 1] == '[';
+ }
+ return false;
+}
+
+static bool php_callable_reference_has_dynamic_member_name(PHPLSPContext *ctx, TSNode call) {
+ const char *call_kind = ts_node_type(call);
+ if (strcmp(call_kind, "member_call_expression") != 0 &&
+ strcmp(call_kind, "nullsafe_member_call_expression") != 0 &&
+ strcmp(call_kind, "scoped_call_expression") != 0) {
+ return false;
+ }
+
+ TSNode name = ts_node_child_by_field_name(call, "name", 4);
+ if (ts_node_is_null(name)) {
+ return false;
+ }
+ const char *name_kind = ts_node_type(name);
+ return strcmp(name_kind, "variable_name") == 0 ||
+ strcmp(name_kind, "dynamic_variable_name") == 0 || php_dynamic_reference_expr(ctx, name);
+}
+
+/* Mirror extract_calls.c's terminal_callee_leaf policy so the PHP LSP and
+ * USAGE passes attach the same exact token occurrence to a first-class
+ * callable, including qualified free-function references. */
+static TSNode php_reference_callee_leaf(PHPLSPContext *ctx, TSNode expr) {
+ if (ts_node_is_null(expr) || php_dynamic_reference_expr(ctx, expr)) {
+ return (TSNode){0};
+ }
+
+ static const char *const terminal_fields[] = {"property", "field", "attribute",
+ "method", "name", NULL};
+ for (int i = 0; terminal_fields[i]; i++) {
+ TSNode terminal = ts_node_child_by_field_name(expr, terminal_fields[i],
+ (uint32_t)strlen(terminal_fields[i]));
+ if (!ts_node_is_null(terminal)) {
+ return php_reference_callee_leaf(ctx, terminal);
+ }
+ }
+
+ const char *kind = ts_node_type(expr);
+ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0 ||
+ strcmp(kind, "type_identifier") == 0 || strcmp(kind, "field_identifier") == 0 ||
+ strcmp(kind, "property_identifier") == 0 || strcmp(kind, "name") == 0 ||
+ strcmp(kind, "variable_name") == 0 || strcmp(kind, "attribute") == 0 ||
+ strcmp(kind, "symbol") == 0 || strcmp(kind, "sym_lit") == 0 ||
+ strcmp(kind, "user_symbol") == 0) {
+ return expr;
+ }
+
+ uint32_t count = ts_node_named_child_count(expr);
+ if (count == 0) {
+ return (TSNode){0};
+ }
+ bool terminal_is_last = strstr(kind, "qualified") || strstr(kind, "scoped") ||
+ strstr(kind, "member") || strstr(kind, "selector") ||
+ strstr(kind, "navigation") || strstr(kind, "field_expression");
+ return php_reference_callee_leaf(ctx,
+ ts_node_named_child(expr, terminal_is_last ? count - 1 : 0));
+}
+
+static TSNode php_callable_reference_leaf(PHPLSPContext *ctx, TSNode call, const char *kind) {
+ if (php_callable_reference_has_dynamic_member_name(ctx, call)) {
+ return (TSNode){0};
+ }
+ TSNode expr = {0};
+ if (strcmp(kind, "function_call_expression") == 0) {
+ expr = ts_node_child_by_field_name(call, "function", 8);
+ } else {
+ expr = ts_node_child_by_field_name(call, "name", 4);
+ }
+ return php_reference_callee_leaf(ctx, expr);
+}
+
+static void php_stamp_resolved_site(PHPLSPContext *ctx, int first, TSNode site) {
+ if (!ctx->resolved_calls || ts_node_is_null(site) || first < 0) {
+ return;
+ }
+ for (int i = first; i < ctx->resolved_calls->count; i++) {
+ ctx->resolved_calls->items[i].site_start_byte = ts_node_start_byte(site);
+ ctx->resolved_calls->items[i].site_end_byte = ts_node_end_byte(site);
+ }
}
static void emit_unresolved(PHPLSPContext *ctx, const char *expr_text, const char *reason) {
if (!ctx->resolved_calls || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
rc.strategy = "lsp_unresolved";
@@ -1449,7 +1591,7 @@ static void process_catch(PHPLSPContext *ctx, TSNode node) {
/* ── call resolution ────────────────────────────────────────────── */
-static void resolve_function_call(PHPLSPContext *ctx, TSNode call) {
+static void resolve_function_call(PHPLSPContext *ctx, TSNode call, CBMResolvedKind kind) {
TSNode fn = ts_node_child_by_field_name(call, "function", 8);
if (ts_node_is_null(fn))
return;
@@ -1457,12 +1599,34 @@ static void resolve_function_call(PHPLSPContext *ctx, TSNode call) {
if (!name)
return;
+ /* In PHP, `$handler(...)` is syntactically a function-call expression but
+ * a typed object value dispatches to its materialized `__invoke` method.
+ * This is precise only for a first-class callable and a receiver type whose
+ * exact method exists in the registry; otherwise leave it unresolved so
+ * the usage pipeline can retain ordinary value semantics. */
+ if (kind == CBM_RESOLVED_CALL_REFERENCE && strcmp(ts_node_type(fn), "variable_name") == 0) {
+ const CBMType *receiver = php_eval_expr_type(ctx, fn);
+ const char *class_qn = NULL;
+ if (receiver && receiver->kind == CBM_TYPE_NAMED) {
+ class_qn = receiver->data.named.qualified_name;
+ } else if (receiver && receiver->kind == CBM_TYPE_TEMPLATE) {
+ class_qn = receiver->data.template_type.template_name;
+ }
+ const CBMRegisteredFunc *invoke =
+ class_qn ? php_lookup_method(ctx, class_qn, "__invoke") : NULL;
+ if (invoke && invoke->qualified_name) {
+ emit_resolved_reason_kind(ctx, invoke->qualified_name, "php_invokable_reference", 0.95f,
+ name, kind);
+ }
+ return;
+ }
+
/* `use function Foo\\bar;` mapping. */
const char *target = find_use(ctx, name, CBM_PHP_USE_FUNCTION);
if (target) {
const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, target);
if (f) {
- emit_resolved(ctx, f->qualified_name, "php_function_namespaced", 0.95f);
+ emit_resolved_kind(ctx, f->qualified_name, "php_function_namespaced", 0.95f, kind);
return;
}
}
@@ -1472,7 +1636,7 @@ static void resolve_function_call(PHPLSPContext *ctx, TSNode call) {
const char *ns_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->current_namespace_qn, name);
const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, ns_qn);
if (f) {
- emit_resolved(ctx, f->qualified_name, "php_function_namespaced", 0.95f);
+ emit_resolved_kind(ctx, f->qualified_name, "php_function_namespaced", 0.95f, kind);
return;
}
}
@@ -1504,7 +1668,7 @@ static void resolve_function_call(PHPLSPContext *ctx, TSNode call) {
}
}
if (best) {
- emit_resolved(ctx, best->qualified_name, "php_function_global_fallback", 0.70f);
+ emit_resolved_kind(ctx, best->qualified_name, "php_function_global_fallback", 0.70f, kind);
return;
}
/* Unresolved — but DO NOT emit unresolved noise here; the unified
@@ -1513,11 +1677,15 @@ static void resolve_function_call(PHPLSPContext *ctx, TSNode call) {
(void)emit_unresolved;
}
-static void resolve_member_call(PHPLSPContext *ctx, TSNode call) {
+static void resolve_member_call(PHPLSPContext *ctx, TSNode call, CBMResolvedKind kind) {
TSNode obj = ts_node_child_by_field_name(call, "object", 6);
TSNode name_node = ts_node_child_by_field_name(call, "name", 4);
if (ts_node_is_null(name_node))
return;
+ if (kind == CBM_RESOLVED_CALL_REFERENCE &&
+ php_callable_reference_has_dynamic_member_name(ctx, call)) {
+ return;
+ }
char *method_name = php_node_text(ctx, name_node);
if (!method_name)
return;
@@ -1541,7 +1709,7 @@ static void resolve_member_call(PHPLSPContext *ctx, TSNode call) {
const char *strategy = (f->receiver_type && strcmp(f->receiver_type, class_qn) == 0)
? "php_method_typed"
: "php_method_inherited";
- emit_resolved(ctx, f->qualified_name, strategy, 0.95f);
+ emit_resolved_kind(ctx, f->qualified_name, strategy, 0.95f, kind);
return;
}
/* Receiver known but method missing — magic __call? The call dispatches to
@@ -1550,8 +1718,8 @@ static void resolve_member_call(PHPLSPContext *ctx, TSNode call) {
* so stash it in reason for the join (lsp_resolve.h, php_method_dynamic).
* Emit above the join's confidence floor — dispatch to __call is certain. */
if (class_has_magic_call(ctx, class_qn, false)) {
- emit_resolved_reason(ctx, cbm_arena_sprintf(ctx->arena, "%s.__call", class_qn),
- "php_method_dynamic", 0.85f, method_name);
+ emit_resolved_reason_kind(ctx, cbm_arena_sprintf(ctx->arena, "%s.__call", class_qn),
+ "php_method_dynamic", 0.85f, method_name, kind);
return;
}
/* Receiver known but class not in registry (e.g. vendor type not indexed,
@@ -1559,15 +1727,19 @@ static void resolve_member_call(PHPLSPContext *ctx, TSNode call) {
* at "<class_qn>.<method>" so the pipeline bridge can BLOCK the unified
* extractor's likely-incorrect short-name fallback. The bridge filters
* unknown targets and yields no edge — better than a wrong edge. */
- emit_resolved(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
- "php_method_typed_unindexed", 0.55f);
+ emit_resolved_kind(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
+ "php_method_typed_unindexed", 0.55f, kind);
}
-static void resolve_static_call(PHPLSPContext *ctx, TSNode call) {
+static void resolve_static_call(PHPLSPContext *ctx, TSNode call, CBMResolvedKind kind) {
TSNode scope = ts_node_child_by_field_name(call, "scope", 5);
TSNode name_node = ts_node_child_by_field_name(call, "name", 4);
if (ts_node_is_null(name_node))
return;
+ if (kind == CBM_RESOLVED_CALL_REFERENCE &&
+ php_callable_reference_has_dynamic_member_name(ctx, call)) {
+ return;
+ }
char *method_name = php_node_text(ctx, name_node);
if (!method_name)
return;
@@ -1593,20 +1765,30 @@ static void resolve_static_call(PHPLSPContext *ctx, TSNode call) {
const CBMRegisteredFunc *f = php_lookup_method(ctx, class_qn, method_name);
if (f) {
- emit_resolved(ctx, f->qualified_name, strategy, 0.95f);
+ emit_resolved_kind(ctx, f->qualified_name, strategy, 0.95f, kind);
+ return;
+ }
+ /* A first-class reference to an absent static method has an exact target
+ * only when a materialized `__callStatic` exists. Preserve the source name
+ * as the occurrence-join reason, but point at the real method node. Normal
+ * facade invocations retain their existing low-confidence behavior. */
+ const CBMRegisteredFunc *magic_static = php_lookup_method(ctx, class_qn, "__callStatic");
+ if (magic_static && kind == CBM_RESOLVED_CALL_REFERENCE) {
+ emit_resolved_reason_kind(ctx, magic_static->qualified_name, "php_static_magic_reference",
+ 0.95f, method_name, kind);
return;
}
/* Facade detection: class has __callStatic in its chain. */
- if (class_has_magic_call(ctx, class_qn, true)) {
- emit_resolved(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
- "php_dynamic_unresolved", 0.10f);
+ if (magic_static) {
+ emit_resolved_kind(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
+ "php_dynamic_unresolved", 0.10f, kind);
return;
}
/* Class resolved (e.g., from a `use` clause), method unknown — emit
* synthetic resolved call so the pipeline bridge can suppress the
* unified extractor's name-fallback misroute. */
- emit_resolved(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
- "php_static_unindexed", 0.55f);
+ emit_resolved_kind(ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, method_name),
+ "php_static_unindexed", 0.55f, kind);
}
/* ── type narrowing ─────────────────────────────────────────────────
@@ -2158,14 +2340,32 @@ static void php_resolve_calls_in_node_inner(PHPLSPContext *ctx, TSNode node) {
return; /* process_if_statement already walked body under narrowing */
}
- /* Call-resolution dispatch. */
+ /* Call-resolution dispatch. A first-class callable has the same outer AST
+ * node as an invocation, so carry the semantic kind alongside resolution
+ * and skip invocation-only narrowing/binding effects. */
+ bool is_callable_reference = php_is_first_class_callable(node);
+ CBMResolvedKind resolved_kind =
+ is_callable_reference ? CBM_RESOLVED_CALL_REFERENCE : CBM_RESOLVED_INVOCATION;
if (strcmp(kind, "function_call_expression") == 0) {
- resolve_function_call(ctx, node);
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ resolve_function_call(ctx, node, resolved_kind);
+ if (is_callable_reference) {
+ php_stamp_resolved_site(ctx, first, php_callable_reference_leaf(ctx, node, kind));
+ } else {
+ php_stamp_resolved_site(ctx, first, node);
+ }
/* assert(...) in current scope narrows sequentially. */
- apply_assert_narrowing(ctx, node);
+ if (!is_callable_reference)
+ apply_assert_narrowing(ctx, node);
} else if (strcmp(kind, "member_call_expression") == 0 ||
strcmp(kind, "nullsafe_member_call_expression") == 0) {
- resolve_member_call(ctx, node);
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ resolve_member_call(ctx, node, resolved_kind);
+ if (is_callable_reference) {
+ php_stamp_resolved_site(ctx, first, php_callable_reference_leaf(ctx, node, kind));
+ } else {
+ php_stamp_resolved_site(ctx, first, node);
+ }
/* Closure binding via $f->bindTo($obj). When $f is an inline
* closure literal AND the bindTo call's first arg is a typed
* variable, walk the closure body with $this rebound. We only
@@ -2174,7 +2374,7 @@ static void php_resolve_calls_in_node_inner(PHPLSPContext *ctx, TSNode node) {
* value-typing is Phase 6+ infrastructure). */
TSNode obj = ts_node_child_by_field_name(node, "object", 6);
TSNode mname = ts_node_child_by_field_name(node, "name", 4);
- if (!ts_node_is_null(obj) && !ts_node_is_null(mname)) {
+ if (!is_callable_reference && !ts_node_is_null(obj) && !ts_node_is_null(mname)) {
char *mn = php_node_text(ctx, mname);
const char *ok = ts_node_type(obj);
if (mn && strcmp(mn, "bindTo") == 0 &&
@@ -2212,13 +2412,19 @@ static void php_resolve_calls_in_node_inner(PHPLSPContext *ctx, TSNode node) {
}
}
} else if (strcmp(kind, "scoped_call_expression") == 0) {
- resolve_static_call(ctx, node);
+ int first = ctx->resolved_calls ? ctx->resolved_calls->count : -1;
+ resolve_static_call(ctx, node, resolved_kind);
+ if (is_callable_reference) {
+ php_stamp_resolved_site(ctx, first, php_callable_reference_leaf(ctx, node, kind));
+ } else {
+ php_stamp_resolved_site(ctx, first, node);
+ }
/* Closure binding via Closure::bind($f, $obj). Same shape as
* bindTo: rebind $this when the first arg is a closure literal
* and the second arg has a known class. */
TSNode scope = ts_node_child_by_field_name(node, "scope", 5);
TSNode mname2 = ts_node_child_by_field_name(node, "name", 4);
- if (!ts_node_is_null(scope) && !ts_node_is_null(mname2)) {
+ if (!is_callable_reference && !ts_node_is_null(scope) && !ts_node_is_null(mname2)) {
char *cls = php_node_text(ctx, scope);
char *mn = php_node_text(ctx, mname2);
bool is_closure_bind = mn && strcmp(mn, "bind") == 0 && cls &&
@@ -2782,6 +2988,22 @@ static const CBMType *parse_return_type_text(CBMArena *arena, const char *text,
return cbm_type_named(arena, php_ns_to_dot(arena, first));
}
+typedef struct {
+ const char *module_qn;
+ const char *namespace_qn;
+ const char **use_local_names;
+ const char **use_target_qns;
+ int use_count;
+} PHPSignatureParseContext;
+
+static const CBMType *php_signature_parse_type(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const PHPSignatureParseContext *ctx = (const PHPSignatureParseContext *)parser_ctx;
+ return parse_return_type_text(arena, text, ctx ? ctx->module_qn : NULL,
+ ctx ? ctx->namespace_qn : NULL, ctx ? ctx->use_local_names : NULL,
+ ctx ? ctx->use_target_qns : NULL, ctx ? ctx->use_count : 0);
+}
+
/* ── property type extraction ───────────────────────────────────────
*
* Walks the AST top-level for class/trait/interface bodies and registers
@@ -3514,7 +3736,7 @@ static void flatten_trait_into_class(PHPLSPContext *ctx, CBMTypeRegistry *reg, c
if (rets) {
rets[0] = cbm_type_named(ctx->arena, class_qn);
rets[1] = NULL;
- new_sig = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ new_sig = cbm_type_func_replace_returns(ctx->arena, src->signature, rets);
}
}
}
@@ -3815,7 +4037,8 @@ static void process_class_for_fields(PHPLSPContext *ctx, CBMTypeRegistry *reg, T
if (rets) {
rets[0] = parsed;
rets[1] = NULL;
- rf->signature = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ rf->signature =
+ cbm_type_func_replace_returns(ctx->arena, rf->signature, rets);
}
break;
}
@@ -3892,7 +4115,8 @@ static void process_class_for_fields(PHPLSPContext *ctx, CBMTypeRegistry *reg, T
if (rets) {
rets[0] = ret_t;
rets[1] = NULL;
- rf->signature = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ rf->signature = cbm_type_func_replace_returns(
+ ctx->arena, rf->signature, rets);
}
break;
}
@@ -3944,6 +4168,26 @@ static void php_lsp_collect_class_fields(PHPLSPContext *ctx, CBMTypeRegistry *re
}
}
+void cbm_php_refine_lsp_registry(PHPLSPContext *ctx, CBMTypeRegistry *reg, TSNode root) {
+ if (!ctx || !reg || ts_node_is_null(root))
+ return;
+
+ php_class_field_table_t tab = {0};
+ php_lsp_collect_class_fields(ctx, reg, root, &tab);
+ for (int i = 0; i < tab.count; i++) {
+ php_class_fields_t *fields = &tab.items[i];
+ if (fields->count == 0)
+ continue;
+ for (int t = 0; t < reg->type_count; t++) {
+ if (strcmp(reg->types[t].qualified_name, fields->class_qn) == 0) {
+ reg->types[t].field_names = fields->field_names;
+ reg->types[t].field_types = fields->field_types;
+ break;
+ }
+ }
+ }
+}
+
/* ── entry: cbm_run_php_lsp ─────────────────────────────────────── */
void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
@@ -4015,7 +4259,29 @@ void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
if (strcmp(d->label, "Method") == 0 && d->parent_class) {
rf.receiver_type = d->parent_class;
}
- /* Build a minimal signature with just the return type. */
+ PHPSignatureParseContext parse_ctx = {
+ .module_qn = module_qn,
+ .namespace_qn = NULL,
+ .use_local_names = NULL,
+ .use_target_qns = NULL,
+ .use_count = 0,
+ };
+ const CBMType **param_types = NULL;
+ if (d->signature_param_types || d->signature_param_count > 0) {
+ param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ php_signature_parse_type, &parse_ctx);
+ } else if (!d->signature_param_types && d->signature_param_count == 0 &&
+ d->param_types) {
+ /* Legacy CBMDefinition callers have no counted carrier. Keep
+ * their historical projection as a local-only fallback. */
+ int legacy_count = 0;
+ while (d->param_types[legacy_count])
+ legacy_count++;
+ param_types = cbm_type_materialize_signature_params(
+ arena, d->param_types, legacy_count, php_signature_parse_type, &parse_ctx);
+ }
+ /* Build a signature carrying ordered params plus the return type. */
const CBMType *ret_t =
d->return_type
? parse_return_type_text(arena, d->return_type, module_qn, NULL, NULL, NULL, 0)
@@ -4026,7 +4292,7 @@ void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
rets[0] = ret_t;
rets[1] = NULL;
}
- rf.signature = cbm_type_func(arena, NULL, NULL, rets);
+ rf.signature = cbm_type_func(arena, NULL, param_types, rets);
cbm_registry_add_func(&reg, rf);
}
}
@@ -4040,7 +4306,6 @@ void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
* file defs are registered but before the call walk so eval_expr_type
* for $this->prop and $obj->prop sees the field types. */
{
- php_class_field_table_t tab = {0};
/* First pass to populate the use map (so type names in property
* declarations resolve correctly). */
/* Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). */
@@ -4055,25 +4320,10 @@ void cbm_run_php_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
collect_use_declaration(&ctx, c);
}
}
- php_lsp_collect_class_fields(&ctx, &reg, root, &tab);
+ cbm_php_refine_lsp_registry(&ctx, &reg, root);
/* Reset namespace/use state — process_file will re-collect. */
ctx.current_namespace_qn = "";
ctx.use_count = 0;
-
- for (int i = 0; i < tab.count; i++) {
- php_class_fields_t *f = &tab.items[i];
- if (f->count == 0)
- continue;
- /* Mutate the existing entry — registered types are stored by
- * value in reg.types[], find the index and update it. */
- for (int t = 0; t < reg.type_count; t++) {
- if (strcmp(reg.types[t].qualified_name, f->class_qn) == 0) {
- reg.types[t].field_names = f->field_names;
- reg.types[t].field_types = f->field_types;
- break;
- }
- }
- }
}
php_lsp_process_file(&ctx, root);
@@ -4131,8 +4381,8 @@ static const char **php_split_pipe(CBMArena *arena, const char *text) {
* functions. Return type strings are parsed via parse_return_type_text using
* each def's def_module_qn so bare type names qualify against the module
* where the def lives, not the importer's module. */
-static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,
- CBMLSPDef *defs, int def_count) {
+void cbm_php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,
+ const CBMLSPDef *defs, int def_count) {
/* Pass 1: types only. The method pass below probes the registry per
* Method def (receiver auto-registration); doing that against an
* unfinalized registry is a LINEAR scan over the growing type table —
@@ -4141,7 +4391,7 @@ static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeR
* the hash, then register funcs/methods with O(1) lookups (post-finalize
* stub additions stay visible via the registry's tail-scan). */
for (int i = 0; i < def_count; i++) {
- CBMLSPDef *d = &defs[i];
+ const CBMLSPDef *d = &defs[i];
if (!d->qualified_name || !d->short_name || !d->label)
continue;
@@ -4168,7 +4418,7 @@ static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeR
/* Pass 2: functions and methods. */
for (int i = 0; i < def_count; i++) {
- CBMLSPDef *d = &defs[i];
+ const CBMLSPDef *d = &defs[i];
if (!d->qualified_name || !d->short_name || !d->label)
continue;
@@ -4178,6 +4428,18 @@ static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeR
rf.qualified_name = d->qualified_name; /* borrowed */
rf.short_name = d->short_name;
+ const char *def_mod = d->def_module_qn ? d->def_module_qn : "";
+ PHPSignatureParseContext parse_ctx = {
+ .module_qn = def_mod,
+ .namespace_qn = d->namespace_name,
+ .use_local_names = NULL,
+ .use_target_qns = NULL,
+ .use_count = 0,
+ };
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count, php_signature_parse_type,
+ &parse_ctx);
+
/* Build FUNC type from "|"-separated return-type texts. Each piece
* is the unqualified return-type expression as it appears in the
* def-defining module's source. parse_return_type_text qualifies
@@ -4192,7 +4454,6 @@ static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeR
ret_types = (const CBMType **)cbm_arena_alloc(
arena, (size_t)(n + 1) * sizeof(const CBMType *));
if (ret_types) {
- const char *def_mod = d->def_module_qn ? d->def_module_qn : "";
for (int j = 0; j < n; j++) {
ret_types[j] = parse_return_type_text(arena, ret_strs[j], def_mod, NULL,
NULL, NULL, 0);
@@ -4201,7 +4462,7 @@ static void php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeR
}
}
}
- rf.signature = cbm_type_func(arena, NULL, NULL, ret_types);
+ rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
rf.receiver_type = d->receiver_type; /* borrowed */
@@ -4254,7 +4515,7 @@ void cbm_run_php_lsp_cross(CBMArena *arena, const char *source, int source_len,
* accumulate GBs across a large repo. The scratch dies with this call. */
CBMArena idx_arena;
cbm_arena_init(&idx_arena);
- php_register_lsp_defs(arena, &idx_arena, &reg, defs, def_count);
+ cbm_php_register_lsp_defs(arena, &idx_arena, &reg, defs, def_count);
/* Finalize registry — O(1) lookups. See go_lsp.c "3c. Finalize"
* comment for the rationale. */
@@ -4275,7 +4536,6 @@ void cbm_run_php_lsp_cross(CBMArena *arena, const char *source, int source_len,
* to populate typed-property field maps so $this->prop and $obj->prop
* resolve to the right type during the call walk. */
{
- php_class_field_table_t tab = {0};
/* Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). */
uint32_t pkn = 0;
TSNode *pkids = cbm_lsp_collect_children(ctx.arena, root, &pkn);
@@ -4288,22 +4548,10 @@ void cbm_run_php_lsp_cross(CBMArena *arena, const char *source, int source_len,
collect_use_declaration(&ctx, c);
}
}
- php_lsp_collect_class_fields(&ctx, &reg, root, &tab);
+ cbm_php_refine_lsp_registry(&ctx, &reg, root);
ctx.current_namespace_qn = "";
/* Reset to caller-supplied uses only — process_file re-adds AST uses. */
ctx.use_count = import_count;
- for (int i = 0; i < tab.count; i++) {
- php_class_fields_t *f = &tab.items[i];
- if (f->count == 0)
- continue;
- for (int t = 0; t < reg.type_count; t++) {
- if (strcmp(reg.types[t].qualified_name, f->class_qn) == 0) {
- reg.types[t].field_names = f->field_names;
- reg.types[t].field_types = f->field_types;
- break;
- }
- }
- }
}
php_lsp_process_file(&ctx, root);
@@ -4344,6 +4592,7 @@ void cbm_batch_php_lsp_cross(CBMArena *arena, CBMBatchPHPLSPFile *files, int fil
for (int j = 0; j < file_out.count; j++) {
CBMResolvedCall *src = &file_out.items[j];
CBMResolvedCall *dst = &out[f].items[j];
+ memset(dst, 0, sizeof(*dst));
dst->caller_qn =
src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn =
@@ -4351,6 +4600,9 @@ void cbm_batch_php_lsp_cross(CBMArena *arena, CBMBatchPHPLSPFile *files, int fil
dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
}
} else {
out[f].count = 0;
diff --git a/internal/cbm/lsp/php_lsp.h b/internal/cbm/lsp/php_lsp.h
index 44cc0a09d..2d83d7a00 100644
--- a/internal/cbm/lsp/php_lsp.h
+++ b/internal/cbm/lsp/php_lsp.h
@@ -71,6 +71,10 @@ void php_lsp_add_use(PHPLSPContext *ctx, const char *local_name, const char *tar
/* Process a file's AST: walk top-level decls, then function/method bodies. */
void php_lsp_process_file(PHPLSPContext *ctx, TSNode root);
+/* Refine an already-populated registry from local class ASTs: declared and
+ * PHPDoc returns, trait flattening, and typed fields. */
+void cbm_php_refine_lsp_registry(PHPLSPContext *ctx, CBMTypeRegistry *reg, TSNode root);
+
/* Evaluate a PHP expression's type. May return NULL / CBM_TYPE_UNKNOWN. */
const CBMType *php_eval_expr_type(PHPLSPContext *ctx, TSNode node);
@@ -100,6 +104,9 @@ void cbm_php_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
* `use` declarations from the AST are layered on top by process_file.
*
* Reuses go_lsp.h's CBMLSPDef so cross-language registration is uniform. */
+void cbm_php_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRegistry *reg,
+ const CBMLSPDef *defs, int def_count);
+
void cbm_run_php_lsp_cross(
CBMArena *arena,
const char *source, int source_len,
diff --git a/internal/cbm/lsp/py_lsp.c b/internal/cbm/lsp/py_lsp.c
index d78b71904..fbfd22e0f 100644
--- a/internal/cbm/lsp/py_lsp.c
+++ b/internal/cbm/lsp/py_lsp.c
@@ -14,6 +14,8 @@
#include "../cbm.h"
#include "../helpers.h"
#include "tree_sitter/api.h"
+#include <ctype.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -31,6 +33,107 @@
// Forward decls
static void py_resolve_calls_in_inner(PyLSPContext *ctx, TSNode node);
+/* Decorators are extracted as raw syntax (`@property`, `@pkg.cache(...)`),
+ * not resolved qualified names. Preserve the raw array for sound callable-
+ * value admission, while parsing only enough of the spelling to retain the
+ * existing descriptive flags used by Python type inference. */
+static bool py_decorator_short_name_is(const char *raw, const char *expected) {
+ if (!raw || !expected)
+ return false;
+ while (*raw && (isspace((unsigned char)*raw) || *raw == '@'))
+ raw++;
+ const char *end = raw;
+ const char *leaf = raw;
+ while (*end && *end != '(' && !isspace((unsigned char)*end)) {
+ if (*end == '.')
+ leaf = end + 1;
+ end++;
+ }
+ size_t expected_len = strlen(expected);
+ return (size_t)(end - leaf) == expected_len && strncmp(leaf, expected, expected_len) == 0;
+}
+
+static void py_register_func_decorators(CBMRegisteredFunc *func, const char **decorators) {
+ if (!func)
+ return;
+ func->decorator_qns = decorators;
+ if (!decorators)
+ return;
+ for (int i = 0; decorators[i]; i++) {
+ const char *decorator = decorators[i];
+ if (py_decorator_short_name_is(decorator, "property"))
+ func->flags |= CBM_FUNC_FLAG_PROPERTY;
+ else if (py_decorator_short_name_is(decorator, "classmethod"))
+ func->flags |= CBM_FUNC_FLAG_CLASSMETHOD;
+ else if (py_decorator_short_name_is(decorator, "staticmethod"))
+ func->flags |= CBM_FUNC_FLAG_STATICMETHOD;
+ else if (py_decorator_short_name_is(decorator, "abstractmethod"))
+ func->flags |= CBM_FUNC_FLAG_ABSTRACTMETHOD;
+ else if (py_decorator_short_name_is(decorator, "overload"))
+ func->flags |= CBM_FUNC_FLAG_OVERLOAD;
+ else if (py_decorator_short_name_is(decorator, "final"))
+ func->flags |= CBM_FUNC_FLAG_FINAL;
+ }
+}
+
+/* Python defines `@decorator def f` as rebinding `f = decorator(f)`. Until
+ * decorator identity and composition are semantically resolved, the raw
+ * decorated definition cannot prove that a value occurrence denotes the
+ * exact underlying function. Fail closed to ordinary USAGE. */
+static bool py_func_is_exact_callable_value(const CBMRegisteredFunc *func) {
+ return func && func->qualified_name &&
+ !(func->flags &
+ (CBM_FUNC_FLAG_PROPERTY | CBM_FUNC_FLAG_OVERLOAD | CBM_FUNC_FLAG_AMBIGUOUS_BINDING)) &&
+ (!func->decorator_qns || !func->decorator_qns[0]);
+}
+
+static int py_func_qn_pointer_cmp(const void *left, const void *right) {
+ const CBMRegisteredFunc *a = *(CBMRegisteredFunc *const *)left;
+ const CBMRegisteredFunc *b = *(CBMRegisteredFunc *const *)right;
+ const char *aqn = a ? a->qualified_name : NULL;
+ const char *bqn = b ? b->qualified_name : NULL;
+ if (!aqn || !bqn)
+ return aqn ? 1 : bqn ? -1 : 0;
+ return strcmp(aqn, bqn);
+}
+
+/* The graph identifies functions by QN. When Python source redefines the
+ * same QN, the runtime's last binding is knowable but the graph no longer has
+ * one occurrence-exact definition target. Mark the whole duplicate group so
+ * callable values fail closed without changing ordinary call overload/rebind
+ * behavior. */
+static void py_mark_ambiguous_callable_bindings(CBMTypeRegistry *registry) {
+ if (!registry || registry->func_count <= 1)
+ return;
+ size_t count = (size_t)registry->func_count;
+ CBMRegisteredFunc **sorted = count <= SIZE_MAX / sizeof(*sorted)
+ ? (CBMRegisteredFunc **)malloc(count * sizeof(*sorted))
+ : NULL;
+ if (!sorted) {
+ /* Allocation failure must reduce precision, never fabricate it. */
+ for (int i = 0; i < registry->func_count; i++)
+ registry->funcs[i].flags |= CBM_FUNC_FLAG_AMBIGUOUS_BINDING;
+ return;
+ }
+ for (int i = 0; i < registry->func_count; i++)
+ sorted[i] = &registry->funcs[i];
+ qsort(sorted, count, sizeof(*sorted), py_func_qn_pointer_cmp);
+ for (size_t first = 0; first < count;) {
+ size_t end = first + 1;
+ const char *qn = sorted[first]->qualified_name;
+ while (qn && end < count && sorted[end]->qualified_name &&
+ strcmp(qn, sorted[end]->qualified_name) == 0) {
+ end++;
+ }
+ if (qn && end - first > 1) {
+ for (size_t i = first; i < end; i++)
+ sorted[i]->flags |= CBM_FUNC_FLAG_AMBIGUOUS_BINDING;
+ }
+ first = end;
+ }
+ free(sorted);
+}
+
/* Depth-guarded entry for the AST call-resolution walk. The walk recurses once
* per nesting level; a deeply-nested or cyclic file can overflow the native
* stack (SIGSEGV) and take down the whole index. Past the cap the subtree is
@@ -51,7 +154,7 @@ static void py_process_statement(PyLSPContext *ctx, TSNode node);
static const CBMRegisteredFunc *py_lookup_attribute(PyLSPContext *ctx, const char *type_qn,
const char *member_name);
static void py_emit_resolved_call(PyLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence);
+ float confidence, TSNode site);
static const CBMType *py_resolve_annotation(PyLSPContext *ctx, const char *ann);
static const CBMType *py_iterable_element_type(PyLSPContext *ctx, const CBMType *iter_type);
static const CBMType *py_lookup_field(PyLSPContext *ctx, const char *type_qn,
@@ -85,6 +188,18 @@ static void py_scope_bind(PyLSPContext *ctx, const char *name, const CBMType *ty
cbm_scope_bind(ctx->current_scope, name, type);
}
+static void py_scope_bind_callable(PyLSPContext *ctx, const char *name, const CBMType *type,
+ const char *callable_qn) {
+ ctx->type_cache_gen++;
+ cbm_scope_bind_callable(ctx->current_scope, name, type, callable_qn);
+}
+
+static void py_scope_clear_callable(PyLSPContext *ctx, const char *name) {
+ if (cbm_scope_update_callable(ctx->current_scope, name, NULL)) {
+ ctx->type_cache_gen++;
+ }
+}
+
static void py_scope_restore(PyLSPContext *ctx, CBMScope *saved) {
ctx->type_cache_gen++;
ctx->current_scope = saved;
@@ -116,20 +231,25 @@ void py_lsp_add_import(PyLSPContext *ctx, const char *local_name, const char *mo
(const char **)cbm_arena_alloc(ctx->arena, (size_t)(new_count + 1) * sizeof(const char *));
const char **qns =
(const char **)cbm_arena_alloc(ctx->arena, (size_t)(new_count + 1) * sizeof(const char *));
- if (!names || !qns)
+ unsigned char *kinds =
+ (unsigned char *)cbm_arena_alloc(ctx->arena, (size_t)new_count * sizeof(unsigned char));
+ if (!names || !qns || !kinds)
return;
for (int i = 0; i < ctx->import_count; i++) {
names[i] = ctx->import_local_names[i];
qns[i] = ctx->import_module_qns[i];
+ kinds[i] = ctx->import_kinds ? ctx->import_kinds[i] : 0;
}
names[ctx->import_count] = cbm_arena_strdup(ctx->arena, local_name);
qns[ctx->import_count] = cbm_arena_strdup(ctx->arena, module_qn);
+ kinds[ctx->import_count] = 0;
names[new_count] = NULL;
qns[new_count] = NULL;
ctx->import_local_names = names;
ctx->import_module_qns = qns;
+ ctx->import_kinds = kinds;
ctx->import_count = new_count;
}
@@ -153,11 +273,219 @@ static bool import_is_from_style(const char *local_name, const char *module_qn)
return true;
}
-/* For `import a.b.c`, also bind every dotted prefix as MODULE so that
- * `a.b.c.fn()` style chained access walks correctly: `a` → MODULE(a),
- * `a.b` → MODULE(a.b), `a.b.c` → MODULE(a.b.c). The underlying CBMImport
- * already records local_name="c" / module_path="a.b.c"; we walk the
- * prefix chain in addition. */
+typedef enum {
+ PY_DIRECT_IMPORT_UNKNOWN = 0,
+ PY_DIRECT_IMPORT_UNALIASED,
+ PY_DIRECT_IMPORT_ALIASED,
+ PY_FROM_IMPORT,
+ PY_IMPORT_AMBIGUOUS,
+ PY_IMPORT_UNCLASSIFIED,
+} PyDirectImportKind;
+
+typedef struct {
+ int count;
+ PyDirectImportKind kind;
+ const char *canonical_qn;
+} PyImportSyntaxMatch;
+
+static bool py_import_node_text_equals(const PyLSPContext *ctx, TSNode node, const char *expected) {
+ if (!ctx || !expected || ts_node_is_null(node))
+ return false;
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ size_t expected_len = strlen(expected);
+ return end >= start && (int)end <= ctx->source_len && (size_t)(end - start) == expected_len &&
+ memcmp(ctx->source + start, expected, expected_len) == 0;
+}
+
+static bool py_qn_has_boundary_suffix(const char *qualified_name, const char *suffix) {
+ if (!qualified_name || !suffix)
+ return false;
+ while (*suffix == '.')
+ suffix++;
+ size_t qn_len = strlen(qualified_name);
+ size_t suffix_len = strlen(suffix);
+ if (suffix_len == 0 || qn_len < suffix_len)
+ return false;
+ size_t start = qn_len - suffix_len;
+ return (start == 0 || qualified_name[start - 1] == '.') &&
+ strcmp(qualified_name + start, suffix) == 0;
+}
+
+static char *py_import_node_text_dup(PyLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return NULL;
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ if (end < start || (int)end > ctx->source_len)
+ return NULL;
+ return cbm_arena_strndup(ctx->arena, ctx->source + start, (size_t)(end - start));
+}
+
+static TSNode py_from_import_module_node(TSNode statement) {
+ TSNode module = ts_node_child_by_field_name(statement, "module_name", 11);
+ if (!ts_node_is_null(module))
+ return module;
+ uint32_t count = ts_node_named_child_count(statement);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode child = ts_node_named_child(statement, i);
+ const char *kind = ts_node_type(child);
+ if (strcmp(kind, "dotted_name") == 0 || strcmp(kind, "relative_import") == 0)
+ return child;
+ }
+ return (TSNode){0};
+}
+
+static bool py_import_node_root_equals(PyLSPContext *ctx, TSNode node, const char *expected_root) {
+ char *text = py_import_node_text_dup(ctx, node);
+ if (!text || !expected_root)
+ return false;
+ size_t root_len = strlen(expected_root);
+ size_t text_len = strlen(text);
+ if (root_len > text_len)
+ return false;
+ return strncmp(text, expected_root, root_len) == 0 &&
+ (text[root_len] == '\0' || text[root_len] == '.');
+}
+
+static void py_import_syntax_match_add(PyImportSyntaxMatch *match, PyDirectImportKind kind,
+ const char *canonical_qn) {
+ if (!match)
+ return;
+ match->count++;
+ if (match->count == 1) {
+ match->kind = kind;
+ match->canonical_qn = canonical_qn;
+ }
+}
+
+/* The graph import map can only name the imported module. Python extraction
+ * intentionally records the same metadata for
+ *
+ * from target import handler as callback
+ * import target.handler as callback
+ *
+ * so only the parsed statement can decide whether `handler` is a member or
+ * part of a module path. Canonicalize a proven from-import once, before scope
+ * binding: `<project>.target` becomes `<project>.target.handler`. The sealed
+ * registry then retains responsibility for proving that the exact target is
+ * an undecorated, unambiguous callable. */
+static const char *py_canonical_from_import_qn(PyLSPContext *ctx, TSNode statement,
+ TSNode imported_name, const char *incoming_qn) {
+ if (!ctx || !incoming_qn || ts_node_is_null(statement) || ts_node_is_null(imported_name))
+ return NULL;
+ TSNode module = py_from_import_module_node(statement);
+
+ char *member = py_import_node_text_dup(ctx, imported_name);
+ char *module_text = py_import_node_text_dup(ctx, module);
+ if (!member || !member[0])
+ return NULL;
+ const char *module_suffix = module_text;
+ while (module_suffix && *module_suffix == '.')
+ module_suffix++;
+
+ const char *full_suffix =
+ module_suffix && module_suffix[0]
+ ? cbm_arena_sprintf(ctx->arena, "%s.%s", module_suffix, member)
+ : member;
+ if (!full_suffix)
+ return NULL;
+ if (py_qn_has_boundary_suffix(incoming_qn, full_suffix))
+ return incoming_qn;
+ if (module_suffix && module_suffix[0] &&
+ !py_qn_has_boundary_suffix(incoming_qn, module_suffix)) {
+ return NULL;
+ }
+ return cbm_arena_sprintf(ctx->arena, "%s.%s", incoming_qn, member);
+}
+
+/* CBMImport intentionally stores only the local spelling and module path.
+ * Recover the binding form from the AST, but require exactly one top-level
+ * binding for the local name. Python permits later imports to rebind the same
+ * local; selecting the first would turn conflicting runtime identities into
+ * false semantic proof. */
+static PyDirectImportKind py_import_kind_from_ast(PyLSPContext *ctx, TSNode root,
+ const char *local, const char **qn_io) {
+ const char *qn = qn_io ? *qn_io : NULL;
+ if (!ctx || !local || !qn || !qn_io || ts_node_is_null(root))
+ return PY_DIRECT_IMPORT_UNKNOWN;
+
+ PyImportSyntaxMatch match = {0};
+ uint32_t root_count = ts_node_named_child_count(root);
+ for (uint32_t i = 0; i < root_count; i++) {
+ TSNode stmt = ts_node_named_child(root, i);
+ const char *stmt_kind = ts_node_type(stmt);
+ if (strcmp(stmt_kind, "import_from_statement") == 0) {
+ TSNode module = py_from_import_module_node(stmt);
+ uint32_t import_count = ts_node_named_child_count(stmt);
+ for (uint32_t j = 0; j < import_count; j++) {
+ TSNode item = ts_node_named_child(stmt, j);
+ if (!ts_node_is_null(module) && ts_node_eq(item, module))
+ continue;
+ const char *kind = ts_node_type(item);
+ if (strcmp(kind, "aliased_import") == 0) {
+ TSNode name = ts_node_child_by_field_name(item, "name", 4);
+ TSNode alias = ts_node_child_by_field_name(item, "alias", 5);
+ if (py_import_node_text_equals(ctx, alias, local)) {
+ const char *canonical =
+ py_canonical_from_import_qn(ctx, stmt, name, qn);
+ py_import_syntax_match_add(
+ &match, canonical ? PY_FROM_IMPORT : PY_IMPORT_UNCLASSIFIED,
+ canonical ? canonical : qn);
+ }
+ } else if ((strcmp(kind, "identifier") == 0 ||
+ strcmp(kind, "dotted_name") == 0) &&
+ py_import_node_text_equals(ctx, item, local)) {
+ const char *canonical = py_canonical_from_import_qn(ctx, stmt, item, qn);
+ py_import_syntax_match_add(
+ &match, canonical ? PY_FROM_IMPORT : PY_IMPORT_UNCLASSIFIED,
+ canonical ? canonical : qn);
+ }
+ }
+ continue;
+ }
+ if (strcmp(stmt_kind, "import_statement") != 0)
+ continue;
+ uint32_t import_count = ts_node_named_child_count(stmt);
+ for (uint32_t j = 0; j < import_count; j++) {
+ TSNode item = ts_node_named_child(stmt, j);
+ const char *kind = ts_node_type(item);
+ if (strcmp(kind, "aliased_import") == 0) {
+ TSNode alias = ts_node_child_by_field_name(item, "alias", 5);
+ if (py_import_node_text_equals(ctx, alias, local))
+ py_import_syntax_match_add(&match, PY_DIRECT_IMPORT_ALIASED, qn);
+ } else if ((strcmp(kind, "dotted_name") == 0 || strcmp(kind, "identifier") == 0) &&
+ py_import_node_root_equals(ctx, item, local)) {
+ char *imported_path = py_import_node_text_dup(ctx, item);
+ PyDirectImportKind matched_kind =
+ imported_path && py_qn_has_boundary_suffix(qn, imported_path)
+ ? PY_DIRECT_IMPORT_UNALIASED
+ : PY_IMPORT_UNCLASSIFIED;
+ py_import_syntax_match_add(&match, matched_kind, qn);
+ }
+ }
+ }
+ if (match.count == 0)
+ return PY_IMPORT_UNCLASSIFIED;
+ if (match.count > 1)
+ return PY_IMPORT_AMBIGUOUS;
+ if (match.kind == PY_FROM_IMPORT && match.canonical_qn)
+ *qn_io = match.canonical_qn;
+ return match.kind;
+}
+
+static bool py_import_index_is_from_binding(const PyLSPContext *ctx, int index) {
+ if (!ctx || index < 0 || index >= ctx->import_count)
+ return false;
+ if (ctx->import_kinds && ctx->import_kinds[index] == PY_FROM_IMPORT)
+ return true;
+ return (!ctx->import_kinds || ctx->import_kinds[index] == PY_DIRECT_IMPORT_UNKNOWN) &&
+ import_is_from_style(ctx->import_local_names[index], ctx->import_module_qns[index]);
+}
+
+/* For an unaliased `import a.b.c`, also bind every dotted prefix as MODULE so
+ * that `a.b.c.fn()` style chained access walks correctly: `a` -> MODULE(a),
+ * `a.b` -> MODULE(a.b), `a.b.c` -> MODULE(a.b.c). */
static void py_bind_dotted_prefixes(PyLSPContext *ctx, const char *qn) {
if (!ctx || !qn)
return;
@@ -185,7 +513,7 @@ static void py_bind_dotted_prefixes(PyLSPContext *ctx, const char *qn) {
}
}
-void py_lsp_bind_imports(PyLSPContext *ctx) {
+static void py_lsp_bind_imports_for_root(PyLSPContext *ctx, TSNode root) {
if (!ctx || !ctx->current_scope)
return;
for (int i = 0; i < ctx->import_count; i++) {
@@ -200,8 +528,20 @@ void py_lsp_bind_imports(PyLSPContext *ctx) {
if (strcmp(local, "*") == 0)
continue;
+ PyDirectImportKind direct_kind = py_import_kind_from_ast(ctx, root, local, &qn);
+ ctx->import_module_qns[i] = qn;
+ if (ctx->import_kinds)
+ ctx->import_kinds[i] = (unsigned char)direct_kind;
+ bool from_style = direct_kind == PY_FROM_IMPORT ||
+ (direct_kind == PY_DIRECT_IMPORT_UNKNOWN &&
+ import_is_from_style(local, qn));
const CBMType *t;
- if (import_is_from_style(local, qn)) {
+ if (direct_kind == PY_DIRECT_IMPORT_UNALIASED) {
+ // Python binds only the root of an unaliased dotted import.
+ t = cbm_type_module(ctx->arena, local);
+ } else if (direct_kind == PY_DIRECT_IMPORT_ALIASED) {
+ t = cbm_type_module(ctx->arena, qn);
+ } else if (from_style) {
// `from X import Y` — bind Y to NAMED(X.Y). Phase 6 attribute
// resolution checks the registry to upgrade to MODULE / class
// / function as appropriate.
@@ -221,19 +561,25 @@ void py_lsp_bind_imports(PyLSPContext *ctx) {
// `import X` / `import X as Y` (single segment) — MODULE(X).
t = cbm_type_module(ctx->arena, qn);
}
- py_scope_bind(ctx, local, t);
- // Always walk the dotted prefix chain. The CBMImport shape
- // can't distinguish `import a.b.c` from `from a.b import c`
- // (both produce local_name=c, module_path=a.b.c), but binding
- // parent modules (`a`, `a.b`) into scope is correct in both
- // cases: in the first form Python actually does this; in the
- // second form the parent isn't in scope at runtime, but our
- // adding it doesn't cause false positives because real source
- // wouldn't reference an unimported parent module name.
- py_bind_dotted_prefixes(ctx, qn);
+ const CBMRegisteredFunc *imported =
+ from_style && ctx->registry ? cbm_registry_lookup_func(ctx->registry, qn) : NULL;
+ if (py_func_is_exact_callable_value(imported)) {
+ py_scope_bind_callable(ctx, local, t, imported->qualified_name);
+ } else {
+ py_scope_bind(ctx, local, t);
+ }
+ // With a real AST, only an unaliased direct import introduces the
+ // dotted root. Keep the historical prefix fallback for synthetic
+ // unit-test contexts that call py_lsp_bind_imports without a tree.
+ if (direct_kind == PY_DIRECT_IMPORT_UNALIASED || ts_node_is_null(root))
+ py_bind_dotted_prefixes(ctx, qn);
}
}
+void py_lsp_bind_imports(PyLSPContext *ctx) {
+ py_lsp_bind_imports_for_root(ctx, (TSNode){0});
+}
+
const CBMType *py_lsp_lookup_in_scope(const PyLSPContext *ctx, const char *name) {
if (!ctx)
return cbm_type_unknown();
@@ -383,11 +729,13 @@ static const char *py_lookup_dict_dispatch(PyLSPContext *ctx, const char *var, c
}
static void py_emit_resolved_call_reason(PyLSPContext *ctx, const char *callee_qn,
- const char *strategy, float confidence,
- const char *reason) {
+ const char *strategy, float confidence, const char *reason,
+ TSNode site) {
if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
- // Dedupe by (caller, callee). Bounded-window scan: most duplicate
+ uint32_t site_start = ts_node_is_null(site) ? 0 : ts_node_start_byte(site);
+ uint32_t site_end = ts_node_is_null(site) ? 0 : ts_node_end_byte(site);
+ // Dedupe by exact invocation identity. Bounded-window scan: most duplicate
// emissions are nearby in time (same expression evaluated by both
// resolver and emitter passes), so checking only the last DEDUP_WINDOW
// entries catches the common case while keeping per-emission O(1).
@@ -398,28 +746,191 @@ static void py_emit_resolved_call_reason(PyLSPContext *ctx, const char *callee_q
int start = n > DEDUP_WINDOW ? n - DEDUP_WINDOW : 0;
for (int i = start; i < n; i++) {
CBMResolvedCall *rc = &ctx->resolved_calls->items[i];
- if (rc->caller_qn && rc->callee_qn && strcmp(rc->caller_qn, ctx->enclosing_func_qn) == 0 &&
+ if (rc->kind == CBM_RESOLVED_INVOCATION && rc->site_start_byte == site_start &&
+ rc->site_end_byte == site_end && rc->caller_qn && rc->callee_qn &&
+ strcmp(rc->caller_qn, ctx->enclosing_func_qn) == 0 &&
strcmp(rc->callee_qn, callee_qn) == 0) {
if (confidence > rc->confidence) {
rc->confidence = confidence;
rc->strategy = strategy;
+ rc->reason = reason ? cbm_arena_strdup(ctx->arena, reason) : NULL;
}
return;
}
}
- CBMResolvedCall rc;
- memset(&rc, 0, sizeof(rc));
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = cbm_arena_strdup(ctx->arena, callee_qn);
rc.strategy = strategy;
rc.confidence = confidence;
rc.reason = reason ? cbm_arena_strdup(ctx->arena, reason) : NULL;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ rc.site_start_byte = site_start;
+ rc.site_end_byte = site_end;
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
static void py_emit_resolved_call(PyLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
- py_emit_resolved_call_reason(ctx, callee_qn, strategy, confidence, NULL);
+ float confidence, TSNode site) {
+ py_emit_resolved_call_reason(ctx, callee_qn, strategy, confidence, NULL, site);
+}
+
+static void py_emit_resolved_reference(PyLSPContext *ctx, const char *callee_qn,
+ const char *source_name, TSNode site) {
+ if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ for (int i = ctx->resolved_calls->count - 1; i >= 0; i--) {
+ CBMResolvedCall *existing = &ctx->resolved_calls->items[i];
+ if (existing->kind == CBM_RESOLVED_CALL_REFERENCE && existing->site_start_byte == start &&
+ existing->site_end_byte == end && existing->caller_qn && existing->callee_qn &&
+ strcmp(existing->caller_qn, ctx->enclosing_func_qn) == 0 &&
+ strcmp(existing->callee_qn, callee_qn) == 0) {
+ return;
+ }
+ }
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = cbm_arena_strdup(ctx->arena, callee_qn);
+ rc.strategy = "lsp_callable_value_reference";
+ rc.confidence = 0.97f;
+ const char *leaf = strrchr(callee_qn, '.');
+ leaf = leaf ? leaf + 1 : callee_qn;
+ rc.reason = source_name && strcmp(source_name, leaf) != 0
+ ? cbm_arena_strdup(ctx->arena, source_name)
+ : NULL;
+ rc.kind = CBM_RESOLVED_CALL_REFERENCE;
+ rc.site_start_byte = start;
+ rc.site_end_byte = end;
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+static void py_emit_unresolved_reference(PyLSPContext *ctx, const char *candidate_qn, TSNode site) {
+ if (!ctx || !ctx->resolved_calls || !candidate_qn || !ctx->enclosing_func_qn ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = cbm_arena_strdup(ctx->arena, candidate_qn);
+ rc.strategy = "lsp_unresolved";
+ rc.confidence = 0.0f;
+ rc.reason = "callable_value_not_in_registry";
+ rc.kind = CBM_RESOLVED_CALL_REFERENCE;
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+/* Return a project-pass candidate only when the import metadata itself names
+ * one exact from-import target. Module imports and ambiguous duplicate local
+ * bindings deliberately return NULL. */
+static const char *py_exact_imported_reference_candidate(PyLSPContext *ctx,
+ const char *local_name) {
+ if (!ctx || !local_name)
+ return NULL;
+ const char *candidate = NULL;
+ for (int i = 0; i < ctx->import_count; i++) {
+ const char *local = ctx->import_local_names[i];
+ const char *qn = ctx->import_module_qns[i];
+ if (!local || !qn || strcmp(local, local_name) != 0 ||
+ !py_import_index_is_from_binding(ctx, i)) {
+ continue;
+ }
+ if (candidate && strcmp(candidate, qn) != 0)
+ return NULL;
+ candidate = qn;
+ }
+ return candidate;
+}
+
+/* Return one graph target only for an expression whose callable identity is
+ * statically exact. Complex containers/conditionals deliberately return NULL
+ * so their constituent function names stay ordinary USAGE. */
+static const char *py_exact_callable_target(PyLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return NULL;
+
+ /* Parentheses do not change callable identity. Unwrap them iteratively:
+ * an assignment such as `fn = (((target)))` reaches this helper after
+ * expression-type inference, and adversarial nesting must not consume one
+ * native stack frame per parenthesized_expression. */
+ const char *kind = ts_node_type(node);
+ while (strcmp(kind, "parenthesized_expression") == 0 && ts_node_named_child_count(node) == 1) {
+ node = ts_node_named_child(node, 0);
+ kind = ts_node_type(node);
+ }
+ if (strcmp(kind, "identifier") == 0) {
+ char *name = py_node_text(ctx, node);
+ if (!name)
+ return NULL;
+ if (cbm_scope_contains(ctx->current_scope, name)) {
+ return cbm_scope_lookup_callable(ctx->current_scope, name);
+ }
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, name);
+ return py_func_is_exact_callable_value(f) ? f->qualified_name : NULL;
+ }
+ if (strcmp(kind, "attribute") == 0) {
+ TSNode object = ts_node_child_by_field_name(node, "object", 6);
+ TSNode attribute = ts_node_child_by_field_name(node, "attribute", 9);
+ if (ts_node_is_null(object) || ts_node_is_null(attribute))
+ return NULL;
+ char *member = py_node_text(ctx, attribute);
+ const CBMType *receiver = py_eval_expr_type(ctx, object);
+ if (!member || !receiver)
+ return NULL;
+ receiver = cbm_type_resolve_alias(receiver);
+ if (receiver->kind == CBM_TYPE_MODULE) {
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, receiver->data.module.module_qn, member);
+ return py_func_is_exact_callable_value(f) ? f->qualified_name : NULL;
+ }
+ if (receiver->kind == CBM_TYPE_NAMED) {
+ /* Instance fields shadow class methods. Without an exact callable
+ * identity for the field value, promoting the same-named method
+ * would fabricate a callable target. */
+ if (py_lookup_field(ctx, receiver->data.named.qualified_name, member))
+ return NULL;
+ const CBMRegisteredFunc *f =
+ py_lookup_attribute(ctx, receiver->data.named.qualified_name, member);
+ return py_func_is_exact_callable_value(f) ? f->qualified_name : NULL;
+ }
+ }
+ return NULL;
+}
+
+static void py_resolve_value_references_at(PyLSPContext *ctx, TSNode call) {
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(args))
+ return;
+ uint32_t count = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode arg = ts_node_named_child(args, i);
+ if (strcmp(ts_node_type(arg), "keyword_argument") == 0) {
+ arg = ts_node_child_by_field_name(arg, "value", 5);
+ if (ts_node_is_null(arg))
+ continue;
+ }
+ const char *kind = ts_node_type(arg);
+ if (strcmp(kind, "identifier") != 0 && strcmp(kind, "attribute") != 0 &&
+ strcmp(kind, "parenthesized_expression") != 0)
+ continue;
+ const char *target = py_exact_callable_target(ctx, arg);
+ char *source_name = py_node_text(ctx, arg);
+ if (target) {
+ py_emit_resolved_reference(ctx, target, source_name, arg);
+ continue;
+ }
+ const char *candidate = strcmp(kind, "identifier") == 0
+ ? py_exact_imported_reference_candidate(ctx, source_name)
+ : NULL;
+ if (candidate)
+ py_emit_unresolved_reference(ctx, candidate, arg);
+ }
}
/* ── helpers: registry-driven attribute lookup with depth cap ──── */
@@ -891,8 +1402,8 @@ static const CBMType *py_eval_expr_type_uncached(PyLSPContext *ctx, TSNode node)
if (!name)
return cbm_type_unknown();
const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
- if (!cbm_type_is_unknown(t))
- return t;
+ if (cbm_scope_contains(ctx->current_scope, name))
+ return t ? t : cbm_type_unknown();
// Builtin globals: True / False / None at top level.
if (strcmp(name, "True") == 0 || strcmp(name, "False") == 0)
return cbm_type_builtin(ctx->arena, "bool");
@@ -1159,6 +1670,10 @@ static const CBMType *py_eval_expr_type_uncached(PyLSPContext *ctx, TSNode node)
}
// Constructor call: ClassName() returns NAMED(ClassName).
const CBMType *in_scope = cbm_scope_lookup(ctx->current_scope, fname);
+ const char *callable_qn = cbm_scope_lookup_callable(ctx->current_scope, fname);
+ if (callable_qn) {
+ return py_func_return_type(ctx, callable_qn);
+ }
if (!cbm_type_is_unknown(in_scope)) {
if (in_scope->kind == CBM_TYPE_NAMED) {
const CBMRegisteredType *rt = cbm_registry_lookup_type(
@@ -1181,6 +1696,10 @@ static const CBMType *py_eval_expr_type_uncached(PyLSPContext *ctx, TSNode node)
return in_scope->data.template_type.template_args[n - 1];
}
}
+ /* Even an UNKNOWN local/parameter is a real lexical shadow. Do
+ * not borrow the return type of a same-named module function. */
+ if (cbm_scope_contains(ctx->current_scope, fname))
+ return cbm_type_unknown();
// Module-local function call.
const CBMRegisteredFunc *f =
cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, fname);
@@ -1592,6 +2111,8 @@ static void py_process_statement(PyLSPContext *ctx, TSNode node) {
const CBMType *rhs_type =
ts_node_is_null(right) ? cbm_type_unknown() : py_eval_expr_type(ctx, right);
+ const char *rhs_callable =
+ ts_node_is_null(right) ? NULL : py_exact_callable_target(ctx, right);
// Annotated assignment: x: T = expr — annotation wins.
bool has_annotation = !ts_node_is_null(ann);
@@ -1667,7 +2188,11 @@ static void py_process_statement(PyLSPContext *ctx, TSNode node) {
if (strcmp(lk, "identifier") == 0) {
char *name = py_node_text(ctx, left);
if (name) {
- py_scope_bind(ctx, name, rhs_type);
+ if (rhs_callable) {
+ py_scope_bind_callable(ctx, name, rhs_type, rhs_callable);
+ } else {
+ py_scope_bind(ctx, name, rhs_type);
+ }
// Lambda registry: `fn = lambda x: ...`.
if (!ts_node_is_null(right) && strcmp(ts_node_type(right), "lambda") == 0) {
py_register_lambda(ctx, name, right);
@@ -1921,42 +2446,74 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
py_scope_restore(ctx, saved);
return;
}
- // Constructor call (ClassName()) — or a call through any other
- // NAMED scope binding (aliased imports land here too).
+ /* Lexical identity takes precedence over same-named module symbols.
+ * An ordinary local binding is also a hard shadow: if it is not a
+ * proven callable alias, do not fall through and fabricate a direct
+ * call to a module-level function with the same spelling. */
+ if (cbm_scope_contains(ctx->current_scope, fname)) {
+ const char *alias_target = cbm_scope_lookup_callable(ctx->current_scope, fname);
+ if (alias_target) {
+ py_emit_resolved_call_reason(ctx, alias_target, "lsp_callable_alias", 0.97f, fname,
+ call_node);
+ return;
+ }
+ const CBMType *in_scope = cbm_scope_lookup(ctx->current_scope, fname);
+ if (!cbm_type_is_unknown(in_scope) && in_scope->kind == CBM_TYPE_NAMED) {
+ const char *qn = in_scope->data.named.qualified_name;
+ const char *tail = qn ? strrchr(qn, '.') : NULL;
+ const char *qn_short = tail ? tail + 1 : qn;
+ bool imported_alias = false;
+
+ /* #988 is specifically an import binding. Gate the
+ * reason-based alias join by import metadata so an unrelated
+ * local NAMED value cannot masquerade as an imported callable. */
+ if (qn && qn_short && strcmp(qn_short, fname) != 0) {
+ for (int i = 0; i < ctx->import_count; i++) {
+ const char *local = ctx->import_local_names[i];
+ const char *import_qn = ctx->import_module_qns[i];
+ if (local && import_qn && strcmp(local, fname) == 0 &&
+ strcmp(import_qn, qn) == 0 &&
+ py_import_index_is_from_binding(ctx, i)) {
+ imported_alias = true;
+ break;
+ }
+ }
+ }
+
+ if (imported_alias) {
+ py_emit_resolved_call_reason(ctx, qn, "lsp_import_alias", 0.85f, fname,
+ call_node);
+ } else if (qn && cbm_registry_lookup_type(ctx->registry, qn)) {
+ py_emit_resolved_call(ctx, qn, "lsp_constructor", 0.85f, call_node);
+ }
+ }
+ return;
+ }
+ // Constructor call (ClassName())
const CBMType *in_scope = cbm_scope_lookup(ctx->current_scope, fname);
if (!cbm_type_is_unknown(in_scope) && in_scope->kind == CBM_TYPE_NAMED) {
const char *qn = in_scope->data.named.qualified_name;
- const char *tail = strrchr(qn, '.');
- const char *qn_short = tail ? tail + 1 : qn;
- if (strcmp(qn_short, fname) != 0) {
- /* Aliased binding (`from m import f as g; g()`): the textual
- * callee ("g") differs from the resolved QN's tail ("f"), so
- * the pass join would never match them. Stash the textual
- * name in `reason` under a join-gated strategy, mirroring
- * lsp_dict_dispatch (see lsp_resolve.h) (#988). */
- py_emit_resolved_call_reason(ctx, qn, "lsp_import_alias", 0.85f, fname);
- } else {
- py_emit_resolved_call(ctx, qn, "lsp_constructor", 0.85f);
- }
+ py_emit_resolved_call(ctx, qn, "lsp_constructor", 0.85f, call_node);
return;
}
// Module-local function
const CBMRegisteredFunc *f =
cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, fname);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, call_node);
return;
}
// Builtins (range / len / list / dict / str / int / print / ...).
f = cbm_registry_lookup_symbol(ctx->registry, "builtins", fname);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin", 0.92f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin", 0.92f, call_node);
return;
}
const CBMRegisteredType *rt = cbm_registry_lookup_type(
ctx->registry, cbm_arena_sprintf(ctx->arena, "builtins.%s", fname));
if (rt) {
- py_emit_resolved_call(ctx, rt->qualified_name, "lsp_builtin_constructor", 0.88f);
+ py_emit_resolved_call(ctx, rt->qualified_name, "lsp_builtin_constructor", 0.88f,
+ call_node);
return;
}
return;
@@ -1978,7 +2535,8 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
/* The textual callee of `funcs["a"](v)` is the subscript base
* identifier ("funcs"), not the resolved target ("foo"), so
* stash it in `reason` for the join (see lsp_resolve.h). */
- py_emit_resolved_call_reason(ctx, tgt, "lsp_dict_dispatch", 0.86f, var_name);
+ py_emit_resolved_call_reason(ctx, tgt, "lsp_dict_dispatch", 0.86f, var_name,
+ call_node);
return;
}
}
@@ -2026,13 +2584,15 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
fi ? fi->qualified_name
: cbm_arena_sprintf(ctx->arena, "%s.__init__",
enclosing->embedded_types[i]);
- py_emit_resolved_call(ctx, init_qn, "lsp_super_init", 0.90f);
+ py_emit_resolved_call(ctx, init_qn, "lsp_super_init", 0.90f,
+ call_node);
return;
}
const CBMRegisteredFunc *f =
py_lookup_attribute(ctx, enclosing->embedded_types[i], attr_name);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_super", 0.88f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_super", 0.88f,
+ call_node);
return;
}
}
@@ -2049,7 +2609,7 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
const char *mod = obj_type->data.module.module_qn;
const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(ctx->registry, mod, attr_name);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_module_attr", 0.92f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_module_attr", 0.92f, call_node);
return;
}
// An `import sibling` of an IN-PROJECT module records the module's QN
@@ -2080,7 +2640,7 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
cbm_registry_lookup_symbol(ctx->registry, qual_mod, attr_name);
if (qf) {
py_emit_resolved_call(ctx, qf->qualified_name, "lsp_module_attr",
- 0.92f);
+ 0.92f, call_node);
return;
}
}
@@ -2089,14 +2649,14 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
}
// Best-effort: emit "module.attr" QN — Phase 9 cross-file may fix up.
const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mod, attr_name);
- py_emit_resolved_call(ctx, qn, "lsp_module_attr_unresolved", 0.55f);
+ py_emit_resolved_call(ctx, qn, "lsp_module_attr_unresolved", 0.55f, call_node);
return;
}
if (obj_type->kind == CBM_TYPE_NAMED) {
const CBMRegisteredFunc *f =
py_lookup_attribute(ctx, obj_type->data.named.qualified_name, attr_name);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_method", 0.9f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_method", 0.9f, call_node);
return;
}
}
@@ -2106,7 +2666,8 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
cbm_arena_sprintf(ctx->arena, "builtins.%s", obj_type->data.builtin.name);
const CBMRegisteredFunc *f = py_lookup_attribute(ctx, recv_qn, attr_name);
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin_method", 0.9f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_builtin_method", 0.9f,
+ call_node);
return;
}
}
@@ -2118,7 +2679,8 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
f = py_lookup_attribute(ctx, tname, attr_name);
}
if (f) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_generic_method", 0.88f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_generic_method", 0.88f,
+ call_node);
return;
}
}
@@ -2143,7 +2705,8 @@ static void py_emit_call_for(PyLSPContext *ctx, TSNode call_node) {
}
}
if (matches == 1 && hit) {
- py_emit_resolved_call(ctx, hit->qualified_name, "lsp_method_union", 0.85f);
+ py_emit_resolved_call(ctx, hit->qualified_name, "lsp_method_union", 0.85f,
+ call_node);
return;
}
}
@@ -2339,6 +2902,34 @@ static bool py_block_terminates(TSNode block) {
strcmp(k, "break_statement") == 0 || strcmp(k, "continue_statement") == 0;
}
+/* A write guarded by an if has more than one possible post-if value. Clear an
+ * outer exact callable identity before walking the temporary branch scopes so
+ * the initializer cannot leak through the control-flow join. */
+static void py_invalidate_conditional_aliases(PyLSPContext *ctx, TSNode node, int depth) {
+ if (!ctx || ts_node_is_null(node) || depth > 64)
+ return;
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "function_definition") == 0 || strcmp(kind, "class_definition") == 0 ||
+ strcmp(kind, "lambda") == 0 || strcmp(kind, "list_comprehension") == 0 ||
+ strcmp(kind, "set_comprehension") == 0 || strcmp(kind, "dictionary_comprehension") == 0 ||
+ strcmp(kind, "generator_expression") == 0) {
+ return;
+ }
+ if (strcmp(kind, "assignment") == 0) {
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ if (!ts_node_is_null(left) && strcmp(ts_node_type(left), "identifier") == 0) {
+ char *name = py_node_text(ctx, left);
+ if (name && cbm_scope_lookup_callable(ctx->current_scope, name))
+ py_scope_clear_callable(ctx, name);
+ }
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++) {
+ py_invalidate_conditional_aliases(ctx, ts_node_named_child(node, i), depth + 1);
+ }
+}
+
/* Walk if_statement: push scope for consequence body when narrowing
* applies, then recurse. If the consequence terminates (return/raise),
* apply the negated narrow to the *enclosing* scope so subsequent
@@ -2348,6 +2939,9 @@ static void py_walk_if_statement(PyLSPContext *ctx, TSNode if_node) {
TSNode body = ts_node_child_by_field_name(if_node, "consequence", 11);
TSNode alt = ts_node_child_by_field_name(if_node, "alternative", 11);
+ py_invalidate_conditional_aliases(ctx, body, 0);
+ py_invalidate_conditional_aliases(ctx, alt, 0);
+
// Walrus bindings in the condition leak into the enclosing scope.
py_bind_walrus_in(ctx, cond);
@@ -2480,12 +3074,13 @@ static const char *py_binop_dunder(const char *op_text) {
* guessing the sole class that declares the dunder would mis-resolve ordinary
* built-in subscripts/operators (`some_list[0]`, `a + b` on ints) onto an
* unrelated user class, so we only resolve when the receiver type is known. */
-static void py_emit_dunder_call(PyLSPContext *ctx, const CBMType *recv, const char *dunder) {
+static void py_emit_dunder_call(PyLSPContext *ctx, const CBMType *recv, const char *dunder,
+ TSNode site) {
if (!recv || recv->kind != CBM_TYPE_NAMED || !dunder)
return;
const CBMRegisteredFunc *f = py_lookup_attribute(ctx, recv->data.named.qualified_name, dunder);
if (f && f->qualified_name) {
- py_emit_resolved_call(ctx, f->qualified_name, "lsp_operator_dunder", 0.85f);
+ py_emit_resolved_call(ctx, f->qualified_name, "lsp_operator_dunder", 0.85f, site);
/* A subscript (`s[k]`) / binary_operator (`a + b`) is not a syntactic
* `call` node, so the extractor produced no CBMCall for it and the
* resolved_call above would never be matched into a CALLS edge. Inject
@@ -2494,12 +3089,37 @@ static void py_emit_dunder_call(PyLSPContext *ctx, const CBMType *recv, const ch
* resolved callee QN ends in the dunder, so its short name == dunder.
* Mirrors rust_inject_syn_call. */
if (ctx->syn_calls && ctx->arena && ctx->enclosing_func_qn) {
+ uint32_t site_start = ts_node_start_byte(site);
+ uint32_t site_end = ts_node_end_byte(site);
+ for (int i = 0; i < ctx->syn_calls->count; i++) {
+ const CBMCall *existing = &ctx->syn_calls->items[i];
+ if (existing->requires_lsp_resolution && existing->callee_name &&
+ existing->enclosing_func_qn && strcmp(existing->callee_name, dunder) == 0 &&
+ strcmp(existing->enclosing_func_qn, ctx->enclosing_func_qn) == 0 &&
+ existing->site_start_byte == site_start &&
+ existing->site_end_byte == site_end) {
+ return;
+ }
+ }
CBMCall call;
memset(&call, 0, sizeof(call));
call.callee_name = cbm_arena_strdup(ctx->arena, dunder);
call.enclosing_func_qn = ctx->enclosing_func_qn;
+ call.start_line = (int)ts_node_start_point(site).row + 1;
+ call.site_start_byte = site_start;
+ call.site_end_byte = site_end;
+ call.requires_lsp_resolution = true;
cbm_calls_push(ctx->syn_calls, ctx->arena, call);
}
+ } else if (recv->data.named.qualified_name) {
+ /* The per-file registry cannot see an imported class's dunder method.
+ * Preserve this source-exact semantic candidate so the fused parallel
+ * pipeline knows a cross-file pass is still required. No carrier is
+ * injected until the project registry proves the target. */
+ const char *candidate =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", recv->data.named.qualified_name, dunder);
+ py_emit_resolved_call_reason(ctx, candidate, "lsp_unresolved", 0.0f,
+ "operator_method_not_in_registry", site);
}
}
@@ -2513,6 +3133,7 @@ static void py_resolve_calls_in_inner(PyLSPContext *ctx, TSNode node) {
// Emit call entry if applicable.
if (strcmp(k, "call") == 0) {
+ py_resolve_value_references_at(ctx, node);
py_emit_call_for(ctx, node);
}
@@ -2526,13 +3147,13 @@ static void py_resolve_calls_in_inner(PyLSPContext *ctx, TSNode node) {
if (!ts_node_is_null(left) && !ts_node_is_null(op)) {
const char *dunder = py_binop_dunder(py_node_text(ctx, op));
if (dunder) {
- py_emit_dunder_call(ctx, py_eval_expr_type(ctx, left), dunder);
+ py_emit_dunder_call(ctx, py_eval_expr_type(ctx, left), dunder, node);
}
}
} else if (strcmp(k, "subscript") == 0) {
TSNode value = ts_node_child_by_field_name(node, "value", 5);
if (!ts_node_is_null(value)) {
- py_emit_dunder_call(ctx, py_eval_expr_type(ctx, value), "__getitem__");
+ py_emit_dunder_call(ctx, py_eval_expr_type(ctx, value), "__getitem__", node);
}
}
@@ -3026,6 +3647,16 @@ static const CBMType *py_parse_type_text_qn(CBMArena *arena, const char *ann,
return cbm_type_named(arena, ann);
}
+typedef struct {
+ const char *module_qn;
+} PySignatureParamParserContext;
+
+static const CBMType *py_signature_param_type_adapter(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const PySignatureParamParserContext *ctx = (const PySignatureParamParserContext *)parser_ctx;
+ return py_parse_type_text_qn(arena, text, ctx ? ctx->module_qn : NULL);
+}
+
static const CBMType *py_parse_type_text(CBMArena *arena, const char *ann) {
return py_parse_type_text_qn(arena, ann, NULL);
}
@@ -3462,7 +4093,7 @@ static void py_bind_module_classes(PyLSPContext *ctx) {
void py_lsp_process_file(PyLSPContext *ctx, TSNode root) {
if (!ctx || ts_node_is_null(root))
return;
- py_lsp_bind_imports(ctx);
+ py_lsp_bind_imports_for_root(ctx, root);
py_bind_module_classes(ctx);
uint32_t nc = ts_node_named_child_count(root);
@@ -3596,40 +4227,7 @@ static bool py_register_def(CBMArena *arena, CBMTypeRegistry *reg, CBMDefinition
memset(&rf, 0, sizeof(rf));
rf.qualified_name = d->qualified_name;
rf.short_name = d->name;
-
- // Translate Python decorators into flags + carry the QN list.
- if (d->decorators) {
- int dec_count = 0;
- while (d->decorators[dec_count])
- dec_count++;
- if (dec_count > 0) {
- const char **dec_qns = (const char **)cbm_arena_alloc(
- arena, (size_t)(dec_count + 1) * sizeof(const char *));
- for (int j = 0; j < dec_count; j++) {
- const char *dec = d->decorators[j];
- dec_qns[j] = cbm_arena_strdup(arena, dec);
- // Match by short name (last "." segment) so both
- // "property" and "functools.cache" / "abc.abstractmethod"
- // forms light up.
- const char *short_dec = strrchr(dec, '.');
- short_dec = short_dec ? short_dec + 1 : dec;
- if (strcmp(short_dec, "property") == 0)
- rf.flags |= CBM_FUNC_FLAG_PROPERTY;
- else if (strcmp(short_dec, "classmethod") == 0)
- rf.flags |= CBM_FUNC_FLAG_CLASSMETHOD;
- else if (strcmp(short_dec, "staticmethod") == 0)
- rf.flags |= CBM_FUNC_FLAG_STATICMETHOD;
- else if (strcmp(short_dec, "abstractmethod") == 0)
- rf.flags |= CBM_FUNC_FLAG_ABSTRACTMETHOD;
- else if (strcmp(short_dec, "overload") == 0)
- rf.flags |= CBM_FUNC_FLAG_OVERLOAD;
- else if (strcmp(short_dec, "final") == 0)
- rf.flags |= CBM_FUNC_FLAG_FINAL;
- }
- dec_qns[dec_count] = NULL;
- rf.decorator_qns = dec_qns;
- }
- }
+ py_register_func_decorators(&rf, d->decorators);
const CBMType **ret_types = NULL;
// Prefer d->return_type (full text) when it has subscript brackets
@@ -3657,7 +4255,16 @@ static bool py_register_def(CBMArena *arena, CBMTypeRegistry *reg, CBMDefinition
ret_types[0] = py_parse_type_text_qn(arena, d->return_type, module_qn);
ret_types[1] = NULL;
}
- rf.signature = cbm_type_func(arena, d->param_names, NULL, ret_types);
+ const CBMType **param_types = NULL;
+ const char **param_names = d->param_names;
+ if (d->signature_param_types || d->signature_param_count > 0) {
+ PySignatureParamParserContext parser_ctx = {.module_qn = module_qn};
+ param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ py_signature_param_type_adapter, &parser_ctx);
+ param_names = NULL;
+ }
+ rf.signature = cbm_type_func(arena, param_names, param_types, ret_types);
if (strcmp(d->label, "Method") == 0) {
// Receiver type: the enclosing class. Python def metadata may
@@ -3703,6 +4310,7 @@ void cbm_run_py_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
for (int i = 0; i < result->defs.count; i++) {
py_register_def(arena, &reg, &result->defs.items[i], module_qn);
}
+ py_mark_ambiguous_callable_bindings(&reg);
PyLSPContext ctx;
py_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, &result->resolved_calls);
@@ -3803,6 +4411,7 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
memset(&rf, 0, sizeof(rf));
rf.qualified_name = d->qualified_name; /* borrowed */
rf.short_name = d->short_name;
+ py_register_func_decorators(&rf, d->decorators);
// Build FUNC type from "|"-separated return types.
const char **ret_strs = py_split_pipe(arena, d->return_types);
@@ -3820,7 +4429,11 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
ret_types[n] = NULL;
}
}
- rf.signature = cbm_type_func(arena, NULL, NULL, ret_types);
+ PySignatureParamParserContext parser_ctx = {.module_qn = d->def_module_qn};
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ py_signature_param_type_adapter, &parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
rf.receiver_type = d->receiver_type; /* borrowed */
@@ -3841,7 +4454,8 @@ static void py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
void cbm_run_py_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) {
+ TSTree *cached_tree, CBMResolvedCallArray *out,
+ CBMCallArray *synthetic_calls) {
if (!arena || !source || source_len <= 0 || !out)
return;
@@ -3870,6 +4484,7 @@ void cbm_run_py_lsp_cross(CBMArena *arena, const char *source, int source_len,
CBMArena idx_arena;
cbm_arena_init(&idx_arena);
py_register_lsp_defs(arena, &idx_arena, &reg, defs, def_count);
+ py_mark_ambiguous_callable_bindings(&reg);
/* Finalize registry — O(1) lookups. See go_lsp.c "3c. Finalize"
* comment for the rationale. */
@@ -3877,6 +4492,7 @@ void cbm_run_py_lsp_cross(CBMArena *arena, const char *source, int source_len,
PyLSPContext ctx;
py_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, out);
+ ctx.syn_calls = synthetic_calls;
for (int i = 0; i < import_count; i++) {
if (import_names && import_qns && import_names[i] && import_qns[i]) {
py_lsp_add_import(&ctx, import_names[i], import_qns[i]);
@@ -3910,6 +4526,7 @@ CBMTypeRegistry *cbm_py_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i
py_register_lsp_defs(arena, NULL, reg, d, 1);
}
+ py_mark_ambiguous_callable_bindings(reg);
cbm_registry_finalize(reg);
reg->read_only = true; /* seal: shared Tier-2 registry is read-only during resolve */
return reg;
@@ -3919,7 +4536,7 @@ void cbm_run_py_lsp_cross_with_registry(CBMArena *arena, const char *source, int
const char *module_qn, CBMTypeRegistry *reg,
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
- CBMResolvedCallArray *out) {
+ CBMResolvedCallArray *out, CBMCallArray *synthetic_calls) {
if (!arena || !source || source_len <= 0 || !out || !reg)
return;
@@ -3942,6 +4559,7 @@ void cbm_run_py_lsp_cross_with_registry(CBMArena *arena, const char *source, int
PyLSPContext ctx;
py_lsp_init(&ctx, arena, source, source_len, reg, module_qn, out);
+ ctx.syn_calls = synthetic_calls;
for (int i = 0; i < import_count; i++) {
if (import_names && import_qns && import_names[i] && import_qns[i]) {
py_lsp_add_import(&ctx, import_names[i], import_qns[i]);
@@ -3974,7 +4592,7 @@ void cbm_batch_py_lsp_cross(CBMArena *arena, CBMBatchPyLSPFile *files, int file_
cbm_run_py_lsp_cross(&file_arena, file->source, file->source_len, file->module_qn,
file->defs, file->def_count, file->import_names, file->import_qns,
- file->import_count, file->cached_tree, &file_out);
+ file->import_count, file->cached_tree, &file_out, NULL);
if (file_out.count > 0) {
out[f].count = file_out.count;
@@ -3984,6 +4602,7 @@ void cbm_batch_py_lsp_cross(CBMArena *arena, CBMBatchPyLSPFile *files, int file_
for (int j = 0; j < file_out.count; j++) {
CBMResolvedCall *src = &file_out.items[j];
CBMResolvedCall *dst = &out[f].items[j];
+ memset(dst, 0, sizeof(*dst));
dst->caller_qn =
src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn =
@@ -3991,6 +4610,9 @@ void cbm_batch_py_lsp_cross(CBMArena *arena, CBMBatchPyLSPFile *files, int file_
dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
}
} else {
out[f].count = 0;
diff --git a/internal/cbm/lsp/py_lsp.h b/internal/cbm/lsp/py_lsp.h
index 1d99a7a39..8f6401a1e 100644
--- a/internal/cbm/lsp/py_lsp.h
+++ b/internal/cbm/lsp/py_lsp.h
@@ -50,6 +50,7 @@ typedef struct {
// Built from CBMFileResult.imports.
const char **import_local_names;
const char **import_module_qns;
+ unsigned char *import_kinds; // internal PyDirectImportKind, classified once from the AST
int import_count;
// Current function/class context for resolving `self`/`cls` and emitting
@@ -69,8 +70,9 @@ typedef struct {
// appears in result->calls because a `subscript`/`binary_operator` is not
// a `call` node, so the syntactic extractor produced no call. When this is
// non-NULL, py_emit_dunder_call injects a matching synthetic CBMCall so the
- // recovered dunder call becomes a real CALLS edge. NULL in the cross-file
- // path (no result->calls available there). Mirrors RustLSPContext.syn_calls.
+ // recovered dunder call becomes a real CALLS edge. Cross-file callers use
+ // a separate arena-owned output and merge it into the file result after
+ // resolution. Mirrors RustLSPContext.syn_calls.
CBMCallArray *syn_calls;
// Lambda registry: simple linear list, looked up by name.
@@ -155,7 +157,7 @@ void cbm_run_py_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);
+ CBMResolvedCallArray *out, CBMCallArray *synthetic_calls);
/* Tier 2: pre-built per-language registry (mirrors Go pilot).
* Filters all_defs to Python entries, builds + finalizes once. */
@@ -166,7 +168,7 @@ void cbm_run_py_lsp_cross_with_registry(CBMArena *arena, const char *source, int
CBMTypeRegistry *reg, // pre-built, finalized, READ-ONLY
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
- CBMResolvedCallArray *out);
+ CBMResolvedCallArray *out, CBMCallArray *synthetic_calls);
// --- Batch cross-file LSP ---
diff --git a/internal/cbm/lsp/rust_lsp.c b/internal/cbm/lsp/rust_lsp.c
index 5ca867cd2..68fb444a6 100644
--- a/internal/cbm/lsp/rust_lsp.c
+++ b/internal/cbm/lsp/rust_lsp.c
@@ -43,13 +43,16 @@ static void rust_resolve_calls_in_node(RustLSPContext *ctx, TSNode node);
static void rust_emit_resolved_call(RustLSPContext *ctx, const char *callee_qn,
const char *strategy, float confidence);
static void rust_inject_syn_call(RustLSPContext *ctx, const char *callee_qn);
+static bool rust_map_source_range(const RustLSPContext *ctx, uint32_t start, uint32_t end,
+ uint32_t *mapped_start, uint32_t *mapped_end);
static void rust_emit_unresolved_call(RustLSPContext *ctx, const char *expr_text,
const char *reason);
static const CBMType *rust_lookup_field(RustLSPContext *ctx, const char *type_qn,
const char *field_name, int depth);
static const CBMRegisteredFunc *rust_lookup_method_in_trait(RustLSPContext *ctx,
const char *trait_qn,
- const char *method_name);
+ const char *method_name,
+ bool allow_abstract);
static char *rust_node_text(RustLSPContext *ctx, TSNode node);
static const char *convert_path_to_qn(CBMArena *arena, const char *path);
static bool rust_type_derefs_to_first_arg(const char *type_qn);
@@ -65,6 +68,7 @@ void rust_lsp_init(RustLSPContext *ctx, CBMArena *arena, const char *source, int
ctx->arena = arena;
ctx->source = source;
ctx->source_len = source_len;
+ ctx->root_source = source;
ctx->registry = registry;
ctx->module_qn = module_qn;
ctx->resolved_calls = out;
@@ -385,6 +389,158 @@ static const char *rust_lookup_prelude(const char *name) {
return NULL;
}
+/* Canonical trait-name index used while registries are still under
+ * construction. Every suffix of an interface QN is indexed, but a suffix is
+ * usable only if all registrations with that spelling name the same QN. This
+ * makes raw cross-file paths (`Pinger`, `contract::Pinger`) O(1) to resolve
+ * without the old leaf-first guess or an impls x types scan. */
+typedef struct {
+ CBMIdxMemo unique;
+ CBMIdxMemo ambiguous;
+} RustTraitNameIndex;
+
+static void rust_trait_name_index_add(RustTraitNameIndex *index, CBMArena *arena,
+ const CBMTypeRegistry *reg, const char *key, int type_index) {
+ if (!index || !arena || !reg || !key || !key[0] || type_index < 0 ||
+ type_index >= reg->type_count) {
+ return;
+ }
+ int32_t previous = cbm_idxmemo_get(&index->unique, key);
+ if (previous < 0) {
+ cbm_idxmemo_put_if_absent(&index->unique, arena, key, type_index);
+ return;
+ }
+ const char *previous_qn = reg->types[previous].qualified_name;
+ const char *current_qn = reg->types[type_index].qualified_name;
+ if (previous_qn && current_qn && strcmp(previous_qn, current_qn) != 0) {
+ cbm_idxmemo_put_if_absent(&index->ambiguous, arena, key, 1);
+ }
+}
+
+static void rust_trait_name_index_build(RustTraitNameIndex *index, CBMArena *arena,
+ const CBMTypeRegistry *reg) {
+ memset(index, 0, sizeof(*index));
+ if (!arena || !reg) {
+ return;
+ }
+ for (int i = 0; i < reg->type_count; i++) {
+ const CBMRegisteredType *type = &reg->types[i];
+ if (!type->is_interface || !type->qualified_name) {
+ continue;
+ }
+ const char *suffix = type->qualified_name;
+ for (;;) {
+ rust_trait_name_index_add(index, arena, reg, suffix, i);
+ const char *dot = strchr(suffix, '.');
+ if (!dot || !dot[1]) {
+ break;
+ }
+ suffix = dot + 1;
+ }
+ }
+}
+
+static const char *rust_trait_name_index_lookup(const RustTraitNameIndex *index,
+ const CBMTypeRegistry *reg, const char *key) {
+ if (!index || !reg || !key || cbm_idxmemo_get(&index->ambiguous, key) >= 0) {
+ return NULL;
+ }
+ int32_t type_index = cbm_idxmemo_get(&index->unique, key);
+ if (type_index < 0 || type_index >= reg->type_count) {
+ return NULL;
+ }
+ return reg->types[type_index].qualified_name;
+}
+
+static const char *rust_canonical_impl_trait(CBMArena *arena, const CBMTypeRegistry *reg,
+ const RustTraitNameIndex *index, const char *raw_trait,
+ const char *def_module_qn) {
+ if (!arena || !reg || !index || !raw_trait || !raw_trait[0]) {
+ return NULL;
+ }
+ while (isspace((unsigned char)*raw_trait)) {
+ raw_trait++;
+ }
+ if (strncmp(raw_trait, "dyn ", 4) == 0) {
+ raw_trait += 4;
+ } else if (strncmp(raw_trait, "impl ", 5) == 0) {
+ raw_trait += 5;
+ }
+ const char *normalized = convert_path_to_qn(arena, raw_trait);
+ if (!normalized || !normalized[0]) {
+ return NULL;
+ }
+
+ /* A bare/relative trait declared in the impl's own module is exact and
+ * therefore wins even if another module declares the same leaf. */
+ const char *relative = normalized;
+ if (strncmp(relative, "self.", 5) == 0) {
+ relative += 5;
+ }
+ if (def_module_qn && relative[0] && strncmp(relative, "crate.", 6) != 0 &&
+ strncmp(relative, "super.", 6) != 0) {
+ const char *local = cbm_arena_sprintf(arena, "%s.%s", def_module_qn, relative);
+ const char *local_qn = rust_trait_name_index_lookup(index, reg, local);
+ if (local_qn) {
+ return local_qn;
+ }
+ }
+
+ const char *exact = rust_trait_name_index_lookup(index, reg, normalized);
+ if (exact) {
+ return exact;
+ }
+
+ /* Prelude traits have canonical external QNs. This remains fail-closed:
+ * the canonical QN must actually be registered in this registry. */
+ if (!strchr(normalized, '.')) {
+ const char *prelude = rust_lookup_prelude(normalized);
+ const char *prelude_qn = rust_trait_name_index_lookup(index, reg, prelude);
+ if (prelude_qn) {
+ return prelude_qn;
+ }
+ }
+
+ /* `crate::x::Trait` has no literal `crate` segment in extracted QNs.
+ * Resolve its semantic tail only when globally unique. */
+ const char *suffix = normalized;
+ if (strncmp(suffix, "crate.", 6) == 0) {
+ suffix += 6;
+ } else {
+ while (strncmp(suffix, "super.", 6) == 0) {
+ suffix += 6;
+ }
+ }
+ return rust_trait_name_index_lookup(index, reg, suffix);
+}
+
+static void rust_registered_type_add_embedded(CBMArena *arena, CBMRegisteredType *type,
+ const char *embedded_qn) {
+ if (!arena || !type || !embedded_qn || !embedded_qn[0]) {
+ return;
+ }
+ int count = 0;
+ if (type->embedded_types) {
+ while (type->embedded_types[count]) {
+ if (strcmp(type->embedded_types[count], embedded_qn) == 0) {
+ return;
+ }
+ count++;
+ }
+ }
+ const char **items =
+ (const char **)cbm_arena_alloc(arena, (size_t)(count + 2) * sizeof(*items));
+ if (!items) {
+ return;
+ }
+ for (int i = 0; i < count; i++) {
+ items[i] = type->embedded_types[i];
+ }
+ items[count] = embedded_qn;
+ items[count + 1] = NULL;
+ type->embedded_types = items;
+}
+
/* Strip a leading `&` / `&mut` reference prefix from a textual type so we
* can compare the inner head segment against builtins. */
static const char *skip_ref_prefix(const char *text) {
@@ -413,6 +569,38 @@ static const char *skip_ref_prefix(const char *text) {
return text;
}
+/* Resolve an otherwise-relative multi-segment type only when its head is an
+ * explicit top-level `mod head;` declaration and exactly one graph-qualified
+ * candidate exists. Rust filename-stem QNs do not encode whether a source is
+ * a crate root, so both the child and sibling layouts are tested and any
+ * ambiguity stays unresolved. No short-name/suffix guess is admitted. */
+static const char *rust_registered_relative_path(RustLSPContext *ctx, const char *normalized) {
+ if (!ctx || !ctx->arena || !ctx->registry || !ctx->module_qn || !normalized || !normalized[0]) {
+ return NULL;
+ }
+ const char *head_end = strchr(normalized, '.');
+ if (!head_end || head_end == normalized) {
+ return NULL;
+ }
+ char *head = cbm_arena_strndup(ctx->arena, normalized, (size_t)(head_end - normalized));
+ if (!head || cbm_idxmemo_get(&ctx->declared_modules, head) < 0) {
+ return NULL;
+ }
+
+ const char *current = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, normalized);
+ const char *parent_end = strrchr(ctx->module_qn, '.');
+ const char *parent =
+ parent_end ? cbm_arena_sprintf(ctx->arena, "%.*s.%s", (int)(parent_end - ctx->module_qn),
+ ctx->module_qn, normalized)
+ : NULL;
+ bool current_exists = current && cbm_registry_lookup_type(ctx->registry, current);
+ bool parent_exists = parent && cbm_registry_lookup_type(ctx->registry, parent);
+ if (current_exists == parent_exists) {
+ return NULL;
+ }
+ return current_exists ? current : parent;
+}
+
/* Resolve a Rust *path expression* (e.g. `Foo::bar` or `crate::x::y`)
* into a canonical QN. The resolver cascades through these rules,
* matching what `rust-analyzer`'s name resolver does at the path level:
@@ -535,7 +723,10 @@ static const char *rust_resolve_path_expr(RustLSPContext *ctx, const char *path)
}
}
- /* Treat unknown-head paths as absolute: `std::io::Read` → `std.io.Read`. */
+ /* Treat unknown-head paths as absolute: `std::io::Read` → `std.io.Read`.
+ * Type parsing performs the narrower exact project-relative probe; doing
+ * it here would reclassify `Type::method` as a direct free-function call
+ * before the UFCS/constructor dispatch logic sees it. */
return convert_path_to_qn(ctx->arena, path);
}
@@ -569,6 +760,14 @@ static const char *resolve_path_to_type_qn(RustLSPContext *ctx, const char *path
if (cbm_registry_lookup_type(ctx->registry, qn)) {
return qn;
}
+ const char *normalized = convert_path_to_qn(ctx->arena, path);
+ if (!normalized || strcmp(qn, normalized) != 0) {
+ return qn;
+ }
+ const char *relative = rust_registered_relative_path(ctx, normalized);
+ if (relative) {
+ return relative;
+ }
return qn; /* may not be registered yet but caller can still wrap as NAMED */
}
@@ -609,7 +808,7 @@ const CBMType *rust_parse_type_node(RustLSPContext *ctx, TSNode node) {
if (!path) {
return cbm_type_unknown();
}
- const char *qn = rust_resolve_path_expr(ctx, path);
+ const char *qn = resolve_path_to_type_qn(ctx, path);
return cbm_type_named(ctx->arena, qn);
}
@@ -696,7 +895,7 @@ const CBMType *rust_parse_type_node(RustLSPContext *ctx, TSNode node) {
if (!head) {
return cbm_type_unknown();
}
- const char *head_qn = rust_resolve_path_expr(ctx, head);
+ const char *head_qn = resolve_path_to_type_qn(ctx, head);
/* Gather type_arguments. */
TSNode args = ts_node_child_by_field_name(node, "type_arguments", 14);
@@ -1003,6 +1202,17 @@ static const CBMType *rust_parse_return_type_text(CBMArena *arena, const char *t
return parse_type_text_with_params(arena, text, module_qn, NULL);
}
+typedef struct {
+ const char *module_qn;
+} RustSignatureParamParserContext;
+
+static const CBMType *rust_signature_param_type_adapter(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const RustSignatureParamParserContext *ctx =
+ (const RustSignatureParamParserContext *)parser_ctx;
+ return rust_parse_return_type_text(arena, text, ctx ? ctx->module_qn : NULL);
+}
+
/* ════════════════════════════════════════════════════════════════════
* 5. Generic substitution
* ════════════════════════════════════════════════════════════════════ */
@@ -1952,7 +2162,7 @@ const CBMType *rust_eval_expr_type(RustLSPContext *ctx, TSNode node) {
if (!ts_node_is_null(name_node)) {
char *path = rust_node_text(ctx, name_node);
if (path) {
- return cbm_type_named(ctx->arena, rust_resolve_path_expr(ctx, path));
+ return cbm_type_named(ctx->arena, resolve_path_to_type_qn(ctx, path));
}
}
return cbm_type_unknown();
@@ -2243,6 +2453,93 @@ static const CBMType *rust_deref_step(RustLSPContext *ctx, const CBMType *t) {
return NULL;
}
+static const CBMRegisteredFunc *rust_registry_lookup_inherent_method(const CBMTypeRegistry *reg,
+ const char *receiver_qn,
+ const char *method_name) {
+ if (!reg || !receiver_qn || !method_name) {
+ return NULL;
+ }
+ int best_index = -1;
+ CBMMethodIter it;
+ cbm_registry_methods(reg, receiver_qn, method_name, &it);
+ for (int index; (index = cbm_method_iter_next(&it)) >= 0;) {
+ const CBMRegisteredFunc *candidate = &reg->funcs[index];
+ if ((candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) == 0 &&
+ (best_index < 0 || index < best_index)) {
+ best_index = index;
+ }
+ }
+ if (best_index >= 0) {
+ return &reg->funcs[best_index];
+ }
+ return reg->fallback
+ ? rust_registry_lookup_inherent_method(reg->fallback, receiver_qn, method_name)
+ : NULL;
+}
+
+static const CBMRegisteredFunc *rust_registry_lookup_inherent_method_aliased(
+ const CBMTypeRegistry *reg, const char *receiver_qn, const char *method_name) {
+ const CBMRegisteredFunc *method =
+ rust_registry_lookup_inherent_method(reg, receiver_qn, method_name);
+ if (method) {
+ return method;
+ }
+ const CBMRegisteredType *type = cbm_registry_lookup_type(reg, receiver_qn);
+ for (int depth = 0; depth < 16 && type && type->alias_of; depth++) {
+ method = rust_registry_lookup_inherent_method(reg, type->alias_of, method_name);
+ if (method) {
+ return method;
+ }
+ type = cbm_registry_lookup_type(reg, type->alias_of);
+ }
+ return NULL;
+}
+
+/* Find the trait-impl method for one concrete receiver. With trait_qn==NULL,
+ * exactly one implemented trait may contribute this method; two distinct
+ * traits are ambiguous and deliberately resolve to NULL. */
+static const CBMRegisteredFunc *rust_registry_lookup_trait_impl_method(const CBMTypeRegistry *reg,
+ const char *receiver_qn,
+ const char *trait_qn,
+ const char *method_name,
+ bool *out_ambiguous) {
+ if (out_ambiguous) {
+ *out_ambiguous = false;
+ }
+ if (!reg || !receiver_qn || !method_name) {
+ return NULL;
+ }
+ int best_index = -1;
+ const char *matched_trait = NULL;
+ CBMMethodIter it;
+ cbm_registry_methods(reg, receiver_qn, method_name, &it);
+ for (int index; (index = cbm_method_iter_next(&it)) >= 0;) {
+ const CBMRegisteredFunc *candidate = &reg->funcs[index];
+ if ((candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) == 0 || !candidate->impl_trait_qn) {
+ continue;
+ }
+ if (trait_qn && strcmp(candidate->impl_trait_qn, trait_qn) != 0) {
+ continue;
+ }
+ if (!trait_qn && matched_trait && strcmp(matched_trait, candidate->impl_trait_qn) != 0) {
+ if (out_ambiguous) {
+ *out_ambiguous = true;
+ }
+ return NULL;
+ }
+ matched_trait = candidate->impl_trait_qn;
+ if (best_index < 0 || index < best_index) {
+ best_index = index;
+ }
+ }
+ if (best_index >= 0) {
+ return &reg->funcs[best_index];
+ }
+ return reg->fallback ? rust_registry_lookup_trait_impl_method(
+ reg->fallback, receiver_qn, trait_qn, method_name, out_ambiguous)
+ : NULL;
+}
+
static const CBMRegisteredFunc *rust_lookup_method_depth(RustLSPContext *ctx, const char *type_qn,
const char *member_name, int depth) {
if (!type_qn || !member_name)
@@ -2252,10 +2549,20 @@ static const CBMRegisteredFunc *rust_lookup_method_depth(RustLSPContext *ctx, co
/* Direct inherent method lookup. */
const CBMRegisteredFunc *f =
- cbm_registry_lookup_method_aliased(ctx->registry, type_qn, member_name);
+ rust_registry_lookup_inherent_method_aliased(ctx->registry, type_qn, member_name);
if (f)
return f;
+ bool trait_ambiguous = false;
+ f = rust_registry_lookup_trait_impl_method(ctx->registry, type_qn, NULL, member_name,
+ &trait_ambiguous);
+ if (f) {
+ return f;
+ }
+ if (trait_ambiguous) {
+ return NULL;
+ }
+
/* Follow alias / embedded chain. */
const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn);
if (rt) {
@@ -2294,41 +2601,75 @@ const CBMRegisteredFunc *rust_lookup_method(RustLSPContext *ctx, const char *typ
return rust_lookup_method_depth(ctx, type_qn, member_name, 0);
}
-/* Walk the registry for any method named `member_name` on a type that
- * implements `trait_qn`. We approximate trait impl membership by checking
- * whether the type's `embedded_types` contains `trait_qn` (we treat
- * `impl Trait for Type` as registering the trait QN as an embedded type
- * of the receiver). */
static const CBMRegisteredFunc *rust_lookup_method_in_trait(RustLSPContext *ctx,
const char *trait_qn,
- const char *method_name) {
+ const char *method_name,
+ bool allow_abstract) {
if (!ctx || !trait_qn || !method_name)
return NULL;
const CBMTypeRegistry *reg = ctx->registry;
- /* Trait method is also registered on the trait itself with `receiver_type`
- * set to the trait QN (default impls / signatures). */
- return cbm_registry_lookup_method(reg, trait_qn, method_name);
+ int best_default = -1;
+ int best_any = -1;
+ CBMMethodIter it;
+ cbm_registry_methods(reg, trait_qn, method_name, &it);
+ for (int index; (index = cbm_method_iter_next(&it)) >= 0;) {
+ const CBMRegisteredFunc *candidate = &reg->funcs[index];
+ if (candidate->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) {
+ continue;
+ }
+ if (best_any < 0 || index < best_any) {
+ best_any = index;
+ }
+ if ((candidate->flags & CBM_FUNC_FLAG_RUST_ABSTRACT) == 0 &&
+ (best_default < 0 || index < best_default)) {
+ best_default = index;
+ }
+ }
+ int selected = best_default >= 0 ? best_default : (allow_abstract ? best_any : -1);
+ if (selected >= 0) {
+ return &reg->funcs[selected];
+ }
+ if (reg->fallback) {
+ RustLSPContext fallback_ctx = *ctx;
+ fallback_ctx.registry = reg->fallback;
+ return rust_lookup_method_in_trait(&fallback_ctx, trait_qn, method_name, allow_abstract);
+ }
+ return NULL;
}
-/* For a method call where the receiver is a `dyn Trait` or `impl Trait`,
- * try to resolve through the trait's known impls. Returns the chosen
- * concrete method, the trait method (default impl), or NULL. */
+/* Resolve an ordinary method call with Rust precedence: inherent first,
+ * concrete trait override second, then an unambiguous trait default. */
static const CBMRegisteredFunc *rust_resolve_trait_method(RustLSPContext *ctx,
const char *receiver_type_qn,
const char *method_name,
- int *out_impl_count) {
+ int *out_impl_count,
+ bool *out_trait_dispatch) {
if (out_impl_count)
*out_impl_count = 0;
+ if (out_trait_dispatch)
+ *out_trait_dispatch = false;
if (!ctx || !receiver_type_qn || !method_name)
return NULL;
const CBMTypeRegistry *reg = ctx->registry;
- /* First try inherent method on the receiver itself, following any
- * type aliases (so `std.sync.Arc.clone` resolves through to
- * `alloc.sync.Arc.clone` in the registry). Stays BEFORE the memo check —
- * a colliding real hit is always found (collision guard). */
+ const CBMRegisteredType *receiver_type = cbm_registry_lookup_type(reg, receiver_type_qn);
+ if (receiver_type && receiver_type->is_interface) {
+ const CBMRegisteredFunc *trait_method =
+ rust_lookup_method_in_trait(ctx, receiver_type_qn, method_name, true);
+ if (trait_method && out_impl_count) {
+ *out_impl_count = 2; /* dynamic/bound trait dispatch */
+ }
+ if (trait_method && out_trait_dispatch) {
+ *out_trait_dispatch = true;
+ }
+ return trait_method;
+ }
+
+ /* Ordinary concrete dispatch always prefers an inherent method. Trait
+ * implementations may share the exact same receiver/name/QN, so the
+ * generic registry first-match lookup is not precise enough here. */
const CBMRegisteredFunc *inh =
- cbm_registry_lookup_method_aliased(reg, receiver_type_qn, method_name);
+ rust_registry_lookup_inherent_method_aliased(reg, receiver_type_qn, method_name);
if (inh) {
if (out_impl_count)
*out_impl_count = 1;
@@ -2352,72 +2693,77 @@ static const CBMRegisteredFunc *rust_resolve_trait_method(RustLSPContext *ctx,
}
}
- /* Look at every type whose embedded_types include the receiver_type_qn
- * (treated as a trait): pick the single-impl case. Prefilter to the types whose
- * embedded_types carry a matching BARE name via the registry index; the exact
- * full-QN check below is unchanged, so the result set is identical. */
- const CBMRegisteredFunc *unique = NULL;
- int impls = 0;
- const char *rdot = strrchr(receiver_type_qn, '.');
- const char *rbare = rdot ? rdot + 1 : receiver_type_qn;
- CBMTypeEmbedIter eit;
- cbm_registry_types_by_embedded_bare(reg, rbare, &eit);
- for (int ti; impls < 3 && (ti = cbm_type_embed_iter_next(&eit)) >= 0;) {
- const CBMRegisteredType *t = &reg->types[ti];
- if (!t->embedded_types)
- continue;
- for (int j = 0; t->embedded_types[j]; j++) {
- if (strcmp(t->embedded_types[j], receiver_type_qn) == 0) {
- const CBMRegisteredFunc *mf =
- cbm_registry_lookup_method(reg, t->qualified_name, method_name);
- if (mf) {
- impls++;
- if (impls == 1)
- unique = mf;
+ bool trait_ambiguous = false;
+ const CBMRegisteredFunc *impl_method = rust_registry_lookup_trait_impl_method(
+ reg, receiver_type_qn, NULL, method_name, &trait_ambiguous);
+ if (trait_ambiguous) {
+ if (out_impl_count) {
+ *out_impl_count = 2;
+ }
+ return NULL;
+ }
+ if (impl_method) {
+ if (out_impl_count) {
+ *out_impl_count = 1;
+ }
+ if (out_trait_dispatch) {
+ *out_trait_dispatch = true;
+ }
+ return impl_method;
+ }
+
+ /* No concrete override. Resolve a default through the receiver's exact
+ * type-level impl relations. Two traits contributing the same default
+ * method are ambiguous without a source-level qualification/import proof. */
+ const CBMRegisteredFunc *default_method = NULL;
+ const char *default_trait = NULL;
+ if (receiver_type && receiver_type->embedded_types) {
+ for (int i = 0; receiver_type->embedded_types[i]; i++) {
+ const char *trait_qn = receiver_type->embedded_types[i];
+ if (strncmp(trait_qn, "DerefTarget:", 12) == 0 || strncmp(trait_qn, "Bound:", 6) == 0) {
+ continue;
+ }
+ const CBMRegisteredType *trait_type = cbm_registry_lookup_type(reg, trait_qn);
+ if (!trait_type || !trait_type->is_interface) {
+ continue;
+ }
+ const CBMRegisteredFunc *candidate =
+ rust_lookup_method_in_trait(ctx, trait_qn, method_name, false);
+ if (!candidate) {
+ continue;
+ }
+ if (default_trait && strcmp(default_trait, trait_qn) != 0) {
+ if (out_impl_count) {
+ *out_impl_count = 2;
}
- break;
+ return NULL;
}
+ default_trait = trait_qn;
+ default_method = candidate;
}
}
- if (out_impl_count)
- *out_impl_count = impls;
- if (impls == 1)
- return unique;
- const CBMRegisteredFunc *tm =
- rust_lookup_method_in_trait(ctx, receiver_type_qn, method_name);
- if (nm_active && !tm && impls == 0) {
- cbm_negmemo_insert(&ctx->neg_memo, ctx->arena, nm_key);
+ if (default_method) {
+ if (out_impl_count) {
+ *out_impl_count = 1;
+ }
+ if (out_trait_dispatch) {
+ *out_trait_dispatch = true;
+ }
+ return default_method;
}
- return tm;
-}
-
-// True if `type_qn` implements a trait that declares `method_name` — i.e. a
-// method resolved inherently on the receiver is actually a trait-impl method
-// (lsp_trait_dispatch) rather than a plain inherent one (lsp_method_dispatch).
-// A struct's embedded_types are the traits it implements (the impl-link model
-// rust_resolve_trait_method already relies on), so a declaring trait among them
-// means the method came from `impl Trait for Type`.
-static bool rust_method_is_trait_impl(RustLSPContext *ctx, const char *type_qn,
- const char *method_name) {
- if (!ctx || !type_qn || !method_name)
- return false;
- const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn);
- if (!rt || !rt->embedded_types)
- return false;
- for (int i = 0; rt->embedded_types[i]; i++) {
- if (cbm_registry_lookup_method(ctx->registry, rt->embedded_types[i], method_name))
- return true;
+ if (nm_active) {
+ cbm_negmemo_insert(&ctx->neg_memo, ctx->arena, nm_key);
}
- return false;
+ return NULL;
}
// Find the sole concrete implementer of trait `trait_qn` that declares
// `method_name`, returning that impl's method (NULL if none or 2+), setting
// *out_n to the count (capped at 2). Used for `Trait::method` UFCS so it
// resolves to the concrete impl rather than the trait's own abstract method.
-// Matches the embedded (impl-link) entry by full QN OR bare name, since the
-// link is recorded short in some registry entries and fully-qualified in
-// others; dedups implementers by QN.
+// Type-level impl links are canonical full QNs. Concrete lookup additionally
+// requires the function's exact impl-trait provenance, so an inherent method
+// with the same receiver/name can never satisfy this trait-specific path.
static const CBMRegisteredFunc *rust_find_sole_trait_impl(RustLSPContext *ctx, const char *trait_qn,
const char *method_name, int *out_n) {
if (out_n)
@@ -2435,14 +2781,11 @@ static const CBMRegisteredFunc *rust_find_sole_trait_impl(RustLSPContext *ctx, c
return NULL;
}
}
- const char *tdot = strrchr(trait_qn, '.');
- const char *tbare = tdot ? tdot + 1 : trait_qn;
const CBMRegisteredFunc *first = NULL;
const char *first_qn = NULL;
int n = 0;
- /* Prefilter to types whose embedded_types carry the trait's BARE name; the
- * exact (full-QN OR bare) check below is unchanged. tbare-keyed index captures
- * every original match (a full-QN match implies a bare-name match). */
+ const char *tdot = strrchr(trait_qn, '.');
+ const char *tbare = tdot ? tdot + 1 : trait_qn;
CBMTypeEmbedIter eit;
cbm_registry_types_by_embedded_bare(reg, tbare, &eit);
for (int ti; n < 2 && (ti = cbm_type_embed_iter_next(&eit)) >= 0;) {
@@ -2452,19 +2795,15 @@ static const CBMRegisteredFunc *rust_find_sole_trait_impl(RustLSPContext *ctx, c
bool impls = false;
for (int j = 0; t->embedded_types[j]; j++) {
const char *e = t->embedded_types[j];
- const char *edot = strrchr(e, '.');
- const char *ebare = edot ? edot + 1 : e;
- if (strcmp(e, trait_qn) == 0 || strcmp(ebare, tbare) == 0) {
+ if (strcmp(e, trait_qn) == 0) {
impls = true;
break;
}
}
if (!impls)
continue;
- const CBMRegisteredFunc *mf =
- cbm_registry_lookup_method(reg, t->qualified_name, method_name);
- if (!mf)
- continue;
+ const CBMRegisteredFunc *mf = rust_registry_lookup_trait_impl_method(
+ reg, t->qualified_name, trait_qn, method_name, NULL);
if (!first_qn) {
first = mf;
first_qn = t->qualified_name;
@@ -2543,7 +2882,8 @@ static const char *rust_binop_trait_method(const char *op_text) {
* T::index). Sound-only: we emit nothing when the operand type is unknown,
* primitive, or the type has no such method registered — so we never guess on
* built-in arithmetic. */
-static void rust_emit_operator_call(RustLSPContext *ctx, const CBMType *recv, const char *method) {
+static void rust_emit_operator_call(RustLSPContext *ctx, const CBMType *recv, const char *method,
+ TSNode site) {
if (!recv || !method)
return;
const CBMType *base = recv;
@@ -2558,14 +2898,30 @@ static void rust_emit_operator_call(RustLSPContext *ctx, const CBMType *recv, co
if (!type_qn || is_rust_primitive(type_qn))
return;
int impl_count = 0;
- const CBMRegisteredFunc *m = rust_resolve_trait_method(ctx, type_qn, method, &impl_count);
+ const CBMRegisteredFunc *m = rust_resolve_trait_method(ctx, type_qn, method, &impl_count, NULL);
if (m && m->qualified_name) {
+ uint32_t saved_start = ctx->emit_site_start_byte;
+ uint32_t saved_end = ctx->emit_site_end_byte;
+ uint32_t mapped_start = 0;
+ uint32_t mapped_end = 0;
+ bool mapped = !ts_node_is_null(site) &&
+ rust_map_source_range(ctx, ts_node_start_byte(site), ts_node_end_byte(site),
+ &mapped_start, &mapped_end);
+ ctx->emit_site_start_byte = mapped ? mapped_start : 0;
+ ctx->emit_site_end_byte = mapped ? mapped_end : 0;
rust_emit_resolved_call(ctx, m->qualified_name, "lsp_operator_trait",
CBM_RUST_CONF_OPERATOR);
/* `a + b` is a binary_expression, never a syntactic call node, so the
* extractor produced no CBMCall to pair with the resolved_call above.
- * Inject one so the pipeline emits the CALLS edge. */
- rust_inject_syn_call(ctx, m->qualified_name);
+ * Inject one so the pipeline emits the CALLS edge. Inside a built-in
+ * expression macro rust_emit_resolved_call already injects through
+ * inject_syn_calls; outside it, inject explicitly. Generated
+ * macro_rules! source has no faithful mapped site and stays semantic
+ * only. */
+ if (mapped && ctx->inject_syn_calls == 0)
+ rust_inject_syn_call(ctx, m->qualified_name);
+ ctx->emit_site_start_byte = saved_start;
+ ctx->emit_site_end_byte = saved_end;
}
}
@@ -2586,6 +2942,10 @@ typedef struct RustMacroRule {
int pattern_len;
const char *transcriber_text;
int transcriber_len;
+ uint32_t definition_start_byte;
+ uint32_t definition_end_byte;
+ uint32_t scope_start_byte;
+ uint32_t scope_end_byte;
} RustMacroRule;
/* Strip a single outer pair of matching brackets from a token-tree
@@ -2603,7 +2963,7 @@ static void rust_macro_strip_outer(const char *tt, int len, const char **out_tex
}
static void rust_record_macro_rule(RustLSPContext *ctx, const char *macro_name, TSNode pattern,
- TSNode transcriber) {
+ TSNode transcriber, TSNode definition, TSNode scope) {
if (!ctx || !macro_name || ts_node_is_null(transcriber))
return;
if (ctx->macro_rules_count % 16 == 0) {
@@ -2623,6 +2983,10 @@ static void rust_record_macro_rule(RustLSPContext *ctx, const char *macro_name,
return;
memset(r, 0, sizeof(*r));
r->macro_name = cbm_arena_strdup(ctx->arena, macro_name);
+ r->definition_start_byte = ts_node_start_byte(definition);
+ r->definition_end_byte = ts_node_end_byte(definition);
+ r->scope_start_byte = ts_node_start_byte(scope);
+ r->scope_end_byte = ts_node_end_byte(scope);
/* Cache pattern text for matching at invocation time. */
if (!ts_node_is_null(pattern)) {
@@ -2674,7 +3038,7 @@ static void rust_collect_macro_rules(RustLSPContext *ctx, TSNode root) {
TSNode left = ts_node_child_by_field_name(rule, "left", 4);
TSNode right = ts_node_child_by_field_name(rule, "right", 5);
if (!ts_node_is_null(right)) {
- rust_record_macro_rule(ctx, macro_name, left, right);
+ rust_record_macro_rule(ctx, macro_name, left, right, c, root);
}
}
} else if (strcmp(k, "mod_item") == 0) {
@@ -2685,6 +3049,53 @@ static void rust_collect_macro_rules(RustLSPContext *ctx, TSNode root) {
}
}
+/* macro_rules! uses textual scope: a definition is visible only after its
+ * declaration, inside the containing module. A nested module may shadow an
+ * outer definition; within one scope the latest preceding definition wins.
+ * Every rule belonging to the selected definition shares the same source
+ * coordinates, so expansion can still try its patterns in declaration order. */
+static RustMacroRule *rust_visible_macro_definition(RustLSPContext *ctx, const char *macro_name,
+ TSNode invocation) {
+ if (!ctx || !macro_name || !ctx->macro_rules_arr)
+ return NULL;
+
+ uint32_t position = 0;
+ bool have_position = false;
+ if (ctx->macro_origin_valid) {
+ position = ctx->macro_origin_byte;
+ have_position = true;
+ } else if (ctx->source == ctx->root_source && !ts_node_is_null(invocation)) {
+ position = ts_node_start_byte(invocation);
+ have_position = true;
+ }
+ if (!have_position)
+ return NULL;
+
+ RustMacroRule *best = NULL;
+ uint32_t best_scope_width = UINT32_MAX;
+ for (int i = 0; i < ctx->macro_rules_count; i++) {
+ RustMacroRule *rule = ctx->macro_rules_arr[i];
+ if (!rule || !rule->macro_name || strcmp(rule->macro_name, macro_name) != 0 ||
+ position < rule->definition_end_byte || position < rule->scope_start_byte ||
+ position > rule->scope_end_byte) {
+ continue;
+ }
+ uint32_t scope_width = rule->scope_end_byte - rule->scope_start_byte;
+ if (!best || scope_width < best_scope_width ||
+ (scope_width == best_scope_width &&
+ rule->definition_start_byte > best->definition_start_byte)) {
+ best = rule;
+ best_scope_width = scope_width;
+ }
+ }
+ return best;
+}
+
+static bool rust_has_visible_macro_definition(RustLSPContext *ctx, const char *macro_name,
+ TSNode invocation) {
+ return rust_visible_macro_definition(ctx, macro_name, invocation) != NULL;
+}
+
/* ── Metavar matching + substitution ─────────────────────────────
*
* Real `macro_rules!` semantics in a clean-room subset. We implement
@@ -3118,7 +3529,12 @@ static void rust_expand_user_macro(RustLSPContext *ctx, const char *mname, TSNod
if (ctx->macro_expand_depth >= 8)
return;
- /* Try each rule until one matches; first to match wins. */
+ RustMacroRule *visible = rust_visible_macro_definition(ctx, mname, invocation);
+ if (!visible)
+ return;
+
+ /* Try each rule from the lexically selected definition until one matches;
+ * first matching rule wins. */
RustMacroRule *hit = NULL;
MacroEnv env;
memset(&env, 0, sizeof(env));
@@ -3138,8 +3554,12 @@ static void rust_expand_user_macro(RustLSPContext *ctx, const char *mname, TSNod
for (int i = 0; i < ctx->macro_rules_count; i++) {
RustMacroRule *r = ctx->macro_rules_arr[i];
- if (strcmp(r->macro_name, mname) != 0)
+ if (strcmp(r->macro_name, mname) != 0 ||
+ r->definition_start_byte != visible->definition_start_byte ||
+ r->scope_start_byte != visible->scope_start_byte ||
+ r->scope_end_byte != visible->scope_end_byte) {
continue;
+ }
memset(&env, 0, sizeof(env));
if (r->pattern_text && inv_args &&
macro_pattern_match(r->pattern_text, r->pattern_len, inv_args, inv_args_len, &env)) {
@@ -3197,14 +3617,32 @@ static void rust_expand_user_macro(RustLSPContext *ctx, const char *mname, TSNod
TSNode body = ts_node_child_by_field_name(top, "body", 4);
if (ts_node_is_null(body))
continue;
- /* Swap source so node_text inside reads from `wrapped`. */
+ /* Swap source so node_text inside reads from `wrapped`. A
+ * transcriber is generated source: even when this expansion was
+ * reached through a mapped built-in-macro argument, its offsets
+ * do not have an affine relationship to the invocation tokens. */
const char *saved_source = ctx->source;
int saved_len = ctx->source_len;
+ bool saved_map_active = ctx->site_map_active;
+ uint32_t saved_map_synthetic_start = ctx->site_map_synthetic_start_byte;
+ uint32_t saved_map_synthetic_end = ctx->site_map_synthetic_end_byte;
+ uint32_t saved_map_original_start = ctx->site_map_original_start_byte;
+ uint32_t saved_emit_start = ctx->emit_site_start_byte;
+ uint32_t saved_emit_end = ctx->emit_site_end_byte;
ctx->source = wrapped;
ctx->source_len = (int)strlen(wrapped);
+ ctx->site_map_active = false;
+ ctx->emit_site_start_byte = 0;
+ ctx->emit_site_end_byte = 0;
rust_resolve_calls_in_node(ctx, body);
ctx->source = saved_source;
ctx->source_len = saved_len;
+ ctx->site_map_active = saved_map_active;
+ ctx->site_map_synthetic_start_byte = saved_map_synthetic_start;
+ ctx->site_map_synthetic_end_byte = saved_map_synthetic_end;
+ ctx->site_map_original_start_byte = saved_map_original_start;
+ ctx->emit_site_start_byte = saved_emit_start;
+ ctx->emit_site_end_byte = saved_emit_end;
}
ctx->macro_expand_depth--;
ts_tree_delete(tree);
@@ -3272,8 +3710,8 @@ static void rust_resolve_macro_arg_exprs(RustLSPContext *ctx, TSNode invocation)
* thing parses as one valid expression (a trailing format-spec arg like
* `width = w` would otherwise break statement parsing). Calls inside any
* element are still walked. */
- char *wrapped =
- cbm_arena_sprintf(ctx->arena, "fn __cbm_macro_args() { let _ = (%s); }\n", arg_text);
+ static const char macro_arg_prefix[] = "fn __cbm_macro_args() { let _ = (";
+ char *wrapped = cbm_arena_sprintf(ctx->arena, "%s%s); }\n", macro_arg_prefix, arg_text);
if (!wrapped)
return;
@@ -3301,8 +3739,31 @@ static void rust_resolve_macro_arg_exprs(RustLSPContext *ctx, TSNode invocation)
continue;
const char *saved_source = ctx->source;
int saved_len = ctx->source_len;
+ bool saved_map_active = ctx->site_map_active;
+ uint32_t saved_map_synthetic_start = ctx->site_map_synthetic_start_byte;
+ uint32_t saved_map_synthetic_end = ctx->site_map_synthetic_end_byte;
+ uint32_t saved_map_original_start = ctx->site_map_original_start_byte;
+
+ /* `arg_text` is a byte-for-byte copy of the token tree's inner
+ * text. Translate that inner range through any enclosing
+ * built-in-macro map before switching to the synthetic wrapper.
+ * If the current source is macro_rules!-generated, no faithful
+ * original occurrence exists and the new map stays disabled. */
+ uint32_t inner_start = ts_node_start_byte(args_tt) + (uint32_t)(inner - at);
+ uint32_t inner_end = inner_start + (uint32_t)inner_len;
+ uint32_t original_start = 0;
+ uint32_t original_end = 0;
+ bool mapped = rust_map_source_range(ctx, inner_start, inner_end, &original_start,
+ &original_end);
ctx->source = wrapped;
ctx->source_len = (int)strlen(wrapped);
+ ctx->site_map_active = mapped;
+ if (mapped) {
+ ctx->site_map_synthetic_start_byte = (uint32_t)strlen(macro_arg_prefix);
+ ctx->site_map_synthetic_end_byte =
+ ctx->site_map_synthetic_start_byte + (uint32_t)inner_len;
+ ctx->site_map_original_start_byte = original_start;
+ }
/* The syntactic extractor never produced call nodes for these
* macro-hidden expressions, so resolved_calls emitted here have
* no CBMCall to pair with. Inject matching synthetic calls. */
@@ -3311,6 +3772,10 @@ static void rust_resolve_macro_arg_exprs(RustLSPContext *ctx, TSNode invocation)
ctx->inject_syn_calls--;
ctx->source = saved_source;
ctx->source_len = saved_len;
+ ctx->site_map_active = saved_map_active;
+ ctx->site_map_synthetic_start_byte = saved_map_synthetic_start;
+ ctx->site_map_synthetic_end_byte = saved_map_synthetic_end;
+ ctx->site_map_original_start_byte = saved_map_original_start;
}
ctx->macro_expand_depth--;
}
@@ -3443,6 +3908,9 @@ static void rust_bind_pattern(RustLSPContext *ctx, TSNode pattern, const CBMType
/* Other patterns we ignore for binding purposes. */
}
+static const char *rust_resolve_callable_value(RustLSPContext *ctx, TSNode value,
+ const char **source_name);
+
void rust_process_statement(RustLSPContext *ctx, TSNode node) {
if (ts_node_is_null(node))
return;
@@ -3473,6 +3941,55 @@ void rust_process_statement(RustLSPContext *ctx, TSNode node) {
let_type = cbm_type_unknown();
if (!ts_node_is_null(pat))
rust_bind_pattern(ctx, pat, let_type);
+ if (!ts_node_is_null(pat) && strcmp(ts_node_type(pat), "identifier") == 0 &&
+ !ts_node_is_null(val)) {
+ char *binding_name = rust_node_text(ctx, pat);
+ const char *value_kind = ts_node_type(val);
+ const char *callable_qn = NULL;
+ if (strcmp(value_kind, "identifier") == 0) {
+ char *value_name = rust_node_text(ctx, val);
+ if (value_name && cbm_scope_contains(ctx->current_scope, value_name)) {
+ callable_qn = cbm_scope_lookup_callable(ctx->current_scope, value_name);
+ } else if (value_name) {
+ const char *resolved = rust_resolve_path_expr(ctx, value_name);
+ const CBMRegisteredFunc *function =
+ resolved ? cbm_registry_lookup_func(ctx->registry, resolved) : NULL;
+ if (!function && resolved && ctx->module_qn) {
+ function = cbm_registry_lookup_func(
+ ctx->registry,
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, resolved));
+ }
+ callable_qn = function ? function->qualified_name : NULL;
+ }
+ } else if (strcmp(value_kind, "scoped_identifier") == 0) {
+ char *value_path = rust_node_text(ctx, val);
+ const char *resolved = value_path ? rust_resolve_path_expr(ctx, value_path) : NULL;
+ const CBMRegisteredFunc *function =
+ resolved ? cbm_registry_lookup_func(ctx->registry, resolved) : NULL;
+ callable_qn = function ? function->qualified_name : NULL;
+ }
+ if (binding_name && callable_qn) {
+ cbm_scope_bind_callable(ctx->current_scope, binding_name, let_type, callable_qn);
+ }
+ }
+ return;
+ }
+
+ if (strcmp(kind, "assignment_expression") == 0 ||
+ strcmp(kind, "compound_assignment_expr") == 0) {
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(left) && strcmp(ts_node_type(left), "identifier") == 0) {
+ char *name = rust_node_text(ctx, left);
+ if (name && cbm_scope_contains(ctx->current_scope, name)) {
+ const char *target = NULL;
+ if (strcmp(kind, "assignment_expression") == 0 &&
+ ctx->callable_control_flow_depth == 0 && !ts_node_is_null(right)) {
+ target = rust_resolve_callable_value(ctx, right, NULL);
+ }
+ cbm_scope_update_callable(ctx->current_scope, name, target);
+ }
+ }
return;
}
@@ -3501,6 +4018,30 @@ void rust_process_statement(RustLSPContext *ctx, TSNode node) {
* callee_name, matching how the resolver's short-name comparison works. Only
* used for calls the syntactic extractor cannot see (operator desugaring,
* macro-hidden method calls). */
+static bool rust_map_source_range(const RustLSPContext *ctx, uint32_t start, uint32_t end,
+ uint32_t *mapped_start, uint32_t *mapped_end) {
+ if (!ctx || !mapped_start || !mapped_end || end <= start)
+ return false;
+ if (ctx->site_map_active) {
+ if (start < ctx->site_map_synthetic_start_byte || end > ctx->site_map_synthetic_end_byte) {
+ return false;
+ }
+ *mapped_start =
+ ctx->site_map_original_start_byte + (start - ctx->site_map_synthetic_start_byte);
+ *mapped_end =
+ ctx->site_map_original_start_byte + (end - ctx->site_map_synthetic_start_byte);
+ return *mapped_end > *mapped_start;
+ }
+ /* Only the immutable root buffer has identity coordinates. A
+ * macro_rules! transcriber is reparsed from substituted generated text and
+ * cannot be mapped by a single offset. */
+ if (ctx->source != ctx->root_source)
+ return false;
+ *mapped_start = start;
+ *mapped_end = end;
+ return true;
+}
+
static void rust_inject_syn_call(RustLSPContext *ctx, const char *callee_qn) {
if (!ctx || !ctx->syn_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
@@ -3511,11 +4052,49 @@ static void rust_inject_syn_call(RustLSPContext *ctx, const char *callee_qn) {
CBMCall call = {0};
call.callee_name = cbm_arena_strdup(ctx->arena, short_name);
call.enclosing_func_qn = ctx->enclosing_func_qn;
+ if (ctx->emit_site_end_byte > ctx->emit_site_start_byte) {
+ call.site_start_byte = ctx->emit_site_start_byte;
+ call.site_end_byte = ctx->emit_site_end_byte;
+ call.requires_lsp_resolution = true;
+ }
cbm_calls_push(ctx->syn_calls, ctx->arena, call);
}
-static void rust_emit_resolved_call(RustLSPContext *ctx, const char *callee_qn,
- const char *strategy, float confidence) {
+/* The generic call extractor intentionally filters Rust built-in macro names
+ * that live in its keyword table (`println`, `panic`, ...). Once the LSP has
+ * proven a canonical macro target, restore exactly one source-occurrence
+ * carrier and require that semantic result: a same-named local function must
+ * never win through the legacy fallback. Non-keyword macros already have a
+ * parser carrier, so leave them alone to avoid duplicate cross-pass carriers. */
+static void rust_ensure_known_macro_carrier(RustLSPContext *ctx, const char *macro_name,
+ const char *callee_qn) {
+ if (!ctx || !ctx->syn_calls || !macro_name || !callee_qn ||
+ !cbm_is_keyword(macro_name, CBM_LANG_RUST) ||
+ ctx->emit_site_end_byte <= ctx->emit_site_start_byte) {
+ return;
+ }
+
+ const char *dot = strrchr(callee_qn, '.');
+ const char *short_name = dot ? dot + 1 : callee_qn;
+ for (int i = 0; i < ctx->syn_calls->count; i++) {
+ CBMCall *call = &ctx->syn_calls->items[i];
+ if (!call->callee_name || !call->enclosing_func_qn ||
+ strcmp(call->enclosing_func_qn, ctx->enclosing_func_qn) != 0 ||
+ (strcmp(call->callee_name, macro_name) != 0 &&
+ strcmp(call->callee_name, short_name) != 0) ||
+ call->site_start_byte != ctx->emit_site_start_byte ||
+ call->site_end_byte != ctx->emit_site_end_byte) {
+ continue;
+ }
+ call->requires_lsp_resolution = true;
+ return;
+ }
+ rust_inject_syn_call(ctx, callee_qn);
+}
+
+static void rust_emit_resolved_call_reason(RustLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence,
+ const char *reason) {
if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
CBMResolvedCall rc = {
@@ -3523,14 +4102,115 @@ static void rust_emit_resolved_call(RustLSPContext *ctx, const char *callee_qn,
.callee_qn = callee_qn,
.strategy = strategy,
.confidence = confidence,
- .reason = NULL,
+ .reason = reason,
+ .kind = CBM_RESOLVED_INVOCATION,
+ .site_start_byte = ctx->emit_site_start_byte,
+ .site_end_byte = ctx->emit_site_end_byte,
};
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
- if (ctx->inject_syn_calls > 0) {
+ if (ctx->inject_syn_calls > 0 && ctx->emit_site_end_byte > ctx->emit_site_start_byte) {
rust_inject_syn_call(ctx, callee_qn);
}
}
+static void rust_emit_resolved_call(RustLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence) {
+ rust_emit_resolved_call_reason(ctx, callee_qn, strategy, confidence, NULL);
+}
+
+static bool rust_qn_has_suffix(const char *qualified_name, const char *suffix) {
+ if (!qualified_name || !suffix) {
+ return false;
+ }
+ size_t qn_len = strlen(qualified_name);
+ size_t suffix_len = strlen(suffix);
+ return qn_len >= suffix_len && strcmp(qualified_name + qn_len - suffix_len, suffix) == 0 &&
+ (qn_len == suffix_len || qualified_name[qn_len - suffix_len - 1U] == '.');
+}
+
+/* Resolve only an exact identifier/scoped-path value. No branch, closure, or
+ * other composite expression enters this helper. A suffix fallback is admitted
+ * only for a qualified import path and only when it identifies one free func. */
+static const char *rust_resolve_callable_value(RustLSPContext *ctx, TSNode value,
+ const char **source_name) {
+ const char *kind = ts_node_type(value);
+ if (strcmp(kind, "identifier") != 0 && strcmp(kind, "scoped_identifier") != 0) {
+ return NULL;
+ }
+ char *path = rust_node_text(ctx, value);
+ if (!path || !path[0]) {
+ return NULL;
+ }
+ if (source_name) {
+ *source_name = path;
+ }
+ if (strcmp(kind, "identifier") == 0 && cbm_scope_contains(ctx->current_scope, path)) {
+ return cbm_scope_lookup_callable(ctx->current_scope, path);
+ }
+ const char *resolved = rust_resolve_path_expr(ctx, path);
+ if (!resolved) {
+ return NULL;
+ }
+ const CBMRegisteredFunc *function = cbm_registry_lookup_func(ctx->registry, resolved);
+ if (!function && ctx->module_qn) {
+ function = cbm_registry_lookup_func(
+ ctx->registry, cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, resolved));
+ }
+ if (function && !function->receiver_type) {
+ return function->qualified_name;
+ }
+ if (!strchr(resolved, '.')) {
+ return NULL;
+ }
+ const char *tail = strrchr(resolved, '.');
+ tail = tail ? tail + 1 : resolved;
+ const CBMRegisteredFunc *unique = NULL;
+ int matches = 0;
+ CBMFreeFuncIter iter;
+ cbm_registry_free_funcs_by_short_name(ctx->registry, tail, &iter);
+ for (int index; matches < 2 && (index = cbm_free_func_iter_next(&iter)) >= 0;) {
+ const CBMRegisteredFunc *candidate = &ctx->registry->funcs[index];
+ if (!candidate->receiver_type && candidate->qualified_name &&
+ rust_qn_has_suffix(candidate->qualified_name, resolved)) {
+ unique = candidate;
+ matches++;
+ }
+ }
+ return matches == 1 && unique ? unique->qualified_name : NULL;
+}
+
+static void rust_resolve_callable_argument_references(RustLSPContext *ctx, TSNode arguments) {
+ if (ts_node_is_null(arguments)) {
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(arguments);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode value = ts_node_named_child(arguments, i);
+ const char *source_name = NULL;
+ const char *target = rust_resolve_callable_value(ctx, value, &source_name);
+ if (!target) {
+ continue;
+ }
+ uint32_t start = 0;
+ uint32_t end = 0;
+ if (!rust_map_source_range(ctx, ts_node_start_byte(value), ts_node_end_byte(value), &start,
+ &end)) {
+ continue;
+ }
+ CBMResolvedCall reference = {
+ .caller_qn = ctx->enclosing_func_qn,
+ .callee_qn = target,
+ .strategy = "lsp_callable_value_reference",
+ .confidence = CBM_RUST_CONF_DIRECT,
+ .reason = source_name,
+ .kind = CBM_RESOLVED_CALL_REFERENCE,
+ .site_start_byte = start,
+ .site_end_byte = end,
+ };
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, reference);
+ }
+}
+
static void rust_emit_unresolved_call(RustLSPContext *ctx, const char *expr_text,
const char *reason) {
if (!ctx || !ctx->resolved_calls || !ctx->enclosing_func_qn)
@@ -3541,16 +4221,22 @@ static void rust_emit_unresolved_call(RustLSPContext *ctx, const char *expr_text
.strategy = "lsp_unresolved",
.confidence = 0.0f,
.reason = reason,
+ .kind = CBM_RESOLVED_INVOCATION,
+ .site_start_byte = ctx->emit_site_start_byte,
+ .site_end_byte = ctx->emit_site_end_byte,
};
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
-/* Entry hook: classify a call_expression and emit the best edge we can. */
-static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
+/* Entry hook implementation: classify a call_expression and emit the best
+ * edge we can. The wrapper below establishes the exact original occurrence
+ * for every return path through this function. */
+static void rust_resolve_call_expression_inner(RustLSPContext *ctx, TSNode node) {
TSNode func_node = ts_node_child_by_field_name(node, "function", 8);
TSNode args_node = ts_node_child_by_field_name(node, "arguments", 9);
if (ts_node_is_null(func_node))
return;
+ rust_resolve_callable_argument_references(ctx, args_node);
const char *fk = ts_node_type(func_node);
/* Method call via field_expression. The grammar can also expose
@@ -3605,19 +4291,19 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
if (type_qn) {
int impl_count = 0;
+ bool trait_dispatch = false;
const CBMRegisteredFunc *m =
- rust_resolve_trait_method(ctx, type_qn, mname, &impl_count);
+ rust_resolve_trait_method(ctx, type_qn, mname, &impl_count, &trait_dispatch);
if (m) {
const char *strategy = "lsp_method_dispatch";
float conf = CBM_RUST_CONF_METHOD;
- if (m->receiver_type && strcmp(m->receiver_type, type_qn) != 0) {
+ const CBMRegisteredType *method_owner =
+ m->receiver_type ? cbm_registry_lookup_type(ctx->registry, m->receiver_type)
+ : NULL;
+ if ((m->flags & CBM_FUNC_FLAG_RUST_TRAIT_IMPL) != 0 ||
+ (method_owner && method_owner->is_interface) || trait_dispatch) {
strategy = "lsp_trait_dispatch";
conf = (impl_count == 1) ? CBM_RUST_CONF_TRAIT_SOLE : CBM_RUST_CONF_TRAIT_AMB;
- } else if (rust_method_is_trait_impl(ctx, type_qn, mname)) {
- // Inherently resolved, but the method comes from a trait impl
- // (`impl Trait for Type`) → polymorphic trait dispatch.
- strategy = "lsp_trait_dispatch";
- conf = CBM_RUST_CONF_TRAIT_SOLE;
}
rust_emit_resolved_call(ctx, m->qualified_name, strategy, conf);
(void)args_node;
@@ -3656,7 +4342,7 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
break;
int hop_impls = 0;
const CBMRegisteredFunc *hm =
- rust_resolve_trait_method(ctx, next_qn, mname, &hop_impls);
+ rust_resolve_trait_method(ctx, next_qn, mname, &hop_impls, NULL);
if (hm) {
rust_emit_resolved_call(ctx, hm->qualified_name, "lsp_deref_dispatch",
CBM_RUST_CONF_PROMOTED);
@@ -3678,7 +4364,7 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
if (bound) {
int bimpls = 0;
const CBMRegisteredFunc *bm =
- rust_resolve_trait_method(ctx, bound, mname, &bimpls);
+ rust_resolve_trait_method(ctx, bound, mname, &bimpls, NULL);
if (bm) {
rust_emit_resolved_call(ctx, bm->qualified_name, "lsp_bound_dispatch",
CBM_RUST_CONF_TRAIT_AMB);
@@ -3722,6 +4408,18 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
/* Strip ALL turbofish (`Vec::<i32>::new` → `Vec::new`). */
rust_strip_turbofish(path);
+ if (strcmp(ts_node_type(actual_func), "identifier") == 0) {
+ const char *alias_target = cbm_scope_lookup_callable(ctx->current_scope, path);
+ if (alias_target) {
+ rust_emit_resolved_call_reason(ctx, alias_target, "lsp_callable_alias",
+ CBM_RUST_CONF_DIRECT, path);
+ return;
+ }
+ if (cbm_scope_contains(ctx->current_scope, path)) {
+ return;
+ }
+ }
+
const char *qn = rust_resolve_path_expr(ctx, path);
if (!qn)
return;
@@ -3769,13 +4467,12 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
int tn = 0;
const CBMRegisteredFunc *ti_m =
rust_find_sole_trait_impl(ctx, trait_qn, short_name, &tn);
- if (tn >= 1) {
+ if (tn == 1) {
rust_emit_resolved_call(
ctx,
ti_m ? ti_m->qualified_name
: cbm_arena_sprintf(ctx->arena, "%s.%s", trait_qn, short_name),
- tn == 1 ? "lsp_trait_ufcs" : "lsp_trait_ufcs_amb",
- tn == 1 ? CBM_RUST_CONF_TRAIT_SOLE : CBM_RUST_CONF_TRAIT_AMB);
+ "lsp_trait_ufcs", CBM_RUST_CONF_TRAIT_SOLE);
}
return;
}
@@ -3797,16 +4494,16 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
}
/* Trait method through single-impl dispatch. */
int impls = 0;
- const CBMRegisteredFunc *tm = rust_resolve_trait_method(ctx, head, short_name, &impls);
+ const CBMRegisteredFunc *tm =
+ rust_resolve_trait_method(ctx, head, short_name, &impls, NULL);
if (!tm && ctx->module_qn) {
const char *full_head =
cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, head);
- tm = rust_resolve_trait_method(ctx, full_head, short_name, &impls);
+ tm = rust_resolve_trait_method(ctx, full_head, short_name, &impls, NULL);
}
- if (tm) {
- rust_emit_resolved_call(
- ctx, tm->qualified_name, impls == 1 ? "lsp_trait_ufcs" : "lsp_trait_ufcs_amb",
- impls == 1 ? CBM_RUST_CONF_TRAIT_SOLE : CBM_RUST_CONF_TRAIT_AMB);
+ if (tm && impls == 1) {
+ rust_emit_resolved_call(ctx, tm->qualified_name, "lsp_trait_ufcs",
+ CBM_RUST_CONF_TRAIT_SOLE);
return;
}
}
@@ -3912,6 +4609,24 @@ static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
}
}
+static void rust_resolve_call_expression(RustLSPContext *ctx, TSNode node) {
+ uint32_t saved_start = ctx->emit_site_start_byte;
+ uint32_t saved_end = ctx->emit_site_end_byte;
+ uint32_t mapped_start = 0;
+ uint32_t mapped_end = 0;
+ if (rust_map_source_range(ctx, ts_node_start_byte(node), ts_node_end_byte(node), &mapped_start,
+ &mapped_end)) {
+ ctx->emit_site_start_byte = mapped_start;
+ ctx->emit_site_end_byte = mapped_end;
+ } else {
+ ctx->emit_site_start_byte = 0;
+ ctx->emit_site_end_byte = 0;
+ }
+ rust_resolve_call_expression_inner(ctx, node);
+ ctx->emit_site_start_byte = saved_start;
+ ctx->emit_site_end_byte = saved_end;
+}
+
/* Walk every node in a function body, recording calls and refining scope
* for control-flow constructs that bind variables. */
#define CBM_RUST_EVAL_STEP_CAP 200000 /* per-file budget */
@@ -3999,7 +4714,7 @@ static void rust_resolve_calls_in_node(RustLSPContext *ctx, TSNode node) {
char *op = rust_node_text(ctx, c);
const char *method = rust_binop_trait_method(op);
if (method) {
- rust_emit_operator_call(ctx, rust_eval_expr_type(ctx, left), method);
+ rust_emit_operator_call(ctx, rust_eval_expr_type(ctx, left), method, node);
}
break; /* operator is the sole anonymous child */
}
@@ -4010,73 +4725,101 @@ static void rust_resolve_calls_in_node(RustLSPContext *ctx, TSNode node) {
value = ts_node_named_child(node, 0);
}
if (!ts_node_is_null(value)) {
- rust_emit_operator_call(ctx, rust_eval_expr_type(ctx, value), "index");
+ rust_emit_operator_call(ctx, rust_eval_expr_type(ctx, value), "index", node);
}
}
/* Macro invocation: walk inner tokens for nested calls and try the
* macro-as-function mapping. */
if (strcmp(kind, "macro_invocation") == 0) {
+ uint32_t saved_start = ctx->emit_site_start_byte;
+ uint32_t saved_end = ctx->emit_site_end_byte;
+ uint32_t mapped_start = 0;
+ uint32_t mapped_end = 0;
+ bool mapped = rust_map_source_range(ctx, ts_node_start_byte(node), ts_node_end_byte(node),
+ &mapped_start, &mapped_end);
+ ctx->emit_site_start_byte = mapped ? mapped_start : 0;
+ ctx->emit_site_end_byte = mapped ? mapped_end : 0;
+
+ uint32_t saved_macro_origin = ctx->macro_origin_byte;
+ bool saved_macro_origin_valid = ctx->macro_origin_valid;
+ /* A mapped macro-argument wrapper still identifies an exact original
+ * occurrence; generated macro_rules! transcribers deliberately do not
+ * map and therefore inherit the invocation that established them. */
+ if (mapped) {
+ ctx->macro_origin_byte = mapped_start;
+ ctx->macro_origin_valid = true;
+ }
+
TSNode mname_node = ts_node_child_by_field_name(node, "macro", 5);
if (!ts_node_is_null(mname_node)) {
char *mname = rust_node_text(ctx, mname_node);
if (mname) {
- /* For known std macros emit a synthetic call under their
- * canonical paths so trace tools can see the dependency. */
- const char *path = NULL;
- /* Macros whose arguments are ordinary Rust expressions — their
- * call sites are lost to tree-sitter's macro tokenisation, so
- * re-parse the args to recover calls like `format!("{}",
- * d.label())`. */
- bool expr_arg_macro =
- strcmp(mname, "println") == 0 || strcmp(mname, "eprintln") == 0 ||
- strcmp(mname, "print") == 0 || strcmp(mname, "eprint") == 0 ||
- strcmp(mname, "format") == 0 || strcmp(mname, "write") == 0 ||
- strcmp(mname, "writeln") == 0 || strcmp(mname, "panic") == 0 ||
- strcmp(mname, "assert") == 0 || strcmp(mname, "assert_eq") == 0 ||
- strcmp(mname, "assert_ne") == 0 || strcmp(mname, "debug_assert") == 0 ||
- strcmp(mname, "debug_assert_eq") == 0 ||
- strcmp(mname, "debug_assert_ne") == 0 || strcmp(mname, "dbg") == 0;
- if (expr_arg_macro) {
- rust_resolve_macro_arg_exprs(ctx, node);
- }
- if (strcmp(mname, "println") == 0 || strcmp(mname, "eprintln") == 0 ||
- strcmp(mname, "print") == 0 || strcmp(mname, "eprint") == 0 ||
- strcmp(mname, "format") == 0 || strcmp(mname, "write") == 0 ||
- strcmp(mname, "writeln") == 0) {
- path = cbm_arena_sprintf(ctx->arena, "std.macros.%s", mname);
- } else if (strcmp(mname, "vec") == 0) {
- path = "alloc.vec.vec";
- } else if (strcmp(mname, "panic") == 0) {
- path = "core.panicking.panic";
- } else if (strcmp(mname, "include") == 0) {
- /* `include!` pulls another file in at compile time —
- * we never see the included source. Emit a
- * documentation edge so trace tools can flag it. */
- path = "core.macros.include";
- } else if (strcmp(mname, "include_str") == 0 ||
- strcmp(mname, "include_bytes") == 0) {
- /* Equivalent for data inclusion. */
- path = cbm_arena_sprintf(ctx->arena, "core.macros.%s", mname);
- } else if (strcmp(mname, "env") == 0 || strcmp(mname, "option_env") == 0) {
- /* Compile-time env var read. Specifically: an
- * `include!(concat!(env!("OUT_DIR"), …))` pattern
- * indicates code generated by a build.rs that we
- * cannot see. We surface the env! call so trace
- * tools know to look for OUT_DIR. */
- path = cbm_arena_sprintf(ctx->arena, "core.macros.%s", mname);
- }
- if (path) {
- rust_emit_resolved_call(ctx, path, "lsp_macro", CBM_RUST_CONF_MACRO_KNOWN);
- } else {
- /* User-defined macro: try expanding via macro_rules!. */
+ /* A source-visible macro_rules! definition wins over prelude
+ * macros with the same name. Do this before applying any
+ * built-in argument grammar or canonical std path. */
+ if (rust_has_visible_macro_definition(ctx, mname, node)) {
rust_expand_user_macro(ctx, mname, node);
+ } else {
+ /* For known std macros emit a synthetic call under their
+ * canonical paths so trace tools can see the dependency. */
+ const char *path = NULL;
+ /* Macros whose arguments are ordinary Rust expressions — their
+ * call sites are lost to tree-sitter's macro tokenisation, so
+ * re-parse the args to recover calls like `format!("{}",
+ * d.label())`. */
+ bool expr_arg_macro =
+ strcmp(mname, "println") == 0 || strcmp(mname, "eprintln") == 0 ||
+ strcmp(mname, "print") == 0 || strcmp(mname, "eprint") == 0 ||
+ strcmp(mname, "format") == 0 || strcmp(mname, "write") == 0 ||
+ strcmp(mname, "writeln") == 0 || strcmp(mname, "panic") == 0 ||
+ strcmp(mname, "assert") == 0 || strcmp(mname, "assert_eq") == 0 ||
+ strcmp(mname, "assert_ne") == 0 || strcmp(mname, "debug_assert") == 0 ||
+ strcmp(mname, "debug_assert_eq") == 0 ||
+ strcmp(mname, "debug_assert_ne") == 0 || strcmp(mname, "dbg") == 0;
+ if (expr_arg_macro) {
+ rust_resolve_macro_arg_exprs(ctx, node);
+ }
+ if (strcmp(mname, "println") == 0 || strcmp(mname, "eprintln") == 0 ||
+ strcmp(mname, "print") == 0 || strcmp(mname, "eprint") == 0 ||
+ strcmp(mname, "format") == 0 || strcmp(mname, "write") == 0 ||
+ strcmp(mname, "writeln") == 0) {
+ path = cbm_arena_sprintf(ctx->arena, "std.macros.%s", mname);
+ } else if (strcmp(mname, "vec") == 0) {
+ path = "alloc.vec.vec";
+ } else if (strcmp(mname, "panic") == 0) {
+ path = "core.panicking.panic";
+ } else if (strcmp(mname, "include") == 0) {
+ /* `include!` pulls another file in at compile time —
+ * we never see the included source. Emit a
+ * documentation edge so trace tools can flag it. */
+ path = "core.macros.include";
+ } else if (strcmp(mname, "include_str") == 0 ||
+ strcmp(mname, "include_bytes") == 0) {
+ /* Equivalent for data inclusion. */
+ path = cbm_arena_sprintf(ctx->arena, "core.macros.%s", mname);
+ } else if (strcmp(mname, "env") == 0 || strcmp(mname, "option_env") == 0) {
+ /* Compile-time env var read. Specifically: an
+ * `include!(concat!(env!("OUT_DIR"), …))` pattern
+ * indicates code generated by a build.rs that we
+ * cannot see. We surface the env! call so trace
+ * tools know to look for OUT_DIR. */
+ path = cbm_arena_sprintf(ctx->arena, "core.macros.%s", mname);
+ }
+ if (path) {
+ rust_emit_resolved_call(ctx, path, "lsp_macro", CBM_RUST_CONF_MACRO_KNOWN);
+ rust_ensure_known_macro_carrier(ctx, mname, path);
+ }
}
}
}
TSNode args = ts_node_child_by_field_name(node, "arguments", 9);
if (!ts_node_is_null(args))
rust_walk_macro_tokens(ctx, args);
+ ctx->macro_origin_byte = saved_macro_origin;
+ ctx->macro_origin_valid = saved_macro_origin_valid;
+ ctx->emit_site_start_byte = saved_start;
+ ctx->emit_site_end_byte = saved_end;
/* Don't recurse normally below — we already drilled into args. */
return;
}
@@ -4087,11 +4830,19 @@ static void rust_resolve_calls_in_node(RustLSPContext *ctx, TSNode node) {
strcmp(kind, "if_let_expression") == 0 || strcmp(kind, "while_expression") == 0 ||
strcmp(kind, "while_let_expression") == 0 || strcmp(kind, "for_expression") == 0 ||
strcmp(kind, "match_arm") == 0 || strcmp(kind, "closure_expression") == 0);
+ bool uncertain_callable_flow =
+ strcmp(kind, "if_expression") == 0 || strcmp(kind, "if_let_expression") == 0 ||
+ strcmp(kind, "while_expression") == 0 || strcmp(kind, "while_let_expression") == 0 ||
+ strcmp(kind, "for_expression") == 0 || strcmp(kind, "loop_expression") == 0 ||
+ strcmp(kind, "match_arm") == 0 || strcmp(kind, "closure_expression") == 0;
CBMScope *saved = ctx->current_scope;
if (push_scope) {
ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);
}
+ if (uncertain_callable_flow) {
+ ctx->callable_control_flow_depth++;
+ }
/* if_let / while_let bind a pattern from the value's matched form.
* Modern tree-sitter-rust parses `if let X = y { ... }` as
@@ -4226,6 +4977,9 @@ static void rust_resolve_calls_in_node(RustLSPContext *ctx, TSNode node) {
if (push_scope) {
ctx->current_scope = saved;
}
+ if (uncertain_callable_flow) {
+ ctx->callable_control_flow_depth--;
+ }
}
/* Process a single function: bind parameters / `self`, then walk body. */
@@ -4574,6 +5328,7 @@ void rust_lsp_process_file(RustLSPContext *ctx, TSNode root) {
char *name = rust_node_text(ctx, mname);
if (!name)
continue;
+ cbm_idxmemo_put_if_absent(&ctx->declared_modules, ctx->arena, name, 1);
/* Surface as a synthetic CALLS edge from "<module>" to
* the sibling module so the cross-file pass picks it up
* via short-name fallback. We attribute it to the file's
@@ -4755,31 +5510,42 @@ static void rust_collect_uses(RustLSPContext *ctx, TSNode root) {
/* Build the registry from the per-file `result->defs`, `result->impl_traits`,
* and a Rust prelude seed. */
-static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
- CBMFileResult *result, const char *module_qn, TSNode root,
- const char *source) {
+void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFileResult *result,
+ const char *module_qn, TSNode root, const char *source) {
cbm_registry_init(reg, arena);
cbm_rust_stdlib_register(reg, arena);
- /* Phase A: register every Class/Type/Trait/Function/Method definition. */
+ /* Phase A1: register all type containers first. Trait provenance on a
+ * later method can then be canonicalized without declaration-order or
+ * leaf-first guesses. */
+ CBMIdxMemo type_idx = {0};
+ for (int i = 0; i < reg->type_count; i++) {
+ if (reg->types[i].qualified_name) {
+ cbm_idxmemo_put_if_absent(&type_idx, arena, reg->types[i].qualified_name, i);
+ }
+ }
for (int i = 0; i < result->defs.count; i++) {
CBMDefinition *d = &result->defs.items[i];
- if (!d->qualified_name || !d->name)
+ if (!d->qualified_name || !d->name || !cbm_label_is_type_like(d->label)) {
continue;
-
- // Every type-like container (Class/Struct/Type/Interface/Trait/Enum).
- // Struct included so a Rust `struct Foo` (now labelled "Struct") registers
- // as a type and its `impl Foo` methods/fields resolve.
- if (cbm_label_is_type_like(d->label)) {
- CBMRegisteredType rt;
- memset(&rt, 0, sizeof(rt));
- rt.qualified_name = d->qualified_name;
- rt.short_name = d->name;
- rt.is_interface =
- (strcmp(d->label, "Interface") == 0 || strcmp(d->label, "Trait") == 0);
- cbm_registry_add_type(reg, rt);
}
+ CBMRegisteredType rt;
+ memset(&rt, 0, sizeof(rt));
+ rt.qualified_name = d->qualified_name;
+ rt.short_name = d->name;
+ rt.is_interface = (strcmp(d->label, "Interface") == 0 || strcmp(d->label, "Trait") == 0);
+ cbm_registry_add_type(reg, rt);
+ cbm_idxmemo_put_if_absent(&type_idx, arena, rt.qualified_name, reg->type_count - 1);
+ }
+ RustTraitNameIndex trait_names;
+ rust_trait_name_index_build(&trait_names, arena, reg);
+
+ /* Phase A2: register every Function/Method definition. */
+ for (int i = 0; i < result->defs.count; i++) {
+ CBMDefinition *d = &result->defs.items[i];
+ if (!d->qualified_name || !d->name)
+ continue;
if (d->label && (strcmp(d->label, "Function") == 0 || strcmp(d->label, "Method") == 0)) {
CBMRegisteredFunc rf;
@@ -4787,6 +5553,14 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
rf.qualified_name = d->qualified_name;
rf.short_name = d->name;
rf.min_params = -1;
+ if (d->is_abstract) {
+ rf.flags |= CBM_FUNC_FLAG_RUST_ABSTRACT;
+ }
+ if (d->impl_trait) {
+ rf.flags |= CBM_FUNC_FLAG_RUST_TRAIT_IMPL;
+ rf.impl_trait_qn =
+ rust_canonical_impl_trait(arena, reg, &trait_names, d->impl_trait, module_qn);
+ }
/* Build FUNC sig from return_types / param_types. */
const CBMType **ret_types = NULL;
@@ -4809,7 +5583,14 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
ret_types[1] = NULL;
}
const CBMType **param_types = NULL;
- if (d->param_types) {
+ const char **param_names = d->param_names;
+ if (d->signature_param_types || d->signature_param_count > 0) {
+ RustSignatureParamParserContext parser_ctx = {.module_qn = module_qn};
+ param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ rust_signature_param_type_adapter, &parser_ctx);
+ param_names = NULL;
+ } else if (d->param_types) {
int count = 0;
while (d->param_types[count])
count++;
@@ -4823,17 +5604,19 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
param_types[count] = NULL;
}
}
- rf.signature = cbm_type_func(arena, d->param_names, param_types, ret_types);
+ rf.signature = cbm_type_func(arena, param_names, param_types, ret_types);
if (strcmp(d->label, "Method") == 0 && d->parent_class) {
rf.receiver_type = d->parent_class;
- if (!cbm_registry_lookup_type(reg, rf.receiver_type)) {
+ if (cbm_idxmemo_get(&type_idx, rf.receiver_type) < 0) {
CBMRegisteredType auto_t;
memset(&auto_t, 0, sizeof(auto_t));
auto_t.qualified_name = rf.receiver_type;
const char *dot = strrchr(rf.receiver_type, '.');
auto_t.short_name = dot ? cbm_arena_strdup(arena, dot + 1) : rf.receiver_type;
cbm_registry_add_type(reg, auto_t);
+ cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name,
+ reg->type_count - 1);
}
}
@@ -5001,7 +5784,7 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
(const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
ret_arr[0] = ret;
ret_arr[1] = NULL;
- rf->signature = cbm_type_func(arena, NULL, NULL, ret_arr);
+ rf->signature = cbm_type_func_replace_returns(arena, rf->signature, ret_arr);
break;
}
}
@@ -5173,6 +5956,8 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
* static path lookups via UFCS. */
rf.receiver_type = d->qualified_name;
rf.min_params = -1;
+ rf.flags |= CBM_FUNC_FLAG_RUST_TRAIT_IMPL;
+ rf.impl_trait_qn = di_entry->trait_qn;
const CBMType *ret_t = cbm_type_unknown();
if (dm->return_type) {
if (strcmp(dm->return_type, "bool") == 0) {
@@ -5260,7 +6045,7 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
(const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
ret_arr[0] = ret;
ret_arr[1] = NULL;
- rf->signature = cbm_type_func(arena, NULL, NULL, ret_arr);
+ rf->signature = cbm_type_func_replace_returns(arena, rf->signature, ret_arr);
break;
}
}
@@ -5273,18 +6058,19 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
CBMImplTrait *it = &result->impl_traits.items[i];
if (!it->struct_name || !it->trait_name)
continue;
- const char *recv_qn = cbm_arena_sprintf(arena, "%s.%s", module_qn, it->struct_name);
- const char *trait_qn = strstr(it->trait_name, "::")
- ? convert_path_to_qn(arena, it->trait_name)
- : cbm_arena_sprintf(arena, "%s.%s", module_qn, it->trait_name);
+ const char *recv_qn = it->struct_qn
+ ? it->struct_qn
+ : cbm_arena_sprintf(arena, "%s.%s", module_qn, it->struct_name);
+ const char *trait_qn =
+ rust_canonical_impl_trait(arena, reg, &trait_names, it->trait_name, module_qn);
+ if (!trait_qn) {
+ continue;
+ }
CBMRegisteredType *rt = NULL;
- for (int ti = 0; ti < reg->type_count; ti++) {
- if (reg->types[ti].qualified_name &&
- strcmp(reg->types[ti].qualified_name, recv_qn) == 0) {
- rt = &reg->types[ti];
- break;
- }
+ int32_t type_index = cbm_idxmemo_get(&type_idx, recv_qn);
+ if (type_index >= 0) {
+ rt = &reg->types[type_index];
}
if (!rt) {
CBMRegisteredType auto_t;
@@ -5294,20 +6080,9 @@ static void rust_build_registry_from_defs(CBMArena *arena, CBMTypeRegistry *reg,
auto_t.short_name = dot ? dot + 1 : recv_qn;
cbm_registry_add_type(reg, auto_t);
rt = &reg->types[reg->type_count - 1];
+ cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, reg->type_count - 1);
}
- /* Append trait_qn to embedded_types. */
- int existing = 0;
- if (rt->embedded_types) {
- while (rt->embedded_types[existing])
- existing++;
- }
- const char **new_arr =
- (const char **)cbm_arena_alloc(arena, (existing + 2) * sizeof(const char *));
- for (int j = 0; j < existing; j++)
- new_arr[j] = rt->embedded_types[j];
- new_arr[existing] = trait_qn;
- new_arr[existing + 1] = NULL;
- rt->embedded_types = new_arr;
+ rust_registered_type_add_embedded(arena, rt, trait_qn);
}
}
@@ -5319,7 +6094,7 @@ void cbm_run_rust_lsp_with_manifest(CBMArena *arena, CBMFileResult *result, cons
const char *module_qn = result->module_qn ? result->module_qn : "rust";
CBMTypeRegistry reg;
- rust_build_registry_from_defs(arena, &reg, result, module_qn, root, source);
+ cbm_rust_build_local_registry(arena, &reg, result, module_qn, root, source);
/* Finalize after all per-file adds so lookups during the walk
* use the hash buckets. */
cbm_registry_finalize(&reg);
@@ -5341,11 +6116,6 @@ void cbm_run_rust_lsp_with_manifest(CBMArena *arena, CBMFileResult *result, cons
}
rust_lsp_process_file(&ctx, root);
-
- /* Curated attribute proc-macro synthesis (Option B of the
- * follow-up plan). Runs after the main walk so the synthetic
- * edges are appended without affecting in-walk attribution. */
- cbm_rust_synth_proc_macro_edges(arena, result);
}
void cbm_run_rust_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
@@ -5389,24 +6159,59 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena,
}
}
+ /* Register all type declarations before resolving raw impl-trait names.
+ * This makes provenance independent of source/file ordering. */
for (int i = 0; i < def_count; i++) {
CBMRustLSPDef *d = &defs[i];
if (!d->qualified_name || !d->short_name || !d->label)
continue;
- const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn;
+ if (!cbm_label_is_type_like(d->label)) {
+ continue;
+ }
+ CBMRegisteredType rt;
+ memset(&rt, 0, sizeof(rt));
+ rt.qualified_name = cbm_arena_strdup(arena, d->qualified_name);
+ rt.short_name = cbm_arena_strdup(arena, d->short_name);
+ rt.is_interface =
+ d->is_interface || strcmp(d->label, "Trait") == 0 || strcmp(d->label, "Interface") == 0;
+ cbm_registry_add_type(reg, rt);
+ cbm_idxmemo_put_if_absent(&type_idx, arena, rt.qualified_name, reg->type_count - 1);
+ }
+
+ RustTraitNameIndex trait_names;
+ rust_trait_name_index_build(&trait_names, arena, reg);
- // Every type-like container (Type/Class/Struct/Interface/Trait/Enum).
- // Struct included so Rust structs (now labelled "Struct") register here.
- if (cbm_label_is_type_like(d->label)) {
- CBMRegisteredType rt;
- memset(&rt, 0, sizeof(rt));
- rt.qualified_name = cbm_arena_strdup(arena, d->qualified_name);
- rt.short_name = cbm_arena_strdup(arena, d->short_name);
- rt.is_interface = d->is_interface || strcmp(d->label, "Trait") == 0 ||
- strcmp(d->label, "Interface") == 0;
- cbm_registry_add_type(reg, rt);
- cbm_idxmemo_put_if_absent(&type_idx, arena, rt.qualified_name, reg->type_count - 1);
+ /* Materialize independent impl relations first, including empty impls. */
+ for (int i = 0; i < def_count; i++) {
+ CBMRustLSPDef *d = &defs[i];
+ if (!d->is_rust_impl_relation || !d->receiver_type || !d->trait_qn) {
+ continue;
+ }
+ const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn;
+ const char *trait_qn =
+ rust_canonical_impl_trait(arena, reg, &trait_names, d->trait_qn, def_mod);
+ if (!trait_qn) {
+ continue;
+ }
+ int32_t type_index = cbm_idxmemo_get(&type_idx, d->receiver_type);
+ if (type_index < 0) {
+ CBMRegisteredType auto_t;
+ memset(&auto_t, 0, sizeof(auto_t));
+ auto_t.qualified_name = cbm_arena_strdup(arena, d->receiver_type);
+ const char *dot = strrchr(d->receiver_type, '.');
+ auto_t.short_name = dot ? cbm_arena_strdup(arena, dot + 1) : auto_t.qualified_name;
+ cbm_registry_add_type(reg, auto_t);
+ type_index = reg->type_count - 1;
+ cbm_idxmemo_put_if_absent(&type_idx, arena, auto_t.qualified_name, type_index);
}
+ rust_registered_type_add_embedded(arena, &reg->types[type_index], trait_qn);
+ }
+
+ for (int i = 0; i < def_count; i++) {
+ CBMRustLSPDef *d = &defs[i];
+ if (!d->qualified_name || !d->short_name || !d->label || d->is_rust_impl_relation)
+ continue;
+ const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn;
if (strcmp(d->label, "Function") == 0 || strcmp(d->label, "Method") == 0) {
CBMRegisteredFunc rf;
@@ -5414,6 +6219,14 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena,
rf.qualified_name = cbm_arena_strdup(arena, d->qualified_name);
rf.short_name = cbm_arena_strdup(arena, d->short_name);
rf.min_params = -1;
+ if (d->is_abstract) {
+ rf.flags |= CBM_FUNC_FLAG_RUST_ABSTRACT;
+ }
+ if (d->trait_qn && d->trait_qn[0]) {
+ rf.flags |= CBM_FUNC_FLAG_RUST_TRAIT_IMPL;
+ rf.impl_trait_qn =
+ rust_canonical_impl_trait(arena, reg, &trait_names, d->trait_qn, def_mod);
+ }
/* Build sig from return_types text. */
const CBMType **ret_types = NULL;
@@ -5442,7 +6255,11 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena,
}
ret_types[idx] = NULL;
}
- rf.signature = cbm_type_func(arena, NULL, NULL, ret_types);
+ RustSignatureParamParserContext parser_ctx = {.module_qn = def_mod};
+ const CBMType **param_types = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ rust_signature_param_type_adapter, &parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
rf.receiver_type = cbm_arena_strdup(arena, d->receiver_type);
@@ -5460,25 +6277,17 @@ static void rust_populate_cross_registry(CBMTypeRegistry *reg, CBMArena *arena,
cbm_registry_add_func(reg, rf);
- /* If trait_qn set: encode embedded_type linkage on receiver. */
- if (rf.receiver_type && d->trait_qn && d->trait_qn[0]) {
+ /* Method provenance also carries the type-level relation for
+ * backwards-compatible direct CBMRustLSPDef callers. Production
+ * extraction additionally emits an independent relation record. */
+ if (rf.receiver_type && rf.impl_trait_qn) {
CBMRegisteredType *rt = NULL;
int32_t tix = cbm_idxmemo_get(&type_idx, rf.receiver_type);
if (tix >= 0) {
rt = &reg->types[tix];
}
if (rt) {
- int existing = 0;
- if (rt->embedded_types)
- while (rt->embedded_types[existing])
- existing++;
- const char **new_arr = (const char **)cbm_arena_alloc(
- arena, (existing + 2) * sizeof(const char *));
- for (int j = 0; j < existing; j++)
- new_arr[j] = rt->embedded_types[j];
- new_arr[existing] = cbm_arena_strdup(arena, d->trait_qn);
- new_arr[existing + 1] = NULL;
- rt->embedded_types = new_arr;
+ rust_registered_type_add_embedded(arena, rt, rf.impl_trait_qn);
}
}
}
@@ -5495,10 +6304,12 @@ static void rust_resolve_against_registry(CBMArena *arena, const char *source, i
const char **import_names, const char **import_qns,
int import_count, TSNode root,
const struct CBMCargoManifest *manifest,
- CBMResolvedCallArray *out, CBMFileResult *result) {
+ CBMResolvedCallArray *out,
+ CBMCallArray *synthetic_calls) {
RustLSPContext ctx;
rust_lsp_init(&ctx, arena, source, source_len, reg, module_qn, out);
ctx.cargo_manifest = manifest;
+ ctx.syn_calls = synthetic_calls;
rust_collect_uses(&ctx, root);
for (int i = 0; i < import_count; i++) {
if (import_names[i] && import_qns[i]) {
@@ -5506,15 +6317,13 @@ static void rust_resolve_against_registry(CBMArena *arena, const char *source, i
}
}
rust_lsp_process_file(&ctx, root);
- if (result)
- cbm_rust_synth_proc_macro_edges(arena, result);
}
/* Tier-2: build the Rust cross registry ONCE from all project defs, sealed
* read-only, and shared across every Rust file's resolve (mirrors C/py/cs/ts).
* Converts the pipeline's CBMLSPDef into CBMRustLSPDef inline (same field copy as
- * pass_lsp_cross.c's pxc_lspdefs_to_rust, incl. trait_qn=NULL). module_qn=NULL is
- * byte-identical because all_defs always carry def_module_qn. */
+ * pass_lsp_cross.c's pxc_lspdefs_to_rust, including proven trait provenance).
+ * module_qn=NULL is byte-identical because all_defs always carry def_module_qn. */
CBMTypeRegistry *cbm_rust_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, int def_count) {
if (!arena)
return NULL;
@@ -5536,8 +6345,12 @@ CBMTypeRegistry *cbm_rust_build_cross_registry(CBMArena *arena, CBMLSPDef *defs,
rdefs[i].embedded_types = defs[i].embedded_types;
rdefs[i].field_defs = defs[i].field_defs;
rdefs[i].method_names_str = defs[i].method_names_str;
- rdefs[i].trait_qn = NULL;
+ rdefs[i].signature_param_types = defs[i].signature_param_types;
+ rdefs[i].signature_param_count = defs[i].signature_param_count;
+ rdefs[i].trait_qn = defs[i].trait_qn;
rdefs[i].is_interface = defs[i].is_interface;
+ rdefs[i].is_rust_impl_relation = defs[i].is_rust_impl_relation;
+ rdefs[i].is_abstract = defs[i].is_abstract;
}
}
rust_populate_cross_registry(reg, arena, rdefs, def_count, /*module_qn=*/NULL);
@@ -5552,7 +6365,8 @@ void cbm_run_rust_lsp_cross_with_registry(CBMArena *arena, const char *source, i
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
const struct CBMCargoManifest *manifest,
- CBMResolvedCallArray *out, CBMFileResult *result) {
+ CBMResolvedCallArray *out,
+ CBMCallArray *synthetic_calls) {
if (!source || source_len <= 0 || !out || !reg)
return;
TSParser *parser = NULL;
@@ -5572,7 +6386,7 @@ void cbm_run_rust_lsp_cross_with_registry(CBMArena *arena, const char *source, i
}
TSNode root = ts_tree_root_node(tree);
rust_resolve_against_registry(arena, source, source_len, module_qn, reg, import_names,
- import_qns, import_count, root, manifest, out, result);
+ import_qns, import_count, root, manifest, out, synthetic_calls);
if (owns_tree) {
ts_tree_delete(tree);
if (parser)
@@ -5585,7 +6399,8 @@ void cbm_run_rust_lsp_cross_with_manifest(CBMArena *arena, const char *source, i
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
const struct CBMCargoManifest *manifest,
- CBMResolvedCallArray *out) {
+ CBMResolvedCallArray *out,
+ CBMCallArray *synthetic_calls) {
if (!source || source_len <= 0 || !out)
return;
@@ -5610,19 +6425,8 @@ void cbm_run_rust_lsp_cross_with_manifest(CBMArena *arena, const char *source, i
CBMTypeRegistry reg;
rust_populate_cross_registry(&reg, arena, defs, def_count, module_qn);
- RustLSPContext ctx;
- rust_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, out);
- /* Workspace/dependency awareness for cross-CRATE path routing (#56).
- * Mirrors the single-file path (cbm_run_rust_lsp_with_manifest). NULL
- * when no Cargo.toml was parsed — in-crate resolution is unaffected. */
- ctx.cargo_manifest = manifest;
- rust_collect_uses(&ctx, root);
- for (int i = 0; i < import_count; i++) {
- if (import_names[i] && import_qns[i]) {
- rust_lsp_add_use(&ctx, import_names[i], import_qns[i]);
- }
- }
- rust_lsp_process_file(&ctx, root);
+ rust_resolve_against_registry(arena, source, source_len, module_qn, &reg, import_names,
+ import_qns, import_count, root, manifest, out, synthetic_calls);
if (owns_tree) {
ts_tree_delete(tree);
@@ -5640,7 +6444,7 @@ void cbm_run_rust_lsp_cross(CBMArena *arena, const char *source, int source_len,
TSTree *cached_tree, CBMResolvedCallArray *out) {
cbm_run_rust_lsp_cross_with_manifest(arena, source, source_len, module_qn, defs, def_count,
import_names, import_qns, import_count, cached_tree, NULL,
- out);
+ out, NULL);
}
void cbm_batch_rust_lsp_cross(CBMArena *arena, CBMBatchRustLSPFile *files, int file_count,
@@ -5671,11 +6475,15 @@ void cbm_batch_rust_lsp_cross(CBMArena *arena, CBMBatchRustLSPFile *files, int f
for (int j = 0; j < file_out.count; j++) {
CBMResolvedCall *src = &file_out.items[j];
CBMResolvedCall *dst = &out[f].items[j];
+ memset(dst, 0, sizeof(*dst));
dst->caller_qn = src->caller_qn ? cbm_arena_strdup(arena, src->caller_qn) : NULL;
dst->callee_qn = src->callee_qn ? cbm_arena_strdup(arena, src->callee_qn) : NULL;
dst->strategy = src->strategy ? cbm_arena_strdup(arena, src->strategy) : NULL;
dst->confidence = src->confidence;
dst->reason = src->reason ? cbm_arena_strdup(arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
}
}
diff --git a/internal/cbm/lsp/rust_lsp.h b/internal/cbm/lsp/rust_lsp.h
index f6ddd223b..bc9fcae43 100644
--- a/internal/cbm/lsp/rust_lsp.h
+++ b/internal/cbm/lsp/rust_lsp.h
@@ -55,9 +55,13 @@ typedef struct {
CBMArena *arena;
const char *source;
int source_len;
+ const char *root_source; /* immutable original file buffer */
const CBMTypeRegistry *registry;
CBMScope *current_scope;
+ /* Alias assignments beneath a branch/loop/match/closure cannot establish
+ * one unconditional post-region target, so they clear callable identity. */
+ int callable_control_flow_depth;
/* Negative-lookup memo for the registry-pure resolve cascades (trait
* method / sole-trait-impl / free-func fallback). Active ONLY when the
@@ -75,6 +79,11 @@ typedef struct {
const char **glob_module_qns;
int glob_count;
+ /* Exact names from top-level out-of-line `mod name;` declarations. A
+ * relative scoped type may be project-qualified only when its head is in
+ * this set; coincidentally same-named indexed modules stay external. */
+ CBMIdxMemo declared_modules;
+
/* Module-qualified name for this file (e.g. "<project>.<crate>.foo"). */
const char *module_qn;
@@ -107,6 +116,13 @@ typedef struct {
struct RustMacroRule **macro_rules_arr;
int macro_rules_count;
+ /* Original-file occurrence that established the lexical environment for
+ * the current macro expansion. Nested macro invocations are parsed from a
+ * synthetic transcriber buffer, so their tree-sitter offsets cannot be
+ * used to decide which source-level macro_rules! definition is visible. */
+ uint32_t macro_origin_byte;
+ bool macro_origin_valid;
+
/* Recursion guard for macro expansion. Real macro_rules! can be
* recursive; we cap at 8 nested expansions to keep the walker
* bounded. */
@@ -162,8 +178,9 @@ typedef struct {
* calls hidden inside macro token-trees (`format!("{}", d.label())`) —
* never appear in result->calls because the syntactic extractor cannot
* see them. When this is non-NULL the resolver injects matching synthetic
- * CBMCall entries so those recovered calls become real edges. NULL in the
- * cross-file path (no result available). */
+ * CBMCall entries so those recovered calls become real edges. Cross-file
+ * callers provide a separate output array and merge it into the owning
+ * file result with explicit arena-aware copying. */
CBMCallArray *syn_calls;
/* While >0, rust_emit_resolved_call also injects a matching synthetic
@@ -172,6 +189,19 @@ typedef struct {
* produced a call node. */
int inject_syn_calls;
+ /* Current invocation occurrence in ORIGINAL-file coordinates. Ordinary
+ * source calls use their tree-sitter node directly. Calls recovered by
+ * reparsing built-in macro arguments use the affine map below to translate
+ * the synthetic wrapper's offsets back to the copied token-tree span.
+ * macro_rules! transcriber text is intentionally left unmapped because
+ * substitution is not position-preserving. */
+ uint32_t emit_site_start_byte;
+ uint32_t emit_site_end_byte;
+ bool site_map_active;
+ uint32_t site_map_synthetic_start_byte;
+ uint32_t site_map_synthetic_end_byte;
+ uint32_t site_map_original_start_byte;
+
/* CBM_LSP_DEBUG=1 in env enables verbose stderr trace. */
bool debug;
@@ -235,6 +265,12 @@ void rust_process_statement(RustLSPContext *ctx, TSNode node);
const CBMRegisteredFunc *rust_lookup_method(RustLSPContext *ctx, const char *type_qn,
const char *member_name);
+/* Populate the same per-file registry used by cbm_run_rust_lsp, including
+ * AST-declared return-type refinements. Exposed as a production-used seam for
+ * structural registry regression tests. */
+void cbm_rust_build_local_registry(CBMArena *arena, CBMTypeRegistry *reg, CBMFileResult *result,
+ const char *module_qn, TSNode root, const char *source);
+
/* Entry point — called from `cbm_extract_file()` after the unified
* extractor has filled `result->defs`, `result->imports`, and
* `result->impl_traits`. Builds a per-file registry, parses the `use`
@@ -242,19 +278,6 @@ const CBMRegisteredFunc *rust_lookup_method(RustLSPContext *ctx, const char *typ
void cbm_run_rust_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
TSNode root);
-/* Synthesize call edges for curated attribute proc-macros.
- *
- * For each `CBMDefinition` whose decorators include a known
- * attribute proc-macro (`#[tokio::main]`, `#[tracing::instrument]`,
- * `#[async_trait]`, …), emit synthetic edges from that definition
- * to the helper functions the macro would have injected (e.g.
- * `tokio::runtime::Runtime::new` + `block_on`). The edges carry
- * strategy `lsp_proc_macro` so consumers can distinguish them from
- * direct call attributions.
- *
- * Called automatically from `cbm_run_rust_lsp_with_manifest`. */
-void cbm_rust_synth_proc_macro_edges(CBMArena *arena, CBMFileResult *result);
-
/* Same as `cbm_run_rust_lsp`, but accepts an optional Cargo manifest
* so the resolver can route paths whose head is a workspace member /
* declared dependency. Pass NULL to fall back to the manifest-free
@@ -293,8 +316,12 @@ typedef struct {
const char *embedded_types; /* "|"-separated embedded type QNs */
const char *field_defs; /* "|"-separated "name:type" pairs */
const char *method_names_str; /* "|"-separated method names for traits */
- const char *trait_qn; /* impl Trait for Type → set on Method defs */
+ const char **signature_param_types; /* borrowed ordered parameter texts */
+ int signature_param_count; /* positional entries; "?" is unknown */
+ const char *trait_qn; /* raw impl-trait spelling; uniquely canonicalized */
bool is_interface; /* true for traits */
+ bool is_rust_impl_relation; /* independent type-level impl record */
+ bool is_abstract; /* required trait declaration (no default) */
} CBMRustLSPDef;
/* Run cross-file resolution on a single file. */
@@ -314,7 +341,7 @@ void cbm_run_rust_lsp_cross_with_manifest(CBMArena *arena, const char *source, i
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
const struct CBMCargoManifest *manifest,
- CBMResolvedCallArray *out);
+ CBMResolvedCallArray *out, CBMCallArray *synthetic_calls);
/* Tier-2: build the project-wide Rust cross registry ONCE from all defs, finalize,
* and seal read-only. Shared across every Rust file's resolve (mirrors C/py/cs/ts).
@@ -323,14 +350,16 @@ CBMTypeRegistry *cbm_rust_build_cross_registry(CBMArena *arena, CBMLSPDef *defs,
/* Cross-file Rust resolve using a pre-built shared registry (Tier-2). Skips the
* per-file registry build; just parse + resolve. `manifest` = the same Cargo manifest
- * the per-file path uses (cross-crate #56). `result` may be NULL (the cross path does
- * not synthesise proc-macro edges). Mirrors cbm_run_c_lsp_cross_with_registry. */
+ * the per-file path uses (cross-crate #56). `synthetic_calls` is an optional,
+ * arena-owned output for exact carriers recovered from non-call syntax. Attribute
+ * proc-macros are handled by the graph's DECORATES + USAGE semantic passes, not
+ * by this resolver. */
void cbm_run_rust_lsp_cross_with_registry(CBMArena *arena, const char *source, int source_len,
const char *module_qn, const CBMTypeRegistry *reg,
const char **import_names, const char **import_qns,
int import_count, TSTree *cached_tree,
const struct CBMCargoManifest *manifest,
- CBMResolvedCallArray *out, CBMFileResult *result);
+ CBMResolvedCallArray *out, CBMCallArray *synthetic_calls);
/* Per-file input for batch cross-file Rust LSP processing. */
typedef struct {
diff --git a/internal/cbm/lsp/rust_proc_macros.c b/internal/cbm/lsp/rust_proc_macros.c
index 034b664ea..b5348abdb 100644
--- a/internal/cbm/lsp/rust_proc_macros.c
+++ b/internal/cbm/lsp/rust_proc_macros.c
@@ -1,145 +1,11 @@
-/* rust_proc_macros.c — Curated attribute proc-macro expansion.
+/* Rust procedural-macro policy boundary.
*
- * RUST_LSP_FOLLOWUP §A1 + improvement Option B: extend derive synthesis
- * (already done for #[derive(...)]) to *attribute*-style proc-macros.
+ * Attribute and derive macros are represented by the generic graph semantic
+ * passes as DECORATES plus USAGE. This file intentionally emits no
+ * CBMResolvedCall records: without executing rustc and the proc-macro, helper
+ * invocations such as Runtime::block_on or Span::enter are not source-proven
+ * calls and must not be fabricated.
*
- * We can't run proc-macros (would need rustc). But for the ~20
- * most-used attribute proc-macros we KNOW the expansion shape and can
- * synthesize equivalent calls/impls so the resolver doesn't go blind.
- *
- * Covered:
- * - `#[tokio::main]` / `#[tokio::test]` — wrap fn body in
- * `tokio::runtime::Runtime::new().unwrap().block_on(async { ... })`
- * - `#[async_std::main]` — same shape via async_std executor
- * - `#[async_trait::async_trait]` — methods on the trait become
- * `Pin<Box<dyn Future>>` returning shapes; we just register the
- * method bodies normally (the resolver already handles `async fn`)
- * - `#[derive(thiserror::Error)]` — synthesise `source`, `description`
- * (we already synth via the curated derive table; this just adds
- * `thiserror::Error` to the alias chain)
- * - `#[derive(serde::Serialize|Deserialize)]` — already covered by
- * the curated derive table (alias `serde::Serialize` to
- * `serde.Serialize`)
- * - `#[clap(...)]` field attributes — no synthesis needed; the
- * `#[derive(clap::Parser)]` outer macro handles the impl
- * - `#[tracing::instrument]` — wraps the function body in a span;
- * we synthesise a call to `tracing::span::Span::enter`
- * - `#[rocket::main]`/`#[actix_web::main]` — same shape as tokio
- * - `#[test]` / `#[bench]` — no synthesis; the function body is
- * attributed as-is
- *
- * For each, we register a synthetic "wrapper call" QN per
- * decorator → resolved-call edge so the project's tracing/dependency
- * analyses see what the proc-macro injected. */
-
-#include "../arena.h"
-#include "../cbm.h"
-#include "rust_lsp.h"
-#include <string.h>
-#include <stdio.h>
-
-/* The attribute-decorator table. For each pattern in `decorator` text
- * we emit a *synthetic call edge* attributed to the wrapped function
- * so tracing tools can see the implicit dependency. The synthesis is
- * conservative: we emit only when the decorator text matches one of
- * the curated tokens — anything else is left alone. */
-typedef struct {
- const char* match; /* substring to find in the decorator text */
- const char* edges[6]; /* synthesized callee QNs (NULL-terminated) */
-} RustAttrSynth;
-
-static const RustAttrSynth ATTR_SYNTH[] = {
- {"tokio::main", {
- "tokio.runtime.Runtime.new",
- "tokio.runtime.Runtime.block_on",
- NULL
- }},
- {"tokio::test", {
- "tokio.runtime.Runtime.new",
- "tokio.runtime.Runtime.block_on",
- NULL
- }},
- {"async_std::main", {
- "async_std.task.block_on",
- NULL
- }},
- {"actix_web::main", {
- "actix_web.rt.System.new",
- "actix_web.rt.System.block_on",
- NULL
- }},
- {"actix_rt::main", {
- "actix_rt.System.new",
- "actix_rt.System.block_on",
- NULL
- }},
- {"rocket::main", {
- "rocket.async_main",
- NULL
- }},
- {"rocket::launch", {
- "rocket.launch",
- NULL
- }},
- {"tracing::instrument", {
- "tracing.span.Span.enter",
- NULL
- }},
- {"async_trait", {
- /* The macro wraps each method's return in
- * `Pin<Box<dyn Future<Output = R> + Send>>` — no method-name
- * synthesis needed, just record the boxed-future bridging
- * call so analyses see the async-trait shape. */
- "alloc.boxed.Box.new",
- "core.pin.Pin.new",
- NULL
- }},
- {"wasm_bindgen", {
- "wasm_bindgen.JsValue.from",
- NULL
- }},
- {"napi", {
- "napi.Env.create",
- NULL
- }},
- {"pyo3::pyfunction", {
- "pyo3.Python.with_gil",
- NULL
- }},
- {"pyo3::pymethods", {
- "pyo3.Python.with_gil",
- NULL
- }},
-};
-
-#define ATTR_SYNTH_COUNT (int)(sizeof(ATTR_SYNTH) / sizeof(ATTR_SYNTH[0]))
-
-/* Inspect a definition's decorators and, if any matches a curated
- * proc-macro attribute, emit synthetic edges from that definition's
- * QN to the wrapper functions the macro would have injected. The
- * edges are best-effort and tagged `lsp_proc_macro` so consumers can
- * distinguish them from direct calls. */
-void cbm_rust_synth_proc_macro_edges(CBMArena* arena, CBMFileResult* result) {
- if (!arena || !result) return;
- for (int i = 0; i < result->defs.count; i++) {
- CBMDefinition* d = &result->defs.items[i];
- if (!d->decorators || !d->qualified_name) continue;
- for (int di = 0; d->decorators[di]; di++) {
- const char* dec = d->decorators[di];
- for (int t = 0; t < ATTR_SYNTH_COUNT; t++) {
- const RustAttrSynth* s = &ATTR_SYNTH[t];
- if (!strstr(dec, s->match)) continue;
- /* Emit one resolved call per edge. */
- for (int e = 0; s->edges[e]; e++) {
- CBMResolvedCall rc;
- memset(&rc, 0, sizeof(rc));
- rc.caller_qn = d->qualified_name;
- rc.callee_qn = cbm_arena_strdup(arena, s->edges[e]);
- rc.strategy = "lsp_proc_macro";
- rc.confidence = 0.78f; /* high-but-not-direct */
- cbm_resolvedcall_push(&result->resolved_calls, arena, rc);
- }
- }
- }
- }
-}
+ * Kept as a separate compilation unit because lsp_all.c includes the historic
+ * module directly; the empty policy boundary also makes accidental synthesis
+ * conspicuous in review. */
diff --git a/internal/cbm/lsp/scope.c b/internal/cbm/lsp/scope.c
index f2cbcc6f0..4d8e63b0a 100644
--- a/internal/cbm/lsp/scope.c
+++ b/internal/cbm/lsp/scope.c
@@ -33,7 +33,8 @@ static CBMScopeChunk* alloc_chunk(CBMScope* scope) {
return c;
}
-void cbm_scope_bind(CBMScope* scope, const char* name, const CBMType* type) {
+static void cbm_scope_bind_value(CBMScope *scope, const char *name, const CBMType *type,
+ const char *callable_qn) {
if (!scope || !name) {
return;
}
@@ -41,6 +42,7 @@ void cbm_scope_bind(CBMScope* scope, const char* name, const CBMType* type) {
for (int i = 0; i < c->used; i++) {
if (c->bindings[i].name && strcmp(c->bindings[i].name, name) == 0) {
c->bindings[i].type = type;
+ c->bindings[i].callable_qn = callable_qn;
return;
}
}
@@ -54,9 +56,19 @@ void cbm_scope_bind(CBMScope* scope, const char* name, const CBMType* type) {
}
head->bindings[head->used].name = name;
head->bindings[head->used].type = type;
+ head->bindings[head->used].callable_qn = callable_qn;
head->used++;
}
+void cbm_scope_bind(CBMScope *scope, const char *name, const CBMType *type) {
+ cbm_scope_bind_value(scope, name, type, NULL);
+}
+
+void cbm_scope_bind_callable(CBMScope *scope, const char *name, const CBMType *type,
+ const char *callable_qn) {
+ cbm_scope_bind_value(scope, name, type, callable_qn);
+}
+
const CBMType* cbm_scope_lookup(const CBMScope* scope, const char* name) {
if (!name) {
return cbm_type_unknown();
@@ -72,3 +84,52 @@ const CBMType* cbm_scope_lookup(const CBMScope* scope, const char* name) {
}
return cbm_type_unknown();
}
+
+bool cbm_scope_contains(const CBMScope *scope, const char *name) {
+ if (!name) {
+ return false;
+ }
+ for (const CBMScope *s = scope; s != NULL; s = s->parent) {
+ for (const CBMScopeChunk *c = s->chunks; c != NULL; c = c->next) {
+ for (int i = 0; i < c->used; i++) {
+ if (c->bindings[i].name && strcmp(c->bindings[i].name, name) == 0) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+const char *cbm_scope_lookup_callable(const CBMScope *scope, const char *name) {
+ if (!name) {
+ return NULL;
+ }
+ for (const CBMScope *s = scope; s != NULL; s = s->parent) {
+ for (const CBMScopeChunk *c = s->chunks; c != NULL; c = c->next) {
+ for (int i = 0; i < c->used; i++) {
+ if (c->bindings[i].name && strcmp(c->bindings[i].name, name) == 0) {
+ return c->bindings[i].callable_qn;
+ }
+ }
+ }
+ }
+ return NULL;
+}
+
+bool cbm_scope_update_callable(CBMScope *scope, const char *name, const char *callable_qn) {
+ if (!name) {
+ return false;
+ }
+ for (CBMScope *s = scope; s != NULL; s = s->parent) {
+ for (CBMScopeChunk *c = s->chunks; c != NULL; c = c->next) {
+ for (int i = 0; i < c->used; i++) {
+ if (c->bindings[i].name && strcmp(c->bindings[i].name, name) == 0) {
+ c->bindings[i].callable_qn = callable_qn;
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
diff --git a/internal/cbm/lsp/scope.h b/internal/cbm/lsp/scope.h
index 5aa0498d7..859079d09 100644
--- a/internal/cbm/lsp/scope.h
+++ b/internal/cbm/lsp/scope.h
@@ -8,6 +8,11 @@
typedef struct {
const char* name;
const CBMType* type;
+ /* Exact callable value carried by this lexical binding, or NULL when the
+ * binding is not proven to denote one callable. This is deliberately
+ * identity metadata rather than another CBMType kind: aliases need both
+ * their ordinary type and the graph QN of the value they reference. */
+ const char *callable_qn;
} CBMVarBinding;
#define CBM_SCOPE_CHUNK_BINDINGS 16
@@ -56,6 +61,20 @@ static inline int cbm_lsp_max_walk_depth(void) {
CBMScope* cbm_scope_push(CBMArena* a, CBMScope* current);
CBMScope* cbm_scope_pop(CBMScope* scope);
void cbm_scope_bind(CBMScope* scope, const char* name, const CBMType* type);
+/* Bind a value whose identity is one exact callable. A later ordinary
+ * cbm_scope_bind of the same name clears this identity, so reassignment fails
+ * closed instead of leaking a stale alias target. */
+void cbm_scope_bind_callable(CBMScope *scope, const char *name, const CBMType *type,
+ const char *callable_qn);
const CBMType* cbm_scope_lookup(const CBMScope* scope, const char* name);
+/* True when any lexical frame contains name, even when its type is UNKNOWN. */
+bool cbm_scope_contains(const CBMScope *scope, const char *name);
+/* Return the exact callable QN from the nearest binding. A nearer ordinary
+ * binding shadows a parent's callable and therefore returns NULL. */
+const char *cbm_scope_lookup_callable(const CBMScope *scope, const char *name);
+/* Replace (or clear with NULL) callable identity on the nearest existing
+ * lexical binding. Returns false when name is unbound. This is for assignment;
+ * declarations should continue to use cbm_scope_bind[_callable]. */
+bool cbm_scope_update_callable(CBMScope *scope, const char *name, const char *callable_qn);
#endif // CBM_LSP_SCOPE_H
diff --git a/internal/cbm/lsp/ts_lsp.c b/internal/cbm/lsp/ts_lsp.c
index 556ae8f2e..912e0dcfc 100644
--- a/internal/cbm/lsp/ts_lsp.c
+++ b/internal/cbm/lsp/ts_lsp.c
@@ -145,28 +145,57 @@ static TSNode find_first_kind(TSNode node, const char *kind) {
return null_node;
}
-static void ts_emit_resolved_call(TSLSPContext *ctx, const char *callee_qn, const char *strategy,
- float confidence) {
+static void ts_emit_resolved_call_at(TSLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site) {
if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = callee_qn;
rc.strategy = strategy ? strategy : "lsp_ts";
rc.confidence = confidence;
rc.reason = NULL;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
-static void ts_emit_unresolved_call(TSLSPContext *ctx, const char *expr_text, const char *reason) {
+static void ts_emit_resolved_reference(TSLSPContext *ctx, const char *callee_qn,
+ const char *strategy, float confidence, TSNode site) {
+ if (!ctx || !ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn ||
+ ts_node_is_null(site)) {
+ return;
+ }
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = callee_qn;
+ rc.strategy = strategy ? strategy : "lsp_ts_value_reference";
+ rc.confidence = confidence;
+ rc.reason = NULL;
+ rc.kind = CBM_RESOLVED_CALL_REFERENCE;
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+static void ts_emit_unresolved_call_at(TSLSPContext *ctx, const char *expr_text, const char *reason,
+ TSNode site) {
if (!ctx || !ctx->resolved_calls || !ctx->enclosing_func_qn)
return;
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
rc.caller_qn = ctx->enclosing_func_qn;
rc.callee_qn = expr_text ? expr_text : "?";
rc.strategy = "lsp_unresolved";
rc.confidence = 0.0f;
rc.reason = reason;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
}
@@ -638,6 +667,17 @@ static const CBMType *parse_ts_type_text(CBMArena *arena, const char *text, cons
return cbm_type_named(arena, cbm_arena_strndup(arena, text, len));
}
+typedef struct {
+ const char *module_qn;
+} CBMTSLSPSignatureParserContext;
+
+static const CBMType *cbm_ts_lsp_parse_signature_param_text(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ const CBMTSLSPSignatureParserContext *ctx = (const CBMTSLSPSignatureParserContext *)parser_ctx;
+ const char *module_qn = ctx && ctx->module_qn ? ctx->module_qn : "";
+ return parse_ts_type_text(arena, text, module_qn);
+}
+
// Return param-type CBMType array from a CBMDefinition's param_types text array.
static const CBMType **parse_param_types_array(CBMArena *arena, const char **texts,
const char *module_qn) {
@@ -1242,14 +1282,110 @@ static const CBMType *simplify_type(TSLSPContext *ctx, const CBMType *t) {
return t;
}
+/* cbm_scope_lookup intentionally collapses an absent binding and an UNKNOWN
+ * binding to the same type. Reference resolution needs the stronger question:
+ * even an untyped local/parameter shadows an import and must block promotion. */
+static const CBMScope *ts_scope_binding_owner(const CBMScope *scope, const char *name) {
+ if (!name) {
+ return NULL;
+ }
+ for (const CBMScope *s = scope; s; s = s->parent) {
+ for (const CBMScopeChunk *chunk = s->chunks; chunk; chunk = chunk->next) {
+ for (int i = 0; i < chunk->used; i++) {
+ if (chunk->bindings[i].name && strcmp(chunk->bindings[i].name, name) == 0) {
+ return s;
+ }
+ }
+ }
+ }
+ return NULL;
+}
+
+static bool ts_scope_has_binding(const CBMScope *scope, const char *name) {
+ return ts_scope_binding_owner(scope, name) != NULL;
+}
+
+static const char *ts_import_symbol_qn(TSLSPContext *ctx, const char *module_qn, const char *name) {
+ if (!ctx || !module_qn || !name) {
+ return NULL;
+ }
+ size_t module_len = strlen(module_qn);
+ size_t name_len = strlen(name);
+ if (module_len > name_len + 1 && module_qn[module_len - name_len - 1] == '.' &&
+ strcmp(module_qn + module_len - name_len, name) == 0) {
+ return module_qn;
+ }
+ return cbm_arena_sprintf(ctx->arena, "%s.%s", module_qn, name);
+}
+
+/* Same-file function values use only the exact current-module QN. No short-name,
+ * suffix, overload-arity, or project-wide uniqueness fallback is admissible. */
+static const CBMRegisteredFunc *ts_exact_same_module_function(TSLSPContext *ctx, const char *name) {
+ if (!ctx || !ctx->registry || !ctx->module_qn || !name ||
+ ts_scope_has_binding(ctx->current_scope, name)) {
+ return NULL;
+ }
+ const char *full_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, name);
+ return full_qn ? cbm_registry_lookup_func(ctx->registry, full_qn) : NULL;
+}
+
+/* Return a function only when the local import binding maps to one unambiguous
+ * module and that module contains the exact local-name QN. Aliases whose export
+ * name is unavailable in CBMImport deliberately fail closed and remain USAGE. */
+static const CBMRegisteredFunc *ts_exact_imported_function(TSLSPContext *ctx, const char *name) {
+ if (!ctx || !ctx->registry || !name || ts_scope_has_binding(ctx->current_scope, name)) {
+ return NULL;
+ }
+ const char *matched_module = NULL;
+ for (int i = 0; i < ctx->import_count; i++) {
+ const char *local = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *module_qn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ if (!local || !module_qn || strcmp(local, name) != 0) {
+ continue;
+ }
+ if (matched_module && strcmp(matched_module, module_qn) != 0) {
+ return NULL;
+ }
+ matched_module = module_qn;
+ }
+ if (!matched_module) {
+ return NULL;
+ }
+ const char *full_qn = ts_import_symbol_qn(ctx, matched_module, name);
+ return full_qn ? cbm_registry_lookup_func(ctx->registry, full_qn) : NULL;
+}
+
+static void ts_block_shadowed_reference_usage(TSLSPContext *ctx, const char *name, TSNode site) {
+ if (!ctx || !ctx->usages || !name || !ctx->enclosing_func_qn || ts_node_is_null(site)) {
+ return;
+ }
+ const CBMScope *binding_scope = ts_scope_binding_owner(ctx->current_scope, name);
+ if (!binding_scope) {
+ return;
+ }
+ uint32_t start = ts_node_start_byte(site);
+ uint32_t end = ts_node_end_byte(site);
+ for (int i = 0; i < ctx->usages->count; i++) {
+ CBMUsage *usage = &ctx->usages->items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->may_be_call_reference && usage->ref_name &&
+ usage->enclosing_func_qn && strcmp(usage->ref_name, name) == 0 &&
+ strcmp(usage->enclosing_func_qn, ctx->enclosing_func_qn) == 0 &&
+ usage->site_start_byte == start && usage->site_end_byte == end) {
+ usage->semantic_reference_blocked = true;
+ usage->semantic_reference_local_shadow = binding_scope->parent != NULL;
+ return;
+ }
+ }
+}
+
static const CBMType *type_of_identifier(TSLSPContext *ctx, const char *name) {
if (!ctx || !name)
return cbm_type_unknown();
// Scope lookup (params, locals).
const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);
- if (t && !cbm_type_is_unknown(t))
- return t;
+ if (ts_scope_has_binding(ctx->current_scope, name))
+ return t ? t : cbm_type_unknown();
// Imports: bare identifier matching an import binding. Compute the full symbol QN
// and look it up in the registry. If it's a registered func, return its signature;
@@ -1261,17 +1397,9 @@ static const CBMType *type_of_identifier(TSLSPContext *ctx, const char *name) {
if (!local || !mqn || strcmp(local, name) != 0)
continue;
- // Construct the full symbol QN: if mqn already ends in ".name" use it; else
- // append ".name". This matches `resolve_type_with_imports`' convention.
- size_t mqn_len = strlen(mqn);
- size_t name_len = strlen(name);
- const char *full_qn;
- if (mqn_len > name_len + 1 && mqn[mqn_len - name_len - 1] == '.' &&
- strcmp(mqn + mqn_len - name_len, name) == 0) {
- full_qn = mqn;
- } else {
- full_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, name);
- }
+ // Construct the full symbol QN using the same convention as exact
+ // imported function-value resolution.
+ const char *full_qn = ts_import_symbol_qn(ctx, mqn, name);
// Try the symbol lookup precedence: registered func, then registered type.
const CBMRegisteredFunc *f = cbm_registry_lookup_func(ctx->registry, full_qn);
@@ -1633,6 +1761,201 @@ static const CBMRegisteredFunc *lookup_method(TSLSPContext *ctx, const CBMType *
return NULL;
}
+/* Select one overload for both edge emission and call-expression return
+ * typing. The first lookup preserves wrapper/alias/inheritance/template/union
+ * traversal; its receiver identifies the concrete overload set. */
+static const CBMRegisteredFunc *ts_lookup_method_for_call(TSLSPContext *ctx, const CBMType *recv,
+ const char *method_name, TSNode args) {
+ const CBMRegisteredFunc *fallback = lookup_method(ctx, recv, method_name);
+ if (!fallback || !fallback->receiver_type)
+ return fallback;
+
+ int arg_count = ts_node_is_null(args) ? 0 : (int)ts_node_named_child_count(args);
+ const CBMRegisteredFunc *selected = NULL;
+ if (arg_count > 0 && arg_count <= 16) {
+ const CBMType *arg_types[16] = {0};
+ for (int i = 0; i < arg_count; i++) {
+ arg_types[i] = ts_eval_expr_type(ctx, ts_node_named_child(args, (uint32_t)i));
+ }
+ selected = cbm_registry_lookup_method_by_types(ctx->registry, fallback->receiver_type,
+ method_name, arg_types, arg_count);
+ } else {
+ selected = cbm_registry_lookup_method_by_args(ctx->registry, fallback->receiver_type,
+ method_name, arg_count);
+ }
+ return selected ? selected : fallback;
+}
+
+/* Select a free function/namespace export by the same ordered argument types
+ * used for method overloads. Edge emission and expression return typing must
+ * share this decision; otherwise the graph can point at one overload while a
+ * chained call is typed from another. */
+static const CBMRegisteredFunc *ts_lookup_symbol_for_call(TSLSPContext *ctx, const char *module_qn,
+ const char *symbol_name, TSNode args) {
+ if (!ctx || !ctx->registry || !module_qn || !symbol_name)
+ return NULL;
+
+ /* Import maps may carry either a module QN or an already-qualified symbol
+ * QN. The registry overload APIs accept the former, so strip one exact
+ * trailing `.symbol` before lookup instead of producing x.symbol.symbol. */
+ const char *lookup_module = module_qn;
+ size_t module_len = strlen(module_qn);
+ size_t symbol_len = strlen(symbol_name);
+ if (module_len > symbol_len + 1 && module_qn[module_len - symbol_len - 1] == '.' &&
+ strcmp(module_qn + module_len - symbol_len, symbol_name) == 0) {
+ lookup_module = cbm_arena_strndup(ctx->arena, module_qn, module_len - symbol_len - 1);
+ }
+
+ int arg_count = ts_node_is_null(args) ? 0 : (int)ts_node_named_child_count(args);
+ const CBMRegisteredFunc *selected = NULL;
+ if (arg_count > 0 && arg_count <= 16) {
+ const CBMType *arg_types[16] = {0};
+ for (int i = 0; i < arg_count; i++)
+ arg_types[i] = ts_eval_expr_type(ctx, ts_node_named_child(args, (uint32_t)i));
+ selected = cbm_registry_lookup_symbol_by_types(ctx->registry, lookup_module, symbol_name,
+ arg_types, arg_count);
+ }
+ if (!selected) {
+ selected = cbm_registry_lookup_symbol_by_args(ctx->registry, lookup_module, symbol_name,
+ arg_count);
+ }
+ return selected;
+}
+
+/* Map one local import binding to its module. Duplicate bindings from
+ * different modules are ambiguous and deliberately fail closed. */
+static const char *ts_import_module_for_local(const TSLSPContext *ctx, const char *local_name,
+ bool *out_matched) {
+ if (out_matched)
+ *out_matched = false;
+ if (!ctx || !local_name)
+ return NULL;
+ const char *matched = NULL;
+ for (int i = 0; i < ctx->import_count; i++) {
+ const char *local = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
+ const char *module_qn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
+ if (!local || !module_qn || strcmp(local, local_name) != 0)
+ continue;
+ if (out_matched)
+ *out_matched = true;
+ if (matched && strcmp(matched, module_qn) != 0)
+ return NULL;
+ matched = module_qn;
+ }
+ return matched;
+}
+
+static const CBMRegisteredFunc *ts_lookup_namespace_call(TSLSPContext *ctx, const char *object_name,
+ const char *method_name, TSNode args,
+ bool *out_is_import) {
+ if (out_is_import)
+ *out_is_import = false;
+ bool import_matched = false;
+ const char *import_module = ts_import_module_for_local(ctx, object_name, &import_matched);
+ if (out_is_import)
+ *out_is_import = import_matched;
+ if (import_matched) {
+ /* An import binding lexically shadows a same-named local namespace.
+ * Ambiguous imports and missing imported symbols both fail closed. */
+ return import_module ? ts_lookup_symbol_for_call(ctx, import_module, method_name, args)
+ : NULL;
+ }
+ /* TypeScript namespaces are module-like lexical scopes. Inside `namespace
+ * App`, `Utils.fn()` addresses App.Utils.fn, not a typed instance named
+ * Utils. Require an exact registered function so ordinary unknown objects
+ * still fall through to receiver-type dispatch. */
+ if (ctx && ctx->module_qn && object_name) {
+ const char *local_module =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, object_name);
+ return local_module ? ts_lookup_symbol_for_call(ctx, local_module, method_name, args)
+ : NULL;
+ }
+ return NULL;
+}
+
+/* Preserve the generic receiver substitution historically performed by
+ * lookup_member_type(). Only substitute when the selected method belongs to
+ * that template owner; inherited methods may declare unrelated type params. */
+static const CBMType *ts_method_signature_for_receiver(TSLSPContext *ctx, const CBMType *recv,
+ const CBMRegisteredFunc *method) {
+ if (!method || !method->signature)
+ return NULL;
+ const CBMType *base = simplify_type(ctx, recv);
+ base = base ? unwrap_passthrough_template(base) : NULL;
+ if (!base || base->kind != CBM_TYPE_TEMPLATE || !base->data.template_type.template_args) {
+ return method->signature;
+ }
+
+ const CBMRegisteredType *registered =
+ cbm_registry_lookup_type(ctx->registry, base->data.template_type.template_name);
+ if (!registered || !registered->qualified_name || !registered->type_param_names ||
+ !method->receiver_type || strcmp(registered->qualified_name, method->receiver_type) != 0) {
+ return method->signature;
+ }
+ const CBMType *substituted =
+ cbm_type_substitute(ctx->arena, method->signature, registered->type_param_names,
+ base->data.template_type.template_args);
+ return substituted ? substituted : method->signature;
+}
+
+/* Return the function signature selected at this call site. This is the
+ * single boundary shared by chained return typing and contextual callback
+ * typing; both must observe the same overload as edge resolution. */
+static const CBMType *ts_signature_for_call(TSLSPContext *ctx, TSNode function, TSNode args) {
+ if (!ctx || ts_node_is_null(function))
+ return NULL;
+
+ if (node_kind_is(function, "member_expression")) {
+ TSNode object = ts_node_child_by_field_name(function, "object", TS_LSP_FIELD_LEN("object"));
+ TSNode property =
+ ts_node_child_by_field_name(function, "property", TS_LSP_FIELD_LEN("property"));
+ if (ts_node_is_null(object) || ts_node_is_null(property))
+ return NULL;
+
+ char *method_name = node_text(ctx, property);
+ if (!method_name)
+ return NULL;
+
+ if (node_kind_is(object, "identifier")) {
+ char *object_name = node_text(ctx, object);
+ if (!ts_scope_has_binding(ctx->current_scope, object_name)) {
+ bool is_import = false;
+ const CBMRegisteredFunc *namespace_func =
+ ts_lookup_namespace_call(ctx, object_name, method_name, args, &is_import);
+ if (namespace_func || is_import)
+ return namespace_func ? namespace_func->signature : NULL;
+ }
+ }
+
+ const CBMType *recv = ts_eval_expr_type(ctx, object);
+ const CBMRegisteredFunc *method = ts_lookup_method_for_call(ctx, recv, method_name, args);
+ const CBMType *signature = ts_method_signature_for_receiver(ctx, recv, method);
+ /* Callable fields still use ordinary member typing. Reuse the receiver
+ * already evaluated above so deep fluent chains remain linear. */
+ return signature ? signature : lookup_member_type(ctx, recv, method_name);
+ }
+
+ if (node_kind_is(function, "identifier")) {
+ char *name = node_text(ctx, function);
+ if (name && ts_scope_has_binding(ctx->current_scope, name))
+ return type_of_identifier(ctx, name);
+ if (name) {
+ const CBMRegisteredFunc *registered = NULL;
+ if (ctx->module_qn)
+ registered = ts_lookup_symbol_for_call(ctx, ctx->module_qn, name, args);
+ if (!registered) {
+ const char *module_qn = ts_import_module_for_local(ctx, name, NULL);
+ if (module_qn)
+ registered = ts_lookup_symbol_for_call(ctx, module_qn, name, args);
+ }
+ if (registered)
+ return registered->signature;
+ }
+ }
+
+ return ts_eval_expr_type(ctx, function);
+}
+
// Pull the underlying return type out of a FUNC signature, collapsing single-element
// return arrays to that element.
static const CBMType *return_type_of(CBMArena *arena, const CBMType *sig) {
@@ -1730,7 +2053,9 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {
} else if (strcmp(kind, "call_expression") == 0) {
TSNode fn = ts_node_child_by_field_name(node, "function", TS_LSP_FIELD_LEN("function"));
if (!ts_node_is_null(fn)) {
- const CBMType *fn_type = ts_eval_expr_type(ctx, fn);
+ TSNode call_args =
+ ts_node_child_by_field_name(node, "arguments", TS_LSP_FIELD_LEN("arguments"));
+ const CBMType *fn_type = ts_signature_for_call(ctx, fn, call_args);
if (ctx->debug) {
fprintf(stderr, "[ts_lsp] eval call_expression: fn_kind=%s fn_type_kind=%d\n",
ts_node_type(fn), fn_type ? (int)fn_type->kind : -1);
@@ -1760,8 +2085,7 @@ const CBMType *ts_eval_expr_type(TSLSPContext *ctx, TSNode node) {
// inferTypeArguments — single-pass, argument-driven.
if (result && result->kind == CBM_TYPE_TYPE_PARAM &&
fn_type->data.func.param_types) {
- TSNode args = ts_node_child_by_field_name(node, "arguments",
- TS_LSP_FIELD_LEN("arguments"));
+ TSNode args = call_args;
if (!ts_node_is_null(args)) {
// Build a list of inferred type-param names + arg types.
const char *inf_names[8] = {0};
@@ -2263,17 +2587,86 @@ void ts_process_statement(TSLSPContext *ctx, TSNode node) {
// ── Call resolution + tree walk ───────────────────────────────────────────────
+static void resolve_value_references_at(TSLSPContext *ctx, TSNode call_node) {
+ if (!ctx || !ctx->enclosing_func_qn) {
+ return;
+ }
+ TSNode args =
+ ts_node_child_by_field_name(call_node, "arguments", TS_LSP_FIELD_LEN("arguments"));
+ if (ts_node_is_null(args)) {
+ return;
+ }
+ uint32_t count = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < count; i++) {
+ TSNode arg = ts_node_named_child(args, i);
+ if (node_kind_is(arg, "member_expression")) {
+ /* A direct `receiver.method` value can be promoted only when a
+ * lexical receiver has one concrete registered method. Reject
+ * unions/intersections here: lookup_method() otherwise returns the
+ * first member, which would turn a multi-target value into false
+ * precision. */
+ if (!ctx->cross_file_mode) {
+ continue;
+ }
+ TSNode object = ts_node_child_by_field_name(arg, "object", TS_LSP_FIELD_LEN("object"));
+ TSNode property =
+ ts_node_child_by_field_name(arg, "property", TS_LSP_FIELD_LEN("property"));
+ if (!node_kind_is(object, "identifier") ||
+ !node_kind_is(property, "property_identifier")) {
+ continue;
+ }
+ char *object_name = node_text(ctx, object);
+ char *method_name = node_text(ctx, property);
+ if (!object_name || !method_name ||
+ !ts_scope_has_binding(ctx->current_scope, object_name)) {
+ continue;
+ }
+ const CBMType *receiver = ts_eval_expr_type(ctx, object);
+ const CBMType *base = receiver ? simplify_type(ctx, receiver) : NULL;
+ base = base ? unwrap_passthrough_template(base) : NULL;
+ if (!base || (base->kind != CBM_TYPE_NAMED && base->kind != CBM_TYPE_TEMPLATE)) {
+ continue;
+ }
+ const CBMRegisteredFunc *target = lookup_method(ctx, receiver, method_name);
+ if (target && target->qualified_name) {
+ ts_emit_resolved_reference(ctx, target->qualified_name,
+ "lsp_ts_bound_method_value_reference", 0.95f, property);
+ }
+ continue;
+ }
+ if (!node_kind_is(arg, "identifier")) {
+ continue;
+ }
+ char *name = node_text(ctx, arg);
+ if (ts_scope_has_binding(ctx->current_scope, name)) {
+ ts_block_shadowed_reference_usage(ctx, name, arg);
+ continue;
+ }
+ /* Per-file resolution still performs the scope/shadow check above, but
+ * promotion waits for the project-wide registry phase where the graph
+ * target can be proved and materialized. */
+ if (!ctx->cross_file_mode) {
+ continue;
+ }
+ const CBMRegisteredFunc *target = ts_exact_same_module_function(ctx, name);
+ const char *strategy = "lsp_ts_same_module_value_reference";
+ if (!target) {
+ target = ts_exact_imported_function(ctx, name);
+ strategy = "lsp_ts_import_value_reference";
+ }
+ if (target) {
+ ts_emit_resolved_reference(ctx, target->qualified_name, strategy, 0.95f, arg);
+ }
+ }
+}
+
static void resolve_call_at(TSLSPContext *ctx, TSNode call_node) {
TSNode fn = ts_node_child_by_field_name(call_node, "function", TS_LSP_FIELD_LEN("function"));
if (ts_node_is_null(fn))
return;
- // Argument count.
- int arg_count = 0;
TSNode args =
ts_node_child_by_field_name(call_node, "arguments", TS_LSP_FIELD_LEN("arguments"));
- if (!ts_node_is_null(args))
- arg_count = (int)ts_node_named_child_count(args);
const char *fk = ts_node_type(fn);
@@ -2287,59 +2680,33 @@ static void resolve_call_at(TSLSPContext *ctx, TSNode call_node) {
// Identifier as namespace import: `name.fn()` or `mod.fn()`.
if (node_kind_is(obj, "identifier")) {
char *on = node_text(ctx, obj);
- if (on) {
- for (int i = 0; i < ctx->import_count; i++) {
- const char *lname =
- ctx->import_local_names ? ctx->import_local_names[i] : NULL;
- const char *mqn =
- ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
- if (lname && mqn && strcmp(lname, on) == 0) {
- const CBMRegisteredFunc *f = cbm_registry_lookup_symbol_by_args(
- ctx->registry, mqn, mname, arg_count);
- if (f) {
- ts_emit_resolved_call(ctx, f->qualified_name,
- "lsp_ts_namespace", 0.95f);
- return;
- }
- ts_emit_unresolved_call(
- ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", on, mname),
- "module_symbol_not_in_registry");
- return;
- }
+ if (on && !ts_scope_has_binding(ctx->current_scope, on)) {
+ bool is_import = false;
+ const CBMRegisteredFunc *f =
+ ts_lookup_namespace_call(ctx, on, mname, args, &is_import);
+ if (f) {
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_namespace",
+ 0.95f, call_node);
+ return;
+ }
+ if (is_import) {
+ ts_emit_unresolved_call_at(
+ ctx, cbm_arena_sprintf(ctx->arena, "%s.%s", on, mname),
+ "module_symbol_not_in_registry", call_node);
+ return;
}
}
}
// Type-based dispatch.
const CBMType *recv = ts_eval_expr_type(ctx, obj);
- const CBMRegisteredFunc *f = lookup_method(ctx, recv, mname);
-
- // Overload resolution by arg types: when receiver is NAMED and the
- // registry has multiple overloads (same receiver+name), eval each
- // arg's type and let cbm_registry_lookup_method_by_types score them.
- // Falls back to the first match if scoring fails.
- if (f && recv) {
- const CBMType *base = simplify_type(ctx, recv);
- base = base ? unwrap_passthrough_template(base) : NULL;
- if (base && base->kind == CBM_TYPE_NAMED && base->data.named.qualified_name &&
- arg_count > 0) {
- const CBMType *arg_types[16] = {0};
- int n = arg_count > 16 ? 16 : arg_count;
- for (int i = 0; i < n; i++) {
- TSNode arg = ts_node_named_child(args, (uint32_t)i);
- arg_types[i] = ts_eval_expr_type(ctx, arg);
- }
- const CBMRegisteredFunc *better = cbm_registry_lookup_method_by_types(
- ctx->registry, base->data.named.qualified_name, mname, arg_types, n);
- if (better)
- f = better;
- }
- }
+ const CBMRegisteredFunc *f = ts_lookup_method_for_call(ctx, recv, mname, args);
if (f) {
- ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_method", 0.95f);
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_method", 0.95f,
+ call_node);
return;
}
- ts_emit_unresolved_call(ctx, mname, "method_not_in_registry");
+ ts_emit_unresolved_call_at(ctx, mname, "method_not_in_registry", call_node);
}
}
return;
@@ -2350,31 +2717,14 @@ static void resolve_call_at(TSLSPContext *ctx, TSNode call_node) {
char *name = node_text(ctx, fn);
if (!name)
return;
+ if (ts_scope_has_binding(ctx->current_scope, name))
+ return;
- // Eval arg types up-front for type-aware overload resolution.
- const CBMType *arg_types[16] = {0};
- int typed_arg_n = 0;
- if (!ts_node_is_null(args) && arg_count > 0) {
- typed_arg_n = arg_count > 16 ? 16 : arg_count;
- for (int i = 0; i < typed_arg_n; i++) {
- TSNode arg = ts_node_named_child(args, (uint32_t)i);
- arg_types[i] = ts_eval_expr_type(ctx, arg);
- }
- }
-
- // Module-local function: prefer by-types when args are typed.
+ // Module-local function: ordered argument types first, then arity.
if (ctx->module_qn) {
- const CBMRegisteredFunc *f = NULL;
- if (typed_arg_n > 0) {
- f = cbm_registry_lookup_symbol_by_types(ctx->registry, ctx->module_qn, name,
- arg_types, typed_arg_n);
- }
- if (!f) {
- f = cbm_registry_lookup_symbol_by_args(ctx->registry, ctx->module_qn, name,
- arg_count);
- }
+ const CBMRegisteredFunc *f = ts_lookup_symbol_for_call(ctx, ctx->module_qn, name, args);
if (f) {
- ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_local", 0.95f);
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_local", 0.95f, call_node);
return;
}
}
@@ -2383,19 +2733,19 @@ static void resolve_call_at(TSLSPContext *ctx, TSNode call_node) {
const char *lname = ctx->import_local_names ? ctx->import_local_names[i] : NULL;
const char *mqn = ctx->import_module_qns ? ctx->import_module_qns[i] : NULL;
if (lname && mqn && strcmp(lname, name) == 0) {
- const CBMRegisteredFunc *f =
- cbm_registry_lookup_symbol_by_args(ctx->registry, mqn, name, arg_count);
+ const CBMRegisteredFunc *f = ts_lookup_symbol_for_call(ctx, mqn, name, args);
if (f) {
- ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_import", 0.95f);
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_import", 0.95f,
+ call_node);
return;
}
// Fall through to qualified_name fallback.
const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, name);
- ts_emit_unresolved_call(ctx, qn, "import_symbol_not_in_registry");
+ ts_emit_unresolved_call_at(ctx, qn, "import_symbol_not_in_registry", call_node);
return;
}
}
- ts_emit_unresolved_call(ctx, name, "func_not_in_registry");
+ ts_emit_unresolved_call_at(ctx, name, "func_not_in_registry", call_node);
}
}
@@ -2694,12 +3044,19 @@ static void resolve_jsx_element(TSLSPContext *ctx, TSNode element_node) {
if (tag_name[0] >= 'a' && tag_name[0] <= 'z')
return;
+ /* Parameters and locals own the JSX identifier before module/import
+ * symbols. They may still be callable at runtime, but without a graph
+ * node for that lexical value we must fail closed instead of redirecting
+ * the tag to a same-named component definition. */
+ if (ts_scope_has_binding(ctx->current_scope, tag_name))
+ return;
+
// Resolve as a free-function/component call.
if (ctx->module_qn) {
const CBMRegisteredFunc *f =
cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, tag_name);
if (f) {
- ts_emit_resolved_call(ctx, f->qualified_name, "lsp_ts_jsx", 0.95f);
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_jsx", 0.95f, tag);
return;
}
}
@@ -2715,15 +3072,57 @@ static void resolve_jsx_element(TSLSPContext *ctx, TSNode element_node) {
* real module QN and emits the correct resolution, so skip the per-file
* emission for relative specifiers and let that one stand. */
if (mqn[0] == '.') {
- ts_emit_unresolved_call(ctx, tag_name, "jsx_import_unresolved_path");
+ ts_emit_unresolved_call_at(ctx, tag_name, "jsx_import_unresolved_path", tag);
+ return;
+ }
+ /* The import establishes lexical ownership, but a raw package or
+ * tsconfig-alias specifier is not a semantic target. Require the
+ * current (per-file or cross-file overlay) registry to materialize
+ * the exact component before emitting CALLS. An unresolved
+ * per-file row deliberately keeps the file eligible for the
+ * cross-file pass, where resolved import QNs and project defs are
+ * available. */
+ const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(ctx->registry, mqn, tag_name);
+ if (f) {
+ ts_emit_resolved_call_at(ctx, f->qualified_name, "lsp_ts_jsx_import", 0.95f, tag);
return;
}
- const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", mqn, tag_name);
- ts_emit_resolved_call(ctx, qn, "lsp_ts_jsx_import", 0.85f);
+ ts_emit_unresolved_call_at(ctx, tag_name, "jsx_component_not_in_registry", tag);
return;
}
}
- ts_emit_unresolved_call(ctx, tag_name, "jsx_component_not_in_registry");
+ ts_emit_unresolved_call_at(ctx, tag_name, "jsx_component_not_in_registry", tag);
+}
+
+/* Namespace members need the same function boundary handling as top-level
+ * declarations. Generic recursion can find their calls, but without setting
+ * enclosing_func_qn it cannot attribute those calls to the namespace member. */
+static void process_namespace_member(TSLSPContext *ctx, TSNode node) {
+ if (!ctx || ts_node_is_null(node))
+ return;
+
+ const char *kind = ts_node_type(node);
+ if (strcmp(kind, "export_statement") == 0) {
+ uint32_t count = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < count; i++)
+ process_namespace_member(ctx, ts_node_named_child(node, i));
+ return;
+ }
+
+ if (strcmp(kind, "function_declaration") == 0 && ctx->module_qn) {
+ TSNode name = ts_node_child_by_field_name(node, "name", TS_LSP_FIELD_LEN("name"));
+ if (!ts_node_is_null(name)) {
+ char *function_name = node_text(ctx, name);
+ if (function_name) {
+ const char *function_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, function_name);
+ process_function_body(ctx, node, function_qn, NULL);
+ return;
+ }
+ }
+ }
+
+ process_node(ctx, node);
}
static void process_node(TSLSPContext *ctx, TSNode node) {
@@ -2731,11 +3130,29 @@ static void process_node(TSLSPContext *ctx, TSNode node) {
return;
const char *kind = ts_node_type(node);
+ /* A nested statement block owns `let`/`const` declarations. Function-body
+ * blocks are intentionally unwrapped by process_function_body(), so this
+ * branch applies only to nested lexical blocks and cannot hide parameters. */
+ if (strcmp(kind, "statement_block") == 0) {
+ CBMScope *saved = ctx->current_scope;
+ ctx->current_scope = cbm_scope_push(ctx->arena, saved);
+ TSTreeCursor cursor = ts_tree_cursor_new(node);
+ if (ts_tree_cursor_goto_first_child(&cursor)) {
+ do {
+ process_node(ctx, ts_tree_cursor_current_node(&cursor));
+ } while (ts_tree_cursor_goto_next_sibling(&cursor));
+ }
+ ts_tree_cursor_delete(&cursor);
+ ctx->current_scope = saved;
+ return;
+ }
+
// Scope-affecting statements bind first, then we recurse.
ts_process_statement(ctx, node);
if (strcmp(kind, "call_expression") == 0) {
resolve_call_at(ctx, node);
+ resolve_value_references_at(ctx, node);
// Contextual callback typing: when an arg is an arrow_function and the
// corresponding param of the called function is itself a FUNC, propagate the
@@ -2747,15 +3164,15 @@ static void process_node(TSLSPContext *ctx, TSNode node) {
ts_node_child_by_field_name(node, "function", TS_LSP_FIELD_LEN("function"));
if (ts_node_is_null(fn_node))
break;
- const CBMType *fn_type = ts_eval_expr_type(ctx, fn_node);
- if (!fn_type || fn_type->kind != CBM_TYPE_FUNC)
- break;
- if (!fn_type->data.func.param_types)
- break;
TSNode args =
ts_node_child_by_field_name(node, "arguments", TS_LSP_FIELD_LEN("arguments"));
if (ts_node_is_null(args))
break;
+ const CBMType *fn_type = ts_signature_for_call(ctx, fn_node, args);
+ if (!fn_type || fn_type->kind != CBM_TYPE_FUNC)
+ break;
+ if (!fn_type->data.func.param_types)
+ break;
// Process the function child for nested call resolution.
process_node(ctx, fn_node);
@@ -3008,6 +3425,26 @@ static void process_node(TSLSPContext *ctx, TSNode node) {
return;
}
+ if (strcmp(kind, "internal_module") == 0) {
+ TSNode name = ts_node_child_by_field_name(node, "name", TS_LSP_FIELD_LEN("name"));
+ const char *saved_module_qn = ctx->module_qn;
+ if (!ts_node_is_null(name) && saved_module_qn) {
+ char *namespace_name = node_text(ctx, name);
+ if (namespace_name && namespace_name[0]) {
+ ctx->module_qn =
+ cbm_arena_sprintf(ctx->arena, "%s.%s", saved_module_qn, namespace_name);
+ }
+ }
+ TSNode body = ts_node_child_by_field_name(node, "body", TS_LSP_FIELD_LEN("body"));
+ if (!ts_node_is_null(body)) {
+ uint32_t count = ts_node_named_child_count(body);
+ for (uint32_t i = 0; i < count; i++)
+ process_namespace_member(ctx, ts_node_named_child(body, i));
+ }
+ ctx->module_qn = saved_module_qn;
+ return;
+ }
+
// Class / interface declarations are walked by the registry pass; here we just dive
// into method_definition bodies for inner call resolution.
if (strcmp(kind, "class_declaration") == 0) {
@@ -3158,8 +3595,18 @@ void ts_lsp_process_file(TSLSPContext *ctx, TSNode root) {
continue;
const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
process_function_body(ctx, child, fqn, NULL);
- } else if (strcmp(kind, "class_declaration") == 0) {
+ } else if (strcmp(kind, "class_declaration") == 0 || strcmp(kind, "internal_module") == 0) {
process_node(ctx, child);
+ } else if (strcmp(kind, "expression_statement") == 0) {
+ /* tree-sitter-typescript wraps a namespace declaration in an
+ * expression_statement. Unwrap only that declaration shape;
+ * ordinary top-level expressions are not owned by a function. */
+ uint32_t count = ts_node_named_child_count(child);
+ for (uint32_t j = 0; j < count; j++) {
+ TSNode inner = ts_node_named_child(child, j);
+ if (node_kind_is(inner, "internal_module"))
+ process_node(ctx, inner);
+ }
} else if (strcmp(kind, "export_statement") == 0) {
// Walk the wrapped declaration.
uint32_t enc = ts_node_named_child_count(child);
@@ -3178,12 +3625,13 @@ void ts_lsp_process_file(TSLSPContext *ctx, TSNode root) {
continue;
const char *fqn = cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, fn);
process_function_body(ctx, inner, fqn, NULL);
- } else if (strcmp(ik, "class_declaration") == 0) {
+ } else if (strcmp(ik, "class_declaration") == 0 ||
+ strcmp(ik, "internal_module") == 0) {
process_node(ctx, inner);
}
}
}
- // Top-level expression_statement bodies are not graphed as functions; skip.
+ // Other top-level expression_statement bodies are not graphed as functions.
}
}
@@ -3957,8 +4405,23 @@ static void register_file_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMFileRes
}
}
}
- const CBMType **params_t = parse_param_types_array(arena, d->param_types, module_qn);
- rf.signature = cbm_type_func(arena, d->param_names, params_t, rets);
+ /* The counted occurrence-preserving carrier wins even when its
+ * explicit count is zero. Legacy names are only safe alongside the
+ * legacy fallback because the two legacy projections share shape. */
+ bool has_ordered_params =
+ d->signature_param_types != NULL || d->signature_param_count > 0;
+ const CBMType **params_t = NULL;
+ const char **param_names = NULL;
+ if (has_ordered_params) {
+ CBMTSLSPSignatureParserContext param_parser_ctx = {module_qn};
+ params_t = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_ts_lsp_parse_signature_param_text, &param_parser_ctx);
+ } else {
+ params_t = parse_param_types_array(arena, d->param_types, module_qn);
+ param_names = d->param_names;
+ }
+ rf.signature = cbm_type_func(arena, param_names, params_t, rets);
// Methods: deduce receiver from QN ("module.Class.method" → receiver "module.Class").
if (strcmp(d->label, "Method") == 0) {
@@ -4624,6 +5087,87 @@ static void infer_implicit_returns(TSLSPContext *ctx, TSNode root, CBMTypeRegist
}
}
+/* Interface methods are synthesized after definition extraction and therefore
+ * cannot consume the CBMLSPDef ordered carrier. Build their FUNC type from the
+ * AST without matching by QN (overloads intentionally share a QN). */
+static const CBMType *interface_method_signature_from_ast(TSLSPContext *ctx, TSNode method,
+ int *out_min_params) {
+ const CBMType *param_types[32] = {0};
+ int param_count = 0;
+ int min_params = 0;
+ TSNode params =
+ ts_node_child_by_field_name(method, "parameters", TS_LSP_FIELD_LEN("parameters"));
+ if (!ts_node_is_null(params)) {
+ uint32_t count = ts_node_named_child_count(params);
+ for (uint32_t i = 0; i < count && param_count < 31; i++) {
+ TSNode param = ts_node_named_child(params, i);
+ const char *kind = ts_node_type(param);
+ if (strcmp(kind, "required_parameter") != 0 &&
+ strcmp(kind, "optional_parameter") != 0) {
+ continue;
+ }
+
+ TSNode pattern =
+ ts_node_child_by_field_name(param, "pattern", TS_LSP_FIELD_LEN("pattern"));
+ if (ts_node_is_null(pattern)) {
+ pattern = ts_node_child_by_field_name(param, "name", TS_LSP_FIELD_LEN("name"));
+ }
+ if (!ts_node_is_null(pattern)) {
+ char *name = node_text(ctx, pattern);
+ if (name && strcmp(name, "this") == 0)
+ continue;
+ }
+
+ const CBMType *param_type = cbm_type_unknown();
+ TSNode annotation =
+ ts_node_child_by_field_name(param, "type", TS_LSP_FIELD_LEN("type"));
+ if (ts_node_is_null(annotation)) {
+ uint32_t child_count = ts_node_named_child_count(param);
+ for (uint32_t j = 0; j < child_count; j++) {
+ TSNode child = ts_node_named_child(param, j);
+ if (strcmp(ts_node_type(child), "type_annotation") == 0) {
+ annotation = child;
+ break;
+ }
+ }
+ }
+ if (!ts_node_is_null(annotation)) {
+ TSNode type_node = strcmp(ts_node_type(annotation), "type_annotation") == 0
+ ? ts_node_named_child(annotation, 0)
+ : annotation;
+ if (!ts_node_is_null(type_node))
+ param_type = ts_parse_type_node(ctx, type_node);
+ }
+ param_types[param_count++] = param_type;
+
+ if (strcmp(kind, "required_parameter") == 0) {
+ TSNode value =
+ ts_node_child_by_field_name(param, "value", TS_LSP_FIELD_LEN("value"));
+ bool rest =
+ !ts_node_is_null(pattern) && strcmp(ts_node_type(pattern), "rest_pattern") == 0;
+ if (ts_node_is_null(value) && !rest)
+ min_params++;
+ }
+ }
+ }
+ param_types[param_count] = NULL;
+
+ const CBMType *return_type = cbm_type_unknown();
+ TSNode return_node =
+ ts_node_child_by_field_name(method, "return_type", TS_LSP_FIELD_LEN("return_type"));
+ if (!ts_node_is_null(return_node)) {
+ TSNode type_node = strcmp(ts_node_type(return_node), "type_annotation") == 0
+ ? ts_node_named_child(return_node, 0)
+ : return_node;
+ if (!ts_node_is_null(type_node))
+ return_type = ts_parse_type_node(ctx, type_node);
+ }
+ const CBMType *return_types[2] = {return_type, NULL};
+ if (out_min_params)
+ *out_min_params = min_params;
+ return cbm_type_func(ctx->arena, NULL, param_count ? param_types : NULL, return_types);
+}
+
// AST sweep: walk class/interface bodies to collect field names+types and refine
// embedded_types / type_param_names.
static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *reg) {
@@ -4766,19 +5310,8 @@ static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *re
if (!mnm)
continue;
- // Return type via field "return_type" — it's a type_annotation node.
- const CBMType *ret = cbm_type_unknown();
- TSNode rt_node =
- ts_node_child_by_field_name(m, "return_type", TS_LSP_FIELD_LEN("return_type"));
- if (!ts_node_is_null(rt_node)) {
- TSNode tch = (strcmp(ts_node_type(rt_node), "type_annotation") == 0)
- ? ts_node_named_child(rt_node, 0)
- : rt_node;
- if (!ts_node_is_null(tch))
- ret = ts_parse_type_node(ctx, tch);
- }
- const CBMType *rets[2] = {ret, NULL};
- const CBMType *sig = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ int min_params = -1;
+ const CBMType *sig = interface_method_signature_from_ast(ctx, m, &min_params);
const char *mqn = cbm_arena_sprintf(ctx->arena, "%s.%s", class_qn, mnm);
iface_method_names[iface_method_count] = mnm;
@@ -4793,7 +5326,7 @@ static void ast_sweep_shapes(TSLSPContext *ctx, TSNode root, CBMTypeRegistry *re
rf.short_name = mnm;
rf.receiver_type = class_qn;
rf.signature = sig;
- rf.min_params = -1;
+ rf.min_params = min_params;
cbm_registry_add_func(reg, rf);
}
}
@@ -4856,6 +5389,7 @@ void cbm_run_ts_lsp(CBMArena *arena, CBMFileResult *result, const char *source,
TSLSPContext ctx;
ts_lsp_init(&ctx, arena, source, source_len, &reg, result->module_qn, js_mode, jsx_mode,
dts_mode, &result->resolved_calls);
+ ctx.usages = &result->usages;
// Add imports early so type-resolution passes can rewrite NAMED references that
// refer to imported symbols. ts_parse_type_node consults these via
@@ -4990,13 +5524,14 @@ static void ts_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMLSPDe
rf.qualified_name = d->qualified_name;
rf.short_name = d->short_name;
rf.min_params = -1;
+ const CBMType **rets = NULL;
if (d->return_types && d->return_types[0]) {
int n = 1;
for (const char *s = d->return_types; *s; s++)
if (*s == '|')
n++;
- const CBMType **rets = (const CBMType **)cbm_arena_alloc(
- arena, (size_t)(n + 1) * sizeof(const CBMType *));
+ rets = (const CBMType **)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const CBMType *));
if (rets) {
int idx = 0;
const char *start = d->return_types;
@@ -5010,9 +5545,13 @@ static void ts_register_lsp_defs(CBMArena *arena, CBMTypeRegistry *reg, CBMLSPDe
}
}
rets[idx] = NULL;
- rf.signature = cbm_type_func(arena, NULL, NULL, rets);
}
}
+ CBMTSLSPSignatureParserContext param_parser_ctx = {d->def_module_qn};
+ const CBMType **params = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_ts_lsp_parse_signature_param_text, &param_parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, params, rets);
if (strcmp(d->label, "Method") == 0 && d->receiver_type) {
rf.receiver_type = d->receiver_type;
}
@@ -5109,6 +5648,7 @@ void cbm_run_ts_lsp_cross_with_registry(CBMArena *arena, const char *source, int
TSLSPContext ctx;
ts_lsp_init(&ctx, arena, source, source_len, &overlay, module_qn, js_mode, jsx_mode, dts_mode,
out);
+ ctx.cross_file_mode = true;
for (int i = 0; i < import_count; i++) {
if (import_names && import_qns && import_names[i] && import_qns[i]) {
ts_lsp_add_import(&ctx, import_names[i], import_qns[i]);
@@ -5253,13 +5793,14 @@ void cbm_run_ts_lsp_cross(CBMArena *arena, const char *source, int source_len,
rf.short_name = d->short_name;
rf.min_params = -1;
// Return types from pipe-separated return_types text.
+ const CBMType **rets = NULL;
if (d->return_types && d->return_types[0]) {
int n = 1;
for (const char *s = d->return_types; *s; s++)
if (*s == '|')
n++;
- const CBMType **rets = (const CBMType **)cbm_arena_alloc(
- arena, (size_t)(n + 1) * sizeof(const CBMType *));
+ rets = (const CBMType **)cbm_arena_alloc(arena,
+ (size_t)(n + 1) * sizeof(const CBMType *));
if (rets) {
int idx = 0;
const char *start = d->return_types;
@@ -5273,9 +5814,13 @@ void cbm_run_ts_lsp_cross(CBMArena *arena, const char *source, int source_len,
}
}
rets[idx] = NULL;
- rf.signature = cbm_type_func(arena, NULL, NULL, rets);
}
}
+ CBMTSLSPSignatureParserContext param_parser_ctx = {d->def_module_qn};
+ const CBMType **params = cbm_type_materialize_signature_params(
+ arena, d->signature_param_types, d->signature_param_count,
+ cbm_ts_lsp_parse_signature_param_text, &param_parser_ctx);
+ rf.signature = cbm_type_func(arena, NULL, params, rets);
if (strcmp(d->label, "Method") == 0 && d->receiver_type) {
rf.receiver_type = d->receiver_type;
}
@@ -5317,6 +5862,7 @@ void cbm_run_ts_lsp_cross(CBMArena *arena, const char *source, int source_len,
TSLSPContext ctx;
ts_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, js_mode, jsx_mode, dts_mode, out);
+ ctx.cross_file_mode = true;
// Add imports early so type passes can resolve imported types.
for (int i = 0; i < import_count; i++) {
diff --git a/internal/cbm/lsp/ts_lsp.h b/internal/cbm/lsp/ts_lsp.h
index 1473ce1bd..63fc14476 100644
--- a/internal/cbm/lsp/ts_lsp.h
+++ b/internal/cbm/lsp/ts_lsp.h
@@ -40,6 +40,10 @@ typedef struct {
// Output: resolved calls accumulate here.
CBMResolvedCallArray *resolved_calls;
+ // Optional raw usages owned by the per-file extraction result. The scope
+ // pass marks occurrence-exact module/import shadows without emitting a
+ // semantic reference record for them.
+ CBMUsageArray *usages;
// Type-parameter scope (innermost generic function/class).
// type_param_constraints may be NULL or shorter — entries default to "any".
@@ -51,6 +55,7 @@ typedef struct {
bool js_mode;
bool jsx_mode;
bool dts_mode;
+ bool cross_file_mode; // project-wide registry is available for exact reference proof
bool strict; // tsconfig "strict": true → fewer implicit-any fallbacks
bool debug; // CBM_LSP_DEBUG env
diff --git a/internal/cbm/lsp/type_registry.c b/internal/cbm/lsp/type_registry.c
index e840a6b5a..28353d591 100644
--- a/internal/cbm/lsp/type_registry.c
+++ b/internal/cbm/lsp/type_registry.c
@@ -286,6 +286,58 @@ int cbm_free_func_iter_next(CBMFreeFuncIter *it) {
return -1;
}
+void cbm_registry_methods(const CBMTypeRegistry *reg, const char *receiver_qn,
+ const char *method_name, CBMMethodIter *out) {
+ memset(out, 0, sizeof(*out));
+ out->reg = reg;
+ out->receiver_qn = receiver_qn;
+ out->method_name = method_name;
+ out->chain_idx = -1;
+ if (!reg || !receiver_qn || !method_name) {
+ return;
+ }
+ out->hash = fnv1a_pair(receiver_qn, method_name);
+ if (reg->method_buckets && reg->method_bucket_count > 0) {
+ int slot = (int)(out->hash & (uint64_t)(reg->method_bucket_count - 1));
+ out->chain_idx = reg->method_buckets[slot];
+ out->tail_i = reg->func_qn_entry_count;
+ out->tail_end = reg->func_count;
+ } else {
+ out->tail_i = 0;
+ out->tail_end = reg->func_count;
+ }
+}
+
+int cbm_method_iter_next(CBMMethodIter *it) {
+ if (!it || !it->reg || !it->receiver_qn || !it->method_name) {
+ return -1;
+ }
+ const CBMTypeRegistry *reg = it->reg;
+ while (it->chain_idx >= 0) {
+ const CBMRegistryHashEntry *e = &reg->method_entries[it->chain_idx];
+ int p = e->payload_index;
+ uint64_t h = e->hash;
+ it->chain_idx = e->next_index;
+ if (h != it->hash) {
+ continue;
+ }
+ const CBMRegisteredFunc *f = &reg->funcs[p];
+ if (f->receiver_type && f->short_name && strcmp(f->receiver_type, it->receiver_qn) == 0 &&
+ strcmp(f->short_name, it->method_name) == 0) {
+ return p;
+ }
+ }
+ while (it->tail_i < it->tail_end) {
+ int p = it->tail_i++;
+ const CBMRegisteredFunc *f = &reg->funcs[p];
+ if (f->receiver_type && f->short_name && strcmp(f->receiver_type, it->receiver_qn) == 0 &&
+ strcmp(f->short_name, it->method_name) == 0) {
+ return p;
+ }
+ }
+ return -1;
+}
+
void cbm_registry_finalize_into(CBMTypeRegistry *reg, CBMArena *idx_arena) {
if (!reg || !idx_arena)
return;
@@ -604,6 +656,27 @@ const CBMRegisteredFunc *cbm_registry_lookup_method_by_args(const CBMTypeRegistr
range_pi = pi;
}
}
+ /* Mirror lookup_method_self's post-finalize visibility contract. The
+ * hash chain covers the finalize-time prefix only; overloads added
+ * later must participate in the same exact/range/first ordering. */
+ for (int pi = reg->func_qn_entry_count; pi < reg->func_count; pi++) {
+ const CBMRegisteredFunc *f = &reg->funcs[pi];
+ if (!f->receiver_type || !f->short_name || strcmp(f->receiver_type, receiver_qn) != 0 ||
+ strcmp(f->short_name, method_name) != 0)
+ continue;
+ if (first_pi < 0 || pi < first_pi)
+ first_pi = pi;
+ int pc = count_func_params(f);
+ if (pc == arg_count) {
+ if (exact_pi < 0 || pi < exact_pi)
+ exact_pi = pi;
+ continue;
+ }
+ int min_pc = (f->min_params >= 0) ? f->min_params : pc;
+ if (arg_count >= min_pc && arg_count <= pc && (range_pi < 0 || pi < range_pi)) {
+ range_pi = pi;
+ }
+ }
int sel = exact_pi >= 0 ? exact_pi : (range_pi >= 0 ? range_pi : first_pi);
if (sel >= 0)
return &reg->funcs[sel];
@@ -776,6 +849,19 @@ const CBMRegisteredFunc *cbm_registry_lookup_method_by_types(const CBMTypeRegist
best_pi = pi;
}
}
+ for (int pi = reg->func_qn_entry_count; pi < reg->func_count; pi++) {
+ const CBMRegisteredFunc *f = &reg->funcs[pi];
+ if (!f->receiver_type || !f->short_name || strcmp(f->receiver_type, receiver_qn) != 0 ||
+ strcmp(f->short_name, method_name) != 0)
+ continue;
+ if (first_pi < 0 || pi < first_pi)
+ first_pi = pi;
+ int s = score_overload_match(f, arg_types, arg_count);
+ if (s > best_score || (s == best_score && best_pi >= 0 && pi < best_pi)) {
+ best_score = s;
+ best_pi = pi;
+ }
+ }
// best_score starts at 0; a score of 0 means "wrong arg count" → no
// match, exactly as the linear scan (which never sets best on s==0).
int sel = (best_pi >= 0 && best_score > 0) ? best_pi : first_pi;
@@ -857,6 +943,18 @@ const CBMRegisteredFunc *cbm_registry_lookup_symbol_by_types(const CBMTypeRegist
best_pi = pi;
}
}
+ for (int pi = reg->func_qn_entry_count; pi < reg->func_count; pi++) {
+ const CBMRegisteredFunc *f = &reg->funcs[pi];
+ if (!f->qualified_name || strcmp(f->qualified_name, buf) != 0)
+ continue;
+ if (first_pi < 0 || pi < first_pi)
+ first_pi = pi;
+ int s = score_overload_match(f, arg_types, arg_count);
+ if (s > best_score || (s == best_score && best_pi >= 0 && pi < best_pi)) {
+ best_score = s;
+ best_pi = pi;
+ }
+ }
int sel = (best_pi >= 0 && best_score > 0) ? best_pi : first_pi;
if (sel >= 0)
return &reg->funcs[sel];
@@ -935,6 +1033,23 @@ const CBMRegisteredFunc *cbm_registry_lookup_symbol_by_args(const CBMTypeRegistr
range_pi = pi;
}
}
+ for (int pi = reg->func_qn_entry_count; pi < reg->func_count; pi++) {
+ const CBMRegisteredFunc *f = &reg->funcs[pi];
+ if (!f->qualified_name || strcmp(f->qualified_name, buf) != 0)
+ continue;
+ if (first_pi < 0 || pi < first_pi)
+ first_pi = pi;
+ int pc = count_func_params(f);
+ if (pc == arg_count) {
+ if (exact_pi < 0 || pi < exact_pi)
+ exact_pi = pi;
+ continue;
+ }
+ int min_pc = (f->min_params >= 0) ? f->min_params : pc;
+ if (arg_count >= min_pc && arg_count <= pc && (range_pi < 0 || pi < range_pi)) {
+ range_pi = pi;
+ }
+ }
int sel = exact_pi >= 0 ? exact_pi : (range_pi >= 0 ? range_pi : first_pi);
if (sel >= 0)
return &reg->funcs[sel];
diff --git a/internal/cbm/lsp/type_registry.h b/internal/cbm/lsp/type_registry.h
index ac15ee162..154c37a00 100644
--- a/internal/cbm/lsp/type_registry.h
+++ b/internal/cbm/lsp/type_registry.h
@@ -5,18 +5,24 @@
#include "../arena.h"
#include <stdbool.h>
-// Decorator-derived flags (Python). Added at struct tail so existing
+// Language-specific function metadata. Added at struct tail so existing
// callers that memset to zero before populating other fields keep working.
typedef enum {
CBM_FUNC_FLAG_NONE = 0,
- CBM_FUNC_FLAG_PROPERTY = 1 << 0, // @property -> obj.attr returns getter return
- CBM_FUNC_FLAG_CLASSMETHOD = 1 << 1, // @classmethod -> first arg is cls (the class)
- CBM_FUNC_FLAG_STATICMETHOD = 1 << 2, // @staticmethod -> no implicit self/cls
- CBM_FUNC_FLAG_ABSTRACTMETHOD = 1 << 3, // @abstractmethod -> still callable for resolution
- CBM_FUNC_FLAG_OVERLOAD = 1 << 4, // @overload entry — non-implementation stub
- CBM_FUNC_FLAG_ASYNC = 1 << 5, // async def — return is Coroutine[..., T]
- CBM_FUNC_FLAG_GENERATOR = 1 << 6, // contains yield — return is Generator[T, ...]
- CBM_FUNC_FLAG_FINAL = 1 << 7, // @final — overrides not allowed
+ CBM_FUNC_FLAG_PROPERTY = 1 << 0, // @property -> obj.attr returns getter return
+ CBM_FUNC_FLAG_CLASSMETHOD = 1 << 1, // @classmethod -> first arg is cls (the class)
+ CBM_FUNC_FLAG_STATICMETHOD = 1 << 2, // @staticmethod -> no implicit self/cls
+ CBM_FUNC_FLAG_ABSTRACTMETHOD = 1 << 3, // @abstractmethod -> still callable for resolution
+ CBM_FUNC_FLAG_OVERLOAD = 1 << 4, // @overload entry — non-implementation stub
+ CBM_FUNC_FLAG_ASYNC = 1 << 5, // async def — return is Coroutine[..., T]
+ CBM_FUNC_FLAG_GENERATOR = 1 << 6, // contains yield — return is Generator[T, ...]
+ CBM_FUNC_FLAG_FINAL = 1 << 7, // @final — overrides not allowed
+ CBM_FUNC_FLAG_RUST_TRAIT_IMPL = 1 << 8, // exact method from impl Trait for Type
+ CBM_FUNC_FLAG_RUST_ABSTRACT = 1 << 9, // required trait method without a default body
+ /* Python only: more than one registered definition has this exact QN.
+ * Ordinary call resolution keeps its historical language-specific choice,
+ * but a function value cannot name one materialized definition exactly. */
+ CBM_FUNC_FLAG_AMBIGUOUS_BINDING = 1 << 10,
} CBMFuncFlags;
// Registered function/method with full type signature.
@@ -27,9 +33,13 @@ typedef struct {
const CBMType *signature; // FUNC type with param/return types
const char **type_param_names; // NULL-terminated, e.g., ["T", "R", NULL] for generics
int min_params; // Minimum required params (excluding defaulted). -1 = unknown.
- int flags; // CBM_FUNC_FLAG_* bitfield (Python decorator info; 0 elsewhere)
+ int flags; // CBM_FUNC_FLAG_* bitfield
const char **decorator_qns; // NULL-terminated decorator QNs (Python only); used for
// user-decorator return-type substitution.
+ /* Rust only: canonical trait QN for a concrete trait-impl method. It may
+ * remain NULL when raw cross-file provenance is ambiguous; the Rust trait
+ * flag still prevents that method from being mistaken for inherent. */
+ const char *impl_trait_qn;
} CBMRegisteredFunc;
// Registered type with fields and method names.
@@ -242,6 +252,24 @@ void cbm_registry_free_funcs_by_short_name(const CBMTypeRegistry *reg, const cha
CBMFreeFuncIter *out);
int cbm_free_func_iter_next(CBMFreeFuncIter *it);
+// Iterate function indices for one exact (receiver QN, method name) key. This
+// exposes the existing finalized method bucket without making Rust scan the
+// project-wide func array merely to distinguish inherent and trait-impl
+// entries that intentionally share the same source-level QN. The caller may
+// filter on language-specific flags. Read-only and allocation-free.
+typedef struct {
+ const CBMTypeRegistry *reg;
+ const char *receiver_qn;
+ const char *method_name;
+ uint64_t hash;
+ int chain_idx;
+ int tail_i;
+ int tail_end;
+} CBMMethodIter;
+void cbm_registry_methods(const CBMTypeRegistry *reg, const char *receiver_qn,
+ const char *method_name, CBMMethodIter *out);
+int cbm_method_iter_next(CBMMethodIter *it);
+
// --- TS-specific helpers (return NULL for types without these signatures) ---
// If the type has a call signature (e.g., `interface F { (x:number): string }`), return
diff --git a/internal/cbm/lsp/type_rep.c b/internal/cbm/lsp/type_rep.c
index edb90c50e..afc5b0d52 100644
--- a/internal/cbm/lsp/type_rep.c
+++ b/internal/cbm/lsp/type_rep.c
@@ -115,6 +115,41 @@ const CBMType *cbm_type_func(CBMArena *a, const char **param_names, const CBMTyp
return t;
}
+const CBMType **cbm_type_materialize_signature_params(CBMArena *a, const char *const *type_texts,
+ int count, CBMTypeTextParser parser,
+ void *parser_ctx) {
+ if (count <= 0)
+ return NULL;
+
+ const CBMType **types =
+ (const CBMType **)cbm_arena_alloc(a, ((size_t)count + 1) * sizeof(const CBMType *));
+ if (!types)
+ return NULL;
+
+ for (int i = 0; i < count; i++) {
+ const char *text = type_texts ? type_texts[i] : NULL;
+ if (!text || text[0] == '\0' || strcmp(text, "?") == 0) {
+ types[i] = cbm_type_unknown();
+ continue;
+ }
+
+ const CBMType *parsed = parser ? parser(a, text, parser_ctx) : NULL;
+ types[i] = parsed ? parsed : cbm_type_unknown();
+ }
+ types[count] = NULL;
+ return types;
+}
+
+const CBMType *cbm_type_func_replace_returns(CBMArena *a, const CBMType *old_signature,
+ const CBMType *const *new_return_types) {
+ if (!old_signature || old_signature->kind != CBM_TYPE_FUNC)
+ return cbm_type_unknown();
+
+ /* cbm_type_func only reads and then copies this vector into arena memory. */
+ return cbm_type_func(a, old_signature->data.func.param_names,
+ old_signature->data.func.param_types, (const CBMType **)new_return_types);
+}
+
const CBMType *cbm_type_builtin(CBMArena *a, const char *name) {
CBMType *t = (CBMType *)cbm_arena_alloc(a, sizeof(CBMType));
if (!t)
diff --git a/internal/cbm/lsp/type_rep.h b/internal/cbm/lsp/type_rep.h
index 73d7def0c..a32e7812a 100644
--- a/internal/cbm/lsp/type_rep.h
+++ b/internal/cbm/lsp/type_rep.h
@@ -45,6 +45,9 @@ typedef enum {
// Forward declaration
typedef struct CBMType CBMType;
+// Language-specific adapter used to parse one ordered signature type spelling.
+typedef const CBMType *(*CBMTypeTextParser)(CBMArena *arena, const char *text, void *parser_ctx);
+
// CBMTypeParam represents a generic type parameter with optional constraint.
typedef struct {
const char* name; // "T", "K", "V"
@@ -153,6 +156,14 @@ const CBMType* cbm_type_slice(CBMArena* a, const CBMType* elem);
const CBMType* cbm_type_map(CBMArena* a, const CBMType* key, const CBMType* value);
const CBMType* cbm_type_channel(CBMArena* a, const CBMType* elem, int direction);
const CBMType* cbm_type_func(CBMArena* a, const char** param_names, const CBMType** param_types, const CBMType** return_types);
+// Materialize exactly count positional parameter slots. NULL, empty, exact "?",
+// and parser failures become UNKNOWN; the returned vector is NULL-terminated.
+const CBMType **cbm_type_materialize_signature_params(CBMArena *a, const char *const *type_texts,
+ int count, CBMTypeTextParser parser,
+ void *parser_ctx);
+// Rebuild a FUNC with new returns while preserving its parameter names/types.
+const CBMType *cbm_type_func_replace_returns(CBMArena *a, const CBMType *old_signature,
+ const CBMType *const *new_return_types);
const CBMType* cbm_type_builtin(CBMArena* a, const char* name);
const CBMType* cbm_type_tuple(CBMArena* a, const CBMType** elems, int count);
const CBMType* cbm_type_type_param(CBMArena* a, const char* name);
diff --git a/scripts/repro.sh b/scripts/repro.sh
index 78162e779..304352558 100755
--- a/scripts/repro.sh
+++ b/scripts/repro.sh
@@ -1,10 +1,11 @@
#!/usr/bin/env bash
# repro.sh — Build + run the cumulative BUG-REPRODUCTION suite (test-repro).
#
-# Unlike test.sh (the gating suite, must be GREEN), this suite is RED by design:
-# every case reproduces an open bug. So we distinguish two outcomes:
+# Unlike test.sh (the gating suite, must be GREEN), this suite tracks open RED
+# reproductions alongside GREEN controls and regression guards. We distinguish:
# - BUILD/LINK failure → real breakage → exit non-zero (fail the CI job).
-# - Test redness → EXPECTED → report the count, exit 0 (green board).
+# - Reproduced RED cases → expected board data → report the count, exit 0.
+# - Any skipped case → incomplete board → report it, exit non-zero.
#
# Usage: scripts/repro.sh [CC=clang] [CXX=clang++] [--arch arm64|x86_64]
set -uo pipefail
@@ -37,7 +38,12 @@ done
print_env "repro.sh"
verify_compiler "$CC"
-OUT="$ROOT/repro-out.txt"
+OUT="$(mktemp "${TMPDIR:-/tmp}/cbm-repro-out.XXXXXX")"
+if [[ -z "$OUT" ]]; then
+ echo "::error::unable to create bug-repro transcript"
+ exit 1
+fi
+trap 'rm -f "$OUT"' EXIT
# A RED reproduction fails its assertion and returns EARLY — before any cleanup —
# so LeakSanitizer would flag benign harness leaks on every red store-level test
# and abort. The board's signal is the FAIL rows, not leak-cleanliness (the leak
@@ -50,23 +56,45 @@ set +e
make -j"$NPROC" -f Makefile.cbm test-repro $MAKE_ARGS 2>&1 | tee "$OUT"
set -e
-# The runner prints a "<N> passed[, <M> failed]" summary line only if it actually
-# ran. No summary line ⇒ the build/link failed ⇒ real breakage.
-if ! grep -qE '[0-9]+ passed' "$OUT"; then
+# The runner's final aggregate is the only line that starts with the count.
+# Per-suite lines also contain "N passed, M failed", so selecting the first
+# match undercounts every multi-suite run.
+summary_line="$(grep -E '^[[:space:]]*[0-9]+ passed(, [0-9]+ failed)?(, [0-9]+ skipped)?[[:space:]]*$' "$OUT" | tail -1 || true)"
+if [[ -z "$summary_line" ]]; then
echo "::error::bug-repro runner did not execute — build or link failure"
exit 1
fi
-reproduced=$(grep -oE '[0-9]+ failed' "$OUT" | head -1 | grep -oE '[0-9]+' || echo 0)
-green=$(grep -oE '[0-9]+ passed' "$OUT" | head -1 | grep -oE '[0-9]+' || echo 0)
+green="$(printf '%s\n' "$summary_line" | grep -oE '[0-9]+ passed' | grep -oE '[0-9]+')"
+reproduced="$(printf '%s\n' "$summary_line" | grep -oE '[0-9]+ failed' | grep -oE '[0-9]+' || echo 0)"
+skipped="$(printf '%s\n' "$summary_line" | grep -oE '[0-9]+ skipped' | grep -oE '[0-9]+' || echo 0)"
+
+if ((green + reproduced == 0)); then
+ echo "::error::bug-repro runner executed zero tests"
+ exit 1
+fi
-{
+emit_board_summary() {
echo "## Bug-reproduction board — ${OS:-$(uname -s)} ${ARCH:-}"
echo ""
echo "- **${reproduced}** open bug(s) still reproduced (RED — expected)"
- echo "- **${green}** case(s) PASSING — candidate-fixed → verify + close the issue + promote the guard to the gating suite"
-} >> "${GITHUB_STEP_SUMMARY:-/dev/stderr}"
+ echo "- **${green}** case(s) passing control(s) or candidate-fix candidate(s); verify each RED→GREEN transition before closing an issue"
+ if ((skipped > 0)); then
+ echo "- **${skipped}** case(s) SKIPPED — board is incomplete"
+ fi
+}
+
+if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
+ emit_board_summary >> "$GITHUB_STEP_SUMMARY"
+else
+ emit_board_summary >&2
+fi
+
+echo "=== bug-repro board: ${reproduced} reproduced (RED), ${green} passing control(s) or candidate-fix candidate(s) ==="
+if ((skipped > 0)); then
+ echo "::warning::bug-repro board incomplete — ${skipped} case(s) skipped"
+ exit 1
+fi
-echo "=== bug-repro board: ${reproduced} reproduced (RED), ${green} passing (candidate-fixed) ==="
# Green board: the suite ran. Redness is the data, not a job failure.
exit 0
diff --git a/src/cli/cli.c b/src/cli/cli.c
index aec3cf102..1a51a4628 100644
--- a/src/cli/cli.c
+++ b/src/cli/cli.c
@@ -576,7 +576,7 @@ static const char skill_content[] =
"\n"
"## Edge Types\n"
"CALLS, HTTP_CALLS, ASYNC_CALLS, DATA_FLOWS, IMPORTS, DEFINES, DEFINES_METHOD,\n"
- "HANDLES, IMPLEMENTS, OVERRIDE, USAGE, CONFIGURES, FILE_CHANGES_WITH,\n"
+ "HANDLES, IMPLEMENTS, OVERRIDE, USAGE, CALL_REFERENCE, CONFIGURES, FILE_CHANGES_WITH,\n"
"SIMILAR_TO, SEMANTICALLY_RELATED, CONTAINS_FILE, CONTAINS_FOLDER,\n"
"CONTAINS_PACKAGE\n"
"\n"
diff --git a/src/discover/discover.c b/src/discover/discover.c
index 19d4a3190..63e706d45 100644
--- a/src/discover/discover.c
+++ b/src/discover/discover.c
@@ -48,7 +48,7 @@ static const char *ALWAYS_SKIP_DIRS[] = {
/* Deploy */
".vercel", ".netlify", "deploy", "deployed",
/* Misc */
- ".qdrant_code_embeddings", ".tmp", "vendor", "vendored", NULL};
+ ".codebase-memory", ".qdrant_code_embeddings", ".tmp", "vendor", "vendored", NULL};
static const char *FAST_SKIP_DIRS[] = {
"generated", "gen", "auto-generated", "fixtures", "testdata", "test_data",
diff --git a/src/discover/userconfig.c b/src/discover/userconfig.c
index f533edd0e..f392ae3f5 100644
--- a/src/discover/userconfig.c
+++ b/src/discover/userconfig.c
@@ -14,6 +14,7 @@
#include "foundation/constants.h"
#include "foundation/platform.h" /* cbm_safe_getenv */
#include "foundation/compat_fs.h"
+#include "foundation/sha256.h"
enum { MAX_CONFIG_SIZE = 65536 };
#include "foundation/log.h"
@@ -29,6 +30,26 @@ enum { MAX_CONFIG_SIZE = 65536 };
static const cbm_userconfig_t *g_userconfig = NULL;
+static void userconfig_source_digest(const char *state, const void *bytes, size_t len,
+ char out[CBM_SHA256_HEX_LEN + 1]) {
+ static const char domain[] = "cbm-userconfig-source-v1";
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ cbm_sha256_update(&sha, domain, sizeof(domain));
+ cbm_sha256_update(&sha, state, strlen(state) + 1);
+ if (bytes && len > 0) {
+ cbm_sha256_update(&sha, bytes, len);
+ }
+ 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 * 2] = hex[digest[i] >> 4];
+ out[i * 2 + 1] = hex[digest[i] & 0x0f];
+ }
+ out[CBM_SHA256_HEX_LEN] = '\0';
+}
+
void cbm_set_user_lang_config(const cbm_userconfig_t *cfg) {
g_userconfig = cfg;
}
@@ -232,7 +253,9 @@ static int parse_extra_extensions(yyjson_val *root, cbm_userext_t **entries, int
* Silently ignores missing files. Logs warnings for corrupt JSON.
* Returns 0 on success (or absent file), -1 on alloc failure.
*/
-static int load_config_file(const char *path, cbm_userext_t **entries, int *count) {
+static int load_config_file(const char *path, cbm_userext_t **entries, int *count,
+ char source_sha256[CBM_SHA256_HEX_LEN + 1]) {
+ userconfig_source_digest("missing-or-unreadable", NULL, 0, source_sha256);
FILE *f = cbm_fopen(path, "rb");
if (!f) {
return 0; /* file absent — silently ignore */
@@ -240,11 +263,13 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
if (fseek(f, 0, SEEK_END) != 0) {
(void)fclose(f);
+ userconfig_source_digest("seek-error", NULL, 0, source_sha256);
return 0;
}
long len = ftell(f);
if (fseek(f, 0, SEEK_SET) != 0) {
(void)fclose(f);
+ userconfig_source_digest("seek-error", NULL, 0, source_sha256);
return 0;
}
@@ -252,6 +277,9 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
(void)fclose(f);
if (len > MAX_CONFIG_SIZE) {
cbm_log_warn("userconfig.file_too_large", "path", path);
+ userconfig_source_digest("oversized", NULL, 0, source_sha256);
+ } else {
+ userconfig_source_digest("empty", NULL, 0, source_sha256);
}
return 0;
}
@@ -268,6 +296,7 @@ static int load_config_file(const char *path, cbm_userext_t **entries, int *coun
nread = (size_t)len;
}
buf[nread] = '\0';
+ userconfig_source_digest("present", buf, nread, source_sha256);
yyjson_doc *doc = yyjson_read(buf, nread, 0);
free(buf);
@@ -301,7 +330,7 @@ cbm_userconfig_t *cbm_userconfig_load(const char *repo_path) {
char global_path[PATH_BUF_SZ];
snprintf(global_path, sizeof(global_path), "%s/codebase-memory-mcp/config.json", cfg_fallback);
- if (load_config_file(global_path, &entries, &count) != 0) {
+ if (load_config_file(global_path, &entries, &count, cfg->global_source_sha256) != 0) {
for (int i = 0; i < count; i++) {
free(entries[i].ext);
}
@@ -313,11 +342,12 @@ cbm_userconfig_t *cbm_userconfig_load(const char *repo_path) {
int global_count = count; /* entries[0..global_count) are from global */
/* ── Step 2: Load project config ── */
+ userconfig_source_digest("not-applicable", NULL, 0, cfg->project_source_sha256);
if (repo_path && repo_path[0]) {
char project_path[PATH_BUF_SZ];
snprintf(project_path, sizeof(project_path), "%s/.codebase-memory.json", repo_path);
- if (load_config_file(project_path, &entries, &count) != 0) {
+ if (load_config_file(project_path, &entries, &count, cfg->project_source_sha256) != 0) {
/* Free already-allocated entries */
for (int i = 0; i < count; i++) {
free(entries[i].ext);
diff --git a/src/discover/userconfig.h b/src/discover/userconfig.h
index 233734845..5d24ec183 100644
--- a/src/discover/userconfig.h
+++ b/src/discover/userconfig.h
@@ -18,6 +18,7 @@
#define CBM_USERCONFIG_H
#include "cbm.h" /* CBMLanguage */
+#include "foundation/sha256.h"
/* ── Types ──────────────────────────────────────────────────────── */
@@ -29,6 +30,9 @@ typedef struct {
typedef struct {
cbm_userext_t *entries; /* heap-allocated array */
int count; /* number of entries */
+ /* Digests of the exact bytes/state consumed by cbm_userconfig_load(). */
+ char global_source_sha256[CBM_SHA256_HEX_LEN + 1];
+ char project_source_sha256[CBM_SHA256_HEX_LEN + 1];
} cbm_userconfig_t;
/* ── API ────────────────────────────────────────────────────────── */
diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.c
index 54c9e3c67..2f09cfcbc 100644
--- a/src/foundation/compat_fs.c
+++ b/src/foundation/compat_fs.c
@@ -11,6 +11,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <stdint.h>
#ifdef _WIN32
@@ -118,6 +119,40 @@ cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
return &d->entry;
}
+int cbm_path_info_utf8(const char *path, cbm_path_info_t *out) {
+ if (!path || !out) {
+ return CBM_NOT_FOUND;
+ }
+ wchar_t *wpath = cbm_utf8_to_wide(path);
+ if (!wpath) {
+ return CBM_NOT_FOUND;
+ }
+ WIN32_FILE_ATTRIBUTE_DATA data;
+ BOOL ok = GetFileAttributesExW(wpath, GetFileExInfoStandard, &data);
+ free(wpath);
+ if (!ok) {
+ return CBM_NOT_FOUND;
+ }
+ memset(out, 0, sizeof(*out));
+ out->is_directory = (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ out->is_symlink = (data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
+ out->is_regular = !out->is_directory && !out->is_symlink;
+ ULARGE_INTEGER file_size;
+ file_size.LowPart = data.nFileSizeLow;
+ file_size.HighPart = data.nFileSizeHigh;
+ out->size = (int64_t)file_size.QuadPart;
+ ULARGE_INTEGER written;
+ written.LowPart = data.ftLastWriteTime.dwLowDateTime;
+ written.HighPart = data.ftLastWriteTime.dwHighDateTime;
+ enum { NANOSECONDS_PER_WINDOWS_TICK = 100 };
+ const uint64_t windows_to_unix_ticks = UINT64_C(116444736000000000);
+ out->mtime_ns =
+ written.QuadPart >= windows_to_unix_ticks
+ ? (int64_t)((written.QuadPart - windows_to_unix_ticks) * NANOSECONDS_PER_WINDOWS_TICK)
+ : 0;
+ return 0;
+}
+
void cbm_closedir(cbm_dir_t *d) {
if (d) {
if (d->find_handle != INVALID_HANDLE_VALUE) {
@@ -658,13 +693,51 @@ cbm_dirent_t *cbm_readdir(cbm_dir_t *d) {
}
memcpy(d->entry.name, de->d_name, nlen);
d->entry.name[nlen] = '\0';
- d->entry.is_dir = (de->d_type == DT_DIR);
- d->entry.d_type = de->d_type;
+ unsigned char type = de->d_type;
+#if defined(DT_UNKNOWN) && defined(AT_SYMLINK_NOFOLLOW)
+ if (type == DT_UNKNOWN) {
+ struct stat state;
+ if (fstatat(dirfd(d->dir), de->d_name, &state, AT_SYMLINK_NOFOLLOW) == 0) {
+ if (S_ISDIR(state.st_mode)) {
+ type = DT_DIR;
+ } else if (S_ISREG(state.st_mode)) {
+ type = DT_REG;
+ } else if (S_ISLNK(state.st_mode)) {
+ type = DT_LNK;
+ }
+ }
+ }
+#endif
+ d->entry.is_dir = (type == DT_DIR);
+ d->entry.d_type = type;
return &d->entry;
}
return NULL;
}
+int cbm_path_info_utf8(const char *path, cbm_path_info_t *out) {
+ if (!path || !out) {
+ return CBM_NOT_FOUND;
+ }
+ struct stat state;
+ if (lstat(path, &state) != 0) {
+ return CBM_NOT_FOUND;
+ }
+ memset(out, 0, sizeof(*out));
+ out->is_regular = S_ISREG(state.st_mode);
+ out->is_directory = S_ISDIR(state.st_mode);
+ out->is_symlink = S_ISLNK(state.st_mode);
+ out->size = (int64_t)state.st_size;
+#ifdef __APPLE__
+ out->mtime_ns = ((int64_t)state.st_mtimespec.tv_sec * INT64_C(1000000000)) +
+ (int64_t)state.st_mtimespec.tv_nsec;
+#else
+ out->mtime_ns =
+ ((int64_t)state.st_mtim.tv_sec * INT64_C(1000000000)) + (int64_t)state.st_mtim.tv_nsec;
+#endif
+ return 0;
+}
+
void cbm_closedir(cbm_dir_t *d) {
if (d) {
if (d->dir) {
@@ -871,23 +944,67 @@ int cbm_rename_replace(const char *src, const char *dst) {
#endif
}
+int cbm_rename_noreplace(const char *src, const char *dst) {
+ if (!src || !dst || !src[0] || !dst[0]) {
+ return CBM_NOT_FOUND;
+ }
+#ifdef _WIN32
+ wchar_t *wsrc = cbm_utf8_to_wide(src);
+ wchar_t *wdst = cbm_utf8_to_wide(dst);
+ int ret = CBM_NOT_FOUND;
+ if (wsrc && wdst) {
+ ret = MoveFileExW(wsrc, wdst, MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)
+ ? 0
+ : CBM_NOT_FOUND;
+ }
+ free(wsrc);
+ free(wdst);
+ return ret;
+#else
+ /* link()+unlink() provides no-overwrite semantics portably (including
+ * macOS, where renameat2(RENAME_NOREPLACE) is unavailable). Both paths
+ * are adjacent database files and therefore on the same filesystem. */
+ if (link(src, dst) != 0) {
+ return CBM_NOT_FOUND;
+ }
+ if (unlink(src) != 0) {
+ int saved_errno = errno;
+ (void)unlink(dst);
+ errno = saved_errno;
+ return CBM_NOT_FOUND;
+ }
+ return 0;
+#endif
+}
+
/* Remove a SQLite database's -wal/-shm sidecars (both platforms). Any code
* path that installs a FRESH database file where a previous generation lived
* must remove them before the new generation can be opened: SQLite decides
* whether to replay a WAL purely from the sidecar's own header/checksums, so
* a leftover WAL can splice old-generation pages into the new file (#897). */
-void cbm_remove_db_sidecars(const char *db_path) {
+int cbm_remove_db_sidecars_checked(const char *db_path) {
if (!db_path || !db_path[0]) {
- return;
+ return CBM_NOT_FOUND;
}
enum { SIDECAR_PATH_MAX = 4096 };
char side[SIDECAR_PATH_MAX];
int n = snprintf(side, sizeof(side), "%s-wal", db_path);
- if (n > 0 && (size_t)n < sizeof(side)) {
- (void)cbm_unlink(side);
+ if (n <= 0 || (size_t)n >= sizeof(side)) {
+ return CBM_NOT_FOUND;
+ }
+ if (cbm_unlink(side) != 0 && errno != ENOENT) {
+ return CBM_NOT_FOUND;
}
n = snprintf(side, sizeof(side), "%s-shm", db_path);
- if (n > 0 && (size_t)n < sizeof(side)) {
- (void)cbm_unlink(side);
+ if (n <= 0 || (size_t)n >= sizeof(side)) {
+ return CBM_NOT_FOUND;
+ }
+ if (cbm_unlink(side) != 0 && errno != ENOENT) {
+ return CBM_NOT_FOUND;
}
+ return 0;
+}
+
+void cbm_remove_db_sidecars(const char *db_path) {
+ (void)cbm_remove_db_sidecars_checked(db_path);
}
diff --git a/src/foundation/compat_fs.h b/src/foundation/compat_fs.h
index af89c795d..6994e5680 100644
--- a/src/foundation/compat_fs.h
+++ b/src/foundation/compat_fs.h
@@ -9,12 +9,13 @@
#include <stdbool.h>
#include <stddef.h>
+#include <stdint.h>
#include <stdio.h>
/* ── Directory iteration ──────────────────────────────────────── */
/* Max filename length (MAX_PATH on Windows, NAME_MAX on POSIX). */
-#define CBM_DIRENT_NAME_MAX 260
+#define CBM_DIRENT_NAME_MAX 1024
typedef struct cbm_dir cbm_dir_t;
@@ -24,6 +25,20 @@ typedef struct {
unsigned char d_type; /* DT_REG, DT_DIR, DT_LNK, etc. (POSIX only, 0 on Windows) */
} cbm_dirent_t;
+/* Locale-independent metadata for a UTF-8 path. Symlinks/reparse points are
+ * reported rather than followed so semantic-input walkers cannot leave the
+ * repository through an alias. mtime_ns is Unix-epoch nanoseconds. */
+typedef struct {
+ bool is_regular;
+ bool is_directory;
+ bool is_symlink;
+ int64_t size;
+ int64_t mtime_ns;
+} cbm_path_info_t;
+
+/* Returns 0 on success and -1 when the path cannot be inspected. */
+int cbm_path_info_utf8(const char *path, cbm_path_info_t *out);
+
/* Open a directory for iteration. Returns NULL on error. */
cbm_dir_t *cbm_opendir(const char *path);
@@ -50,9 +65,15 @@ int cbm_unlink(const char *path);
* do this before the new generation can be opened; a leftover WAL is
* otherwise replayed on top of the new file (#897). */
void cbm_remove_db_sidecars(const char *db_path);
+/* Checked form used at an atomic replacement boundary. Missing sidecars are
+ * success; any other deletion or path-construction failure is reported. */
+int cbm_remove_db_sidecars_checked(const char *db_path);
/* rename() that replaces an existing destination on every platform
* (Windows rename fails with EEXIST; this uses write-through MoveFileExW). */
int cbm_rename_replace(const char *src, const char *dst);
+/* Move a regular file only when dst does not exist. Never overwrites dst.
+ * Used for collision-safe evidence quarantine beside a database. */
+int cbm_rename_noreplace(const char *src, const char *dst);
/* Canonicalize an EXISTING path (realpath / wide GetFullPathNameW). Locale-
* independent on Windows — never routes UTF-8 through the ANSI CRT (#973).
* out must be >= 4096 bytes. Returns 1 on success, 0 otherwise. */
diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c
index a04057419..083a7b3a8 100644
--- a/src/mcp/mcp.c
+++ b/src/mcp/mcp.c
@@ -375,7 +375,8 @@ static const tool_def_t TOOLS[] = {
"RESPONSE: prefix-grouped tree rows by default — a shared (qn-prefix, file) group "
"header printed once, then `name label lines in out` per row (full qn = group prefix "
"+ dot + name). in/out = TOTAL degree across ALL edge types (DEFINES, "
- "USAGE, CALLS, ...), NOT caller/callee counts — use trace_path for callers. Add per-node "
+ "USAGE, CALLS, CALL_REFERENCE, ...), NOT caller/callee counts — use trace_path for callers. "
+ "Add per-node "
"property columns via "
"fields (e.g. [\"complexity\",\"signature\",\"docstring\"]); format=\"json\" returns "
"the SAME tree model as structured JSON. "
diff --git a/src/pipeline/artifact.c b/src/pipeline/artifact.c
index 5aa4a3fa3..5f781f611 100644
--- a/src/pipeline/artifact.c
+++ b/src/pipeline/artifact.c
@@ -574,7 +574,7 @@ int cbm_artifact_export(const char *db_path, const char *repo_path, const char *
/* Get node/edge counts for metadata */
int nodes = 0;
int edges = 0;
- cbm_store_t *count_store = cbm_store_open_path(db_path);
+ cbm_store_t *count_store = cbm_store_open_path_query(db_path);
if (count_store) {
nodes = cbm_store_count_nodes(count_store, project_name);
edges = cbm_store_count_edges(count_store, project_name);
diff --git a/src/pipeline/lsp_resolve.h b/src/pipeline/lsp_resolve.h
index 2bb72e8f9..4e4fab0cb 100644
--- a/src/pipeline/lsp_resolve.h
+++ b/src/pipeline/lsp_resolve.h
@@ -25,7 +25,9 @@
#include "graph_buffer/graph_buffer.h"
#include "foundation/constants.h"
+#include <ctype.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
/* Confidence floor below which LSP-resolved calls are ignored and the
@@ -35,6 +37,16 @@
* (Go, C/C++, Python, PHP). */
#define CBM_LSP_CONFIDENCE_FLOOR 0.6f
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+/* Test-build-only operation counter implemented by pass_usages.c. Keeping the
+ * increment behind this seam lets the regression measure the real sequential
+ * and fused-parallel materialization helper without retaining instrumentation
+ * in production builds. */
+void cbm_pipeline_lsp_reference_lookup_test_note_row(void);
+#else
+static inline void cbm_pipeline_lsp_reference_lookup_test_note_row(void) {}
+#endif
+
/* Bare last segment of a (possibly qualified) name, splitting on the LAST
* member/scope separator. C++ textual callees carry `::` (Class::method,
* Ns::f) and `->` (p->run), while the LSP records dotted internal QNs
@@ -61,6 +73,9 @@ static inline const char *cbm_lsp_bare_segment(const char *name) {
seg = p + SKIP_ONE;
}
}
+ while (*seg && isspace((unsigned char)*seg)) {
+ seg++;
+ }
return seg;
}
@@ -105,11 +120,238 @@ static inline bool cbm_pipeline_lsp_allow_tail_match(CBMLanguage lang) {
return lang == CBM_LANG_JAVA || lang == CBM_LANG_KOTLIN;
}
+/* When a JVM callable-reference occurrence has no exact semantic target, its
+ * ordinary-USAGE fallback must still respect package/import reachability.
+ * `unique_name` and `suffix_match` are project-wide guesses: admitting either
+ * would bind an unresolved `::handler` in one package to an unrelated callable
+ * in another. Other languages retain their legacy value-usage fallback. */
+static inline bool cbm_pipeline_call_reference_usage_fallback_allowed(CBMLanguage lang,
+ const char *strategy) {
+ if (lang != CBM_LANG_JAVA && lang != CBM_LANG_KOTLIN) {
+ return true;
+ }
+ if (!strategy || !strategy[0]) {
+ return false;
+ }
+ return strcmp(strategy, "unique_name") != 0 && strcmp(strategy, "suffix_match") != 0;
+}
+
+static inline bool cbm_pipeline_reference_candidate_fallback_allowed(
+ CBMLanguage lang, const CBMUsage *usage, const char *strategy, const char *const *import_names,
+ int import_count) {
+ if (!usage) {
+ return false;
+ }
+ bool reference_candidate =
+ usage->kind == CBM_USAGE_CALL_REFERENCE ||
+ (lang == CBM_LANG_KOTLIN && usage->kind == CBM_USAGE_VALUE && usage->may_be_call_reference);
+ if (!reference_candidate ||
+ cbm_pipeline_call_reference_usage_fallback_allowed(lang, strategy)) {
+ return true;
+ }
+ /* Kotlin's project import map currently names the imported module rather
+ * than the member. A syntactically explicit, locally imported `::name`
+ * may therefore resolve by unique name after LSP proves it is not a
+ * callable. Admit that ordinary USAGE only when the import map confirms
+ * the local spelling; an unimported same-name symbol remains unreachable. */
+ if (lang == CBM_LANG_KOTLIN && usage->ref_name && import_names) {
+ for (int i = 0; i < import_count; i++) {
+ if (import_names[i] && strcmp(import_names[i], usage->ref_name) == 0) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+/* Explicit reference syntax always participates in the semantic join. An
+ * ordinary value participates only when extraction marked the narrow direct
+ * argument shape in a language whose resolver can prove callable identity;
+ * without an exact LSP record it remains USAGE. */
+static inline bool cbm_pipeline_usage_semantic_reference_candidate(const CBMUsage *usage) {
+ if (!usage) {
+ return false;
+ }
+ return usage->kind == CBM_USAGE_CALL_REFERENCE ||
+ (usage->kind == CBM_USAGE_VALUE && usage->may_be_call_reference);
+}
+
+/* Lexical extraction has whole-scope information that a source-order semantic
+ * walk can lack. In Python and JS/TS, a later local binding makes an earlier
+ * same-named value local too; an LSP row that still points at the module
+ * function must not override that proof. A callable-alias row is different:
+ * it explicitly resolves the local binding itself to its assigned callable. */
+static inline bool cbm_pipeline_usage_allows_semantic_reference(const CBMUsage *usage,
+ const CBMResolvedCall *resolved) {
+ if (!usage || !resolved) {
+ return false;
+ }
+ if (usage->kind != CBM_USAGE_VALUE || !usage->semantic_reference_blocked ||
+ !usage->semantic_reference_local_shadow) {
+ return true;
+ }
+ return resolved->strategy && strcmp(resolved->strategy, "lsp_callable_alias") == 0;
+}
+
+/* A blocked module value can still retain an ordinary edge to a same-named
+ * non-callable declaration, but it must never fall back to an executable
+ * declaration. A local lexical shadow rejects every raw-name fallback because
+ * even a same-named module variable is a different binding. Exact semantic
+ * rows are joined before either rule. This label check keeps sequential and
+ * fused resolution aligned. */
+static inline bool cbm_pipeline_node_is_callable_target(const cbm_gbuf_node_t *node) {
+ if (!node || !node->label) {
+ return false;
+ }
+ return strcmp(node->label, "Function") == 0 || strcmp(node->label, "Method") == 0 ||
+ strcmp(node->label, "Constructor") == 0 || strcmp(node->label, "Class") == 0;
+}
+
static inline int cbm_pipeline_qn_class_method_tail_eq(const char *qn, const char *tail) {
const char *qt = cbm_pipeline_qn_class_method_tail(qn);
return qt && tail && strcmp(qt, tail) == 0;
}
+static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node_policy(
+ const cbm_gbuf_t *gbuf, const char *project_name, const char *callee_qn, bool allow_tail_match,
+ bool allow_unique_callable_fallback);
+
+/* Local and cross passes may spell one exact invocation target with and without
+ * the project prefix. Collapse that cross-language case only when exact graph
+ * lookup maps both spellings to one materialized node. JVM passes additionally
+ * reconcile file/project and declared-package QNs below; Class.method-tail
+ * equality alone is insufficient because two packages can declare the same
+ * class and method. */
+static inline bool cbm_pipeline_invocation_targets_equal(const char *left_qn, const char *right_qn,
+ const cbm_gbuf_t *gbuf,
+ const char *project_name,
+ bool allow_tail_match) {
+ if (!left_qn || !right_qn) {
+ return false;
+ }
+ if (strcmp(left_qn, right_qn) == 0) {
+ return true;
+ }
+ if (!gbuf || !project_name) {
+ return false;
+ }
+ const cbm_gbuf_node_t *left_exact =
+ cbm_pipeline_lsp_target_node_policy(gbuf, project_name, left_qn, false, false);
+ const cbm_gbuf_node_t *right_exact =
+ cbm_pipeline_lsp_target_node_policy(gbuf, project_name, right_qn, false, false);
+ if (left_exact && right_exact) {
+ return left_exact->id == right_exact->id;
+ }
+ if (!allow_tail_match) {
+ return false;
+ }
+ const char *left_tail = cbm_pipeline_qn_class_method_tail(left_qn);
+ const char *right_tail = cbm_pipeline_qn_class_method_tail(right_qn);
+ if (!left_tail || !right_tail || strcmp(left_tail, right_tail) != 0) {
+ return false;
+ }
+ /* Two package-shaped rows that both reach a node only through the tail
+ * fallback are still distinct semantic claims. Require at least one row
+ * to name the materialized node exactly (or by project-prefix retry). */
+ if (!left_exact && !right_exact) {
+ return false;
+ }
+ const cbm_gbuf_node_t *left =
+ left_exact ? left_exact
+ : cbm_pipeline_lsp_target_node_policy(gbuf, project_name, left_qn, true, true);
+ const cbm_gbuf_node_t *right =
+ right_exact ? right_exact
+ : cbm_pipeline_lsp_target_node_policy(gbuf, project_name, right_qn, true, true);
+ return left && right && left->id == right->id;
+}
+
+/* A semantic join is occurrence-exact only when both producers recorded the
+ * same non-empty source span. Byte spans, unlike line numbers, distinguish
+ * repeated same-named references/operators on one line. */
+static inline bool cbm_pipeline_source_site_present(uint32_t start, uint32_t end) {
+ return end > start;
+}
+
+static inline bool cbm_pipeline_source_site_legacy(uint32_t start, uint32_t end) {
+ return start == 0 && end == 0;
+}
+
+static inline bool cbm_pipeline_source_site_eq(uint32_t lhs_start, uint32_t lhs_end,
+ uint32_t rhs_start, uint32_t rhs_end) {
+ return cbm_pipeline_source_site_present(lhs_start, lhs_end) &&
+ cbm_pipeline_source_site_present(rhs_start, rhs_end) && lhs_start == rhs_start &&
+ lhs_end == rhs_end;
+}
+
+static inline bool cbm_pipeline_source_occurrence_eq(uint32_t lhs_start, uint32_t lhs_end,
+ CBMSourceOrigin lhs_origin, uint32_t rhs_start,
+ uint32_t rhs_end, CBMSourceOrigin rhs_origin) {
+ return lhs_origin == rhs_origin &&
+ cbm_pipeline_source_site_eq(lhs_start, lhs_end, rhs_start, rhs_end);
+}
+
+/* Rank an invocation record for one parser carrier. Exact occurrence identity
+ * is stronger than the legacy 0:0 compatibility join. Partial/reversed spans
+ * are corrupt metadata and never participate in either class. */
+static inline int cbm_pipeline_invocation_site_rank(const CBMResolvedCall *resolved,
+ const CBMCall *call) {
+ if (!resolved || !call) {
+ return 0;
+ }
+ bool call_has_site =
+ cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte);
+ bool call_is_legacy =
+ cbm_pipeline_source_site_legacy(call->site_start_byte, call->site_end_byte);
+ if (!call_has_site && !call_is_legacy) {
+ return 0;
+ }
+ if (cbm_pipeline_source_site_present(resolved->site_start_byte, resolved->site_end_byte)) {
+ return cbm_pipeline_source_occurrence_eq(call->site_start_byte, call->site_end_byte,
+ call->source_origin, resolved->site_start_byte,
+ resolved->site_end_byte, resolved->source_origin)
+ ? 2
+ : 0;
+ }
+ if (!cbm_pipeline_source_site_legacy(resolved->site_start_byte, resolved->site_end_byte)) {
+ return 0;
+ }
+ return call->requires_lsp_resolution || call->source_origin != resolved->source_origin ? 0 : 1;
+}
+
+static inline bool cbm_pipeline_invocation_reason_join_strategy(const char *strategy) {
+ return strategy &&
+ (strcmp(strategy, "lsp_func_ptr") == 0 || strcmp(strategy, "lsp_callable_alias") == 0 ||
+ strcmp(strategy, "lsp_dll_resolve") == 0 ||
+ strcmp(strategy, "lsp_method_ref_ctor") == 0 ||
+ strcmp(strategy, "lsp_method_ref_ctor_synth") == 0 ||
+ strcmp(strategy, "lsp_dict_dispatch") == 0 ||
+ strcmp(strategy, "lsp_import_alias") == 0 ||
+ strcmp(strategy, "php_method_dynamic") == 0);
+}
+
+static inline bool cbm_pipeline_invocation_leaf_matches(const CBMResolvedCall *resolved,
+ const CBMCall *call, int site_rank) {
+ if (!resolved || !resolved->callee_qn || !call || !call->callee_name) {
+ return false;
+ }
+ const char *resolved_leaf = cbm_lsp_bare_segment(resolved->callee_qn);
+ const char *call_leaf = cbm_lsp_bare_segment(call->callee_name);
+ if (resolved_leaf && call_leaf && strcmp(resolved_leaf, call_leaf) == 0) {
+ return true;
+ }
+
+ /* Destructors intentionally join by their exact delete-expression
+ * occurrence because the parser carrier starts as a neutral "~" marker. */
+ if (site_rank == 2 && call->requires_lsp_resolution && resolved->strategy &&
+ strcmp(resolved->strategy, "lsp_destructor") == 0) {
+ return true;
+ }
+
+ /* Indirect resolvers retain the textual source leaf in reason. */
+ return cbm_pipeline_invocation_reason_join_strategy(resolved->strategy) && resolved->reason &&
+ call_leaf && strcmp(cbm_lsp_bare_segment(resolved->reason), call_leaf) == 0;
+}
+
/* 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`
@@ -119,8 +361,9 @@ static inline int cbm_pipeline_qn_class_method_tail_eq(const char *qn, const cha
* 1. exact caller_qn + callee short-name match wins first;
* 2. if no exact caller match exists AND allow_tail_match is set
* (JVM callers only, see cbm_pipeline_lsp_allow_tail_match), a
- * unique Class.method tail match between rc->caller_qn and
- * call->enclosing_func_qn may win;
+ * unique Class.method tail match may win; an occurrence-exact row may
+ * also reconcile Kotlin's package-vs-file top-level owner QNs when their
+ * bare caller leaves agree;
* 3. ambiguous tails return NULL so the registry fallback stays in
* control.
*
@@ -129,8 +372,9 @@ static inline int cbm_pipeline_qn_class_method_tail_eq(const char *qn, const cha
*
* The pointer returned aliases into `arr` and stays valid as long as the
* underlying CBMFileResult is alive. */
-static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution(
- const CBMResolvedCallArray *arr, const CBMCall *call, bool allow_tail_match) {
+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) {
if (!arr || arr->count == 0 || !call) {
return NULL;
}
@@ -138,9 +382,14 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution(
return NULL;
}
- const CBMResolvedCall *best_exact = NULL;
+ 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;
}
@@ -150,77 +399,445 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution(
if (strcmp(rc->caller_qn, call->enclosing_func_qn) != 0) {
continue;
}
- const char *short_name = cbm_lsp_bare_segment(rc->callee_qn);
- /* The call's callee_name is receiver-qualified for method/qualified
- * calls ("c.inc", "A.Helper", "Math::square", "p->run"); the LSP
- * records the resolved class-qualified callee_qn ("Class.inc"). Compare
- * the bare last segment on BOTH sides so method-dispatch resolutions
- * join — the LSP already did the receiver->type resolution, and matching
- * the full "c.inc" against "inc" would always miss, silently dropping the
- * type-aware LSP strategy to the weaker textual registry. Free-function
- * calls (bare callee_name) are unaffected. */
- const char *call_short = cbm_lsp_bare_segment(call->callee_name);
- if (strcmp(short_name, call_short) != 0) {
- /* Indirect/implicit resolution: the textual callee differs from the
- * resolved callee_qn's short name. A function-pointer / DLL call's
- * callee is the pointer name (`fp`); a C++ destructor's only textual
- * anchor is the deleted operand (`p`, vs. the `T.~T` callee QN). In
- * both the LSP stashed the original textual name in `reason`. Match
- * the call site on that name, gated to those strategies so `reason`
- * is never misread as an unresolved-call diagnostic. */
- if (!(rc->reason && rc->strategy &&
- (strcmp(rc->strategy, "lsp_func_ptr") == 0 ||
- strcmp(rc->strategy, "lsp_dll_resolve") == 0 ||
- strcmp(rc->strategy, "lsp_method_ref_ctor") == 0 ||
- strcmp(rc->strategy, "lsp_method_ref_ctor_synth") == 0 ||
- strcmp(rc->strategy, "lsp_dict_dispatch") == 0 ||
- strcmp(rc->strategy, "lsp_import_alias") == 0 ||
- strcmp(rc->strategy, "lsp_destructor") == 0 ||
- strcmp(rc->strategy, "php_method_dynamic") == 0) &&
- strcmp(cbm_lsp_bare_segment(rc->reason), call_short) == 0)) {
- continue;
- }
+ int site_rank = cbm_pipeline_invocation_site_rank(rc, call);
+ if (site_rank == 0 || !cbm_pipeline_invocation_leaf_matches(rc, call, site_rank)) {
+ continue;
}
- if (!best_exact || rc->confidence > best_exact->confidence) {
- best_exact = rc;
+ if (!best_exact_caller || site_rank > best_exact_caller_rank) {
+ best_exact_caller = rc;
+ best_exact_caller_rank = site_rank;
+ exact_caller_ambiguous = false;
+ continue;
+ }
+ if (site_rank < best_exact_caller_rank) {
+ continue;
+ }
+ if (!cbm_pipeline_invocation_targets_equal(best_exact_caller->callee_qn, rc->callee_qn,
+ gbuf, project_name, allow_tail_match)) {
+ exact_caller_ambiguous = true;
+ continue;
+ }
+ if (rc->confidence > best_exact_caller->confidence) {
+ best_exact_caller = rc;
}
}
- if (best_exact) {
- return best_exact;
+ if (best_exact_caller) {
+ return exact_caller_ambiguous ? NULL : best_exact_caller;
}
if (!allow_tail_match) {
return NULL;
}
const char *call_tail = cbm_pipeline_qn_class_method_tail(call->enclosing_func_qn);
- if (!call_tail) {
- return NULL;
- }
- const CBMResolvedCall *best_tail = NULL;
+ const CBMResolvedCall *best_tail_exact = NULL;
+ const CBMResolvedCall *best_tail_legacy = NULL;
+ bool tail_exact_ambiguous = false;
+ 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) {
continue;
}
- const char *short_name = strrchr(rc->callee_qn, '.');
- short_name = short_name ? short_name + SKIP_ONE : rc->callee_qn;
- const char *call_leaf = cbm_pipeline_call_callee_leaf(call->callee_name);
- if (!call_leaf || strcmp(short_name, call_leaf) != 0) {
+ 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)) {
+ 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;
+ }
+ }
+ if (best_tail_exact) {
+ return tail_exact_ambiguous ? NULL : best_tail_exact;
+ }
+ return tail_legacy_ambiguous ? NULL : best_tail_legacy;
+}
+
+/* Graph-free compatibility entry point for resolver unit tests. Raw distinct
+ * targets remain ambiguous because no materialized-node identity is available. */
+static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution(
+ const CBMResolvedCallArray *arr, const CBMCall *call, bool allow_tail_match) {
+ return cbm_pipeline_find_lsp_resolution_in_graph(arr, call, allow_tail_match, NULL, NULL);
+}
+
+static inline bool cbm_pipeline_reference_reason_matches(const CBMResolvedCall *resolved,
+ const char *reference_leaf) {
+ if (!resolved || !resolved->strategy || !resolved->reason || !reference_leaf) {
+ return false;
+ }
+ bool reason_join_strategy = strcmp(resolved->strategy, "php_method_dynamic") == 0 ||
+ strcmp(resolved->strategy, "php_static_magic_reference") == 0 ||
+ strcmp(resolved->strategy, "php_invokable_reference") == 0 ||
+ strcmp(resolved->strategy, "lsp_callable_alias") == 0 ||
+ strcmp(resolved->strategy, "lsp_callable_value") == 0 ||
+ strcmp(resolved->strategy, "lsp_callable_value_reference") == 0;
+ return reason_join_strategy &&
+ strcmp(cbm_lsp_bare_segment(resolved->reason), reference_leaf) == 0;
+}
+
+static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node(const cbm_gbuf_t *gbuf,
+ const char *project_name,
+ const char *callee_qn,
+ bool allow_tail_match) {
+ return cbm_pipeline_lsp_target_node_policy(gbuf, project_name, callee_qn, allow_tail_match,
+ true);
+}
+
+/* External Kotlin protocol carriers must resolve to the exact semantic target.
+ * A project-qualified retry is still exact, but Class.method and unique-leaf
+ * fallbacks could bind `kotlin.IntArray.iterator` to an unrelated project
+ * method and are therefore deliberately disabled. */
+static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node_strict(const cbm_gbuf_t *gbuf,
+ const char *project_name,
+ const char *callee_qn,
+ bool allow_tail_match) {
+ (void)allow_tail_match;
+ return cbm_pipeline_lsp_target_node_policy(gbuf, project_name, callee_qn, false, false);
+}
+
+/* Keep exact-only lookup scoped to known external Kotlin namespaces. Project
+ * callable aliases and operators still need the normal JVM QN reconciliation
+ * path, while unresolved synthetic carriers remain fail-closed at the caller. */
+static inline bool cbm_pipeline_kotlin_external_target(CBMLanguage lang, const char *callee_qn) {
+ if (lang != CBM_LANG_KOTLIN || !callee_qn) {
+ return false;
+ }
+ return strncmp(callee_qn, "kotlin.", strlen("kotlin.")) == 0 ||
+ strncmp(callee_qn, "java.", strlen("java.")) == 0 ||
+ strncmp(callee_qn, "javax.", strlen("javax.")) == 0;
+}
+
+/* Resolvers may report one graph target both project-relative and already
+ * project-prefixed. Raw string inequality is not ambiguity when both spellings
+ * resolve to the same materialized node; conversely, if both nodes exist they
+ * remain distinct and the reference must fail closed. */
+static inline bool cbm_pipeline_reference_targets_equal(const char *left_qn, const char *right_qn,
+ const cbm_gbuf_t *gbuf,
+ const char *project_name,
+ bool allow_tail_match) {
+ if (!left_qn || !right_qn) {
+ return false;
+ }
+ if (strcmp(left_qn, right_qn) == 0) {
+ return true;
+ }
+ if (!gbuf || !project_name) {
+ return false;
+ }
+ /* Caller-tail fallback helps JVM rows find a materialized target, but it is
+ * not proof that two distinct semantic target QNs denote the same symbol.
+ * Equivalence is deliberately stricter: collapse only direct and
+ * project-prefix spellings of one graph node, otherwise stay ambiguous. */
+ (void)allow_tail_match;
+ const cbm_gbuf_node_t *left = cbm_pipeline_lsp_target_node(gbuf, project_name, left_qn, false);
+ const cbm_gbuf_node_t *right =
+ cbm_pipeline_lsp_target_node(gbuf, project_name, right_qn, false);
+ return left && right && left->id == right->id;
+}
+
+typedef struct {
+ const CBMResolvedCall *row;
+ int original_index;
+} cbm_pipeline_lsp_reference_index_entry_t;
+
+typedef struct {
+ cbm_pipeline_lsp_reference_index_entry_t *entries;
+ int count;
+} cbm_pipeline_lsp_reference_index_t;
+
+/* Sort by exact occurrence while retaining extraction order within one site.
+ * The final ordinal key is intentional: confidence ties keep the first row,
+ * so an unstable qsort tie must not silently change semantic selection. */
+static inline int cbm_pipeline_lsp_reference_index_entry_cmp(const void *left_ptr,
+ const void *right_ptr) {
+ const cbm_pipeline_lsp_reference_index_entry_t *left =
+ (const cbm_pipeline_lsp_reference_index_entry_t *)left_ptr;
+ const cbm_pipeline_lsp_reference_index_entry_t *right =
+ (const cbm_pipeline_lsp_reference_index_entry_t *)right_ptr;
+ if (left->row->source_origin != right->row->source_origin) {
+ return left->row->source_origin < right->row->source_origin ? -1 : 1;
+ }
+ if (left->row->site_start_byte != right->row->site_start_byte) {
+ return left->row->site_start_byte < right->row->site_start_byte ? -1 : 1;
+ }
+ if (left->row->site_end_byte != right->row->site_end_byte) {
+ return left->row->site_end_byte < right->row->site_end_byte ? -1 : 1;
+ }
+ if (left->original_index == right->original_index) {
+ return 0;
+ }
+ return left->original_index < right->original_index ? -1 : 1;
+}
+
+/* Build one compact pointer index per extracted file. Invocation rows cannot
+ * participate in CALL_REFERENCE matching and are excluded. False means only
+ * allocation failure; callers must then use the unchanged linear matcher. */
+static inline bool cbm_pipeline_lsp_reference_index_build(
+ const CBMResolvedCallArray *arr, cbm_pipeline_lsp_reference_index_t *index) {
+ if (!index) {
+ return false;
+ }
+ index->entries = NULL;
+ index->count = 0;
+ if (!arr || arr->count <= 0) {
+ return true;
+ }
+
+ int reference_count = 0;
+ for (int i = 0; i < arr->count; i++) {
+ if (arr->items[i].kind == CBM_RESOLVED_CALL_REFERENCE) {
+ reference_count++;
+ }
+ }
+ if (reference_count == 0) {
+ return true;
+ }
+ if ((size_t)reference_count > SIZE_MAX / sizeof(cbm_pipeline_lsp_reference_index_entry_t)) {
+ return false;
+ }
+
+ cbm_pipeline_lsp_reference_index_entry_t *entries =
+ (cbm_pipeline_lsp_reference_index_entry_t *)malloc((size_t)reference_count *
+ sizeof(*entries));
+ if (!entries) {
+ return false;
+ }
+ int next = 0;
+ for (int i = 0; i < arr->count; i++) {
+ if (arr->items[i].kind != CBM_RESOLVED_CALL_REFERENCE) {
+ continue;
+ }
+ entries[next].row = &arr->items[i];
+ entries[next].original_index = i;
+ next++;
+ }
+ qsort(entries, (size_t)reference_count, sizeof(*entries),
+ cbm_pipeline_lsp_reference_index_entry_cmp);
+ index->entries = entries;
+ index->count = reference_count;
+ return true;
+}
+
+static inline void cbm_pipeline_lsp_reference_index_free(
+ cbm_pipeline_lsp_reference_index_t *index) {
+ if (!index) {
+ return;
+ }
+ free(index->entries);
+ index->entries = NULL;
+ index->count = 0;
+}
+
+static inline int cbm_pipeline_lsp_reference_site_cmp_usage(const CBMResolvedCall *row,
+ const CBMUsage *usage) {
+ if (row->source_origin != usage->source_origin) {
+ return row->source_origin < usage->source_origin ? -1 : 1;
+ }
+ if (row->site_start_byte != usage->site_start_byte) {
+ return row->site_start_byte < usage->site_start_byte ? -1 : 1;
+ }
+ if (row->site_end_byte != usage->site_end_byte) {
+ return row->site_end_byte < usage->site_end_byte ? -1 : 1;
+ }
+ return 0;
+}
+
+static inline const CBMResolvedCall *cbm_pipeline_lsp_reference_view_row(
+ const CBMResolvedCallArray *arr, const cbm_pipeline_lsp_reference_index_entry_t *entries,
+ int first, int offset) {
+ return entries ? entries[first + offset].row : &arr->items[first + offset];
+}
+
+/* Look up the highest-confidence LSP resolution for a callable reference.
+ * Reference records intentionally use a separate kind from invocations: an
+ * explicit `Type::method`/`obj::method`, PHP first-class callable, or an exact
+ * TS function-value argument denotes a function value and must never enter
+ * the CALLS pipeline.
+ *
+ * Exact enclosing-function matches win. The unique Class.method caller-tail
+ * fallback is admitted only when the caller opted into the existing JVM-only
+ * rule via `allow_tail_match`; ambiguity returns NULL so the usage pipeline can
+ * fall back to the textual registry without fabricating a semantic match.
+ *
+ * `entries` is either NULL for the original full-array fallback or a sorted
+ * occurrence slice. The matching body is deliberately shared so indexing
+ * cannot diverge on caller, reason, ambiguity, target identity, or confidence. */
+static inline const CBMResolvedCall *cbm_pipeline_find_lsp_reference_view_in_graph(
+ const CBMResolvedCallArray *arr, const cbm_pipeline_lsp_reference_index_entry_t *entries,
+ int first, int row_count, const CBMUsage *usage, bool allow_tail_match, const cbm_gbuf_t *gbuf,
+ const char *project_name) {
+ if ((!entries && !arr) || row_count <= 0 || !usage || !usage->enclosing_func_qn ||
+ !usage->ref_name) {
+ return NULL;
+ }
+
+ const char *ref_leaf = cbm_lsp_bare_segment(usage->ref_name);
+ if (!ref_leaf || !ref_leaf[0]) {
+ return NULL;
+ }
+
+ const CBMResolvedCall *best_exact = NULL;
+ bool exact_ambiguous = false;
+ for (int i = 0; i < row_count; i++) {
+ cbm_pipeline_lsp_reference_lookup_test_note_row();
+ const CBMResolvedCall *rc = cbm_pipeline_lsp_reference_view_row(arr, entries, first, i);
+ if (rc->kind != CBM_RESOLVED_CALL_REFERENCE || !rc->caller_qn || !rc->callee_qn ||
+ rc->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
continue;
}
- if (!cbm_pipeline_qn_class_method_tail_eq(rc->caller_qn, call_tail)) {
+ if (strcmp(rc->caller_qn, usage->enclosing_func_qn) != 0 ||
+ !cbm_pipeline_source_occurrence_eq(usage->site_start_byte, usage->site_end_byte,
+ usage->source_origin, rc->site_start_byte,
+ rc->site_end_byte, rc->source_origin)) {
continue;
}
- if (best_tail) {
- return NULL;
+ bool name_matches = strcmp(cbm_lsp_bare_segment(rc->callee_qn), ref_leaf) == 0;
+ bool semantic_reason_matches = cbm_pipeline_reference_reason_matches(rc, ref_leaf);
+ if (!name_matches && !semantic_reason_matches) {
+ continue;
}
- best_tail = rc;
+ if (!best_exact) {
+ best_exact = rc;
+ continue;
+ }
+ if (!cbm_pipeline_reference_targets_equal(best_exact->callee_qn, rc->callee_qn, gbuf,
+ project_name, allow_tail_match)) {
+ exact_ambiguous = true;
+ continue;
+ }
+ if (rc->confidence > best_exact->confidence) {
+ best_exact = rc;
+ }
+ }
+ if (best_exact || !allow_tail_match) {
+ return exact_ambiguous ? NULL : best_exact;
+ }
+
+ const char *caller_tail = cbm_pipeline_qn_class_method_tail(usage->enclosing_func_qn);
+ if (!caller_tail) {
+ return NULL;
}
- return best_tail;
+
+ const CBMResolvedCall *best_tail = NULL;
+ bool tail_ambiguous = false;
+ for (int i = 0; i < row_count; i++) {
+ cbm_pipeline_lsp_reference_lookup_test_note_row();
+ const CBMResolvedCall *rc = cbm_pipeline_lsp_reference_view_row(arr, entries, first, i);
+ if (rc->kind != CBM_RESOLVED_CALL_REFERENCE || !rc->caller_qn || !rc->callee_qn ||
+ rc->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
+ continue;
+ }
+ if (!cbm_pipeline_qn_class_method_tail_eq(rc->caller_qn, caller_tail) ||
+ !cbm_pipeline_source_occurrence_eq(usage->site_start_byte, usage->site_end_byte,
+ usage->source_origin, rc->site_start_byte,
+ rc->site_end_byte, rc->source_origin)) {
+ continue;
+ }
+ bool name_matches = strcmp(cbm_lsp_bare_segment(rc->callee_qn), ref_leaf) == 0;
+ bool semantic_reason_matches = cbm_pipeline_reference_reason_matches(rc, ref_leaf);
+ if (!name_matches && !semantic_reason_matches) {
+ continue;
+ }
+ if (!best_tail) {
+ best_tail = rc;
+ continue;
+ }
+ if (!cbm_pipeline_reference_targets_equal(best_tail->callee_qn, rc->callee_qn, gbuf,
+ project_name, allow_tail_match)) {
+ tail_ambiguous = true;
+ continue;
+ }
+ if (rc->confidence > best_tail->confidence) {
+ best_tail = rc;
+ }
+ }
+ return tail_ambiguous ? NULL : best_tail;
+}
+
+/* Full-array compatibility/fallback path. Allocation failure in either
+ * materializer deliberately lands here rather than dropping semantic edges. */
+static inline const CBMResolvedCall *cbm_pipeline_find_lsp_reference_in_graph(
+ const CBMResolvedCallArray *arr, const CBMUsage *usage, bool allow_tail_match,
+ const cbm_gbuf_t *gbuf, const char *project_name) {
+ int count = arr ? arr->count : 0;
+ return cbm_pipeline_find_lsp_reference_view_in_graph(arr, NULL, 0, count, usage,
+ allow_tail_match, gbuf, project_name);
+}
+
+/* Binary-search the exact (origin,start,end) occurrence, then run the shared
+ * matcher only over that stable-order slice. A NULL index means construction
+ * failed and selects the original linear fallback above. */
+static inline const CBMResolvedCall *cbm_pipeline_find_lsp_reference_indexed_in_graph(
+ const CBMResolvedCallArray *arr, const cbm_pipeline_lsp_reference_index_t *index,
+ const CBMUsage *usage, bool allow_tail_match, const cbm_gbuf_t *gbuf,
+ const char *project_name) {
+ if (!index) {
+ return cbm_pipeline_find_lsp_reference_in_graph(arr, usage, allow_tail_match, gbuf,
+ project_name);
+ }
+ if (!usage || !usage->enclosing_func_qn || !usage->ref_name || index->count <= 0) {
+ return NULL;
+ }
+
+ int low = 0;
+ int high = index->count;
+ while (low < high) {
+ int middle = low + (high - low) / 2;
+ if (cbm_pipeline_lsp_reference_site_cmp_usage(index->entries[middle].row, usage) < 0) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ int first = low;
+ high = index->count;
+ while (low < high) {
+ int middle = low + (high - low) / 2;
+ if (cbm_pipeline_lsp_reference_site_cmp_usage(index->entries[middle].row, usage) <= 0) {
+ low = middle + 1;
+ } else {
+ high = middle;
+ }
+ }
+ int row_count = low - first;
+ return cbm_pipeline_find_lsp_reference_view_in_graph(
+ arr, index->entries, first, row_count, usage, allow_tail_match, gbuf, project_name);
+}
+
+/* String-strict helper retained for unit tests and callers without a graph.
+ * Production edge materialization uses the graph-aware variant above. */
+static inline const CBMResolvedCall *cbm_pipeline_find_lsp_reference(
+ const CBMResolvedCallArray *arr, const CBMUsage *usage, bool allow_tail_match) {
+ return cbm_pipeline_find_lsp_reference_in_graph(arr, usage, allow_tail_match, NULL, NULL);
}
/* Resolve an LSP-emitted callee_qn to a graph-buffer node.
@@ -234,13 +851,14 @@ static inline const CBMResolvedCall *cbm_pipeline_find_lsp_resolution(
* cbm_pipeline_lsp_allow_tail_match), use the exact node-name index
* to narrow candidates by short method name and accept exactly one
* Function/Method whose qualified_name has the same Class.method
- * tail.
+ * tail;
+ * 4. when a package-shaped top-level JVM QN cannot share a tail with the
+ * graph's file-shaped QN, accept one globally unique callable short name.
*
* Returns the matching node, or NULL if neither lookup hits. */
-static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node(const cbm_gbuf_t *gbuf,
- const char *project_name,
- const char *callee_qn,
- bool allow_tail_match) {
+static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node_policy(
+ const cbm_gbuf_t *gbuf, const char *project_name, const char *callee_qn, bool allow_tail_match,
+ bool allow_unique_callable_fallback) {
if (!gbuf || !callee_qn) {
return NULL;
}
@@ -251,12 +869,19 @@ static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node(const cbm_gbuf
if (project_name && project_name[0]) {
size_t proj_len = strlen(project_name);
if (!(strncmp(callee_qn, project_name, proj_len) == 0 && callee_qn[proj_len] == '.')) {
- char buf[CBM_SZ_1K];
- int written = snprintf(buf, sizeof(buf), "%s.%s", project_name, callee_qn);
- if (written > 0 && (size_t)written < sizeof(buf)) {
- const cbm_gbuf_node_t *prefixed = cbm_gbuf_find_by_qn(gbuf, buf);
- if (prefixed) {
- return prefixed;
+ size_t callee_len = strlen(callee_qn);
+ if (proj_len <= SIZE_MAX - callee_len - 2U) {
+ size_t prefixed_len = proj_len + 1U + callee_len;
+ char *prefixed_qn = (char *)malloc(prefixed_len + 1U);
+ if (prefixed_qn) {
+ memcpy(prefixed_qn, project_name, proj_len);
+ prefixed_qn[proj_len] = '.';
+ memcpy(prefixed_qn + proj_len + 1U, callee_qn, callee_len + 1U);
+ const cbm_gbuf_node_t *prefixed = cbm_gbuf_find_by_qn(gbuf, prefixed_qn);
+ free(prefixed_qn);
+ if (prefixed) {
+ return prefixed;
+ }
}
}
}
@@ -278,6 +903,9 @@ static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node(const cbm_gbuf
}
const cbm_gbuf_node_t *match = NULL;
+ const cbm_gbuf_node_t *unique_callable = NULL;
+ bool tail_ambiguous = false;
+ bool callable_ambiguous = false;
for (int i = 0; i < hit_count; i++) {
const cbm_gbuf_node_t *cand = hits[i];
if (!cand || !cand->label || !cand->qualified_name) {
@@ -286,15 +914,27 @@ static inline const cbm_gbuf_node_t *cbm_pipeline_lsp_target_node(const cbm_gbuf
if (strcmp(cand->label, "Function") != 0 && strcmp(cand->label, "Method") != 0) {
continue;
}
+ if (!unique_callable) {
+ unique_callable = cand;
+ } else if (unique_callable->id != cand->id) {
+ callable_ambiguous = true;
+ }
if (!cbm_pipeline_qn_class_method_tail_eq(cand->qualified_name, callee_tail)) {
continue;
}
- if (match) {
- return NULL;
+ if (match && match->id != cand->id) {
+ tail_ambiguous = true;
+ continue;
}
match = cand;
}
- return match;
+ if (match) {
+ return tail_ambiguous ? NULL : match;
+ }
+ if (!allow_unique_callable_fallback) {
+ return NULL;
+ }
+ return callable_ambiguous ? NULL : unique_callable;
}
#endif /* CBM_PIPELINE_LSP_RESOLVE_H */
diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.c
index 6db2a73f7..8cb4083b6 100644
--- a/src/pipeline/pass_calls.c
+++ b/src/pipeline/pass_calls.c
@@ -467,10 +467,16 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
/* 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(lsp_calls, call, allow_tail);
+ const CBMResolvedCall *lsp = cbm_pipeline_find_lsp_resolution_in_graph(
+ lsp_calls, call, allow_tail, ctx->gbuf, ctx->project_name);
if (lsp) {
+ bool exact_external_target = call->requires_lsp_resolution &&
+ cbm_pipeline_kotlin_external_target(lang, lsp->callee_qn);
const cbm_gbuf_node_t *target_node =
- cbm_pipeline_lsp_target_node(ctx->gbuf, ctx->project_name, lsp->callee_qn, allow_tail);
+ exact_external_target ? cbm_pipeline_lsp_target_node_strict(
+ ctx->gbuf, ctx->project_name, lsp->callee_qn, allow_tail)
+ : cbm_pipeline_lsp_target_node(ctx->gbuf, ctx->project_name,
+ lsp->callee_qn, allow_tail);
if (target_node && source_node->id != target_node->id) {
cbm_resolution_t res = {0};
/* Use the gbuf node's QN so downstream edge props show the canonical
@@ -485,6 +491,15 @@ static int resolve_single_call(cbm_pipeline_ctx_t *ctx, CBMCall *call,
}
}
+ /* Synthetic semantic candidates (currently implicit C++ operators) are
+ * valid calls only when the language resolver identifies a concrete
+ * invocation target. Textual registry/service fallbacks would bind an
+ * unresolved primitive expression such as `int + int` to an unrelated
+ * project `operator+`, fabricating a CALLS edge. */
+ if (call->requires_lsp_resolution) {
+ return 0;
+ }
+
/* Service-pattern HTTP/ASYNC client call (`requests.get(url)`): the service
* signal lives in the callee_name. The registry can mis-resolve such a call
* to a spurious builtin short-name match (e.g. `requests.get` ->
diff --git a/src/pipeline/pass_definitions.c b/src/pipeline/pass_definitions.c
index ebbb95414..2aea44d4e 100644
--- a/src/pipeline/pass_definitions.c
+++ b/src/pipeline/pass_definitions.c
@@ -405,8 +405,8 @@ static void create_channel_edges_for_file(cbm_pipeline_ctx_t *ctx, const CBMFile
* env key and link the enclosing function (or the file node) CONFIGURES-> it,
* so environment-driven configuration is visible even when the accessor is a
* stdlib symbol that never resolves to an in-graph callee. */
-static int create_env_configures_for_file(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,
- const char *rel) {
+int cbm_pipeline_create_env_configures_for_file(cbm_pipeline_ctx_t *ctx,
+ const CBMFileResult *result, const char *rel) {
int count = 0;
char *file_qn = NULL;
const cbm_gbuf_node_t *file_node = NULL;
@@ -481,6 +481,186 @@ static int create_import_edges_for_file(cbm_pipeline_ctx_t *ctx, const CBMFileRe
return count;
}
+static bool objectscript_export_append_strings(CBMArena *arena, const char ***dst,
+ const char *const *src) {
+ if (!src) {
+ return true;
+ }
+ int old_count = 0;
+ int add_count = 0;
+ while (*dst && (*dst)[old_count]) {
+ old_count++;
+ }
+ while (src[add_count]) {
+ add_count++;
+ }
+ const char **items = (const char **)cbm_arena_alloc(arena, (size_t)(old_count + add_count + 1) *
+ sizeof(const char *));
+ if (!items) {
+ return false;
+ }
+ for (int i = 0; i < old_count; i++) {
+ items[i] = (*dst)[i];
+ }
+ for (int i = 0; i < add_count; i++) {
+ items[old_count + i] = src[i];
+ }
+ items[old_count + add_count] = NULL;
+ *dst = items;
+ return true;
+}
+
+#define OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, field, push_fn) \
+ do { \
+ int expected_count = (aggregate)->field.count + (part)->field.count; \
+ for (int item_i = 0; item_i < (part)->field.count; item_i++) { \
+ push_fn(&(aggregate)->field, &(aggregate)->arena, (part)->field.items[item_i]); \
+ } \
+ if ((aggregate)->field.count != expected_count) { \
+ return false; \
+ } \
+ } while (0)
+
+static bool objectscript_export_append_primary_arrays(CBMFileResult *aggregate,
+ const CBMFileResult *part) {
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, defs, cbm_defs_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, calls, cbm_calls_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, imports, cbm_imports_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, usages, cbm_usages_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, throws, cbm_throws_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, rw, cbm_rw_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, type_refs, cbm_typerefs_push);
+ return true;
+}
+
+static bool objectscript_export_append_secondary_arrays(CBMFileResult *aggregate,
+ const CBMFileResult *part) {
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, env_accesses, cbm_envaccess_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, type_assigns, cbm_typeassign_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, impl_traits, cbm_impltrait_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, resolved_calls, cbm_resolvedcall_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, string_refs, cbm_stringref_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, infra_bindings, cbm_infrabinding_push);
+ OBJECTSCRIPT_EXPORT_APPEND_ARRAY(aggregate, part, channels, cbm_channels_push);
+ return true;
+}
+
+/* Preserve every generated class's parse diagnostics. The generated UDL
+ * snippets all map back to one physical Studio Export file, so their compact
+ * range lists can be concatenated using the ordinary comma separator. */
+static bool objectscript_export_append_error_ranges(CBMFileResult *aggregate,
+ const CBMFileResult *part) {
+ aggregate->parse_incomplete = aggregate->parse_incomplete || part->parse_incomplete;
+ aggregate->error_region_count += part->error_region_count;
+ if (!part->error_ranges || !part->error_ranges[0]) {
+ return true;
+ }
+ const char *combined = NULL;
+ if (aggregate->error_ranges && aggregate->error_ranges[0]) {
+ combined = cbm_arena_sprintf(&aggregate->arena, "%s,%s", aggregate->error_ranges,
+ part->error_ranges);
+ } else {
+ combined = cbm_arena_strdup(&aggregate->arena, part->error_ranges);
+ }
+ if (!combined) {
+ return false;
+ }
+ aggregate->error_ranges = combined;
+ return true;
+}
+
+/* Studio Export files may contain multiple <Class> elements, while the
+ * pipeline cache has one slot per physical file. Extract each generated UDL
+ * class independently (preserving the upstream parser behavior), then compose
+ * every extracted carrier into one result for the normal registry/call/usage/
+ * semantic passes. */
+CBMFileResult *cbm_pipeline_extract_objectscript_export(
+ const char *source, int source_len, const char *project_name, const char *rel_path,
+ const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table) {
+ CBMArena export_arena;
+ cbm_arena_init(&export_arena);
+ int class_count = 0;
+ char **udl_strings = cbm_iris_export_to_udl(&export_arena, source, source_len, &class_count);
+ if (!udl_strings || class_count <= 0) {
+ cbm_arena_destroy(&export_arena);
+ return NULL;
+ }
+
+ CBMFileResult *aggregate = (CBMFileResult *)calloc(1, sizeof(CBMFileResult));
+ if (!aggregate) {
+ cbm_arena_destroy(&export_arena);
+ return NULL;
+ }
+ cbm_arena_init(&aggregate->arena);
+ if (aggregate->arena.nblocks == 0) {
+ cbm_free_result(aggregate);
+ cbm_arena_destroy(&export_arena);
+ return NULL;
+ }
+ aggregate->owned_results =
+ (CBMFileResult **)calloc((size_t)class_count, sizeof(CBMFileResult *));
+ if (!aggregate->owned_results) {
+ cbm_free_result(aggregate);
+ cbm_arena_destroy(&export_arena);
+ return NULL;
+ }
+ aggregate->cached_lang = CBM_LANG_OBJECTSCRIPT_UDL;
+
+ for (int ci = 0; ci < class_count; ci++) {
+ CBMFileResult *part = cbm_extract_file_ex(
+ udl_strings[ci], (int)strlen(udl_strings[ci]), CBM_LANG_OBJECTSCRIPT_UDL, project_name,
+ rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, macro_table, return_type_table);
+ if (!part) {
+ continue;
+ }
+
+ /* The aggregate has no single parse tree. Later ObjectScript Export
+ * passes consume extracted carriers, not a raw-XML tree. */
+ cbm_free_tree(part);
+ if (!objectscript_export_append_primary_arrays(aggregate, part) ||
+ !objectscript_export_append_secondary_arrays(aggregate, part) ||
+ !objectscript_export_append_strings(&aggregate->arena, &aggregate->exports,
+ part->exports) ||
+ !objectscript_export_append_strings(&aggregate->arena, &aggregate->constants,
+ part->constants) ||
+ !objectscript_export_append_strings(&aggregate->arena, &aggregate->global_vars,
+ part->global_vars) ||
+ !objectscript_export_append_strings(&aggregate->arena, &aggregate->macros,
+ part->macros) ||
+ !objectscript_export_append_error_ranges(aggregate, part)) {
+ goto merge_failed;
+ }
+
+ if (!aggregate->module_qn) {
+ aggregate->module_qn = part->module_qn;
+ }
+ if (!aggregate->namespace_name) {
+ aggregate->namespace_name = part->namespace_name;
+ }
+ if (part->has_error) {
+ aggregate->has_error = true;
+ if (!aggregate->error_msg) {
+ aggregate->error_msg = part->error_msg;
+ }
+ }
+ aggregate->is_test_file = aggregate->is_test_file || part->is_test_file;
+ aggregate->owned_results[aggregate->owned_result_count++] = part;
+ continue;
+
+ merge_failed:
+ cbm_free_result(part);
+ cbm_free_result(aggregate);
+ cbm_arena_destroy(&export_arena);
+ return NULL;
+ }
+
+ aggregate->imports_count = aggregate->imports.count;
+ cbm_arena_destroy(&export_arena);
+ return aggregate;
+}
+
+#undef OBJECTSCRIPT_EXPORT_APPEND_ARRAY
+
int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int file_count) {
cbm_log_info("pass.start", "pass", "definitions", "files", itoa_log(file_count));
@@ -568,42 +748,15 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
continue;
}
- /* ObjectScript Studio Export XML: transcode each <Class> to UDL and
- * extract it as CBM_LANG_OBJECTSCRIPT_UDL. The XML→UDL mapping is 1:1,
- * so the same UDL extractor handles the result. These files are not
- * cached (their defs/edges are emitted directly here). */
- if (lang == CBM_LANG_OBJECTSCRIPT_EXPORT) {
- CBMArena export_arena;
- cbm_arena_init(&export_arena);
- int class_count = 0;
- char **udl_strings =
- cbm_iris_export_to_udl(&export_arena, source, source_len, &class_count);
- free(source);
- for (int ci = 0; ci < class_count; ci++) {
- CBMFileResult *xr = cbm_extract_file_ex(
- udl_strings[ci], (int)strlen(udl_strings[ci]), CBM_LANG_OBJECTSCRIPT_UDL,
- ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL, NULL, ctx->macro_table, NULL);
- if (!xr) {
- continue;
- }
- for (int d = 0; d < xr->defs.count; d++) {
- process_def(ctx, &xr->defs.items[d], rel);
- total_defs++;
- }
- total_calls += xr->calls.count;
- total_imports += create_import_edges_for_file(ctx, xr, rel, NULL);
- create_channel_edges_for_file(ctx, xr, rel);
- create_env_configures_for_file(ctx, xr, rel);
- cbm_free_result(xr);
- }
- cbm_arena_destroy(&export_arena);
- continue;
- }
-
- /* Extract */
- CBMFileResult *result = cbm_extract_file_ex(
- source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL,
- NULL /* no extra defines or include paths */, ctx->macro_table, NULL);
+ /* Studio Export XML is transformed to one cacheable aggregate so later
+ * passes see the same calls/usages/semantic carriers as native UDL. */
+ CBMFileResult *result =
+ lang == CBM_LANG_OBJECTSCRIPT_EXPORT
+ ? cbm_pipeline_extract_objectscript_export(source, source_len, ctx->project_name,
+ rel, ctx->macro_table, NULL)
+ : cbm_extract_file_ex(
+ source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL,
+ NULL /* no extra defines or include paths */, ctx->macro_table, NULL);
free(source);
if (!result) {
@@ -647,7 +800,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
* map is available without the cache (single-file scope). */
total_imports += create_import_edges_for_file(ctx, result, rel, NULL);
create_channel_edges_for_file(ctx, result, rel);
- create_env_configures_for_file(ctx, result, rel);
+ cbm_pipeline_create_env_configures_for_file(ctx, result, rel);
cbm_free_result(result);
}
}
@@ -680,7 +833,7 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
total_imports +=
create_import_edges_for_file(ctx, result, files[i].rel_path, namespace_map);
create_channel_edges_for_file(ctx, result, files[i].rel_path);
- create_env_configures_for_file(ctx, result, files[i].rel_path);
+ cbm_pipeline_create_env_configures_for_file(ctx, result, files[i].rel_path);
}
cbm_pipeline_namespace_map_free(namespace_map);
if (owns_local_cache) {
diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c
index 7194bd5b5..79c45fe60 100644
--- a/src/pipeline/pass_lsp_cross.c
+++ b/src/pipeline/pass_lsp_cross.c
@@ -15,6 +15,7 @@
*/
#include "pipeline/pass_lsp_cross.h"
#include "pipeline/pipeline_internal.h"
+#include "pipeline/lsp_resolve.h"
#include "lsp/go_lsp.h"
#include "lsp/c_lsp.h"
#include "lsp/py_lsp.h"
@@ -31,6 +32,7 @@
#include "foundation/compat_fs.h"
#include <stdio.h>
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
@@ -234,6 +236,19 @@ static const char *pxc_infer_jvm_namespace(CBMArena *arena, const char *rel_path
return ns;
}
+static const char *pxc_qn_leaf(const char *name) {
+ if (!name) {
+ return NULL;
+ }
+ const char *leaf = name;
+ for (const char *p = name; *p; p++) {
+ if (*p == '.' || *p == ':' || *p == '/' || *p == '\\') {
+ leaf = p + 1;
+ }
+ }
+ return leaf;
+}
+
/* Convert one CBMDefinition into a CBMLSPDef. Returns 0 on success, -1
* to skip (unsupported label or missing required field). dst gets borrowed
* pointers into src and into `arena` for synthesised composites. */
@@ -260,7 +275,39 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
* piece, which is what's already stored. */
dst->return_types = src->return_type;
dst->embedded_types = pxc_join_pipe(arena, src->base_classes);
+ dst->signature_param_types = src->signature_param_types;
+ dst->signature_param_count = src->signature_param_count;
dst->lang = lang;
+ dst->decorators = src->decorators;
+ if (lang == CBM_LANG_RUST) {
+ /* Exact impl-block provenance is captured while the Rust impl node is
+ * still on hand. Do not reconstruct it later from leaf names. */
+ dst->trait_qn = src->impl_trait;
+ dst->is_abstract = src->is_abstract;
+ }
+ return 0;
+}
+
+/* Carry one Rust type-level impl independently of any method definition.
+ * `impl Trait for Type {}` is semantically meaningful even when the block is
+ * empty (the trait may provide defaults), so attaching the relation only to
+ * concrete method records is lossy. */
+static int pxc_build_rust_impl_relation(CBMArena *arena, const CBMImplTrait *impl,
+ const char *project_name, const char *rel_path,
+ const char *module_qn, CBMLSPDef *dst) {
+ if (!arena || !impl || !impl->trait_name || !impl->struct_name || !impl->struct_qn) {
+ return -1;
+ }
+ const char *receiver_qn = impl->struct_qn;
+ memset(dst, 0, sizeof(*dst));
+ dst->qualified_name = receiver_qn;
+ dst->short_name = pxc_qn_leaf(receiver_qn);
+ dst->label = "RustImpl";
+ dst->receiver_type = receiver_qn;
+ dst->def_module_qn = module_qn;
+ dst->trait_qn = impl->trait_name; /* raw; canonicalized by Rust registry */
+ dst->lang = CBM_LANG_RUST;
+ dst->is_rust_impl_relation = true;
return 0;
}
@@ -272,8 +319,12 @@ CBMLSPDef *cbm_pxc_collect_all_defs(CBMFileResult **cache, const cbm_file_info_t
int *out_count) {
int total = 0;
for (int i = 0; i < file_count; i++) {
- if (cache[i])
+ if (cache[i]) {
total += cache[i]->defs.count;
+ if (files[i].language == CBM_LANG_RUST) {
+ total += cache[i]->impl_traits.count;
+ }
+ }
}
if (total == 0) {
*out_count = 0;
@@ -306,39 +357,198 @@ CBMLSPDef *cbm_pxc_collect_all_defs(CBMFileResult **cache, const cbm_file_info_t
idx++;
}
}
+ if (files[fi].language == CBM_LANG_RUST) {
+ for (int ii = 0; ii < cache[fi]->impl_traits.count; ii++) {
+ if (pxc_build_rust_impl_relation(
+ &cache[fi]->arena, &cache[fi]->impl_traits.items[ii], project_name,
+ files[fi].rel_path, def_modules[fi], &defs[idx]) == 0) {
+ idx++;
+ }
+ }
+ }
}
*out_count = idx;
return defs;
}
-/* Build per-file import map (local_name -> resolved module QN) from gbuf
- * IMPORTS edges. Mirrors build_import_map() in pass_parallel.c. Returns 0
- * with *out_count = 0 when the file has no IMPORTS edges. Caller frees keys
- * with pxc_free_import_map. */
-static int pxc_build_import_map(const cbm_gbuf_t *gbuf, const char *project_name,
- const char *rel_path, const char ***out_keys,
- const char ***out_vals, int *out_count) {
+/* Return the one source import path bound to `local_name`, or NULL when the
+ * extraction metadata is absent or two distinct imports bind the same local.
+ * The latter is deliberately fail-closed: choosing either path would turn an
+ * ambiguous Python value into a fabricated CALL_REFERENCE. */
+static const char *pxc_unique_import_path(const CBMFileResult *result, const char *local_name,
+ bool *out_ambiguous) {
+ if (out_ambiguous)
+ *out_ambiguous = false;
+ if (!result || !local_name)
+ return NULL;
+ const char *path = NULL;
+ for (int i = 0; i < result->imports.count; i++) {
+ const CBMImport *imp = &result->imports.items[i];
+ if (!imp->local_name || !imp->module_path || strcmp(imp->local_name, local_name) != 0) {
+ continue;
+ }
+ if (path && strcmp(path, imp->module_path) != 0) {
+ if (out_ambiguous)
+ *out_ambiguous = true;
+ return NULL;
+ }
+ path = imp->module_path;
+ }
+ return path;
+}
+
+static const char *pxc_import_leaf(const char *path) {
+ if (!path)
+ return NULL;
+ const char *leaf = path;
+ for (const char *p = path; *p; p++) {
+ if (*p == '.' || *p == '/' || *p == '\\' || *p == ':')
+ leaf = p + 1;
+ }
+ return leaf;
+}
+
+static char *pxc_kotlin_import_from_metadata(const CBMFileResult *result, const char *local_name) {
+ bool ambiguous = false;
+ const char *path = pxc_unique_import_path(result, local_name, &ambiguous);
+ const char *leaf = pxc_import_leaf(path);
+ if (ambiguous || !path || !path[0] || path[0] == '.' || !leaf ||
+ strcmp(leaf, local_name) != 0) {
+ return NULL;
+ }
+ /* Keep the source package/member spelling. Kotlin cross registries are
+ * package-qualified (target.actual), not path/project-qualified. The
+ * resolver still requires a registered function/type before emitting an
+ * exact semantic relationship. */
+ return strdup(path);
+}
+
+/* IMPORTS edges correctly target dependency modules, but Python from-imports
+ * also carry a source-level member: `from target import handler` is extracted
+ * as module_path=`target.handler` while its edge targets Module `P.target`.
+ * Reattach that member only when the raw metadata proves one unique,
+ * non-aliased path. The shared Python registry must still materialize the
+ * resulting exact QN before it earns CALL_REFERENCE. */
+static char *pxc_import_value_qn(CBMLanguage lang, const CBMFileResult *result,
+ const char *local_name, const cbm_gbuf_node_t *target) {
+ if (!target || !target->qualified_name)
+ return NULL;
+ if (lang == CBM_LANG_KOTLIN)
+ return pxc_kotlin_import_from_metadata(result, local_name);
+ if (lang != CBM_LANG_PYTHON)
+ return strdup(target->qualified_name);
+
+ bool ambiguous = false;
+ const char *path = pxc_unique_import_path(result, local_name, &ambiguous);
+ if (ambiguous)
+ return NULL;
+ const char *source_leaf = pxc_import_leaf(path);
+ const char *target_leaf = pxc_import_leaf(target->qualified_name);
+ if (!path || !source_leaf || !target_leaf || strcmp(source_leaf, local_name) != 0 ||
+ strcmp(source_leaf, target_leaf) == 0 || !target->label ||
+ (strcmp(target->label, "Module") != 0 && strcmp(target->label, "Folder") != 0)) {
+ return strdup(target->qualified_name);
+ }
+
+ size_t need = strlen(target->qualified_name) + 1 + strlen(source_leaf) + 1;
+ char *qualified = (char *)malloc(need);
+ if (!qualified)
+ return NULL;
+ snprintf(qualified, need, "%s.%s", target->qualified_name, source_leaf);
+ return qualified;
+}
+
+static bool pxc_import_map_has_local(const char *const *keys, int count, const char *local_name) {
+ if (!keys || !local_name)
+ return false;
+ for (int i = 0; i < count; i++) {
+ if (keys[i] && strcmp(keys[i], local_name) == 0)
+ return true;
+ }
+ return false;
+}
+
+/* Recover a Python import directly from extraction metadata when graph import
+ * materialization produced no edge. Prefer an already materialized exact node
+ * (including the shared project-prefix rule); otherwise accept only the
+ * ordinary non-aliased dotted spelling and let the sealed Python registry
+ * decide whether that QN denotes a class/function. A wrong candidate cannot
+ * earn a semantic edge because the resolver requires registry materialization. */
+static char *pxc_python_import_from_metadata(const cbm_gbuf_t *gbuf, const char *project_name,
+ const char *local_name, const char *module_path) {
+ if (!gbuf || !local_name || !module_path)
+ return NULL;
+ const char *source_leaf = pxc_import_leaf(module_path);
+ if (!source_leaf || strcmp(source_leaf, local_name) != 0 || module_path[0] == '.')
+ return NULL;
+
+ const cbm_gbuf_node_t *exact =
+ cbm_pipeline_lsp_target_node(gbuf, project_name, module_path, false);
+ if (exact && exact->qualified_name)
+ return strdup(exact->qualified_name);
+
+ const char *last_dot = strrchr(module_path, '.');
+ if (last_dot && last_dot > module_path) {
+ size_t module_len = (size_t)(last_dot - module_path);
+ char *module = (char *)malloc(module_len + 1);
+ if (!module)
+ return NULL;
+ memcpy(module, module_path, module_len);
+ module[module_len] = '\0';
+ const cbm_gbuf_node_t *module_node =
+ cbm_pipeline_lsp_target_node(gbuf, project_name, module, false);
+ free(module);
+ if (module_node && module_node->qualified_name && module_node->label &&
+ (strcmp(module_node->label, "Module") == 0 ||
+ strcmp(module_node->label, "Folder") == 0)) {
+ size_t need = strlen(module_node->qualified_name) + 1 + strlen(source_leaf) + 1;
+ char *qualified = (char *)malloc(need);
+ if (!qualified)
+ return NULL;
+ snprintf(qualified, need, "%s.%s", module_node->qualified_name, source_leaf);
+ return qualified;
+ }
+ }
+
+ if (!project_name || !project_name[0])
+ return strdup(module_path);
+ size_t need = strlen(project_name) + 1 + strlen(module_path) + 1;
+ char *qualified = (char *)malloc(need);
+ if (!qualified)
+ return NULL;
+ snprintf(qualified, need, "%s.%s", project_name, module_path);
+ return qualified;
+}
+
+/* Build per-file import map (local_name -> semantic import QN) from gbuf
+ * IMPORTS edges. Both pipeline drivers call this implementation. Returns 0
+ * with *out_count = 0 when the file has no IMPORTS edges. */
+int cbm_pxc_build_import_map(const cbm_gbuf_t *gbuf, const char *project_name, const char *rel_path,
+ CBMLanguage lang, const CBMFileResult *result, const char ***out_keys,
+ const char ***out_vals, int *out_count) {
*out_keys = NULL;
*out_vals = NULL;
*out_count = 0;
+ const cbm_gbuf_edge_t **edges = NULL;
+ int edge_count = 0;
char *file_qn = cbm_pipeline_fqn_compute(project_name, rel_path, "__file__");
- if (!file_qn)
- return 0;
- const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(gbuf, file_qn);
+ const cbm_gbuf_node_t *file_node = file_qn ? cbm_gbuf_find_by_qn(gbuf, file_qn) : NULL;
free(file_qn);
- if (!file_node)
- return 0;
+ if (file_node && cbm_gbuf_find_edges_by_source_type(gbuf, file_node->id, "IMPORTS", &edges,
+ &edge_count) != 0) {
+ edges = NULL;
+ edge_count = 0;
+ }
- const cbm_gbuf_edge_t **edges = NULL;
- int edge_count = 0;
- int rc =
- cbm_gbuf_find_edges_by_source_type(gbuf, file_node->id, "IMPORTS", &edges, &edge_count);
- if (rc != 0 || edge_count == 0)
+ int metadata_count =
+ (lang == CBM_LANG_PYTHON || lang == CBM_LANG_KOTLIN) && result ? result->imports.count : 0;
+ if (edge_count == 0 && metadata_count == 0)
return 0;
- const char **keys = (const char **)calloc((size_t)edge_count, sizeof(const char *));
- const char **vals = (const char **)calloc((size_t)edge_count, sizeof(const char *));
+ size_t capacity = (size_t)edge_count + (size_t)metadata_count;
+ const char **keys = (const char **)calloc(capacity, sizeof(const char *));
+ const char **vals = (const char **)calloc(capacity, sizeof(const char *));
if (!keys || !vals) {
free(keys);
free(vals);
@@ -363,8 +573,43 @@ static int pxc_build_import_map(const cbm_gbuf_t *gbuf, const char *project_name
continue;
memcpy(local, start, n);
local[n] = '\0';
+ char *value = pxc_import_value_qn(lang, result, local, target);
+ if (!value) {
+ free(local);
+ continue;
+ }
+ keys[count] = local;
+ vals[count] = value;
+ count++;
+ }
+
+ /* IMPORTS edges are best-effort graph relationships. The cross-LSP still
+ * has the authoritative extraction metadata in both sequential and
+ * parallel caches, so a missing edge must not erase an otherwise exact
+ * Python import. Add only locals not already represented by an edge. */
+ for (int i = 0; i < metadata_count; i++) {
+ const CBMImport *imp = &result->imports.items[i];
+ if (!imp->local_name || !imp->local_name[0] || !imp->module_path ||
+ pxc_import_map_has_local(keys, count, imp->local_name)) {
+ continue;
+ }
+ bool ambiguous = false;
+ const char *path = pxc_unique_import_path(result, imp->local_name, &ambiguous);
+ if (ambiguous || !path)
+ continue;
+ char *value =
+ lang == CBM_LANG_KOTLIN
+ ? pxc_kotlin_import_from_metadata(result, imp->local_name)
+ : pxc_python_import_from_metadata(gbuf, project_name, imp->local_name, path);
+ if (!value)
+ continue;
+ char *local = strdup(imp->local_name);
+ if (!local) {
+ free(value);
+ continue;
+ }
keys[count] = local;
- vals[count] = target->qualified_name; /* borrowed from gbuf */
+ vals[count] = value;
count++;
}
*out_keys = keys;
@@ -373,13 +618,17 @@ static int pxc_build_import_map(const cbm_gbuf_t *gbuf, const char *project_name
return 0;
}
-static void pxc_free_import_map(const char **keys, const char **vals, int count) {
+void cbm_pxc_free_import_map(const char **keys, const char **vals, int count) {
if (keys) {
for (int i = 0; i < count; i++)
free((void *)keys[i]);
free((void *)keys);
}
- free((void *)vals); /* vals strings borrowed from gbuf — don't free elements */
+ if (vals) {
+ for (int i = 0; i < count; i++)
+ free((void *)vals[i]);
+ free((void *)vals);
+ }
}
/* Detect TS dialect flags from a relative path. */
@@ -424,10 +673,14 @@ bool cbm_pxc_has_cross_lsp(CBMLanguage lang) {
/* Append cross-file results from `src_out` (allocated in a scratch arena
* about to be destroyed) into `dst_calls` (lives in cache_entry->arena),
* copying every string field into dst_arena. Skips entries whose
- * (caller_qn, callee_qn) is already present — avoids inflating the array with
- * cross-file duplicates of per-file LSP output.
+ * (kind, caller_qn, callee_qn, source span) is already present — avoids
+ * inflating the array with cross-file duplicates without conflating distinct
+ * same-named occurrences. For an exact duplicate, retain the higher-confidence
+ * record.
*
- * Dedup uses a hash set keyed on "caller\x1fcallee", giving O(1) membership.
+ * Dedup uses a hash table keyed on
+ * "kind\x1fcaller\x1fcallee\x1fstart:end\x1forigin", giving O(1)
+ * membership.
* The previous linear strcmp scan made each append O(n), so a file that
* resolved very many cross-calls turned the whole append into O(n^2) and could
* peg a core for minutes (observed: an index hung in pxc_append_results/strcmp).
@@ -444,9 +697,16 @@ static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_ca
for (int i = 0; i < dst_calls->count; i++) {
const CBMResolvedCall *rc = &dst_calls->items[i];
if (rc->caller_qn && rc->callee_qn) {
- char *k = cbm_arena_sprintf(&keys, "%s\x1f%s", rc->caller_qn, rc->callee_qn);
+ char *k = cbm_arena_sprintf(&keys, "%u\x1f%s\x1f%s\x1f%u:%u\x1f%u", (unsigned)rc->kind,
+ rc->caller_qn, rc->callee_qn, rc->site_start_byte,
+ rc->site_end_byte, (unsigned)rc->source_origin);
if (k) {
- cbm_ht_set(seen, k, (void *)1);
+ void *prior = cbm_ht_get(seen, k);
+ if (!prior ||
+ rc->confidence > dst_calls->items[(int)(uintptr_t)prior - 1].confidence) {
+ const char *stored = cbm_ht_get_key(seen, k);
+ cbm_ht_set(seen, stored ? stored : k, (void *)(uintptr_t)(i + 1));
+ }
}
}
}
@@ -455,20 +715,104 @@ static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_ca
const CBMResolvedCall *src = &src_out->items[j];
if (!src->caller_qn || !src->callee_qn)
continue;
- char *k = cbm_arena_sprintf(&keys, "%s\x1f%s", src->caller_qn, src->callee_qn);
- if (k && cbm_ht_has(seen, k))
+ char *k = cbm_arena_sprintf(&keys, "%u\x1f%s\x1f%s\x1f%u:%u\x1f%u", (unsigned)src->kind,
+ src->caller_qn, src->callee_qn, src->site_start_byte,
+ src->site_end_byte, (unsigned)src->source_origin);
+ void *prior = k ? cbm_ht_get(seen, k) : NULL;
+ if (prior) {
+ CBMResolvedCall *dst = &dst_calls->items[(int)(uintptr_t)prior - 1];
+ if (src->confidence > dst->confidence) {
+ dst->caller_qn = cbm_arena_strdup(dst_arena, src->caller_qn);
+ dst->callee_qn = cbm_arena_strdup(dst_arena, src->callee_qn);
+ dst->strategy = src->strategy ? cbm_arena_strdup(dst_arena, src->strategy) : NULL;
+ dst->confidence = src->confidence;
+ dst->reason = src->reason ? cbm_arena_strdup(dst_arena, src->reason) : NULL;
+ dst->kind = src->kind;
+ dst->site_start_byte = src->site_start_byte;
+ dst->site_end_byte = src->site_end_byte;
+ dst->source_origin = src->source_origin;
+ }
continue;
- if (k) {
- cbm_ht_set(seen, k, (void *)1);
}
- CBMResolvedCall dst;
- memset(&dst, 0, sizeof(dst));
+ CBMResolvedCall dst = {0};
dst.caller_qn = cbm_arena_strdup(dst_arena, src->caller_qn);
dst.callee_qn = cbm_arena_strdup(dst_arena, src->callee_qn);
dst.strategy = src->strategy ? cbm_arena_strdup(dst_arena, src->strategy) : NULL;
dst.confidence = src->confidence;
dst.reason = src->reason ? cbm_arena_strdup(dst_arena, src->reason) : NULL;
+ dst.kind = src->kind;
+ dst.site_start_byte = src->site_start_byte;
+ dst.site_end_byte = src->site_end_byte;
+ dst.source_origin = src->source_origin;
cbm_resolvedcall_push(dst_calls, dst_arena, dst);
+ if (k) {
+ cbm_ht_set(seen, k, (void *)(uintptr_t)dst_calls->count);
+ }
+ }
+
+ cbm_ht_free(seen);
+ cbm_arena_destroy(&keys);
+}
+
+/* Merge exact synthetic call carriers produced by a cross-LSP resolver. The
+ * source may live in the per-file result arena or in cbm_pxc_run_one's scratch
+ * arena, so every pointer-bearing field is copied explicitly. Invalid/legacy
+ * zero-span carriers are rejected: a requires-LSP carrier is safe only when it
+ * can join the semantic record for the same source occurrence. */
+static void pxc_append_synthetic_calls(CBMArena *dst_arena, CBMCallArray *dst_calls,
+ const CBMCallArray *src_calls) {
+ if (!dst_arena || !dst_calls || !src_calls || src_calls->count <= 0)
+ return;
+
+ CBMArena keys;
+ cbm_arena_init(&keys);
+ CBMHashTable *seen = cbm_ht_create((uint32_t)(dst_calls->count + src_calls->count + 1));
+
+ for (int i = 0; i < dst_calls->count; i++) {
+ const CBMCall *call = &dst_calls->items[i];
+ if (!call->callee_name || !call->enclosing_func_qn ||
+ call->site_end_byte <= call->site_start_byte) {
+ continue;
+ }
+ char *key = cbm_arena_sprintf(
+ &keys, "%s\x1f%s\x1f%u:%u\x1f%u\x1f%d:%d", call->enclosing_func_qn, call->callee_name,
+ call->site_start_byte, call->site_end_byte, (unsigned)call->source_origin,
+ call->requires_lsp_resolution ? 1 : 0, call->is_method ? 1 : 0);
+ if (key && !cbm_ht_get(seen, key))
+ cbm_ht_set(seen, key, (void *)(uintptr_t)(i + 1));
+ }
+
+ for (int i = 0; i < src_calls->count; i++) {
+ const CBMCall *src = &src_calls->items[i];
+ if (!src->requires_lsp_resolution || !src->callee_name || !src->enclosing_func_qn ||
+ src->site_end_byte <= src->site_start_byte) {
+ continue;
+ }
+ char *key = cbm_arena_sprintf(
+ &keys, "%s\x1f%s\x1f%u:%u\x1f%u\x1f%d:%d", src->enclosing_func_qn, src->callee_name,
+ src->site_start_byte, src->site_end_byte, (unsigned)src->source_origin,
+ src->requires_lsp_resolution ? 1 : 0, src->is_method ? 1 : 0);
+ if (key && cbm_ht_get(seen, key))
+ continue;
+
+ CBMCall dst = *src;
+ dst.callee_name = cbm_arena_strdup(dst_arena, src->callee_name);
+ dst.enclosing_func_qn = cbm_arena_strdup(dst_arena, src->enclosing_func_qn);
+ dst.first_string_arg =
+ src->first_string_arg ? cbm_arena_strdup(dst_arena, src->first_string_arg) : NULL;
+ dst.second_arg_name =
+ src->second_arg_name ? cbm_arena_strdup(dst_arena, src->second_arg_name) : NULL;
+ for (int ai = 0; ai < CBM_MAX_CALL_ARGS; ai++) {
+ dst.args[ai].expr =
+ src->args[ai].expr ? cbm_arena_strdup(dst_arena, src->args[ai].expr) : NULL;
+ dst.args[ai].value =
+ src->args[ai].value ? cbm_arena_strdup(dst_arena, src->args[ai].value) : NULL;
+ dst.args[ai].keyword =
+ src->args[ai].keyword ? cbm_arena_strdup(dst_arena, src->args[ai].keyword) : NULL;
+ }
+ cbm_calls_push(dst_calls, dst_arena, dst);
+ if (key)
+ cbm_ht_set(seen, key, (void *)(uintptr_t)dst_calls->count);
}
cbm_ht_free(seen);
@@ -498,12 +842,8 @@ const struct CBMCargoManifest *cbm_pxc_get_rust_manifest(void) {
/* Convert a CBMLSPDef array (the pipeline's lingua franca, go_lsp.h:73)
* into a CBMRustLSPDef array (rust_lsp.h) inside `arena`. The two structs
- * share their first 9 string fields; CBMRustLSPDef adds `trait_qn` before
- * `is_interface` whereas CBMLSPDef has `is_interface` followed by `lang`,
- * so a memcpy is unsafe — copy field-by-field. trait_qn is left NULL
- * because the pipeline's collect-all-defs step does not carry the
- * impl-Trait-for-Type linkage; the resolver still recovers trait dispatch
- * from the in-file walk (the cross-file path only needs receiver_type). */
+ * have similar fields but different layouts; CBMLSPDef adds
+ * language/namespace metadata, so a memcpy is unsafe — copy field-by-field. */
static CBMRustLSPDef *pxc_lspdefs_to_rust(CBMArena *arena, const CBMLSPDef *defs, int def_count) {
if (!defs || def_count <= 0)
return NULL;
@@ -521,8 +861,12 @@ static CBMRustLSPDef *pxc_lspdefs_to_rust(CBMArena *arena, const CBMLSPDef *defs
out[i].embedded_types = defs[i].embedded_types;
out[i].field_defs = defs[i].field_defs;
out[i].method_names_str = defs[i].method_names_str;
- out[i].trait_qn = NULL;
+ out[i].signature_param_types = defs[i].signature_param_types;
+ out[i].signature_param_count = defs[i].signature_param_count;
+ out[i].trait_qn = defs[i].trait_qn;
out[i].is_interface = defs[i].is_interface;
+ out[i].is_rust_impl_relation = defs[i].is_rust_impl_relation;
+ out[i].is_abstract = defs[i].is_abstract;
}
return out;
}
@@ -543,6 +887,8 @@ void cbm_pxc_run_one(CBMLanguage lang, CBMFileResult *r, const char *source, int
cbm_arena_init(&scratch);
CBMResolvedCallArray out;
memset(&out, 0, sizeof(out));
+ CBMCallArray synthetic_calls;
+ memset(&synthetic_calls, 0, sizeof(synthetic_calls));
switch (lang) {
case CBM_LANG_GO:
@@ -563,7 +909,7 @@ void cbm_pxc_run_one(CBMLanguage lang, CBMFileResult *r, const char *source, int
}
case CBM_LANG_PYTHON:
cbm_run_py_lsp_cross(&scratch, source, source_len, module_qn, defs, def_count, imp_names,
- imp_qns, imp_count, tree, &out);
+ imp_qns, imp_count, tree, &out, &synthetic_calls);
break;
case CBM_LANG_PHP:
cbm_run_php_lsp_cross(&scratch, source, source_len, module_qn, defs, def_count, imp_names,
@@ -586,7 +932,7 @@ void cbm_pxc_run_one(CBMLanguage lang, CBMFileResult *r, const char *source, int
CBMRustLSPDef *rdefs = pxc_lspdefs_to_rust(&scratch, defs, def_count);
cbm_run_rust_lsp_cross_with_manifest(&scratch, source, source_len, module_qn, rdefs,
def_count, imp_names, imp_qns, imp_count, tree,
- g_pxc_rust_manifest, &out);
+ g_pxc_rust_manifest, &out, &synthetic_calls);
break;
}
default:
@@ -594,6 +940,7 @@ void cbm_pxc_run_one(CBMLanguage lang, CBMFileResult *r, const char *source, int
}
pxc_append_results(&r->arena, &r->resolved_calls, &out);
+ pxc_append_synthetic_calls(&r->arena, &r->calls, &synthetic_calls);
cbm_arena_destroy(&scratch);
}
@@ -655,12 +1002,20 @@ void cbm_pxc_dispatch_file(CBMLanguage lang, CBMFileResult *result, const char *
cbm_go_fast_resolve_qualified_calls(result, prebuilt, imp_keys, imp_vals, imp_count);
used_prebuilt = true;
break;
- case CBM_LANG_PYTHON:
- cbm_run_py_lsp_cross_with_registry(&result->arena, source, source_len, def_module,
- prebuilt, imp_keys, imp_vals, imp_count,
- result->cached_tree, &result->resolved_calls);
+ case CBM_LANG_PYTHON: {
+ CBMArena scratch;
+ cbm_arena_init(&scratch);
+ CBMResolvedCallArray out = {0};
+ CBMCallArray synthetic_calls = {0};
+ cbm_run_py_lsp_cross_with_registry(&scratch, source, source_len, def_module, prebuilt,
+ imp_keys, imp_vals, imp_count, result->cached_tree,
+ &out, &synthetic_calls);
+ pxc_append_results(&result->arena, &result->resolved_calls, &out);
+ pxc_append_synthetic_calls(&result->arena, &result->calls, &synthetic_calls);
+ cbm_arena_destroy(&scratch);
used_prebuilt = true;
break;
+ }
case CBM_LANG_C:
case CBM_LANG_CPP:
case CBM_LANG_CUDA:
@@ -690,10 +1045,11 @@ void cbm_pxc_dispatch_file(CBMLanguage lang, CBMFileResult *result, const char *
CBMLSPDef *ts_filtered = NULL;
if (module_def_index) {
int fc = 0;
- ts_filtered = cbm_pxc_filter_defs_for_file(module_def_index, all_defs, lang,
- result->namespace_name, def_module,
- imp_vals, imp_count, &fc);
- if (ts_filtered) {
+ bool filter_succeeded = false;
+ ts_filtered = cbm_pxc_filter_defs_for_file(
+ module_def_index, all_defs, lang, result->namespace_name, def_module, imp_vals,
+ imp_count, &fc, &filter_succeeded);
+ if (filter_succeeded) {
ts_defs = ts_filtered;
ts_def_count = fc;
}
@@ -728,10 +1084,11 @@ void cbm_pxc_dispatch_file(CBMLanguage lang, CBMFileResult *result, const char *
int file_def_count = all_def_count;
if (module_def_index && lang != CBM_LANG_RUST) {
int filtered_count = 0;
- filtered =
- cbm_pxc_filter_defs_for_file(module_def_index, all_defs, lang, result->namespace_name,
- def_module, imp_vals, imp_count, &filtered_count);
- if (filtered) {
+ bool filter_succeeded = false;
+ filtered = cbm_pxc_filter_defs_for_file(module_def_index, all_defs, lang,
+ result->namespace_name, def_module, imp_vals,
+ imp_count, &filtered_count, &filter_succeeded);
+ if (filter_succeeded) {
file_defs = filtered;
file_def_count = filtered_count;
}
@@ -739,11 +1096,16 @@ void cbm_pxc_dispatch_file(CBMLanguage lang, CBMFileResult *result, const char *
if (lang == CBM_LANG_RUST) {
CBMTypeRegistry *shared = rust_shared_get ? rust_shared_get(rust_shared_ctx) : NULL;
if (shared) {
- cbm_run_rust_lsp_cross_with_registry(&result->arena, source, source_len, def_module,
- shared, imp_keys, imp_vals, imp_count,
- result->cached_tree, cbm_pxc_get_rust_manifest(),
- &result->resolved_calls,
- /*result=*/NULL);
+ CBMArena scratch;
+ cbm_arena_init(&scratch);
+ CBMResolvedCallArray out = {0};
+ CBMCallArray synthetic_calls = {0};
+ cbm_run_rust_lsp_cross_with_registry(
+ &scratch, source, source_len, def_module, shared, imp_keys, imp_vals, imp_count,
+ result->cached_tree, cbm_pxc_get_rust_manifest(), &out, &synthetic_calls);
+ pxc_append_results(&result->arena, &result->resolved_calls, &out);
+ pxc_append_synthetic_calls(&result->arena, &result->calls, &synthetic_calls);
+ cbm_arena_destroy(&scratch);
} else {
cbm_pxc_run_one(lang, result, source, source_len, def_module, file_defs, file_def_count,
imp_keys, imp_vals, imp_count);
@@ -877,8 +1239,8 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
const char **imp_keys = NULL;
const char **imp_vals = NULL;
int imp_count = 0;
- pxc_build_import_map(ctx->gbuf, ctx->project_name, files[i].rel_path, &imp_keys, &imp_vals,
- &imp_count);
+ cbm_pxc_build_import_map(ctx->gbuf, ctx->project_name, files[i].rel_path, lang, cache[i],
+ &imp_keys, &imp_vals, &imp_count);
/* Journal around the resolve: a hang here must be attributed to THIS
* file, not to a stale extraction marker (the innocent-quarantine
@@ -891,7 +1253,7 @@ int cbm_pipeline_pass_lsp_cross(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *
per_lang_calls++;
processed++;
- pxc_free_import_map(imp_keys, imp_vals, imp_count);
+ cbm_pxc_free_import_map(imp_keys, imp_vals, imp_count);
free(source);
}
@@ -1003,6 +1365,15 @@ static bool pxc_is_jvm_lang(CBMLanguage lang) {
return lang == CBM_LANG_JAVA || lang == CBM_LANG_KOTLIN;
}
+/* Java and Kotlin files without a package declaration still share one JVM
+ * default package. The hash table intentionally rejects empty keys, so use an
+ * internal-only sentinel to make that package selectable across files. */
+static const char *pxc_namespace_index_key(const char *namespace_name) {
+ return namespace_name && namespace_name[0] ? namespace_name
+ : "\x1f"
+ "cbm-jvm-default-package";
+}
+
static bool pxc_def_lang_matches(CBMLanguage caller_lang, CBMLanguage def_lang) {
if (pxc_is_jvm_lang(caller_lang)) {
return pxc_is_jvm_lang(def_lang);
@@ -1023,6 +1394,65 @@ static void pxc_mark_module_defs(const CBMModuleDefIndex *idx, bool *selected,
}
}
+/* Import maps bind source locals to semantic targets. A from-import therefore
+ * carries a symbol QN (`project.module.Class` / `project.module.function`),
+ * while the def index is keyed by the declaring file module
+ * (`project.module`). Select the nearest materialized module prefix; the
+ * language registry still has to prove the full target QN before an edge is
+ * emitted, so this broadens the candidate set without weakening precision. */
+static void pxc_mark_import_defs(const CBMModuleDefIndex *idx, bool *selected,
+ const CBMLSPDef *all_defs, CBMLanguage caller_lang,
+ const char *import_qn, int *total) {
+ if (!idx || !idx->ht || !import_qn || !import_qn[0]) {
+ return;
+ }
+ char *candidate = strdup(import_qn);
+ if (!candidate) {
+ return;
+ }
+ bool matched = false;
+ for (;;) {
+ pxc_module_entry_t *entry = (pxc_module_entry_t *)cbm_ht_get(idx->ht, candidate);
+ if (entry) {
+ int added = pxc_mark_entry_defs(selected, entry, all_defs, caller_lang);
+ if (total) {
+ *total += added;
+ }
+ matched = true;
+ break;
+ }
+ char *dot = strrchr(candidate, '.');
+ if (!dot) {
+ break;
+ }
+ *dot = '\0';
+ }
+ /* Kotlin/Java source imports are package-qualified while file modules are
+ * path-qualified. If no module prefix matched, walk the declared-package
+ * index from the full import toward its package. This only selects a small
+ * candidate registry; the language resolver must still prove the symbol. */
+ if (!matched && pxc_is_jvm_lang(caller_lang) && idx->namespace_ht) {
+ strcpy(candidate, import_qn);
+ for (;;) {
+ pxc_module_entry_t *entry = (pxc_module_entry_t *)cbm_ht_get(
+ idx->namespace_ht, pxc_namespace_index_key(candidate));
+ if (entry) {
+ int added = pxc_mark_entry_defs(selected, entry, all_defs, caller_lang);
+ if (total) {
+ *total += added;
+ }
+ break;
+ }
+ char *dot = strrchr(candidate, '.');
+ if (!dot) {
+ break;
+ }
+ *dot = '\0';
+ }
+ }
+ free(candidate);
+}
+
CBMModuleDefIndex *cbm_pxc_build_module_def_index(CBMLSPDef *all_defs, int def_count) {
if (!all_defs || def_count <= 0) {
return NULL;
@@ -1043,7 +1473,9 @@ CBMModuleDefIndex *cbm_pxc_build_module_def_index(CBMLSPDef *all_defs, int def_c
pxc_module_entry_add_index(pxc_module_entry_get_or_create(ht, all_defs[i].def_module_qn),
i);
pxc_module_entry_add_index(
- pxc_module_entry_get_or_create(namespace_ht, all_defs[i].namespace_name), i);
+ pxc_module_entry_get_or_create(namespace_ht,
+ pxc_namespace_index_key(all_defs[i].namespace_name)),
+ i);
}
CBMModuleDefIndex *idx = (CBMModuleDefIndex *)calloc(1, sizeof(*idx));
@@ -1078,11 +1510,14 @@ void cbm_pxc_free_module_def_index(CBMModuleDefIndex *idx) {
CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef *all_defs,
CBMLanguage caller_lang, const char *caller_namespace,
const char *own_module, const char *const *imp_qns,
- int imp_count, int *out_count) {
+ int imp_count, int *out_count, bool *out_success) {
if (out_count) {
*out_count = 0;
}
- if (!idx || !idx->ht || !all_defs || !out_count || idx->def_count <= 0) {
+ if (out_success) {
+ *out_success = false;
+ }
+ if (!idx || !idx->ht || !all_defs || !out_count || !out_success || idx->def_count <= 0) {
return NULL;
}
@@ -1094,17 +1529,17 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
int total = 0;
pxc_mark_module_defs(idx, selected, all_defs, caller_lang, own_module, &total);
for (int i = 0; i < imp_count; i++) {
- pxc_mark_module_defs(idx, selected, all_defs, caller_lang, imp_qns[i], &total);
+ pxc_mark_import_defs(idx, selected, all_defs, caller_lang, imp_qns[i], &total);
}
- if (pxc_is_jvm_lang(caller_lang) && caller_namespace && caller_namespace[0] &&
- idx->namespace_ht) {
- pxc_module_entry_t *e =
- (pxc_module_entry_t *)cbm_ht_get(idx->namespace_ht, caller_namespace);
+ if (pxc_is_jvm_lang(caller_lang) && idx->namespace_ht) {
+ const char *namespace_key = pxc_namespace_index_key(caller_namespace);
+ pxc_module_entry_t *e = (pxc_module_entry_t *)cbm_ht_get(idx->namespace_ht, namespace_key);
total += pxc_mark_entry_defs(selected, e, all_defs, caller_lang);
}
if (total == 0) {
free(selected);
+ *out_success = true;
return NULL;
}
@@ -1121,6 +1556,7 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
}
}
*out_count = n;
+ *out_success = true;
free(selected);
return out;
}
diff --git a/src/pipeline/pass_lsp_cross.h b/src/pipeline/pass_lsp_cross.h
index b63a1ce11..c81eab1a9 100644
--- a/src/pipeline/pass_lsp_cross.h
+++ b/src/pipeline/pass_lsp_cross.h
@@ -58,6 +58,17 @@ CBMLSPDef *cbm_pxc_collect_all_defs(CBMFileResult **cache, const cbm_file_info_t
void cbm_pxc_ts_modes(CBMLanguage lang, const char *rel_path, bool *out_js, bool *out_jsx,
bool *out_dts);
+/* Build the local-name -> semantic import-QN map consumed by cross-file LSPs.
+ * Both sequential and parallel drivers use this exact helper so import
+ * metadata cannot diverge between pipelines. Values are owned by the returned
+ * map (not borrowed from gbuf); release both arrays with
+ * cbm_pxc_free_import_map(). */
+int cbm_pxc_build_import_map(const cbm_gbuf_t *gbuf, const char *project_name, const char *rel_path,
+ CBMLanguage lang, const CBMFileResult *result, const char ***out_keys,
+ const char ***out_vals, int *out_count);
+
+void cbm_pxc_free_import_map(const char **keys, const char **vals, int count);
+
/* ── Per-module def index (the gopls "package summary" pattern) ──
*
* The hot path used to register ALL all_defs[] into a fresh registry
@@ -87,11 +98,13 @@ void cbm_pxc_free_module_def_index(CBMModuleDefIndex *idx);
* `src/main/kotlin` roots without import statements. String fields inside
* each entry are borrowed from the original all_defs[] arena (caller keeps
* it alive). Caller frees the returned array with free(). Writes the entry
- * count to *out_count. Returns NULL if no matches (with *out_count = 0). */
+ * count to *out_count and sets *out_success on every valid selection. A valid
+ * empty selection returns NULL with *out_count = 0 and *out_success = true;
+ * NULL with *out_success = false means invalid input or allocation failure. */
CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef *all_defs,
CBMLanguage caller_lang, const char *caller_namespace,
const char *own_module, const char *const *imp_qns,
- int imp_count, int *out_count);
+ int imp_count, int *out_count, bool *out_success);
/* ── Tier 2 full: pre-built per-language cross-LSP registries ─────
*
diff --git a/src/pipeline/pass_parallel.c b/src/pipeline/pass_parallel.c
index 68b66545c..61c05d3a2 100644
--- a/src/pipeline/pass_parallel.c
+++ b/src/pipeline/pass_parallel.c
@@ -89,7 +89,6 @@ enum { PP_CSHARP_M_PREFIX_LEN = 2 };
#include "cbm.h"
#include "arena.h"
#include "macro_table.h"
-#include "iris_export_xml.h"
#include "simhash/minhash.h"
#include "semantic/ast_profile.h"
@@ -106,6 +105,7 @@ enum { PP_CSHARP_M_PREFIX_LEN = 2 };
* not re-pay the full nap tax on every file pull when napping cannot reclaim
* 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;
long cbm_pp_bp_nap_cycles(void) {
return atomic_load_explicit(&g_bp_nap_cycles, memory_order_relaxed);
@@ -115,6 +115,14 @@ void cbm_pp_bp_nap_cycles_reset(void) {
atomic_store_explicit(&g_bp_nap_cycles, 0, memory_order_relaxed);
}
+uint64_t cbm_pp_lsp_linear_fallback_rows(void) {
+ return atomic_load_explicit(&g_lsp_linear_fallback_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);
+}
+
/* Parse a positive MB-valued retention env knob (CBM_RETAIN_*_MB) into bytes.
* Follows the limits.c strtol convention: unset / unparseable / non-positive
* → return 0 so the caller keeps its derived default. */
@@ -528,68 +536,6 @@ static void build_def_props(char *buf, size_t bufsize, const CBMDefinition *def)
}
}
-/* Build import map from graph buffer IMPORTS edges (read-only access to gbuf). */
-static int build_import_map(const cbm_gbuf_t *gbuf, const char *project_name, const char *rel_path,
- const char ***out_keys, const char ***out_vals, int *out_count) {
- *out_keys = NULL;
- *out_vals = NULL;
- *out_count = 0;
-
- char *file_qn = cbm_pipeline_fqn_compute(project_name, rel_path, "__file__");
- const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(gbuf, file_qn);
- free(file_qn);
- if (!file_node) {
- return 0;
- }
-
- const cbm_gbuf_edge_t **edges = NULL;
- int edge_count = 0;
- int rc =
- cbm_gbuf_find_edges_by_source_type(gbuf, file_node->id, "IMPORTS", &edges, &edge_count);
- if (rc != 0 || edge_count == 0) {
- return 0;
- }
-
- const char **keys = calloc(edge_count, sizeof(const char *));
- const char **vals = calloc(edge_count, sizeof(const char *));
- int count = 0;
-
- for (int i = 0; i < edge_count; i++) {
- const cbm_gbuf_edge_t *e = edges[i];
- const cbm_gbuf_node_t *target = cbm_gbuf_find_by_id(gbuf, e->target_id);
- if (!target || !e->properties_json) {
- continue;
- }
- const char *start = strstr(e->properties_json, "\"local_name\":\"");
- if (start) {
- start += strlen("\"local_name\":\"");
- const char *end = strchr(start, '"');
- if (end && end > start) {
- keys[count] = cbm_strndup(start, end - start);
- vals[count] = target->qualified_name;
- count++;
- }
- }
- }
-
- *out_keys = keys;
- *out_vals = vals;
- *out_count = count;
- return 0;
-}
-
-static void free_import_map(const char **keys, const char **vals, int count) {
- if (keys) {
- for (int i = 0; i < count; i++) {
- free((void *)keys[i]);
- }
- free((void *)keys);
- }
- if (vals) {
- free((void *)vals);
- }
-}
-
/* True for languages whose module QN derives from the CONTAINING DIRECTORY
* (Java/Go package). MUST match cbm_lang_module_is_dir() (internal/cbm/helpers.c)
* and pxc_module_is_dir() (pass_lsp_cross.c) so same-module callee resolution
@@ -634,11 +580,14 @@ static void extract_decorator_func(const char *dec, char *out, size_t outsz) {
return;
}
const char *start = dec;
- if (*start == '@') {
+ while (*start == '@' || *start == '#' || *start == '[' || *start == ' ') {
start++;
}
- const char *paren = strchr(start, '(');
- size_t len = paren ? (size_t)(paren - start) : strlen(start);
+ size_t len = 0;
+ while (start[len] && start[len] != '(' && start[len] != '[' && start[len] != ']' &&
+ start[len] != ' ' && start[len] != ',') {
+ len++;
+ }
if (len == 0 || len >= outsz) {
return;
}
@@ -886,38 +835,17 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
uint64_t file_t0 = extract_now_ns();
- /* ObjectScript Studio Export XML: transcode each <Class> to UDL and
- * extract directly into the local gbuf (the per-file cache holds a single
- * result, so multi-class Export files are processed inline here). */
- if (fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT) {
- CBMArena ea;
- cbm_arena_init(&ea);
- int cc = 0;
- char **udls = cbm_iris_export_to_udl(&ea, source, source_len, &cc);
- for (int ci = 0; ci < cc; ci++) {
- CBMFileResult *xr =
- cbm_extract_file_ex(udls[ci], (int)strlen(udls[ci]), CBM_LANG_OBJECTSCRIPT_UDL,
- ec->project_name, fi->rel_path, CBM_EXTRACT_BUDGET, NULL,
- NULL, ec->macro_table, ec->return_type_table);
- if (!xr) {
- continue;
- }
- for (int d = 0; d < xr->defs.count; d++) {
- CBMDefinition *def = &xr->defs.items[d];
- if (def->qualified_name && def->name) {
- insert_def_into_gbuf(ws, fi, def);
- }
- }
- cbm_free_result(xr);
- }
- cbm_arena_destroy(&ea);
- free_source(source);
- continue;
- }
-
- CBMFileResult *result = cbm_extract_file_ex(
- source, source_len, fi->language, ec->project_name, fi->rel_path, CBM_EXTRACT_BUDGET,
- NULL, NULL, ec->macro_table, ec->return_type_table);
+ /* Export XML uses the same cache slot as every physical file, so its
+ * generated classes are composed before entering the common registry
+ * and resolution lifecycle. */
+ CBMFileResult *result =
+ fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT
+ ? cbm_pipeline_extract_objectscript_export(source, source_len, ec->project_name,
+ fi->rel_path, ec->macro_table,
+ ec->return_type_table)
+ : cbm_extract_file_ex(source, source_len, fi->language, ec->project_name,
+ fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, ec->macro_table,
+ ec->return_type_table);
uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS;
@@ -1395,6 +1323,7 @@ int cbm_build_registry_from_cache(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
imports_edges += create_imports_edges(ctx, result, rel, namespace_map);
create_channel_edges(ctx, result, rel);
+ cbm_pipeline_create_env_configures_for_file(ctx, result, rel);
}
cbm_pipeline_namespace_map_free(namespace_map);
@@ -2182,46 +2111,205 @@ static void lsp_idx_free_key(const char *key, void *value, void *ud) {
free((char *)key);
}
+/* A hash key may have multiple semantic rows. Keep a permanent tombstone for
+ * distinct targets so O(1) lookup cannot turn ambiguity into a confidence
+ * contest; duplicate rows for the same target may still keep the best score. */
+static CBMResolvedCall *const LSP_IDX_AMBIGUOUS = (CBMResolvedCall *)(uintptr_t)1;
+
+static bool lsp_idx_keep_best(CBMHashTable *index, const char *key, CBMResolvedCall *candidate,
+ const cbm_gbuf_t *gbuf, const char *project_name,
+ bool allow_tail_match) {
+ if (!index || !key || !candidate) {
+ return false;
+ }
+ CBMResolvedCall *existing = (CBMResolvedCall *)cbm_ht_get(index, key);
+ if (!existing) {
+ char *owned_key = strdup(key);
+ if (owned_key) {
+ cbm_ht_set(index, owned_key, candidate);
+ if (cbm_ht_get(index, key) == candidate) {
+ return true;
+ }
+ free(owned_key);
+ }
+ return false;
+ }
+ if (existing == LSP_IDX_AMBIGUOUS) {
+ return true;
+ }
+ if (!cbm_pipeline_invocation_targets_equal(existing->callee_qn, candidate->callee_qn, gbuf,
+ project_name, allow_tail_match)) {
+ const char *stored_key = cbm_ht_get_key(index, key);
+ if (stored_key) {
+ cbm_ht_set(index, stored_key, LSP_IDX_AMBIGUOUS);
+ }
+ return cbm_ht_get(index, key) != NULL;
+ }
+ if (candidate->confidence > existing->confidence) {
+ const char *stored_key = cbm_ht_get_key(index, key);
+ if (stored_key) {
+ cbm_ht_set(index, stored_key, candidate);
+ }
+ }
+ return cbm_ht_get(index, key) != NULL;
+}
+
+/* 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. */
+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) {
+ if (!caller_qn || !leaf) {
+ return NULL;
+ }
+ size_t caller_len = strlen(caller_qn);
+ size_t leaf_len = strlen(leaf);
+ size_t suffix_len = exact_site ? 48U : 16U;
+ 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);
+ 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);
+ if (written <= 0 || (size_t)written >= cap) {
+ free(key);
+ return NULL;
+ }
+ return key;
+}
+
+static bool lsp_idx_insert_leaf(CBMHashTable *index, CBMResolvedCall *candidate, const char *leaf,
+ bool exact_site, const cbm_gbuf_t *gbuf, const char *project_name,
+ bool allow_tail_match) {
+ if (!index || !candidate || !candidate->caller_qn || !leaf || !leaf[0]) {
+ return false;
+ }
+ char *key = lsp_idx_key(candidate->caller_qn, leaf, exact_site, candidate->site_start_byte,
+ candidate->site_end_byte, candidate->source_origin);
+ if (!key) {
+ return false;
+ }
+ bool inserted = lsp_idx_keep_best(index, key, candidate, gbuf, project_name, allow_tail_match);
+ free(key);
+ return inserted;
+}
+
+static const CBMResolvedCall *lsp_idx_lookup(const CBMHashTable *index, const CBMCall *call,
+ bool exact_site, bool *key_built, bool *ambiguous) {
+ if (key_built) {
+ *key_built = false;
+ }
+ if (ambiguous) {
+ *ambiguous = false;
+ }
+ if (!index || !call || !call->enclosing_func_qn || !call->callee_name) {
+ return NULL;
+ }
+ const char *leaf = cbm_pipeline_call_callee_leaf(call->callee_name);
+ if (!leaf || !leaf[0]) {
+ return NULL;
+ }
+ char *key = lsp_idx_key(call->enclosing_func_qn, leaf, exact_site, call->site_start_byte,
+ call->site_end_byte, call->source_origin);
+ if (!key) {
+ return NULL;
+ }
+ if (key_built) {
+ *key_built = true;
+ }
+ const CBMResolvedCall *candidate = (const CBMResolvedCall *)cbm_ht_get(index, key);
+ free(key);
+ if (candidate == LSP_IDX_AMBIGUOUS) {
+ if (ambiguous) {
+ *ambiguous = true;
+ }
+ return NULL;
+ }
+ if (!candidate || candidate->kind != CBM_RESOLVED_INVOCATION || !candidate->caller_qn ||
+ strcmp(candidate->caller_qn, call->enclosing_func_qn) != 0 ||
+ candidate->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
+ 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;
+}
+
/* Resolve calls for one file and emit CALLS/HTTP_CALLS/ASYNC_CALLS edges. */
static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CBMFileResult *result,
const char *rel, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, CBMLanguage lang) {
- /* Build a per-file hash index of resolved_calls keyed by
- * "caller_qn|callee_short" for O(1) lookup. cbm_pipeline_find_lsp_
- * resolution would otherwise do an O(N) linear scan over
- * resolved_calls for EACH of result->calls.count calls — the
- * dominant cost in parallel_resolve on kubernetes (~50s of pure
- * scanning). On insert, keep the highest-confidence entry per key
- * (matches the original "best" tie-break). Skip the build entirely
- * when there are no calls (nothing to look up) or no resolved
- * entries (lookups would all miss). */
- CBMHashTable *lsp_idx = NULL;
+ /* 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);
if (result->calls.count > 0 && result->resolved_calls.count > 0) {
- lsp_idx = cbm_ht_create((uint32_t)result->resolved_calls.count * 2u + 16u);
- if (lsp_idx) {
+ 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->caller_qn || !rc_e->callee_qn ||
+ if (rc_e->kind != CBM_RESOLVED_INVOCATION || !rc_e->caller_qn || !rc_e->callee_qn ||
rc_e->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
continue;
}
- const char *short_name = strrchr(rc_e->callee_qn, '.');
- short_name = short_name ? short_name + 1 : rc_e->callee_qn;
- char key[1024];
- int kn = snprintf(key, sizeof(key), "%s|%s", rc_e->caller_qn, short_name);
- if (kn <= 0 || kn >= (int)sizeof(key))
+ 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;
- CBMResolvedCall *existing = (CBMResolvedCall *)cbm_ht_get(lsp_idx, key);
- if (!existing) {
- /* New entry — strdup so the key outlives the loop body. */
- char *kdup = strdup(key);
- if (kdup)
- cbm_ht_set(lsp_idx, kdup, rc_e);
- } else if (rc_e->confidence > existing->confidence) {
- /* Update value; reuse stored key pointer to avoid leak. */
- const char *skey = cbm_ht_get_key(lsp_idx, key);
- if (skey)
- cbm_ht_set(lsp_idx, skey, rc_e);
+ }
+ 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;
}
}
}
@@ -2247,25 +2335,37 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
* 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). */
- bool allow_tail = cbm_pipeline_lsp_allow_tail_match(lang);
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 (lsp_idx && call->enclosing_func_qn) {
- const char *call_leaf = cbm_pipeline_call_callee_leaf(call->callee_name);
- char key[1024];
- int kn = call_leaf
- ? snprintf(key, sizeof(key), "%s|%s", call->enclosing_func_qn, call_leaf)
- : -1;
- if (kn > 0 && kn < (int)sizeof(key)) {
- lsp = (const CBMResolvedCall *)cbm_ht_get(lsp_idx, key);
- }
- }
- if (!lsp) {
+ 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. */
- lsp = cbm_pipeline_find_lsp_resolution(&result->resolved_calls, call, allow_tail);
+ 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);
}
atomic_fetch_add_explicit(&rc->time_ns_rc_lsp_lookup, extract_now_ns() - _rc_t0,
memory_order_relaxed);
@@ -2275,8 +2375,13 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
/* Canonicalise to the gbuf node's QN so res.qualified_name matches
* the gbuf even when the cross-file fallback had to prefix the
* project name. */
- lsp_target = cbm_pipeline_lsp_target_node(rc->main_gbuf, rc->project_name,
- lsp->callee_qn, allow_tail);
+ bool exact_external_target = call->requires_lsp_resolution &&
+ cbm_pipeline_kotlin_external_target(lang, lsp->callee_qn);
+ lsp_target = exact_external_target
+ ? cbm_pipeline_lsp_target_node_strict(rc->main_gbuf, rc->project_name,
+ lsp->callee_qn, allow_tail)
+ : cbm_pipeline_lsp_target_node(rc->main_gbuf, rc->project_name,
+ lsp->callee_qn, allow_tail);
if (lsp_target) {
res.qualified_name = lsp_target->qualified_name;
res.strategy = lsp->strategy ? lsp->strategy : "lsp_override";
@@ -2295,14 +2400,24 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
* losing every alias-imported JSX component edge on the parallel path
* (~21% of a Next.js call graph) while the sequential pass, which falls
* THROUGH to the registry here, kept them. This restores seq/parallel
- * parity via the import_map / unique_name resolution. */
- if (!res.qualified_name || !res.qualified_name[0]) {
+ * parity via the import_map / unique_name resolution. Synthetic
+ * semantic candidates are deliberately excluded: they require an
+ * exact LSP target and must fail closed rather than accepting a textual
+ * registry match. */
+ if ((!res.qualified_name || !res.qualified_name[0]) && !call->requires_lsp_resolution) {
res = cbm_registry_resolve(rc->registry, call->callee_name, module_qn, imp_keys,
imp_vals, imp_count);
}
atomic_fetch_add_explicit(&rc->time_ns_rc_resolve, extract_now_ns() - _rc_t0,
memory_order_relaxed);
+ /* A synthetic semantic candidate is an invocation only when the LSP
+ * resolved it to a concrete graph node. Never let registry, field-name,
+ * route, or service heuristics manufacture a target for it. */
+ if (call->requires_lsp_resolution && !lsp_target) {
+ continue;
+ }
+
_rc_t0 = extract_now_ns();
try_field_type_hint(rc, &res, call->callee_name, source_node->id);
atomic_fetch_add_explicit(&rc->time_ns_rc_hint, extract_now_ns() - _rc_t0,
@@ -2428,16 +2543,24 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
memory_order_relaxed);
ws->calls_resolved++;
}
- if (lsp_idx) {
- cbm_ht_foreach(lsp_idx, lsp_idx_free_key, NULL);
- cbm_ht_free(lsp_idx);
+ 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);
}
}
/* Resolve usages for one file. */
static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
CBMFileResult *result, const char *rel, const char *module_qn,
- const char **imp_keys, const char **imp_vals, int imp_count) {
+ const char **imp_keys, const char **imp_vals, int imp_count,
+ CBMLanguage lang) {
+ cbm_pipeline_lsp_reference_index_t reference_index = {0};
+ bool reference_index_ready =
+ cbm_pipeline_lsp_reference_index_build(&result->resolved_calls, &reference_index);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
@@ -2448,12 +2571,45 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
if (!src) {
continue;
}
- cbm_resolution_t res = cbm_registry_resolve(rc->registry, usage->ref_name, module_qn,
- imp_keys, imp_vals, imp_count);
- if (!res.qualified_name || res.qualified_name[0] == '\0') {
- continue;
+ const cbm_gbuf_node_t *tgt = NULL;
+ bool precise_call_reference = false;
+ const CBMResolvedCall *semantic_reference = NULL;
+ if (cbm_pipeline_usage_semantic_reference_candidate(usage)) {
+ bool allow_tail = cbm_pipeline_lsp_allow_tail_match(lang);
+ semantic_reference = cbm_pipeline_find_lsp_reference_indexed_in_graph(
+ &result->resolved_calls, reference_index_ready ? &reference_index : NULL, usage,
+ allow_tail, rc->main_gbuf, rc->project_name);
+ if (semantic_reference &&
+ !cbm_pipeline_usage_allows_semantic_reference(usage, semantic_reference)) {
+ semantic_reference = NULL;
+ }
+ if (semantic_reference) {
+ tgt = cbm_pipeline_lsp_target_node(rc->main_gbuf, rc->project_name,
+ semantic_reference->callee_qn, allow_tail);
+ precise_call_reference = cbm_pipeline_node_is_callable_target(tgt);
+ }
+ }
+ if (!tgt) {
+ /* Exact semantic ownership beats textual name fallback even when
+ * the semantic target is not materialized in this graph. */
+ if (semantic_reference) {
+ continue;
+ }
+ cbm_resolution_t res = cbm_registry_resolve(rc->registry, usage->ref_name, module_qn,
+ imp_keys, imp_vals, imp_count);
+ if (!res.qualified_name || res.qualified_name[0] == '\0') {
+ continue;
+ }
+ if (!cbm_pipeline_reference_candidate_fallback_allowed(lang, usage, res.strategy,
+ imp_keys, imp_count)) {
+ continue;
+ }
+ tgt = cbm_gbuf_find_by_qn(rc->main_gbuf, res.qualified_name);
+ if (usage->semantic_reference_blocked && (usage->semantic_reference_local_shadow ||
+ cbm_pipeline_node_is_callable_target(tgt))) {
+ continue;
+ }
}
- const cbm_gbuf_node_t *tgt = cbm_gbuf_find_by_qn(rc->main_gbuf, res.qualified_name);
if (!tgt || src->id == tgt->id) {
continue;
}
@@ -2461,9 +2617,11 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
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);
- cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, "USAGE", uprops);
+ 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);
ws->usages_resolved++;
}
+ cbm_pipeline_lsp_reference_index_free(&reference_index);
}
/* Resolve throws/raises for one file. */
@@ -2572,6 +2730,14 @@ static void resolve_def_decorators(resolve_ctx_t *rc, resolve_worker_state_t *ws
if (res.qualified_name && res.qualified_name[0] != '\0') {
dn = cbm_gbuf_find_by_qn(rc->main_gbuf, res.qualified_name);
}
+ /* Qualified Rust proc-macro paths must not degrade to the decorated
+ * function itself through the registry's same-module suffix fallback
+ * (`#[tokio::main]` on local `main`). Preserve the full external path
+ * through the synthetic Decorator node instead. */
+ if (dn && dn->id == node->id && def->decorators[dc][0] == '#' &&
+ def->decorators[dc][1] == '[' && strstr(fn, "::")) {
+ dn = NULL;
+ }
int64_t dn_id = 0;
if (dn) {
dn_id = dn->id;
@@ -2678,6 +2844,55 @@ static CBMTypeRegistry *pp_rust_shared_registry_get(void *ctx) {
return pp_rust_shared_registry((resolve_ctx_t *)ctx);
}
+static int pp_call_reference_site_count(const CBMFileResult *result, CBMLanguage lang) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ if (cbm_pipeline_usage_semantic_reference_candidate(&result->usages.items[i])) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int pp_qualified_lsp_site_count(const CBMFileResult *result) {
+ int count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if ((resolved->kind == CBM_RESOLVED_INVOCATION ||
+ resolved->kind == CBM_RESOLVED_CALL_REFERENCE) &&
+ resolved->caller_qn && resolved->callee_qn &&
+ resolved->confidence >= CBM_LSP_CONFIDENCE_FLOOR) {
+ count++;
+ }
+ }
+ return count;
+}
+
+/* A per-file semantic walk can discover a faithful source occurrence that the
+ * syntax extractor cannot represent as a CBMCall yet: Python operators and
+ * calls hidden in Rust built-in macro token trees are the canonical examples.
+ * An exact unresolved/low-confidence record is therefore an explicit request
+ * for the project-registry pass, even when the parser-backed site count is
+ * zero or already fully qualified. Zero-span generated semantics are excluded:
+ * without source provenance they cannot safely join a graph carrier. */
+static bool pp_has_pending_lsp_site(const CBMFileResult *result) {
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION &&
+ resolved->kind != CBM_RESOLVED_CALL_REFERENCE) {
+ continue;
+ }
+ if (!resolved->caller_qn || !resolved->callee_qn ||
+ resolved->site_end_byte <= resolved->site_start_byte) {
+ continue;
+ }
+ if (resolved->reason || resolved->confidence < CBM_LSP_CONFIDENCE_FLOOR) {
+ return true;
+ }
+ }
+ return false;
+}
+
static void resolve_worker(int worker_id, void *ctx_ptr) {
resolve_ctx_t *rc = ctx_ptr;
resolve_worker_state_t *ws = &rc->workers[worker_id];
@@ -2737,19 +2952,23 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
}
/* Cross-file LSP is a per-file tree-sitter re-parse + AST walk +
- * registry lookups — ~50-150ms per file. It can ONLY find calls
- * that exist in the AST. If the per-file extract found zero calls,
- * cross-LSP will too: the AST is the same. For non-JVM languages,
- * skip when per-file LSP already produced at least as many resolved
- * entries as textual calls. Java/Kotlin per-file LSP can fill the
- * count with constructors or same-file calls while a mixed-source-root
- * Java↔Kotlin call remains unresolved, so JVM callers run whenever
- * calls exist. */
+ * registry lookups — ~50-150ms per file. It can only resolve semantic
+ * sites present in that AST: invocations plus explicit callable
+ * references. A file containing only a callable reference still needs
+ * this pass. For non-JVM languages, skip when per-file LSP already
+ * produced at least as many qualifying typed resolutions as sites.
+ * Java/Kotlin per-file LSP can fill the count with same-file sites while
+ * a mixed-source-root Java↔Kotlin site remains unresolved, so JVM
+ * callers run whenever either kind of site exists. */
bool jvm_cross_lsp = (lang == CBM_LANG_JAVA || lang == CBM_LANG_KOTLIN);
+ int call_reference_sites = pp_call_reference_site_count(result, lang);
+ int semantic_sites = result->calls.count + call_reference_sites;
+ int qualified_lsp_sites = pp_qualified_lsp_site_count(result);
+ bool pending_lsp_site = pp_has_pending_lsp_site(result);
bool cross_lsp_eligible =
(rc->all_defs && rc->def_count > 0 && cbm_pxc_has_cross_lsp(lang) &&
- result->calls.count > 0 &&
- (jvm_cross_lsp || result->resolved_calls.count < result->calls.count) &&
+ (semantic_sites > 0 || pending_lsp_site) &&
+ (jvm_cross_lsp || pending_lsp_site || qualified_lsp_sites < semantic_sites) &&
!is_generated);
/* Skip files with nothing else to resolve and no cross-LSP work. */
@@ -2766,7 +2985,8 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
const char **imp_vals = NULL;
int imp_count = 0;
uint64_t _imp_t0 = extract_now_ns();
- build_import_map(rc->main_gbuf, rc->project_name, rel, &imp_keys, &imp_vals, &imp_count);
+ cbm_pxc_build_import_map(rc->main_gbuf, rc->project_name, rel, lang, result, &imp_keys,
+ &imp_vals, &imp_count);
atomic_fetch_add_explicit(&rc->time_ns_import_map, extract_now_ns() - _imp_t0,
memory_order_relaxed);
@@ -2882,7 +3102,7 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
/* ── USAGE resolution ──────────────────────────────────── */
_ph_t0 = extract_now_ns();
- resolve_file_usages(rc, ws, result, rel, module_qn, imp_keys, imp_vals, imp_count);
+ resolve_file_usages(rc, ws, result, rel, module_qn, imp_keys, imp_vals, imp_count, lang);
atomic_fetch_add_explicit(&rc->time_ns_usages, extract_now_ns() - _ph_t0,
memory_order_relaxed);
@@ -2908,7 +3128,7 @@ static void resolve_worker(int worker_id, void *ctx_ptr) {
cbm_registry_resolve_cache_end();
free(module_qn);
- free_import_map(imp_keys, imp_vals, imp_count);
+ cbm_pxc_free_import_map(imp_keys, imp_vals, imp_count);
atomic_fetch_add_explicit(&rc->time_ns_total_loop, extract_now_ns() - _loop_t0,
memory_order_relaxed);
diff --git a/src/pipeline/pass_semantic.c b/src/pipeline/pass_semantic.c
index 8a3bb01f0..fd321af5e 100644
--- a/src/pipeline/pass_semantic.c
+++ b/src/pipeline/pass_semantic.c
@@ -400,6 +400,15 @@ static void resolve_decorator(cbm_pipeline_ctx_t *ctx, const cbm_gbuf_node_t *no
if (res.qualified_name && res.qualified_name[0] != '\0') {
dec = cbm_gbuf_find_by_qn(ctx->gbuf, res.qualified_name);
}
+ /* A qualified Rust proc-macro path can collide with the decorated
+ * function's own name: resolving `#[tokio::main]` from module `main`
+ * may fall back from `tokio::main` to same-module `main`. That is not a
+ * local decorator target (and the self-edge is discarded below), so keep
+ * the full external spelling by materialising the synthetic decorator. */
+ if (dec && dec->id == node->id && decorator[0] == '#' && decorator[1] == '[' &&
+ strstr(func_name, "::")) {
+ dec = NULL;
+ }
if (!dec) {
/* The decorator target is not a local symbol (external attribute /
* stdlib annotation / proc-macro derive). Materialise a synthetic
diff --git a/src/pipeline/pass_usages.c b/src/pipeline/pass_usages.c
index b8bb211c9..498cf849c 100644
--- a/src/pipeline/pass_usages.c
+++ b/src/pipeline/pass_usages.c
@@ -2,7 +2,8 @@
* pass_usages.c — Resolve usages, throws, and read/write edges.
*
* For each file, re-extracts and resolves:
- * - USAGE edges: identifier references (not calls) to registered symbols
+ * - USAGE edges: ordinary identifier references to registered symbols
+ * - CALL_REFERENCE edges: explicit callable-reference syntax (not invocations)
* - THROWS/RAISES edges: exception types
* - READS/WRITES edges: variable read/write access patterns
*
@@ -15,6 +16,8 @@
#include "foundation/str_util.h" // cbm_json_escape
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
+#include "pipeline/lsp_resolve.h"
+#include "pipeline/pass_lsp_cross.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
#include "foundation/compat.h"
@@ -26,6 +29,24 @@
#include <stdlib.h>
#include <string.h>
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+#include <stdatomic.h>
+
+static _Atomic uint64_t g_lsp_reference_lookup_rows_examined = 0;
+
+void cbm_pipeline_lsp_reference_lookup_test_note_row(void) {
+ atomic_fetch_add_explicit(&g_lsp_reference_lookup_rows_examined, 1, memory_order_relaxed);
+}
+
+void cbm_pipeline_lsp_reference_lookup_test_reset(void) {
+ atomic_store_explicit(&g_lsp_reference_lookup_rows_examined, 0, memory_order_relaxed);
+}
+
+uint64_t cbm_pipeline_lsp_reference_lookup_test_rows_examined(void) {
+ return atomic_load_explicit(&g_lsp_reference_lookup_rows_examined, memory_order_relaxed);
+}
+#endif
+
/* True for languages whose module QN derives from the CONTAINING DIRECTORY
* (Java/Go package). MUST match cbm_lang_module_is_dir() (internal/cbm/helpers.c)
* so same-module resolution keys against the directory-based def-node QNs. */
@@ -87,108 +108,18 @@ static bool is_checked_exception(const char *name) {
return true; /* Default: treat as checked */
}
-/* Build import map from cached extraction result (fast path). */
-static int build_import_map_from_cache(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,
- const char ***out_keys, const char ***out_vals,
- int *out_count) {
- const char **keys = calloc((size_t)result->imports.count, sizeof(const char *));
- const char **vals = calloc((size_t)result->imports.count, sizeof(const char *));
- int count = 0;
-
- for (int i = 0; i < result->imports.count; i++) {
- const CBMImport *imp = &result->imports.items[i];
- if (!imp->local_name || !imp->local_name[0] || !imp->module_path) {
- continue;
- }
- char *target_qn = cbm_pipeline_fqn_module(ctx->project_name, imp->module_path);
- const cbm_gbuf_node_t *target = cbm_gbuf_find_by_qn(ctx->gbuf, target_qn);
- free(target_qn);
- if (!target) {
- continue;
- }
- keys[count] = strdup(imp->local_name);
- vals[count] = target->qualified_name;
- count++;
- }
-
- *out_keys = keys;
- *out_vals = vals;
- *out_count = count;
- return 0;
-}
-
-/* Build import map from graph buffer IMPORTS edges (slow path). */
-static int build_import_map_from_edges(cbm_pipeline_ctx_t *ctx, const char *rel_path,
- const char ***out_keys, const char ***out_vals,
- int *out_count) {
- char *file_qn = cbm_pipeline_fqn_compute(ctx->project_name, rel_path, "__file__");
- const cbm_gbuf_node_t *file_node = cbm_gbuf_find_by_qn(ctx->gbuf, file_qn);
- free(file_qn);
- if (!file_node) {
- return 0;
- }
-
- const cbm_gbuf_edge_t **edges = NULL;
- int edge_count = 0;
- int rc = cbm_gbuf_find_edges_by_source_type(ctx->gbuf, file_node->id, "IMPORTS", &edges,
- &edge_count);
- if (rc != 0 || edge_count == 0) {
- return 0;
- }
-
- const char **keys = calloc(edge_count, sizeof(const char *));
- const char **vals = calloc(edge_count, sizeof(const char *));
- int count = 0;
-
- for (int i = 0; i < edge_count; i++) {
- const cbm_gbuf_edge_t *e = edges[i];
- const cbm_gbuf_node_t *target = cbm_gbuf_find_by_id(ctx->gbuf, e->target_id);
- if (!target || !e->properties_json) {
- continue;
- }
-
- const char *start = strstr(e->properties_json, "\"local_name\":\"");
- if (start) {
- start += strlen("\"local_name\":\"");
- const char *end = strchr(start, '"');
- if (end && end > start) {
- keys[count] = cbm_strndup(start, end - start);
- vals[count] = target->qualified_name;
- count++;
- }
- }
- }
-
- *out_keys = keys;
- *out_vals = vals;
- *out_count = count;
- return 0;
-}
-
-/* Build per-file import map from cached extraction result or graph buffer edges. */
+/* Build the same semantic import map used by cross-LSP and parallel resolution.
+ * The old sequential-only shortcut treated raw paths such as `./types` as QNs,
+ * so duplicate symbol names fell through to an ambiguous unique-name lookup. */
static int build_import_map(cbm_pipeline_ctx_t *ctx, const char *rel_path,
const CBMFileResult *result, const char ***out_keys,
- const char ***out_vals, int *out_count) {
- *out_keys = NULL;
- *out_vals = NULL;
- *out_count = 0;
-
- if (result && result->imports.count > 0) {
- return build_import_map_from_cache(ctx, result, out_keys, out_vals, out_count);
- }
- return build_import_map_from_edges(ctx, rel_path, out_keys, out_vals, out_count);
+ const char ***out_vals, int *out_count, CBMLanguage lang) {
+ return cbm_pxc_build_import_map(ctx->gbuf, ctx->project_name, rel_path, lang, result, out_keys,
+ out_vals, out_count);
}
static void free_import_map(const char **keys, const char **vals, int count) {
- if (keys) {
- for (int i = 0; i < count; i++) {
- free((void *)keys[i]);
- }
- free((void *)keys);
- }
- if (vals) {
- free((void *)vals);
- }
+ cbm_pxc_free_import_map(keys, vals, count);
}
/* Find the graph buffer node for an enclosing function QN, falling back to file node. */
@@ -215,26 +146,67 @@ 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) {
+ const char **imp_vals, int imp_count, CBMLanguage lang) {
int resolved = 0;
+ cbm_pipeline_lsp_reference_index_t reference_index = {0};
+ bool reference_index_ready =
+ cbm_pipeline_lsp_reference_index_build(&result->resolved_calls, &reference_index);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
continue;
}
-
const cbm_gbuf_node_t *src = find_enclosing_node(ctx, usage->enclosing_func_qn, rel);
if (!src) {
continue;
}
- cbm_resolution_t res = cbm_registry_resolve(ctx->registry, usage->ref_name, module_qn,
- imp_keys, imp_vals, imp_count);
- if (!res.qualified_name || res.qualified_name[0] == '\0') {
- continue;
+ const cbm_gbuf_node_t *tgt = NULL;
+ bool precise_call_reference = false;
+ const CBMResolvedCall *semantic_reference = NULL;
+ if (cbm_pipeline_usage_semantic_reference_candidate(usage)) {
+ bool allow_tail = cbm_pipeline_lsp_allow_tail_match(lang);
+ semantic_reference = cbm_pipeline_find_lsp_reference_indexed_in_graph(
+ &result->resolved_calls, reference_index_ready ? &reference_index : NULL, usage,
+ allow_tail, ctx->gbuf, ctx->project_name);
+ if (semantic_reference &&
+ !cbm_pipeline_usage_allows_semantic_reference(usage, semantic_reference)) {
+ semantic_reference = NULL;
+ }
+ if (semantic_reference) {
+ tgt = cbm_pipeline_lsp_target_node(ctx->gbuf, ctx->project_name,
+ semantic_reference->callee_qn, allow_tail);
+ precise_call_reference = cbm_pipeline_node_is_callable_target(tgt);
+ }
}
- const cbm_gbuf_node_t *tgt = cbm_gbuf_find_by_qn(ctx->gbuf, res.qualified_name);
+ /* A syntactically explicit reference remains useful when exact semantic
+ * resolution is unavailable, but the textual registry fallback proves
+ * only value use—not an occurrence-exact callable target. Emit USAGE in
+ * that case; CALL_REFERENCE is reserved for the exact LSP join. */
+ if (!tgt) {
+ /* An occurrence-exact semantic record owns this reference even when
+ * its target is not materialized in the graph (for example, a
+ * Kotlin local function). Falling back by raw name here would bind
+ * an unrelated same-named declaration. */
+ if (semantic_reference) {
+ continue;
+ }
+ cbm_resolution_t res = cbm_registry_resolve(ctx->registry, usage->ref_name, module_qn,
+ imp_keys, imp_vals, imp_count);
+ if (!res.qualified_name || res.qualified_name[0] == '\0') {
+ continue;
+ }
+ if (!cbm_pipeline_reference_candidate_fallback_allowed(lang, usage, res.strategy,
+ imp_keys, imp_count)) {
+ continue;
+ }
+ tgt = cbm_gbuf_find_by_qn(ctx->gbuf, res.qualified_name);
+ if (usage->semantic_reference_blocked && (usage->semantic_reference_local_shadow ||
+ cbm_pipeline_node_is_callable_target(tgt))) {
+ continue;
+ }
+ }
if (!tgt || src->id == tgt->id) {
continue;
}
@@ -245,9 +217,11 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
char uprops[CBM_SZ_512];
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
- cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, "USAGE", uprops);
+ const char *edge_type = precise_call_reference ? "CALL_REFERENCE" : "USAGE";
+ cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, edge_type, uprops);
resolved++;
}
+ cbm_pipeline_lsp_reference_index_free(&reference_index);
return resolved;
}
@@ -368,13 +342,13 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
const char **imp_keys = NULL;
const char **imp_vals = NULL;
int imp_count = 0;
- build_import_map(ctx, rel, result, &imp_keys, &imp_vals, &imp_count);
+ build_import_map(ctx, rel, result, &imp_keys, &imp_vals, &imp_count, files[i].language);
char *module_qn = cbm_pipeline_fqn_module_dir(ctx->project_name, rel,
pu_module_is_dir(files[i].language));
- usage_resolved +=
- resolve_usage_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count);
+ usage_resolved += resolve_usage_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,
+ imp_count, files[i].language);
throw_resolved +=
resolve_throw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count);
rw_resolved += resolve_rw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count);
diff --git a/src/pipeline/path_alias.c b/src/pipeline/path_alias.c
index 454e5466b..8fae754c1 100644
--- a/src/pipeline/path_alias.c
+++ b/src/pipeline/path_alias.c
@@ -289,24 +289,29 @@ static cbm_path_alias_map_t *load_tsconfig_file(const char *abs_path, const char
/* ── Public API ────────────────────────────────────────────────── */
+static void free_alias_map(cbm_path_alias_map_t *map) {
+ if (!map) {
+ return;
+ }
+ for (int j = 0; j < map->count; j++) {
+ free(map->entries[j].alias_prefix);
+ free(map->entries[j].alias_suffix);
+ free(map->entries[j].target_prefix);
+ free(map->entries[j].target_suffix);
+ }
+ free(map->entries);
+ free(map->base_url);
+ free(map);
+}
+
void cbm_path_alias_collection_free(cbm_path_alias_collection_t *coll) {
if (!coll) {
return;
}
for (int i = 0; i < coll->count; i++) {
free(coll->scopes[i].dir_prefix);
- if (coll->scopes[i].map) {
- cbm_path_alias_map_t *map = coll->scopes[i].map;
- for (int j = 0; j < map->count; j++) {
- free(map->entries[j].alias_prefix);
- free(map->entries[j].alias_suffix);
- free(map->entries[j].target_prefix);
- free(map->entries[j].target_suffix);
- }
- free(map->entries);
- free(map->base_url);
- free(map);
- }
+ free(coll->scopes[i].source_rel_path);
+ free_alias_map(coll->scopes[i].map);
}
free(coll->scopes);
free(coll);
@@ -472,7 +477,24 @@ cbm_path_alias_collection_t *cbm_load_path_aliases_excluded(const char *repo_pat
if (!map) {
continue;
}
- coll->scopes[coll->count].dir_prefix = strdup(hits[i].rel);
+ const char *base = strrchr(hits[i].abs, '/');
+ base = base ? base + 1 : hits[i].abs;
+ char selected_rel[CBM_SZ_512];
+ if (hits[i].rel[0]) {
+ snprintf(selected_rel, sizeof(selected_rel), "%s/%s", hits[i].rel, base);
+ } else {
+ snprintf(selected_rel, sizeof(selected_rel), "%s", base);
+ }
+ char *dir_prefix = strdup(hits[i].rel);
+ char *source_rel_path = strdup(selected_rel);
+ if (!dir_prefix || !source_rel_path) {
+ free(dir_prefix);
+ free(source_rel_path);
+ free_alias_map(map);
+ continue;
+ }
+ coll->scopes[coll->count].dir_prefix = dir_prefix;
+ coll->scopes[coll->count].source_rel_path = source_rel_path;
coll->scopes[coll->count].map = map;
coll->count++;
}
diff --git a/src/pipeline/path_alias.h b/src/pipeline/path_alias.h
index f2b0a790c..bc462e524 100644
--- a/src/pipeline/path_alias.h
+++ b/src/pipeline/path_alias.h
@@ -55,6 +55,7 @@ typedef struct {
* pick up the map of the nearest ancestor scope. */
typedef struct {
char *dir_prefix;
+ char *source_rel_path; /* selected config file (tsconfig beats jsconfig) */
cbm_path_alias_map_t *map;
} cbm_path_alias_scope_t;
diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c
index 9f363922a..95ff74017 100644
--- a/src/pipeline/pipeline.c
+++ b/src/pipeline/pipeline.c
@@ -43,6 +43,13 @@ enum { CBM_DIR_PERMS = 0755, PL_RING = 4, PL_RING_MASK = 3, PL_SEQ_PASSES = 6, P
#include <stdatomic.h>
#include <sys/stat.h>
#include <time.h>
+#ifdef _WIN32
+#include <process.h>
+#define cbm_pipeline_getpid _getpid
+#else
+#include <unistd.h>
+#define cbm_pipeline_getpid getpid
+#endif
static inline void *intptr_to_ptr(intptr_t v) {
void *p;
@@ -55,6 +62,68 @@ static inline void *intptr_to_ptr(intptr_t v) {
* Atomic spinlock: 0 = free, 1 = locked. */
static atomic_int g_pipeline_busy = 0;
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+static atomic_bool g_persist_test_fail_after_stage_dump = false;
+static atomic_bool g_persist_test_cancel_after_predump = false;
+static atomic_bool g_persist_test_cancel_after_destination_prepare = false;
+static atomic_bool g_persist_test_fail_adr_capture = false;
+static cbm_pipeline_test_hook_fn g_persist_test_before_final_manifest = NULL;
+static void *g_persist_test_before_final_manifest_userdata = NULL;
+
+void cbm_pipeline_incremental_test_fail_after_stage_dump_once(void) {
+ atomic_store(&g_persist_test_fail_after_stage_dump, true);
+}
+
+void cbm_pipeline_incremental_test_cancel_after_predump_once(void) {
+ atomic_store(&g_persist_test_cancel_after_predump, true);
+}
+
+void cbm_pipeline_incremental_test_cancel_after_destination_prepare_once(void) {
+ atomic_store(&g_persist_test_cancel_after_destination_prepare, true);
+}
+
+void cbm_pipeline_incremental_test_fail_adr_capture_once(void) {
+ atomic_store(&g_persist_test_fail_adr_capture, true);
+}
+
+void cbm_pipeline_incremental_test_before_final_manifest_once(cbm_pipeline_test_hook_fn hook,
+ void *userdata) {
+ g_persist_test_before_final_manifest = hook;
+ g_persist_test_before_final_manifest_userdata = userdata;
+}
+
+void cbm_pipeline_persist_test_run_before_final_manifest(void) {
+ cbm_pipeline_test_hook_fn hook = g_persist_test_before_final_manifest;
+ void *userdata = g_persist_test_before_final_manifest_userdata;
+ g_persist_test_before_final_manifest = NULL;
+ g_persist_test_before_final_manifest_userdata = NULL;
+ if (hook) {
+ hook(userdata);
+ }
+}
+
+bool cbm_pipeline_persist_test_take_failure_after_stage_dump(void) {
+ return atomic_exchange(&g_persist_test_fail_after_stage_dump, false);
+}
+
+bool cbm_pipeline_persist_test_take_cancel_after_predump(void) {
+ return atomic_exchange(&g_persist_test_cancel_after_predump, false);
+}
+
+bool cbm_pipeline_persist_test_take_cancel_after_destination_prepare(void) {
+ return atomic_exchange(&g_persist_test_cancel_after_destination_prepare, false);
+}
+
+void cbm_pipeline_persist_test_reset_faults(void) {
+ atomic_store(&g_persist_test_fail_after_stage_dump, false);
+ atomic_store(&g_persist_test_cancel_after_predump, false);
+ atomic_store(&g_persist_test_cancel_after_destination_prepare, false);
+ atomic_store(&g_persist_test_fail_adr_capture, false);
+ g_persist_test_before_final_manifest = NULL;
+ g_persist_test_before_final_manifest_userdata = NULL;
+}
+#endif
+
bool cbm_pipeline_try_lock(void) {
return atomic_exchange(&g_pipeline_busy, 1) == 0;
}
@@ -188,6 +257,24 @@ cbm_pipeline_t *cbm_pipeline_new(const char *repo_path, const char *db_path,
return p;
}
+static int pipeline_refresh_git_context(cbm_pipeline_t *p) {
+ cbm_git_context_t fresh = {0};
+ if (!p || cbm_git_context_resolve(p->repo_path, &fresh) != 0) {
+ cbm_git_context_free(&fresh);
+ return CBM_NOT_FOUND;
+ }
+ char *fresh_branch_qn = cbm_git_context_branch_qn(p->project_name, &fresh);
+ if (!fresh_branch_qn) {
+ cbm_git_context_free(&fresh);
+ return CBM_NOT_FOUND;
+ }
+ cbm_git_context_free(&p->git_ctx);
+ free(p->branch_qn);
+ p->git_ctx = fresh;
+ p->branch_qn = fresh_branch_qn;
+ return 0;
+}
+
void cbm_pipeline_set_persistence(cbm_pipeline_t *p, bool enabled) {
if (p) {
p->persistence = enabled;
@@ -979,6 +1066,9 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
cbm_log_info("pass.timing", "pass", "parallel_extract", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
if (rc != 0 || check_cancel(p)) {
+ for (int i = 0; i < file_count; i++) {
+ cbm_free_result(cache[i]);
+ }
free(cache);
return rc != 0 ? rc : CBM_NOT_FOUND;
}
@@ -1005,6 +1095,15 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
free(cache);
return rc != 0 ? rc : CBM_NOT_FOUND;
}
+ /* Registry consumers may materialize serial nodes (Channel, EnvVar, and
+ * future carrier-derived resources) after parallel extraction established
+ * the shared allocator watermark. Advance the atomic allocator before
+ * resolve workers resume; otherwise their IDs and the later next-id reset
+ * can collide with those nodes and orphan freshly inserted edges. */
+ int64_t registry_next_id = cbm_gbuf_next_id(p->gbuf);
+ if (registry_next_id > atomic_load(&shared_ids)) {
+ atomic_store(&shared_ids, registry_next_id);
+ }
/* 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
@@ -1100,77 +1199,76 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
return check_cancel(p) ? CBM_NOT_FOUND : 0;
}
-/* Try incremental pipeline or delete old DB for reindex.
- * Returns >= 0 if incremental was used (the return code), or -1 to proceed with full. */
-static int try_incremental_or_delete_db(cbm_pipeline_t *p, cbm_file_info_t *files, int file_count) {
+static int capture_existing_adr(cbm_pipeline_t *p, const char *db_path) {
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ if (atomic_exchange(&g_persist_test_fail_adr_capture, false)) {
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+#endif
+ cbm_store_t *adr_store = cbm_store_open_path_query(db_path);
+ if (!adr_store) {
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ cbm_adr_t existing = {0};
+ int adr_rc = cbm_store_adr_get(adr_store, p->project_name, &existing);
+ if (adr_rc == CBM_STORE_NOT_FOUND) {
+ cbm_store_close(adr_store);
+ free(p->saved_adr);
+ p->saved_adr = NULL;
+ return 0;
+ }
+ if (adr_rc != CBM_STORE_OK || !existing.content) {
+ cbm_store_adr_free(&existing);
+ cbm_store_close(adr_store);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ char *saved = strdup(existing.content);
+ cbm_store_adr_free(&existing);
+ cbm_store_close(adr_store);
+ if (!saved) {
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ free(p->saved_adr);
+ p->saved_adr = saved;
+ return 0;
+}
+
+/* Route an existing generation. Full rebuilds never delete the live DB here:
+ * publication owns the eventual atomic replacement after every pass and
+ * metadata write has succeeded. */
+static int try_incremental_or_delete_db(cbm_pipeline_t *p, cbm_file_info_t *files, int file_count,
+ const cbm_file_hash_t *baseline_manifest,
+ int baseline_count) {
char *db_path = resolve_db_path(p);
if (!db_path) {
- return CBM_NOT_FOUND;
+ return CBM_PIPELINE_FORCE_FULL_REINDEX;
}
struct stat db_st;
if (stat(db_path, &db_st) != 0) {
free(db_path);
- return CBM_NOT_FOUND;
+ return CBM_PIPELINE_FORCE_FULL_REINDEX;
}
- cbm_store_t *check_store = cbm_store_open_path(db_path);
- if (check_store && cbm_store_check_integrity(check_store)) {
- cbm_file_hash_t *hashes = NULL;
- int hash_count = 0;
- cbm_store_get_file_hashes(check_store, p->project_name, &hashes, &hash_count);
- cbm_store_free_file_hashes(hashes, hash_count);
- cbm_store_close(check_store);
- if (hash_count > 0 && file_count <= hash_count + (hash_count / PAIR_LEN)) {
- cbm_log_info("pipeline.route", "path", "incremental", "stored_hashes",
- itoa_buf(hash_count));
- int rc = cbm_pipeline_run_incremental(p, db_path, files, file_count);
- free(db_path);
- return rc;
- }
- if (hash_count > 0) {
- cbm_log_info("pipeline.route", "path", "mode_change_reindex", "stored_hashes",
- itoa_buf(hash_count), "discovered", itoa_buf(file_count));
- }
- } else if (check_store) {
+ cbm_store_t *check_store = cbm_store_open_path_query(db_path);
+ bool valid = check_store && cbm_store_check_integrity(check_store);
+ if (check_store) {
cbm_store_close(check_store);
}
- cbm_log_info("pipeline.route", "path", "reindex", "action", "deleting old db");
- /* Capture any ADR before deleting the DB so the full-reindex rebuild can
- * restore it (project_summaries is otherwise lost). Issue #516. */
- {
- cbm_store_t *adr_store = cbm_store_open_path(db_path);
- if (adr_store) {
- cbm_adr_t existing;
- if (cbm_store_adr_get(adr_store, p->project_name, &existing) == CBM_STORE_OK) {
- if (existing.content) {
- free(p->saved_adr);
- p->saved_adr = strdup(existing.content);
- }
- cbm_store_adr_free(&existing);
- }
- cbm_store_close(adr_store);
+ if (!valid) {
+ cbm_log_warn("pipeline.route", "path", "full", "reason", "invalid_existing_db");
+ free(db_path);
+ return CBM_PIPELINE_FORCE_FULL_REINDEX;
+ }
+ cbm_log_info("pipeline.route", "path", "incremental_manifest");
+ int rc = cbm_pipeline_run_incremental(p, db_path, files, file_count, baseline_manifest,
+ baseline_count);
+ if (rc == CBM_PIPELINE_FORCE_FULL_REINDEX) {
+ int adr_rc = capture_existing_adr(p, db_path);
+ if (adr_rc != 0) {
+ rc = adr_rc;
}
}
- cbm_unlink(db_path);
- char wal[PL_WAL_BUF];
- char shm[PL_WAL_BUF];
- snprintf(wal, sizeof(wal), "%s-wal", db_path);
- snprintf(shm, sizeof(shm), "%s-shm", db_path);
- cbm_unlink(wal);
- cbm_unlink(shm);
free(db_path);
- return CBM_NOT_FOUND;
-}
-
-/* Get platform-specific mtime in nanoseconds. */
-static int64_t stat_mtime_ns(const struct stat *fst) {
-#ifdef __APPLE__
- return ((int64_t)fst->st_mtimespec.tv_sec * PL_NSEC_PER_SEC) +
- (int64_t)fst->st_mtimespec.tv_nsec;
-#elif defined(_WIN32)
- return (int64_t)fst->st_mtime * 1000000000LL;
-#else
- return ((int64_t)fst->st_mtim.tv_sec * PL_NSEC_PER_SEC) + (int64_t)fst->st_mtim.tv_nsec;
-#endif
+ return rc;
}
static const char *pipeline_mode_name(cbm_index_mode_t mode) {
@@ -1186,9 +1284,348 @@ static const char *pipeline_mode_name(cbm_index_mode_t mode) {
}
}
+static int pipeline_mode_coverage_rank(cbm_index_mode_t mode) {
+ switch (mode) {
+ case CBM_MODE_FULL:
+ return 3;
+ case CBM_MODE_MODERATE:
+ return 2;
+ case CBM_MODE_FAST:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
+/* Index modes are additive: a cheaper run may refresh a fuller graph, but it
+ * must never erase files that the cheaper discovery intentionally skips. The
+ * exact-manifest pipeline therefore keeps the most comprehensive successfully
+ * published mode and performs any changed rebuild at that coverage level. */
+static void promote_mode_to_existing_coverage(cbm_pipeline_t *p) {
+ if (!p || !p->project_name) {
+ return;
+ }
+ char *db_path = resolve_db_path(p);
+ if (!db_path) {
+ return;
+ }
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ free(db_path);
+ if (!store) {
+ return;
+ }
+ cbm_coverage_meta_t meta = {0};
+ if (cbm_store_coverage_meta_get(store, p->project_name, &meta) == CBM_STORE_OK &&
+ meta.index_mode) {
+ cbm_index_mode_t stored_mode = p->mode;
+ if (strcmp(meta.index_mode, "full") == 0) {
+ stored_mode = CBM_MODE_FULL;
+ } else if (strcmp(meta.index_mode, "moderate") == 0) {
+ stored_mode = CBM_MODE_MODERATE;
+ } else if (strcmp(meta.index_mode, "fast") == 0) {
+ stored_mode = CBM_MODE_FAST;
+ }
+ if (pipeline_mode_coverage_rank(stored_mode) > pipeline_mode_coverage_rank(p->mode)) {
+ cbm_log_info("pipeline.mode", "requested", pipeline_mode_name(p->mode), "effective",
+ pipeline_mode_name(stored_mode), "reason", "preserve_existing_coverage");
+ p->mode = stored_mode;
+ }
+ }
+ cbm_store_coverage_meta_clear(&meta);
+ cbm_store_close(store);
+}
+
+int cbm_pipeline_refresh_artifact(cbm_pipeline_t *p, const char *db_path) {
+ if (!p || !db_path || !p->repo_path || !p->project_name) {
+ return 0;
+ }
+ bool existing = cbm_artifact_exists(p->repo_path);
+ if (!p->persistence && !existing) {
+ return 0;
+ }
+ int quality = p->persistence ? CBM_ARTIFACT_BEST : CBM_ARTIFACT_FAST;
+ int rc = cbm_artifact_export(db_path, p->repo_path, p->project_name, quality);
+ if (rc != 0) {
+ const char *err = cbm_artifact_export_last_error();
+ if (p->persistence) {
+ cbm_log_error("pipeline.err", "phase", "artifact_export", "err", err ? err : "unknown");
+ return rc;
+ }
+ cbm_log_warn("artifact.refresh_failed", "err", err ? err : "unknown");
+ }
+ return 0;
+}
+
+static atomic_ullong g_generation_stage_counter = 0;
+
+static void discard_generation_stage(const char *stage_path) {
+ if (!stage_path) {
+ return;
+ }
+ cbm_unlink(stage_path);
+ cbm_remove_db_sidecars(stage_path);
+}
+
+static int generation_rebuild_fts(cbm_store_t *store) {
+ if (cbm_store_exec(store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');") !=
+ CBM_STORE_OK) {
+ return CBM_STORE_ERR;
+ }
+ if (cbm_store_exec(store,
+ "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
+ "SELECT id, cbm_camel_split(name), qualified_name, label, file_path "
+ "FROM nodes;") == CBM_STORE_OK) {
+ return CBM_STORE_OK;
+ }
+ return cbm_store_exec(store,
+ "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
+ "SELECT id, name, qualified_name, label, file_path FROM nodes;");
+}
+
+typedef struct {
+ bool quarantined;
+ char backup_path[CBM_SZ_4K];
+} cbm_replacement_prepare_t;
+
+static int replacement_sidecar_path(char *out, size_t out_size, const char *base,
+ const char *suffix) {
+ int n = snprintf(out, out_size, "%s%s", base, suffix);
+ return n > 0 && (size_t)n < out_size ? 0 : CBM_PIPELINE_PERSIST_FAILED;
+}
+
+static bool replacement_path_exists(const char *path) {
+ cbm_path_info_t info;
+ return cbm_path_info_utf8(path, &info) == 0;
+}
+
+static int rollback_quarantined_generation(const char *db_path,
+ cbm_replacement_prepare_t *prepared) {
+ if (!prepared || !prepared->quarantined) {
+ return 0;
+ }
+ static const char *const suffixes[] = {"-wal", "-shm"};
+ if (cbm_rename_noreplace(prepared->backup_path, db_path) != 0) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); i++) {
+ char source[CBM_SZ_4K];
+ char destination[CBM_SZ_4K];
+ if (replacement_sidecar_path(source, sizeof(source), prepared->backup_path, suffixes[i]) !=
+ 0 ||
+ replacement_sidecar_path(destination, sizeof(destination), db_path, suffixes[i]) != 0) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ if (replacement_path_exists(source) && cbm_rename_noreplace(source, destination) != 0) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ }
+ prepared->quarantined = false;
+ prepared->backup_path[0] = '\0';
+ return 0;
+}
+
+static int quarantine_existing_generation(const char *db_path,
+ cbm_replacement_prepare_t *prepared) {
+ if (!db_path || !prepared) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ static const char *const suffixes[] = {"-wal", "-shm"};
+ char candidate[CBM_SZ_4K];
+ for (int attempt = 0; attempt < 10000; attempt++) {
+ int n = attempt == 0
+ ? snprintf(candidate, sizeof(candidate), "%s.corrupt", db_path)
+ : snprintf(candidate, sizeof(candidate), "%s.corrupt.%d", db_path, attempt);
+ if (n <= 0 || (size_t)n >= sizeof(candidate)) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ bool available = !replacement_path_exists(candidate);
+ for (size_t i = 0; available && i < sizeof(suffixes) / sizeof(suffixes[0]); i++) {
+ char candidate_sidecar[CBM_SZ_4K];
+ if (replacement_sidecar_path(candidate_sidecar, sizeof(candidate_sidecar), candidate,
+ suffixes[i]) != 0) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ available = !replacement_path_exists(candidate_sidecar);
+ }
+ if (!available) {
+ continue;
+ }
+ if (cbm_rename_noreplace(db_path, candidate) != 0) {
+ if (replacement_path_exists(candidate)) {
+ continue;
+ }
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+
+ snprintf(prepared->backup_path, sizeof(prepared->backup_path), "%s", candidate);
+ prepared->quarantined = true;
+ for (size_t i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); i++) {
+ char source[CBM_SZ_4K];
+ char destination[CBM_SZ_4K];
+ if (replacement_sidecar_path(source, sizeof(source), db_path, suffixes[i]) != 0 ||
+ replacement_sidecar_path(destination, sizeof(destination), candidate,
+ suffixes[i]) != 0) {
+ (void)rollback_quarantined_generation(db_path, prepared);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ if (replacement_path_exists(source) && cbm_rename_noreplace(source, destination) != 0) {
+ (void)rollback_quarantined_generation(db_path, prepared);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ }
+ return 0;
+ }
+ return CBM_PIPELINE_PERSIST_FAILED;
+}
+
+static int prepare_existing_generation_for_replace(const char *db_path,
+ cbm_replacement_prepare_t *prepared) {
+ if (!prepared) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ memset(prepared, 0, sizeof(*prepared));
+ cbm_path_info_t info;
+ if (cbm_path_info_utf8(db_path, &info) == 0) {
+ if (!info.is_regular || info.is_symlink) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ int seal_rc = cbm_store_seal_existing_path_for_replace(db_path);
+ if (seal_rc == CBM_STORE_NOT_FOUND) {
+ return quarantine_existing_generation(db_path, prepared);
+ }
+ if (seal_rc != CBM_STORE_OK) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ }
+ return cbm_remove_db_sidecars_checked(db_path) == 0 ? 0 : CBM_PIPELINE_PERSIST_FAILED;
+}
+
+int cbm_pipeline_publish_generation(const cbm_pipeline_generation_t *generation) {
+ if (!generation || !generation->gbuf || !generation->final_db_path || !generation->project ||
+ generation->manifest_count < 0 ||
+ (generation->manifest_count > 0 && !generation->manifest) ||
+ generation->coverage_count < 0 ||
+ (generation->coverage_count > 0 && !generation->coverage)) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ if (generation->cancelled && atomic_load(generation->cancelled)) {
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ size_t stage_size = strlen(generation->final_db_path) + 96;
+ char *stage_path = malloc(stage_size);
+ if (!stage_path) {
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ unsigned long long serial = atomic_fetch_add(&g_generation_stage_counter, 1) + 1;
+ int path_n = snprintf(stage_path, stage_size, "%s.stage.%ld.%llu", generation->final_db_path,
+ (long)cbm_pipeline_getpid(), serial);
+ if (path_n < 0 || (size_t)path_n >= stage_size) {
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ discard_generation_stage(stage_path);
+
+ int dump_rc = cbm_gbuf_dump_to_sqlite(generation->gbuf, stage_path);
+ if (dump_rc != 0) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ if (cbm_pipeline_persist_test_take_failure_after_stage_dump()) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+#endif
+ if (generation->cancelled && atomic_load(generation->cancelled)) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ cbm_store_t *store = cbm_store_open_path(stage_path);
+ if (!store) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ bool ok = cbm_store_exec(store, "PRAGMA synchronous=FULL;") == CBM_STORE_OK;
+ ok = ok && cbm_store_delete_file_hashes(store, generation->project) == CBM_STORE_OK &&
+ cbm_store_upsert_file_hash_batch(store, generation->manifest,
+ generation->manifest_count) == CBM_STORE_OK;
+ if (ok && generation->adr_content) {
+ ok = cbm_store_adr_store(store, generation->project, generation->adr_content) ==
+ CBM_STORE_OK;
+ }
+
+ cbm_project_t project_info = {0};
+ bool have_project_info =
+ cbm_store_get_project(store, generation->project, &project_info) == CBM_STORE_OK;
+ cbm_coverage_meta_t meta = generation->coverage_meta;
+ meta.generation = have_project_info ? project_info.indexed_at : NULL;
+ meta.coverage_version = CBM_SEMANTIC_INDEX_VERSION;
+ meta.hash_records_complete = true;
+ if (!have_project_info ||
+ cbm_store_coverage_replace_ex(store, generation->project, generation->coverage,
+ generation->coverage_count, &meta) != CBM_STORE_OK) {
+ ok = false;
+ }
+ if (have_project_info) {
+ cbm_project_free_fields(&project_info);
+ }
+ if (generation_rebuild_fts(store) != CBM_STORE_OK || !cbm_store_check_integrity(store)) {
+ ok = false;
+ }
+ if (ok && cbm_store_seal_for_atomic_publish(store) != CBM_STORE_OK) {
+ ok = false;
+ }
+ cbm_store_close(store);
+ if (ok && cbm_remove_db_sidecars_checked(stage_path) != 0) {
+ ok = false;
+ }
+ if (!ok) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ if (generation->cancelled && atomic_load(generation->cancelled)) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ cbm_replacement_prepare_t prepared = {0};
+ if (prepare_existing_generation_for_replace(generation->final_db_path, &prepared) != 0) {
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ if (cbm_pipeline_persist_test_take_cancel_after_destination_prepare() &&
+ generation->cancelled) {
+ atomic_store(generation->cancelled, true);
+ }
+#endif
+ if (generation->cancelled && atomic_load(generation->cancelled)) {
+ int rollback_rc = rollback_quarantined_generation(generation->final_db_path, &prepared);
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return rollback_rc == 0 ? CBM_PIPELINE_ABORT_PRESERVE_DB : CBM_PIPELINE_PERSIST_FAILED;
+ }
+ if (cbm_rename_replace(stage_path, generation->final_db_path) != 0) {
+ (void)rollback_quarantined_generation(generation->final_db_path, &prepared);
+ discard_generation_stage(stage_path);
+ free(stage_path);
+ return CBM_PIPELINE_PERSIST_FAILED;
+ }
+ free(stage_path);
+ return 0;
+}
+
/* Dump graph to SQLite and persist file hashes for incremental indexing. */
-static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_info_t *files, int file_count,
- struct timespec *t) {
+static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_hash_t *baseline_manifest,
+ int baseline_count, struct timespec *t) {
cbm_clock_gettime(CLOCK_MONOTONIC, t);
char db_path[CBM_SZ_1K];
if (p->db_path) {
@@ -1207,190 +1644,95 @@ static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_info_t *fil
*last_slash = '\0';
cbm_mkdir_p(db_dir, CBM_DIR_PERMS);
}
- /* Capture committed counts BEFORE the dump. cbm_gbuf_dump_to_sqlite calls
- * release_gbuf_indexes(), which frees node_by_qn (graph_buffer.c), after
- * which cbm_gbuf_node_count() returns 0. Reading these post-dump left
- * committed_nodes at 0, so the #334 plausibility gate never fired. */
- p->committed_nodes = cbm_gbuf_node_count(p->gbuf);
- p->committed_edges = cbm_gbuf_edge_count(p->gbuf);
- int rc = cbm_gbuf_dump_to_sqlite(p->gbuf, db_path);
- if (rc != 0) {
- cbm_log_error("pipeline.err", "phase", "dump");
- return rc;
- }
- cbm_log_info("pass.timing", "pass", "dump", "elapsed_ms", itoa_buf((int)elapsed_ms(*t)));
- /* Persist-tail spans (phase "persist"): attribute the ~60s that lands here
- * AFTER cbm_gbuf_dump_to_sqlite returns. Active only under CBM_PROFILE. */
- CBM_PROF_START(t_reopen);
- cbm_store_t *hash_store = cbm_store_open_path(db_path);
- CBM_PROF_END("persist", "1_reopen", t_reopen);
- if (hash_store) {
- bool hash_records_complete = true;
- CBM_PROF_START(t_delhash);
- if (cbm_store_delete_file_hashes(hash_store, p->project_name) != CBM_STORE_OK) {
- hash_records_complete = false;
- }
- CBM_PROF_END("persist", "2_delete_file_hashes", t_delhash);
-
- /* Restore the ADR captured before the dump. Surface a failed restore
- * rather than silently dropping the ADR (the original #516 symptom). */
- CBM_PROF_START(t_adr);
- if (p->saved_adr) {
- if (cbm_store_adr_store(hash_store, p->project_name, p->saved_adr) != CBM_STORE_OK) {
- cbm_log_error("pipeline.err", "phase", "adr_restore", "project", p->project_name);
- }
- }
- CBM_PROF_END("persist", "3_adr_restore", t_adr);
-
- /* Batch the per-file hash upserts into ONE transaction. The per-file
- * cbm_store_upsert_file_hash path autocommits, i.e. file_count fsyncs
- * (~89k on the kernel); cbm_store_upsert_file_hash_batch wraps the same
- * cached INSERT ... ON CONFLICT upsert in a single begin/commit. Same
- * (project, rel_path, sha256="", mtime_ns, size) tuples, same replace
- * semantics — only the transaction boundary changes. */
- CBM_PROF_START(t_fh);
- cbm_file_hash_t *fhashes = (cbm_file_hash_t *)malloc(
- (size_t)(file_count > 0 ? file_count : 1) * sizeof(cbm_file_hash_t));
- if (fhashes) {
- int fh_n = 0;
- for (int i = 0; i < file_count; i++) {
- struct stat fst;
- if (stat(files[i].path, &fst) == 0) {
- fhashes[fh_n].project = p->project_name;
- fhashes[fh_n].rel_path = files[i].rel_path;
- fhashes[fh_n].sha256 = "";
- fhashes[fh_n].mtime_ns = stat_mtime_ns(&fst);
- fhashes[fh_n].size = fst.st_size;
- fh_n++;
- } else {
- hash_records_complete = false;
- }
- }
- if (cbm_store_upsert_file_hash_batch(hash_store, fhashes, fh_n) != CBM_STORE_OK) {
- cbm_log_error("pipeline.err", "phase", "persist_file_hashes", "project",
- p->project_name);
- hash_records_complete = false;
+
+ cbm_file_hash_t *manifest = NULL;
+ int manifest_count = 0;
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ cbm_pipeline_persist_test_run_before_final_manifest();
+#endif
+ if (cbm_pipeline_build_fresh_semantic_manifest(p->project_name, p->repo_path, p->mode,
+ &manifest, &manifest_count) != 0) {
+ cbm_log_error("pipeline.err", "phase", "semantic_manifest");
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ if (!cbm_pipeline_semantic_manifests_equal(baseline_manifest, baseline_count, manifest,
+ manifest_count)) {
+ cbm_log_warn("pipeline.abort", "reason", "semantic_inputs_changed");
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ int cov_total = p->file_errors_count + p->excluded_count + p->ignored_count;
+ cbm_coverage_row_t *cov = NULL;
+ int cov_count = 0;
+ bool coverage_rows_available = cov_total == 0;
+ if (cov_total > 0) {
+ cov = malloc((size_t)cov_total * sizeof(*cov));
+ if (cov) {
+ coverage_rows_available = true;
+ for (int i = 0; i < p->file_errors_count; i++) {
+ cov[cov_count++] = (cbm_coverage_row_t){.rel_path = p->file_errors[i].path,
+ .kind = p->file_errors[i].phase,
+ .detail = p->file_errors[i].reason};
}
- free(fhashes);
- } else {
- /* OOM fallback: the original per-file path (identical result, slower). */
- for (int i = 0; i < file_count; i++) {
- struct stat fst;
- if (stat(files[i].path, &fst) == 0) {
- if (cbm_store_upsert_file_hash(hash_store, p->project_name, files[i].rel_path,
- "", stat_mtime_ns(&fst),
- fst.st_size) != CBM_STORE_OK) {
- hash_records_complete = false;
- }
- } else {
- hash_records_complete = false;
- }
+ for (int i = 0; i < p->excluded_count; i++) {
+ cov[cov_count++] = (cbm_coverage_row_t){.rel_path = p->excluded_dirs[i],
+ .kind = "not_indexed_dir",
+ .detail = "excluded subtree"};
}
- }
- CBM_PROF_END_N("persist", "4_file_hashes", t_fh, file_count);
-
- /* Coverage rows (#963): a full run's file_errors plus the by-design
- * discovery exclusions are the complete coverage truth for the
- * project. The dump recreated the DB file, so the separate
- * index_coverage table starts empty — write only when there is
- * something to record (AFTER hashes, so the deleted-file prune inside
- * replace sees the live file set; not_indexed_* kinds are exempt from
- * that prune — deliberately-unindexed paths have no hash rows). */
- int cov_total = p->file_errors_count + p->excluded_count + p->ignored_count;
- cbm_coverage_row_t *cov = NULL;
- int cn = 0;
- bool coverage_rows_available = cov_total == 0;
- if (cov_total > 0) {
- cov = (cbm_coverage_row_t *)malloc((size_t)cov_total * sizeof(*cov));
- if (cov) {
- coverage_rows_available = true;
- for (int i = 0; i < p->file_errors_count; i++) {
- cov[cn].rel_path = p->file_errors[i].path;
- cov[cn].kind = p->file_errors[i].phase;
- cov[cn].detail = p->file_errors[i].reason;
- cn++;
- }
- for (int i = 0; i < p->excluded_count; i++) {
- cov[cn].rel_path = p->excluded_dirs[i];
- cov[cn].kind = "not_indexed_dir";
- cov[cn].detail = "excluded subtree";
- cn++;
- }
- for (int i = 0; i < p->ignored_count; i++) {
- cov[cn].rel_path = p->ignored_files[i].rel_path;
- cov[cn].kind = "not_indexed_file";
- cov[cn].detail = p->ignored_files[i].reason;
- cn++;
- }
+ for (int i = 0; i < p->ignored_count; i++) {
+ cov[cov_count++] = (cbm_coverage_row_t){.rel_path = p->ignored_files[i].rel_path,
+ .kind = "not_indexed_file",
+ .detail = p->ignored_files[i].reason};
}
}
+ }
+ cbm_pipeline_generation_t generation = {
+ .gbuf = p->gbuf,
+ .final_db_path = db_path,
+ .project = p->project_name,
+ .cancelled = &p->cancelled,
+ .manifest = manifest,
+ .manifest_count = manifest_count,
+ .adr_content = p->saved_adr,
+ .coverage = cov,
+ .coverage_count = cov_count,
+ .coverage_meta =
+ {
+ .index_mode = pipeline_mode_name(p->mode),
+ .recording_status =
+ !coverage_rows_available
+ ? "unavailable"
+ : (p->ignored_total > p->ignored_count ? "truncated" : "complete"),
+ .ignored_files_stored = p->ignored_count,
+ .ignored_files_total = p->ignored_total,
+ .coverage_version = CBM_SEMANTIC_INDEX_VERSION,
+ .hash_records_complete = true,
+ },
+ };
- cbm_project_t project_info = {0};
- bool have_project_info =
- cbm_store_get_project(hash_store, p->project_name, &project_info) == CBM_STORE_OK;
- const char *recording_status =
- !coverage_rows_available
- ? "unavailable"
- : (p->ignored_total > p->ignored_count ? "truncated" : "complete");
- cbm_coverage_meta_t coverage_meta = {
- .generation = have_project_info ? project_info.indexed_at : NULL,
- .index_mode = pipeline_mode_name(p->mode),
- .recording_status = recording_status,
- .ignored_files_stored = p->ignored_count,
- .ignored_files_total = p->ignored_total,
- .coverage_version = 1,
- .hash_records_complete = hash_records_complete,
- };
- if (cbm_store_coverage_replace_ex(hash_store, p->project_name, cov, cn, &coverage_meta) !=
- CBM_STORE_OK) {
- cbm_log_error("pipeline.err", "phase", "persist_coverage", "project", p->project_name);
- }
- free(cov);
- if (have_project_info) {
- cbm_project_free_fields(&project_info);
- }
- if (p->ignored_total > p->ignored_count) {
- cbm_log_warn("index.ignored_capped", "stored", itoa_buf(p->ignored_count), "total",
- itoa_buf(p->ignored_total));
- }
-
- /* FTS5 backfill: populate nodes_fts with camelCase-split names.
- * Contentless FTS5 requires the special 'delete-all' command instead of
- * DELETE FROM to wipe prior rows (there's no underlying content table).
- * Falls back to plain names if cbm_camel_split is unavailable (which
- * shouldn't happen because we always register it, but we stay defensive). */
- CBM_PROF_START(t_fts);
- cbm_store_exec(hash_store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');");
- if (cbm_store_exec(hash_store,
- "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
- "SELECT id, cbm_camel_split(name), qualified_name, label, file_path "
- "FROM nodes;") != CBM_STORE_OK) {
- cbm_store_exec(hash_store,
- "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
- "SELECT id, name, qualified_name, label, file_path FROM nodes;");
- }
- CBM_PROF_END("persist", "5_fts_backfill", t_fts);
-
- cbm_store_close(hash_store);
- cbm_log_info("pass.timing", "pass", "persist_hashes", "files", itoa_buf(file_count));
+ /* Capture counts before the dump releases graph-buffer indexes. */
+ p->committed_nodes = cbm_gbuf_node_count(p->gbuf);
+ p->committed_edges = cbm_gbuf_edge_count(p->gbuf);
+ int rc = cbm_pipeline_publish_generation(&generation);
+ free(cov);
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count);
+ if (rc != 0) {
+ return rc;
+ }
+ cbm_log_info("pass.timing", "pass", "dump_and_persist", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(*t)), "files", itoa_buf(manifest_count));
+ if (p->ignored_total > p->ignored_count) {
+ cbm_log_warn("index.ignored_capped", "stored", itoa_buf(p->ignored_count), "total",
+ itoa_buf(p->ignored_total));
}
free(p->saved_adr);
p->saved_adr = NULL;
- /* Export persistent artifact if enabled */
- if (p->persistence) {
- CBM_PROF_START(t_art);
- int arc = cbm_artifact_export(db_path, p->repo_path, p->project_name, CBM_ARTIFACT_BEST);
- CBM_PROF_END("persist", "6_artifact_export", t_art);
- if (arc != 0) {
- const char *err = cbm_artifact_export_last_error();
- cbm_log_error("pipeline.err", "phase", "artifact_export", "err", err ? err : "unknown");
- /* A failed persistence export intentionally fails the run; this used to be ignored. */
- return arc;
- }
- }
-
- return 0;
+ /* The SQLite generation is the commit point. Automatic refresh of an
+ * existing artifact is best-effort, but an explicitly requested artifact
+ * is caller-visible and must report an export failure. */
+ return cbm_pipeline_refresh_artifact(p, db_path);
}
/* Run githistory pass. */
@@ -1459,7 +1801,8 @@ static int run_tests_and_history(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
/* Run tests, git history, predump passes, and dump+persist. */
static int run_post_extraction(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
- const cbm_file_info_t *files, int file_count) {
+ const cbm_file_info_t *files, int file_count,
+ const cbm_file_hash_t *baseline_manifest, int baseline_count) {
int rc = run_tests_and_history(p, ctx, files, file_count);
if (rc != 0) {
return rc;
@@ -1469,12 +1812,20 @@ static int run_post_extraction(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
run_predump_passes(p, ctx);
CBM_PROF_END("pipeline", "3_predump_passes_total", t_predump);
- if (!check_cancel(p)) {
- struct timespec t;
- CBM_PROF_START(t_dump);
- rc = dump_and_persist_hashes(p, files, file_count, &t);
- CBM_PROF_END("pipeline", "4_dump_and_persist", t_dump);
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ if (cbm_pipeline_persist_test_take_cancel_after_predump()) {
+ atomic_store(&p->cancelled, 1);
}
+#endif
+
+ if (check_cancel(p)) {
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ struct timespec t;
+ CBM_PROF_START(t_dump);
+ rc = dump_and_persist_hashes(p, baseline_manifest, baseline_count, &t);
+ CBM_PROF_END("pipeline", "4_dump_and_persist", t_dump);
return rc;
}
@@ -1514,6 +1865,17 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
struct timespec t0;
cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
cbm_path_alias_collection_t *path_aliases = NULL;
+ cbm_file_hash_t *baseline_manifest = NULL;
+ int baseline_count = 0;
+
+ promote_mode_to_existing_coverage(p);
+
+ /* cbm_pipeline_new() may precede the actual run by an arbitrary interval.
+ * Refresh once here, then use this exact snapshot for both Branch graph
+ * construction and the baseline semantic manifest. */
+ if (pipeline_refresh_git_context(p) != 0) {
+ return CBM_NOT_FOUND;
+ }
/* C/C++ #define Macro nodes (#375) dominate extraction on macro-dense repos
* (≈49% of nodes on the Linux kernel), so gate them to full mode — moderate
@@ -1560,11 +1922,24 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
goto cleanup;
}
+ /* Snapshot every semantic input once before routing/extraction. The same
+ * bytes drive exact no-op comparison and are checked against a fresh
+ * rediscovery immediately before any replacement is published. */
+ rc = cbm_pipeline_build_semantic_manifest(p->project_name, p->repo_path, files, file_count,
+ p->excluded_dirs, p->excluded_count, &p->git_ctx,
+ p->userconfig, &baseline_manifest, &baseline_count);
+ if (rc != 0) {
+ rc = CBM_PIPELINE_ABORT_PRESERVE_DB;
+ goto cleanup;
+ }
+
/* Check for existing DB → try incremental or delete for reindex */
- rc = try_incremental_or_delete_db(p, files, file_count);
- if (rc == CBM_PIPELINE_ABORT_PRESERVE_DB || rc >= 0) {
- cbm_discover_free(files, file_count);
- return rc;
+ rc = try_incremental_or_delete_db(p, files, file_count, baseline_manifest, baseline_count);
+ if (rc >= 0 || rc == CBM_PIPELINE_ABORT_PRESERVE_DB || rc == CBM_PIPELINE_PERSIST_FAILED) {
+ goto cleanup;
+ }
+ if (rc != CBM_PIPELINE_FORCE_FULL_REINDEX) {
+ goto cleanup;
}
cbm_log_info("pipeline.route", "path", "full");
@@ -1596,7 +1971,7 @@ int cbm_pipeline_run(cbm_pipeline_t *p) {
goto cleanup;
}
- rc = run_post_extraction(p, &ctx, files, file_count);
+ rc = run_post_extraction(p, &ctx, files, file_count, baseline_manifest, baseline_count);
if (rc != 0) {
goto cleanup;
}
@@ -1610,6 +1985,7 @@ cleanup:
cbm_pkgmap_free(cbm_pipeline_get_pkgmap());
cbm_pipeline_set_pkgmap(NULL);
cbm_discover_free(files, file_count);
+ cbm_pipeline_free_semantic_manifest(baseline_manifest, baseline_count);
cbm_gbuf_free(p->gbuf);
p->gbuf = NULL;
cbm_registry_free(p->registry);
diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c
index 8b5766978..0bfaefe34 100644
--- a/src/pipeline/pipeline_incremental.c
+++ b/src/pipeline/pipeline_incremental.c
@@ -25,6 +25,7 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24, INCR_WAL_BUF = 1
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/platform.h"
+#include "foundation/sha256.h"
#include <errno.h>
#include <stdlib.h>
@@ -39,6 +40,45 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24, INCR_WAL_BUF = 1
#define CBM_NS_PER_MS 1000000.0
#define CBM_NS_PER_SEC 1000000000LL
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+/* One-shot fault injection for the parallel incremental result cache. The
+ * production build has no hook or branch at this allocation site. */
+static atomic_bool g_incr_test_fail_result_cache_alloc = false;
+static atomic_bool g_incr_test_force_legacy_partial = false;
+static atomic_int g_incr_test_last_route = CBM_INCREMENTAL_ROUTE_NONE;
+
+void cbm_pipeline_incremental_test_fail_result_cache_alloc_once(void) {
+ atomic_store(&g_incr_test_fail_result_cache_alloc, true);
+}
+
+void cbm_pipeline_incremental_test_force_legacy_partial_once(void) {
+ atomic_store(&g_incr_test_force_legacy_partial, true);
+}
+
+cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void) {
+ return (cbm_incremental_route_t)atomic_load(&g_incr_test_last_route);
+}
+
+void cbm_pipeline_incremental_test_reset_faults(void) {
+ atomic_store(&g_incr_test_fail_result_cache_alloc, false);
+ atomic_store(&g_incr_test_force_legacy_partial, false);
+ atomic_store(&g_incr_test_last_route, CBM_INCREMENTAL_ROUTE_NONE);
+ cbm_pipeline_persist_test_reset_faults();
+}
+
+static bool incr_test_take_result_cache_alloc_failure(void) {
+ return atomic_exchange(&g_incr_test_fail_result_cache_alloc, false);
+}
+
+static bool incr_test_take_force_legacy_partial(void) {
+ return atomic_exchange(&g_incr_test_force_legacy_partial, false);
+}
+
+static void incr_test_set_last_route(cbm_incremental_route_t route) {
+ atomic_store(&g_incr_test_last_route, route);
+}
+#endif
+
/* ── Timing helper (same as pipeline.c) ──────────────────────────── */
static double elapsed_ms(struct timespec start) {
@@ -83,6 +123,423 @@ static const char *incr_mode_name(int mode) {
}
}
+/* ── Exact semantic manifest ───────────────────────────────────── */
+
+typedef struct {
+ cbm_file_hash_t *items;
+ int count;
+ int cap;
+ CBMHashTable *seen_paths;
+} semantic_manifest_builder_t;
+
+static int semantic_manifest_cmp(const void *a, const void *b) {
+ const cbm_file_hash_t *ma = a;
+ const cbm_file_hash_t *mb = b;
+ return strcmp(ma->rel_path, mb->rel_path);
+}
+
+static bool semantic_manifest_is_virtual_path(const char *rel_path) {
+ return rel_path &&
+ strncmp(rel_path, CBM_SEMANTIC_INPUT_PREFIX, strlen(CBM_SEMANTIC_INPUT_PREFIX)) == 0;
+}
+
+void cbm_pipeline_free_semantic_manifest(cbm_file_hash_t *manifest, int count) {
+ if (!manifest) {
+ return;
+ }
+ for (int i = 0; i < count; i++) {
+ free((void *)manifest[i].project);
+ free((void *)manifest[i].rel_path);
+ free((void *)manifest[i].sha256);
+ }
+ free(manifest);
+}
+
+/* Hash a stable file generation. A concurrent edit is retried once; a second
+ * race fails closed so a mixed-generation manifest can never be published. */
+static int semantic_manifest_hash_file(const char *abs_path, char out[CBM_SHA256_HEX_LEN + 1],
+ int64_t *mtime_ns, int64_t *size) {
+ for (int attempt = 0; attempt < 2; attempt++) {
+ cbm_path_info_t before;
+ if (cbm_path_info_utf8(abs_path, &before) != 0 || !before.is_regular || before.is_symlink) {
+ return CBM_NOT_FOUND;
+ }
+ FILE *f = cbm_fopen(abs_path, "rb");
+ if (!f) {
+ return CBM_NOT_FOUND;
+ }
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ unsigned char buf[CBM_SZ_64K];
+ size_t n;
+ while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
+ cbm_sha256_update(&sha, buf, n);
+ }
+ bool read_ok = !ferror(f);
+ if (fclose(f) != 0) {
+ read_ok = false;
+ }
+ cbm_path_info_t after;
+ if (!read_ok || cbm_path_info_utf8(abs_path, &after) != 0 || !after.is_regular ||
+ after.is_symlink) {
+ return CBM_NOT_FOUND;
+ }
+ if (before.size != after.size || before.mtime_ns != after.mtime_ns) {
+ continue;
+ }
+ 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 * 2] = hex[digest[i] >> 4];
+ out[i * 2 + 1] = hex[digest[i] & 0x0f];
+ }
+ out[CBM_SHA256_HEX_LEN] = '\0';
+ *mtime_ns = after.mtime_ns;
+ *size = after.size;
+ return 0;
+ }
+ cbm_log_warn("semantic_manifest.raced", "path", abs_path);
+ return CBM_NOT_FOUND;
+}
+
+static int semantic_manifest_add_digest(semantic_manifest_builder_t *builder, const char *project,
+ const char *rel_path, const char *sha, int64_t mtime_ns,
+ int64_t size) {
+ if (!builder || !project || !rel_path || !rel_path[0] || !sha ||
+ strlen(sha) != CBM_SHA256_HEX_LEN || cbm_ht_has(builder->seen_paths, rel_path)) {
+ return CBM_NOT_FOUND;
+ }
+ for (int i = 0; i < CBM_SHA256_HEX_LEN; i++) {
+ if (!((sha[i] >= '0' && sha[i] <= '9') || (sha[i] >= 'a' && sha[i] <= 'f'))) {
+ return CBM_NOT_FOUND;
+ }
+ }
+ if (builder->count == builder->cap) {
+ int new_cap = builder->cap > 0 ? builder->cap * 2 : CBM_SZ_64;
+ cbm_file_hash_t *grown = realloc(builder->items, (size_t)new_cap * sizeof(*builder->items));
+ if (!grown) {
+ return CBM_NOT_FOUND;
+ }
+ builder->items = grown;
+ builder->cap = new_cap;
+ }
+ char *project_copy = strdup(project);
+ char *path_copy = strdup(rel_path);
+ char *sha_copy = strdup(sha);
+ if (!project_copy || !path_copy || !sha_copy) {
+ free(project_copy);
+ free(path_copy);
+ free(sha_copy);
+ return CBM_NOT_FOUND;
+ }
+ uint32_t before_count = cbm_ht_count(builder->seen_paths);
+ cbm_ht_set(builder->seen_paths, path_copy, path_copy);
+ if (cbm_ht_count(builder->seen_paths) != before_count + 1U) {
+ free(project_copy);
+ free(path_copy);
+ free(sha_copy);
+ return CBM_NOT_FOUND;
+ }
+ builder->items[builder->count++] = (cbm_file_hash_t){
+ .project = project_copy,
+ .rel_path = path_copy,
+ .sha256 = sha_copy,
+ .mtime_ns = mtime_ns,
+ .size = size,
+ };
+ return 0;
+}
+
+static int semantic_manifest_add(semantic_manifest_builder_t *builder, const char *project,
+ const char *rel_path, const char *abs_path) {
+ if (!rel_path || !rel_path[0]) {
+ return 0;
+ }
+ /* Reserved rows are synthetic and can never be supplied by discovery. */
+ if (semantic_manifest_is_virtual_path(rel_path)) {
+ return CBM_NOT_FOUND;
+ }
+ if (cbm_ht_has(builder->seen_paths, rel_path)) {
+ return 0;
+ }
+ char sha[CBM_SHA256_HEX_LEN + 1];
+ int64_t mtime_ns = 0;
+ int64_t size = 0;
+ if (semantic_manifest_hash_file(abs_path, sha, &mtime_ns, &size) != 0) {
+ cbm_log_error("semantic_manifest.err", "path", abs_path);
+ return CBM_NOT_FOUND;
+ }
+ return semantic_manifest_add_digest(builder, project, rel_path, sha, mtime_ns, size);
+}
+
+static void semantic_manifest_git_digest(const cbm_git_context_t *git_ctx,
+ char out[CBM_SHA256_HEX_LEN + 1]) {
+ static const char domain[] = "cbm-semantic-git-context-v1";
+ cbm_sha256_ctx sha;
+ cbm_sha256_init(&sha);
+ cbm_sha256_update(&sha, domain, sizeof(domain));
+#define HASH_GIT_BOOL(field) \
+ do { \
+ const char value = git_ctx && git_ctx->field ? '1' : '0'; \
+ cbm_sha256_update(&sha, #field, sizeof(#field)); \
+ cbm_sha256_update(&sha, &value, sizeof(value)); \
+ } while (0)
+#define HASH_GIT_STRING(field) \
+ do { \
+ const char *value = git_ctx && git_ctx->field ? git_ctx->field : ""; \
+ cbm_sha256_update(&sha, #field, sizeof(#field)); \
+ cbm_sha256_update(&sha, value, strlen(value) + 1); \
+ } while (0)
+ HASH_GIT_BOOL(is_git);
+ HASH_GIT_BOOL(is_worktree);
+ HASH_GIT_BOOL(is_detached);
+ HASH_GIT_BOOL(root_exists);
+ HASH_GIT_STRING(branch);
+ HASH_GIT_STRING(branch_slug);
+ HASH_GIT_STRING(head_sha);
+ HASH_GIT_STRING(base_sha);
+#undef HASH_GIT_BOOL
+#undef HASH_GIT_STRING
+ 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 * 2] = hex[digest[i] >> 4];
+ out[i * 2 + 1] = hex[digest[i] & 0x0f];
+ }
+ out[CBM_SHA256_HEX_LEN] = '\0';
+}
+
+static bool semantic_manifest_package_control(const char *name) {
+ if (!name) {
+ return false;
+ }
+ size_t len = strlen(name);
+ return strcmp(name, "package.json") == 0 || strcmp(name, "go.mod") == 0 ||
+ strcmp(name, "Cargo.toml") == 0 || strcmp(name, "pyproject.toml") == 0 ||
+ strcmp(name, "composer.json") == 0 || strcmp(name, "pubspec.yaml") == 0 ||
+ strcmp(name, "pom.xml") == 0 || strcmp(name, "build.gradle") == 0 ||
+ strcmp(name, "build.gradle.kts") == 0 || strcmp(name, "mix.exs") == 0 ||
+ (len >= 8 && strcmp(name + len - 8, ".gemspec") == 0);
+}
+
+static int semantic_manifest_walk_controls(semantic_manifest_builder_t *builder,
+ const char *project, const char *abs_dir,
+ const char *rel_dir, int depth, char **excluded_dirs,
+ int excluded_count) {
+ enum { MANIFEST_WALK_MAX_DEPTH = 64 };
+ if (depth >= MANIFEST_WALK_MAX_DEPTH) {
+ return 0;
+ }
+ cbm_dir_t *dir = cbm_opendir(abs_dir);
+ if (!dir) {
+ return CBM_NOT_FOUND;
+ }
+ int rc = 0;
+ cbm_dirent_t *entry;
+ while (rc == 0 && (entry = cbm_readdir(dir)) != NULL) {
+ const char *name = entry->name;
+ if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
+ continue;
+ }
+ char abs_path[CBM_SZ_4K];
+ char rel_path[CBM_SZ_4K];
+ int abs_n = snprintf(abs_path, sizeof(abs_path), "%s/%s", abs_dir, name);
+ int rel_n = rel_dir && rel_dir[0]
+ ? snprintf(rel_path, sizeof(rel_path), "%s/%s", rel_dir, name)
+ : snprintf(rel_path, sizeof(rel_path), "%s", name);
+ if (abs_n < 0 || abs_n >= (int)sizeof(abs_path) || rel_n < 0 ||
+ rel_n >= (int)sizeof(rel_path)) {
+ rc = CBM_NOT_FOUND;
+ break;
+ }
+ cbm_path_info_t path_info;
+ if (cbm_path_info_utf8(abs_path, &path_info) != 0) {
+ rc = CBM_NOT_FOUND;
+ break;
+ }
+ if (path_info.is_symlink) {
+ continue;
+ }
+ if (path_info.is_directory) {
+ if (cbm_should_skip_dir(name, CBM_MODE_FULL) ||
+ cbm_pipeline_relpath_is_excluded(rel_path, excluded_dirs, excluded_count)) {
+ continue;
+ }
+ rc = semantic_manifest_walk_controls(builder, project, abs_path, rel_path, depth + 1,
+ excluded_dirs, excluded_count);
+ continue;
+ }
+ bool root_control =
+ (!rel_dir || !rel_dir[0]) &&
+ (strcmp(name, ".cbmignore") == 0 || strcmp(name, ".codebase-memory.json") == 0);
+ if (path_info.is_regular && (strcmp(name, ".gitignore") == 0 || root_control ||
+ semantic_manifest_package_control(name))) {
+ rc = semantic_manifest_add(builder, project, rel_path, abs_path);
+ }
+ }
+ cbm_closedir(dir);
+ return rc;
+}
+
+int cbm_pipeline_build_semantic_manifest(const char *project, const char *repo_path,
+ const cbm_file_info_t *files, int file_count,
+ char **excluded_dirs, int excluded_count,
+ const cbm_git_context_t *git_ctx,
+ const cbm_userconfig_t *userconfig, cbm_file_hash_t **out,
+ int *out_count) {
+ if (!project || !repo_path || !out || !out_count || file_count < 0 ||
+ (file_count > 0 && !files)) {
+ return CBM_NOT_FOUND;
+ }
+ *out = NULL;
+ *out_count = 0;
+ semantic_manifest_builder_t builder = {0};
+ uint64_t reserve = (uint64_t)(file_count > 0 ? file_count : 0) * 2U + CBM_SZ_64;
+ if (reserve > UINT32_MAX) {
+ reserve = UINT32_MAX;
+ }
+ builder.seen_paths = cbm_ht_create((uint32_t)reserve);
+ if (!builder.seen_paths) {
+ return CBM_NOT_FOUND;
+ }
+ int rc = 0;
+ char git_digest[CBM_SHA256_HEX_LEN + 1];
+ char absent_config_digest[CBM_SHA256_HEX_LEN + 1];
+ semantic_manifest_git_digest(git_ctx, git_digest);
+ cbm_sha256_hex("cbm-userconfig-unavailable-v1", strlen("cbm-userconfig-unavailable-v1"),
+ absent_config_digest);
+ const char *global_config_digest =
+ userconfig ? userconfig->global_source_sha256 : absent_config_digest;
+ const char *project_config_digest =
+ userconfig ? userconfig->project_source_sha256 : absent_config_digest;
+ rc = semantic_manifest_add_digest(&builder, project, CBM_SEMANTIC_INPUT_GIT_CONTEXT, git_digest,
+ 0, 0);
+ if (rc == 0) {
+ rc = semantic_manifest_add_digest(&builder, project, CBM_SEMANTIC_INPUT_GLOBAL_CONFIG,
+ global_config_digest, 0, 0);
+ }
+ if (rc == 0) {
+ rc = semantic_manifest_add_digest(&builder, project, CBM_SEMANTIC_INPUT_PROJECT_CONFIG,
+ project_config_digest, 0, 0);
+ }
+ for (int i = 0; rc == 0 && i < file_count; i++) {
+ rc = semantic_manifest_add(&builder, project, files[i].rel_path, files[i].path);
+ }
+ if (rc == 0) {
+ rc = semantic_manifest_walk_controls(&builder, project, repo_path, "", 0, excluded_dirs,
+ excluded_count);
+ }
+ if (rc == 0) {
+ cbm_path_alias_collection_t *aliases =
+ cbm_load_path_aliases_excluded(repo_path, excluded_dirs, excluded_count);
+ if (aliases) {
+ for (int i = 0; rc == 0 && i < aliases->count; i++) {
+ const char *rel = aliases->scopes[i].source_rel_path;
+ if (!rel) {
+ continue;
+ }
+ char abs_path[CBM_SZ_4K];
+ int n = snprintf(abs_path, sizeof(abs_path), "%s/%s", repo_path, rel);
+ rc = (n < 0 || n >= (int)sizeof(abs_path))
+ ? CBM_NOT_FOUND
+ : semantic_manifest_add(&builder, project, rel, abs_path);
+ }
+ cbm_path_alias_collection_free(aliases);
+ }
+ }
+ if (rc != 0) {
+ cbm_ht_free(builder.seen_paths);
+ cbm_pipeline_free_semantic_manifest(builder.items, builder.count);
+ return rc;
+ }
+ cbm_ht_free(builder.seen_paths);
+ qsort(builder.items, (size_t)builder.count, sizeof(*builder.items), semantic_manifest_cmp);
+ *out = builder.items;
+ *out_count = builder.count;
+ return 0;
+}
+
+bool cbm_pipeline_semantic_manifests_equal(const cbm_file_hash_t *left, int left_count,
+ const cbm_file_hash_t *right, int right_count) {
+ if (left_count < 0 || right_count < 0 || left_count != right_count ||
+ (left_count > 0 && (!left || !right))) {
+ return false;
+ }
+ uint64_t reserve = (uint64_t)(right_count > 0 ? right_count : 0) * 2U + CBM_SZ_64;
+ if (reserve > UINT32_MAX) {
+ reserve = UINT32_MAX;
+ }
+ CBMHashTable *by_path = cbm_ht_create((uint32_t)reserve);
+ if (!by_path) {
+ return false;
+ }
+ bool equal = true;
+ for (int i = 0; equal && i < right_count; i++) {
+ if (!right[i].rel_path || !right[i].sha256 || cbm_ht_has(by_path, right[i].rel_path)) {
+ equal = false;
+ break;
+ }
+ uint32_t before = cbm_ht_count(by_path);
+ cbm_ht_set(by_path, right[i].rel_path, (void *)right[i].sha256);
+ equal = cbm_ht_count(by_path) == before + 1U;
+ }
+ for (int i = 0; equal && i < left_count; i++) {
+ if (!left[i].rel_path || !left[i].sha256) {
+ equal = false;
+ break;
+ }
+ const char *sha = cbm_ht_get(by_path, left[i].rel_path);
+ equal = sha && strcmp(sha, left[i].sha256) == 0;
+ }
+ cbm_ht_free(by_path);
+ return equal;
+}
+
+int cbm_pipeline_build_fresh_semantic_manifest(const char *project, const char *repo_path, int mode,
+ cbm_file_hash_t **out, int *out_count) {
+ if (!project || !repo_path || !out || !out_count) {
+ return CBM_NOT_FOUND;
+ }
+ *out = NULL;
+ *out_count = 0;
+ cbm_discover_opts_t opts = {
+ .mode = (cbm_index_mode_t)mode,
+ .ignore_file = NULL,
+ .max_file_size = 0,
+ };
+ cbm_file_info_t *fresh_files = NULL;
+ int fresh_file_count = 0;
+ char **fresh_excluded = NULL;
+ int fresh_excluded_count = 0;
+ cbm_ignored_file_t *fresh_ignored = NULL;
+ int fresh_ignored_count = 0;
+ int fresh_ignored_total = 0;
+ cbm_userconfig_t *fresh_userconfig = cbm_userconfig_load(repo_path);
+ cbm_git_context_t fresh_git_ctx = {0};
+ const cbm_userconfig_t *previous_userconfig = cbm_get_user_lang_config();
+ int rc = fresh_userconfig ? cbm_git_context_resolve(repo_path, &fresh_git_ctx) : CBM_NOT_FOUND;
+ if (rc == 0) {
+ cbm_set_user_lang_config(fresh_userconfig);
+ rc = cbm_discover_ex2(repo_path, &opts, &fresh_files, &fresh_file_count, &fresh_excluded,
+ &fresh_excluded_count, &fresh_ignored, &fresh_ignored_count,
+ &fresh_ignored_total);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_build_semantic_manifest(project, repo_path, fresh_files, fresh_file_count,
+ fresh_excluded, fresh_excluded_count,
+ &fresh_git_ctx, fresh_userconfig, out, out_count);
+ }
+ cbm_set_user_lang_config(previous_userconfig);
+ cbm_git_context_free(&fresh_git_ctx);
+ cbm_userconfig_free(fresh_userconfig);
+ cbm_discover_free(fresh_files, fresh_file_count);
+ cbm_discover_free_excluded(fresh_excluded, fresh_excluded_count);
+ cbm_discover_free_ignored(fresh_ignored, fresh_ignored_count);
+ return rc;
+}
+
/* ── File classification ─────────────────────────────────────────── */
/* Classify discovered files against stored hashes using mtime+size.
@@ -217,6 +674,9 @@ static int find_deleted_files(const char *repo_path, cbm_file_info_t *files, int
}
for (int i = 0; i < stored_count; i++) {
+ if (semantic_manifest_is_virtual_path(stored[i].rel_path)) {
+ continue; /* synthetic semantic inputs are not repository files */
+ }
if (cbm_ht_get(current, stored[i].rel_path)) {
continue; /* still visited by current pass */
}
@@ -316,7 +776,7 @@ static void free_mode_skipped(cbm_file_hash_t *ms, int count) {
* edges whose source lives in an UNCHANGED file (e.g. StudyService.grade ->
* SM2.review, or a Folder -> File containment edge). Because incremental only
* re-parses the changed files, the resolution passes never regenerate those
- * inbound edges, so the graph silently loses cross-file CALLS / USAGE /
+ * inbound edges, so the graph silently loses cross-file CALLS / CALL_REFERENCE / USAGE /
* CONTAINS_FILE / INHERITS / ... edges on every edit and diverges from a
* clean full reindex (which resolves every file).
*
@@ -361,7 +821,7 @@ typedef struct {
* limitation rather than something to restore stale.
* Every other edge type IS safe to re-link, by one of two routes that both
* match a full reindex: edges re-emitted by the per-file resolution passes that
- * run incrementally (CALLS, USAGE, DEFINES, DEFINES_METHOD, INHERITS,
+ * run incrementally (CALLS, CALL_REFERENCE, USAGE, DEFINES, DEFINES_METHOD, INHERITS,
* IMPLEMENTS) are deduped on re-link, while structural containment edges
* (CONTAINS_FILE, CONTAINS_FOLDER) — which the full-only structure pass does
* NOT regenerate incrementally — are preserved precisely by this snapshot. */
@@ -444,77 +904,6 @@ static void incr_free_edge_capture(cbm_edge_capture_t *cap) {
cap->cap = 0;
}
-/* ── Persist file hashes ─────────────────────────────────────────── */
-
-/* Persist file hash rows for the current discovery and any mode-skipped
- * files preserved from the previous DB.
- *
- * Partial-failure policy: an `upsert` failure on any single row is logged
- * as a warning and the loop continues. We deliberately do NOT abort the
- * whole reindex on a single bad row — partial preservation is better than
- * total loss, and a transient failure on one file should not invalidate
- * the entire incremental update. The trade-off is that a silently-failed
- * row produces the same downstream effect as if the file were never
- * indexed at all (forced re-parse on the next run for current-files,
- * potential orphaned-node revival for mode_skipped). The warning surface
- * is the only signal that something went wrong. */
-static bool persist_hashes(cbm_store_t *store, const char *project, cbm_file_info_t *files,
- int file_count, const cbm_file_hash_t *mode_skipped,
- int mode_skipped_count) {
- int current_failed = 0;
- int ms_failed = 0;
-
- /* Current discovery: re-stat to capture any mtime/size that changed
- * during the run, and write fresh hash rows for visited files. */
- for (int i = 0; i < file_count; i++) {
- struct stat st;
- if (stat(files[i].path, &st) != 0) {
- current_failed++;
- continue;
- }
- int rc = cbm_store_upsert_file_hash(store, project, files[i].rel_path, "",
- stat_mtime_ns(&st), st.st_size);
- if (rc != CBM_STORE_OK) {
- cbm_log_warn("incremental.persist_hash_failed", "scope", "current", "rel_path",
- files[i].rel_path, "rc", itoa_buf(rc));
- current_failed++;
- }
- }
-
- /* Mode-skipped (preserved): re-upsert hash rows from the previous DB
- * so the next reindex can still classify these files correctly. Without
- * this, an orphaned-node bug emerges where:
- * - full mode indexes everything
- * - fast mode runs and drops mode-skipped hash rows
- * - file is then deleted on disk
- * - next reindex's stored hashes don't include the file → noop or
- * can't detect the deletion → graph nodes for the deleted file
- * remain forever (or until a destructive rebuild).
- *
- * A failure here is more serious than a current-files failure because
- * it can revive the orphaned-node bug for that specific file. Logged
- * with scope=mode_skipped so the warning is searchable. */
- if (mode_skipped) {
- for (int i = 0; i < mode_skipped_count; i++) {
- int rc =
- cbm_store_upsert_file_hash(store, project, mode_skipped[i].rel_path,
- mode_skipped[i].sha256 ? mode_skipped[i].sha256 : "",
- mode_skipped[i].mtime_ns, mode_skipped[i].size);
- if (rc != CBM_STORE_OK) {
- cbm_log_warn("incremental.persist_hash_failed", "scope", "mode_skipped", "rel_path",
- mode_skipped[i].rel_path, "rc", itoa_buf(rc));
- ms_failed++;
- }
- }
- }
-
- if (current_failed > 0 || ms_failed > 0) {
- cbm_log_warn("incremental.persist_summary", "current_failed", itoa_buf(current_failed),
- "mode_skipped_failed", itoa_buf(ms_failed));
- }
- return current_failed == 0 && ms_failed == 0;
-}
-
/* ── Registry seed visitor ────────────────────────────────────────── */
/* Labels the full-index definition pass seeds into the registry
@@ -545,8 +934,20 @@ static void registry_visitor(const cbm_gbuf_node_t *node, void *userdata) {
cbm_registry_add(r, node->name, node->qualified_name, node->label);
}
-/* Run parallel or sequential extract+resolve for changed files. */
-static void run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci) {
+static void free_incremental_result_cache(CBMFileResult **cache, int count) {
+ if (!cache) {
+ return;
+ }
+ for (int i = 0; i < count; i++) {
+ cbm_free_result(cache[i]);
+ }
+ free(cache);
+}
+
+/* Run parallel or sequential extract+resolve for changed files. Any failure
+ * aborts before persistence: the caller discards this in-memory graph and
+ * preserves the old on-disk database and its retryable hashes. */
+static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci) {
struct timespec t;
/* Per-file LSP always runs (every mode). Cross-file LSP stays disabled in
@@ -564,160 +965,222 @@ static void run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *change
_Atomic int64_t shared_ids;
atomic_init(&shared_ids, cbm_gbuf_next_id(ctx->gbuf));
- CBMFileResult **cache = (CBMFileResult **)calloc(ci, sizeof(CBMFileResult *));
- if (cache) {
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_parallel_extract(ctx, changed_files, ci, cache, &shared_ids, worker_count);
- cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
- cbm_log_info("pass.timing", "pass", "incr_extract", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_build_registry_from_cache(ctx, changed_files, ci, cache);
- cbm_log_info("pass.timing", "pass", "incr_registry", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- /* Incremental skips cross-file LSP precondition build — it
- * would need all_defs from the full project, not just the
- * changed slice. Per-file LSP (run inside cbm_extract_file)
- * still fires; cross-file resolution is deferred to the
- * next full re-index. Pass NULL/0/NULL to make the fused
- * step in resolve_worker a no-op. */
- cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_parallel_resolve(ctx, changed_files, ci, cache, &shared_ids, worker_count, NULL, 0,
- NULL, NULL /* module_def_index */,
- NULL /* cross_registries — incremental skips Tier 2 prebuild */);
- cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
- cbm_log_info("pass.timing", "pass", "incr_resolve", "elapsed_ms",
- itoa_buf((int)elapsed_ms(t)));
-
- for (int j = 0; j < ci; j++) {
- if (cache[j]) {
- cbm_free_result(cache[j]);
- }
- }
- free(cache);
+ CBMFileResult **cache;
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ if (incr_test_take_result_cache_alloc_failure()) {
+ cache = NULL;
+ } else
+#endif
+ {
+ cache = (CBMFileResult **)calloc((size_t)ci, sizeof(CBMFileResult *));
+ }
+ if (!cache) {
+ cbm_log_error("incremental.err", "phase", "result_cache_alloc");
+ return CBM_NOT_FOUND;
+ }
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ int rc = cbm_parallel_extract(ctx, changed_files, ci, cache, &shared_ids, worker_count);
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
}
+ cbm_log_info("pass.timing", "pass", "incr_extract", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+ if (rc != 0) {
+ free_incremental_result_cache(cache, ci);
+ return rc;
+ }
+ cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
+
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ rc = cbm_build_registry_from_cache(ctx, changed_files, ci, cache);
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ cbm_log_info("pass.timing", "pass", "incr_registry", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+ if (rc != 0) {
+ free_incremental_result_cache(cache, ci);
+ return rc;
+ }
+
+ /* Registry construction can materialize serial resource nodes after
+ * extraction established the workers' shared allocator. Hand the main
+ * buffer's monotonic watermark back to the workers before resolve-time
+ * synthetic nodes are created. */
+ int64_t registry_next_id = cbm_gbuf_next_id(ctx->gbuf);
+ if (registry_next_id > atomic_load(&shared_ids)) {
+ atomic_store(&shared_ids, registry_next_id);
+ }
+
+ /* Incremental skips cross-file LSP precondition build — it would need
+ * all_defs from the full project, not just the changed slice. */
+ cbm_clock_gettime(CLOCK_MONOTONIC, &t);
+ rc = cbm_parallel_resolve(ctx, changed_files, ci, cache, &shared_ids, worker_count, NULL, 0,
+ NULL, NULL /* module_def_index */,
+ NULL /* cross_registries — incremental skips Tier 2 prebuild */);
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ cbm_log_info("pass.timing", "pass", "incr_resolve", "elapsed_ms",
+ itoa_buf((int)elapsed_ms(t)));
+ cbm_gbuf_set_next_id(ctx->gbuf, atomic_load(&shared_ids));
+ free_incremental_result_cache(cache, ci);
+ return rc;
} else {
cbm_log_info("incremental.mode", "mode", "sequential", "changed", itoa_buf(ci));
- cbm_pipeline_pass_definitions(ctx, changed_files, ci);
- cbm_pipeline_pass_calls(ctx, changed_files, ci);
- cbm_pipeline_pass_usages(ctx, changed_files, ci);
- cbm_pipeline_pass_semantic(ctx, changed_files, ci);
+
+ /* Keep the definition pass's transformed/extracted result alive for
+ * the following resolution passes. This mirrors the full sequential
+ * pipeline and is required for transform-only inputs such as
+ * ObjectScript Studio Export XML, whose original source cannot be
+ * re-extracted directly by the call/usage/semantic passes. */
+ CBMFileResult **prior_cache = ctx->result_cache;
+ CBMFileResult **cache = prior_cache;
+ bool owns_cache = false;
+ if (!cache && ci > 0) {
+ cache = (CBMFileResult **)calloc((size_t)ci, sizeof(CBMFileResult *));
+ if (!cache) {
+ cbm_log_error("incremental.err", "phase", "result_cache_alloc");
+ return CBM_NOT_FOUND;
+ }
+ ctx->result_cache = cache;
+ owns_cache = true;
+ }
+ int rc = cbm_pipeline_pass_definitions(ctx, changed_files, ci);
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_pass_calls(ctx, changed_files, ci);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_pass_usages(ctx, changed_files, ci);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_pass_semantic(ctx, changed_files, ci);
+ }
+ if (rc == 0) {
+ rc = cbm_pipeline_check_cancel(ctx);
+ }
+ if (owns_cache) {
+ free_incremental_result_cache(cache, ci);
+ ctx->result_cache = prior_cache;
+ }
+ return rc;
}
}
/* Run post-extraction passes (tests, decorator tags, configlink). */
-static void run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci,
- const char *project) {
+static int run_postpasses(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed_files, int ci,
+ const char *project) {
struct timespec t;
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_tests(ctx, changed_files, ci);
+ int rc = cbm_pipeline_pass_tests(ctx, changed_files, ci);
cbm_log_info("pass.timing", "pass", "incr_tests", "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
+ if (rc != 0 || cbm_pipeline_check_cancel(ctx)) {
+ return rc != 0 ? rc : CBM_NOT_FOUND;
+ }
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_decorator_tags(ctx->gbuf, project);
+ rc = cbm_pipeline_pass_decorator_tags(ctx->gbuf, project);
cbm_log_info("pass.timing", "pass", "incr_decorator_tags", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
+ if (rc < 0 || cbm_pipeline_check_cancel(ctx)) {
+ return rc < 0 ? rc : CBM_NOT_FOUND;
+ }
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_configlink(ctx);
+ rc = cbm_pipeline_pass_configlink(ctx);
cbm_log_info("pass.timing", "pass", "incr_configlink", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
+ if (rc < 0 || cbm_pipeline_check_cancel(ctx)) {
+ return rc < 0 ? rc : CBM_NOT_FOUND;
+ }
/* SIMILAR_TO + SEMANTICALLY_RELATED edges only in moderate/full modes */
if (ctx->mode <= CBM_MODE_MODERATE) {
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_similarity(ctx);
+ rc = cbm_pipeline_pass_similarity(ctx);
cbm_log_info("pass.timing", "pass", "incr_similarity", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
+ if (rc < 0 || cbm_pipeline_check_cancel(ctx)) {
+ return rc < 0 ? rc : CBM_NOT_FOUND;
+ }
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
- cbm_pipeline_pass_semantic_edges(ctx);
+ rc = cbm_pipeline_pass_semantic_edges(ctx);
cbm_log_info("pass.timing", "pass", "incr_semantic_edges", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
+ if (rc < 0 || cbm_pipeline_check_cancel(ctx)) {
+ return rc < 0 ? rc : CBM_NOT_FOUND;
+ }
}
+ return 0;
}
-/* Delete old DB and dump merged graph + hashes to disk.
- * Mode-skipped hash rows are preserved across the rebuild so subsequent
- * reindexes can correctly distinguish "never indexed" from "indexed but
- * not visited this pass". */
-static void dump_and_persist(cbm_gbuf_t *gbuf, const char *db_path, const char *project,
- cbm_file_info_t *files, int file_count,
- const cbm_file_hash_t *mode_skipped, int mode_skipped_count,
- const char *repo_path, const cbm_coverage_row_t *cov, int cov_count,
- const cbm_coverage_meta_t *meta_template) {
+/* Publish the test-only legacy partial result through the same atomic
+ * generation boundary as full indexing. */
+static int dump_and_persist(cbm_gbuf_t *gbuf, const char *db_path, const char *project,
+ atomic_int *cancelled, const cbm_file_hash_t *manifest,
+ int manifest_count, const char *adr_content, const char *repo_path,
+ const cbm_coverage_row_t *cov, int cov_count,
+ const cbm_coverage_meta_t *meta_template) {
struct timespec t;
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
-
- cbm_unlink(db_path);
- char wal[INCR_WAL_BUF];
- char shm[INCR_WAL_BUF];
- snprintf(wal, sizeof(wal), "%s-wal", db_path);
- snprintf(shm, sizeof(shm), "%s-shm", db_path);
- cbm_unlink(wal);
- cbm_unlink(shm);
-
- int dump_rc = cbm_gbuf_dump_to_sqlite(gbuf, db_path);
- cbm_log_info("incremental.dump", "rc", itoa_buf(dump_rc), "elapsed_ms",
+ cbm_pipeline_generation_t generation = {
+ .gbuf = gbuf,
+ .final_db_path = db_path,
+ .project = project,
+ .cancelled = cancelled,
+ .manifest = manifest,
+ .manifest_count = manifest_count,
+ .adr_content = adr_content,
+ .coverage = cov,
+ .coverage_count = cov_count,
+ .coverage_meta = meta_template ? *meta_template : (cbm_coverage_meta_t){0},
+ };
+ int rc = cbm_pipeline_publish_generation(&generation);
+ cbm_log_info("incremental.dump", "rc", itoa_buf(rc), "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
-
- cbm_store_t *hash_store = cbm_store_open_path(db_path);
- if (hash_store) {
- bool hash_records_complete = persist_hashes(hash_store, project, files, file_count,
- mode_skipped, mode_skipped_count);
-
- /* Coverage rows (#963): re-write the merged set into the rebuilt DB
- * (AFTER hashes, so the deleted-file prune sees the live file set). */
- cbm_project_t project_info = {0};
- bool have_project_info =
- cbm_store_get_project(hash_store, project, &project_info) == CBM_STORE_OK;
- cbm_coverage_meta_t meta = meta_template ? *meta_template : (cbm_coverage_meta_t){0};
- meta.generation = have_project_info ? project_info.indexed_at : NULL;
- meta.hash_records_complete = hash_records_complete;
- if (cbm_store_coverage_replace_ex(hash_store, project, cov, cov_count, &meta) !=
- CBM_STORE_OK) {
- cbm_log_error("incremental.err", "msg", "persist_coverage", "project", project);
- }
- if (have_project_info) {
- cbm_project_free_fields(&project_info);
- }
-
- /* FTS5 rebuild after incremental dump. The btree dump path bypasses
- * any triggers that could have kept nodes_fts synchronized, so we
- * rebuild from the nodes table here. See the full-dump path in
- * pipeline.c for the matching logic. */
- cbm_store_exec(hash_store, "INSERT INTO nodes_fts(nodes_fts) VALUES('delete-all');");
- if (cbm_store_exec(hash_store,
- "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
- "SELECT id, cbm_camel_split(name), qualified_name, label, file_path "
- "FROM nodes;") != CBM_STORE_OK) {
- cbm_store_exec(hash_store,
- "INSERT INTO nodes_fts(rowid, name, qualified_name, label, file_path) "
- "SELECT id, name, qualified_name, label, file_path FROM nodes;");
- }
-
- cbm_store_close(hash_store);
+ if (rc != 0) {
+ return rc;
}
/* Auto-update artifact if one already exists (persistence was enabled previously) */
if (repo_path && cbm_artifact_exists(repo_path)) {
cbm_artifact_export(db_path, repo_path, project, CBM_ARTIFACT_FAST);
}
+ return 0;
}
/* ── Incremental pipeline entry point ────────────────────────────── */
int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_file_info_t *files,
- int file_count) {
+ int file_count, const cbm_file_hash_t *baseline_manifest,
+ int baseline_count) {
struct timespec t0;
cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
const char *project = cbm_pipeline_project_name(p);
- /* Open existing disk DB */
- cbm_store_t *store = cbm_store_open_path(db_path);
+ bool force_legacy_partial = false;
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ force_legacy_partial = incr_test_take_force_legacy_partial();
+ incr_test_set_last_route(CBM_INCREMENTAL_ROUTE_NONE);
+#endif
+
+ /* Exact semantic-manifest routing is read-only. Do not reopen a sealed
+ * generation in WAL mode merely to prove that it is already current.
+ * The legacy partial test route still needs a writable connection. */
+ cbm_store_t *store =
+ force_legacy_partial ? cbm_store_open_path(db_path) : cbm_store_open_path_query(db_path);
if (!store) {
cbm_log_error("incremental.err", "msg", "open_db_failed", "path", db_path);
return CBM_NOT_FOUND;
@@ -726,7 +1189,43 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
/* Load stored file hashes */
cbm_file_hash_t *stored = NULL;
int stored_count = 0;
- cbm_store_get_file_hashes(store, project, &stored, &stored_count);
+ if (cbm_store_get_file_hashes(store, project, &stored, &stored_count) != CBM_STORE_OK) {
+ cbm_log_error("incremental.err", "msg", "manifest_read_failed", "project", project);
+ cbm_store_close(store);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ /* Production incremental routing is deliberately binary: an exact
+ * semantic-manifest match is a no-op; any byte/set/mode/migration delta
+ * rebuilds the complete graph. This avoids partial LSP/package/config
+ * convergence gaps while retaining the common unchanged-repo fast path. */
+ if (!force_legacy_partial) {
+ cbm_coverage_meta_t meta = {0};
+ int meta_rc = cbm_store_coverage_meta_get(store, project, &meta);
+ const char *mode_name = incr_mode_name(cbm_pipeline_get_mode(p));
+ bool metadata_current = meta_rc == CBM_STORE_OK &&
+ meta.coverage_version == CBM_SEMANTIC_INDEX_VERSION &&
+ meta.hash_records_complete && meta.index_mode &&
+ strcmp(meta.index_mode, mode_name) == 0;
+ bool exact = metadata_current &&
+ cbm_pipeline_semantic_manifests_equal(stored, stored_count, baseline_manifest,
+ baseline_count);
+ cbm_store_coverage_meta_clear(&meta);
+ cbm_store_free_file_hashes(stored, stored_count);
+ cbm_store_close(store);
+ if (exact) {
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ incr_test_set_last_route(CBM_INCREMENTAL_ROUTE_NOOP);
+#endif
+ cbm_log_info("incremental.noop", "reason", "semantic_manifest_equal");
+ return cbm_pipeline_refresh_artifact(p, db_path);
+ }
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ incr_test_set_last_route(CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+#endif
+ cbm_log_info("incremental.force_full", "reason", "semantic_manifest_changed");
+ return CBM_PIPELINE_FORCE_FULL_REINDEX;
+ }
/* Classify files */
int n_changed = 0;
@@ -751,6 +1250,9 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
* which means existing hash rows (including for any mode-skipped files
* that were already preserved by an earlier run) remain intact. */
if (n_changed == 0 && deleted_count == 0) {
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ incr_test_set_last_route(CBM_INCREMENTAL_ROUTE_NOOP);
+#endif
cbm_log_info("incremental.noop", "reason", "no_changes");
free(is_changed);
free(deleted);
@@ -760,6 +1262,10 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
return 0;
}
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ incr_test_set_last_route(CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+#endif
+
cbm_store_free_file_hashes(stored, stored_count);
/* Coverage rows (#963): the dump below rebuilds the DB file, wiping the
@@ -818,6 +1324,41 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
return CBM_NOT_FOUND;
}
+ char *saved_adr = NULL;
+ cbm_adr_t existing_adr = {0};
+ int adr_rc = cbm_store_adr_get(store, project, &existing_adr);
+ if (adr_rc == CBM_STORE_OK) {
+ bool had_adr_content = existing_adr.content != NULL;
+ if (had_adr_content) {
+ saved_adr = strdup(existing_adr.content);
+ }
+ cbm_store_adr_free(&existing_adr);
+ if (had_adr_content && !saved_adr) {
+ cbm_gbuf_free(existing);
+ free(changed_files);
+ for (int i = 0; i < deleted_count; i++) {
+ free(deleted[i]);
+ }
+ free(deleted);
+ free_mode_skipped(mode_skipped, mode_skipped_count);
+ cbm_store_free_coverage(old_cov, old_cov_count);
+ cbm_store_close(store);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+ } else if (adr_rc != CBM_STORE_NOT_FOUND) {
+ cbm_store_adr_free(&existing_adr);
+ cbm_gbuf_free(existing);
+ free(changed_files);
+ for (int i = 0; i < deleted_count; i++) {
+ free(deleted[i]);
+ }
+ free(deleted);
+ free_mode_skipped(mode_skipped, mode_skipped_count);
+ cbm_store_free_coverage(old_cov, old_cov_count);
+ cbm_store_close(store);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
cbm_store_close(store);
/* Snapshot inbound cross-file edges into changed files BEFORE purging, so
@@ -900,9 +1441,16 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
}
}
- run_extract_resolve(&ctx, changed_files, ci);
- cbm_pipeline_pass_k8s(&ctx, changed_files, ci);
- run_postpasses(&ctx, changed_files, ci, project);
+ int phase_rc = run_extract_resolve(&ctx, changed_files, ci);
+ if (phase_rc == 0) {
+ phase_rc = cbm_pipeline_pass_k8s(&ctx, changed_files, ci);
+ }
+ if (phase_rc == 0) {
+ phase_rc = cbm_pipeline_check_cancel(&ctx);
+ }
+ if (phase_rc == 0) {
+ phase_rc = run_postpasses(&ctx, changed_files, ci, project);
+ }
/* Free ObjectScript tables built by pass_calls during run_extract_resolve. */
if (ctx.return_type_table) {
@@ -917,6 +1465,24 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
ctx.macro_table = NULL;
}
+ /* Parallel extraction builds the process-global package map. Match the
+ * full pipeline's ownership boundary on both success and failure. */
+ cbm_pkgmap_free(cbm_pipeline_get_pkgmap());
+ cbm_pipeline_set_pkgmap(NULL);
+
+ if (phase_rc != 0) {
+ cbm_log_error("incremental.err", "phase", "extract_resolve", "rc", itoa_buf(phase_rc));
+ free(changed_files);
+ cbm_registry_free(registry);
+ cbm_path_alias_collection_free(path_aliases);
+ incr_free_edge_capture(&edge_cap);
+ cbm_store_free_coverage(old_cov, old_cov_count);
+ free_mode_skipped(mode_skipped, mode_skipped_count);
+ free(saved_adr);
+ cbm_gbuf_free(existing);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
/* Coverage rows (#963): merge = previous FAILURE rows for files NOT
* re-extracted this run + this run's fresh entries (changed files replace
* their old rows — a file that parses cleanly now simply contributes
@@ -990,10 +1556,26 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
itoa_buf(edge_cap.count), "elapsed_ms", itoa_buf((int)elapsed_ms(t)));
incr_free_edge_capture(&edge_cap);
- /* Step 7: Dump to disk (preserves mode-skipped hash rows so the next
- * reindex can correctly classify those files instead of seeing them
- * as never-existed; also exports a fast-mode artifact when one is
- * already present alongside the repo). */
+ cbm_file_hash_t *manifest = NULL;
+ int manifest_count = 0;
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ cbm_pipeline_persist_test_run_before_final_manifest();
+#endif
+ int manifest_rc = cbm_pipeline_build_fresh_semantic_manifest(
+ project, cbm_pipeline_repo_path(p), cbm_pipeline_get_mode(p), &manifest, &manifest_count);
+ if (manifest_rc != 0 || !cbm_pipeline_semantic_manifests_equal(
+ baseline_manifest, baseline_count, manifest, manifest_count)) {
+ cbm_log_warn("incremental.abort", "reason", "semantic_inputs_changed");
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count);
+ free(cov);
+ cbm_store_free_coverage(old_cov, old_cov_count);
+ free_mode_skipped(mode_skipped, mode_skipped_count);
+ free(saved_adr);
+ cbm_gbuf_free(existing);
+ return CBM_PIPELINE_ABORT_PRESERVE_DB;
+ }
+
+ /* Step 7: atomically publish the complete staged generation. */
/* Record committed counts before dump_and_persist (whose dump frees the
* gbuf node index, zeroing the count) so the #334 plausibility gate also
* covers incremental reindexes, not just full ones. */
@@ -1008,15 +1590,19 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
: (run_ignored_total > run_ignored_count ? "truncated" : "complete"),
.ignored_files_stored = run_ignored_count,
.ignored_files_total = run_ignored_total,
- .coverage_version = 1,
+ .coverage_version = CBM_SEMANTIC_INDEX_VERSION,
+ .hash_records_complete = true,
};
- dump_and_persist(existing, db_path, project, files, file_count, mode_skipped,
- mode_skipped_count, cbm_pipeline_repo_path(p), cov, cov_n, &coverage_meta);
+ int persist_rc = dump_and_persist(existing, db_path, project, cbm_pipeline_cancelled_ptr(p),
+ manifest, manifest_count, saved_adr,
+ cbm_pipeline_repo_path(p), cov, cov_n, &coverage_meta);
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count);
+ free(saved_adr);
free(cov);
cbm_store_free_coverage(old_cov, old_cov_count);
free_mode_skipped(mode_skipped, mode_skipped_count);
cbm_gbuf_free(existing);
cbm_log_info("incremental.done", "elapsed_ms", itoa_buf((int)elapsed_ms(t0)));
- return 0;
+ return persist_rc;
}
diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h
index d2180a47a..9ed45e8d3 100644
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@ -11,7 +11,10 @@
#include "pipeline/pipeline.h"
#include "pipeline/path_alias.h"
#include "graph_buffer/graph_buffer.h"
+#include "store/store.h"
#include "discover/discover.h"
+#include "discover/userconfig.h"
+#include "git/git_context.h"
#include "foundation/hash_table.h"
#include "cbm.h"
#include "lsp/go_lsp.h" /* CBMLSPDef for cbm_parallel_resolve cross-LSP inputs */
@@ -30,6 +33,8 @@
* Distinct from CBM_NOT_FOUND, which the orchestrator uses as the normal
* "no incremental route; continue with a full index" sentinel. */
#define CBM_PIPELINE_ABORT_PRESERVE_DB (-2)
+#define CBM_PIPELINE_FORCE_FULL_REINDEX (-3)
+#define CBM_PIPELINE_PERSIST_FAILED (-4)
/* Canonicalize route-path parameter placeholders (":id", "{id}", "<id>",
* "${...}") to a single "{}" token so that client call sites and server
@@ -125,6 +130,18 @@ typedef struct {
const CBMReturnTypeTable *return_type_table;
} cbm_pipeline_ctx_t;
+/* Transcode an ObjectScript Studio Export XML file and compose every generated
+ * UDL class into one cacheable result. The returned result owns all child
+ * extraction arenas and is released with the ordinary cbm_free_result(). */
+CBMFileResult *cbm_pipeline_extract_objectscript_export(
+ const char *source, int source_len, const char *project_name, const char *rel_path,
+ const CBMMacroTable *macro_table, const CBMReturnTypeTable *return_type_table);
+
+/* Materialize CONFIGURES edges from one extracted file's env-access carriers.
+ * Shared by sequential definition processing and the parallel cache registry. */
+int cbm_pipeline_create_env_configures_for_file(cbm_pipeline_ctx_t *ctx,
+ const CBMFileResult *result, const char *rel);
+
static inline int cbm_pipeline_relpath_is_excluded(const char *rel_path, char *const *excluded_dirs,
int excluded_count) {
if (!rel_path || rel_path[0] == '\0' || !excluded_dirs || excluded_count <= 0) {
@@ -622,7 +639,56 @@ int cbm_scan_project_env_urls_excluded(const char *root_path, cbm_env_binding_t
* Classifies files by mtime+size, deletes changed nodes, re-parses changed
* files, merges into disk DB. Returns 0 on success. */
int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_file_info_t *files,
- int file_count);
+ int file_count, const cbm_file_hash_t *baseline_manifest,
+ int baseline_count);
+
+/* Exact semantic inputs for no-op/forced-full routing. The manifest contains
+ * every discovered source plus repository controls actually consumed by
+ * discovery, package mapping, path aliases, and extension overrides. */
+#define CBM_SEMANTIC_INPUT_PREFIX ".codebase-memory/.semantic-input/"
+#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"
+
+int cbm_pipeline_build_semantic_manifest(const char *project, const char *repo_path,
+ const cbm_file_info_t *files, int file_count,
+ char **excluded_dirs, int excluded_count,
+ const cbm_git_context_t *git_ctx,
+ const cbm_userconfig_t *userconfig, cbm_file_hash_t **out,
+ int *out_count);
+void cbm_pipeline_free_semantic_manifest(cbm_file_hash_t *manifest, int count);
+bool cbm_pipeline_semantic_manifests_equal(const cbm_file_hash_t *left, int left_count,
+ const cbm_file_hash_t *right, int right_count);
+/* Re-run discovery and hash its exact semantic inputs. Used at the publication
+ * boundary so late additions/deletions cannot escape a frozen file list. */
+int cbm_pipeline_build_fresh_semantic_manifest(const char *project, const char *repo_path, int mode,
+ cbm_file_hash_t **out, int *out_count);
+
+/* Compatibility contract persisted in coverage metadata. Increment when a
+ * graph/manifest semantic change makes prior exact-input indexes unsafe. */
+enum { CBM_SEMANTIC_INDEX_VERSION = 3 };
+
+typedef struct {
+ cbm_gbuf_t *gbuf;
+ const char *final_db_path;
+ const char *project;
+ atomic_int *cancelled;
+ const cbm_file_hash_t *manifest;
+ int manifest_count;
+ const char *adr_content;
+ const cbm_coverage_row_t *coverage;
+ int coverage_count;
+ cbm_coverage_meta_t coverage_meta;
+} cbm_pipeline_generation_t;
+
+/* Serialize and fully populate a sibling staging database, then atomically
+ * replace final_db_path. The old generation is untouched on every failure or
+ * cancellation observed before the rename commit point. */
+int cbm_pipeline_publish_generation(const cbm_pipeline_generation_t *generation);
+/* The SQLite generation is authoritative. An explicitly requested artifact is
+ * part of the caller-visible operation and its export error is returned;
+ * automatic refresh of an already-existing artifact remains best-effort. */
+int cbm_pipeline_refresh_artifact(cbm_pipeline_t *p, const char *db_path);
/* Pipeline accessors for incremental use */
const char *cbm_pipeline_repo_path(const cbm_pipeline_t *p);
@@ -645,4 +711,48 @@ bool extract_grpc_service_method(const char *callee, char *service, size_t srv_s
long cbm_pp_bp_nap_cycles(void);
void cbm_pp_bp_nap_cycles_reset(void);
+/* Number of resolved-call rows handed to the parallel resolver's linear LSP
+ * fallback since the last reset. Test observability for occurrence-index
+ * 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);
+
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+/* Deterministic test-only operation count for the shared semantic-reference
+ * matcher used by both sequential and fused-parallel usage materialization. */
+void cbm_pipeline_lsp_reference_lookup_test_reset(void);
+uint64_t cbm_pipeline_lsp_reference_lookup_test_rows_examined(void);
+#endif
+
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+typedef enum {
+ CBM_INCREMENTAL_ROUTE_NONE = 0,
+ CBM_INCREMENTAL_ROUTE_NOOP,
+ CBM_INCREMENTAL_ROUTE_FORCED_FULL,
+ CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL,
+} cbm_incremental_route_t;
+
+/* Deterministic one-shot fault injection for the incremental-parallel result
+ * cache allocation. Reset explicitly so one test cannot affect another. */
+void cbm_pipeline_incremental_test_fail_result_cache_alloc_once(void);
+void cbm_pipeline_incremental_test_force_legacy_partial_once(void);
+void cbm_pipeline_incremental_test_fail_after_stage_dump_once(void);
+void cbm_pipeline_incremental_test_cancel_after_predump_once(void);
+void cbm_pipeline_incremental_test_cancel_after_destination_prepare_once(void);
+void cbm_pipeline_incremental_test_fail_adr_capture_once(void);
+typedef void (*cbm_pipeline_test_hook_fn)(void *userdata);
+void cbm_pipeline_incremental_test_before_final_manifest_once(cbm_pipeline_test_hook_fn hook,
+ void *userdata);
+cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void);
+void cbm_pipeline_incremental_test_reset_faults(void);
+
+/* Shared persistence-hook plumbing. Tests use the incremental facade above so
+ * one reset covers route, extraction, and publication faults. */
+bool cbm_pipeline_persist_test_take_failure_after_stage_dump(void);
+bool cbm_pipeline_persist_test_take_cancel_after_predump(void);
+bool cbm_pipeline_persist_test_take_cancel_after_destination_prepare(void);
+void cbm_pipeline_persist_test_run_before_final_manifest(void);
+void cbm_pipeline_persist_test_reset_faults(void);
+#endif
+
#endif /* CBM_PIPELINE_INTERNAL_H */
diff --git a/src/store/store.c b/src/store/store.c
index 7b966051a..e8bc58822 100644
--- a/src/store/store.c
+++ b/src/store/store.c
@@ -437,15 +437,17 @@ static int configure_pragmas(cbm_store_t *s, bool in_memory, bool read_only) {
return rc;
}
/* #1083: bound the WAL file so a checkpoint-starved log is physically
- * reclaimed the next time a checkpoint can reset it. Our checkpoints are
- * all PASSIVE (they never ftruncate — see cbm_store_checkpoint's SIGBUS
- * note), so without a size limit the -wal file only ever grows; a
- * journal_size_limit truncates it back to N bytes on the next successful
+ * reclaimed the next time a checkpoint can reset it. Shared/live
+ * checkpoints are PASSIVE (they never ftruncate — see
+ * cbm_store_checkpoint's SIGBUS note), so without a size limit the -wal
+ * file only ever grows; journal_size_limit truncates it back to N bytes
+ * on the next successful
* reset. N is far above the healthy WAL (~4 MiB under the default
* 1000-page autocheckpoint), so normal indexing never triggers
- * truncate/regrow churn — it only fires after abnormal growth. We do NOT
- * use a TRUNCATE checkpoint: its ftruncate(fd,0) can raise SIGBUS in a
- * sibling process that has the DB mmap'd on macOS. */
+ * truncate/regrow churn — it only fires after abnormal growth.
+ * Shared/live paths do NOT use a TRUNCATE checkpoint: truncating the WAL
+ * to zero can raise SIGBUS in a sibling process that has the DB mmap'd
+ * on macOS. Exclusive staging publication seals separately below. */
rc = exec_sql(s, "PRAGMA journal_size_limit = 268435456;"); /* 256 MiB */
if (rc != CBM_STORE_OK) {
return rc;
@@ -1135,6 +1137,118 @@ int64_t cbm_store_journal_size_limit(cbm_store_t *s) {
return limit;
}
+int cbm_store_seal_for_atomic_publish(cbm_store_t *s) {
+ if (!s || !s->db) {
+ return CBM_STORE_ERR;
+ }
+
+ /* Bulk indexing deliberately relaxes synchronous writes. Restore the
+ * strongest durability before copying WAL pages into the database file.
+ * This staging connection is exclusively owned by the publisher. */
+ if (exec_sql(s, "PRAGMA synchronous = FULL;") != CBM_STORE_OK) {
+ return CBM_STORE_ERR;
+ }
+
+ int log_frames = 0;
+ int checkpointed_frames = 0;
+ int rc = sqlite3_wal_checkpoint_v2(s->db, NULL, SQLITE_CHECKPOINT_TRUNCATE, &log_frames,
+ &checkpointed_frames);
+ if (rc != SQLITE_OK) {
+ snprintf(s->errbuf, sizeof(s->errbuf), "seal checkpoint: %s (log=%d checkpointed=%d)",
+ sqlite3_errstr(rc), log_frames, checkpointed_frames);
+ return CBM_STORE_ERR;
+ }
+
+ /* PRAGMA journal_mode returns the mode SQLite actually entered. sqlite3_exec
+ * would discard that result and could falsely report a successful seal. */
+ sqlite3_stmt *stmt = NULL;
+ rc = sqlite3_prepare_v2(s->db, "PRAGMA journal_mode = DELETE;", CBM_NOT_FOUND, &stmt, NULL);
+ if (rc != SQLITE_OK) {
+ store_set_error_sqlite(s, "seal journal_mode prepare");
+ return CBM_STORE_ERR;
+ }
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_ROW) {
+ store_set_error_sqlite(s, "seal journal_mode step");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ const char *mode = (const char *)sqlite3_column_text(stmt, 0);
+ bool is_delete = mode && sqlite3_stricmp(mode, "delete") == 0;
+
+ rc = sqlite3_step(stmt);
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "seal journal_mode completion");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ rc = sqlite3_finalize(stmt);
+ if (rc != SQLITE_OK) {
+ store_set_error_sqlite(s, "seal journal_mode finalize");
+ return CBM_STORE_ERR;
+ }
+ if (!is_delete) {
+ store_set_error(s, "seal journal_mode did not enter delete mode");
+ return CBM_STORE_ERR;
+ }
+
+ return CBM_STORE_OK;
+}
+
+int cbm_store_seal_existing_path_for_replace(const char *db_path) {
+ if (!db_path || !db_path[0]) {
+ return CBM_STORE_ERR;
+ }
+
+ cbm_store_t maintenance = {0};
+ int rc = sqlite3_open_v2(db_path, &maintenance.db, SQLITE_OPEN_READWRITE, NULL);
+ if (rc != SQLITE_OK) {
+ int primary = rc & 0xff;
+ sqlite3_close(maintenance.db);
+ return primary == SQLITE_CORRUPT || primary == SQLITE_NOTADB || primary == SQLITE_FORMAT
+ ? CBM_STORE_NOT_FOUND
+ : CBM_STORE_ERR;
+ }
+ (void)sqlite3_busy_timeout(maintenance.db, 10000);
+
+ sqlite3_stmt *stmt = NULL;
+ rc = sqlite3_prepare_v2(maintenance.db, "PRAGMA quick_check(1);", CBM_NOT_FOUND, &stmt, NULL);
+ if (rc != SQLITE_OK) {
+ int primary = rc & 0xff;
+ sqlite3_close(maintenance.db);
+ return primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_READONLY ||
+ primary == SQLITE_CANTOPEN || primary == SQLITE_IOERR
+ ? CBM_STORE_ERR
+ : CBM_STORE_NOT_FOUND;
+ }
+ rc = sqlite3_step(stmt);
+ const char *result = rc == SQLITE_ROW ? (const char *)sqlite3_column_text(stmt, 0) : NULL;
+ bool structurally_valid = result && strcmp(result, "ok") == 0;
+ int finalize_rc = sqlite3_finalize(stmt);
+ if (!structurally_valid || finalize_rc != SQLITE_OK) {
+ int primary = rc & 0xff;
+ sqlite3_close(maintenance.db);
+ return primary == SQLITE_BUSY || primary == SQLITE_LOCKED || primary == SQLITE_READONLY ||
+ primary == SQLITE_CANTOPEN || primary == SQLITE_IOERR
+ ? CBM_STORE_ERR
+ : CBM_STORE_NOT_FOUND;
+ }
+
+ /* A structurally valid SQLite file that is not recognizably a codebase
+ * graph is incompatible at this destination and must be preserved before
+ * replacement. Legacy graph schemas still pass this shallow identity
+ * check and can be sealed without running init_schema(). */
+ if (!cbm_store_check_integrity(&maintenance)) {
+ sqlite3_close(maintenance.db);
+ return CBM_STORE_NOT_FOUND;
+ }
+
+ int seal_rc = cbm_store_seal_for_atomic_publish(&maintenance);
+ sqlite3_close(maintenance.db);
+ return seal_rc;
+}
+
/* ── Dump ───────────────────────────────────────────────────────── */
/* Dump entire in-memory database to a file via sqlite3_backup.
@@ -1288,8 +1402,15 @@ int cbm_store_get_project(cbm_store_t *s, const char *name, cbm_project_t *out)
out->name = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
out->indexed_at = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
out->root_path = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
+ /* Cached SELECT statements must not remain parked on SQLITE_ROW.
+ * Besides retaining a read transaction, an active reader prevents
+ * publication from switching a fully-written staging database out of
+ * WAL mode before the atomic rename. All result text is owned by the
+ * caller at this point, so release the reader immediately. */
+ sqlite3_reset(stmt);
return CBM_STORE_OK;
}
+ sqlite3_reset(stmt);
return CBM_STORE_NOT_FOUND;
}
@@ -1438,8 +1559,10 @@ int cbm_store_find_node_by_id(cbm_store_t *s, int64_t id, cbm_node_t *out) {
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
+ sqlite3_reset(stmt);
return CBM_STORE_OK;
}
+ sqlite3_reset(stmt);
return CBM_STORE_NOT_FOUND;
}
@@ -1462,8 +1585,10 @@ int cbm_store_find_node_by_qn(cbm_store_t *s, const char *project, const char *q
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
+ sqlite3_reset(stmt);
return CBM_STORE_OK;
}
+ sqlite3_reset(stmt);
return CBM_STORE_NOT_FOUND;
}
@@ -1484,8 +1609,10 @@ int cbm_store_find_node_by_qn_any(cbm_store_t *s, const char *qn, cbm_node_t *ou
int rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
scan_node(stmt, out);
+ sqlite3_reset(stmt);
return CBM_STORE_OK;
}
+ sqlite3_reset(stmt);
return CBM_STORE_NOT_FOUND;
}
@@ -1654,10 +1781,12 @@ int cbm_store_count_nodes(cbm_store_t *s, const char *project) {
}
bind_text(stmt, SKIP_ONE, project);
+ int count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
- return sqlite3_column_int(stmt, 0);
+ count = sqlite3_column_int(stmt, 0);
}
- return 0;
+ sqlite3_reset(stmt);
+ return count;
}
int cbm_store_delete_nodes_by_project(cbm_store_t *s, const char *project) {
@@ -1972,10 +2101,12 @@ int cbm_store_count_edges(cbm_store_t *s, const char *project) {
}
bind_text(stmt, SKIP_ONE, project);
+ int count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
- return sqlite3_column_int(stmt, 0);
+ count = sqlite3_column_int(stmt, 0);
}
- return 0;
+ sqlite3_reset(stmt);
+ return count;
}
int cbm_store_count_edges_by_type(cbm_store_t *s, const char *project, const char *type) {
@@ -1988,10 +2119,12 @@ int cbm_store_count_edges_by_type(cbm_store_t *s, const char *project, const cha
bind_text(stmt, SKIP_ONE, project);
bind_text(stmt, ST_COL_2, type);
+ int count = 0;
if (sqlite3_step(stmt) == SQLITE_ROW) {
- return sqlite3_column_int(stmt, 0);
+ count = sqlite3_column_int(stmt, 0);
}
- return 0;
+ sqlite3_reset(stmt);
+ return count;
}
int cbm_store_delete_edges_by_project(cbm_store_t *s, const char *project) {
@@ -3552,9 +3685,11 @@ int cbm_store_search(cbm_store_t *s, const cbm_search_params_t *params, cbm_sear
const char *select_cols = "SELECT n.id, n.project, n.label, n.name, n.qualified_name, "
"n.file_path, n.start_line, n.end_line, n.properties, "
"(SELECT COUNT(*) FROM edges e WHERE e.target_id = n.id AND "
- "e.type IN ('CALLS', 'USAGE', 'INHERITS', 'IMPLEMENTS')) AS in_deg, "
+ "e.type IN ('CALLS', 'USAGE', 'CALL_REFERENCE', 'INHERITS', "
+ "'IMPLEMENTS')) AS in_deg, "
"(SELECT COUNT(*) FROM edges e WHERE e.source_id = n.id AND "
- "e.type IN ('CALLS', 'USAGE', 'INHERITS', 'IMPLEMENTS')) AS out_deg ";
+ "e.type IN ('CALLS', 'USAGE', 'CALL_REFERENCE', 'INHERITS', "
+ "'IMPLEMENTS')) AS out_deg ";
char where[CBM_SZ_2K] = "";
search_bind_t binds[ST_SEARCH_MAX_BINDS];
@@ -7174,6 +7309,33 @@ int cbm_store_adr_store(cbm_store_t *s, const char *project, const char *content
}
int cbm_store_adr_get(cbm_store_t *s, const char *project, cbm_adr_t *out) {
+ if (!s || !s->db || !project || !out) {
+ return CBM_STORE_ERR;
+ }
+ memset(out, 0, sizeof(*out));
+
+ /* ADR storage was added after the original graph schema. A readable
+ * legacy generation without project_summaries has no ADR to preserve; it
+ * is not a read failure and must remain replaceable by a full reindex. */
+ sqlite3_stmt *table_stmt = NULL;
+ int rc = sqlite3_prepare_v2(
+ s->db,
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='project_summaries' LIMIT 1;",
+ CBM_NOT_FOUND, &table_stmt, NULL);
+ if (rc != SQLITE_OK) {
+ store_set_error_sqlite(s, "adr_get table probe");
+ return CBM_STORE_ERR;
+ }
+ rc = sqlite3_step(table_stmt);
+ if (rc == SQLITE_DONE) {
+ sqlite3_finalize(table_stmt);
+ return CBM_STORE_NOT_FOUND;
+ }
+ if (rc != SQLITE_ROW || sqlite3_finalize(table_stmt) != SQLITE_OK) {
+ store_set_error_sqlite(s, "adr_get table probe step");
+ return CBM_STORE_ERR;
+ }
+
const char *sql = "SELECT project, summary, created_at, updated_at FROM project_summaries "
"WHERE project=?1";
sqlite3_stmt *stmt = NULL;
@@ -7181,18 +7343,42 @@ int cbm_store_adr_get(cbm_store_t *s, const char *project, cbm_adr_t *out) {
store_set_error_sqlite(s, "adr_get");
return CBM_STORE_ERR;
}
- bind_text(stmt, SKIP_ONE, project);
- int rc = sqlite3_step(stmt);
+ if (bind_text(stmt, SKIP_ONE, project) != SQLITE_OK) {
+ store_set_error_sqlite(s, "adr_get bind");
+ sqlite3_finalize(stmt);
+ return CBM_STORE_ERR;
+ }
+ rc = sqlite3_step(stmt);
if (rc != SQLITE_ROW) {
+ if (rc != SQLITE_DONE) {
+ store_set_error_sqlite(s, "adr_get step");
+ }
sqlite3_finalize(stmt);
- store_set_error(s, "no ADR found");
- return CBM_STORE_NOT_FOUND;
+ if (rc == SQLITE_DONE) {
+ store_set_error(s, "no ADR found");
+ return CBM_STORE_NOT_FOUND;
+ }
+ return CBM_STORE_ERR;
}
out->project = heap_strdup((const char *)sqlite3_column_text(stmt, 0));
out->content = heap_strdup((const char *)sqlite3_column_text(stmt, SKIP_ONE));
out->created_at = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_2));
out->updated_at = heap_strdup((const char *)sqlite3_column_text(stmt, CBM_SZ_3));
- sqlite3_finalize(stmt);
+ rc = sqlite3_finalize(stmt);
+ if (rc != SQLITE_OK) {
+ cbm_store_adr_free(out);
+ store_set_error_sqlite(s, "adr_get finalize");
+ return CBM_STORE_ERR;
+ }
+
+ /* Every selected column is NOT NULL in the schema. A NULL here therefore
+ * means either allocation failure or corrupt data; never return a partial
+ * ADR that a full rebuild could silently drop during publication. */
+ if (!out->project || !out->content || !out->created_at || !out->updated_at) {
+ cbm_store_adr_free(out);
+ store_set_error(s, "adr_get: failed to copy complete ADR");
+ return CBM_STORE_ERR;
+ }
return CBM_STORE_OK;
}
diff --git a/src/store/store.h b/src/store/store.h
index 373440474..bc4d1fd10 100644
--- a/src/store/store.h
+++ b/src/store/store.h
@@ -207,6 +207,12 @@ cbm_store_t *cbm_store_open_path(const char *db_path);
* exist — never creates a new .db file. */
cbm_store_t *cbm_store_open_path_query(const char *db_path);
+/* Validate and seal an existing DB for atomic replacement without creating or
+ * migrating its schema. Returns OK when sealed, NOT_FOUND when the bytes are
+ * definitely corrupt/incompatible and should be quarantined, or ERR when the
+ * file is busy/unavailable and must be left in place. */
+int cbm_store_seal_existing_path_for_replace(const char *db_path);
+
/* On-disk path of a file-backed store, or NULL for an in-memory (:memory:)
* store. The returned pointer is owned by the store. */
const char *cbm_store_db_path(const cbm_store_t *s);
@@ -271,6 +277,14 @@ int64_t cbm_store_journal_size_limit(cbm_store_t *s);
* bumps on every index run. "legacy" for DBs predating store_meta. */
int cbm_store_generation(cbm_store_t *s, char *buf, size_t bufsz);
+/* Seal a fully-written staging database before atomic publication.
+ * Raises synchronous to FULL, requires an exclusive TRUNCATE checkpoint to
+ * complete, then leaves the database in verified DELETE journal mode so the
+ * main file is self-contained (no required -wal/-shm sidecars). This is a
+ * fail-closed operation: SQLITE_BUSY and an unconfirmed mode transition are
+ * errors. The caller must own the staging database exclusively. */
+int cbm_store_seal_for_atomic_publish(cbm_store_t *s);
+
/* Resolve the mmap_size pragma value applied to on-disk stores from the
* CBM_SQLITE_MMAP_SIZE environment variable. Defaults to 67108864 (64 MB)
* when the variable is unset, malformed, or partially numeric. Negative
diff --git a/src/ui/layout3d.c b/src/ui/layout3d.c
index 327f8e48b..3176da2ff 100644
--- a/src/ui/layout3d.c
+++ b/src/ui/layout3d.c
@@ -650,16 +650,24 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
int64_t *node_ids = malloc((size_t)n * sizeof(int64_t));
int *in_calls = calloc((size_t)n, sizeof(int));
int *in_usage = calloc((size_t)n, sizeof(int));
+ int *in_call_reference = calloc((size_t)n, sizeof(int));
int *deg_dummy = calloc((size_t)n, sizeof(int));
- if (node_ids && in_calls && in_usage && deg_dummy) {
+ bool dead_degrees_valid = node_ids && in_calls && in_usage && in_call_reference && deg_dummy;
+ if (dead_degrees_valid) {
for (int i = 0; i < n; i++)
node_ids[i] = search_out.results[i].node.id;
for (int off = 0; off < n; off += DEAD_DEGREE_CHUNK) {
int cnt = (n - off < DEAD_DEGREE_CHUNK) ? (n - off) : DEAD_DEGREE_CHUNK;
- cbm_store_batch_count_degrees(store, node_ids + off, cnt, "CALLS", in_calls + off,
- deg_dummy + off);
- cbm_store_batch_count_degrees(store, node_ids + off, cnt, "USAGE", in_usage + off,
- deg_dummy + off);
+ if (cbm_store_batch_count_degrees(store, node_ids + off, cnt, "CALLS", in_calls + off,
+ deg_dummy + off) != CBM_STORE_OK ||
+ cbm_store_batch_count_degrees(store, node_ids + off, cnt, "USAGE", in_usage + off,
+ deg_dummy + off) != CBM_STORE_OK ||
+ cbm_store_batch_count_degrees(store, node_ids + off, cnt, "CALL_REFERENCE",
+ in_call_reference + off,
+ deg_dummy + off) != CBM_STORE_OK) {
+ dead_degrees_valid = false;
+ break;
+ }
}
}
@@ -720,8 +728,8 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
bool is_fn =
sn->label && (strcmp(sn->label, "Function") == 0 || strcmp(sn->label, "Method") == 0);
bool testish = nf.is_test || (sn->file_path && cbm_is_test_file_path(sn->file_path));
- int ic = in_calls ? in_calls[i] : 1;
- int iu = in_usage ? in_usage[i] : 1;
+ int ic = dead_degrees_valid ? in_calls[i] : 1;
+ int iu = dead_degrees_valid ? in_usage[i] + in_call_reference[i] : 1;
const char *status;
if (!is_fn)
status = "structural";
@@ -770,6 +778,7 @@ cbm_layout_result_t *cbm_layout_compute(cbm_store_t *store, const char *project,
free(node_ids);
free(in_calls);
free(in_usage);
+ free(in_call_reference);
free(deg_dummy);
free_edge_array(all_edges, mapped);
cbm_store_search_free(&search_out);
diff --git a/tests/repro/repro_call_argument_matrix_a.c b/tests/repro/repro_call_argument_matrix_a.c
new file mode 100644
index 000000000..963a1f322
--- /dev/null
+++ b/tests/repro/repro_call_argument_matrix_a.c
@@ -0,0 +1,1285 @@
+/*
+ * repro_call_argument_matrix_a.c -- all call-capable languages from GO through AGDA.
+ *
+ * This is the general reference-preservation invariant, not a claim that every
+ * fixture passes a function object. Most semantic rows intentionally pass a
+ * scalar/value parameter named `handler` to `accept`, while a different function
+ * directly invokes the function named `handler`. The identical spelling gets two
+ * exact AST roles and proves that only the invoked occurrence is replaced by
+ * CALLS. True function-object/callback cases are covered separately by
+ * repro_call_argument_usages.c and repro_call_scope_usages.c.
+ *
+ * Languages whose call metadata describes a DSL without ordinary user routine
+ * bodies use paired native argument and bare-reference fixtures. The bare fixture
+ * distinguishes missing reference vocabulary from call-boundary suppression.
+ * CSS custom properties are an explicit domain exception because their only
+ * reference syntax is var(...); that row makes no vocabulary-isolation claim.
+ */
+#include "test_framework.h"
+#include "lang_specs.h"
+
+#include <stdio.h>
+#include <string.h>
+
+size_t repro_call_argument_matrix_a_copy_language_ids(CBMLanguage *language_ids, size_t capacity);
+
+typedef enum {
+ MATRIX_SEMANTIC,
+ MATRIX_NATIVE_SCOPE,
+} MatrixMode;
+
+typedef enum {
+ NATIVE_PAIRED,
+ NATIVE_DOMAIN_EXCEPTION,
+} NativeFixtureMode;
+
+typedef struct {
+ const char *tag;
+ CBMLanguage language;
+ const char *filename;
+ const char *source;
+ MatrixMode mode;
+ NativeFixtureMode native_fixture_mode;
+ int expect_lexical_local_shadow; /* semantic parameter rows only */
+ const char *value_name;
+ const char *call_kind;
+ int scope_node_count;
+ int scope_call_count;
+ const char *reference_node_kind;
+ const char *reference_node_text;
+ int scope_reference_node_count;
+ int bare_reference_node_count;
+ int bare_call_count;
+ const char *reason;
+ const char *outer_callee;
+ const char *scope_caller;
+ const char *scope_value;
+ const char *scope_definition;
+ const char *outer_definition;
+ const char *bare_source;
+ const char *bare_filename;
+ const char *bare_caller;
+ const char *bare_value;
+ const char *bare_definition;
+ const char *broad_source;
+ const char *broad_filename;
+ const char *broad_caller;
+ const char *broad_value;
+ const char *broad_node_kind;
+ int broad_node_count;
+ const char *broad_callee;
+ int broad_call_count;
+} MatrixCase;
+
+static int qn_has_terminal_name(const char *qn, const char *name) {
+ if (!qn || !name)
+ return 0;
+ size_t qn_len = strlen(qn);
+ size_t name_len = strlen(name);
+ if (name_len > qn_len || strcmp(qn + qn_len - name_len, name) != 0)
+ return 0;
+ if (name_len == qn_len)
+ return 1;
+ char separator = qn[qn_len - name_len - 1];
+ return separator == '.' || separator == ':' || separator == '/' || separator == '#';
+}
+
+static const char *short_call_name(const char *name) {
+ if (!name)
+ return NULL;
+ const char *short_name = name;
+ for (const char *p = name; *p; p++) {
+ if (*p == '.' || *p == ':' || *p == '/' || *p == '#')
+ short_name = p + 1;
+ }
+ return short_name;
+}
+
+static int definition_count(const CBMFileResult *result, const char *name) {
+ int count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ int callable = definition->label && (strcmp(definition->label, "Function") == 0 ||
+ strcmp(definition->label, "Method") == 0);
+ if (callable && definition->name && strcmp(definition->name, name) == 0)
+ count++;
+ }
+ return count;
+}
+
+static int call_count(const CBMFileResult *result, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ const char *callee = short_call_name(call->callee_name);
+ if (callee && strcmp(callee, target) == 0 &&
+ (!caller || qn_has_terminal_name(call->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int usage_within_call_count(const CBMFileResult *result, const char *caller,
+ const char *value, const char *callee) {
+ int count = 0;
+ for (int u = 0; u < result->usages.count; u++) {
+ const CBMUsage *usage = &result->usages.items[u];
+ if (!usage->ref_name || strcmp(usage->ref_name, value) != 0 ||
+ !qn_has_terminal_name(usage->enclosing_func_qn, caller) ||
+ usage->site_end_byte <= usage->site_start_byte) {
+ continue;
+ }
+ for (int c = 0; c < result->calls.count; c++) {
+ const CBMCall *call = &result->calls.items[c];
+ const char *call_name = short_call_name(call->callee_name);
+ if (!call_name || strcmp(call_name, callee) != 0 ||
+ !qn_has_terminal_name(call->enclosing_func_qn, caller) ||
+ call->source_origin != usage->source_origin ||
+ call->site_end_byte <= call->site_start_byte) {
+ continue;
+ }
+ if (usage->site_start_byte >= call->site_start_byte &&
+ usage->site_end_byte <= call->site_end_byte) {
+ count++;
+ }
+ }
+ }
+ return count;
+}
+
+static int usage_count(const CBMFileResult *result, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->ref_name && strcmp(usage->ref_name, target) == 0 &&
+ (!caller || qn_has_terminal_name(usage->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int usage_kind_count(const CBMFileResult *result, const char *caller, const char *target,
+ CBMUsageKind kind) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == kind && usage->ref_name && strcmp(usage->ref_name, target) == 0 &&
+ (!caller || qn_has_terminal_name(usage->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int local_shadow_usage_count(const CBMFileResult *result, const char *caller,
+ const char *target) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->semantic_reference_blocked &&
+ usage->semantic_reference_local_shadow && usage->ref_name &&
+ strcmp(usage->ref_name, target) == 0 &&
+ (!caller || qn_has_terminal_name(usage->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int type_list_contains(const char *const *types, const char *expected) {
+ if (!types || !expected)
+ return 0;
+ for (int i = 0; types[i]; i++) {
+ if (strcmp(types[i], expected) == 0)
+ return 1;
+ }
+ return 0;
+}
+
+static int ast_node_match_count(TSNode node, const char *node_kind, const char *node_text,
+ const char *source) {
+ int count = 0;
+ if (strcmp(ts_node_type(node), node_kind) == 0) {
+ if (!node_text) {
+ count = 1;
+ } else {
+ uint32_t start = ts_node_start_byte(node);
+ uint32_t end = ts_node_end_byte(node);
+ size_t expected_length = strlen(node_text);
+ if (end >= start && (size_t)(end - start) == expected_length &&
+ memcmp(source + start, node_text, expected_length) == 0) {
+ count = 1;
+ }
+ }
+ }
+ uint32_t child_count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < child_count; i++)
+ count += ast_node_match_count(ts_node_child(node, i), node_kind, node_text, source);
+ return count;
+}
+
+static int check_ast_contract(const MatrixCase *matrix_case, const char *source, const char *phase,
+ const char *primary_kind, const char *primary_text,
+ int primary_expected, const char *primary_invariant,
+ const char *secondary_kind, const char *secondary_text,
+ int secondary_expected, const char *secondary_invariant) {
+ int failures = 0;
+ const TSLanguage *language = cbm_ts_language(matrix_case->language);
+ TSParser *parser = ts_parser_new();
+ if (!language || !parser || !ts_parser_set_language(parser, language)) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=ast_parser_ready expected=1 "
+ "actual=0\n",
+ matrix_case->tag, phase);
+ if (parser)
+ ts_parser_delete(parser);
+ return 1;
+ }
+
+ TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
+ if (!tree) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=ast_tree expected=non-null "
+ "actual=null\n",
+ matrix_case->tag, phase);
+ ts_parser_delete(parser);
+ return 1;
+ }
+
+ TSNode root = ts_tree_root_node(tree);
+ if (ts_node_has_error(root)) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=ast_clean_parse expected=1 "
+ "actual=0\n",
+ matrix_case->tag, phase);
+ failures++;
+ }
+ int primary_actual = ast_node_match_count(root, primary_kind, primary_text, source);
+ if (primary_actual != primary_expected) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=%s kind=%s text=%s expected=%d "
+ "actual=%d\n",
+ matrix_case->tag, phase, primary_invariant, primary_kind,
+ primary_text ? primary_text : "*", primary_expected, primary_actual);
+ failures++;
+ }
+ if (secondary_kind) {
+ int secondary_actual = ast_node_match_count(root, secondary_kind, secondary_text, source);
+ if (secondary_actual != secondary_expected) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=%s kind=%s text=%s expected=%d "
+ "actual=%d\n",
+ matrix_case->tag, phase, secondary_invariant, secondary_kind,
+ secondary_text ? secondary_text : "*", secondary_expected, secondary_actual);
+ failures++;
+ }
+ }
+ ts_tree_delete(tree);
+ ts_parser_delete(parser);
+ return failures;
+}
+
+#define CHECK_EXACT(tag, invariant, expression, expected) \
+ do { \
+ int actual = (expression); \
+ if (actual != (expected)) { \
+ fprintf(stderr, " [call-matrix-a] lang=%s invariant=%s expected=%d actual=%d\n", \
+ (tag), (invariant), (expected), actual); \
+ failures++; \
+ } \
+ } while (0)
+
+static CBMFileResult *extract_matrix_source(const MatrixCase *matrix_case, const char *source,
+ const char *filename, const char *phase) {
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), matrix_case->language,
+ "repro", filename, 0, NULL, NULL);
+ if (!result) {
+ fprintf(stderr, " [call-matrix-a] lang=%s phase=%s invariant=extract_result_null\n",
+ matrix_case->tag, phase);
+ }
+ return result;
+}
+
+static int check_reference_fixture(const MatrixCase *matrix_case, const char *source,
+ const char *filename, const char *caller, const char *value,
+ const char *outer_callee, const char *definition,
+ const char *outer_definition, const char *phase,
+ const char *usage_invariant, const char *not_call_invariant,
+ const char *shape_callee, int expected_call_count,
+ const char *total_calls_invariant) {
+ CBMFileResult *result = extract_matrix_source(matrix_case, source, filename, phase);
+ if (!result)
+ return 1;
+
+ int failures = 0;
+ if (result->has_error || result->parse_incomplete) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=%s invariant=valid_fixture expected=clean\n",
+ matrix_case->tag, phase);
+ failures++;
+ }
+ if (definition)
+ CHECK_EXACT(matrix_case->tag, "native_fixture_definition",
+ definition_count(result, definition), 1);
+ if (outer_definition)
+ CHECK_EXACT(matrix_case->tag, "native_outer_definition",
+ definition_count(result, outer_definition), 1);
+ if (outer_callee) {
+ CHECK_EXACT(matrix_case->tag, "native_outer_call", call_count(result, caller, outer_callee),
+ 1);
+ CHECK_EXACT(matrix_case->tag, "native_outer_callee_not_usage",
+ usage_count(result, caller, outer_callee), 0);
+ }
+ CHECK_EXACT(matrix_case->tag, usage_invariant, usage_count(result, caller, value), 1);
+ CHECK_EXACT(matrix_case->tag, "reference_is_ordinary_usage",
+ usage_kind_count(result, caller, value, CBM_USAGE_VALUE), 1);
+ CHECK_EXACT(matrix_case->tag, "reference_not_call_reference",
+ usage_kind_count(result, caller, value, CBM_USAGE_CALL_REFERENCE), 0);
+ CHECK_EXACT(matrix_case->tag, not_call_invariant, call_count(result, caller, value), 0);
+ CHECK_EXACT(matrix_case->tag, total_calls_invariant, result->calls.count, expected_call_count);
+ if (shape_callee)
+ CHECK_EXACT(matrix_case->tag, "broad_expected_callee",
+ call_count(result, caller, shape_callee), expected_call_count);
+ cbm_free_result(result);
+ return failures;
+}
+
+static int check_semantic_case(const MatrixCase *matrix_case) {
+ int failures = check_ast_contract(matrix_case, matrix_case->source, "roles-ast",
+ matrix_case->call_kind, NULL, matrix_case->scope_node_count,
+ "semantic_primary_call_node_count", NULL, NULL, 0, NULL);
+ CBMFileResult *result =
+ extract_matrix_source(matrix_case, matrix_case->source, matrix_case->filename, "roles");
+ if (!result)
+ return failures + 1;
+
+ if (result->has_error || result->parse_incomplete) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s phase=roles invariant=valid_fixture expected=clean\n",
+ matrix_case->tag);
+ failures++;
+ }
+
+ CHECK_EXACT(matrix_case->tag, "handler_definition", definition_count(result, "handler"), 1);
+ CHECK_EXACT(matrix_case->tag, "accept_definition", definition_count(result, "accept"), 1);
+ CHECK_EXACT(matrix_case->tag, "argument_definition", definition_count(result, "argument"), 1);
+ CHECK_EXACT(matrix_case->tag, "direct_definition", definition_count(result, "direct"), 1);
+ CHECK_EXACT(matrix_case->tag, "bare_definition", definition_count(result, "bare"), 1);
+ CHECK_EXACT(matrix_case->tag, "registrar_call", call_count(result, "argument", "accept"), 1);
+ CHECK_EXACT(matrix_case->tag, "direct_call", call_count(result, "direct", "handler"), 1);
+ CHECK_EXACT(matrix_case->tag, "inside_value_usage",
+ usage_count(result, "argument", matrix_case->value_name), 1);
+ CHECK_EXACT(matrix_case->tag, "inside_value_site_owned_by_registrar_call",
+ usage_within_call_count(result, "argument", matrix_case->value_name, "accept"), 1);
+ CHECK_EXACT(matrix_case->tag, "inside_value_is_ordinary_usage",
+ usage_kind_count(result, "argument", matrix_case->value_name, CBM_USAGE_VALUE), 1);
+ CHECK_EXACT(
+ matrix_case->tag, "inside_value_not_call_reference",
+ usage_kind_count(result, "argument", matrix_case->value_name, CBM_USAGE_CALL_REFERENCE), 0);
+ if (matrix_case->expect_lexical_local_shadow) {
+ CHECK_EXACT(matrix_case->tag, "inside_value_blocks_callable_promotion",
+ local_shadow_usage_count(result, "argument", matrix_case->value_name), 1);
+ }
+ CHECK_EXACT(matrix_case->tag, "bare_value_usage",
+ usage_count(result, "bare", matrix_case->value_name), 1);
+ CHECK_EXACT(matrix_case->tag, "bare_value_is_ordinary_usage",
+ usage_kind_count(result, "bare", matrix_case->value_name, CBM_USAGE_VALUE), 1);
+ CHECK_EXACT(matrix_case->tag, "bare_value_not_call_reference",
+ usage_kind_count(result, "bare", matrix_case->value_name, CBM_USAGE_CALL_REFERENCE),
+ 0);
+ CHECK_EXACT(matrix_case->tag, "direct_callee_not_usage",
+ usage_count(result, "direct", "handler"), 0);
+ CHECK_EXACT(matrix_case->tag, "argument_not_fabricated_call",
+ call_count(result, "argument", "handler"), 0);
+ CHECK_EXACT(matrix_case->tag, "semantic_total_calls", result->calls.count,
+ matrix_case->scope_call_count);
+ cbm_free_result(result);
+
+ if (matrix_case->broad_source) {
+ failures += check_ast_contract(
+ matrix_case, matrix_case->broad_source, "broad-node", matrix_case->broad_node_kind,
+ NULL, matrix_case->broad_node_count, "broad_ast_node_count", NULL, NULL, 0, NULL);
+ failures += check_reference_fixture(
+ matrix_case, matrix_case->broad_source, matrix_case->broad_filename,
+ matrix_case->broad_caller, matrix_case->broad_value, NULL, NULL, NULL, "broad-node",
+ "broad_reference_usage", "broad_reference_not_call", matrix_case->broad_callee,
+ matrix_case->broad_call_count, "broad_total_calls");
+ }
+ return failures;
+}
+
+static int check_native_scope_case(const MatrixCase *matrix_case) {
+ int failures = 0;
+ const CBMLangSpec *spec = cbm_lang_spec(matrix_case->language);
+ if (!spec || spec->language != matrix_case->language) {
+ fprintf(stderr, " [call-matrix-a] lang=%s invariant=registered_spec_missing\n",
+ matrix_case->tag);
+ failures++;
+ } else if (!type_list_contains(spec->call_node_types, matrix_case->call_kind)) {
+ fprintf(stderr,
+ " [call-matrix-a] lang=%s invariant=native_call_kind_missing expected=%s\n",
+ matrix_case->tag, matrix_case->call_kind);
+ failures++;
+ }
+ if (!matrix_case->reason || matrix_case->reason[0] == '\0') {
+ fprintf(stderr, " [call-matrix-a] lang=%s invariant=applicability_reason_missing\n",
+ matrix_case->tag);
+ failures++;
+ }
+ if (!matrix_case->call_kind || !matrix_case->reference_node_kind ||
+ !matrix_case->reference_node_text) {
+ fprintf(stderr, " [call-matrix-a] lang=%s invariant=native_ast_contract_missing\n",
+ matrix_case->tag);
+ return failures + 1;
+ }
+ failures += check_ast_contract(
+ matrix_case, matrix_case->source, "native-argument", matrix_case->call_kind, NULL,
+ matrix_case->scope_node_count, "native_call_node_count", matrix_case->reference_node_kind,
+ matrix_case->reference_node_text, matrix_case->scope_reference_node_count,
+ "native_argument_reference_shape");
+ failures += check_reference_fixture(
+ matrix_case, matrix_case->source, matrix_case->filename, matrix_case->scope_caller,
+ matrix_case->scope_value, matrix_case->outer_callee, matrix_case->scope_definition,
+ matrix_case->outer_definition, "native-argument", "native_argument_usage",
+ "native_argument_not_call", NULL, matrix_case->scope_call_count,
+ "native_argument_total_calls");
+
+ if (matrix_case->native_fixture_mode == NATIVE_DOMAIN_EXCEPTION)
+ return failures;
+
+ if (!matrix_case->bare_source || !matrix_case->bare_filename || !matrix_case->bare_value) {
+ fprintf(stderr, " [call-matrix-a] lang=%s invariant=native_bare_fixture_missing\n",
+ matrix_case->tag);
+ return failures + 1;
+ }
+ failures +=
+ check_ast_contract(matrix_case, matrix_case->bare_source, "native-bare",
+ matrix_case->call_kind, NULL, 0, "native_bare_call_node_count",
+ matrix_case->reference_node_kind, matrix_case->reference_node_text,
+ matrix_case->bare_reference_node_count, "native_bare_reference_shape");
+ failures += check_reference_fixture(
+ matrix_case, matrix_case->bare_source, matrix_case->bare_filename, matrix_case->bare_caller,
+ matrix_case->bare_value, NULL, matrix_case->bare_definition, NULL, "native-bare",
+ "native_bare_usage", "native_bare_not_call", NULL, matrix_case->bare_call_count,
+ "native_bare_total_calls");
+ return failures;
+}
+
+static int check_matrix_case(const MatrixCase *matrix_case) {
+ return matrix_case->mode == MATRIX_SEMANTIC ? check_semantic_case(matrix_case)
+ : check_native_scope_case(matrix_case);
+}
+
+#define SEMANTIC_CASE(tag_, lang_, file_, source_, value_, kind_, node_count_, call_count_) \
+ static const MatrixCase CASE_##tag_ = { \
+ .tag = #tag_, \
+ .language = CBM_LANG_##lang_, \
+ .filename = file_, \
+ .source = source_, \
+ .mode = MATRIX_SEMANTIC, \
+ .expect_lexical_local_shadow = 1, \
+ .value_name = value_, \
+ .call_kind = kind_, \
+ .scope_node_count = node_count_, \
+ .scope_call_count = call_count_, \
+ }
+
+#define SEMANTIC_BROAD_CASE(tag_, lang_, file_, source_, value_, kind_, node_count_, call_count_, \
+ broad_src_, broad_file_, broad_caller_, broad_value_, broad_kind_, \
+ broad_node_count_, broad_callee_, broad_call_count_) \
+ static const MatrixCase CASE_##tag_ = { \
+ .tag = #tag_, \
+ .language = CBM_LANG_##lang_, \
+ .filename = file_, \
+ .source = source_, \
+ .mode = MATRIX_SEMANTIC, \
+ .expect_lexical_local_shadow = 1, \
+ .value_name = value_, \
+ .call_kind = kind_, \
+ .scope_node_count = node_count_, \
+ .scope_call_count = call_count_, \
+ .broad_source = broad_src_, \
+ .broad_filename = broad_file_, \
+ .broad_caller = broad_caller_, \
+ .broad_value = broad_value_, \
+ .broad_node_kind = broad_kind_, \
+ .broad_node_count = broad_node_count_, \
+ .broad_callee = broad_callee_, \
+ .broad_call_count = broad_call_count_, \
+ }
+
+#define NATIVE_SCOPE_CASE(tag_, lang_, file_, source_, kind_, reason_, callee_, caller_, value_, \
+ definition_, outer_definition_, bare_source_, bare_file_, bare_caller_, \
+ bare_value_, bare_definition_, node_count_, reference_kind_, \
+ reference_text_, scope_reference_count_, bare_reference_count_, \
+ scope_call_count_, bare_call_count_) \
+ static const MatrixCase CASE_##tag_ = { \
+ .tag = #tag_, \
+ .language = CBM_LANG_##lang_, \
+ .filename = file_, \
+ .source = source_, \
+ .mode = MATRIX_NATIVE_SCOPE, \
+ .native_fixture_mode = NATIVE_PAIRED, \
+ .call_kind = kind_, \
+ .scope_node_count = node_count_, \
+ .scope_call_count = scope_call_count_, \
+ .reference_node_kind = reference_kind_, \
+ .reference_node_text = reference_text_, \
+ .scope_reference_node_count = scope_reference_count_, \
+ .bare_reference_node_count = bare_reference_count_, \
+ .bare_call_count = bare_call_count_, \
+ .reason = reason_, \
+ .outer_callee = callee_, \
+ .scope_caller = caller_, \
+ .scope_value = value_, \
+ .scope_definition = definition_, \
+ .outer_definition = outer_definition_, \
+ .bare_source = bare_source_, \
+ .bare_filename = bare_file_, \
+ .bare_caller = bare_caller_, \
+ .bare_value = bare_value_, \
+ .bare_definition = bare_definition_, \
+ }
+
+#define NATIVE_DOMAIN_CASE(tag_, lang_, file_, source_, kind_, reason_, callee_, value_, \
+ node_count_, reference_kind_, reference_text_, reference_count_, \
+ call_count_) \
+ static const MatrixCase CASE_##tag_ = { \
+ .tag = #tag_, \
+ .language = CBM_LANG_##lang_, \
+ .filename = file_, \
+ .source = source_, \
+ .mode = MATRIX_NATIVE_SCOPE, \
+ .native_fixture_mode = NATIVE_DOMAIN_EXCEPTION, \
+ .call_kind = kind_, \
+ .scope_node_count = node_count_, \
+ .scope_call_count = call_count_, \
+ .reference_node_kind = reference_kind_, \
+ .reference_node_text = reference_text_, \
+ .scope_reference_node_count = reference_count_, \
+ .reason = reason_, \
+ .outer_callee = callee_, \
+ .scope_value = value_, \
+ }
+
+SEMANTIC_CASE(go, GO, "main.go",
+ "package sample\n"
+ "func handler() int { return 0 }\n"
+ "func accept(value int) int { return value }\n"
+ "func argument(handler int) int { return accept(handler) }\n"
+ "func direct() int { return handler() }\n"
+ "func bare(handler int) int { return handler }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(python, PYTHON, "main.py",
+ "def handler():\n return 0\n"
+ "def accept(value):\n return value\n"
+ "def argument(handler):\n return accept(handler)\n"
+ "def direct():\n return handler()\n"
+ "def bare(handler):\n return handler\n",
+ "handler", "call", 2, 2);
+
+SEMANTIC_CASE(javascript, JAVASCRIPT, "main.js",
+ "function handler() { return 0; }\n"
+ "function accept(value) { return value; }\n"
+ "function argument(handler) { return accept(handler); }\n"
+ "function direct() { return handler(); }\n"
+ "function bare(handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(typescript, TYPESCRIPT, "main.ts",
+ "function handler(): number { return 0; }\n"
+ "function accept(value: number): number { return value; }\n"
+ "function argument(handler: number): number { return accept(handler); }\n"
+ "function direct(): number { return handler(); }\n"
+ "function bare(handler: number): number { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(tsx, TSX, "main.tsx",
+ "function handler(): number { return 0; }\n"
+ "function accept(value: number): number { return value; }\n"
+ "function argument(handler: number): number { return accept(handler); }\n"
+ "function direct(): number { return handler(); }\n"
+ "function bare(handler: number): number { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(rust, RUST, "main.rs",
+ "fn handler() -> i32 { 0 }\n"
+ "fn accept(value: i32) -> i32 { value }\n"
+ "fn argument(handler: i32) -> i32 { accept(handler) }\n"
+ "fn direct() -> i32 { handler() }\n"
+ "fn bare(handler: i32) -> i32 { handler }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(java, JAVA, "Sample.java",
+ "class Sample {\n"
+ " static int handler() { return 0; }\n"
+ " static int accept(int value) { return value; }\n"
+ " static int argument(int handler) { return accept(handler); }\n"
+ " static int direct() { return handler(); }\n"
+ " static int bare(int handler) { return handler; }\n"
+ "}\n",
+ "handler", "method_invocation", 2, 2);
+
+SEMANTIC_CASE(cpp, CPP, "main.cpp",
+ "int handler() { return 0; }\n"
+ "int accept(int value) { return value; }\n"
+ "int argument(int handler) { return accept(handler); }\n"
+ "int direct() { return handler(); }\n"
+ "int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(csharp, CSHARP, "Sample.cs",
+ "class Sample {\n"
+ " static int handler() { return 0; }\n"
+ " static int accept(int value) { return value; }\n"
+ " static int argument(int handler) { return accept(handler); }\n"
+ " static int direct() { return handler(); }\n"
+ " static int bare(int handler) { return handler; }\n"
+ "}\n",
+ "handler", "invocation_expression", 2, 2);
+
+SEMANTIC_CASE(php, PHP, "main.php",
+ "<?php\n"
+ "function handler() { return 0; }\n"
+ "function accept($value) { return $value; }\n"
+ "function argument($handler) { return accept($handler); }\n"
+ "function direct() { return handler(); }\n"
+ "function bare($handler) { return $handler; }\n",
+ "$handler", "function_call_expression", 2, 2);
+
+SEMANTIC_CASE(lua, LUA, "main.lua",
+ "function handler() return 0 end\n"
+ "function accept(value) return value end\n"
+ "function argument(handler) return accept(handler) end\n"
+ "function direct() return handler() end\n"
+ "function bare(handler) return handler end\n",
+ "handler", "function_call", 2, 2);
+
+SEMANTIC_BROAD_CASE(scala, SCALA, "Main.scala",
+ "object Sample {\n"
+ " def handler(): Int = 0\n"
+ " def accept(value: Int): Int = value\n"
+ " def argument(handler: Int): Int = accept(handler)\n"
+ " def direct(): Int = handler()\n"
+ " def bare(handler: Int): Int = handler\n"
+ "}\n",
+ "handler", "call_expression", 2, 2,
+ "object Scope { def scope(watched: Int): Int = watched + 1 }\n", "Scope.scala",
+ "scope", "watched", "infix_expression", 1, "+", 1);
+
+SEMANTIC_CASE(kotlin, KOTLIN, "Main.kt",
+ "fun handler(): Int = 0\n"
+ "fun accept(value: Int): Int = value\n"
+ "fun argument(handler: Int): Int = accept(handler)\n"
+ "fun direct(): Int = handler()\n"
+ "fun bare(handler: Int): Int = handler\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(ruby, RUBY, "main.rb",
+ "def handler; 0; end\n"
+ "def accept(value); value; end\n"
+ "def argument(handler); accept(handler); end\n"
+ "def direct; handler(); end\n"
+ "def bare(handler); handler; end\n",
+ "handler", "call", 2, 2);
+
+SEMANTIC_CASE(c, C, "main.c",
+ "int handler(void) { return 0; }\n"
+ "int accept(int value) { return value; }\n"
+ "int argument(int handler) { return accept(handler); }\n"
+ "int direct(void) { return handler(); }\n"
+ "int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(bash, BASH, "main.sh",
+ "handler() { return 0; }\n"
+ "accept() { printf '%s' \"$1\"; }\n"
+ "argument() { local handler=$1; accept \"$handler\"; }\n"
+ "direct() { handler; }\n"
+ "bare() { local handler=$1; printf '%s' \"$handler\"; }\n",
+ "handler", "command", 5, 4);
+
+SEMANTIC_CASE(zig, ZIG, "main.zig",
+ "fn handler() i32 { return 0; }\n"
+ "fn accept(value: i32) i32 { return value; }\n"
+ "fn argument(handler: i32) i32 { return accept(handler); }\n"
+ "fn direct() i32 { return handler(); }\n"
+ "fn bare(handler: i32) i32 { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(elixir, ELIXIR, "main.ex",
+ "defmodule Sample do\n"
+ " def handler(), do: 0\n"
+ " def accept(value), do: value\n"
+ " def argument(handler), do: accept(handler)\n"
+ " def direct(), do: handler()\n"
+ " def bare(handler), do: handler\n"
+ "end\n",
+ "handler", "call", 13, 2);
+
+SEMANTIC_BROAD_CASE(haskell, HASKELL, "Main.hs",
+ "module Main where\n"
+ "handler :: Int -> Int\nhandler value = value\n"
+ "accept :: Int -> Int\naccept value = value\n"
+ "argument :: Int -> Int\nargument handler = accept handler\n"
+ "direct :: Int -> Int\ndirect value = handler value\n"
+ "bare :: Int -> Int\nbare handler = handler\n",
+ "handler", "apply", 2, 2, "module Scope where\nscope watched = watched + 1\n",
+ "Scope.hs", "scope", "watched", "infix", 1, "+", 1);
+
+SEMANTIC_BROAD_CASE(ocaml, OCAML, "main.ml",
+ "let handler value = value\n"
+ "let accept value = value\n"
+ "let argument handler = accept handler\n"
+ "let direct value = handler value\n"
+ "let bare handler = handler\n",
+ "handler", "application_expression", 2, 2, "let scope watched = watched + 1\n",
+ "scope.ml", "scope", "watched", "infix_expression", 1, "+", 1);
+
+SEMANTIC_CASE(objc, OBJC, "main.m",
+ "int handler(void) { return 0; }\n"
+ "int accept(int value) { return value; }\n"
+ "int argument(int handler) { return accept(handler); }\n"
+ "int direct(void) { return handler(); }\n"
+ "int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_BROAD_CASE(swift, SWIFT, "main.swift",
+ "func handler() -> Int { return 0 }\n"
+ "func accept(_ value: Int) -> Int { return value }\n"
+ "func argument(_ handler: Int) -> Int { return accept(handler) }\n"
+ "func direct() -> Int { return handler() }\n"
+ "func bare(_ handler: Int) -> Int { return handler }\n",
+ "handler", "call_expression", 2, 2,
+ "struct Holder { let value: Int }\n"
+ "func scope(_ holder: Holder) -> Int { return holder.value }\n",
+ "Scope.swift", "scope", "holder", "navigation_expression", 1, NULL, 0);
+
+SEMANTIC_CASE(dart, DART, "main.dart",
+ "int handler() => 0;\n"
+ "int accept(int value) => value;\n"
+ "int argument(int handler) => accept(handler);\n"
+ "int direct() => handler();\n"
+ "int bare(int handler) => handler;\n",
+ "handler", "selector", 2, 2);
+
+SEMANTIC_CASE(perl, PERL, "main.pl",
+ "sub handler { return 0; }\n"
+ "sub accept { my ($value) = @_; return $value; }\n"
+ "sub argument { my ($handler) = @_; return accept($handler); }\n"
+ "sub direct { return handler(); }\n"
+ "sub bare { my ($handler) = @_; return $handler; }\n",
+ "$handler", "function_call_expression", 2, 2);
+
+SEMANTIC_CASE(groovy, GROOVY, "Main.groovy",
+ "int handler() { return 0 }\n"
+ "int accept(int value) { return value }\n"
+ "int argument(int handler) { return accept(handler) }\n"
+ "int direct() { return handler() }\n"
+ "int bare(int handler) { return handler }\n",
+ "handler", "function_call", 2, 2);
+
+SEMANTIC_CASE(erlang, ERLANG, "main.erl",
+ "-module(main).\n"
+ "handler() -> 0.\n"
+ "accept(Value) -> Value.\n"
+ "argument(Handler) -> accept(Handler).\n"
+ "direct() -> handler().\n"
+ "bare(Handler) -> Handler.\n",
+ "Handler", "call", 2, 2);
+
+SEMANTIC_CASE(r, R, "main.R",
+ "handler <- function() { 0 }\n"
+ "accept <- function(value) { value }\n"
+ "argument <- function(handler) { accept(handler) }\n"
+ "direct <- function() { handler() }\n"
+ "bare <- function(handler) { handler }\n",
+ "handler", "call", 2, 2);
+
+NATIVE_DOMAIN_CASE(css, CSS, "main.css",
+ ":root { --watched: 0; }\n.sample { color: var(--watched); }\n",
+ "call_expression",
+ "CSS custom properties can only be referenced through var(), so no honest "
+ "bare equivalent exists; this checks exact AST/call/usage behavior without "
+ "claiming vocabulary isolation",
+ "var", "--watched", 1, "plain_value", "--watched", 1, 1);
+
+SEMANTIC_CASE(scss, SCSS, "main.scss",
+ "@function handler($unused) {\n @return 0;\n}\n"
+ "@function accept($value) {\n @return $value;\n}\n"
+ "@function argument($handler) {\n @return accept($handler);\n}\n"
+ "@function direct($unused) {\n @return handler(0);\n}\n"
+ "@function bare($handler) {\n @return $handler;\n}\n",
+ "$handler", "call_expression", 2, 2);
+
+NATIVE_SCOPE_CASE(hcl, HCL, "main.tf", "locals {\n watched = [1]\n result = length(watched)\n}\n",
+ "function_call",
+ "HCL exposes built-in function applications but cannot declare user routines, "
+ "so local-expression references use exact global counts",
+ "length", NULL, "watched", NULL, NULL,
+ "locals {\n watched = [1]\n result = watched\n}\n", "bare.tf", NULL, "watched",
+ NULL, 1, "variable_expr", "watched", 1, 1, 1, 0);
+
+/* This known-valid PL/pgSQL shape exercises the grammar-real `invocation` node.
+ * The registered `function_call` spelling remains covered as a stale manifest
+ * defect; SQL `command` is separately classified NOT_A_CALL. */
+NATIVE_SCOPE_CASE(sql, SQL, "argument.sql",
+ "CREATE FUNCTION accept(value integer) RETURNS integer AS $$\n"
+ "BEGIN\n RETURN value;\nEND;\n$$ LANGUAGE plpgsql;\n"
+ "CREATE FUNCTION argument(handler integer) RETURNS integer AS $$\n"
+ "BEGIN\n RETURN accept(handler);\nEND;\n$$ LANGUAGE plpgsql;\n",
+ "invocation",
+ "SQL create_function supplies an enclosing callable, so definitions and "
+ "caller-qualified references are exact",
+ "accept", "argument", "handler", "argument", "accept",
+ "CREATE FUNCTION bare(handler integer) RETURNS integer AS $$\n"
+ "BEGIN\n RETURN handler;\nEND;\n$$ LANGUAGE plpgsql;\n",
+ "bare.sql", "bare", "handler", "bare", 1, "identifier", "handler", 2, 2, 1, 0);
+
+SEMANTIC_CASE(clojure, CLOJURE, "main.clj",
+ "(defn handler [] 0)\n"
+ "(defn accept [value] value)\n"
+ "(defn argument [handler] (accept handler))\n"
+ "(defn direct [] (handler))\n"
+ "(defn bare [handler] handler)\n",
+ "handler", "list_lit", 7, 2);
+
+SEMANTIC_BROAD_CASE(fsharp, FSHARP, "Main.fs",
+ "let handler () = 0\n"
+ "let accept value = value\n"
+ "let argument handler = accept handler\n"
+ "let direct () = handler ()\n"
+ "let bare handler = handler\n",
+ "handler", "application_expression", 2, 2,
+ "type Holder = { value: int }\n"
+ "let scope (watched: Holder) = (watched).value\n",
+ "Scope.fs", "scope", "watched", "dot_expression", 1, NULL, 0);
+
+SEMANTIC_CASE(julia, JULIA, "main.jl",
+ "function handler()\n return 0\nend\n"
+ "function accept(value)\n return value\nend\n"
+ "function argument(handler)\n return accept(handler)\nend\n"
+ "function direct()\n return handler()\nend\n"
+ "function bare(handler)\n return handler\nend\n",
+ "handler", "call_expression", 7, 2);
+
+SEMANTIC_CASE(vimscript, VIMSCRIPT, "main.vim",
+ "function! handler()\n return 0\nendfunction\n"
+ "function! accept(value)\n return a:value\nendfunction\n"
+ "function! argument(handler)\n return accept(a:handler)\nendfunction\n"
+ "function! direct()\n return handler()\nendfunction\n"
+ "function! bare(handler)\n return a:handler\nendfunction\n",
+ "a:handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(nix, NIX, "main.nix",
+ "let\n"
+ " handler = value: value;\n"
+ " accept = value: value;\n"
+ " argument = handler: accept handler;\n"
+ " direct = value: handler value;\n"
+ " bare = handler: handler;\n"
+ "in argument\n",
+ "handler", "apply_expression", 2, 2);
+
+SEMANTIC_CASE(commonlisp, COMMONLISP, "main.lisp",
+ "(defun handler () 0)\n"
+ "(defun accept (value) value)\n"
+ "(defun argument (handler) (accept handler))\n"
+ "(defun direct () (handler))\n"
+ "(defun bare (handler) handler)\n",
+ "handler", "list_lit", 12, 2);
+
+SEMANTIC_CASE(elm, ELM, "Main.elm",
+ "module Main exposing (..)\n"
+ "handler value = value\n"
+ "accept value = value\n"
+ "argument handler = accept handler\n"
+ "direct value = handler value\n"
+ "bare handler = handler\n",
+ "handler", "function_call_expr", 2, 2);
+
+SEMANTIC_CASE(fortran, FORTRAN, "main.f90",
+ "module sample\ncontains\n"
+ " integer function handler()\n handler = 0\n end function handler\n"
+ " integer function accept(value)\n integer :: value\n accept = value\n"
+ " end function accept\n"
+ " integer function argument(handler)\n integer :: handler\n"
+ " argument = accept(handler)\n end function argument\n"
+ " integer function direct()\n direct = handler()\n end function direct\n"
+ " integer function bare(handler)\n integer :: handler\n"
+ " bare = handler\n end function bare\nend module sample\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(cuda, CUDA, "main.cu",
+ "__device__ int handler() { return 0; }\n"
+ "__device__ int accept(int value) { return value; }\n"
+ "__device__ int argument(int handler) { return accept(handler); }\n"
+ "__device__ int direct() { return handler(); }\n"
+ "__device__ int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+NATIVE_SCOPE_CASE(cobol, COBOL, "main.cob",
+ " IDENTIFICATION DIVISION.\n"
+ " PROGRAM-ID. argument.\n"
+ " DATA DIVISION.\n"
+ " WORKING-STORAGE SECTION.\n"
+ " 01 handler PIC 9 VALUE 1.\n"
+ " PROCEDURE DIVISION.\n"
+ " CALL \"accept\" USING handler.\n"
+ " STOP RUN.\n"
+ " END PROGRAM argument.\n"
+ " IDENTIFICATION DIVISION.\n"
+ " PROGRAM-ID. accept.\n"
+ " PROCEDURE DIVISION.\n"
+ " STOP RUN.\n"
+ " END PROGRAM accept.\n",
+ "call_statement",
+ "COBOL programs are callable definitions, so CALL USING and MOVE references "
+ "are caller-qualified to exact program definitions",
+ "accept", "argument", "handler", "argument", "accept",
+ " IDENTIFICATION DIVISION.\n"
+ " PROGRAM-ID. bare.\n"
+ " DATA DIVISION.\n"
+ " WORKING-STORAGE SECTION.\n"
+ " 01 handler PIC 9 VALUE 1.\n"
+ " 01 result-value PIC 9 VALUE 0.\n"
+ " PROCEDURE DIVISION.\n"
+ " MOVE handler TO result-value.\n"
+ " STOP RUN.\n"
+ " END PROGRAM bare.\n",
+ "bare.cob", "bare", "handler", "bare", 1, "qualified_word", "handler", 1, 1, 1,
+ 0);
+
+SEMANTIC_CASE(verilog, VERILOG, "main.sv",
+ "module sample;\n"
+ "function integer handler(input integer value); handler = value; endfunction\n"
+ "function integer accept(input integer value); accept = value; endfunction\n"
+ "function integer argument(input integer handler); argument = accept(handler); "
+ "endfunction\n"
+ "function integer direct(); direct = handler(0); endfunction\n"
+ "function integer bare(input integer handler); bare = handler; endfunction\n"
+ "endmodule\n",
+ "handler", "function_subroutine_call", 2, 2);
+
+SEMANTIC_CASE(emacslisp, EMACSLISP, "main.el",
+ "(defun handler () 0)\n"
+ "(defun accept (value) value)\n"
+ "(defun argument (handler) (accept handler))\n"
+ "(defun direct () (handler))\n"
+ "(defun bare (handler) handler)\n",
+ "handler", "list", 7, 2);
+
+NATIVE_SCOPE_CASE(makefile, MAKEFILE, "Makefile",
+ "handler := watched\nargument := $(info $(handler))\n", "function_call",
+ "Make functions are macro expansions attached to variables rather than user "
+ "callable bodies, so variable references use exact global counts",
+ "info", NULL, "handler", NULL, NULL, "handler := watched\nbare := $(handler)\n",
+ "Bare.mk", NULL, "handler", NULL, 1, "variable_reference", "$(handler)", 1, 1, 1,
+ 0);
+
+SEMANTIC_CASE(cmake, CMAKE, "CMakeLists.txt",
+ "function(handler)\nendfunction()\n"
+ "function(accept value)\nendfunction()\n"
+ "function(argument handler)\n accept(${handler})\nendfunction()\n"
+ "function(direct)\n handler()\nendfunction()\n"
+ "function(bare handler)\n set(result ${handler})\nendfunction()\n",
+ "handler", "normal_command", 3, 3);
+
+NATIVE_SCOPE_CASE(meson, MESON, "meson.build", "watched = 'value'\nmessage(watched)\n",
+ "normal_command",
+ "Meson normal commands call built-ins and provide no named user callable body, "
+ "so assignment references use exact global counts",
+ "message", NULL, "watched", NULL, NULL, "watched = 'value'\nbare = watched\n",
+ "bare.build", NULL, "watched", NULL, 1, "identifier", "watched", 2, 2, 1, 0);
+
+SEMANTIC_CASE(glsl, GLSL, "main.glsl",
+ "int handler() { return 0; }\n"
+ "int accept(int value) { return value; }\n"
+ "int argument(int handler) { return accept(handler); }\n"
+ "int direct() { return handler(); }\n"
+ "int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(matlab, MATLAB, "main.m",
+ "function out = handler()\n out = 0;\nend\n"
+ "function out = accept(value)\n out = value;\nend\n"
+ "function out = argument(handler)\n out = accept(handler);\nend\n"
+ "function out = direct()\n out = handler();\nend\n"
+ "function out = bare(handler)\n out = handler;\nend\n",
+ "handler", "function_call", 2, 2);
+
+SEMANTIC_CASE(lean, LEAN, "Main.lean",
+ "def handler (value : Nat) : Nat := value\n"
+ "def accept (value : Nat) : Nat := value\n"
+ "def argument (handler : Nat) : Nat := accept handler\n"
+ "def direct (value : Nat) : Nat := handler value\n"
+ "def bare (handler : Nat) : Nat := handler\n",
+ "handler", "apply", 2, 2);
+
+SEMANTIC_CASE(form, FORM, "main.frm",
+ "#procedure handler()\n id out = 0;\n#endprocedure\n"
+ "#procedure accept(value)\n id out = value;\n#endprocedure\n"
+ "#procedure argument(handler)\n #call accept(handler)\n#endprocedure\n"
+ "#procedure direct()\n #call handler()\n#endprocedure\n"
+ "#procedure bare(handler)\n id out = handler;\n#endprocedure\n",
+ "handler", "call_statement", 2, 2);
+
+SEMANTIC_CASE(magma, MAGMA, "main.magma",
+ "function handler()\n return 0;\nend function;\n"
+ "function accept(value)\n return value;\nend function;\n"
+ "function argument(handler)\n return accept(handler);\nend function;\n"
+ "function direct()\n return handler();\nend function;\n"
+ "function bare(handler)\n return handler;\nend function;\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(wolfram, WOLFRAM, "main.wl",
+ "handler[] := 0\n"
+ "accept[value_] := value\n"
+ "argument[handler_] := accept[handler]\n"
+ "direct[] := handler[]\n"
+ "bare[handler_] := handler\n",
+ "handler", "apply", 7, 2);
+
+SEMANTIC_CASE(solidity, SOLIDITY, "Main.sol",
+ "pragma solidity ^0.8.0;\ncontract Sample {\n"
+ "function handler() internal pure returns (uint) { return 0; }\n"
+ "function accept(uint value) internal pure returns (uint) { return value; }\n"
+ "function argument(uint handler) internal pure returns (uint) { return "
+ "accept(handler); }\n"
+ "function direct() internal pure returns (uint) { return handler(); }\n"
+ "function bare(uint handler) internal pure returns (uint) { return handler; }\n}\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(typst, TYPST, "main.typ",
+ "#let handler() = 0\n"
+ "#let accept(value) = value\n"
+ "#let argument(handler) = accept(handler)\n"
+ "#let direct() = handler()\n"
+ "#let bare(handler) = handler\n",
+ "handler", "call", 7, 2);
+
+SEMANTIC_CASE(gdscript, GDSCRIPT, "main.gd",
+ "func handler():\n return 0\n"
+ "func accept(value):\n return value\n"
+ "func argument(handler):\n return accept(handler)\n"
+ "func direct():\n return handler()\n"
+ "func bare(handler):\n return handler\n",
+ "handler", "call", 2, 2);
+
+SEMANTIC_CASE(gleam, GLEAM, "main.gleam",
+ "fn handler() { 0 }\n"
+ "fn accept(value: Int) { value }\n"
+ "fn argument(handler: Int) { accept(handler) }\n"
+ "fn direct() { handler() }\n"
+ "fn bare(handler: Int) { handler }\n",
+ "handler", "function_call", 2, 2);
+
+SEMANTIC_CASE(powershell, POWERSHELL, "main.ps1",
+ "function handler {\n return 0\n}\n"
+ "function accept {\n param($value)\n return $value\n}\n"
+ "function argument {\n param($handler)\n accept $handler\n}\n"
+ "function direct {\n handler\n}\n"
+ "function bare {\n param($handler)\n return $handler\n}\n",
+ "$handler", "command", 2, 2);
+
+SEMANTIC_CASE(pascal, PASCAL, "main.pas",
+ "program Sample;\n"
+ "function handler: Integer; begin handler := 0; end;\n"
+ "function accept(value: Integer): Integer; begin accept := value; end;\n"
+ "function argument(handler: Integer): Integer; begin argument := accept(handler); "
+ "end;\n"
+ "function direct: Integer; begin direct := handler(); end;\n"
+ "function bare(handler: Integer): Integer; begin bare := handler; end;\n"
+ "begin end.\n",
+ "handler", "exprCall", 2, 2);
+
+SEMANTIC_CASE(dlang, DLANG, "main.d",
+ "int handler() { return 0; }\n"
+ "int accept(int value) { return value; }\n"
+ "int argument(int handler) { return accept(handler); }\n"
+ "int direct() { return handler(); }\n"
+ "int bare(int handler) { return handler; }\n",
+ "handler", "call_expression", 2, 2);
+
+SEMANTIC_CASE(scheme, SCHEME, "main.scm",
+ "(define (handler) 0)\n"
+ "(define (accept value) value)\n"
+ "(define (argument handler) (accept handler))\n"
+ "(define (direct) (handler))\n"
+ "(define (bare handler) handler)\n",
+ "handler", "list", 12, 2);
+
+SEMANTIC_CASE(fennel, FENNEL, "main.fnl",
+ "(fn handler [] 0)\n"
+ "(fn accept [value] value)\n"
+ "(fn argument [handler] (accept handler))\n"
+ "(fn direct [] (handler))\n"
+ "(fn bare [handler] handler)\n",
+ "handler", "list", 2, 2);
+
+SEMANTIC_CASE(fish, FISH, "main.fish",
+ "function handler\n return 0\nend\n"
+ "function accept --argument value\n echo $value\nend\n"
+ "function argument --argument handler\n accept $handler\nend\n"
+ "function direct\n handler\nend\n"
+ "function bare --argument handler\n echo $handler\nend\n",
+ "handler", "command", 4, 4);
+
+SEMANTIC_BROAD_CASE(awk, AWK, "main.awk",
+ "function handler() { return 0 }\n"
+ "function accept(value) { return value }\n"
+ "function argument(handler) { return accept(handler) }\n"
+ "function direct() { return handler() }\n"
+ "function bare(handler) { return handler }\n",
+ "handler", "func_call", 2, 2, "function scope(watched) { print watched }\n",
+ "Scope.awk", "scope", "watched", "command", 0, NULL, 0);
+
+SEMANTIC_CASE(zsh, ZSH, "main.zsh",
+ "handler() { return 0 }\n"
+ "accept() { print -- $1 }\n"
+ "argument() { local handler=$1; accept $handler }\n"
+ "direct() { handler }\n"
+ "bare() { local handler=$1; print -- $handler }\n",
+ "handler", "command", 5, 4);
+
+SEMANTIC_CASE(tcl, TCL, "main.tcl",
+ "proc handler {} { return 0 }\n"
+ "proc accept {value} { return $value }\n"
+ "proc argument {handler} { return [accept $handler] }\n"
+ "proc direct {} { return [handler] }\n"
+ "proc bare {handler} { return $handler }\n",
+ "$handler", "command", 7, 2);
+
+SEMANTIC_CASE(ada, ADA, "main.adb",
+ "package body Sample is\n"
+ " function handler(value : Integer) return Integer is begin return value; end "
+ "handler;\n"
+ " function accept(value : Integer) return Integer is begin return value; end "
+ "accept;\n"
+ " function argument(handler : Integer) return Integer is begin return "
+ "accept(handler); end argument;\n"
+ " function direct return Integer is begin return handler(0); end direct;\n"
+ " function bare(handler : Integer) return Integer is begin return handler; end "
+ "bare;\n"
+ "end Sample;\n",
+ "handler", "function_call", 2, 2);
+
+SEMANTIC_CASE(agda, AGDA, "Main.agda",
+ "module Main where\n"
+ "open import Agda.Builtin.Nat\n"
+ "handler : Nat -> Nat\nhandler value = value\n"
+ "accept : Nat -> Nat\naccept value = value\n"
+ "argument : Nat -> Nat\nargument handler = accept handler\n"
+ "direct : Nat -> Nat\ndirect value = handler value\n"
+ "bare : Nat -> Nat\nbare handler = handler\n",
+ "handler", "expr", 15, 2);
+
+#define MATRIX_A_CASES(X) \
+ X(go) \
+ X(python) \
+ X(javascript) \
+ X(typescript) \
+ X(tsx) \
+ X(rust) \
+ X(java) \
+ X(cpp) \
+ X(csharp) \
+ X(php) \
+ X(lua) \
+ X(scala) \
+ X(kotlin) \
+ X(ruby) \
+ X(c) \
+ X(bash) \
+ X(zig) \
+ X(elixir) \
+ X(haskell) \
+ X(ocaml) \
+ X(objc) \
+ X(swift) \
+ X(dart) \
+ X(perl) \
+ X(groovy) \
+ X(erlang) \
+ X(r) \
+ X(css) \
+ X(scss) \
+ X(hcl) \
+ X(sql) \
+ X(clojure) \
+ X(fsharp) \
+ X(julia) \
+ X(vimscript) \
+ X(nix) \
+ X(commonlisp) \
+ X(elm) \
+ X(fortran) \
+ X(cuda) \
+ X(cobol) \
+ X(verilog) \
+ X(emacslisp) \
+ X(makefile) \
+ X(cmake) \
+ X(meson) \
+ X(glsl) \
+ X(matlab) \
+ X(lean) \
+ X(form) \
+ X(magma) \
+ X(wolfram) \
+ X(solidity) \
+ X(typst) \
+ X(gdscript) \
+ X(gleam) \
+ X(powershell) \
+ X(pascal) \
+ X(dlang) \
+ X(scheme) \
+ X(fennel) \
+ X(fish) \
+ X(awk) \
+ X(zsh) \
+ X(tcl) \
+ X(ada) \
+ X(agda)
+
+#define DEFINE_MATRIX_TEST(tag_) \
+ TEST(repro_call_argument_matrix_a_##tag_) { \
+ int failures = check_matrix_case(&CASE_##tag_); \
+ ASSERT_EQ(failures, 0); \
+ PASS(); \
+ }
+
+MATRIX_A_CASES(DEFINE_MATRIX_TEST)
+
+#define MATRIX_CASE_POINTER(tag_) &CASE_##tag_,
+static const MatrixCase *const MATRIX_A_CASE_ROWS[] = {MATRIX_A_CASES(MATRIX_CASE_POINTER)};
+#undef MATRIX_CASE_POINTER
+
+_Static_assert(sizeof(MATRIX_A_CASE_ROWS) / sizeof(MATRIX_A_CASE_ROWS[0]) == 67,
+ "GO..AGDA call-capable matrix must contain exactly 67 language rows");
+
+size_t repro_call_argument_matrix_a_copy_language_ids(CBMLanguage *language_ids, size_t capacity) {
+ size_t row_count = sizeof(MATRIX_A_CASE_ROWS) / sizeof(MATRIX_A_CASE_ROWS[0]);
+ for (size_t row = 0; language_ids && row < row_count && row < capacity; row++) {
+ language_ids[row] = MATRIX_A_CASE_ROWS[row]->language;
+ }
+ return row_count;
+}
+
+SUITE(repro_call_argument_matrix_a) {
+#define RUN_MATRIX_TEST(tag_) RUN_TEST(repro_call_argument_matrix_a_##tag_);
+ MATRIX_A_CASES(RUN_MATRIX_TEST)
+#undef RUN_MATRIX_TEST
+}
+
+#undef DEFINE_MATRIX_TEST
+#undef MATRIX_A_CASES
+#undef NATIVE_DOMAIN_CASE
+#undef NATIVE_SCOPE_CASE
+#undef SEMANTIC_BROAD_CASE
+#undef SEMANTIC_CASE
+#undef CHECK_EXACT
diff --git a/tests/repro/repro_call_argument_matrix_b.c b/tests/repro/repro_call_argument_matrix_b.c
new file mode 100644
index 000000000..803b0c535
--- /dev/null
+++ b/tests/repro/repro_call_argument_matrix_b.c
@@ -0,0 +1,1333 @@
+/*
+ * Exhaustive call-argument reproduction matrix, CBMLanguage 80..162.
+ *
+ * Every language in this numeric range whose live spec has call-node metadata
+ * owns one TEST row below. Semantic applications are exercised twice: once as
+ * a direct call argument and once as the same bare reference outside a call.
+ * This makes the call-scope suppression defect independent from reference-node
+ * vocabulary gaps. DSL and document grammars whose call metadata represents a
+ * command, dependency, directive, or other non-callback construct instead use
+ * an explicit scope-safety/non-applicability control. ObjectScript Studio
+ * Export is intentionally absent: it is a transform-only input that is
+ * transcoded to ObjectScript UDL before grammar extraction.
+ */
+#include "test_framework.h"
+#include "cbm.h"
+#include "lang_specs.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+
+size_t repro_call_argument_matrix_b_copy_language_ids(CBMLanguage *language_ids, size_t capacity);
+
+typedef struct {
+ const char *tag;
+ CBMLanguage language;
+ const char *filename;
+ const char *reason;
+} CaseIdentity;
+
+typedef struct {
+ CaseIdentity identity;
+ const char *inside_source;
+ const char *bare_source;
+ const char *call_node_kind;
+ const char *caller;
+ const char *callee;
+ const char *argument;
+ int callable_definition_count;
+ int inside_total_calls;
+ int bare_total_calls;
+ int expect_lexical_local_shadow; /* routine parameters; never module/DSL rows */
+} RoutineArgumentCase;
+
+typedef struct {
+ CaseIdentity identity;
+ const char *inside_source;
+ const char *bare_source;
+ const char *call_node_kind;
+ const char *callee;
+ const char *argument;
+ int inside_total_calls;
+ int bare_total_calls;
+} ModuleArgumentCase;
+
+static int terminal_name_matches(const char *raw, const char *expected) {
+ if (!raw || !expected)
+ return 0;
+ if (strcmp(raw, expected) == 0)
+ return 1;
+
+ size_t raw_len = strlen(raw);
+ size_t expected_len = strlen(expected);
+ if (raw_len < expected_len)
+ return 0;
+ const char *tail = raw + raw_len - expected_len;
+ if (strcmp(tail, expected) != 0)
+ return 0;
+ if (tail == raw)
+ return 1;
+
+ unsigned char boundary = (unsigned char)tail[-1];
+ return !isalnum(boundary) && boundary != '_';
+}
+
+typedef enum {
+ SCOPE_ROUTINE,
+ SCOPE_EXACT,
+} ScopeMode;
+
+static int scope_matches(const char *actual, const char *expected, ScopeMode mode) {
+ if (!actual || !expected)
+ return 0;
+ if (mode == SCOPE_EXACT)
+ return strcmp(actual, expected) == 0;
+ return terminal_name_matches(actual, expected);
+}
+
+static int usage_count_scoped(const CBMFileResult *result, const char *target, const char *scope,
+ ScopeMode mode) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (terminal_name_matches(usage->ref_name, target) &&
+ scope_matches(usage->enclosing_func_qn, scope, mode))
+ count++;
+ }
+ return count;
+}
+
+static int usage_kind_count_scoped(const CBMFileResult *result, const char *target,
+ const char *scope, ScopeMode mode, CBMUsageKind kind) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == kind && terminal_name_matches(usage->ref_name, target) &&
+ scope_matches(usage->enclosing_func_qn, scope, mode)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int local_shadow_usage_count_scoped(const CBMFileResult *result, const char *target,
+ const char *scope, ScopeMode mode) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->semantic_reference_blocked &&
+ usage->semantic_reference_local_shadow &&
+ terminal_name_matches(usage->ref_name, target) &&
+ scope_matches(usage->enclosing_func_qn, scope, mode)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int call_count_scoped(const CBMFileResult *result, const char *target, const char *scope,
+ ScopeMode mode) {
+ int count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (terminal_name_matches(call->callee_name, target) &&
+ scope_matches(call->enclosing_func_qn, scope, mode))
+ count++;
+ }
+ return count;
+}
+
+static int usage_within_call_count_scoped(const CBMFileResult *result, const char *target,
+ const char *scope, ScopeMode mode, const char *callee) {
+ int count = 0;
+ for (int u = 0; u < result->usages.count; u++) {
+ const CBMUsage *usage = &result->usages.items[u];
+ if (!terminal_name_matches(usage->ref_name, target) ||
+ !scope_matches(usage->enclosing_func_qn, scope, mode) ||
+ usage->site_end_byte <= usage->site_start_byte) {
+ continue;
+ }
+ for (int c = 0; c < result->calls.count; c++) {
+ const CBMCall *call = &result->calls.items[c];
+ if (!terminal_name_matches(call->callee_name, callee) ||
+ !scope_matches(call->enclosing_func_qn, scope, mode) ||
+ call->source_origin != usage->source_origin ||
+ call->site_end_byte <= call->site_start_byte) {
+ continue;
+ }
+ if (usage->site_start_byte >= call->site_start_byte &&
+ usage->site_end_byte <= call->site_end_byte) {
+ count++;
+ }
+ }
+ }
+ return count;
+}
+
+static int callable_definition_count(const CBMFileResult *result, const char *target) {
+ int count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ int callable_label = definition->label && (strcmp(definition->label, "Function") == 0 ||
+ strcmp(definition->label, "Method") == 0);
+ if (callable_label && terminal_name_matches(definition->name, target) &&
+ terminal_name_matches(definition->qualified_name, target))
+ count++;
+ }
+ return count;
+}
+
+static const char *checked_callable_qn(const CaseIdentity *identity, const char *variant,
+ const CBMFileResult *result, const char *target,
+ int *failures) {
+ const char *qualified_name = NULL;
+ int count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ int callable_label = definition->label && (strcmp(definition->label, "Function") == 0 ||
+ strcmp(definition->label, "Method") == 0);
+ if (!callable_label || !terminal_name_matches(definition->name, target) ||
+ !terminal_name_matches(definition->qualified_name, target))
+ continue;
+ qualified_name = definition->qualified_name;
+ count++;
+ }
+ if (count == 1 && qualified_name && qualified_name[0])
+ return qualified_name;
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s "
+ "invariant=callable_qualified_name expected=1 actual=%d reason=%s\n",
+ identity->tag, variant, count, identity->reason);
+ (*failures)++;
+ return "<missing-callable-qn>";
+}
+
+static void check_exact(const CaseIdentity *identity, const char *variant, const char *invariant,
+ int actual, int expected, int *failures) {
+ if (actual == expected)
+ return;
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=%s expected=%d actual=%d "
+ "reason=%s\n",
+ identity->tag, variant, invariant, expected, actual, identity->reason);
+ (*failures)++;
+}
+
+static int ast_node_kind_count(TSNode node, const char *node_kind) {
+ int count = strcmp(ts_node_type(node), node_kind) == 0 ? 1 : 0;
+ uint32_t child_count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < child_count; i++)
+ count += ast_node_kind_count(ts_node_child(node, i), node_kind);
+ return count;
+}
+
+static void check_ast_kind_present(const CaseIdentity *identity, const char *variant,
+ const char *source, const char *node_kind, int *failures) {
+ const TSLanguage *language = cbm_ts_language(identity->language);
+ TSParser *parser = ts_parser_new();
+ if (!language || !parser || !ts_parser_set_language(parser, language)) {
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=ast_parser_ready "
+ "expected=1 actual=0 reason=%s\n",
+ identity->tag, variant, identity->reason);
+ (*failures)++;
+ if (parser)
+ ts_parser_delete(parser);
+ return;
+ }
+
+ TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
+ TSNode root = tree ? ts_tree_root_node(tree) : (TSNode){0};
+ if (tree && ts_node_has_error(root)) {
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=ast_clean_parse "
+ "expected=1 actual=0 reason=%s\n",
+ identity->tag, variant, identity->reason);
+ (*failures)++;
+ }
+ int count = tree ? ast_node_kind_count(root, node_kind) : 0;
+ if (count == 0) {
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=ast_kind_present "
+ "kind=%s expected=>0 actual=0 reason=%s\n",
+ identity->tag, variant, node_kind, identity->reason);
+ (*failures)++;
+ }
+ if (tree)
+ ts_tree_delete(tree);
+ ts_parser_delete(parser);
+}
+
+static CBMFileResult *extract_source(const CaseIdentity *identity, const char *variant,
+ const char *source, int *failures) {
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), identity->language,
+ "repro", identity->filename, 0, NULL, NULL);
+ if (!result) {
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=extract_result "
+ "expected=non-null reason=%s\n",
+ identity->tag, variant, identity->reason);
+ (*failures)++;
+ return NULL;
+ }
+ if (result->has_error || result->parse_incomplete) {
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=valid_fixture "
+ "expected=clean reason=%s\n",
+ identity->tag, variant, identity->reason);
+ (*failures)++;
+ }
+ return result;
+}
+
+static const char *checked_module_qn(const CaseIdentity *identity, const char *variant,
+ const CBMFileResult *result, int *failures) {
+ if (result->module_qn && result->module_qn[0])
+ return result->module_qn;
+ fprintf(stderr,
+ " [call-argument-matrix-b] lang=%s variant=%s invariant=module_qn "
+ "expected=non-empty reason=%s\n",
+ identity->tag, variant, identity->reason);
+ (*failures)++;
+ return "<missing-module-qn>";
+}
+
+static int run_routine_argument_case(const RoutineArgumentCase *test_case) {
+ int failures = 0;
+ check_ast_kind_present(&test_case->identity, "inside-call", test_case->inside_source,
+ test_case->call_node_kind, &failures);
+ CBMFileResult *inside =
+ extract_source(&test_case->identity, "inside-call", test_case->inside_source, &failures);
+ if (inside) {
+ check_exact(&test_case->identity, "inside-call", "caller_callable_definition",
+ callable_definition_count(inside, test_case->caller),
+ test_case->callable_definition_count, &failures);
+ check_exact(&test_case->identity, "inside-call", "direct_callee_call_in_caller",
+ call_count_scoped(inside, test_case->callee, test_case->caller, SCOPE_ROUTINE),
+ 1, &failures);
+ check_exact(
+ &test_case->identity, "inside-call", "argument_usage_in_caller",
+ usage_count_scoped(inside, test_case->argument, test_case->caller, SCOPE_ROUTINE), 1,
+ &failures);
+ check_exact(&test_case->identity, "inside-call",
+ "argument_site_owned_by_direct_callee_call",
+ usage_within_call_count_scoped(inside, test_case->argument, test_case->caller,
+ SCOPE_ROUTINE, test_case->callee),
+ 1, &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_is_ordinary_usage_in_caller",
+ usage_kind_count_scoped(inside, test_case->argument, test_case->caller,
+ SCOPE_ROUTINE, CBM_USAGE_VALUE),
+ 1, &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_not_call_reference_in_caller",
+ usage_kind_count_scoped(inside, test_case->argument, test_case->caller,
+ SCOPE_ROUTINE, CBM_USAGE_CALL_REFERENCE),
+ 0, &failures);
+ if (test_case->expect_lexical_local_shadow) {
+ check_exact(&test_case->identity, "inside-call",
+ "argument_blocks_callable_promotion_in_caller",
+ local_shadow_usage_count_scoped(inside, test_case->argument,
+ test_case->caller, SCOPE_ROUTINE),
+ 1, &failures);
+ }
+ check_exact(&test_case->identity, "inside-call", "callee_not_usage_in_caller",
+ usage_count_scoped(inside, test_case->callee, test_case->caller, SCOPE_ROUTINE),
+ 0, &failures);
+ check_exact(
+ &test_case->identity, "inside-call", "argument_not_call_in_caller",
+ call_count_scoped(inside, test_case->argument, test_case->caller, SCOPE_ROUTINE), 0,
+ &failures);
+ check_exact(&test_case->identity, "inside-call", "total_calls", inside->calls.count,
+ test_case->inside_total_calls, &failures);
+ cbm_free_result(inside);
+ }
+
+ CBMFileResult *bare =
+ extract_source(&test_case->identity, "bare-reference", test_case->bare_source, &failures);
+ if (bare) {
+ check_exact(&test_case->identity, "bare-reference", "caller_callable_definition",
+ callable_definition_count(bare, test_case->caller),
+ test_case->callable_definition_count, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_usage_in_caller",
+ usage_count_scoped(bare, test_case->argument, test_case->caller, SCOPE_ROUTINE),
+ 1, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_is_ordinary_usage_in_caller",
+ usage_kind_count_scoped(bare, test_case->argument, test_case->caller,
+ SCOPE_ROUTINE, CBM_USAGE_VALUE),
+ 1, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_not_call_reference_in_caller",
+ usage_kind_count_scoped(bare, test_case->argument, test_case->caller,
+ SCOPE_ROUTINE, CBM_USAGE_CALL_REFERENCE),
+ 0, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_reference_not_call_in_caller",
+ call_count_scoped(bare, test_case->argument, test_case->caller, SCOPE_ROUTINE),
+ 0, &failures);
+ check_exact(&test_case->identity, "bare-reference", "total_calls", bare->calls.count,
+ test_case->bare_total_calls, &failures);
+ cbm_free_result(bare);
+ }
+
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_module_argument_case(const ModuleArgumentCase *test_case) {
+ int failures = 0;
+ check_ast_kind_present(&test_case->identity, "inside-call", test_case->inside_source,
+ test_case->call_node_kind, &failures);
+ CBMFileResult *inside =
+ extract_source(&test_case->identity, "inside-call", test_case->inside_source, &failures);
+ if (inside) {
+ const char *module_qn =
+ checked_module_qn(&test_case->identity, "inside-call", inside, &failures);
+ check_exact(&test_case->identity, "inside-call", "direct_callee_call_in_module",
+ call_count_scoped(inside, test_case->callee, module_qn, SCOPE_EXACT), 1,
+ &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_usage_in_module",
+ usage_count_scoped(inside, test_case->argument, module_qn, SCOPE_EXACT), 1,
+ &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_is_ordinary_usage_in_module",
+ usage_kind_count_scoped(inside, test_case->argument, module_qn, SCOPE_EXACT,
+ CBM_USAGE_VALUE),
+ 1, &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_not_call_reference_in_module",
+ usage_kind_count_scoped(inside, test_case->argument, module_qn, SCOPE_EXACT,
+ CBM_USAGE_CALL_REFERENCE),
+ 0, &failures);
+ check_exact(&test_case->identity, "inside-call", "callee_not_usage_in_module",
+ usage_count_scoped(inside, test_case->callee, module_qn, SCOPE_EXACT), 0,
+ &failures);
+ check_exact(&test_case->identity, "inside-call", "argument_not_call_in_module",
+ call_count_scoped(inside, test_case->argument, module_qn, SCOPE_EXACT), 0,
+ &failures);
+ check_exact(&test_case->identity, "inside-call", "total_calls", inside->calls.count,
+ test_case->inside_total_calls, &failures);
+ cbm_free_result(inside);
+ }
+
+ CBMFileResult *bare =
+ extract_source(&test_case->identity, "bare-reference", test_case->bare_source, &failures);
+ if (bare) {
+ const char *module_qn =
+ checked_module_qn(&test_case->identity, "bare-reference", bare, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_usage_in_module",
+ usage_count_scoped(bare, test_case->argument, module_qn, SCOPE_EXACT), 1,
+ &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_is_ordinary_usage_in_module",
+ usage_kind_count_scoped(bare, test_case->argument, module_qn, SCOPE_EXACT,
+ CBM_USAGE_VALUE),
+ 1, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_not_call_reference_in_module",
+ usage_kind_count_scoped(bare, test_case->argument, module_qn, SCOPE_EXACT,
+ CBM_USAGE_CALL_REFERENCE),
+ 0, &failures);
+ check_exact(&test_case->identity, "bare-reference", "bare_reference_not_call_in_module",
+ call_count_scoped(bare, test_case->argument, module_qn, SCOPE_EXACT), 0,
+ &failures);
+ check_exact(&test_case->identity, "bare-reference", "total_calls", bare->calls.count,
+ test_case->bare_total_calls, &failures);
+ cbm_free_result(bare);
+ }
+
+ return failures == 0 ? 0 : 1;
+}
+
+/* Synthetic Lisp application; Racket's reference nodes are not yet in the
+ * usage vocabulary, so both sources are independently RED. */
+static const char RACKET_INSIDE[] = "#lang racket\n"
+ "(define (accept value) value)\n"
+ "(define (run watched) (accept watched))\n";
+static const char RACKET_BARE[] = "#lang racket\n"
+ "(define (run watched) watched)\n";
+
+static const char ODIN_INSIDE[] = "package sample\n"
+ "accept :: proc(value: int) -> int { return value }\n"
+ "run :: proc(watched: int) -> int { return accept(watched) }\n";
+static const char ODIN_BARE[] = "package sample\n"
+ "run :: proc(watched: int) -> int { return watched }\n";
+
+static const char RESCRIPT_INSIDE[] = "let accept = value => value\n"
+ "let run = watched => accept(watched)\n";
+static const char RESCRIPT_BARE[] = "let run = watched => watched\n";
+
+static const char PURESCRIPT_INSIDE[] = "module Main where\n"
+ "accept value = value\n"
+ "run watched = accept watched\n";
+static const char PURESCRIPT_BARE[] = "module Main where\n"
+ "run watched = watched\n";
+
+static const char NICKEL_INSIDE[] = "let accept = fun value => value in\n"
+ "let run = fun watched => accept watched in\n"
+ "run\n";
+static const char NICKEL_BARE[] = "let run = fun watched => watched in\n"
+ "run\n";
+
+static const char CRYSTAL_INSIDE[] = "def accept(value)\n"
+ " value\n"
+ "end\n"
+ "def run(watched)\n"
+ " accept(watched)\n"
+ "end\n";
+static const char CRYSTAL_BARE[] = "def run(watched)\n"
+ " watched\n"
+ "end\n";
+
+static const char LUA_TYPED_INSIDE[] = "local function accept(value: number): number\n"
+ " return value\n"
+ "end\n"
+ "local function run(watched: number): number\n"
+ " return accept(watched)\n"
+ "end\n";
+static const char LUA_TYPED_BARE[] = "local function run(watched: number): number\n"
+ " return watched\n"
+ "end\n";
+
+static const char HARE_INSIDE[] = "fn accept(value: int) int = {\n"
+ "\treturn value;\n"
+ "};\n"
+ "fn run(watched: int) int = {\n"
+ "\treturn accept(watched);\n"
+ "};\n";
+static const char HARE_BARE[] = "fn run(watched: int) int = {\n"
+ "\treturn watched;\n"
+ "};\n";
+
+static const char PONY_INSIDE[] = "class Calculator\n"
+ " fun accept(value: I32): I32 => value\n"
+ " fun run(watched: I32): I32 => accept(watched)\n";
+static const char PONY_BARE[] = "class Calculator\n"
+ " fun run(watched: I32): I32 => watched\n";
+
+static const char SWAY_INSIDE[] = "fn accept(value: u64) -> u64 {\n"
+ " value\n"
+ "}\n"
+ "fn run(watched: u64) -> u64 {\n"
+ " accept(watched)\n"
+ "}\n";
+static const char SWAY_BARE[] = "fn run(watched: u64) -> u64 {\n"
+ " watched\n"
+ "}\n";
+
+/* NASM actual_instruction is synthetic call metadata. A real call is valid;
+ * mov must not be promoted to a call merely because it shares that boundary. */
+static const char NASM_SCOPE[] = "section .text\n"
+ "accept:\n"
+ " ret\n"
+ "run:\n"
+ " mov rax, rbx\n"
+ " call accept\n"
+ " ret\n";
+/* NASM function-like macros use the grammar's call_syntax_expression form. */
+static const char NASM_CALL_SYNTAX[] = "%define accept(value) value\n"
+ "dd accept(7)\n";
+
+/* Just expressions support built-in function calls over identifier values. */
+static const char JUST_INSIDE[] = "watched := \"value\"\n"
+ "result := uppercase(watched)\n"
+ "show:\n"
+ " @echo {{result}}\n";
+static const char JUST_BARE[] = "watched := \"value\"\n"
+ "result := watched\n"
+ "show:\n"
+ " @echo {{result}}\n";
+static const char JUST_DEPENDENCY[] = "build:\n"
+ " @echo build\n"
+ "test: build\n"
+ " @echo test\n";
+
+/* Go-template function calls have pipeline values, not function-object
+ * callback syntax. Keep the semantic printf call and reject a fabricated call
+ * to the field argument. */
+static const char GOTEMPLATE_INSIDE[] = "{{ printf \"%s\" .Watched }}\n";
+static const char GOTEMPLATE_BARE[] = "{{ .Watched }}\n";
+
+static const char TEMPL_INSIDE[] = "package sample\n"
+ "func accept(value string) string {\n"
+ " return value\n"
+ "}\n"
+ "func run(watched string) string {\n"
+ " return accept(watched)\n"
+ "}\n";
+static const char TEMPL_BARE[] = "package sample\n"
+ "func run(watched string) string {\n"
+ " return watched\n"
+ "}\n";
+
+/* Prisma call expressions are schema defaults, not higher-order application. */
+static const char PRISMA_SCOPE[] = "model Event {\n"
+ " id Int @id\n"
+ " createdAt DateTime @default(now())\n"
+ "}\n";
+
+/* Diff command nodes are patch records and must never fabricate code calls. */
+static const char DIFF_SCOPE[] = "diff --git a/main.c b/main.c\n"
+ "index 1111111..2222222 100644\n"
+ "--- a/main.c\n"
+ "+++ b/main.c\n"
+ "@@ -1 +1 @@\n"
+ "-old\n"
+ "+new\n";
+
+static const char WGSL_INSIDE[] = "fn accept(value: f32) -> f32 {\n"
+ " return value;\n"
+ "}\n"
+ "fn run(watched: f32) -> f32 {\n"
+ " return accept(watched);\n"
+ "}\n";
+static const char WGSL_BARE[] = "fn run(watched: f32) -> f32 {\n"
+ " return watched;\n"
+ "}\n";
+
+static const char JSONNET_INSIDE[] = "local accept(value) = value;\n"
+ "local run(watched) = accept(watched);\n"
+ "run\n";
+static const char JSONNET_BARE[] = "local run(watched) = watched;\n"
+ "run\n";
+
+/* BibTeX command nodes are document syntax and have no callable semantics. */
+static const char BIBTEX_SCOPE[] = "@book{sample,\n"
+ " title = {Using \\LaTeX{} Today},\n"
+ " year = {2026}\n"
+ "}\n";
+
+static const char STARLARK_INSIDE[] = "def accept(value):\n"
+ " return value\n"
+ "def run(watched):\n"
+ " return accept(watched)\n";
+static const char STARLARK_BARE[] = "def run(watched):\n"
+ " return watched\n";
+
+static const char BICEP_INSIDE[] = "func accept(value string) string => value\n"
+ "func run(watched string) string => accept(watched)\n";
+static const char BICEP_BARE[] = "func run(watched string) string => watched\n";
+
+static const char HLSL_FAMILY_INSIDE[] = "float accept(float value) {\n"
+ " return value;\n"
+ "}\n"
+ "float run(float watched) {\n"
+ " return accept(watched);\n"
+ "}\n";
+static const char HLSL_FAMILY_BARE[] = "float run(float watched) {\n"
+ " return watched;\n"
+ "}\n";
+
+static const char VHDL_INSIDE[] = "package sample is\n"
+ " function accept(value : integer) return integer;\n"
+ " function run(watched : integer) return integer;\n"
+ "end package;\n"
+ "package body sample is\n"
+ " function accept(value : integer) return integer is\n"
+ " begin\n"
+ " return value;\n"
+ " end function;\n"
+ " function run(watched : integer) return integer is\n"
+ " begin\n"
+ " return accept(watched);\n"
+ " end function;\n"
+ "end package body;\n";
+static const char VHDL_BARE[] = "package sample is\n"
+ " function run(watched : integer) return integer;\n"
+ "end package;\n"
+ "package body sample is\n"
+ " function run(watched : integer) return integer is\n"
+ " begin\n"
+ " return watched;\n"
+ " end function;\n"
+ "end package body;\n";
+
+static const char SYSTEMVERILOG_INSIDE[] = "module sample;\n"
+ " function automatic int accept(int value);\n"
+ " return value;\n"
+ " endfunction\n"
+ " function automatic int run(int watched);\n"
+ " return accept(watched);\n"
+ " endfunction\n"
+ "endmodule\n";
+static const char SYSTEMVERILOG_BARE[] = "module sample;\n"
+ " function automatic int run(int watched);\n"
+ " return watched;\n"
+ " endfunction\n"
+ "endmodule\n";
+
+/* DeviceTree has call_expression metadata for macro-like constructs, but the
+ * native property/reference form below has no function-object application. */
+static const char DEVICETREE_SCOPE[] = "/dts-v1/;\n"
+ "/ {\n"
+ " sample {\n"
+ " clock-frequency = <MHZ(24)>;\n"
+ " };\n"
+ "};\n";
+
+/* Linker-script built-ins do accept symbols. This is a vocabulary-gap test,
+ * not a claim that linker scripts support callbacks. */
+static const char LINKERSCRIPT_INSIDE[] = "SECTIONS {\n"
+ " . = ABSOLUTE(_start);\n"
+ "}\n";
+static const char LINKERSCRIPT_BARE[] = "SECTIONS {\n"
+ " . = _start;\n"
+ "}\n";
+
+/* GN is a build DSL, but its assert() call has a true value argument. */
+static const char GN_INSIDE[] = "watched = true\n"
+ "assert(watched)\n";
+static const char GN_BARE[] = "watched = true\n"
+ "copied = watched\n";
+
+static const char BITBAKE_DOMAIN[] = "python do_run() {\n"
+ " bb.note('ready')\n"
+ "}\n";
+
+static const char CAIRO_INSIDE[] = "fn accept(value: felt252) -> felt252 {\n"
+ " value\n"
+ "}\n"
+ "fn run(watched: felt252) -> felt252 {\n"
+ " accept(watched)\n"
+ "}\n";
+static const char CAIRO_BARE[] = "fn run(watched: felt252) -> felt252 {\n"
+ " watched\n"
+ "}\n";
+
+static const char MOVE_INSIDE[] = "module 0x1::sample {\n"
+ " fun accept(value: u64) {\n"
+ " }\n"
+ " fun run(watched: u64) {\n"
+ " accept(watched);\n"
+ " }\n"
+ "}\n";
+static const char MOVE_BARE[] = "module 0x1::sample {\n"
+ " fun run(watched: u64): u64 {\n"
+ " return watched;\n"
+ " }\n"
+ "}\n";
+
+static const char SQUIRREL_INSIDE[] = "function accept(value) {\n"
+ " return value;\n"
+ "}\n"
+ "function run(watched) {\n"
+ " return accept(watched);\n"
+ "}\n";
+static const char SQUIRREL_BARE[] = "function run(watched) {\n"
+ " return watched;\n"
+ "}\n";
+
+static const char FUNC_INSIDE[] = "int accept(int value) {\n"
+ " return value;\n"
+ "}\n"
+ "int run(int watched) {\n"
+ " return accept(watched);\n"
+ "}\n";
+static const char FUNC_BARE[] = "int run(int watched) {\n"
+ " return watched;\n"
+ "}\n";
+
+static const char PUPPET_INSIDE[] = "function accept(String $value) >> String {\n"
+ " $value\n"
+ "}\n"
+ "function run(String $watched) >> String {\n"
+ " accept($watched)\n"
+ "}\n";
+static const char PUPPET_BARE[] = "function run(String $watched) >> String {\n"
+ " $watched\n"
+ "}\n";
+
+static const char LLVM_IR_INSIDE[] = "declare void @accept(ptr)\n"
+ "define void @run(ptr %watched) {\n"
+ "entry:\n"
+ " call void @accept(ptr %watched)\n"
+ " ret void\n"
+ "}\n";
+static const char LLVM_IR_BARE[] = "define ptr @run(ptr %watched) {\n"
+ "entry:\n"
+ " ret ptr %watched\n"
+ "}\n";
+
+static const char TLAPLUS_INSIDE[] = "---- MODULE Sample ----\n"
+ "Accept(value) == value\n"
+ "Guard(values) == Accept(values)\n"
+ "====\n";
+static const char TLAPLUS_BARE[] = "---- MODULE Sample ----\n"
+ "Guard(values) == values\n"
+ "====\n";
+static const char TLAPLUS_BOUNDED_QUANTIFICATION[] =
+ "---- MODULE Bounded ----\n"
+ "Guard(values) == \\A item \\in values : item = item\n"
+ "====\n";
+
+static const char APEX_INSIDE[] = "public class Sample {\n"
+ " private static Integer accept(Integer value) {\n"
+ " return value;\n"
+ " }\n"
+ " public static Integer run(Integer watched) {\n"
+ " return accept(watched);\n"
+ " }\n"
+ "}\n";
+static const char APEX_BARE[] = "public class Sample {\n"
+ " public static Integer run(Integer watched) {\n"
+ " return watched;\n"
+ " }\n"
+ "}\n";
+
+static const char PINE_INSIDE[] = "//@version=5\n"
+ "indicator(\"Sample\")\n"
+ "accept(value) => value\n"
+ "run(watched) => accept(watched)\n";
+static const char PINE_BARE[] = "//@version=5\n"
+ "indicator(\"Sample\")\n"
+ "run(watched) => watched\n";
+
+static const char QML_INSIDE[] = "import QtQuick 2.15\n"
+ "QtObject {\n"
+ " function accept(value) { return value; }\n"
+ " function run(watched) { return accept(watched); }\n"
+ "}\n";
+static const char QML_BARE[] = "import QtQuick 2.15\n"
+ "QtObject {\n"
+ " function run(watched) { return watched; }\n"
+ "}\n";
+
+static const char CFSCRIPT_INSIDE[] = "component {\n"
+ " function accept(value) { return value; }\n"
+ " function run(watched) { return accept(watched); }\n"
+ "}\n";
+static const char CFSCRIPT_BARE[] = "component {\n"
+ " function run(watched) { return watched; }\n"
+ "}\n";
+
+static const char CFML_INSIDE[] = "<cffunction name=\"accept\">\n"
+ " <cfargument name=\"value\">\n"
+ " <cfreturn arguments.value>\n"
+ "</cffunction>\n"
+ "<cffunction name=\"run\">\n"
+ " <cfargument name=\"watched\">\n"
+ " <cfreturn accept(arguments.watched)>\n"
+ "</cffunction>\n";
+static const char CFML_BARE[] = "<cffunction name=\"run\">\n"
+ " <cfargument name=\"watched\">\n"
+ " <cfreturn arguments.watched>\n"
+ "</cffunction>\n";
+
+/* New focused Mojo fixture: native fn declarations and a value argument. */
+static const char MOJO_INSIDE[] = "fn accept(value: Int) -> Int:\n"
+ " return value\n"
+ "fn run(watched: Int) -> Int:\n"
+ " return accept(watched)\n";
+static const char MOJO_BARE[] = "fn run(watched: Int) -> Int:\n"
+ " return watched\n";
+
+static const char OBJECTSCRIPT_UDL_INSIDE[] = "Class Sample.Callbacks Extends %RegisteredObject\n"
+ "{\n"
+ "ClassMethod Accept(value As %String) As %String\n"
+ "{\n"
+ " Quit value\n"
+ "}\n"
+ "ClassMethod Run(watched As %String) As %String\n"
+ "{\n"
+ " Quit ##class(Sample.Callbacks).Accept(watched)\n"
+ "}\n"
+ "}\n";
+static const char OBJECTSCRIPT_UDL_BARE[] = "Class Sample.Callbacks Extends %RegisteredObject\n"
+ "{\n"
+ "ClassMethod Run(watched As %String) As %String\n"
+ "{\n"
+ " Quit watched\n"
+ "}\n"
+ "}\n";
+
+static const char OBJECTSCRIPT_ROUTINE_INSIDE[] = "SAMPLE\n"
+ " Quit\n"
+ "Accept(value)\n"
+ " Quit value\n"
+ "Run(watched)\n"
+ " Set result = $$Accept(watched)\n"
+ " Quit result\n";
+static const char OBJECTSCRIPT_ROUTINE_BARE[] = "SAMPLE\n"
+ " Quit\n"
+ "Run(watched)\n"
+ " Quit watched\n";
+
+#define ROUTINE_ARGUMENT_CASE(tag_value, language_value, filename_value, inside_value, bare_value, \
+ kind_value, caller_value, callee_value, argument_value, defs_value, \
+ inside_calls_value, bare_calls_value, reason_value) \
+ {{tag_value, language_value, filename_value, reason_value}, \
+ inside_value, \
+ bare_value, \
+ kind_value, \
+ caller_value, \
+ callee_value, \
+ argument_value, \
+ defs_value, \
+ inside_calls_value, \
+ bare_calls_value, \
+ 1}
+
+#define MODULE_ARGUMENT_CASE(tag_value, language_value, filename_value, inside_value, bare_value, \
+ kind_value, callee_value, argument_value, inside_calls_value, \
+ bare_calls_value, reason_value) \
+ {{tag_value, language_value, filename_value, reason_value}, \
+ inside_value, \
+ bare_value, \
+ kind_value, \
+ callee_value, \
+ argument_value, \
+ inside_calls_value, \
+ bare_calls_value}
+
+static const RoutineArgumentCase RACKET_CASE = ROUTINE_ARGUMENT_CASE(
+ "RACKET", CBM_LANG_RACKET, "sample.rkt", RACKET_INSIDE, RACKET_BARE, "list", "run", "accept",
+ "watched", 1, 1, 0, "Racket list application and symbol-reference vocabulary");
+static const RoutineArgumentCase ODIN_CASE = ROUTINE_ARGUMENT_CASE(
+ "ODIN", CBM_LANG_ODIN, "sample.odin", ODIN_INSIDE, ODIN_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase RESCRIPT_CASE = ROUTINE_ARGUMENT_CASE(
+ "RESCRIPT", CBM_LANG_RESCRIPT, "Sample.res", RESCRIPT_INSIDE, RESCRIPT_BARE, "call_expression",
+ "run", "accept", "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase PURESCRIPT_CASE =
+ ROUTINE_ARGUMENT_CASE("PURESCRIPT", CBM_LANG_PURESCRIPT, "Main.purs", PURESCRIPT_INSIDE,
+ PURESCRIPT_BARE, "exp_apply", "run", "accept", "watched", 1, 1, 0,
+ "PureScript application and variable-reference vocabulary");
+static const RoutineArgumentCase NICKEL_CASE = ROUTINE_ARGUMENT_CASE(
+ "NICKEL", CBM_LANG_NICKEL, "sample.ncl", NICKEL_INSIDE, NICKEL_BARE, "applicative", "run",
+ "accept", "watched", 1, 1, 0, "Nickel application and identifier-reference vocabulary");
+static const RoutineArgumentCase CRYSTAL_CASE = ROUTINE_ARGUMENT_CASE(
+ "CRYSTAL", CBM_LANG_CRYSTAL, "sample.cr", CRYSTAL_INSIDE, CRYSTAL_BARE, "call", "run", "accept",
+ "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase TEAL_CASE = ROUTINE_ARGUMENT_CASE(
+ "TEAL", CBM_LANG_TEAL, "sample.tl", LUA_TYPED_INSIDE, LUA_TYPED_BARE, "function_call", "run",
+ "accept", "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase HARE_CASE = ROUTINE_ARGUMENT_CASE(
+ "HARE", CBM_LANG_HARE, "sample.ha", HARE_INSIDE, HARE_BARE, "call_expression", "run", "accept",
+ "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase PONY_CASE = ROUTINE_ARGUMENT_CASE(
+ "PONY", CBM_LANG_PONY, "sample.pony", PONY_INSIDE, PONY_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "native method application");
+static const RoutineArgumentCase LUAU_CASE = ROUTINE_ARGUMENT_CASE(
+ "LUAU", CBM_LANG_LUAU, "sample.luau", LUA_TYPED_INSIDE, LUA_TYPED_BARE, "function_call", "run",
+ "accept", "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase SWAY_CASE = ROUTINE_ARGUMENT_CASE(
+ "SWAY", CBM_LANG_SWAY, "sample.sw", SWAY_INSIDE, SWAY_BARE, "call_expression", "run", "accept",
+ "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase TEMPL_CASE = ROUTINE_ARGUMENT_CASE(
+ "TEMPL", CBM_LANG_TEMPL, "sample.templ", TEMPL_INSIDE, TEMPL_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "embedded Go routine application");
+static const RoutineArgumentCase WGSL_CASE =
+ ROUTINE_ARGUMENT_CASE("WGSL", CBM_LANG_WGSL, "sample.wgsl", WGSL_INSIDE, WGSL_BARE,
+ "type_constructor_or_function_call_expression", "run", "accept",
+ "watched", 1, 1, 0, "native shader routine application");
+static const RoutineArgumentCase JSONNET_CASE = ROUTINE_ARGUMENT_CASE(
+ "JSONNET", CBM_LANG_JSONNET, "sample.jsonnet", JSONNET_INSIDE, JSONNET_BARE, "functioncall",
+ "run", "accept", "watched", 1, 1, 0, "native configuration-function application");
+static const RoutineArgumentCase STARLARK_CASE = ROUTINE_ARGUMENT_CASE(
+ "STARLARK", CBM_LANG_STARLARK, "BUILD", STARLARK_INSIDE, STARLARK_BARE, "call", "run", "accept",
+ "watched", 1, 1, 0, "native Starlark routine application");
+static const RoutineArgumentCase BICEP_CASE = ROUTINE_ARGUMENT_CASE(
+ "BICEP", CBM_LANG_BICEP, "sample.bicep", BICEP_INSIDE, BICEP_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "native Bicep user-function application");
+static const RoutineArgumentCase HLSL_CASE = ROUTINE_ARGUMENT_CASE(
+ "HLSL", CBM_LANG_HLSL, "sample.hlsl", HLSL_FAMILY_INSIDE, HLSL_FAMILY_BARE, "call_expression",
+ "run", "accept", "watched", 1, 1, 0, "native shader routine application");
+static const RoutineArgumentCase VHDL_CASE = ROUTINE_ARGUMENT_CASE(
+ "VHDL", CBM_LANG_VHDL, "sample.vhd", VHDL_INSIDE, VHDL_BARE, "parenthesis_group", "run",
+ "accept", "watched", 2, 1, 0, "VHDL declaration and body application");
+static const RoutineArgumentCase SYSTEMVERILOG_CASE = ROUTINE_ARGUMENT_CASE(
+ "SYSTEMVERILOG", CBM_LANG_SYSTEMVERILOG, "sample.sv", SYSTEMVERILOG_INSIDE, SYSTEMVERILOG_BARE,
+ "function_subroutine_call", "run", "accept", "watched", 1, 1, 0,
+ "native hardware-description routine application");
+static const RoutineArgumentCase ISPC_CASE = ROUTINE_ARGUMENT_CASE(
+ "ISPC", CBM_LANG_ISPC, "sample.ispc", HLSL_FAMILY_INSIDE, HLSL_FAMILY_BARE, "call_expression",
+ "run", "accept", "watched", 1, 1, 0, "native SPMD routine application");
+static const RoutineArgumentCase CAIRO_CASE = ROUTINE_ARGUMENT_CASE(
+ "CAIRO", CBM_LANG_CAIRO, "sample.cairo", CAIRO_INSIDE, CAIRO_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "native smart-contract routine application");
+static const RoutineArgumentCase MOVE_CASE = ROUTINE_ARGUMENT_CASE(
+ "MOVE", CBM_LANG_MOVE, "sample.move", MOVE_INSIDE, MOVE_BARE, "call_expression", "run",
+ "accept", "watched", 1, 1, 0, "native smart-contract routine application");
+static const RoutineArgumentCase SQUIRREL_CASE = ROUTINE_ARGUMENT_CASE(
+ "SQUIRREL", CBM_LANG_SQUIRREL, "sample.nut", SQUIRREL_INSIDE, SQUIRREL_BARE, "call_expression",
+ "run", "accept", "watched", 1, 1, 0, "native routine application");
+static const RoutineArgumentCase FUNC_CASE = ROUTINE_ARGUMENT_CASE(
+ "FUNC", CBM_LANG_FUNC, "sample.fc", FUNC_INSIDE, FUNC_BARE, "function_application", "run",
+ "accept", "watched", 1, 1, 0, "native FunC function application");
+static const RoutineArgumentCase PUPPET_CASE = ROUTINE_ARGUMENT_CASE(
+ "PUPPET", CBM_LANG_PUPPET, "sample.pp", PUPPET_INSIDE, PUPPET_BARE, "function_call", "run",
+ "accept", "watched", 1, 1, 0, "Puppet function application and variable-reference vocabulary");
+static const RoutineArgumentCase SLANG_CASE = ROUTINE_ARGUMENT_CASE(
+ "SLANG", CBM_LANG_SLANG, "sample.slang", HLSL_FAMILY_INSIDE, HLSL_FAMILY_BARE,
+ "call_expression", "run", "accept", "watched", 1, 1, 0, "native shader routine application");
+static const RoutineArgumentCase LLVM_IR_CASE = ROUTINE_ARGUMENT_CASE(
+ "LLVM_IR", CBM_LANG_LLVM_IR, "sample.ll", LLVM_IR_INSIDE, LLVM_IR_BARE, "call", "run", "accept",
+ "watched", 1, 1, 0, "LLVM call instruction and local_var reference vocabulary");
+static const RoutineArgumentCase TLAPLUS_CASE = ROUTINE_ARGUMENT_CASE(
+ "TLAPLUS", CBM_LANG_TLAPLUS, "Sample.tla", TLAPLUS_INSIDE, TLAPLUS_BARE, "bound_op", "Guard",
+ "Accept", "values", 1, 1, 0, "TLA+ operator application with a value argument");
+static const RoutineArgumentCase APEX_CASE = ROUTINE_ARGUMENT_CASE(
+ "APEX", CBM_LANG_APEX, "Sample.cls", APEX_INSIDE, APEX_BARE, "method_invocation", "run",
+ "accept", "watched", 1, 1, 0, "native method application");
+static const RoutineArgumentCase PINE_CASE = ROUTINE_ARGUMENT_CASE(
+ "PINE", CBM_LANG_PINE, "sample.pine", PINE_INSIDE, PINE_BARE, "call", "run", "accept",
+ "watched", 1, 2, 1, "Pine has one module-level indicator call in each fixture");
+static const RoutineArgumentCase QML_CASE = ROUTINE_ARGUMENT_CASE(
+ "QML", CBM_LANG_QML, "Sample.qml", QML_INSIDE, QML_BARE, "call_expression", "run", "accept",
+ "watched", 1, 1, 0, "native QML JavaScript routine application");
+static const RoutineArgumentCase CFSCRIPT_CASE = ROUTINE_ARGUMENT_CASE(
+ "CFSCRIPT", CBM_LANG_CFSCRIPT, "Sample.cfc", CFSCRIPT_INSIDE, CFSCRIPT_BARE, "call_expression",
+ "run", "accept", "watched", 1, 1, 0, "native CFScript routine application");
+static const RoutineArgumentCase CFML_CASE = ROUTINE_ARGUMENT_CASE(
+ "CFML", CBM_LANG_CFML, "sample.cfm", CFML_INSIDE, CFML_BARE, "call_expression", "run", "accept",
+ "watched", 1, 1, 0, "native CFML tag-routine application");
+static const RoutineArgumentCase MOJO_CASE =
+ ROUTINE_ARGUMENT_CASE("MOJO", CBM_LANG_MOJO, "sample.mojo", MOJO_INSIDE, MOJO_BARE, "call",
+ "run", "accept", "watched", 1, 1, 0, "native Mojo routine application");
+static const RoutineArgumentCase OBJECTSCRIPT_UDL_CASE = ROUTINE_ARGUMENT_CASE(
+ "OBJECTSCRIPT_UDL", CBM_LANG_OBJECTSCRIPT_UDL, "Sample.cls", OBJECTSCRIPT_UDL_INSIDE,
+ OBJECTSCRIPT_UDL_BARE, "class_method_call", "Run", "Accept", "watched", 1, 1, 0,
+ "ObjectScript UDL class-method application with a value argument");
+static const RoutineArgumentCase OBJECTSCRIPT_ROUTINE_CASE = ROUTINE_ARGUMENT_CASE(
+ "OBJECTSCRIPT_ROUTINE", CBM_LANG_OBJECTSCRIPT_ROUTINE, "Sample.mac",
+ OBJECTSCRIPT_ROUTINE_INSIDE, OBJECTSCRIPT_ROUTINE_BARE, "extrinsic_function", "Run", "Accept",
+ "watched", 1, 1, 0, "ObjectScript routine extrinsic application with a value argument");
+
+static const ModuleArgumentCase JUST_CASE = MODULE_ARGUMENT_CASE(
+ "JUST", CBM_LANG_JUST, "justfile", JUST_INSIDE, JUST_BARE, "function_call", "uppercase",
+ "watched", 1, 0, "Just expression call; recipe dependency is checked separately");
+static const ModuleArgumentCase GOTEMPLATE_CASE =
+ MODULE_ARGUMENT_CASE("GOTEMPLATE", CBM_LANG_GOTEMPLATE, "sample.tmpl", GOTEMPLATE_INSIDE,
+ GOTEMPLATE_BARE, "function_call", "printf", "Watched", 1, 0,
+ "Go-template pipeline value and paired bare field reference");
+static const ModuleArgumentCase LINKERSCRIPT_CASE =
+ MODULE_ARGUMENT_CASE("LINKERSCRIPT", CBM_LANG_LINKERSCRIPT, "sample.ld", LINKERSCRIPT_INSIDE,
+ LINKERSCRIPT_BARE, "call_expression", "ABSOLUTE", "_start", 1, 0,
+ "linker built-in argument and symbol-reference vocabulary");
+static const ModuleArgumentCase GN_CASE =
+ MODULE_ARGUMENT_CASE("GN", CBM_LANG_GN, "BUILD.gn", GN_INSIDE, GN_BARE, "call_expression",
+ "assert", "watched", 1, 0, "GN expression function with a value argument");
+
+#undef MODULE_ARGUMENT_CASE
+#undef ROUTINE_ARGUMENT_CASE
+
+static int run_no_call_domain(const CaseIdentity *identity, const char *source,
+ const char *node_kind) {
+ int failures = 0;
+ check_ast_kind_present(identity, "domain-negative", source, node_kind, &failures);
+ CBMFileResult *result = extract_source(identity, "domain-negative", source, &failures);
+ if (result) {
+ check_exact(identity, "domain-negative", "total_calls", result->calls.count, 0, &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_module_domain_call(const CaseIdentity *identity, const char *source,
+ const char *node_kind, const char *callee) {
+ int failures = 0;
+ check_ast_kind_present(identity, "domain-call", source, node_kind, &failures);
+ CBMFileResult *result = extract_source(identity, "domain-call", source, &failures);
+ if (result) {
+ const char *module_qn = checked_module_qn(identity, "domain-call", result, &failures);
+ check_exact(identity, "domain-call", "callee_call_in_module",
+ call_count_scoped(result, callee, module_qn, SCOPE_EXACT), 1, &failures);
+ check_exact(identity, "domain-call", "callee_not_usage_in_module",
+ usage_count_scoped(result, callee, module_qn, SCOPE_EXACT), 0, &failures);
+ check_exact(identity, "domain-call", "total_calls", result->calls.count, 1, &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_just_dependency_control(void) {
+ static const CaseIdentity identity = {
+ "JUST", CBM_LANG_JUST, "justfile",
+ "recipe dependency is build-graph metadata, separate from expression arguments"};
+ int failures = 0;
+ check_ast_kind_present(&identity, "dependency-control", JUST_DEPENDENCY, "dependency",
+ &failures);
+ CBMFileResult *result =
+ extract_source(&identity, "dependency-control", JUST_DEPENDENCY, &failures);
+ if (result) {
+ check_exact(&identity, "dependency-control", "build_callable_definition",
+ callable_definition_count(result, "build"), 1, &failures);
+ check_exact(&identity, "dependency-control", "test_callable_definition",
+ callable_definition_count(result, "test"), 1, &failures);
+ const char *test_qn =
+ checked_callable_qn(&identity, "dependency-control", result, "test", &failures);
+ check_exact(&identity, "dependency-control", "dependency_call_in_test",
+ call_count_scoped(result, "build", test_qn, SCOPE_EXACT), 1, &failures);
+ check_exact(&identity, "dependency-control", "dependency_usage_in_test",
+ usage_count_scoped(result, "build", test_qn, SCOPE_EXACT), 1, &failures);
+ check_exact(&identity, "dependency-control", "total_calls", result->calls.count, 1,
+ &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_tlaplus_bounded_quantification_control(void) {
+ static const CaseIdentity identity = {
+ "TLAPLUS", CBM_LANG_TLAPLUS, "Bounded.tla",
+ "bounded quantification is not an operator call and must retain its set reference"};
+ int failures = 0;
+ check_ast_kind_present(&identity, "bounded-quantification-control",
+ TLAPLUS_BOUNDED_QUANTIFICATION, "bounded_quantification", &failures);
+ CBMFileResult *result = extract_source(&identity, "bounded-quantification-control",
+ TLAPLUS_BOUNDED_QUANTIFICATION, &failures);
+ if (result) {
+ check_exact(&identity, "bounded-quantification-control", "guard_callable_definition",
+ callable_definition_count(result, "Guard"), 1, &failures);
+ check_exact(&identity, "bounded-quantification-control", "set_usage_in_guard",
+ usage_count_scoped(result, "values", "Guard", SCOPE_ROUTINE), 1, &failures);
+ check_exact(&identity, "bounded-quantification-control", "set_not_call_in_guard",
+ call_count_scoped(result, "values", "Guard", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "bounded-quantification-control", "bound_name_not_call_in_guard",
+ call_count_scoped(result, "item", "Guard", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "bounded-quantification-control", "total_calls", result->calls.count,
+ 0, &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_nasm_domain_control(void) {
+ static const CaseIdentity identity = {
+ "NASM", CBM_LANG_NASM, "sample.asm",
+ "call instruction is semantic and must retain its enclosing label"};
+ int failures = 0;
+ check_ast_kind_present(&identity, "instruction-control", NASM_SCOPE, "actual_instruction",
+ &failures);
+ CBMFileResult *result = extract_source(&identity, "instruction-control", NASM_SCOPE, &failures);
+ if (result) {
+ check_exact(&identity, "instruction-control", "run_callable_definition",
+ callable_definition_count(result, "run"), 1, &failures);
+ check_exact(&identity, "instruction-control", "accept_callable_definition",
+ callable_definition_count(result, "accept"), 1, &failures);
+ check_exact(&identity, "instruction-control", "real_call_in_run",
+ call_count_scoped(result, "accept", "run", SCOPE_ROUTINE), 1, &failures);
+ check_exact(&identity, "instruction-control", "mov_not_call_in_run",
+ call_count_scoped(result, "mov", "run", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "instruction-control", "ret_not_call_in_run",
+ call_count_scoped(result, "ret", "run", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "instruction-control", "callee_not_usage_in_run",
+ usage_count_scoped(result, "accept", "run", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "instruction-control", "total_calls", result->calls.count, 1,
+ &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_bitbake_domain_control(void) {
+ static const CaseIdentity identity = {
+ "BITBAKE", CBM_LANG_BITBAKE, "sample.bb",
+ "BitBake call metadata covers embedded Python, not task-to-task callback semantics"};
+ int failures = 0;
+ check_ast_kind_present(&identity, "embedded-python", BITBAKE_DOMAIN,
+ "anonymous_python_function", &failures);
+ check_ast_kind_present(&identity, "embedded-python", BITBAKE_DOMAIN, "call", &failures);
+ CBMFileResult *result = extract_source(&identity, "embedded-python", BITBAKE_DOMAIN, &failures);
+ if (result) {
+ check_exact(&identity, "embedded-python", "task_callable_definition",
+ callable_definition_count(result, "do_run"), 1, &failures);
+ check_exact(&identity, "embedded-python", "note_call_in_task",
+ call_count_scoped(result, "note", "do_run", SCOPE_ROUTINE), 1, &failures);
+ check_exact(&identity, "embedded-python", "callee_not_usage_in_task",
+ usage_count_scoped(result, "note", "do_run", SCOPE_ROUTINE), 0, &failures);
+ check_exact(&identity, "embedded-python", "total_calls", result->calls.count, 1, &failures);
+ cbm_free_result(result);
+ }
+ return failures == 0 ? 0 : 1;
+}
+
+#define DEFINE_ROUTINE_ARGUMENT_TEST(name, case_name) \
+ TEST(repro_call_argument_matrix_b_routine_##name) { \
+ return run_routine_argument_case(&(case_name)); \
+ }
+
+DEFINE_ROUTINE_ARGUMENT_TEST(racket, RACKET_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(odin, ODIN_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(rescript, RESCRIPT_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(purescript, PURESCRIPT_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(nickel, NICKEL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(crystal, CRYSTAL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(teal, TEAL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(hare, HARE_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(pony, PONY_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(luau, LUAU_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(sway, SWAY_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(templ, TEMPL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(wgsl, WGSL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(jsonnet, JSONNET_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(starlark, STARLARK_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(bicep, BICEP_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(hlsl, HLSL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(vhdl, VHDL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(systemverilog, SYSTEMVERILOG_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(ispc, ISPC_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(cairo, CAIRO_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(move, MOVE_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(squirrel, SQUIRREL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(func, FUNC_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(puppet, PUPPET_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(slang, SLANG_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(llvm_ir, LLVM_IR_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(apex, APEX_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(pine, PINE_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(qml, QML_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(cfscript, CFSCRIPT_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(cfml, CFML_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(mojo, MOJO_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(objectscript_udl, OBJECTSCRIPT_UDL_CASE)
+DEFINE_ROUTINE_ARGUMENT_TEST(objectscript_routine, OBJECTSCRIPT_ROUTINE_CASE)
+
+#undef DEFINE_ROUTINE_ARGUMENT_TEST
+
+TEST(repro_call_argument_matrix_b_routine_tlaplus) {
+ int failures = run_routine_argument_case(&TLAPLUS_CASE);
+ failures += run_tlaplus_bounded_quantification_control();
+ return failures == 0 ? 0 : 1;
+}
+
+TEST(repro_call_argument_matrix_b_module_just) {
+ int failures = run_module_argument_case(&JUST_CASE);
+ failures += run_just_dependency_control();
+ return failures == 0 ? 0 : 1;
+}
+
+#define DEFINE_MODULE_ARGUMENT_TEST(name, case_name) \
+ TEST(repro_call_argument_matrix_b_module_##name) { \
+ return run_module_argument_case(&(case_name)); \
+ }
+
+DEFINE_MODULE_ARGUMENT_TEST(gotemplate, GOTEMPLATE_CASE)
+DEFINE_MODULE_ARGUMENT_TEST(linkerscript, LINKERSCRIPT_CASE)
+DEFINE_MODULE_ARGUMENT_TEST(gn, GN_CASE)
+
+#undef DEFINE_MODULE_ARGUMENT_TEST
+
+TEST(repro_call_argument_matrix_b_domain_nasm) {
+ static const CaseIdentity call_syntax_identity = {
+ "NASM", CBM_LANG_NASM, "macro.asm",
+ "function-like macro application is a semantic call_syntax_expression"};
+ int failures = run_nasm_domain_control();
+ failures += run_module_domain_call(&call_syntax_identity, NASM_CALL_SYNTAX,
+ "call_syntax_expression", "accept");
+ return failures == 0 ? 0 : 1;
+}
+
+TEST(repro_call_argument_matrix_b_domain_prisma) {
+ static const CaseIdentity identity = {
+ "PRISMA", CBM_LANG_PRISMA, "schema.prisma",
+ "schema default function is a domain call, not callback-argument coverage"};
+ return run_module_domain_call(&identity, PRISMA_SCOPE, "call_expression", "now");
+}
+
+TEST(repro_call_argument_matrix_b_domain_diff) {
+ static const CaseIdentity identity = {
+ "DIFF", CBM_LANG_DIFF, "sample.diff",
+ "diff command is a document record and must not emit a code call"};
+ return run_no_call_domain(&identity, DIFF_SCOPE, "command");
+}
+
+TEST(repro_call_argument_matrix_b_domain_bibtex) {
+ static const CaseIdentity identity = {
+ "BIBTEX", CBM_LANG_BIBTEX, "sample.bib",
+ "BibTeX command is document syntax and must not emit a code call"};
+ return run_no_call_domain(&identity, BIBTEX_SCOPE, "command");
+}
+
+TEST(repro_call_argument_matrix_b_domain_devicetree) {
+ static const CaseIdentity identity = {
+ "DEVICETREE", CBM_LANG_DEVICETREE, "sample.dts",
+ "DeviceTree macro expression is a domain call, not callback-argument coverage"};
+ return run_module_domain_call(&identity, DEVICETREE_SCOPE, "call_expression", "MHZ");
+}
+
+TEST(repro_call_argument_matrix_b_domain_bitbake) {
+ return run_bitbake_domain_control();
+}
+
+enum {
+ ROUTINE_ARGUMENT_LANGUAGE_COUNT = 36,
+ MODULE_ARGUMENT_LANGUAGE_COUNT = 4,
+ DOMAIN_CONTROL_LANGUAGE_COUNT = 6,
+ MATRIX_LANGUAGE_COUNT = ROUTINE_ARGUMENT_LANGUAGE_COUNT + MODULE_ARGUMENT_LANGUAGE_COUNT +
+ DOMAIN_CONTROL_LANGUAGE_COUNT,
+};
+
+_Static_assert(MATRIX_LANGUAGE_COUNT == 46,
+ "RACKET..OBJECTSCRIPT_ROUTINE call-capable matrix must contain exactly 46 "
+ "language rows");
+
+#define MATRIX_B_LANGUAGE_ROWS(X) \
+ X(repro_call_argument_matrix_b_routine_racket, RACKET_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_odin, ODIN_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_rescript, RESCRIPT_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_purescript, PURESCRIPT_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_nickel, NICKEL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_crystal, CRYSTAL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_teal, TEAL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_hare, HARE_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_pony, PONY_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_luau, LUAU_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_sway, SWAY_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_templ, TEMPL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_wgsl, WGSL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_jsonnet, JSONNET_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_starlark, STARLARK_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_bicep, BICEP_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_hlsl, HLSL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_vhdl, VHDL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_systemverilog, SYSTEMVERILOG_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_ispc, ISPC_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_cairo, CAIRO_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_move, MOVE_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_squirrel, SQUIRREL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_func, FUNC_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_puppet, PUPPET_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_slang, SLANG_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_llvm_ir, LLVM_IR_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_tlaplus, TLAPLUS_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_apex, APEX_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_pine, PINE_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_qml, QML_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_cfscript, CFSCRIPT_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_cfml, CFML_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_mojo, MOJO_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_objectscript_udl, \
+ OBJECTSCRIPT_UDL_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_routine_objectscript_routine, \
+ OBJECTSCRIPT_ROUTINE_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_module_just, JUST_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_module_gotemplate, GOTEMPLATE_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_module_linkerscript, LINKERSCRIPT_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_module_gn, GN_CASE.identity.language) \
+ X(repro_call_argument_matrix_b_domain_nasm, CBM_LANG_NASM) \
+ X(repro_call_argument_matrix_b_domain_prisma, CBM_LANG_PRISMA) \
+ X(repro_call_argument_matrix_b_domain_diff, CBM_LANG_DIFF) \
+ X(repro_call_argument_matrix_b_domain_bibtex, CBM_LANG_BIBTEX) \
+ X(repro_call_argument_matrix_b_domain_devicetree, CBM_LANG_DEVICETREE) \
+ X(repro_call_argument_matrix_b_domain_bitbake, CBM_LANG_BITBAKE)
+
+#define MATRIX_B_COUNT_ROW(test_name_, language_) +1
+enum { MATRIX_B_ROW_COUNT = 0 MATRIX_B_LANGUAGE_ROWS(MATRIX_B_COUNT_ROW) };
+#undef MATRIX_B_COUNT_ROW
+
+_Static_assert(MATRIX_B_ROW_COUNT == MATRIX_LANGUAGE_COUNT,
+ "matrix B suite and language-row count must stay synchronized");
+
+size_t repro_call_argument_matrix_b_copy_language_ids(CBMLanguage *language_ids, size_t capacity) {
+ size_t row_count = 0;
+#define COPY_MATRIX_B_LANGUAGE(test_name_, language_) \
+ do { \
+ if (language_ids && row_count < capacity) \
+ language_ids[row_count] = (language_); \
+ row_count++; \
+ } while (0);
+ MATRIX_B_LANGUAGE_ROWS(COPY_MATRIX_B_LANGUAGE)
+#undef COPY_MATRIX_B_LANGUAGE
+ return row_count;
+}
+
+SUITE(repro_call_argument_matrix_b) {
+#define RUN_MATRIX_B_LANGUAGE_TEST(test_name_, language_) RUN_TEST(test_name_);
+ MATRIX_B_LANGUAGE_ROWS(RUN_MATRIX_B_LANGUAGE_TEST)
+#undef RUN_MATRIX_B_LANGUAGE_TEST
+}
+
+#undef MATRIX_B_LANGUAGE_ROWS
diff --git a/tests/repro/repro_call_argument_usages.c b/tests/repro/repro_call_argument_usages.c
new file mode 100644
index 000000000..97df66a97
--- /dev/null
+++ b/tests/repro/repro_call_argument_usages.c
@@ -0,0 +1,1501 @@
+/*
+ * repro_call_argument_usages.c — references passed as call arguments.
+ *
+ * A direct callee is represented by CALLS and must not be duplicated as USAGE.
+ * Every other resolvable identifier in the argument subtree remains a value
+ * reference and must be retained as USAGE. The shared extractor currently drops
+ * all such identifiers when WalkState.inside_call is true.
+ */
+#include "test_framework.h"
+#include "repro_harness.h"
+#include "foundation/compat.h"
+#include "pipeline/lsp_resolve.h"
+
+#include <store/store.h>
+
+#include <stdio.h>
+#include <string.h>
+
+typedef struct {
+ const char *tag;
+ const char *filename;
+ const char *source;
+ CBMLanguage language;
+ int check_bare_usage;
+} ArgUsageCase;
+
+static int qn_ends_with_name(const char *qn, const char *name) {
+ if (!qn || !name)
+ return 0;
+ const char *last = strrchr(qn, '.');
+ return strcmp(last ? last + 1 : qn, name) == 0;
+}
+
+static int raw_usage_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *u = &r->usages.items[i];
+ if (u->ref_name && strcmp(u->ref_name, target) == 0 &&
+ qn_ends_with_name(u->enclosing_func_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int raw_usage_count_kind(const CBMFileResult *r, const char *caller, const char *target,
+ CBMUsageKind kind) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *u = &r->usages.items[i];
+ if (u->kind == kind && u->ref_name && strcmp(u->ref_name, target) == 0 &&
+ qn_ends_with_name(u->enclosing_func_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int raw_usage_candidate_count(const CBMFileResult *r, const char *caller,
+ const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *u = &r->usages.items[i];
+ if (u->kind == CBM_USAGE_VALUE && u->may_be_call_reference && u->ref_name &&
+ strcmp(u->ref_name, target) == 0 && qn_ends_with_name(u->enclosing_func_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int raw_usage_exists(const CBMFileResult *r, const char *caller, const char *target) {
+ return raw_usage_count(r, caller, target) > 0;
+}
+
+static int raw_call_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *c = &r->calls.items[i];
+ const char *callee = c->callee_name ? strrchr(c->callee_name, '.') : NULL;
+ callee = callee ? callee + 1 : c->callee_name;
+ if (callee && strcmp(callee, target) == 0 &&
+ qn_ends_with_name(c->enclosing_func_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int raw_call_exists(const CBMFileResult *r, const char *caller, const char *target) {
+ return raw_call_count(r, caller, target) > 0;
+}
+
+static int resolved_call_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *c = &r->resolved_calls.items[i];
+ if (c->kind == CBM_RESOLVED_INVOCATION && qn_ends_with_name(c->caller_qn, caller) &&
+ qn_ends_with_name(c->callee_qn, target)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int edge_connects(cbm_store_t *store, const char *project, const char *type,
+ const char *caller, const char *target) {
+ cbm_edge_t *edges = NULL;
+ int count = 0;
+ if (cbm_store_find_edges_by_type(store, project, type, &edges, &count) != CBM_STORE_OK)
+ return 0;
+
+ int found = 0;
+ for (int i = 0; i < count && !found; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t dst = {0};
+ int src_ok = cbm_store_find_node_by_id(store, edges[i].source_id, &src) == CBM_STORE_OK;
+ int dst_ok = cbm_store_find_node_by_id(store, edges[i].target_id, &dst) == CBM_STORE_OK;
+ if (src_ok && dst_ok && src.name && dst.name && strcmp(src.name, caller) == 0 &&
+ strcmp(dst.name, target) == 0) {
+ found = 1;
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&dst);
+ }
+ cbm_store_free_edges(edges, count);
+ return found;
+}
+
+static int edge_connects_callable(cbm_store_t *store, const char *project, const char *type,
+ const char *caller, const char *target) {
+ cbm_edge_t *edges = NULL;
+ int count = 0;
+ if (cbm_store_find_edges_by_type(store, project, type, &edges, &count) != CBM_STORE_OK)
+ return 0;
+
+ int found = 0;
+ for (int i = 0; i < count && !found; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t dst = {0};
+ int src_ok = cbm_store_find_node_by_id(store, edges[i].source_id, &src) == CBM_STORE_OK;
+ int dst_ok = cbm_store_find_node_by_id(store, edges[i].target_id, &dst) == CBM_STORE_OK;
+ int callable_target =
+ dst.label && (strcmp(dst.label, "Function") == 0 || strcmp(dst.label, "Method") == 0);
+ if (src_ok && dst_ok && callable_target && src.name && dst.name &&
+ strcmp(src.name, caller) == 0 && strcmp(dst.name, target) == 0) {
+ found = 1;
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&dst);
+ }
+ cbm_store_free_edges(edges, count);
+ return found;
+}
+
+static int edge_connects_target_qn(cbm_store_t *store, const char *project, const char *type,
+ const char *caller, const char *target_qn_fragment) {
+ cbm_edge_t *edges = NULL;
+ int count = 0;
+ if (cbm_store_find_edges_by_type(store, project, type, &edges, &count) != CBM_STORE_OK)
+ return 0;
+
+ int found = 0;
+ for (int i = 0; i < count && !found; i++) {
+ cbm_node_t src = {0};
+ cbm_node_t dst = {0};
+ int src_ok = cbm_store_find_node_by_id(store, edges[i].source_id, &src) == CBM_STORE_OK;
+ int dst_ok = cbm_store_find_node_by_id(store, edges[i].target_id, &dst) == CBM_STORE_OK;
+ if (src_ok && dst_ok && src.name && dst.qualified_name && strcmp(src.name, caller) == 0 &&
+ strstr(dst.qualified_name, target_qn_fragment)) {
+ found = 1;
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&dst);
+ }
+ cbm_store_free_edges(edges, count);
+ return found;
+}
+
+static int check_raw_argument_case(const ArgUsageCase *c) {
+ CBMFileResult *r = cbm_extract_file(c->source, (int)strlen(c->source), c->language, "repro",
+ c->filename, 0, NULL, NULL);
+ if (!r) {
+ fprintf(stderr, " [call-arg] lang=%s invariant=extract result=null\n", c->tag);
+ return 1;
+ }
+
+ int failures = 0;
+#define CHECK_RAW(condition, invariant) \
+ do { \
+ if (!(condition)) { \
+ fprintf(stderr, " [call-arg] lang=%s invariant=%s\n", c->tag, invariant); \
+ failures++; \
+ } \
+ } while (0)
+ CHECK_RAW(!r->has_error && !r->parse_incomplete, "valid_fixture");
+ CHECK_RAW(raw_call_exists(r, "argument", "accept"), "registrar_call_missing");
+ CHECK_RAW(raw_call_exists(r, "direct", "handler"), "direct_call_missing");
+ CBMUsageKind expected_kind = CBM_USAGE_VALUE;
+ CBMUsageKind rejected_kind = CBM_USAGE_CALL_REFERENCE;
+ if (c->check_bare_usage) {
+ CHECK_RAW(raw_usage_count_kind(r, "bare", "handler", expected_kind) == 1,
+ "bare_usage_kind_missing");
+ CHECK_RAW(raw_usage_count_kind(r, "bare", "handler", rejected_kind) == 0,
+ "bare_usage_kind_duplicated");
+ if (c->language == CBM_LANG_KOTLIN) {
+ CHECK_RAW(raw_usage_candidate_count(r, "bare", "handler") == 1,
+ "bare_semantic_candidate_missing");
+ }
+ }
+ CHECK_RAW(raw_usage_count_kind(r, "argument", "handler", expected_kind) == 1,
+ "argument_usage_kind_missing");
+ CHECK_RAW(raw_usage_count_kind(r, "argument", "handler", rejected_kind) == 0,
+ "argument_usage_kind_duplicated");
+ CHECK_RAW(raw_usage_candidate_count(r, "argument", "handler") == 1,
+ "argument_semantic_candidate_missing");
+ CHECK_RAW(!raw_usage_exists(r, "direct", "handler"), "direct_call_duplicated_as_usage");
+ CHECK_RAW(!raw_call_exists(r, "argument", "handler"), "argument_fabricated_as_call");
+#undef CHECK_RAW
+
+ cbm_free_result(r);
+ return failures;
+}
+
+static const ArgUsageCase SHARED_CASES[] = {
+ {"javascript", "main.js",
+ "function handler() {}\n"
+ "function accept(cb) {}\n"
+ "function argument() { accept(handler); }\n"
+ "function direct() { handler(); }\n"
+ "function bare() { handler; }\n",
+ CBM_LANG_JAVASCRIPT, 1},
+ {"typescript", "main.ts",
+ "function handler(): void {}\n"
+ "function accept(cb: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n"
+ "function direct(): void { handler(); }\n"
+ "function bare(): void { handler; }\n",
+ CBM_LANG_TYPESCRIPT, 1},
+ {"go", "main.go",
+ "package sample\n"
+ "func handler() {}\n"
+ "func accept(cb func()) {}\n"
+ "func argument() { accept(handler) }\n"
+ "func direct() { handler() }\n"
+ "func bare() { _ = handler }\n",
+ CBM_LANG_GO, 1},
+ {"python", "main.py",
+ "def handler():\n pass\n"
+ "def accept(cb):\n pass\n"
+ "def argument():\n accept(handler)\n"
+ "def direct():\n handler()\n"
+ "def bare():\n handler\n",
+ CBM_LANG_PYTHON, 1},
+ {"c", "main.c",
+ "typedef void (*callback_t)(void);\n"
+ "void handler(void) {}\n"
+ "void accept(callback_t cb) {}\n"
+ "void argument(void) { accept(handler); }\n"
+ "void direct(void) { handler(); }\n"
+ "void bare(void) { callback_t cb = handler; (void)cb; }\n",
+ CBM_LANG_C, 1},
+ {"cpp", "main.cpp",
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback cb) {}\n"
+ "void argument() { accept(handler); }\n"
+ "void direct() { handler(); }\n"
+ "void bare() { Callback cb = handler; (void)cb; }\n",
+ CBM_LANG_CPP, 0},
+ {"rust", "main.rs",
+ "fn handler() {}\n"
+ "fn accept(_cb: fn()) {}\n"
+ "fn argument() { accept(handler); }\n"
+ "fn direct() { handler(); }\n"
+ "fn bare() { let _cb: fn() = handler; }\n",
+ CBM_LANG_RUST, 1},
+ {"csharp", "Main.cs",
+ "using System;\n"
+ "class Sample {\n"
+ " static void handler() {}\n"
+ " static void accept(Action cb) {}\n"
+ " static void argument() { accept(handler); }\n"
+ " static void direct() { handler(); }\n"
+ " static void bare() { Action cb = handler; }\n"
+ "}\n",
+ CBM_LANG_CSHARP, 1},
+ {"kotlin", "Main.kt",
+ "fun handler() {}\n"
+ "fun accept(cb: () -> Unit) {}\n"
+ "fun argument() { accept(::handler) }\n"
+ "fun direct() { handler() }\n"
+ "fun bare() { val cb = ::handler }\n",
+ CBM_LANG_KOTLIN, 1},
+ {"tsx", "main.tsx",
+ "function handler(): void {}\n"
+ "function accept(cb: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n"
+ "function direct(): void { handler(); }\n"
+ "function bare(): void { handler; }\n",
+ CBM_LANG_TSX, 1},
+ {"cuda", "main.cu",
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback cb) {}\n"
+ "void argument() { accept(handler); }\n"
+ "void direct() { handler(); }\n"
+ "void bare() { Callback cb = handler; (void)cb; }\n",
+ CBM_LANG_CUDA, 0},
+};
+
+TEST(repro_call_argument_javascript) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[0]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_typescript) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[1]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_go) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[2]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_python) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[3]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_c) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[4]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_cpp) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[5]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_rust) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[6]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_csharp) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[7]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_kotlin) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[8]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_tsx_raw) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[9]), 0);
+ PASS();
+}
+
+TEST(repro_call_argument_cuda_raw) {
+ ASSERT_EQ(check_raw_argument_case(&SHARED_CASES[10]), 0);
+ PASS();
+}
+
+TEST(repro_python_local_shadow_does_not_link_global_callable) {
+ static const char *source = "def handler():\n return 1\n"
+ "def accept(value):\n return value\n"
+ "def argument(handler):\n return accept(handler)\n"
+ "def direct():\n return handler()\n";
+ RProj project = {0};
+ cbm_store_t *store = rh_index(&project, "main.py", source);
+ if (!store) {
+ FAIL("Python local-shadow fixture did not produce a graph store");
+ }
+
+ int failures = 0;
+ if (!edge_connects_callable(store, project.project, "CALLS", "direct", "handler")) {
+ fprintf(stderr, " [call-shadow] lang=python invariant=direct_global_call_missing\n");
+ failures++;
+ }
+ static const char *forbidden_edge_types[] = {"USAGE", "CALL_REFERENCE", "CALLS"};
+ for (size_t i = 0; i < sizeof(forbidden_edge_types) / sizeof(forbidden_edge_types[0]); i++) {
+ if (edge_connects_callable(store, project.project, forbidden_edge_types[i], "argument",
+ "handler")) {
+ fprintf(stderr,
+ " [call-shadow] lang=python invariant=local_parameter_linked_global "
+ "edge=%s\n",
+ forbidden_edge_types[i]);
+ failures++;
+ }
+ }
+
+ rh_cleanup(&project, store);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Separate defect discovered by the control matrix: a C++ function value in a
+ * variable initializer is lost even though it is not inside a call subtree. */
+TEST(repro_cpp_bare_function_value_usage) {
+ static const char *source = "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void bare() { Callback cb = handler; (void)cb; }\n";
+ CBMFileResult *r = cbm_extract_file(source, (int)strlen(source), CBM_LANG_CPP, "repro",
+ "main.cpp", 0, NULL, NULL);
+ ASSERT_NOT_NULL(r);
+ int found = raw_usage_exists(r, "bare", "handler");
+ cbm_free_result(r);
+ if (!found)
+ fprintf(stderr, " [call-arg] lang=cpp invariant=bare_usage_missing\n");
+ ASSERT_TRUE(found);
+ PASS();
+}
+
+static int check_ts_lsp_mode(int disabled) {
+ static const char *source = "function handler(): void {}\n"
+ "function accept(cb: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n";
+ if (disabled)
+ cbm_setenv("CBM_LSP_DISABLED", "1", 1);
+ else
+ cbm_unsetenv("CBM_LSP_DISABLED");
+
+ CBMFileResult *r = cbm_extract_file(source, (int)strlen(source), CBM_LANG_TYPESCRIPT, "repro",
+ "main.ts", 0, NULL, NULL);
+ int failures = 0;
+ if (!r) {
+ failures++;
+ } else {
+ if (r->has_error) {
+ fprintf(stderr, " [call-arg] lang=typescript lsp=%s invariant=valid_fixture\n",
+ disabled ? "off" : "on");
+ failures++;
+ }
+ if (raw_call_count(r, "argument", "accept") != 1) {
+ fprintf(stderr, " [call-arg] lang=typescript lsp=%s invariant=outer_raw_call_count\n",
+ disabled ? "off" : "on");
+ failures++;
+ }
+ if (r->calls.count != 1) {
+ fprintf(stderr,
+ " [call-arg] lang=typescript lsp=%s invariant=raw_call_total "
+ "expected=1 actual=%d\n",
+ disabled ? "off" : "on", r->calls.count);
+ failures++;
+ }
+ if (raw_usage_count(r, "argument", "handler") != 1) {
+ fprintf(stderr, " [call-arg] lang=typescript lsp=%s invariant=argument_usage_count\n",
+ disabled ? "off" : "on");
+ failures++;
+ }
+ if (r->usages.count != 1) {
+ fprintf(stderr,
+ " [call-arg] lang=typescript lsp=%s invariant=raw_usage_total "
+ "expected=1 actual=%d\n",
+ disabled ? "off" : "on", r->usages.count);
+ for (int i = 0; i < r->usages.count; i++) {
+ fprintf(stderr, " [call-arg] unexpected_usage[%d]=%s owner=%s\n", i,
+ r->usages.items[i].ref_name ? r->usages.items[i].ref_name : "<null>",
+ r->usages.items[i].enclosing_func_qn ? r->usages.items[i].enclosing_func_qn
+ : "<null>");
+ }
+ failures++;
+ }
+ int resolved = resolved_call_count(r, "argument", "accept");
+ if ((!disabled && resolved != 1) || (disabled && resolved != 0)) {
+ fprintf(stderr,
+ " [call-arg] lang=typescript lsp=%s invariant=outer_lsp_call_count "
+ "expected=%d actual=%d\n",
+ disabled ? "off" : "on", disabled ? 0 : 1, resolved);
+ failures++;
+ }
+ int resolved_handler = resolved_call_count(r, "argument", "handler");
+ if (resolved_handler != 0) {
+ fprintf(stderr,
+ " [call-arg] lang=typescript lsp=%s invariant=argument_not_resolved_call "
+ "expected=0 actual=%d\n",
+ disabled ? "off" : "on", resolved_handler);
+ failures++;
+ }
+ int expected_resolved_total = disabled ? 0 : 1;
+ if (r->resolved_calls.count != expected_resolved_total) {
+ fprintf(stderr,
+ " [call-arg] lang=typescript lsp=%s invariant=resolved_call_total "
+ "expected=%d actual=%d\n",
+ disabled ? "off" : "on", expected_resolved_total, r->resolved_calls.count);
+ failures++;
+ }
+ cbm_free_result(r);
+ }
+ return failures;
+}
+
+TEST(repro_call_argument_ts_lsp_cannot_rescue) {
+ const char *prior = getenv("CBM_LSP_DISABLED");
+ char *saved = prior ? cbm_strdup(prior) : NULL;
+ int failures = check_ts_lsp_mode(1) + check_ts_lsp_mode(0);
+ if (saved) {
+ cbm_setenv("CBM_LSP_DISABLED", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_LSP_DISABLED");
+ }
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+static int check_callable_reference_edges(const char *tag, const RFile *files, int nfiles,
+ const char *caller, const char *registrar,
+ const char *target) {
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, nfiles);
+ if (!store) {
+ fprintf(stderr, " [call-ref] case=%s invariant=index_store_missing\n", tag);
+ rh_cleanup(&project, store);
+ return 1;
+ }
+
+ int failures = 0;
+ if (!edge_connects(store, project.project, "CALLS", caller, registrar)) {
+ fprintf(stderr, " [call-ref] case=%s invariant=registrar_call_missing\n", tag);
+ failures++;
+ }
+ if (!edge_connects(store, project.project, "CALL_REFERENCE", caller, target)) {
+ fprintf(stderr, " [call-ref] case=%s invariant=call_reference_missing\n", tag);
+ failures++;
+ }
+ if (edge_connects(store, project.project, "CALLS", caller, target)) {
+ fprintf(stderr, " [call-ref] case=%s invariant=reference_fabricated_as_call\n", tag);
+ failures++;
+ }
+ if (edge_connects(store, project.project, "USAGE", caller, target)) {
+ fprintf(stderr, " [call-ref] case=%s invariant=reference_duplicated_as_usage\n", tag);
+ failures++;
+ }
+
+ rh_cleanup(&project, store);
+ return failures;
+}
+
+TEST(repro_call_argument_ts_pipeline_shapes) {
+ static const RFile same_file[] = {{
+ "main.ts",
+ "function handler(): void {}\n"
+ "function accept(cb: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n",
+ }};
+ static const RFile imported[] = {
+ {"plugin.ts", "export function importedHandler(): void {}\n"},
+ {"main.ts", "import { importedHandler } from './plugin';\n"
+ "function accept(cb: () => void): void {}\n"
+ "export function importedArgument(): void { accept(importedHandler); }\n"},
+ };
+ int failures = check_callable_reference_edges("ts_same_file", same_file, 1, "argument",
+ "accept", "handler");
+ failures += check_callable_reference_edges("ts_imported", imported, 2, "importedArgument",
+ "accept", "importedHandler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_javascript_same_file_value_reference) {
+ static const RFile files[] = {{
+ "main.js",
+ "function handler() {}\n"
+ "function accept(callback) {}\n"
+ "function argument() { accept(handler); }\n",
+ }};
+ int failures = check_callable_reference_edges("javascript_same_file", files, 1, "argument",
+ "accept", "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_tsx_same_file_value_reference) {
+ static const RFile files[] = {{
+ "main.tsx",
+ "function handler(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n",
+ }};
+ int failures =
+ check_callable_reference_edges("tsx_same_file", files, 1, "argument", "accept", "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_ts_family_forward_declared_value_reference) {
+ static const RFile js_files[] = {{
+ "forward.js",
+ "function accept(callback) {}\n"
+ "function argument() { accept(handler); }\n"
+ "function handler() {}\n",
+ }};
+ static const RFile ts_files[] = {{
+ "forward.ts",
+ "function accept(callback: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n"
+ "function handler(): void {}\n",
+ }};
+ static const RFile tsx_files[] = {{
+ "forward.tsx",
+ "function accept(callback: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n"
+ "function handler(): void {}\n",
+ }};
+
+ int failures = 0;
+ failures += check_callable_reference_edges("javascript_forward", js_files, 1, "argument",
+ "accept", "handler");
+ failures += check_callable_reference_edges("typescript_forward", ts_files, 1, "argument",
+ "accept", "handler");
+ failures += check_callable_reference_edges("tsx_forward", tsx_files, 1, "argument", "accept",
+ "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_ts_nested_and_value_refs) {
+ static const RFile files[] = {{
+ "main.ts",
+ "type CallbackOptions = { handler: () => void };\n"
+ "type RuntimeOptions = { enabled: boolean };\n"
+ "const runtimeOptions: RuntimeOptions = { enabled: true };\n"
+ "function handler(): void {}\n"
+ "function register(options: CallbackOptions): void {}\n"
+ "function consume(options: RuntimeOptions): void {}\n"
+ "function nestedArgument(): void { register({ handler: handler }); }\n"
+ "function valueArgument(): void { consume(runtimeOptions); }\n",
+ }};
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("TS value-reference fixture did not produce a graph store");
+ }
+ int nested = edge_connects(store, project.project, "USAGE", "nestedArgument", "handler");
+ int value = edge_connects(store, project.project, "USAGE", "valueArgument", "runtimeOptions");
+ if (!nested)
+ fprintf(stderr, " [call-arg] case=ts_nested invariant=argument_usage_missing\n");
+ if (!value)
+ fprintf(stderr, " [call-arg] case=ts_value invariant=argument_usage_missing\n");
+ rh_cleanup(&project, store);
+ ASSERT_TRUE(nested);
+ ASSERT_TRUE(value);
+ PASS();
+}
+
+TEST(repro_call_argument_ts_member_ref) {
+ static const RFile files[] = {{
+ "main.ts",
+ "class Service { handler(): void {} }\n"
+ "function accept(cb: () => void): void {}\n"
+ "function memberArgument(service: Service): void { accept(service.handler); }\n",
+ }};
+ int failures = check_callable_reference_edges("ts_member", files, 1, "memberArgument", "accept",
+ "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_kotlin_pipeline_join) {
+ static const RFile files[] = {{
+ "Main.kt",
+ "fun handler() {}\n"
+ "fun accept(cb: () -> Unit) {}\n"
+ "fun kotlinArgument() { accept(::handler) }\n",
+ }};
+ int failures = check_callable_reference_edges("kotlin_callable_ref", files, 1, "kotlinArgument",
+ "accept", "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_java_method_reference_edge) {
+ static const RFile files[] = {{
+ "Main.java",
+ "interface Task { void invoke(); }\n"
+ "class Main {\n"
+ " static void handler() {}\n"
+ " static void accept(Task callback) {}\n"
+ " static void javaArgument() { accept(Main::handler); }\n"
+ "}\n",
+ }};
+ int failures = check_callable_reference_edges("java_method_ref", files, 1, "javaArgument",
+ "accept", "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_java_same_name_references_keep_occurrence_identity) {
+ static const RFile files[] = {
+ {"A.java", "class A { static void handler() {} }\n"},
+ {"B.java", "class B { static void handler() {} }\n"},
+ {"Use.java", "interface Task { void invoke(); }\n"
+ "class Use {\n"
+ " static void accept(Task callback) {}\n"
+ " static void references() { accept(A::handler); accept(B::handler); }\n"
+ "}\n"},
+ };
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 3);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Java same-name reference fixture did not produce a graph store");
+ }
+ int a = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "references",
+ ".A.handler");
+ int b = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "references",
+ ".B.handler");
+ rh_cleanup(&project, store);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ PASS();
+}
+
+TEST(repro_kotlin_bound_reference_uses_instance_type) {
+ static const RFile files[] = {{
+ "Main.kt",
+ "class Service { fun handler() {} }\n"
+ "class Other { fun handler() {} }\n"
+ "fun accept(callback: () -> Unit) {}\n"
+ "fun boundReference(service: Service) { accept(service::handler) }\n",
+ }};
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin bound-reference fixture did not produce a graph store");
+ }
+ int service = edge_connects_target_qn(store, project.project, "CALL_REFERENCE",
+ "boundReference", ".Service.handler");
+ int other = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "boundReference",
+ ".Other.handler");
+ rh_cleanup(&project, store);
+ ASSERT_TRUE(service);
+ ASSERT_FALSE(other);
+ PASS();
+}
+
+static const RFile PHP_FIRST_CLASS_CALLABLE[] = {{
+ "main.php",
+ "<?php\n"
+ "function handler(): void {}\n"
+ "function accept(callable $cb): void {}\n"
+ "function phpArgument(): void { accept(handler(...)); }\n",
+}};
+
+TEST(repro_php_first_class_callable_reference_edge) {
+ int failures = check_callable_reference_edges("php_first_class", PHP_FIRST_CLASS_CALLABLE, 1,
+ "phpArgument", "accept", "handler");
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_php_same_name_references_keep_occurrence_identity) {
+ static const RFile files[] = {{
+ "main.php",
+ "<?php\n"
+ "class A { public static function handler(): void {} }\n"
+ "class B { public static function handler(): void {} }\n"
+ "function accept(callable $callback): void {}\n"
+ "function references(): void { accept(A::handler(...)); accept(B::handler(...)); }\n",
+ }};
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("PHP same-name reference fixture did not produce a graph store");
+ }
+ int a = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "references",
+ ".A.handler");
+ int b = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "references",
+ ".B.handler");
+ rh_cleanup(&project, store);
+ ASSERT_TRUE(a);
+ ASSERT_TRUE(b);
+ PASS();
+}
+
+TEST(repro_php_magic_first_class_reference_uses_reason_match) {
+ static const RFile files[] = {{
+ "magic.php",
+ "<?php\n"
+ "class Magic {\n"
+ " public function __call(string $name, array $arguments): mixed { return null; }\n"
+ "}\n"
+ "function accept(callable $callback): void {}\n"
+ "function references(Magic $object): void { accept($object->missing(...)); }\n",
+ }};
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("PHP magic callable-reference fixture did not produce a graph store");
+ }
+ int magic = edge_connects_target_qn(store, project.project, "CALL_REFERENCE", "references",
+ ".Magic.__call");
+ int fabricated =
+ edge_connects(store, project.project, "CALL_REFERENCE", "references", "missing");
+ rh_cleanup(&project, store);
+ ASSERT_TRUE(magic);
+ ASSERT_FALSE(fabricated);
+ PASS();
+}
+
+TEST(repro_cpp_signature_types_preserve_positions_without_changing_legacy_types) {
+ static const char source[] = "struct FreeVec {};\n"
+ "FreeVec operator+(FreeVec lhs, FreeVec rhs) { return lhs; }\n"
+ "void positional(int first, FreeVec middle, int last) {}\n";
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), CBM_LANG_CPP, "repro",
+ "signature.cpp", 0, NULL, NULL);
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+
+ const CBMDefinition *operator_def = NULL;
+ const CBMDefinition *positional_def = NULL;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && strcmp(definition->name, "operator+") == 0)
+ operator_def = definition;
+ if (definition->name && strcmp(definition->name, "positional") == 0)
+ positional_def = definition;
+ }
+
+ ASSERT_NOT_NULL(operator_def);
+ ASSERT_NOT_NULL(operator_def->param_types);
+ ASSERT_STR_EQ(operator_def->param_types[0], "FreeVec");
+ ASSERT_NULL(operator_def->param_types[1]);
+ ASSERT_EQ(operator_def->signature_param_count, 2);
+ ASSERT_NOT_NULL(operator_def->signature_param_types);
+ ASSERT_STR_EQ(operator_def->signature_param_types[0], "FreeVec");
+ ASSERT_STR_EQ(operator_def->signature_param_types[1], "FreeVec");
+
+ ASSERT_NOT_NULL(positional_def);
+ ASSERT_NOT_NULL(positional_def->param_types);
+ ASSERT_STR_EQ(positional_def->param_types[0], "FreeVec");
+ ASSERT_NULL(positional_def->param_types[1]);
+ ASSERT_EQ(positional_def->signature_param_count, 3);
+ ASSERT_NOT_NULL(positional_def->signature_param_types);
+ ASSERT_STR_EQ(positional_def->signature_param_types[0], "int");
+ ASSERT_STR_EQ(positional_def->signature_param_types[1], "FreeVec");
+ ASSERT_STR_EQ(positional_def->signature_param_types[2], "int");
+
+ cbm_free_result(result);
+ PASS();
+}
+
+typedef struct {
+ const char *tag;
+ const char *filename;
+ const char *source;
+ CBMLanguage language;
+ const char *definition_name;
+ const char *expected[4];
+ int expected_count;
+} SignaturePositionCase;
+
+static int check_signature_position_case(const SignaturePositionCase *c) {
+ CBMFileResult *result = cbm_extract_file(c->source, (int)strlen(c->source), c->language,
+ "signature", c->filename, 0, NULL, NULL);
+ if (!result) {
+ fprintf(stderr, " [signature-position] lang=%s invariant=extract_result\n", c->tag);
+ return 1;
+ }
+
+ int failures = 0;
+ if (result->has_error || result->parse_incomplete) {
+ fprintf(stderr, " [signature-position] lang=%s invariant=valid_fixture\n", c->tag);
+ failures++;
+ }
+ const CBMDefinition *found = NULL;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && strcmp(definition->name, c->definition_name) == 0) {
+ found = definition;
+ break;
+ }
+ }
+ if (!found) {
+ fprintf(stderr, " [signature-position] lang=%s invariant=definition_missing\n", c->tag);
+ failures++;
+ } else {
+ if (found->signature_param_count != c->expected_count) {
+ fprintf(stderr,
+ " [signature-position] lang=%s invariant=count expected=%d actual=%d\n",
+ c->tag, c->expected_count, found->signature_param_count);
+ failures++;
+ }
+ for (int i = 0; i < c->expected_count; i++) {
+ const char *actual = found->signature_param_types && i < found->signature_param_count
+ ? found->signature_param_types[i]
+ : NULL;
+ if (!actual || strcmp(actual, c->expected[i]) != 0) {
+ fprintf(stderr,
+ " [signature-position] lang=%s invariant=slot index=%d "
+ "expected=%s actual=%s\n",
+ c->tag, i, c->expected[i], actual ? actual : "<null>");
+ failures++;
+ }
+ }
+ }
+ cbm_free_result(result);
+ return failures;
+}
+
+TEST(repro_lsp_language_signatures_preserve_argument_positions) {
+ static const SignaturePositionCase cases[] = {
+ {"c",
+ "signature.c",
+ "typedef struct Thing { int value; } Thing;\n"
+ "void position(int first, Thing middle, int last) {}\n",
+ CBM_LANG_C,
+ "position",
+ {"int", "Thing", "int", NULL},
+ 3},
+ {"cuda",
+ "signature.cu",
+ "struct Thing { int value; };\n"
+ "void position(int first, Thing middle, int last) {}\n",
+ CBM_LANG_CUDA,
+ "position",
+ {"int", "Thing", "int", NULL},
+ 3},
+ {"go",
+ "signature.go",
+ "package sample\n"
+ "type Thing struct{}\n"
+ "func position(first, middle Thing, last int) {}\n",
+ CBM_LANG_GO,
+ "position",
+ {"Thing", "Thing", "int", NULL},
+ 3},
+ {"javascript",
+ "signature.js",
+ "function position(first, middle, last) {}\n",
+ CBM_LANG_JAVASCRIPT,
+ "position",
+ {"?", "?", "?", NULL},
+ 3},
+ {"typescript",
+ "signature.ts",
+ "class Sample {}\n"
+ "function position(this: Sample, first: number, middle, last: number): void {}\n",
+ CBM_LANG_TYPESCRIPT,
+ "position",
+ {"number", "?", "number", NULL},
+ 3},
+ {"tsx",
+ "signature.tsx",
+ "class Sample {}\n"
+ "function position(this: Sample, first: number, middle, last: number): void {}\n",
+ CBM_LANG_TSX,
+ "position",
+ {"number", "?", "number", NULL},
+ 3},
+ {"python",
+ "signature.py",
+ "class Sample:\n"
+ " def position(self, first: int, middle, last: int):\n"
+ " pass\n",
+ CBM_LANG_PYTHON,
+ "position",
+ {"int", "?", "int", NULL},
+ 3},
+ {"java",
+ "Signature.java",
+ "class Thing {}\n"
+ "class Signature { static void position(int first, Thing middle, int last) {} }\n",
+ CBM_LANG_JAVA,
+ "position",
+ {"int", "Thing", "int", NULL},
+ 3},
+ {"csharp",
+ "Signature.cs",
+ "class Thing {}\n"
+ "class Signature { static void position(int first, Thing middle, int last) {} }\n",
+ CBM_LANG_CSHARP,
+ "position",
+ {"int", "Thing", "int", NULL},
+ 3},
+ {"kotlin",
+ "Signature.kt",
+ "class Thing\n"
+ "fun position(first: Int, middle: Thing, last: Int) {}\n",
+ CBM_LANG_KOTLIN,
+ "position",
+ {"Int", "Thing", "Int", NULL},
+ 3},
+ {"php",
+ "signature.php",
+ "<?php\n"
+ "class Thing {}\n"
+ "function position(int $first, Thing $middle, int $last): void {}\n",
+ CBM_LANG_PHP,
+ "position",
+ {"int", "Thing", "int", NULL},
+ 3},
+ {"rust",
+ "signature.rs",
+ "struct Thing;\n"
+ "struct Sample;\n"
+ "impl Sample { fn position(&self, first: i32, middle: Thing, last: i32) {} }\n",
+ CBM_LANG_RUST,
+ "position",
+ {"i32", "Thing", "i32", NULL},
+ 3},
+ };
+
+ int failures = 0;
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ failures += check_signature_position_case(&cases[i]);
+ }
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_cpp_operator_edges_require_semantic_resolution) {
+ static const RFile files[] = {
+ {"operators.cpp", "struct Vec {\n"
+ " int value;\n"
+ " Vec operator+(const Vec& rhs) const { return *this; }\n"
+ "};\n"
+ "Vec overloaded(Vec lhs, Vec rhs) { return lhs + rhs; }\n"},
+ {"primitive.cpp", "int primitive(int lhs, int rhs) { return lhs + rhs; }\n"},
+ {"free_operator.cpp",
+ "struct FreeVec {};\n"
+ "FreeVec operator+(FreeVec lhs, FreeVec rhs) { return lhs; }\n"
+ "FreeVec freeOverloaded(FreeVec lhs, FreeVec rhs) { return lhs + rhs; }\n"},
+ };
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 3);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("C++ semantic-operator fixture did not produce a graph store");
+ }
+
+ int overloaded = edge_connects(store, project.project, "CALLS", "overloaded", "operator+");
+ int free_overloaded =
+ edge_connects(store, project.project, "CALLS", "freeOverloaded", "operator+");
+ int primitive = edge_connects(store, project.project, "CALLS", "primitive", "operator+");
+ if (!overloaded)
+ fprintf(stderr, " [cpp-operator] invariant=overloaded_lsp_call_missing\n");
+ if (primitive)
+ fprintf(stderr, " [cpp-operator] invariant=primitive_bound_to_unrelated_overload\n");
+ if (!free_overloaded)
+ fprintf(stderr, " [cpp-operator] invariant=free_adl_operator_lsp_call_missing\n");
+ rh_cleanup(&project, store);
+
+ ASSERT_TRUE(overloaded);
+ ASSERT_TRUE(free_overloaded);
+ ASSERT_FALSE(primitive);
+ PASS();
+}
+
+TEST(repro_cpp_operator_lsp_join_is_occurrence_exact) {
+ static const char source[] = "struct Vec {\n"
+ " Vec operator+(const Vec& rhs) const { return *this; }\n"
+ "};\n"
+ "void mixed(Vec lhs, Vec rhs, int a, int b) {\n"
+ " Vec custom = lhs + rhs;\n"
+ " int primitive = a + b;\n"
+ "}\n";
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), CBM_LANG_CPP, "repro",
+ "mixed.cpp", 0, NULL, NULL);
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ const CBMCall *custom = NULL;
+ const CBMCall *primitive = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->callee_name || strcmp(call->callee_name, "operator+") != 0)
+ continue;
+ if (call->start_line == 5)
+ custom = call;
+ if (call->start_line == 6)
+ primitive = call;
+ }
+ ASSERT_NOT_NULL(custom);
+ ASSERT_NOT_NULL(primitive);
+ ASSERT_NOT_NULL(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, custom, false));
+ ASSERT_NULL(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, primitive, false));
+ cbm_free_result(result);
+ PASS();
+}
+
+typedef struct {
+ const char *tag;
+ const char *filename;
+ CBMLanguage language;
+} CompoundAssignmentCase;
+
+static const char COMPOUND_ASSIGNMENT_SOURCE[] =
+ "struct Accumulator {\n"
+ " Accumulator& operator+=(const Accumulator& rhs) { return *this; }\n"
+ "};\n"
+ "struct FreeAccumulator {};\n"
+ "FreeAccumulator& operator+=(FreeAccumulator& lhs, const FreeAccumulator& rhs) { return lhs; "
+ "}\n"
+ "Accumulator memberCustom(Accumulator member_lhs, Accumulator member_rhs) { "
+ "member_lhs += member_rhs; return member_lhs; }\n"
+ "FreeAccumulator freeCustom(FreeAccumulator free_lhs, FreeAccumulator free_rhs) { "
+ "free_lhs += free_rhs; return free_lhs; }\n"
+ "int primitive(int primitive_lhs, int primitive_rhs) { "
+ "primitive_lhs += primitive_rhs; return primitive_lhs; }\n";
+
+static int check_compound_assignment_case(const CompoundAssignmentCase *test_case) {
+ static const char member_site[] = "member_lhs += member_rhs";
+ static const char free_site[] = "free_lhs += free_rhs";
+ static const char primitive_site[] = "primitive_lhs += primitive_rhs";
+ const char *member_text = strstr(COMPOUND_ASSIGNMENT_SOURCE, member_site);
+ const char *free_text = strstr(COMPOUND_ASSIGNMENT_SOURCE, free_site);
+ const char *primitive_text = strstr(COMPOUND_ASSIGNMENT_SOURCE, primitive_site);
+ if (!member_text || !free_text || !primitive_text) {
+ fprintf(stderr, " [compound-assignment] lang=%s invariant=fixture_occurrences_missing\n",
+ test_case->tag);
+ return 1;
+ }
+
+ uint32_t member_start = (uint32_t)(member_text - COMPOUND_ASSIGNMENT_SOURCE);
+ uint32_t member_end = member_start + (uint32_t)strlen(member_site);
+ uint32_t free_start = (uint32_t)(free_text - COMPOUND_ASSIGNMENT_SOURCE);
+ uint32_t free_end = free_start + (uint32_t)strlen(free_site);
+ uint32_t primitive_start = (uint32_t)(primitive_text - COMPOUND_ASSIGNMENT_SOURCE);
+ uint32_t primitive_end = primitive_start + (uint32_t)strlen(primitive_site);
+ CBMFileResult *result = cbm_extract_file(
+ COMPOUND_ASSIGNMENT_SOURCE, (int)strlen(COMPOUND_ASSIGNMENT_SOURCE), test_case->language,
+ "compound_assignment", test_case->filename, 0, NULL, NULL);
+ if (!result) {
+ fprintf(stderr, " [compound-assignment] lang=%s invariant=extract_result\n",
+ test_case->tag);
+ return 1;
+ }
+
+ int failures = 0;
+#define CHECK_COMPOUND(condition, invariant) \
+ do { \
+ if (!(condition)) { \
+ fprintf(stderr, " [compound-assignment] lang=%s invariant=%s\n", test_case->tag, \
+ invariant); \
+ failures++; \
+ } \
+ } while (0)
+ CHECK_COMPOUND(!result->has_error && !result->parse_incomplete, "valid_fixture");
+
+ const char *member_target_qn = NULL;
+ const char *free_target_qn = NULL;
+ int member_target_count = 0;
+ int free_target_count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (!definition->name || strcmp(definition->name, "operator+=") != 0 ||
+ !definition->qualified_name) {
+ continue;
+ }
+ if (definition->parent_class &&
+ strstr(definition->qualified_name, ".Accumulator.operator+=")) {
+ member_target_qn = definition->qualified_name;
+ member_target_count++;
+ } else if (!definition->parent_class) {
+ free_target_qn = definition->qualified_name;
+ free_target_count++;
+ }
+ }
+ CHECK_COMPOUND(member_target_count == 1, "member_target_definition");
+ CHECK_COMPOUND(free_target_count == 1, "free_target_definition");
+ CHECK_COMPOUND(member_target_qn && free_target_qn &&
+ strcmp(member_target_qn, free_target_qn) != 0,
+ "member_free_targets_distinct");
+
+ const CBMCall *member_carrier = NULL;
+ const CBMCall *free_carrier = NULL;
+ const CBMCall *primitive_carrier = NULL;
+ int member_carrier_count = 0;
+ int free_carrier_count = 0;
+ int primitive_carrier_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->requires_lsp_resolution || call->source_origin != CBM_SOURCE_ORIGIN_RAW ||
+ !call->callee_name || strcmp(call->callee_name, "operator+=") != 0) {
+ continue;
+ }
+ if (qn_ends_with_name(call->enclosing_func_qn, "memberCustom") &&
+ call->site_start_byte == member_start && call->site_end_byte == member_end) {
+ member_carrier = call;
+ member_carrier_count++;
+ }
+ if (qn_ends_with_name(call->enclosing_func_qn, "freeCustom") &&
+ call->site_start_byte == free_start && call->site_end_byte == free_end) {
+ free_carrier = call;
+ free_carrier_count++;
+ }
+ if (qn_ends_with_name(call->enclosing_func_qn, "primitive") &&
+ call->site_start_byte == primitive_start && call->site_end_byte == primitive_end) {
+ primitive_carrier = call;
+ primitive_carrier_count++;
+ }
+ }
+ CHECK_COMPOUND(member_carrier_count == 1, "member_exact_gated_carrier");
+ CHECK_COMPOUND(free_carrier_count == 1, "free_exact_gated_carrier");
+ CHECK_COMPOUND(primitive_carrier_count == 1, "primitive_exact_gated_carrier");
+
+ const CBMResolvedCall *member_semantic = NULL;
+ const CBMResolvedCall *free_semantic = NULL;
+ int member_semantic_count = 0;
+ int free_semantic_count = 0;
+ int member_wrong_target_count = 0;
+ int free_wrong_target_count = 0;
+ int primitive_semantic_count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION ||
+ resolved->source_origin != CBM_SOURCE_ORIGIN_RAW || !resolved->callee_qn ||
+ !qn_ends_with_name(resolved->callee_qn, "operator+=")) {
+ continue;
+ }
+ if (qn_ends_with_name(resolved->caller_qn, "memberCustom") &&
+ resolved->site_start_byte == member_start && resolved->site_end_byte == member_end) {
+ if (member_target_qn && strcmp(resolved->callee_qn, member_target_qn) == 0) {
+ member_semantic = resolved;
+ member_semantic_count++;
+ } else {
+ member_wrong_target_count++;
+ }
+ }
+ if (qn_ends_with_name(resolved->caller_qn, "freeCustom") &&
+ resolved->site_start_byte == free_start && resolved->site_end_byte == free_end) {
+ if (free_target_qn && strcmp(resolved->callee_qn, free_target_qn) == 0) {
+ free_semantic = resolved;
+ free_semantic_count++;
+ } else {
+ free_wrong_target_count++;
+ }
+ }
+ if (qn_ends_with_name(resolved->caller_qn, "primitive") &&
+ resolved->site_start_byte == primitive_start &&
+ resolved->site_end_byte == primitive_end) {
+ primitive_semantic_count++;
+ }
+ }
+ CHECK_COMPOUND(member_semantic_count == 1, "member_exact_semantic_resolution");
+ CHECK_COMPOUND(free_semantic_count == 1, "free_exact_semantic_resolution");
+ CHECK_COMPOUND(member_wrong_target_count == 0, "member_semantic_wrong_target");
+ CHECK_COMPOUND(free_wrong_target_count == 0, "free_semantic_wrong_target");
+ CHECK_COMPOUND(primitive_semantic_count == 0, "primitive_semantic_false_positive");
+
+ const CBMResolvedCall *member_join =
+ member_carrier
+ ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, member_carrier, false)
+ : NULL;
+ const CBMResolvedCall *free_join =
+ free_carrier
+ ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, free_carrier, false)
+ : NULL;
+ const CBMResolvedCall *primitive_join =
+ primitive_carrier
+ ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, primitive_carrier, false)
+ : NULL;
+ CHECK_COMPOUND(member_join && member_join == member_semantic, "member_exact_semantic_join");
+ CHECK_COMPOUND(free_join && free_join == free_semantic, "free_exact_semantic_join");
+ CHECK_COMPOUND(primitive_join == NULL, "primitive_join_false_positive");
+ cbm_free_result(result);
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, test_case->filename, COMPOUND_ASSIGNMENT_SOURCE);
+ if (!store) {
+ fprintf(stderr, " [compound-assignment] lang=%s invariant=index_store_missing\n",
+ test_case->tag);
+ failures++;
+ } else {
+ CHECK_COMPOUND(edge_connects_target_qn(store, project.project, "CALLS", "memberCustom",
+ ".Accumulator.operator+="),
+ "member_graph_call_missing");
+ CHECK_COMPOUND(!edge_connects_target_qn(store, project.project, "CALLS", "memberCustom",
+ ".compound_assignment.operator+="),
+ "member_graph_wrong_target");
+ CHECK_COMPOUND(edge_connects_target_qn(store, project.project, "CALLS", "freeCustom",
+ ".compound_assignment.operator+="),
+ "free_graph_call_missing");
+ CHECK_COMPOUND(!edge_connects_target_qn(store, project.project, "CALLS", "freeCustom",
+ ".Accumulator.operator+="),
+ "free_graph_wrong_target");
+ CHECK_COMPOUND(!edge_connects(store, project.project, "CALLS", "primitive", "operator+="),
+ "primitive_graph_call_false_positive");
+ }
+ rh_cleanup(&project, store);
+#undef CHECK_COMPOUND
+ return failures;
+}
+
+TEST(repro_cpp_cuda_compound_assignment_calls_are_semantic_and_occurrence_exact) {
+ static const CompoundAssignmentCase cases[] = {
+ {"cpp", "compound_assignment.cpp", CBM_LANG_CPP},
+ {"cuda", "compound_assignment.cu", CBM_LANG_CUDA},
+ };
+ int failures = 0;
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++)
+ failures += check_compound_assignment_case(&cases[i]);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_kotlin_synthetic_calls_require_semantic_resolution) {
+ static const char source[] = "class Box { operator fun plus(other: Box): Box = this }\n"
+ "fun mixed(lhs: Box, rhs: Box, a: Int, b: Int) {\n"
+ " val custom = lhs + rhs\n"
+ " val primitive = a + b\n"
+ "}\n";
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), CBM_LANG_KOTLIN, "repro",
+ "Mixed.kt", 0, NULL, NULL);
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ const CBMCall *custom = NULL;
+ const CBMCall *primitive = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->callee_name || strcmp(call->callee_name, "plus") != 0)
+ continue;
+ if (call->start_line == 3)
+ custom = call;
+ if (call->start_line == 4)
+ primitive = call;
+ }
+ ASSERT_NOT_NULL(custom);
+ ASSERT_NOT_NULL(primitive);
+ const CBMResolvedCall *custom_resolution =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, custom, true);
+ const CBMResolvedCall *primitive_resolution =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, primitive, true);
+ ASSERT_NOT_NULL(custom_resolution);
+ ASSERT_TRUE(strstr(custom_resolution->callee_qn, ".Box.plus") != NULL);
+ /* `Int.plus` is a valid semantic LSP resolution, but it is an external
+ * stdlib target and must not borrow the in-project Box.plus occurrence.
+ * The graph-level assertions below prove that no primitive CALLS edge is
+ * emitted; this direct check proves the two occurrence joins stay apart. */
+ if (primitive_resolution) {
+ ASSERT_TRUE(strstr(primitive_resolution->callee_qn, ".Box.plus") == NULL);
+ ASSERT_EQ(primitive_resolution->site_start_byte, primitive->site_start_byte);
+ ASSERT_EQ(primitive_resolution->site_end_byte, primitive->site_end_byte);
+ }
+ cbm_free_result(result);
+
+ static const RFile files[] = {{
+ "Builtins.kt",
+ "class Trap {\n"
+ " fun iterator(): Trap = this\n"
+ " fun component1(): Int = 0\n"
+ "}\n"
+ "fun loopBuiltIn(values: IntArray) { for (value in values) { println(value) } }\n"
+ "fun destructureBuiltIn(value: Pair<Int, Int>) { val (left, right) = value }\n",
+ }};
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin synthetic-call negative fixture did not produce a graph store");
+ }
+ int loop = edge_connects(store, project.project, "CALLS", "loopBuiltIn", "iterator");
+ int component =
+ edge_connects(store, project.project, "CALLS", "destructureBuiltIn", "component1");
+ rh_cleanup(&project, store);
+ ASSERT_FALSE(loop);
+ ASSERT_FALSE(component);
+ PASS();
+}
+
+TEST(repro_callable_reference_parallel_pipeline) {
+ enum { PRIMARY_FILES = 6, FILLER_FILES = 45, TOTAL_FILES = PRIMARY_FILES + FILLER_FILES };
+ static const RFile primary[PRIMARY_FILES] = {
+ {"JavaTarget.java", "class JavaTarget { static void javaHandler() {} }\n"},
+ {"JavaUse.java", "interface JavaTask { void invoke(); }\n"
+ "class JavaUse {\n"
+ " static void acceptJava(JavaTask callback) {}\n"
+ " static void javaReference() { acceptJava(JavaTarget::javaHandler); }\n"
+ "}\n"},
+ {"KotlinTarget.kt", "fun kotlinHandler() {}\n"},
+ {"KotlinUse.kt", "fun acceptKotlin(callback: () -> Unit) {}\n"
+ "fun kotlinReference() { acceptKotlin(::kotlinHandler) }\n"},
+ {"php_target.php", "<?php\nfunction phpHandler(): void {}\n"},
+ {"php_use.php", "<?php\n"
+ "require_once 'php_target.php';\n"
+ "function acceptPhp(callable $callback): void {}\n"
+ "function phpReference(): void { acceptPhp(phpHandler(...)); }\n"},
+ };
+
+ RFile files[TOTAL_FILES];
+ char *filler_names[FILLER_FILES];
+ char *filler_sources[FILLER_FILES];
+ memset(filler_names, 0, sizeof(filler_names));
+ memset(filler_sources, 0, sizeof(filler_sources));
+ for (int i = 0; i < PRIMARY_FILES; i++)
+ files[i] = primary[i];
+
+ int built = PRIMARY_FILES;
+ for (int i = 0; i < FILLER_FILES; i++) {
+ filler_names[i] = malloc(64);
+ filler_sources[i] = malloc(128);
+ if (!filler_names[i] || !filler_sources[i])
+ break;
+ snprintf(filler_names[i], 64, "Filler%02d.java", i);
+ snprintf(filler_sources[i], 128, "class Filler%02d { int value%02d; }\n", i, i);
+ files[built].name = filler_names[i];
+ files[built].content = filler_sources[i];
+ built++;
+ }
+
+ const char *prior_workers = getenv("CBM_WORKERS");
+ char *saved_workers = prior_workers ? cbm_strdup(prior_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "2", 1);
+
+ RProj project;
+ memset(&project, 0, sizeof(project));
+ cbm_store_t *store = built == TOTAL_FILES ? rh_index_files(&project, files, built) : NULL;
+ int failures = 0;
+ if (!store) {
+ fprintf(stderr, " [call-ref] case=parallel invariant=index_store_missing\n");
+ failures++;
+ } else {
+ static const struct {
+ const char *caller;
+ const char *target;
+ } expected[] = {{"javaReference", "javaHandler"},
+ {"kotlinReference", "kotlinHandler"},
+ {"phpReference", "phpHandler"}};
+ for (size_t i = 0; i < sizeof(expected) / sizeof(expected[0]); i++) {
+ if (!edge_connects(store, project.project, "CALL_REFERENCE", expected[i].caller,
+ expected[i].target)) {
+ fprintf(stderr,
+ " [call-ref] case=parallel caller=%s target=%s "
+ "invariant=call_reference_missing\n",
+ expected[i].caller, expected[i].target);
+ failures++;
+ }
+ if (edge_connects(store, project.project, "CALLS", expected[i].caller,
+ expected[i].target) ||
+ edge_connects(store, project.project, "USAGE", expected[i].caller,
+ expected[i].target)) {
+ fprintf(stderr,
+ " [call-ref] case=parallel caller=%s target=%s "
+ "invariant=reference_relationship_not_exclusive\n",
+ expected[i].caller, expected[i].target);
+ failures++;
+ }
+ }
+ }
+
+ rh_cleanup(&project, store);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ for (int i = 0; i < FILLER_FILES; i++) {
+ free(filler_names[i]);
+ free(filler_sources[i]);
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+SUITE(repro_call_argument_usages) {
+ RUN_TEST(repro_call_argument_javascript);
+ RUN_TEST(repro_call_argument_typescript);
+ RUN_TEST(repro_call_argument_go);
+ RUN_TEST(repro_call_argument_python);
+ RUN_TEST(repro_call_argument_c);
+ RUN_TEST(repro_call_argument_cpp);
+ RUN_TEST(repro_call_argument_rust);
+ RUN_TEST(repro_call_argument_csharp);
+ RUN_TEST(repro_call_argument_kotlin);
+ RUN_TEST(repro_call_argument_tsx_raw);
+ RUN_TEST(repro_call_argument_cuda_raw);
+ RUN_TEST(repro_python_local_shadow_does_not_link_global_callable);
+ RUN_TEST(repro_cpp_bare_function_value_usage);
+ RUN_TEST(repro_call_argument_ts_lsp_cannot_rescue);
+ RUN_TEST(repro_call_argument_ts_pipeline_shapes);
+ RUN_TEST(repro_call_argument_javascript_same_file_value_reference);
+ RUN_TEST(repro_call_argument_tsx_same_file_value_reference);
+ RUN_TEST(repro_call_argument_ts_family_forward_declared_value_reference);
+ RUN_TEST(repro_call_argument_ts_nested_and_value_refs);
+ RUN_TEST(repro_call_argument_ts_member_ref);
+ RUN_TEST(repro_call_argument_kotlin_pipeline_join);
+ RUN_TEST(repro_call_argument_java_method_reference_edge);
+ RUN_TEST(repro_java_same_name_references_keep_occurrence_identity);
+ RUN_TEST(repro_kotlin_bound_reference_uses_instance_type);
+ RUN_TEST(repro_php_first_class_callable_reference_edge);
+ RUN_TEST(repro_php_same_name_references_keep_occurrence_identity);
+ RUN_TEST(repro_php_magic_first_class_reference_uses_reason_match);
+ RUN_TEST(repro_cpp_signature_types_preserve_positions_without_changing_legacy_types);
+ RUN_TEST(repro_lsp_language_signatures_preserve_argument_positions);
+ RUN_TEST(repro_cpp_operator_edges_require_semantic_resolution);
+ RUN_TEST(repro_cpp_operator_lsp_join_is_occurrence_exact);
+ RUN_TEST(repro_cpp_cuda_compound_assignment_calls_are_semantic_and_occurrence_exact);
+ RUN_TEST(repro_kotlin_synthetic_calls_require_semantic_resolution);
+ RUN_TEST(repro_callable_reference_parallel_pipeline);
+}
diff --git a/tests/repro/repro_call_node_behaviors.c b/tests/repro/repro_call_node_behaviors.c
new file mode 100644
index 000000000..2a007edca
--- /dev/null
+++ b/tests/repro/repro_call_node_behaviors.c
@@ -0,0 +1,984 @@
+/*
+ * repro_call_node_behaviors.c — raw CALL/USAGE ownership for overloaded and
+ * call-shaped expressions.
+ *
+ * C++ and CUDA deliberately register several expression containers as call
+ * nodes. A container may own one synthetic operator call, one semantic-only
+ * implicit-call candidate, or no call at all; none of those roles allows it to erase
+ * operand references. Scala and Elixir operator syntax follows the same rule.
+ * Puppet resource declarations belong to the DSL extractor and must not be
+ * reinterpreted as generic code calls.
+ *
+ * Every fixture has exactly one target AST node. Every raw count is exact and
+ * joined to the exact qualified name of its caller (or exact module QN for the
+ * top-level Puppet DSL case), so duplicate emissions and scope drift stay RED.
+ */
+#include "test_framework.h"
+#include "cbm.h"
+#include "lang_specs.h"
+#include "macro_table.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+typedef struct {
+ const char *tag;
+ CBMLanguage language;
+ const char *filename;
+ const char *source;
+ const char *ast_kind;
+ const char *reason;
+} BehaviorCase;
+
+static int terminal_name_matches(const char *raw, const char *expected) {
+ if (!raw || !expected)
+ return 0;
+ if (strcmp(raw, expected) == 0)
+ return 1;
+
+ size_t raw_len = strlen(raw);
+ size_t expected_len = strlen(expected);
+ if (raw_len < expected_len)
+ return 0;
+ const char *tail = raw + raw_len - expected_len;
+ if (strcmp(tail, expected) != 0)
+ return 0;
+ if (tail == raw)
+ return 1;
+
+ unsigned char boundary = (unsigned char)tail[-1];
+ return !isalnum(boundary) && boundary != '_';
+}
+
+static void check_exact(const BehaviorCase *test_case, const char *invariant, int actual,
+ int expected, int *failures) {
+ if (actual == expected)
+ return;
+ fprintf(stderr, " [call-node-behavior] case=%s invariant=%s expected=%d actual=%d reason=%s\n",
+ test_case->tag, invariant, expected, actual, test_case->reason);
+ (*failures)++;
+}
+
+static int ast_kind_count(TSNode node, const char *kind) {
+ int count = strcmp(ts_node_type(node), kind) == 0 ? 1 : 0;
+ uint32_t child_count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < child_count; i++)
+ count += ast_kind_count(ts_node_child(node, i), kind);
+ return count;
+}
+
+static void check_exact_ast_kind(const BehaviorCase *test_case, int *failures) {
+ const TSLanguage *language = cbm_ts_language(test_case->language);
+ TSParser *parser = ts_parser_new();
+ if (!language || !parser || !ts_parser_set_language(parser, language)) {
+ fprintf(stderr,
+ " [call-node-behavior] case=%s invariant=ast_parser_ready expected=1 "
+ "actual=0 reason=%s\n",
+ test_case->tag, test_case->reason);
+ (*failures)++;
+ if (parser)
+ ts_parser_delete(parser);
+ return;
+ }
+
+ TSTree *tree = ts_parser_parse_string(parser, NULL, test_case->source,
+ (uint32_t)strlen(test_case->source));
+ int count = 0;
+ int parse_error = 1;
+ if (tree) {
+ TSNode root = ts_tree_root_node(tree);
+ parse_error = ts_node_has_error(root) ? 1 : 0;
+ count = ast_kind_count(root, test_case->ast_kind);
+ }
+ check_exact(test_case, "ast_clean_parse", parse_error, 0, failures);
+ check_exact(test_case, "exact_ast_kind_count", count, 1, failures);
+ if (tree)
+ ts_tree_delete(tree);
+ ts_parser_delete(parser);
+}
+
+static CBMFileResult *extract_case_with_macros(const BehaviorCase *test_case,
+ const CBMMacroTable *macro_table, int *failures) {
+ CBMFileResult *result =
+ cbm_extract_file_ex(test_case->source, (int)strlen(test_case->source), test_case->language,
+ "repro", test_case->filename, 0, NULL, NULL, macro_table, NULL);
+ if (!result) {
+ fprintf(stderr,
+ " [call-node-behavior] case=%s invariant=extract_result expected=non-null "
+ "reason=%s\n",
+ test_case->tag, test_case->reason);
+ (*failures)++;
+ return NULL;
+ }
+ check_exact(test_case, "clean_parse", (result->has_error || result->parse_incomplete) ? 1 : 0,
+ 0, failures);
+ return result;
+}
+
+static CBMFileResult *extract_case(const BehaviorCase *test_case, int *failures) {
+ return extract_case_with_macros(test_case, NULL, failures);
+}
+
+static int call_count_exact(const CBMFileResult *result, const char *caller_qn,
+ const char *callee) {
+ int count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->callee_name && call->enclosing_func_qn &&
+ strcmp(call->callee_name, callee) == 0 &&
+ strcmp(call->enclosing_func_qn, caller_qn) == 0)
+ count++;
+ }
+ return count;
+}
+
+static int usage_count_exact(const CBMFileResult *result, const char *caller_qn,
+ const char *reference) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->ref_name && usage->enclosing_func_qn &&
+ strcmp(usage->ref_name, reference) == 0 &&
+ strcmp(usage->enclosing_func_qn, caller_qn) == 0)
+ count++;
+ }
+ return count;
+}
+
+static int value_usage_count_exact(const CBMFileResult *result, const char *caller_qn,
+ const char *reference) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->ref_name && usage->enclosing_func_qn &&
+ strcmp(usage->ref_name, reference) == 0 &&
+ strcmp(usage->enclosing_func_qn, caller_qn) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int callable_definition_count_exact(const CBMFileResult *result, const char *name,
+ const char *qualified_name) {
+ int count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ int callable_label = definition->label && (strcmp(definition->label, "Function") == 0 ||
+ strcmp(definition->label, "Method") == 0);
+ if (callable_label && definition->name && definition->qualified_name &&
+ strcmp(definition->name, name) == 0 &&
+ strcmp(definition->qualified_name, qualified_name) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int call_count_in_routine(const CBMFileResult *result, const char *caller,
+ const char *callee) {
+ int count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, callee) == 0 &&
+ terminal_name_matches(call->enclosing_func_qn, caller))
+ count++;
+ }
+ return count;
+}
+
+static int exact_semantic_candidate_count_in_routine(const BehaviorCase *test_case,
+ const CBMFileResult *result,
+ const char *caller, const char *callee,
+ const char *site_text) {
+ int count = 0;
+ size_t source_len = strlen(test_case->source);
+ size_t site_len = strlen(site_text);
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->requires_lsp_resolution || !call->callee_name ||
+ strcmp(call->callee_name, callee) != 0 ||
+ !terminal_name_matches(call->enclosing_func_qn, caller) ||
+ call->site_end_byte <= call->site_start_byte || call->site_end_byte > source_len ||
+ (size_t)(call->site_end_byte - call->site_start_byte) != site_len ||
+ strncmp(test_case->source + call->site_start_byte, site_text, site_len) != 0) {
+ continue;
+ }
+ count++;
+ }
+ return count;
+}
+
+static int usage_count_in_routine(const CBMFileResult *result, const char *caller,
+ const char *reference) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->ref_name &&
+ strcmp(usage->ref_name, reference) == 0 &&
+ terminal_name_matches(usage->enclosing_func_qn, caller))
+ count++;
+ }
+ return count;
+}
+
+static int callable_reference_count_in_routine(const CBMFileResult *result, const char *caller,
+ const char *reference) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_CALL_REFERENCE && usage->ref_name &&
+ strcmp(usage->ref_name, reference) == 0 &&
+ terminal_name_matches(usage->enclosing_func_qn, caller))
+ count++;
+ }
+ return count;
+}
+
+static int semantic_reference_candidate_count_in_routine(const CBMFileResult *result,
+ const char *caller,
+ const char *reference) {
+ int count = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->may_be_call_reference && usage->ref_name &&
+ strcmp(usage->ref_name, reference) == 0 &&
+ terminal_name_matches(usage->enclosing_func_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int resolved_call_count_in_routine(const CBMFileResult *result, const char *caller,
+ const char *callee) {
+ int count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *call = &result->resolved_calls.items[i];
+ if (call->kind == CBM_RESOLVED_INVOCATION &&
+ terminal_name_matches(call->caller_qn, caller) &&
+ terminal_name_matches(call->callee_qn, callee)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int resolved_call_total_in_routine(const CBMFileResult *result, const char *caller) {
+ int count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ if (result->resolved_calls.items[i].kind == CBM_RESOLVED_INVOCATION &&
+ terminal_name_matches(result->resolved_calls.items[i].caller_qn, caller)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int resolved_reference_count_in_routine(const CBMFileResult *result, const char *caller,
+ const char *callee) {
+ int count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *reference = &result->resolved_calls.items[i];
+ if (reference->kind == CBM_RESOLVED_CALL_REFERENCE &&
+ terminal_name_matches(reference->caller_qn, caller) &&
+ terminal_name_matches(reference->callee_qn, callee)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static void check_caller_definition(const BehaviorCase *test_case, const CBMFileResult *result,
+ const char *caller, int *failures) {
+ int count = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ int callable_label = definition->label && (strcmp(definition->label, "Function") == 0 ||
+ strcmp(definition->label, "Method") == 0);
+ if (callable_label && definition->name && strcmp(definition->name, caller) == 0 &&
+ terminal_name_matches(definition->qualified_name, caller)) {
+ count++;
+ }
+ }
+ check_exact(test_case, "caller_callable_definition", count, 1, failures);
+}
+
+static const char *checked_module_qn(const BehaviorCase *test_case, const CBMFileResult *result,
+ int *failures) {
+ if (result->module_qn && result->module_qn[0])
+ return result->module_qn;
+ fprintf(stderr,
+ " [call-node-behavior] case=%s invariant=module_qn expected=non-empty reason=%s\n",
+ test_case->tag, test_case->reason);
+ (*failures)++;
+ return "<missing-module-qn>";
+}
+
+static int begin_routine_case(const BehaviorCase *test_case, CBMFileResult **result_out,
+ int *failures) {
+ check_exact_ast_kind(test_case, failures);
+ CBMFileResult *result = extract_case(test_case, failures);
+ *result_out = result;
+ if (!result)
+ return 0;
+ check_caller_definition(test_case, result, "run", failures);
+ return 1;
+}
+
+static int finish_case(CBMFileResult *result, int failures) {
+ if (result)
+ cbm_free_result(result);
+ return failures == 0 ? 0 : 1;
+}
+
+static int run_binary_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "operator_call_in_run",
+ call_count_in_routine(result, "run", "operator+"), 1, &failures);
+ check_exact(test_case, "lhs_usage_in_run", usage_count_in_routine(result, "run", "lhs"), 1,
+ &failures);
+ check_exact(test_case, "rhs_usage_in_run", usage_count_in_routine(result, "run", "rhs"), 1,
+ &failures);
+ check_exact(test_case, "lhs_not_call_in_run", call_count_in_routine(result, "run", "lhs"),
+ 0, &failures);
+ check_exact(test_case, "rhs_not_call_in_run", call_count_in_routine(result, "run", "rhs"),
+ 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_subscript_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "operator_call_in_run",
+ call_count_in_routine(result, "run", "operator[]"), 1, &failures);
+ check_exact(test_case, "receiver_usage_in_run",
+ usage_count_in_routine(result, "run", "receiver"), 1, &failures);
+ check_exact(test_case, "index_usage_in_run", usage_count_in_routine(result, "run", "index"),
+ 1, &failures);
+ check_exact(test_case, "receiver_not_call_in_run",
+ call_count_in_routine(result, "run", "receiver"), 0, &failures);
+ check_exact(test_case, "index_not_call_in_run",
+ call_count_in_routine(result, "run", "index"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_unary_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "operator_call_in_run",
+ call_count_in_routine(result, "run", "operator-"), 1, &failures);
+ check_exact(test_case, "operand_usage_in_run",
+ usage_count_in_routine(result, "run", "operand"), 1, &failures);
+ check_exact(test_case, "operand_not_call_in_run",
+ call_count_in_routine(result, "run", "operand"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_update_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "operator_call_in_run",
+ call_count_in_routine(result, "run", "operator++"), 1, &failures);
+ check_exact(test_case, "operand_usage_in_run",
+ usage_count_in_routine(result, "run", "operand"), 1, &failures);
+ check_exact(test_case, "operand_not_call_in_run",
+ call_count_in_routine(result, "run", "operand"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+/* A delete expression has no textual `~Type` token. The raw call therefore uses
+ * a non-textual `~` candidate at the exact expression span. It is semantic-only:
+ * without a materialized destructor the LSP emits no target and the graph pass
+ * drops the candidate instead of falling back to the operand's spelling. */
+static int run_delete_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "raw_delete_semantic_candidate_in_run",
+ call_count_in_routine(result, "run", "~"), 1, &failures);
+ check_exact(test_case, "raw_delete_candidate_exact_site",
+ exact_semantic_candidate_count_in_routine(test_case, result, "run", "~",
+ "delete victim"),
+ 1, &failures);
+ check_exact(test_case, "operand_usage_in_run",
+ usage_count_in_routine(result, "run", "victim"), 1, &failures);
+ check_exact(test_case, "operand_not_call_in_run",
+ call_count_in_routine(result, "run", "victim"), 0, &failures);
+ check_exact(test_case, "semantic_operator_not_minted_raw",
+ call_count_in_routine(result, "run", "operator delete"), 0, &failures);
+ check_exact(test_case, "unmaterialized_destructor_not_resolved",
+ resolved_call_count_in_routine(result, "run", "~Value"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_field_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "receiver_usage_in_run",
+ usage_count_in_routine(result, "run", "receiver"), 1, &failures);
+ check_exact(test_case, "member_usage_in_run",
+ usage_count_in_routine(result, "run", "member"), 1, &failures);
+ check_exact(test_case, "receiver_not_call_in_run",
+ call_count_in_routine(result, "run", "receiver"), 0, &failures);
+ check_exact(test_case, "member_not_call_in_run",
+ call_count_in_routine(result, "run", "member"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 0, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_callable_value_behavior(const BehaviorCase *test_case,
+ int expect_raw_typed_reference,
+ int expect_semantic_reference) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_caller_definition(test_case, result, "handler", &failures);
+ check_exact(test_case, "outer_accept_call_in_run",
+ call_count_in_routine(result, "run", "accept"), 1, &failures);
+ check_exact(test_case, "handler_value_usage_in_run",
+ usage_count_in_routine(result, "run", "handler"),
+ expect_raw_typed_reference ? 0 : 1, &failures);
+ check_exact(test_case, "handler_callable_reference_in_run",
+ callable_reference_count_in_routine(result, "run", "handler"),
+ expect_raw_typed_reference ? 1 : 0, &failures);
+ check_exact(test_case, "handler_semantic_reference_candidate_in_run",
+ semantic_reference_candidate_count_in_routine(result, "run", "handler"),
+ !expect_raw_typed_reference && expect_semantic_reference ? 1 : 0, &failures);
+ check_exact(test_case, "handler_value_not_invoked_in_run",
+ call_count_in_routine(result, "run", "handler"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+
+ if (expect_semantic_reference) {
+ check_exact(test_case, "lsp_outer_accept_call_in_run",
+ resolved_call_count_in_routine(result, "run", "accept"), 1, &failures);
+ check_exact(test_case, "lsp_handler_value_not_invoked_in_run",
+ resolved_call_count_in_routine(result, "run", "handler"), 0, &failures);
+ check_exact(test_case, "lsp_handler_callable_reference_in_run",
+ resolved_reference_count_in_routine(result, "run", "handler"), 1,
+ &failures);
+ check_exact(test_case, "lsp_total_calls_in_run",
+ resolved_call_total_in_routine(result, "run"), 1, &failures);
+ }
+ }
+ return finish_case(result, failures);
+}
+
+static int run_arrow_behavior(const BehaviorCase *test_case) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(test_case, &result, &failures)) {
+ check_exact(test_case, "operator_arrow_call_in_run",
+ call_count_in_routine(result, "run", "operator->"), 1, &failures);
+ check_exact(test_case, "receiver_usage_in_run",
+ usage_count_in_routine(result, "run", "receiver"), 1, &failures);
+ check_exact(test_case, "member_usage_in_run",
+ usage_count_in_routine(result, "run", "member"), 1, &failures);
+ check_exact(test_case, "receiver_not_call_in_run",
+ call_count_in_routine(result, "run", "receiver"), 0, &failures);
+ check_exact(test_case, "member_not_call_in_run",
+ call_count_in_routine(result, "run", "member"), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static int run_objectscript_call_behavior(const BehaviorCase *test_case, const char *caller_qn,
+ const char *callee, const char *callee_reference,
+ const CBMMacroTable *macro_table) {
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ check_exact_ast_kind(test_case, &failures);
+ result = extract_case_with_macros(test_case, macro_table, &failures);
+ if (result) {
+ check_exact(test_case, "exact_caller_definition",
+ callable_definition_count_exact(result, "run", caller_qn), 1, &failures);
+ check_exact(test_case, "exact_call_owner_and_target",
+ call_count_exact(result, caller_qn, callee), 1, &failures);
+ check_exact(test_case, "argument_usage_in_exact_caller",
+ value_usage_count_exact(result, caller_qn, "watched"), 1, &failures);
+ check_exact(test_case, "argument_not_call_in_exact_caller",
+ call_count_exact(result, caller_qn, "watched"), 0, &failures);
+ check_exact(test_case, "callee_not_usage_in_exact_caller",
+ value_usage_count_exact(result, caller_qn, callee_reference), 0, &failures);
+ check_exact(test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+static const char CPP_BINARY_SOURCE[] = "struct Value {};\n"
+ "Value operator+(Value lhs, Value rhs) { return lhs; }\n"
+ "Value run(Value lhs, Value rhs) { return lhs + rhs; }\n";
+
+static const char CPP_SUBSCRIPT_SOURCE[] =
+ "struct Buffer {\n"
+ " int storage;\n"
+ " int& operator[](int index) { return storage; }\n"
+ "};\n"
+ "int run(Buffer& receiver, int index) { return receiver[index]; }\n";
+
+static const char CPP_UNARY_SOURCE[] = "struct Value {};\n"
+ "Value operator-(Value operand) { return operand; }\n"
+ "Value run(Value operand) { return -operand; }\n";
+
+static const char CPP_UPDATE_SOURCE[] = "struct Counter {\n"
+ " Counter& operator++() { return *this; }\n"
+ "};\n"
+ "Counter& run(Counter& operand) { return ++operand; }\n";
+
+static const char CPP_DELETE_SOURCE[] = "struct Value {};\n"
+ "void run(Value* victim) { delete victim; }\n";
+
+static const char CPP_FIELD_SOURCE[] = "struct Record { int member; };\n"
+ "int run(Record receiver) { return receiver.member; }\n";
+
+static const char CPP_ARROW_SOURCE[] = "struct Target { int member; };\n"
+ "struct Proxy {\n"
+ " Target* target;\n"
+ " Target* operator->() { return target; }\n"
+ "};\n"
+ "int run(Proxy receiver) { return receiver->member; }\n";
+
+static const char CPP_DELETE_COLLISION_SOURCE[] = "struct Value { ~Value() {} };\n"
+ "void victim() {}\n"
+ "void run(Value* victim) { delete victim; }\n";
+
+static const char JAVA_METHOD_REFERENCE_SOURCE[] = "interface Task { void invoke(); }\n"
+ "class Sample {\n"
+ " void handler() {}\n"
+ " void accept(Task callback) {}\n"
+ " void run() { accept(this::handler); }\n"
+ "}\n";
+
+static const char KOTLIN_CALLABLE_REFERENCE_SOURCE[] = "fun handler() {}\n"
+ "fun accept(callback: () -> Unit) {}\n"
+ "fun run() { accept(::handler) }\n";
+
+static const char CSHARP_METHOD_GROUP_SOURCE[] = "delegate void Task();\n"
+ "class Sample {\n"
+ " static void handler() {}\n"
+ " static void accept(Task callback) {}\n"
+ " static void run() { accept(handler); }\n"
+ "}\n";
+
+static const char CPP_FUNCTION_VALUE_SOURCE[] = "void handler() {}\n"
+ "void accept(void (*callback)()) {}\n"
+ "void run() { accept(handler); }\n";
+
+static const char RUST_FUNCTION_ITEM_SOURCE[] = "fn handler() {}\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn run() { accept(handler); }\n";
+
+static const char OBJECTSCRIPT_CLASS_METHOD_SOURCE[] =
+ "Class Sample.Behavior Extends %RegisteredObject\n"
+ "{\n"
+ "Method run(watched As %String) As %Status\n"
+ "{\n"
+ " Do ##class(Sample.Target).accept(watched)\n"
+ " Quit\n"
+ "}\n"
+ "}\n";
+
+static const char OBJECTSCRIPT_METHOD_SOURCE[] =
+ "Class Sample.Behavior Extends %RegisteredObject\n"
+ "{\n"
+ "Method run(target As Sample.Target, watched As %String) As %Status\n"
+ "{\n"
+ " Do target.accept(watched)\n"
+ " Quit\n"
+ "}\n"
+ "}\n";
+
+static const char OBJECTSCRIPT_RELATIVE_DOT_METHOD_SOURCE[] =
+ "Class Sample.Behavior Extends %RegisteredObject\n"
+ "{\n"
+ "Method accept(value As %String) As %Status\n"
+ "{\n"
+ " Quit\n"
+ "}\n"
+ "Method run(watched As %String) As %Status\n"
+ "{\n"
+ " Do ..accept(watched)\n"
+ " Quit\n"
+ "}\n"
+ "}\n";
+
+static const char OBJECTSCRIPT_MACRO_SOURCE[] = "Class Sample.Behavior Extends %RegisteredObject\n"
+ "{\n"
+ "Method run(watched As %Status) As %Status\n"
+ "{\n"
+ " Quit $$$ISERR(watched)\n"
+ "}\n"
+ "}\n";
+
+static const char OBJECTSCRIPT_EXTRINSIC_SOURCE[] = "run(watched)\n"
+ " Quit $$accept(watched)\n"
+ "accept(value)\n"
+ " Quit value\n";
+
+static const char OBJECTSCRIPT_ROUTINE_TAG_SOURCE[] = "run(watched)\n"
+ " Do accept(watched)\n"
+ " Quit\n"
+ "accept(value)\n"
+ " Quit value\n";
+
+static const char SCALA_INFIX_SOURCE[] = "class Box {\n"
+ " def merge(other: Box): Box = this\n"
+ "}\n"
+ "object Sample {\n"
+ " def run(lhs: Box, rhs: Box): Box = lhs merge rhs\n"
+ "}\n";
+
+static const char ELIXIR_BINARY_SOURCE[] = "defmodule Sample do\n"
+ " def run(watched), do: watched + 1\n"
+ "end\n";
+
+static const char PUPPET_RESOURCE_SOURCE[] = "$watched = 'ready'\n"
+ "notify { 'call-node-behavior':\n"
+ " message => $watched,\n"
+ "}\n";
+
+#define DEFINE_CPP_CUDA_BEHAVIOR_TESTS(name, source_value, ast_value, runner, reason_value) \
+ TEST(repro_call_node_behavior_cpp_##name) { \
+ static const BehaviorCase test_case = {"cpp/" #name, CBM_LANG_CPP, "behavior.cpp", \
+ source_value, ast_value, reason_value}; \
+ return runner(&test_case); \
+ } \
+ TEST(repro_call_node_behavior_cuda_##name) { \
+ static const BehaviorCase test_case = {"cuda/" #name, CBM_LANG_CUDA, "behavior.cu", \
+ source_value, ast_value, reason_value}; \
+ return runner(&test_case); \
+ }
+
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ binary, CPP_BINARY_SOURCE, "binary_expression", run_binary_behavior,
+ "binary operator call exists, but operands remain independently visible usages")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ subscript, CPP_SUBSCRIPT_SOURCE, "subscript_expression", run_subscript_behavior,
+ "subscript operator needs one synthetic call without consuming receiver or index usages")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ unary, CPP_UNARY_SOURCE, "unary_expression", run_unary_behavior,
+ "unary overload needs its exact synthetic operator name and operand usage")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ update, CPP_UPDATE_SOURCE, "update_expression", run_update_behavior,
+ "update overload needs one operator++ call while retaining its operand usage")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ delete, CPP_DELETE_SOURCE, "delete_expression", run_delete_behavior,
+ "delete keeps an exact-span semantic candidate plus the independent operand usage")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ field, CPP_FIELD_SOURCE, "field_expression", run_field_behavior,
+ "ordinary member access is a callee wrapper, not a call, and both names are usages")
+DEFINE_CPP_CUDA_BEHAVIOR_TESTS(
+ overloaded_arrow, CPP_ARROW_SOURCE, "field_expression", run_arrow_behavior,
+ "overloaded operator-> is an actual invocation while receiver and member remain usages")
+
+#undef DEFINE_CPP_CUDA_BEHAVIOR_TESTS
+
+TEST(repro_call_node_behavior_objectscript_udl_class_method_call) {
+ static const BehaviorCase test_case = {
+ "objectscript-udl/class-method-call",
+ CBM_LANG_OBJECTSCRIPT_UDL,
+ "Behavior.cls",
+ OBJECTSCRIPT_CLASS_METHOD_SOURCE,
+ "class_method_call",
+ "##class(Sample.Target).accept(watched) has one exact class-method callee while its "
+ "argument remains a value usage"};
+ return run_objectscript_call_behavior(&test_case, "repro.Behavior.Sample.Behavior.run",
+ "Sample.Target.accept", "accept", NULL);
+}
+
+TEST(repro_call_node_behavior_objectscript_udl_method_call) {
+ static const BehaviorCase test_case = {
+ "objectscript-udl/method-call",
+ CBM_LANG_OBJECTSCRIPT_UDL,
+ "Behavior.cls",
+ OBJECTSCRIPT_METHOD_SOURCE,
+ "method_call",
+ "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",
+ "Sample.Target.accept", "accept", NULL);
+}
+
+TEST(repro_call_node_behavior_objectscript_udl_relative_dot_method) {
+ static const BehaviorCase test_case = {
+ "objectscript-udl/relative-dot-method",
+ CBM_LANG_OBJECTSCRIPT_UDL,
+ "Behavior.cls",
+ OBJECTSCRIPT_RELATIVE_DOT_METHOD_SOURCE,
+ "relative_dot_method",
+ "..accept(watched) resolves against the exact enclosing class while watched remains a "
+ "value usage"};
+ return run_objectscript_call_behavior(&test_case, "repro.Behavior.Sample.Behavior.run",
+ "repro.Behavior.Sample.Behavior.accept", "accept", NULL);
+}
+
+TEST(repro_call_node_behavior_objectscript_udl_macro) {
+ static const BehaviorCase test_case = {
+ "objectscript-udl/macro",
+ CBM_LANG_OBJECTSCRIPT_UDL,
+ "Behavior.cls",
+ OBJECTSCRIPT_MACRO_SOURCE,
+ "macro",
+ "the system $$$ISERR(watched) macro maps to %SYSTEM.Status.IsError while watched "
+ "remains a value usage"};
+ CBMMacroTable *macro_table = calloc(1, sizeof(*macro_table));
+ ASSERT_NOT_NULL(macro_table);
+ cbm_macro_table_init_system(macro_table);
+ int status = run_objectscript_call_behavior(&test_case, "repro.Behavior.Sample.Behavior.run",
+ "%SYSTEM.Status.IsError", "ISERR", macro_table);
+ cbm_macro_table_free(macro_table);
+ return status;
+}
+
+TEST(repro_call_node_behavior_objectscript_routine_extrinsic_function) {
+ static const BehaviorCase test_case = {
+ "objectscript-routine/extrinsic-function",
+ CBM_LANG_OBJECTSCRIPT_ROUTINE,
+ "Behavior.mac",
+ OBJECTSCRIPT_EXTRINSIC_SOURCE,
+ "extrinsic_function",
+ "$$accept(watched) belongs to the exact run tag and retains watched as its argument "
+ "usage"};
+ return run_objectscript_call_behavior(&test_case, "repro.Behavior.run", "accept", "accept",
+ NULL);
+}
+
+TEST(repro_call_node_behavior_objectscript_routine_tag_call) {
+ static const BehaviorCase test_case = {
+ "objectscript-routine/routine-tag-call",
+ CBM_LANG_OBJECTSCRIPT_ROUTINE,
+ "Behavior.mac",
+ OBJECTSCRIPT_ROUTINE_TAG_SOURCE,
+ "routine_tag_call",
+ "Do accept(watched) belongs to the exact run tag and retains watched as its argument "
+ "usage"};
+ return run_objectscript_call_behavior(&test_case, "repro.Behavior.run", "accept", "accept",
+ NULL);
+}
+
+TEST(repro_call_node_behavior_scala_user_infix) {
+ static const BehaviorCase test_case = {
+ "scala/user-infix",
+ CBM_LANG_SCALA,
+ "Behavior.scala",
+ SCALA_INFIX_SOURCE,
+ "infix_expression",
+ "user-defined infix merge is the callee while lhs and rhs remain value usages"};
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(&test_case, &result, &failures)) {
+ check_exact(&test_case, "merge_call_in_run", call_count_in_routine(result, "run", "merge"),
+ 1, &failures);
+ check_exact(&test_case, "lhs_usage_in_run", usage_count_in_routine(result, "run", "lhs"), 1,
+ &failures);
+ check_exact(&test_case, "rhs_usage_in_run", usage_count_in_routine(result, "run", "rhs"), 1,
+ &failures);
+ check_exact(&test_case, "lhs_not_call_in_run", call_count_in_routine(result, "run", "lhs"),
+ 0, &failures);
+ check_exact(&test_case, "rhs_not_call_in_run", call_count_in_routine(result, "run", "rhs"),
+ 0, &failures);
+ check_exact(&test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+TEST(repro_call_node_behavior_elixir_binary_plus) {
+ static const BehaviorCase test_case = {
+ "elixir/binary-plus",
+ CBM_LANG_ELIXIR,
+ "behavior.ex",
+ ELIXIR_BINARY_SOURCE,
+ "binary_operator",
+ "binary + belongs to the operator callee, not to its watched operand"};
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(&test_case, &result, &failures)) {
+ check_exact(&test_case, "plus_call_in_run", call_count_in_routine(result, "run", "+"), 1,
+ &failures);
+ check_exact(&test_case, "operand_usage_in_run",
+ usage_count_in_routine(result, "run", "watched"), 1, &failures);
+ check_exact(&test_case, "operand_not_call_in_run",
+ call_count_in_routine(result, "run", "watched"), 0, &failures);
+ check_exact(&test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+TEST(repro_call_node_behavior_puppet_resource_ownership) {
+ static const BehaviorCase test_case = {
+ "puppet/resource",
+ CBM_LANG_PUPPET,
+ "behavior.pp",
+ PUPPET_RESOURCE_SOURCE,
+ "resource_declaration",
+ "resource declarations are Puppet DSL ownership and must not fabricate generic calls"};
+ int failures = 0;
+ check_exact_ast_kind(&test_case, &failures);
+ CBMFileResult *result = extract_case(&test_case, &failures);
+ if (result) {
+ const char *module_qn = checked_module_qn(&test_case, result, &failures);
+ check_exact(&test_case, "resource_value_usage_in_module",
+ usage_count_exact(result, module_qn, "$watched"), 1, &failures);
+ check_exact(&test_case, "variable_not_call_in_module",
+ call_count_exact(result, module_qn, "$watched"), 0, &failures);
+ check_exact(&test_case, "total_calls", result->calls.count, 0, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+TEST(repro_call_node_behavior_java_method_reference_value) {
+ static const BehaviorCase test_case = {
+ "java/method-reference-value",
+ CBM_LANG_JAVA,
+ "Behavior.java",
+ JAVA_METHOD_REFERENCE_SOURCE,
+ "method_reference",
+ "a Java method reference is a value, not an invocation at the reference site"};
+ return run_callable_value_behavior(&test_case, 1, 1);
+}
+
+TEST(repro_call_node_behavior_kotlin_callable_reference_value) {
+ static const BehaviorCase test_case = {
+ "kotlin/callable-reference-value",
+ CBM_LANG_KOTLIN,
+ "Behavior.kt",
+ KOTLIN_CALLABLE_REFERENCE_SOURCE,
+ "callable_reference",
+ "a Kotlin callable reference is a value, not an invocation at the reference site"};
+ return run_callable_value_behavior(&test_case, 0, 1);
+}
+
+TEST(repro_call_node_behavior_csharp_method_group_value) {
+ static const BehaviorCase test_case = {
+ "csharp/method-group-value",
+ CBM_LANG_CSHARP,
+ "Behavior.cs",
+ CSHARP_METHOD_GROUP_SOURCE,
+ "invocation_expression",
+ "a C# method group passed as an argument is a value, not a handler invocation"};
+ return run_callable_value_behavior(&test_case, 0, 1);
+}
+
+TEST(repro_call_node_behavior_cpp_function_value) {
+ static const BehaviorCase test_case = {
+ "cpp/function-value",
+ CBM_LANG_CPP,
+ "behavior.cpp",
+ CPP_FUNCTION_VALUE_SOURCE,
+ "call_expression",
+ "a C++ function value passed as an argument is referenced but not invoked"};
+ return run_callable_value_behavior(&test_case, 0, 1);
+}
+
+TEST(repro_call_node_behavior_rust_function_item_value) {
+ static const BehaviorCase test_case = {
+ "rust/function-item-value",
+ CBM_LANG_RUST,
+ "behavior.rs",
+ RUST_FUNCTION_ITEM_SOURCE,
+ "call_expression",
+ "a Rust function item passed as an argument is referenced but not invoked"};
+ return run_callable_value_behavior(&test_case, 0, 1);
+}
+
+TEST(repro_call_node_behavior_cpp_delete_name_collision) {
+ static const BehaviorCase test_case = {
+ "cpp/delete-name-collision",
+ CBM_LANG_CPP,
+ "behavior.cpp",
+ CPP_DELETE_COLLISION_SOURCE,
+ "delete_expression",
+ "delete must key the implicit ~Value destructor, not operand text that collides with "
+ "victim()"};
+ int failures = 0;
+ CBMFileResult *result = NULL;
+ if (begin_routine_case(&test_case, &result, &failures)) {
+ check_caller_definition(&test_case, result, "victim", &failures);
+ check_exact(&test_case, "destructor_call_in_run",
+ call_count_in_routine(result, "run", "~Value"), 1, &failures);
+ check_exact(&test_case, "destructor_candidate_exact_site",
+ exact_semantic_candidate_count_in_routine(&test_case, result, "run", "~Value",
+ "delete victim"),
+ 1, &failures);
+ check_exact(&test_case, "operand_usage_in_run",
+ usage_count_in_routine(result, "run", "victim"), 1, &failures);
+ check_exact(&test_case, "unrelated_victim_not_called_in_run",
+ call_count_in_routine(result, "run", "victim"), 0, &failures);
+ check_exact(&test_case, "lsp_destructor_call_in_run",
+ resolved_call_count_in_routine(result, "run", "~Value"), 1, &failures);
+ check_exact(&test_case, "lsp_unrelated_victim_not_called_in_run",
+ resolved_call_count_in_routine(result, "run", "victim"), 0, &failures);
+ check_exact(&test_case, "lsp_total_calls_in_run",
+ resolved_call_total_in_routine(result, "run"), 1, &failures);
+ check_exact(&test_case, "total_calls", result->calls.count, 1, &failures);
+ }
+ return finish_case(result, failures);
+}
+
+enum {
+ CPP_BEHAVIOR_COUNT = 9,
+ CUDA_BEHAVIOR_COUNT = 7,
+ OTHER_BEHAVIOR_COUNT = 7,
+ OBJECTSCRIPT_BEHAVIOR_COUNT = 6,
+ CALL_NODE_BEHAVIOR_COUNT = CPP_BEHAVIOR_COUNT + CUDA_BEHAVIOR_COUNT + OTHER_BEHAVIOR_COUNT +
+ OBJECTSCRIPT_BEHAVIOR_COUNT,
+};
+
+_Static_assert(CALL_NODE_BEHAVIOR_COUNT == 29,
+ "call-node behavior suite must retain 23 contracts and add 6 ObjectScript "
+ "call-role guards");
+
+SUITE(repro_call_node_behaviors) {
+ RUN_TEST(repro_call_node_behavior_cpp_binary);
+ RUN_TEST(repro_call_node_behavior_cpp_subscript);
+ RUN_TEST(repro_call_node_behavior_cpp_unary);
+ RUN_TEST(repro_call_node_behavior_cpp_update);
+ RUN_TEST(repro_call_node_behavior_cpp_delete);
+ RUN_TEST(repro_call_node_behavior_cpp_field);
+ RUN_TEST(repro_call_node_behavior_cpp_overloaded_arrow);
+ RUN_TEST(repro_call_node_behavior_cpp_function_value);
+ RUN_TEST(repro_call_node_behavior_cpp_delete_name_collision);
+
+ RUN_TEST(repro_call_node_behavior_cuda_binary);
+ RUN_TEST(repro_call_node_behavior_cuda_subscript);
+ RUN_TEST(repro_call_node_behavior_cuda_unary);
+ RUN_TEST(repro_call_node_behavior_cuda_update);
+ RUN_TEST(repro_call_node_behavior_cuda_delete);
+ RUN_TEST(repro_call_node_behavior_cuda_field);
+ RUN_TEST(repro_call_node_behavior_cuda_overloaded_arrow);
+
+ RUN_TEST(repro_call_node_behavior_objectscript_udl_class_method_call);
+ RUN_TEST(repro_call_node_behavior_objectscript_udl_method_call);
+ RUN_TEST(repro_call_node_behavior_objectscript_udl_relative_dot_method);
+ RUN_TEST(repro_call_node_behavior_objectscript_udl_macro);
+ RUN_TEST(repro_call_node_behavior_objectscript_routine_extrinsic_function);
+ RUN_TEST(repro_call_node_behavior_objectscript_routine_tag_call);
+
+ RUN_TEST(repro_call_node_behavior_scala_user_infix);
+ RUN_TEST(repro_call_node_behavior_elixir_binary_plus);
+ RUN_TEST(repro_call_node_behavior_puppet_resource_ownership);
+ RUN_TEST(repro_call_node_behavior_java_method_reference_value);
+ RUN_TEST(repro_call_node_behavior_kotlin_callable_reference_value);
+ RUN_TEST(repro_call_node_behavior_csharp_method_group_value);
+ RUN_TEST(repro_call_node_behavior_rust_function_item_value);
+}
diff --git a/tests/repro/repro_call_node_manifest.c b/tests/repro/repro_call_node_manifest.c
new file mode 100644
index 000000000..822176a4c
--- /dev/null
+++ b/tests/repro/repro_call_node_manifest.c
@@ -0,0 +1,638 @@
+/*
+ * Exhaustive contract for call-node metadata.
+ *
+ * This ledger is intentionally literal. Semantic role and extraction ownership
+ * are independent review decisions; neither field supplies a default for the
+ * other. Every row also states whether it belonged to the historical metadata
+ * snapshot and whether it belongs in the primary call-node registry.
+ *
+ * This metadata contract is not proof of extraction behavior. Changes must also
+ * pass the focused repro_call_scope_usages, repro_call_argument_matrix_a,
+ * repro_call_argument_matrix_b, repro_lsp_c_cpp, repro_grammar_build, and
+ * repro_grammar_shells suites before production metadata is changed.
+ * C++/CUDA operator rows require raw-call-to-LSP assertions in repro_lsp_c_cpp;
+ * Scala/Elixir direct operators require operand-scope assertions in the call
+ * argument suites; Puppet resource ownership remains gated by repro_grammar_build.
+ * TLA+ bound_op is historical direct-call metadata. Bounded quantification is
+ * not a historical ledger row; repro_call_argument_matrix_b is its separate
+ * negative behavior guard.
+ */
+#include "test_framework.h"
+#include "lang_specs.h"
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+typedef enum {
+ DIRECT_CALL = 0,
+ CONSTRUCTOR_CALL,
+ OPERATOR_CALL,
+ IMPLICIT_CALL,
+ DSL_INVOCATION,
+ BUILD_DEPENDENCY,
+ CALLEE_WRAPPER,
+ ARGUMENT_WRAPPER,
+ CONTROL_OR_DOCUMENT_NONCALL,
+ CALL_SEMANTIC_ROLE_COUNT
+} CallSemanticRole;
+
+typedef enum {
+ PRIMARY_EXTRACTOR = 0,
+ SYNTHETIC_EXTRACTOR,
+ NO_CALL_EDGE,
+ CALL_EXTRACTION_OWNER_COUNT
+} CallExtractionOwner;
+
+typedef struct {
+ CBMLanguage language;
+ const char *node_kind;
+ CallSemanticRole semantic_role;
+ CallExtractionOwner extraction_owner;
+ bool historically_registered;
+ bool expected_primary_registered;
+} CallNodeManifestEntry;
+
+enum {
+ EXPECTED_HISTORICAL_CALL_NODE_TOTAL = 219,
+ EXPECTED_ACTIVE_PRIMARY_TOTAL = 189,
+ EXPECTED_DIRECT_CALLS = 155,
+ EXPECTED_CONSTRUCTOR_CALLS = 20,
+ EXPECTED_OPERATOR_CALLS = 12,
+ EXPECTED_IMPLICIT_CALLS = 2,
+ EXPECTED_DSL_INVOCATIONS = 14,
+ EXPECTED_BUILD_DEPENDENCIES = 1,
+ EXPECTED_CALLEE_WRAPPERS = 8,
+ EXPECTED_ARGUMENT_WRAPPERS = 1,
+ EXPECTED_CONTROL_OR_DOCUMENT_NONCALLS = 6,
+ EXPECTED_PRIMARY_OWNERS = 189,
+ EXPECTED_SYNTHETIC_OWNERS = 10,
+ EXPECTED_NO_CALL_EDGE_OWNERS = 20,
+ EXPECTED_PRIMARY_OPERATOR_CALLS = 4,
+ EXPECTED_SYNTHETIC_OPERATOR_CALLS = 8,
+};
+
+#define ENTRY(language, kind, role, owner, historical, expected_primary) \
+ {language, kind, role, owner, historical, expected_primary}
+
+static const CallNodeManifestEntry CALL_NODE_MANIFEST[] = {
+ ENTRY(CBM_LANG_GO, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PYTHON, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PYTHON, "with_statement", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true,
+ false),
+ ENTRY(CBM_LANG_JAVASCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JAVASCRIPT, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TYPESCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TYPESCRIPT, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TSX, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TSX, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_RUST, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_RUST, "macro_invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JAVA, "method_invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JAVA, "object_creation_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_CPP, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CPP, "field_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_CPP, "subscript_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CPP, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CPP, "delete_expression", IMPLICIT_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CPP, "binary_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CPP, "unary_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CPP, "update_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CSHARP, "invocation_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CSHARP, "object_creation_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_PHP, "member_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PHP, "scoped_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PHP, "function_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PHP, "object_creation_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_PHP, "nullsafe_member_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_LUA, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCALA, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCALA, "generic_function", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_SCALA, "field_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_SCALA, "infix_expression", OPERATOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCALA, "instance_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_KOTLIN, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_KOTLIN, "navigation_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_RUBY, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_RUBY, "command_call", DIRECT_CALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_C, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_BASH, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ZIG, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ZIG, "builtin_function", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ELIXIR, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ELIXIR, "dot", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_ELIXIR, "binary_operator", OPERATOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HASKELL, "infix", OPERATOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HASKELL, "apply", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OCAML, "application_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OCAML, "infix_expression", OPERATOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OCAML, "method_invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OCAML, "module_application", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OCAML, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OBJC, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_OBJC, "message_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SWIFT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SWIFT, "constructor_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_SWIFT, "macro_invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SWIFT, "navigation_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_DART, "selector", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_DART, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PERL, "ambiguous_function_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_PERL, "function_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PERL, "func1op_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PERL, "method_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GROOVY, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GROOVY, "juxt_function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ERLANG, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_R, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CSS, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCSS, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCSS, "include_statement", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HCL, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SQL, "function_call", DIRECT_CALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_SQL, "invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SQL, "command", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_CLOJURE, "list_lit", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FSHARP, "application_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FSHARP, "dot_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_JULIA, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JULIA, "broadcast_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VIMSCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VIMSCRIPT, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VIMSCRIPT, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_NIX, "apply_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_COMMONLISP, "list_lit", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ELM, "function_call", DIRECT_CALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_ELM, "function_call_expr", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FORTRAN, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FORTRAN, "keyword_argument", ARGUMENT_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_FORTRAN, "subroutine_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CUDA, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CUDA, "field_expression", CALLEE_WRAPPER, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_CUDA, "subscript_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CUDA, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CUDA, "delete_expression", IMPLICIT_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CUDA, "binary_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CUDA, "unary_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_CUDA, "update_expression", OPERATOR_CALL, SYNTHETIC_EXTRACTOR, true, false),
+ ENTRY(CBM_LANG_COBOL, "call_statement", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VERILOG, "system_tf_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VERILOG, "subroutine_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VERILOG, "function_subroutine_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VERILOG, "method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_EMACSLISP, "list", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MAKEFILE, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MAKEFILE, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MAKEFILE, "shell_function", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CMAKE, "normal_command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MESON, "normal_command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GLSL, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MATLAB, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MATLAB, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LEAN, "apply", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LEAN, "command", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_FORM, "call_statement", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MAGMA, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_WOLFRAM, "apply", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SOLIDITY, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SOLIDITY, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SOLIDITY, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TYPST, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GDSCRIPT, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GDSCRIPT, "attribute_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GDSCRIPT, "base_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_QML, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_QML, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CFSCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CFSCRIPT, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CFML, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GLEAM, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_POWERSHELL, "invokation_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_POWERSHELL, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PASCAL, "exprCall", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_DLANG, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_DLANG, "function_call_expression", DIRECT_CALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_DLANG, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SCHEME, "list", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FENNEL, "list", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FISH, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_AWK, "func_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_AWK, "command", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_ZSH, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ZSH, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TCL, "command", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ADA, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ADA, "procedure_call_statement", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_AGDA, "module_application", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_AGDA, "expr", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_RACKET, "list", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ODIN, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ODIN, "selector_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_RESCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PURESCRIPT, "exp_apply", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_NICKEL, "applicative", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CRYSTAL, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CRYSTAL, "command", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CRYSTAL, "implicit_object_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TEAL, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HARE, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PONY, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LUAU, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SWAY, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SWAY, "abi_call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_NASM, "call_syntax_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_NASM, "actual_instruction", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JUST, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JUST, "dependency", BUILD_DEPENDENCY, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GOTEMPLATE, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GOTEMPLATE, "method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GOTEMPLATE, "template_action", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TEMPL, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PRISMA, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_DIFF, "command", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_WGSL, "type_constructor_or_function_call_expression", DIRECT_CALL,
+ PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_JSONNET, "functioncall", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_BIBTEX, "command", CONTROL_OR_DOCUMENT_NONCALL, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_STARLARK, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_BICEP, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HLSL, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_HLSL, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VHDL, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VHDL, "procedure_call_statement", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_VHDL, "component_instantiation_statement", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR,
+ true, true),
+ ENTRY(CBM_LANG_VHDL, "parenthesis_group", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SYSTEMVERILOG, "function_subroutine_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_SYSTEMVERILOG, "system_tf_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SYSTEMVERILOG, "method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_DEVICETREE, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LINKERSCRIPT, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_GN, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_BITBAKE, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ISPC, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_ISPC, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CAIRO, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_CAIRO, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_MOVE, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SQUIRREL, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FUNC, "method_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_FUNC, "function_application", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PUPPET, "function_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PUPPET, "resource_declaration", DSL_INVOCATION, NO_CALL_EDGE, true, false),
+ ENTRY(CBM_LANG_PUPPET, "include_statement", DSL_INVOCATION, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SLANG, "call_expression", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_SLANG, "new_expression", CONSTRUCTOR_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LLVM_IR, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LLVM_IR, "invoke", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_LLVM_IR, "instruction_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TLAPLUS, "function_evaluation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TLAPLUS, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_TLAPLUS, "bound_op", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_APEX, "method_invocation", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ ENTRY(CBM_LANG_PINE, "call", DIRECT_CALL, PRIMARY_EXTRACTOR, true, true),
+ 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),
+ ENTRY(CBM_LANG_OBJECTSCRIPT_ROUTINE, "extrinsic_function", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+ ENTRY(CBM_LANG_OBJECTSCRIPT_ROUTINE, "routine_tag_call", DIRECT_CALL, PRIMARY_EXTRACTOR, true,
+ true),
+};
+
+#undef ENTRY
+
+#define MANIFEST_COUNT (sizeof(CALL_NODE_MANIFEST) / sizeof(CALL_NODE_MANIFEST[0]))
+
+_Static_assert(MANIFEST_COUNT == EXPECTED_HISTORICAL_CALL_NODE_TOTAL,
+ "call-node manifest must contain exactly 219 entries");
+_Static_assert(EXPECTED_DIRECT_CALLS + EXPECTED_CONSTRUCTOR_CALLS + EXPECTED_OPERATOR_CALLS +
+ EXPECTED_IMPLICIT_CALLS + EXPECTED_DSL_INVOCATIONS +
+ EXPECTED_BUILD_DEPENDENCIES + EXPECTED_CALLEE_WRAPPERS +
+ EXPECTED_ARGUMENT_WRAPPERS + EXPECTED_CONTROL_OR_DOCUMENT_NONCALLS ==
+ EXPECTED_HISTORICAL_CALL_NODE_TOTAL,
+ "semantic-role partition must cover the historical manifest");
+_Static_assert(EXPECTED_PRIMARY_OWNERS + EXPECTED_SYNTHETIC_OWNERS + EXPECTED_NO_CALL_EDGE_OWNERS ==
+ EXPECTED_HISTORICAL_CALL_NODE_TOTAL,
+ "extraction-owner partition must cover the historical manifest");
+_Static_assert(EXPECTED_PRIMARY_OWNERS == EXPECTED_ACTIVE_PRIMARY_TOTAL,
+ "primary-owner and active-primary totals must agree");
+_Static_assert(EXPECTED_PRIMARY_OPERATOR_CALLS + EXPECTED_SYNTHETIC_OPERATOR_CALLS ==
+ EXPECTED_OPERATOR_CALLS,
+ "operator calls must have an explicit direct or synthetic owner");
+
+static int manifest_match_count(CBMLanguage language, const char *node_kind) {
+ int matches = 0;
+ for (size_t i = 0; i < MANIFEST_COUNT; i++) {
+ const CallNodeManifestEntry *entry = &CALL_NODE_MANIFEST[i];
+ if (entry->language == language && strcmp(entry->node_kind, node_kind) == 0) {
+ matches++;
+ }
+ }
+ return matches;
+}
+
+static int spec_match_count(const CBMLangSpec *spec, const char *node_kind) {
+ int matches = 0;
+ if (!spec || !spec->call_node_types) {
+ return 0;
+ }
+ for (int i = 0; spec->call_node_types[i]; i++) {
+ if (strcmp(spec->call_node_types[i], node_kind) == 0) {
+ matches++;
+ }
+ }
+ return matches;
+}
+
+TEST(repro_call_node_manifest_is_unique_and_partitioned) {
+ int failures = 0;
+ int role_counts[CALL_SEMANTIC_ROLE_COUNT] = {0};
+ int owner_counts[CALL_EXTRACTION_OWNER_COUNT] = {0};
+ int historical_total = 0;
+ int expected_primary_total = 0;
+ int primary_operator_calls = 0;
+ int synthetic_operator_calls = 0;
+
+ if (MANIFEST_COUNT != EXPECTED_HISTORICAL_CALL_NODE_TOTAL) {
+ fprintf(stderr, " [call-node-manifest] invariant=table_total expected=%d actual=%zu\n",
+ EXPECTED_HISTORICAL_CALL_NODE_TOTAL, MANIFEST_COUNT);
+ failures++;
+ }
+
+ for (size_t i = 0; i < MANIFEST_COUNT; i++) {
+ const CallNodeManifestEntry *entry = &CALL_NODE_MANIFEST[i];
+ if (entry->language < 0 || entry->language >= CBM_LANG_COUNT ||
+ entry->language == CBM_LANG_NIM) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=invalid_language index=%zu language=%d\n", i,
+ (int)entry->language);
+ failures++;
+ }
+ if (!entry->node_kind || !entry->node_kind[0]) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=empty_node_kind index=%zu language=%d\n", i,
+ (int)entry->language);
+ failures++;
+ }
+ if (entry->semantic_role < DIRECT_CALL ||
+ entry->semantic_role >= CALL_SEMANTIC_ROLE_COUNT) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=invalid_role index=%zu language=%d role=%d\n",
+ i, (int)entry->language, (int)entry->semantic_role);
+ failures++;
+ } else {
+ role_counts[entry->semantic_role]++;
+ }
+ if (entry->extraction_owner < PRIMARY_EXTRACTOR ||
+ entry->extraction_owner >= CALL_EXTRACTION_OWNER_COUNT) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=invalid_owner index=%zu language=%d "
+ "owner=%d\n",
+ i, (int)entry->language, (int)entry->extraction_owner);
+ failures++;
+ } else {
+ owner_counts[entry->extraction_owner]++;
+ }
+
+ if (!entry->historically_registered) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=historical_snapshot_gap index=%zu "
+ "language=%d node=%s\n",
+ i, (int)entry->language, entry->node_kind);
+ failures++;
+ } else {
+ historical_total++;
+ }
+ if (entry->expected_primary_registered) {
+ expected_primary_total++;
+ }
+
+ /*
+ * Direct operator models are PRIMARY_EXTRACTOR entries. C++/CUDA
+ * operator triggers owned by synthetic extraction must not also create
+ * generic primary scopes or raw calls.
+ */
+ if (entry->extraction_owner == SYNTHETIC_EXTRACTOR && entry->expected_primary_registered) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=synthetic_owner_registered_primary "
+ "language=%d node=%s role=%d\n",
+ (int)entry->language, entry->node_kind, (int)entry->semantic_role);
+ failures++;
+ }
+ if (entry->extraction_owner == NO_CALL_EDGE && entry->expected_primary_registered) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=no_edge_owner_registered_primary "
+ "language=%d node=%s role=%d\n",
+ (int)entry->language, entry->node_kind, (int)entry->semantic_role);
+ failures++;
+ }
+ if ((entry->extraction_owner == PRIMARY_EXTRACTOR) != entry->expected_primary_registered) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=primary_owner_membership_mismatch "
+ "language=%d node=%s owner=%d expected_primary=%d\n",
+ (int)entry->language, entry->node_kind, (int)entry->extraction_owner,
+ entry->expected_primary_registered);
+ failures++;
+ }
+
+ if (entry->semantic_role == OPERATOR_CALL) {
+ if (entry->extraction_owner == PRIMARY_EXTRACTOR) {
+ primary_operator_calls++;
+ } else if (entry->extraction_owner == SYNTHETIC_EXTRACTOR) {
+ synthetic_operator_calls++;
+ } else {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=operator_without_extractor "
+ "language=%d node=%s\n",
+ (int)entry->language, entry->node_kind);
+ failures++;
+ }
+ }
+
+ for (size_t j = i + 1; j < MANIFEST_COUNT; j++) {
+ const CallNodeManifestEntry *other = &CALL_NODE_MANIFEST[j];
+ if (entry->language == other->language && entry->node_kind && other->node_kind &&
+ strcmp(entry->node_kind, other->node_kind) == 0) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=duplicate_table_entry language=%d "
+ "node=%s first=%zu second=%zu\n",
+ (int)entry->language, entry->node_kind, i, j);
+ failures++;
+ }
+ }
+ }
+
+ if (historical_total != EXPECTED_HISTORICAL_CALL_NODE_TOTAL ||
+ expected_primary_total != EXPECTED_ACTIVE_PRIMARY_TOTAL) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=registration_partition historical=%d "
+ "expected_primary=%d\n",
+ historical_total, expected_primary_total);
+ failures++;
+ }
+
+ if (role_counts[DIRECT_CALL] != EXPECTED_DIRECT_CALLS ||
+ role_counts[CONSTRUCTOR_CALL] != EXPECTED_CONSTRUCTOR_CALLS ||
+ role_counts[OPERATOR_CALL] != EXPECTED_OPERATOR_CALLS ||
+ role_counts[IMPLICIT_CALL] != EXPECTED_IMPLICIT_CALLS ||
+ role_counts[DSL_INVOCATION] != EXPECTED_DSL_INVOCATIONS ||
+ role_counts[BUILD_DEPENDENCY] != EXPECTED_BUILD_DEPENDENCIES ||
+ role_counts[CALLEE_WRAPPER] != EXPECTED_CALLEE_WRAPPERS ||
+ role_counts[ARGUMENT_WRAPPER] != EXPECTED_ARGUMENT_WRAPPERS ||
+ role_counts[CONTROL_OR_DOCUMENT_NONCALL] != EXPECTED_CONTROL_OR_DOCUMENT_NONCALLS) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=semantic_role_partition direct=%d "
+ "constructor=%d operator=%d implicit=%d dsl=%d build=%d callee_wrapper=%d "
+ "argument_wrapper=%d control_or_document=%d\n",
+ role_counts[DIRECT_CALL], role_counts[CONSTRUCTOR_CALL], role_counts[OPERATOR_CALL],
+ role_counts[IMPLICIT_CALL], role_counts[DSL_INVOCATION],
+ role_counts[BUILD_DEPENDENCY], role_counts[CALLEE_WRAPPER],
+ role_counts[ARGUMENT_WRAPPER], role_counts[CONTROL_OR_DOCUMENT_NONCALL]);
+ failures++;
+ }
+
+ if (owner_counts[PRIMARY_EXTRACTOR] != EXPECTED_PRIMARY_OWNERS ||
+ owner_counts[SYNTHETIC_EXTRACTOR] != EXPECTED_SYNTHETIC_OWNERS ||
+ owner_counts[NO_CALL_EDGE] != EXPECTED_NO_CALL_EDGE_OWNERS) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=extraction_owner_partition primary=%d "
+ "synthetic=%d no_call_edge=%d\n",
+ owner_counts[PRIMARY_EXTRACTOR], owner_counts[SYNTHETIC_EXTRACTOR],
+ owner_counts[NO_CALL_EDGE]);
+ failures++;
+ }
+
+ if (primary_operator_calls != EXPECTED_PRIMARY_OPERATOR_CALLS ||
+ synthetic_operator_calls != EXPECTED_SYNTHETIC_OPERATOR_CALLS) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=operator_owner_partition primary=%d "
+ "synthetic=%d\n",
+ primary_operator_calls, synthetic_operator_calls);
+ failures++;
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_node_manifest_live_specs_contain_only_expected_primary_entries) {
+ int failures = 0;
+ int runtime_total = 0;
+
+ for (int value = 0; value < CBM_LANG_COUNT; value++) {
+ CBMLanguage language = (CBMLanguage)value;
+ const CBMLangSpec *spec = cbm_lang_spec(language);
+
+ /* The registry reproduction owns Nim's stale enum and Studio Export's
+ * transform-only, intentionally grammar-free classification. */
+ if (language == CBM_LANG_NIM || language == CBM_LANG_OBJECTSCRIPT_EXPORT) {
+ continue;
+ }
+ if (!spec || spec->language != language) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=live_spec_missing language=%d actual=%d\n",
+ value, spec ? (int)spec->language : -1);
+ failures++;
+ continue;
+ }
+ if (!spec->call_node_types) {
+ continue;
+ }
+
+ for (int i = 0; spec->call_node_types[i]; i++) {
+ const char *node_kind = spec->call_node_types[i];
+ runtime_total++;
+
+ int table_matches = manifest_match_count(language, node_kind);
+ if (table_matches != 1) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=live_to_table language=%d node=%s "
+ "matches=%d\n",
+ value, node_kind, table_matches);
+ failures++;
+ } else {
+ for (size_t manifest_index = 0; manifest_index < MANIFEST_COUNT; manifest_index++) {
+ const CallNodeManifestEntry *entry = &CALL_NODE_MANIFEST[manifest_index];
+ if (entry->language == language && strcmp(entry->node_kind, node_kind) == 0 &&
+ !entry->expected_primary_registered) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=unexpected_primary_registration "
+ "language=%d node=%s role=%d owner=%d\n",
+ value, node_kind, (int)entry->semantic_role,
+ (int)entry->extraction_owner);
+ failures++;
+ break;
+ }
+ }
+ }
+ for (int j = 0; j < i; j++) {
+ if (strcmp(spec->call_node_types[j], node_kind) == 0) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=duplicate_live_kind language=%d "
+ "node=%s first=%d second=%d\n",
+ value, node_kind, j, i);
+ failures++;
+ }
+ }
+ }
+ }
+
+ if (runtime_total != EXPECTED_ACTIVE_PRIMARY_TOTAL) {
+ fprintf(stderr, " [call-node-manifest] invariant=runtime_total expected=%d actual=%d\n",
+ EXPECTED_ACTIVE_PRIMARY_TOTAL, runtime_total);
+ failures++;
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_node_manifest_live_membership_matches_expected_primary_boolean) {
+ int failures = 0;
+
+ for (size_t i = 0; i < MANIFEST_COUNT; i++) {
+ const CallNodeManifestEntry *entry = &CALL_NODE_MANIFEST[i];
+ const CBMLangSpec *spec = cbm_lang_spec(entry->language);
+ if (!spec || spec->language != entry->language) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=table_spec_missing index=%zu language=%d "
+ "actual=%d\n",
+ i, (int)entry->language, spec ? (int)spec->language : -1);
+ failures++;
+ continue;
+ }
+
+ int live_matches = spec_match_count(spec, entry->node_kind);
+ int expected_matches = entry->expected_primary_registered ? 1 : 0;
+ if (live_matches != expected_matches) {
+ fprintf(stderr,
+ " [call-node-manifest] invariant=table_to_live index=%zu language=%d node=%s "
+ "expected=%d matches=%d role=%d owner=%d historical=%d\n",
+ i, (int)entry->language, entry->node_kind, expected_matches, live_matches,
+ (int)entry->semantic_role, (int)entry->extraction_owner,
+ entry->historically_registered);
+ failures++;
+ }
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+SUITE(repro_call_node_manifest) {
+ RUN_TEST(repro_call_node_manifest_is_unique_and_partitioned);
+ RUN_TEST(repro_call_node_manifest_live_specs_contain_only_expected_primary_entries);
+ RUN_TEST(repro_call_node_manifest_live_membership_matches_expected_primary_boolean);
+}
diff --git a/tests/repro/repro_call_scope_usages.c b/tests/repro/repro_call_scope_usages.c
new file mode 100644
index 000000000..6e8235f52
--- /dev/null
+++ b/tests/repro/repro_call_scope_usages.c
@@ -0,0 +1,678 @@
+/*
+ * repro_call_scope_usages.c — exact reference semantics inside call-shaped ASTs.
+ *
+ * A CALLS edge replaces only the exact invoked callee occurrence. Receivers,
+ * computed keys, arguments, and nested callback bodies remain ordinary value
+ * references. Several language specs also classify non-invocation containers
+ * as call nodes; those containers must neither erase their whole subtree nor
+ * fabricate calls from an arbitrary child. Every assertion uses exact counts
+ * so duplicate CALLS/USAGE emissions cannot masquerade as a successful fix.
+ */
+#include "test_framework.h"
+#include "cbm.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int qn_ends_with(const char *qn, const char *name) {
+ if (!qn || !name)
+ return 0;
+ const char *last = strrchr(qn, '.');
+ return strcmp(last ? last + 1 : qn, name) == 0;
+}
+
+static const char *call_short_name(const char *name) {
+ if (!name)
+ return NULL;
+ const char *short_name = strrchr(name, '.');
+ short_name = short_name ? short_name + 1 : name;
+ const char *scope = strrchr(short_name, ':');
+ return scope ? scope + 1 : short_name;
+}
+
+static int usage_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *usage = &r->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->ref_name &&
+ strcmp(usage->ref_name, target) == 0 &&
+ (!caller || qn_ends_with(usage->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int call_reference_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *usage = &r->usages.items[i];
+ if (usage->kind == CBM_USAGE_CALL_REFERENCE && usage->ref_name &&
+ strcmp(usage->ref_name, target) == 0 &&
+ (!caller || qn_ends_with(usage->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int call_count(const CBMFileResult *r, const char *caller, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ const char *callee = call_short_name(call->callee_name);
+ if (callee && strcmp(callee, target) == 0 &&
+ (!caller || qn_ends_with(call->enclosing_func_qn, caller))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int exact_usage_count(const CBMFileResult *r, const char *caller_qn, const char *target) {
+ int count = 0;
+ for (int i = 0; i < r->usages.count; i++) {
+ const CBMUsage *usage = &r->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->ref_name && usage->enclosing_func_qn &&
+ strcmp(usage->ref_name, target) == 0 &&
+ strcmp(usage->enclosing_func_qn, caller_qn) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int exact_call_count(const CBMFileResult *r, const char *caller_qn, const char *callee) {
+ int count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->callee_name && call->enclosing_func_qn &&
+ strcmp(call->callee_name, callee) == 0 &&
+ strcmp(call->enclosing_func_qn, caller_qn) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int exact_definition_count(const CBMFileResult *r, const char *name,
+ const char *qualified_name) {
+ int count = 0;
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *def = &r->defs.items[i];
+ if (def->name && def->qualified_name && strcmp(def->name, name) == 0 &&
+ strcmp(def->qualified_name, qualified_name) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int definition_count(const CBMFileResult *r, const char *name) {
+ int count = 0;
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *def = &r->defs.items[i];
+ if (def->name && strcmp(def->name, name) == 0)
+ count++;
+ }
+ return count;
+}
+
+static CBMFileResult *extract_case(const char *tag, const char *source, CBMLanguage language,
+ const char *filename) {
+ CBMFileResult *r =
+ cbm_extract_file(source, (int)strlen(source), language, "repro", filename, 0, NULL, NULL);
+ if (!r)
+ fprintf(stderr, " [call-scope] case=%s invariant=extract_result expected=non-null\n", tag);
+ return r;
+}
+
+#define CHECK_COUNT(tag, invariant, expression, expected) \
+ do { \
+ int actual_count = (expression); \
+ if (actual_count != (expected)) { \
+ fprintf(stderr, " [call-scope] case=%s invariant=%s expected=%d actual=%d\n", (tag), \
+ (invariant), (expected), actual_count); \
+ failures++; \
+ } \
+ } while (0)
+
+#define CHECK_CLEAN(tag, result) \
+ do { \
+ if ((result)->has_error || (result)->parse_incomplete) { \
+ fprintf(stderr, " [call-scope] case=%s invariant=valid_fixture expected=clean\n", \
+ (tag)); \
+ failures++; \
+ } \
+ } while (0)
+
+/* The two textual `foo` occurrences have different roles: the first is the
+ * invoked callee, while the second is a function value passed as an argument. */
+TEST(repro_call_scope_same_spelling_callee_and_argument) {
+ static const char source[] = "function foo() {}\n"
+ "function run() { foo(foo); }\n";
+ CBMFileResult *r = extract_case("same_spelling", source, CBM_LANG_JAVASCRIPT, "main.js");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("same_spelling", r);
+ CHECK_COUNT("same_spelling", "foo_definition", definition_count(r, "foo"), 1);
+ CHECK_COUNT("same_spelling", "callee_call", call_count(r, "run", "foo"), 1);
+ CHECK_COUNT("same_spelling", "argument_usage_only", usage_count(r, "run", "foo"), 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Nested calls need independent callee identity. The outer call must not hide
+ * either its direct function-value argument or the inner call's value argument. */
+TEST(repro_call_scope_nested_calls_retain_each_argument) {
+ static const char source[] = "const value = 1;\n"
+ "function handler(): void {}\n"
+ "function inner(input: number): number { return input; }\n"
+ "function outer(cb: () => void, input: number): void {}\n"
+ "function run(): void { outer(handler, inner(value)); }\n";
+ CBMFileResult *r = extract_case("nested_calls", source, CBM_LANG_TYPESCRIPT, "main.ts");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("nested_calls", r);
+ CHECK_COUNT("nested_calls", "outer_call", call_count(r, "run", "outer"), 1);
+ CHECK_COUNT("nested_calls", "inner_call", call_count(r, "run", "inner"), 1);
+ CHECK_COUNT("nested_calls", "handler_argument_usage", usage_count(r, "run", "handler"), 1);
+ CHECK_COUNT("nested_calls", "value_argument_usage", usage_count(r, "run", "value"), 1);
+ CHECK_COUNT("nested_calls", "outer_not_usage", usage_count(r, "run", "outer"), 0);
+ CHECK_COUNT("nested_calls", "inner_not_usage", usage_count(r, "run", "inner"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* A callback body is executable code, not part of the registrar's callee. Its
+ * references remain visible even though the arrow function is an argument. */
+TEST(repro_call_scope_inline_callback_body_usage) {
+ static const char source[] = "const watched = 1;\n"
+ "function register(callback) {}\n"
+ "function run() { register(() => { watched; }); }\n";
+ CBMFileResult *r = extract_case("inline_callback", source, CBM_LANG_JAVASCRIPT, "main.js");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("inline_callback", r);
+ CHECK_COUNT("inline_callback", "registrar_call", call_count(r, "run", "register"), 1);
+ CHECK_COUNT("inline_callback", "callback_body_usage", usage_count(r, NULL, "watched"), 1);
+ CHECK_COUNT("inline_callback", "registrar_not_usage", usage_count(r, "run", "register"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* For a member call only `method` is the direct callee. The receiver and
+ * arguments are values. For a computed call, both receiver and key are values. */
+TEST(repro_call_scope_member_and_computed_components) {
+ static const char source[] =
+ "class Receiver { method(value: number): void {} }\n"
+ "const receiver = new Receiver();\n"
+ "const key = 'method';\n"
+ "const payload = 1;\n"
+ "function run(): void { receiver.method(payload); receiver[key](payload); }\n";
+ CBMFileResult *r = extract_case("member_computed", source, CBM_LANG_TYPESCRIPT, "main.ts");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("member_computed", r);
+ CHECK_COUNT("member_computed", "method_call", call_count(r, "run", "method"), 1);
+ CHECK_COUNT("member_computed", "receiver_usages", usage_count(r, "run", "receiver"), 2);
+ CHECK_COUNT("member_computed", "computed_key_usage", usage_count(r, "run", "key"), 1);
+ CHECK_COUNT("member_computed", "argument_usages", usage_count(r, "run", "payload"), 2);
+ CHECK_COUNT("member_computed", "terminal_method_not_usage", usage_count(r, "run", "method"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Constructor and generic-call syntax must not change argument semantics. The
+ * type argument belongs to type-reference extraction; both handler expressions
+ * are ordinary value usages. */
+TEST(repro_call_scope_constructor_and_generic_arguments) {
+ static const char source[] =
+ "interface Payload {}\n"
+ "class Box { constructor(callback: () => void) {} }\n"
+ "function handler(): void {}\n"
+ "function accept<T>(callback: () => void): void {}\n"
+ "function run(): void { new Box(handler); accept<Payload>(handler); }\n";
+ CBMFileResult *r = extract_case("constructor_generic", source, CBM_LANG_TYPESCRIPT, "main.ts");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("constructor_generic", r);
+ CHECK_COUNT("constructor_generic", "constructor_call", call_count(r, "run", "Box"), 1);
+ CHECK_COUNT("constructor_generic", "generic_call", call_count(r, "run", "accept"), 1);
+ CHECK_COUNT("constructor_generic", "handler_argument_usages", usage_count(r, "run", "handler"),
+ 2);
+ CHECK_COUNT("constructor_generic", "constructor_not_usage", usage_count(r, "run", "Box"), 0);
+ CHECK_COUNT("constructor_generic", "generic_callee_not_usage", usage_count(r, "run", "accept"),
+ 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_scope_c_function_pointer_invocation_and_arguments) {
+ static const char source[] = "typedef void (*Callback)(void);\n"
+ "void handler(void) {}\n"
+ "void invoke(Callback first, Callback second) {}\n"
+ "Callback shared = 0;\n"
+ "void run(void) { invoke(shared, handler); shared(); }\n";
+ CBMFileResult *r = extract_case("c_function_pointer", source, CBM_LANG_C, "main.c");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("c_function_pointer", r);
+ CHECK_COUNT("c_function_pointer", "invoke_call", call_count(r, "run", "invoke"), 1);
+ CHECK_COUNT("c_function_pointer", "pointer_call", call_count(r, "run", "shared"), 1);
+ CHECK_COUNT("c_function_pointer", "pointer_argument_usage", usage_count(r, "run", "shared"), 1);
+ CHECK_COUNT("c_function_pointer", "function_argument_usage", usage_count(r, "run", "handler"),
+ 1);
+ CHECK_COUNT("c_function_pointer", "invoke_not_usage", usage_count(r, "run", "invoke"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_scope_cpp_function_pointer_invocation_and_arguments) {
+ static const char source[] = "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void invoke(Callback first, Callback second) {}\n"
+ "Callback shared = nullptr;\n"
+ "void run() { invoke(shared, handler); shared(); }\n";
+ CBMFileResult *r = extract_case("cpp_function_pointer", source, CBM_LANG_CPP, "main.cpp");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("cpp_function_pointer", r);
+ CHECK_COUNT("cpp_function_pointer", "invoke_call", call_count(r, "run", "invoke"), 1);
+ CHECK_COUNT("cpp_function_pointer", "pointer_call", call_count(r, "run", "shared"), 1);
+ CHECK_COUNT("cpp_function_pointer", "pointer_argument_usage", usage_count(r, "run", "shared"),
+ 1);
+ CHECK_COUNT("cpp_function_pointer", "function_argument_usage", usage_count(r, "run", "handler"),
+ 1);
+ CHECK_COUNT("cpp_function_pointer", "invoke_not_usage", usage_count(r, "run", "invoke"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_scope_python_keyword_argument) {
+ static const char source[] = "def handler():\n pass\n"
+ "def accept(callback=None):\n pass\n"
+ "def run():\n accept(callback=handler)\n";
+ CBMFileResult *r = extract_case("python_keyword", source, CBM_LANG_PYTHON, "main.py");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("python_keyword", r);
+ CHECK_COUNT("python_keyword", "accept_call", call_count(r, "run", "accept"), 1);
+ CHECK_COUNT("python_keyword", "keyword_value_usage", usage_count(r, "run", "handler"), 1);
+ CHECK_COUNT("python_keyword", "keyword_label_not_usage", usage_count(r, "run", "callback"), 0);
+ CHECK_COUNT("python_keyword", "callee_not_usage", usage_count(r, "run", "accept"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Python registers `with_statement` as a call node. The actual manager()
+ * invocation is a call, but the with body is not part of that callee. */
+TEST(repro_call_scope_python_with_body_usage) {
+ static const char source[] = "watched = 1\n"
+ "def manager():\n pass\n"
+ "def run():\n with manager():\n watched\n";
+ CBMFileResult *r = extract_case("python_with", source, CBM_LANG_PYTHON, "main.py");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("python_with", r);
+ CHECK_COUNT("python_with", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("python_with", "manager_call", call_count(r, "run", "manager"), 1);
+ CHECK_COUNT("python_with", "with_body_usage", usage_count(r, "run", "watched"), 1);
+ CHECK_COUNT("python_with", "manager_not_usage", usage_count(r, "run", "manager"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Rust macro_invocation is call-like, but its token-tree arguments remain
+ * value references and must survive the macro callee's scope. */
+TEST(repro_call_scope_rust_macro_argument) {
+ static const char source[] = "static WATCHED: i32 = 1;\n"
+ "macro_rules! probe { ($value:expr) => { $value }; }\n"
+ "fn run() { probe!(WATCHED); }\n";
+ CBMFileResult *r = extract_case("rust_macro", source, CBM_LANG_RUST, "main.rs");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("rust_macro", r);
+ CHECK_COUNT("rust_macro", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("rust_macro", "macro_call", call_count(r, "run", "probe"), 1);
+ CHECK_COUNT("rust_macro", "macro_argument_usage", usage_count(r, "run", "WATCHED"), 1);
+ CHECK_COUNT("rust_macro", "macro_callee_not_usage", usage_count(r, "run", "probe"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Elixir binary_operator is registered as a call node, but `watched + 1` is
+ * not a call to watched. This uses caller-independent counts because Elixir's
+ * callable attribution has a separately documented Module-scope drift. */
+TEST(repro_call_scope_elixir_binary_operator_operand) {
+ static const char source[] = "defmodule Sample do\n"
+ " def run(), do: watched + 1\n"
+ "end\n";
+ CBMFileResult *r = extract_case("elixir_binary", source, CBM_LANG_ELIXIR, "sample.ex");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("elixir_binary", r);
+ CHECK_COUNT("elixir_binary", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("elixir_binary", "operator_call", call_count(r, NULL, "+"), 1);
+ CHECK_COUNT("elixir_binary", "operand_usage", usage_count(r, NULL, "watched"), 1);
+ CHECK_COUNT("elixir_binary", "operand_not_call", call_count(r, NULL, "watched"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Fortran keyword_argument is an argument container, not another invocation.
+ * The keyword label is metadata; only its value is a usage. */
+TEST(repro_call_scope_fortran_keyword_argument) {
+ static const char source[] = "module sample\n"
+ " integer :: watched\n"
+ "contains\n"
+ " integer function consume(value)\n"
+ " integer, intent(in) :: value\n"
+ " consume = value\n"
+ " end function consume\n"
+ " integer function run()\n"
+ " run = consume(value=watched)\n"
+ " end function run\n"
+ "end module sample\n";
+ CBMFileResult *r = extract_case("fortran_keyword", source, CBM_LANG_FORTRAN, "main.f90");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("fortran_keyword", r);
+ CHECK_COUNT("fortran_keyword", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("fortran_keyword", "consume_call", call_count(r, NULL, "consume"), 1);
+ CHECK_COUNT("fortran_keyword", "keyword_value_usage", usage_count(r, "run", "watched"), 1);
+ CHECK_COUNT("fortran_keyword", "keyword_label_not_usage", usage_count(r, "run", "value"), 0);
+ CHECK_COUNT("fortran_keyword", "keyword_label_not_call", call_count(r, "run", "value"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* A separate gap discovered while building the keyword-argument control:
+ * Fortran's `call` statement is registered as call metadata, yet the direct
+ * subroutine invocation currently emits no CBMCall. Keep this independent from
+ * keyword labels so its future fix cannot hide behind another emitted call. */
+TEST(repro_fortran_subroutine_call_is_extracted) {
+ static const char source[] = "subroutine consume(value)\n"
+ " integer :: value\n"
+ "end subroutine consume\n"
+ "subroutine run()\n"
+ " call consume(watched)\n"
+ "end subroutine run\n";
+ CBMFileResult *r =
+ extract_case("fortran_subroutine_call", source, CBM_LANG_FORTRAN, "main.f90");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("fortran_subroutine_call", r);
+ CHECK_COUNT("fortran_subroutine_call", "consume_definition", definition_count(r, "consume"), 1);
+ CHECK_COUNT("fortran_subroutine_call", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("fortran_subroutine_call", "total_calls", r->calls.count, 1);
+ CHECK_COUNT("fortran_subroutine_call", "consume_call_from_run", call_count(r, "run", "consume"),
+ 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Kotlin navigation_expression also represents ordinary property access. A
+ * property read must retain both reference components and emit no call. */
+TEST(repro_call_scope_kotlin_property_navigation) {
+ static const char source[] = "class Holder(val value: Int)\n"
+ "val box = Holder(1)\n"
+ "fun run(): Int = box.value\n";
+ CBMFileResult *r = extract_case("kotlin_navigation", source, CBM_LANG_KOTLIN, "Main.kt");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("kotlin_navigation", r);
+ CHECK_COUNT("kotlin_navigation", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("kotlin_navigation", "receiver_usage", usage_count(r, "run", "box"), 1);
+ CHECK_COUNT("kotlin_navigation", "property_usage", usage_count(r, "run", "value"), 1);
+ CHECK_COUNT("kotlin_navigation", "receiver_not_call", call_count(r, "run", "box"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* PHP 8.1 first-class callable syntax evaluates a function reference without
+ * invoking it. The pinned grammar exposes the ordinary bare, member,
+ * scoped/static, and nullsafe call-expression nodes plus variadic_placeholder;
+ * CHECK_CLEAN guards the combinations used below. A real variadic_unpacking
+ * argument is still an invocation, so keep it as a positive discriminator. */
+TEST(repro_call_scope_php_first_class_callable) {
+ static const char source[] = "<?php\n"
+ "function bare_handler(): void {}\n"
+ "function foo(...$values): void {}\n"
+ "function accept(callable $callback): void {}\n"
+ "class CallbackTarget {\n"
+ " public function member_handler(): void {}\n"
+ " public function nullable_handler(): void {}\n"
+ " public static function static_handler(): void {}\n"
+ "}\n"
+ "function run($receiver, $nullable, array $args): void {\n"
+ " accept(bare_handler(...));\n"
+ " accept($receiver->member_handler(...));\n"
+ " accept(CallbackTarget::static_handler(...));\n"
+ " accept($nullable?->nullable_handler(...));\n"
+ " foo(...$args);\n"
+ "}\n";
+ CBMFileResult *r = extract_case("php_first_class", source, CBM_LANG_PHP, "main.php");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("php_first_class", r);
+ CHECK_COUNT("php_first_class", "total_calls", r->calls.count, 5);
+ CHECK_COUNT("php_first_class", "accept_calls", call_count(r, "run", "accept"), 4);
+ CHECK_COUNT("php_first_class", "bare_reference_usage", usage_count(r, "run", "bare_handler"),
+ 0);
+ CHECK_COUNT("php_first_class", "bare_call_reference",
+ call_reference_count(r, "run", "bare_handler"), 1);
+ CHECK_COUNT("php_first_class", "bare_reference_not_invoked",
+ call_count(r, "run", "bare_handler"), 0);
+ CHECK_COUNT("php_first_class", "member_receiver_usage", usage_count(r, "run", "$receiver"), 1);
+ CHECK_COUNT("php_first_class", "member_reference_usage",
+ usage_count(r, "run", "member_handler"), 0);
+ CHECK_COUNT("php_first_class", "member_call_reference",
+ call_reference_count(r, "run", "member_handler"), 1);
+ CHECK_COUNT("php_first_class", "member_reference_not_invoked",
+ call_count(r, "run", "member_handler"), 0);
+ CHECK_COUNT("php_first_class", "static_scope_usage", usage_count(r, "run", "CallbackTarget"),
+ 1);
+ CHECK_COUNT("php_first_class", "static_reference_usage",
+ usage_count(r, "run", "static_handler"), 0);
+ CHECK_COUNT("php_first_class", "static_call_reference",
+ call_reference_count(r, "run", "static_handler"), 1);
+ CHECK_COUNT("php_first_class", "static_reference_not_invoked",
+ call_count(r, "run", "static_handler"), 0);
+ CHECK_COUNT("php_first_class", "nullsafe_receiver_usage", usage_count(r, "run", "$nullable"),
+ 1);
+ CHECK_COUNT("php_first_class", "nullsafe_reference_usage",
+ usage_count(r, "run", "nullable_handler"), 0);
+ CHECK_COUNT("php_first_class", "nullsafe_call_reference",
+ call_reference_count(r, "run", "nullable_handler"), 1);
+ CHECK_COUNT("php_first_class", "nullsafe_reference_not_invoked",
+ call_count(r, "run", "nullable_handler"), 0);
+ CHECK_COUNT("php_first_class", "unpacking_argument_usage", usage_count(r, "run", "$args"), 1);
+ CHECK_COUNT("php_first_class", "unpacking_is_invocation", call_count(r, "run", "foo"), 1);
+ CHECK_COUNT("php_first_class", "invoked_callee_not_usage", usage_count(r, "run", "foo"), 0);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* MAX_SCOPES is currently a fixed 64-entry stack. The 65th nested function is
+ * silently discarded, so calls in its body inherit the wrong enclosing QN.
+ * The later sibling is an independent pop-recovery control: it must remain
+ * attributed to itself rather than inheriting any deep or stale scope. */
+TEST(repro_scope_stack_preserves_deepest_function) {
+ enum { FUNCTION_DEPTH = 65, SOURCE_CAPACITY = 8192 };
+ char *source = calloc(SOURCE_CAPACITY, 1);
+ ASSERT_NOT_NULL(source);
+
+ size_t used = (size_t)snprintf(source, SOURCE_CAPACITY, "function target() {}\n");
+ for (int depth = 0; depth < FUNCTION_DEPTH && used < SOURCE_CAPACITY; depth++) {
+ used +=
+ (size_t)snprintf(source + used, SOURCE_CAPACITY - used, "function f%d() {\n", depth);
+ }
+ used += (size_t)snprintf(source + used, SOURCE_CAPACITY - used, "target();\n");
+ for (int depth = 0; depth < FUNCTION_DEPTH && used < SOURCE_CAPACITY; depth++) {
+ used += (size_t)snprintf(source + used, SOURCE_CAPACITY - used, "}\n");
+ }
+ used += (size_t)snprintf(source + used, SOURCE_CAPACITY - used,
+ "function sibling() { target(); }\n");
+ ASSERT_TRUE(used < SOURCE_CAPACITY);
+
+ CBMFileResult *r = extract_case("deep_scope", source, CBM_LANG_JAVASCRIPT, "deep.js");
+ free(source);
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("deep_scope", r);
+ CHECK_COUNT("deep_scope", "deepest_definition", definition_count(r, "f64"), 1);
+ CHECK_COUNT("deep_scope", "sibling_definition", definition_count(r, "sibling"), 1);
+ CHECK_COUNT("deep_scope", "target_call_total", call_count(r, NULL, "target"), 2);
+ CHECK_COUNT("deep_scope", "penultimate_scope_not_inherited", call_count(r, "f63", "target"), 0);
+ CHECK_COUNT("deep_scope", "deepest_call_attribution", call_count(r, "f64", "target"), 1);
+ CHECK_COUNT("deep_scope", "sibling_pop_recovery_control", call_count(r, "sibling", "target"),
+ 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* Declarations and simple assignment targets are not references. True reads
+ * remain usages, including the read side of compound assignments and updates.
+ * Distinct names prevent one role from falsely satisfying another assertion. */
+TEST(repro_usage_declarations_are_not_references) {
+ static const char source[] = "function run(unusedParameter: number,\n"
+ " usedParameter: number): number {\n"
+ " let assignmentOnly: number;\n"
+ " assignmentOnly = 1;\n"
+ " let localValue = usedParameter + usedParameter;\n"
+ " let compoundValue = 0;\n"
+ " compoundValue += 1;\n"
+ " let updatedValue = 0;\n"
+ " updatedValue++;\n"
+ " return localValue + localValue;\n"
+ "}\n";
+ CBMFileResult *r = extract_case("declaration_usage", source, CBM_LANG_TYPESCRIPT, "main.ts");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("declaration_usage", r);
+ CHECK_COUNT("declaration_usage", "run_definition", definition_count(r, "run"), 1);
+ CHECK_COUNT("declaration_usage", "unused_parameter_not_usage",
+ usage_count(r, "run", "unusedParameter"), 0);
+ CHECK_COUNT("declaration_usage", "assignment_only_binding_not_usage",
+ usage_count(r, "run", "assignmentOnly"), 0);
+ CHECK_COUNT("declaration_usage", "used_parameter_reads", usage_count(r, "run", "usedParameter"),
+ 2);
+ CHECK_COUNT("declaration_usage", "local_value_reads", usage_count(r, "run", "localValue"), 2);
+ CHECK_COUNT("declaration_usage", "compound_assignment_reads_value",
+ usage_count(r, "run", "compoundValue"), 1);
+ CHECK_COUNT("declaration_usage", "update_reads_value", usage_count(r, "run", "updatedValue"),
+ 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* ObjectScript's typed receiver map must not change either ownership or
+ * CALL/USAGE roles: the method is the exact callee and the parameter passed to
+ * it remains one value usage in Sample.Behavior.run. */
+TEST(repro_call_scope_objectscript_typed_receiver_exact_owner) {
+ static const char source[] =
+ "Class Sample.Behavior Extends %RegisteredObject\n"
+ "{\n"
+ "Method run(target As Sample.Target, watched As %String) As %Status\n"
+ "{\n"
+ " Do target.accept(watched)\n"
+ " Quit\n"
+ "}\n"
+ "}\n";
+ static const char caller_qn[] = "repro.Behavior.Sample.Behavior.run";
+ static const char callee[] = "Sample.Target.accept";
+ CBMFileResult *r = extract_case("objectscript_typed_receiver", source,
+ CBM_LANG_OBJECTSCRIPT_UDL, "Behavior.cls");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("objectscript_typed_receiver", r);
+ CHECK_COUNT("objectscript_typed_receiver", "exact_run_definition",
+ exact_definition_count(r, "run", caller_qn), 1);
+ CHECK_COUNT("objectscript_typed_receiver", "exact_call_owner_and_target",
+ exact_call_count(r, caller_qn, callee), 1);
+ CHECK_COUNT("objectscript_typed_receiver", "argument_usage",
+ exact_usage_count(r, caller_qn, "watched"), 1);
+ CHECK_COUNT("objectscript_typed_receiver", "argument_not_call",
+ exact_call_count(r, caller_qn, "watched"), 0);
+ CHECK_COUNT("objectscript_typed_receiver", "callee_not_usage",
+ exact_usage_count(r, caller_qn, "accept"), 0);
+ CHECK_COUNT("objectscript_typed_receiver", "one_call", r->calls.count, 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* A parameterized ObjectScript routine is represented by a procedure wrapper
+ * around its tag. Calls in the body still belong to the tag's Function node,
+ * not to the module and not to the following tag. */
+TEST(repro_call_scope_objectscript_routine_tag_exact_owner) {
+ static const char source[] = "run(watched)\n"
+ " Do accept(watched)\n"
+ " Quit\n"
+ "accept(value)\n"
+ " Quit value\n";
+ static const char caller_qn[] = "repro.Behavior.run";
+ CBMFileResult *r = extract_case("objectscript_routine_scope", source,
+ CBM_LANG_OBJECTSCRIPT_ROUTINE, "Behavior.mac");
+ ASSERT_NOT_NULL(r);
+ int failures = 0;
+ CHECK_CLEAN("objectscript_routine_scope", r);
+ CHECK_COUNT("objectscript_routine_scope", "exact_run_definition",
+ exact_definition_count(r, "run", caller_qn), 1);
+ CHECK_COUNT("objectscript_routine_scope", "exact_call_owner_and_target",
+ exact_call_count(r, caller_qn, "accept"), 1);
+ CHECK_COUNT("objectscript_routine_scope", "argument_usage",
+ exact_usage_count(r, caller_qn, "watched"), 1);
+ CHECK_COUNT("objectscript_routine_scope", "argument_not_call",
+ exact_call_count(r, caller_qn, "watched"), 0);
+ CHECK_COUNT("objectscript_routine_scope", "callee_not_usage",
+ exact_usage_count(r, caller_qn, "accept"), 0);
+ CHECK_COUNT("objectscript_routine_scope", "one_call", r->calls.count, 1);
+ cbm_free_result(r);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+SUITE(repro_call_scope_usages) {
+ RUN_TEST(repro_call_scope_same_spelling_callee_and_argument);
+ RUN_TEST(repro_call_scope_nested_calls_retain_each_argument);
+ RUN_TEST(repro_call_scope_inline_callback_body_usage);
+ RUN_TEST(repro_call_scope_member_and_computed_components);
+ RUN_TEST(repro_call_scope_constructor_and_generic_arguments);
+ RUN_TEST(repro_call_scope_c_function_pointer_invocation_and_arguments);
+ RUN_TEST(repro_call_scope_cpp_function_pointer_invocation_and_arguments);
+ RUN_TEST(repro_call_scope_python_keyword_argument);
+ RUN_TEST(repro_call_scope_python_with_body_usage);
+ RUN_TEST(repro_call_scope_rust_macro_argument);
+ RUN_TEST(repro_call_scope_elixir_binary_operator_operand);
+ RUN_TEST(repro_call_scope_fortran_keyword_argument);
+ RUN_TEST(repro_fortran_subroutine_call_is_extracted);
+ RUN_TEST(repro_call_scope_kotlin_property_navigation);
+ RUN_TEST(repro_call_scope_php_first_class_callable);
+ RUN_TEST(repro_scope_stack_preserves_deepest_function);
+ RUN_TEST(repro_usage_declarations_are_not_references);
+ RUN_TEST(repro_call_scope_objectscript_typed_receiver_exact_owner);
+ RUN_TEST(repro_call_scope_objectscript_routine_tag_exact_owner);
+}
+
+#undef CHECK_CLEAN
+#undef CHECK_COUNT
diff --git a/tests/repro/repro_grammar_markup.c b/tests/repro/repro_grammar_markup.c
index 7f110f426..9d7db831a 100644
--- a/tests/repro/repro_grammar_markup.c
+++ b/tests/repro/repro_grammar_markup.c
@@ -59,9 +59,8 @@
* languages with non-empty call_types AND a fixture that
* produces a resolvable callee_name (TYPST call, QML JS
* call_expression, PURESCRIPT exp_apply). BIBTEX/DIFF
- * have call_types ("command") but the nodes are not
- * function-application sites with a stable callee_name;
- * dim 6 is SKIPPED there and noted.
+ * intentionally have no call metadata because their
+ * `command` nodes are document records, not applications.
*
* FULL-PIPELINE (rh_index_files -> cbm_store_t*, via inv_count_* store helpers):
* 7. callable-sourcing : inv_count_calls_by_source(store,project,&mod,&call).
@@ -91,15 +90,15 @@
* Dims 1-8. Dim 5 asserts "Function" (a let-bound lambda).
* Dim 7 may RED if the lambda is anonymous and the enclosing-func
* walk attributes the call at Module.
- * BIBTEX -- DOCS. call_types = {command} only; entries (@article{...}) are
+ * BIBTEX -- DOCS. call_types is empty; entries (@article{...}) are
* NOT mapped to any def label, and "command" nodes are LaTeX-style
* commands, not callee-named application sites. Dims 1-4 + R
* (dim 5 skipped -- no def types; dim 6 skipped -- no stable callee).
* MERMAID -- structural-only. module_types only. Dims 1-4 + R.
* PO -- DOCS/structural-only. module_types only (gettext msgid/msgstr
* entries are not mapped to a def label). Dims 1-4 + R.
- * DIFF -- structural. call_types = {command} only (a "command" line in a
- * git-style diff header, not a function call); no def types.
+ * DIFF -- structural. call_types is empty because a "command" line in a
+ * git-style diff header is not a function call; no def types.
* Dims 1-4 + R (dims 5-6 skipped).
* REGEX -- structural-only. module_types = {pattern}. Dims 1-4 + R.
* CAPNP -- SCHEMA. func_types = {method} -> "Function";
@@ -518,28 +517,18 @@ TEST(repro_grammar_markup_rst) {
* Dims asserted: 1-8 (full battery).
* Dim 5 expected GREEN: "Function" def for the let-bound lambda.
* Dim 6 expected GREEN: call to "greet" via the call node.
- * Dim 7 expected RED if the lambda binding name does not flow to the enclosing-
- * func walk and the call is attributed at Module. RED documents the gap.
+ * Dim 7 expected GREEN: `render` calls `greet` from its function body, so the
+ * call must source to the `render` Function rather than the Module.
* Dim 8 expected GREEN: no dangling CALLS endpoints.
*/
TEST(repro_grammar_markup_typst) {
- /* DISABLED — RARE LANGUAGE (maintainer-approved, 2026-06-28): Typst (markup).
- * The `#greet("world")` is a genuinely top-level (module-level) application
- * that production CORRECTLY sources to the Module, but pipeline_battery counts
- * any non-Function-sourced edge as drift (the nix-pattern). A simple in-
- * function wrap conflicts with markup_callable_battery, which needs that very
- * call. Murky markup/fixture interaction in a niche language; deferred. */
- printf("%sSKIP%s rare language (Typst top-level-call sourcing)\n", tf_dim(), tf_reset());
- return -1; /* skip — not counted as pass or fail */
- static const char src[] =
- "#let title = \"Codebase Memory\"\n"
- "#let greet(name) = [Hello, #name!]\n"
- "\n"
- "= #title\n"
- "\n"
- "#greet(\"world\")\n"
- "\n"
- "Some body text with a #strong[bold] run.\n";
+ static const char src[] = "#let title = \"Codebase Memory\"\n"
+ "#let greet(name) = [Hello, #name!]\n"
+ "#let render() = greet(\"world\")\n"
+ "\n"
+ "= #title\n"
+ "\n"
+ "Some body text with a #strong[bold] run.\n";
static const char bad[] = "#let greet(name) = [Hello, #name";
if (markup_callable_battery("Typst", src, CBM_LANG_TYPST, "doc.typ",
"Function", "greet") != 0)
@@ -551,14 +540,13 @@ TEST(repro_grammar_markup_typst) {
/* -- BIBTEX ------------------------------------------------------------------
* Idiomatic BibTeX bibliography with an @article and an @book entry. The spec
- * has bibtex_module_types = {document} and bibtex_call_types = {command}; entry
- * declarations are NOT mapped to any def label, and "command" nodes are
- * LaTeX-style commands without a stable function callee_name.
+ * has bibtex_module_types = {document} and an empty bibtex_call_types array;
+ * entry declarations are NOT mapped to any def label, and "command" nodes are
+ * LaTeX-style document commands rather than function applications.
*
* Dims asserted: 1-4 + R.
* Dim 5 SKIPPED: no def-minting types (entries unmapped).
- * Dim 6 SKIPPED: call_types exists but "command" nodes have no resolvable
- * callee_name to assert against; asserting would be brittle.
+ * Dim 6 SKIPPED: call_types is empty by design.
* Dims 7-8 SKIPPED: no func_types to anchor a call.
* Expected GREEN: dims 1-4. extract-clean RED would indicate the BibTeX grammar
* misparses standard @entry{...} records.
@@ -639,7 +627,7 @@ TEST(repro_grammar_markup_po) {
/* -- DIFF --------------------------------------------------------------------
* Idiomatic unified diff (git-style) with file headers and a hunk. The spec has
- * diff_module_types = {source} and diff_call_types = {command}; there are no
+ * diff_module_types = {source} and an empty diff_call_types array; there are no
* def-minting types and "command" nodes are diff command lines, not function
* application sites with a stable callee_name.
*
diff --git a/tests/repro/repro_grammar_misc.c b/tests/repro/repro_grammar_misc.c
index fec0e0fff..99cd181bb 100644
--- a/tests/repro/repro_grammar_misc.c
+++ b/tests/repro/repro_grammar_misc.c
@@ -2,8 +2,10 @@
* repro_grammar_misc.c -- FINAL per-grammar INVARIANT battery covering the
* remaining MISCELLANEOUS language family (hardware-description, CFML dialects,
* niche scripting, structural assembly/linker/tablegen/ledger/IaC). This file
- * completes the all-159-grammar reproduce-first coverage: every CBM_LANG_* now
- * has a per-language RED/GREEN row on the bug-repro board.
+ * completes the all-161-grammar reproduce-first coverage: every grammar-backed
+ * CBM_LANG_* now has a per-language RED/GREEN row on the bug-repro board.
+ * CBM_LANG_OBJECTSCRIPT_EXPORT is intentionally excluded from the grammar
+ * count because Studio Export XML is transformed to ObjectScript UDL first.
*
* One TEST() per language so per-language RED/GREEN shows on the board. Each
* test runs the battery dimension appropriate to what the language's lang_spec
@@ -31,6 +33,12 @@
* call: call_expression)
* SQL -> CBM_LANG_SQL (func: create_function; call:
* function_call/invocation/command)
+ * OBJECTSCRIPT_UDL -> CBM_LANG_OBJECTSCRIPT_UDL
+ * (func: method/classmethod/query;
+ * call: four registered UDL forms)
+ * OBJECTSCRIPT_ROUTINE -> CBM_LANG_OBJECTSCRIPT_ROUTINE
+ * (func: tag; call: extrinsic_function/
+ * routine_tag_call)
*
* STRUCTURAL family (asm / linker / data / IaC) -> extract-clean +
* labels/fqn/ranges valid + defs-present (the entities each should extract) +
@@ -91,8 +99,9 @@
*
* HONEST RED CONTRACT (the point of this file): dimension 7 (callable-sourcing) is
* expected RED for the non-LSP callable languages here. None of VERILOG /
- * SYSTEMVERILOG / VHDL / CFML / CFSCRIPT / RESCRIPT / SQUIRREL / PINE / TEMPL / SQL
- * has a dedicated cross-LSP rescue, so attribution depends solely on the
+ * SYSTEMVERILOG / VHDL / CFML / CFSCRIPT / RESCRIPT / SQUIRREL / PINE / TEMPL / SQL /
+ * OBJECTSCRIPT_UDL / OBJECTSCRIPT_ROUTINE has a dedicated cross-LSP rescue, so
+ * attribution depends solely on the
* tree-sitter enclosing-func walk (cbm_find_enclosing_func + func_kinds_for_lang in
* helpers.c). When that mapping does not match the grammar's emitted func node
* types, the in-body call falls back to the Module QN -- exactly the enclosing-func
@@ -468,6 +477,67 @@ TEST(repro_grammar_misc_linkerscript) {
return misc_robustness("LINKERSCRIPT", bad, CBM_LANG_LINKERSCRIPT, "link.ld");
}
+/* ── OBJECTSCRIPT UDL (callable) ─────────────────────────────────────────────
+ * A class method calls another class method with a local value argument. The
+ * call is the registered class_method_call form; the other three UDL call forms
+ * remain enumerated by repro_call_node_manifest.
+ *
+ * Dims asserted: 1-8 + R. Studio Export XML is not a grammar row because it is
+ * transformed to this UDL language before extraction.
+ */
+TEST(repro_grammar_misc_objectscript_udl) {
+ static const char src[] = "Class Sample.Callbacks Extends %RegisteredObject\n"
+ "{\n"
+ "ClassMethod Accept(value As %String) As %String\n"
+ "{\n"
+ " Quit value\n"
+ "}\n"
+ "ClassMethod Run(watched As %String) As %String\n"
+ "{\n"
+ " Quit ##class(Sample.Callbacks).Accept(watched)\n"
+ "}\n"
+ "}\n";
+ static const char bad[] = "Class Sample.Callbacks Extends %RegisteredObject\n"
+ "{\n"
+ "ClassMethod Run(watched As %String) As %String\n"
+ "{\n"
+ " Quit ##class(Sample.Callbacks).Accept(\n";
+ if (misc_single_file_battery("OBJECTSCRIPT_UDL", src, CBM_LANG_OBJECTSCRIPT_UDL,
+ "Callbacks.cls", "Method", NULL, "Accept") != 0)
+ return 1;
+ if (misc_robustness("OBJECTSCRIPT_UDL", bad, CBM_LANG_OBJECTSCRIPT_UDL, "Callbacks.cls") != 0)
+ return 1;
+ return misc_pipeline_battery("OBJECTSCRIPT_UDL", "Callbacks.cls", src);
+}
+
+/* ── OBJECTSCRIPT ROUTINE (callable) ─────────────────────────────────────────
+ * A parameterized routine tag invokes a sibling through the registered
+ * extrinsic_function form. routine_tag_call membership is covered separately by
+ * the literal call-node manifest.
+ *
+ * Dims asserted: 1-8 + R.
+ */
+TEST(repro_grammar_misc_objectscript_routine) {
+ static const char src[] = "SAMPLE\n"
+ " Quit\n"
+ "Accept(value)\n"
+ " Quit value\n"
+ "Run(watched)\n"
+ " Set result = $$Accept(watched)\n"
+ " Quit result\n";
+ static const char bad[] = "SAMPLE\n"
+ " Quit\n"
+ "Run(watched)\n"
+ " Set result = $$Accept(\n";
+ if (misc_single_file_battery("OBJECTSCRIPT_ROUTINE", src, CBM_LANG_OBJECTSCRIPT_ROUTINE,
+ "Sample.mac", "Function", NULL, "Accept") != 0)
+ return 1;
+ if (misc_robustness("OBJECTSCRIPT_ROUTINE", bad, CBM_LANG_OBJECTSCRIPT_ROUTINE, "Sample.mac") !=
+ 0)
+ return 1;
+ return misc_pipeline_battery("OBJECTSCRIPT_ROUTINE", "Sample.mac", src);
+}
+
/* ── PINE (callable) ─────────────────────────────────────────────────────────
* Idiomatic Pine Script v5 indicator: a user function `ema2` defined with
* function_declaration_statement, and a call to the built-in `plot()` plus an
@@ -790,6 +860,8 @@ SUITE(repro_grammar_misc) {
RUN_TEST(repro_grammar_misc_cfml);
RUN_TEST(repro_grammar_misc_cfscript);
RUN_TEST(repro_grammar_misc_linkerscript);
+ RUN_TEST(repro_grammar_misc_objectscript_udl);
+ RUN_TEST(repro_grammar_misc_objectscript_routine);
RUN_TEST(repro_grammar_misc_pine);
RUN_TEST(repro_grammar_misc_rescript);
RUN_TEST(repro_grammar_misc_sql);
diff --git a/tests/repro/repro_grammar_systems.c b/tests/repro/repro_grammar_systems.c
index b69f3f01a..1ddf8b7e6 100644
--- a/tests/repro/repro_grammar_systems.c
+++ b/tests/repro/repro_grammar_systems.c
@@ -12,7 +12,7 @@
* Languages covered (12) and the CBM_LANG_* enum each uses (every enum verified
* present in internal/cbm/cbm.h; none missing, none skipped):
* Zig -> CBM_LANG_ZIG
- * Nim -> CBM_LANG_NIM
+ * Nim -> CBM_LANG_NIM (explicitly unsupported; no grammar is vendored)
* Crystal -> CBM_LANG_CRYSTAL
* Hare -> CBM_LANG_HARE
* Odin -> CBM_LANG_ODIN
@@ -65,8 +65,8 @@
* - Crystal (method_def), Odin (procedure_declaration), Pony (method),
* Ada (subprogram_body), Fortran (function/subroutine),
* COBOL (program_definition), Pascal (defProc), Move (function_item).
- * Nim has NO lang_spec / grammar entry at all, so it extracts zero defs and zero
- * calls today: dims 5/6/7 are RED for Nim and the fixture documents that gap.
+ * Nim has no lang_spec / grammar entry. Its row is an explicit registry contract,
+ * not a skipped extraction fixture.
*
* When a language extracts NO in-body call today, dimension 6 (calls-extracted)
* is asserted anyway -- the language SHOULD capture the call -- so the RED row
@@ -78,6 +78,7 @@
*/
#include "test_framework.h"
+#include "lang_specs.h"
#include "repro_invariant_lib.h"
#include <store/store.h>
@@ -248,39 +249,13 @@ TEST(repro_grammar_systems_zig) {
}
/* -- Nim --------------------------------------------------------------------
- * Idiomatic: import, an object type, two `proc`s with the callee called inside
- * the caller body. Nim has NO lang_spec row and NO grammar_nim.c -- there is no
- * func/class/call node-type table for it. Expected: dim 1 (extract-clean) GREEN
- * (cbm_extract_file returns a result), but dims 5/6 RED (zero defs, zero calls)
- * and dim 7 RED (zero CALLS edges to attribute). These RED rows document the
- * missing Nim support; the fixture asserts it SHOULD extract a "Function" and a
- * call to "add".
+ * The enum is retained for API compatibility, but no Nim grammar is linked.
+ * Unsupported must mean NULL; it must never alias the zero-initialized Go row.
*/
TEST(repro_grammar_systems_nim) {
- /* DISABLED — GRAMMAR ISSUE (maintainer-approved, 2026-06-28): extraction of
- * standard Nim (`proc add(a, b: int): int = ...`) fails extract-clean (NULL
- * result or has_error set) — tree-sitter-nim mis-parses the indentation-
- * sensitive layout (Nim was a deferred/problematic grammar in the sweep). A
- * grammar/parser defect, not a cbm extraction bug. Original assertions below
- * are preserved (unreachable) for re-enable when the grammar is fixed. */
- printf("%sSKIP%s grammar issue (tree-sitter-nim parse failure)\n", tf_dim(), tf_reset());
- return -1; /* skip — not counted as pass or fail */
- static const char src[] =
- "import std/strutils\n"
- "\n"
- "type\n"
- " Calc = object\n"
- " base: int\n"
- "\n"
- "proc add(a, b: int): int =\n"
- " return a + b\n"
- "\n"
- "proc compute(x: int): int =\n"
- " return add(x, 1)\n";
- if (single_file_battery("Nim", src, CBM_LANG_NIM, "calc.nim",
- "Function", NULL, "add") != 0)
- return 1;
- return pipeline_battery("Nim", "calc.nim", src);
+ ASSERT_NULL(cbm_lang_spec(CBM_LANG_NIM));
+ ASSERT_NULL(cbm_ts_language(CBM_LANG_NIM));
+ PASS();
}
/* -- Crystal ----------------------------------------------------------------
diff --git a/tests/repro/repro_harness.h b/tests/repro/repro_harness.h
index 74f513040..7aae0f1fd 100644
--- a/tests/repro/repro_harness.h
+++ b/tests/repro/repro_harness.h
@@ -31,6 +31,7 @@
typedef struct {
char tmpdir[256];
+ char cachedir[256];
char dbpath[512];
char *project;
cbm_mcp_server_t *srv;
@@ -54,25 +55,43 @@ static inline cbm_store_t *rh_open_indexed(RProj *lp) {
lp->project = cbm_project_name_from_path(lp->tmpdir);
if (!lp->project)
return NULL;
- const char *home = getenv("HOME");
- if (!home)
- home = "/tmp";
- char cache_dir[512];
- snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home);
- cbm_mkdir(cache_dir);
- snprintf(lp->dbpath, sizeof(lp->dbpath), "%s/%s.db", cache_dir, lp->project);
+ if (!lp->cachedir[0]) {
+ snprintf(lp->cachedir, sizeof(lp->cachedir), "/tmp/cbm_repro_cache_XXXXXX");
+ if (!cbm_mkdtemp(lp->cachedir))
+ return NULL;
+ rh_to_fwd_slashes(lp->cachedir);
+ }
+ snprintf(lp->dbpath, sizeof(lp->dbpath), "%s/%s.db", lp->cachedir, lp->project);
unlink(lp->dbpath);
+
+ const char *prior_cache_dir = getenv("CBM_CACHE_DIR");
+ char *saved_cache_dir = prior_cache_dir ? cbm_strdup(prior_cache_dir) : NULL;
+ cbm_setenv("CBM_CACHE_DIR", lp->cachedir, 1);
+
+ cbm_store_t *store = NULL;
lp->srv = cbm_mcp_server_new(NULL);
- if (!lp->srv)
- return NULL;
- char args[700];
- snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", lp->tmpdir);
- char *resp = cbm_mcp_handle_tool(lp->srv, "index_repository", args);
- if (resp)
- free(resp);
- return cbm_store_open_path(lp->dbpath);
+ if (lp->srv) {
+ char args[700];
+ snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", lp->tmpdir);
+ char *resp = cbm_mcp_handle_tool(lp->srv, "index_repository", args);
+ if (resp)
+ free(resp);
+ /* Repro consumers only inspect the graph. Keep this connection query-only
+ * so the harness does not mutate the publisher's sealed journal mode. */
+ store = cbm_store_open_path_query(lp->dbpath);
+ }
+
+ if (saved_cache_dir) {
+ cbm_setenv("CBM_CACHE_DIR", saved_cache_dir, 1);
+ free(saved_cache_dir);
+ } else {
+ cbm_unsetenv("CBM_CACHE_DIR");
+ }
+ return store;
}
+static inline void rh_cleanup(RProj *lp, cbm_store_t *store);
+
/* Write each fixture file into a fresh temp project, index it via the MCP
* production flow, and open the resulting graph DB. Returns store (NULL on fail). */
static inline cbm_store_t *rh_index_files(RProj *lp, const RFile *files, int nfiles) {
@@ -91,12 +110,18 @@ static inline cbm_store_t *rh_index_files(RProj *lp, const RFile *files, int nfi
*slash = '/';
}
FILE *f = fopen(path, "wb"); /* binary: keep "\n" exact */
- if (!f)
+ if (!f) {
+ rh_cleanup(lp, NULL);
return NULL;
+ }
fputs(files[i].content, f);
fclose(f);
}
- return rh_open_indexed(lp);
+ cbm_store_t *store = rh_open_indexed(lp);
+ if (!store) {
+ rh_cleanup(lp, NULL);
+ }
+ return store;
}
static inline cbm_store_t *rh_index(RProj *lp, const char *filename, const char *content) {
@@ -114,12 +139,15 @@ static inline void rh_cleanup(RProj *lp, cbm_store_t *store) {
free(lp->project);
lp->project = NULL;
th_rmtree(lp->tmpdir);
- unlink(lp->dbpath);
- char wal[600], shm[600];
- snprintf(wal, sizeof(wal), "%s-wal", lp->dbpath);
- unlink(wal);
- snprintf(shm, sizeof(shm), "%s-shm", lp->dbpath);
- unlink(shm);
+ th_rmtree(lp->cachedir);
+ if (lp->dbpath[0]) {
+ unlink(lp->dbpath);
+ char wal[600], shm[600];
+ snprintf(wal, sizeof(wal), "%s-wal", lp->dbpath);
+ unlink(wal);
+ snprintf(shm, sizeof(shm), "%s-shm", lp->dbpath);
+ unlink(shm);
+ }
}
/* Count edges of a given type in the project graph. Returns -1 on query error. */
diff --git a/tests/repro/repro_harness_cleanup.c b/tests/repro/repro_harness_cleanup.c
new file mode 100644
index 000000000..57db20b66
--- /dev/null
+++ b/tests/repro/repro_harness_cleanup.c
@@ -0,0 +1,140 @@
+/* Reproduction for temporary directories leaked by repro_harness failures. */
+#include "test_framework.h"
+#include "repro_harness.h"
+
+#include <stdio.h>
+#include <sys/stat.h>
+
+static int cleanup_path_exists(const char *path) {
+ struct stat st;
+ return path && path[0] && stat(path, &st) == 0;
+}
+
+static int cleanup_write_sentinel(const char *path) {
+ FILE *file = cbm_fopen(path, "wb");
+ if (!file) {
+ return 0;
+ }
+ int wrote = fputs("sentinel\n", file) >= 0;
+ int closed = fclose(file) == 0;
+ return wrote && closed;
+}
+
+TEST(repro_harness_cleans_temp_project_after_fixture_write_failure) {
+ RProj project;
+ const RFile invalid_file = {
+ "", /* Resolves to the fresh project directory, so fopen must fail. */
+ "fixture content",
+ };
+
+ cbm_store_t *store = rh_index_files(&project, &invalid_file, 1);
+
+ char tmpdir[sizeof(project.tmpdir)];
+ char cachedir[sizeof(project.cachedir)];
+ snprintf(tmpdir, sizeof(tmpdir), "%s", project.tmpdir);
+ snprintf(cachedir, sizeof(cachedir), "%s", project.cachedir);
+
+ int temp_project_was_created = tmpdir[0] != '\0';
+ int tmpdir_remained = cleanup_path_exists(tmpdir);
+ int cachedir_remained = cleanup_path_exists(cachedir);
+
+ /* This failure happens before dbpath is initialized. Keep rh_cleanup's WAL
+ * cleanup absolute so the RED guard cannot unlink a relative workspace file. */
+ if (!project.dbpath[0]) {
+ snprintf(project.dbpath, sizeof(project.dbpath), "/tmp/cbm_repro_cleanup_guard_%ld.db",
+ (long)getpid());
+ }
+ rh_cleanup(&project, store);
+
+ int explicit_cleanup_left_tmpdir = cleanup_path_exists(tmpdir);
+ int explicit_cleanup_left_cachedir = cleanup_path_exists(cachedir);
+
+ if (store != NULL) {
+ fprintf(stderr, " [repro-harness-cleanup] invariant=invalid_fixture_was_indexed\n");
+ FAIL("invalid fixture path must make rh_index_files return NULL");
+ }
+ if (!temp_project_was_created) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=temp_project_not_created_before_failure\n");
+ FAIL("test did not reach the post-mkdtemp fixture-write failure path");
+ }
+ if (explicit_cleanup_left_tmpdir || explicit_cleanup_left_cachedir) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=test_cleanup_failed tmpdir=%d cachedir=%d\n",
+ explicit_cleanup_left_tmpdir, explicit_cleanup_left_cachedir);
+ FAIL("rh_cleanup did not remove the test's temporary directories");
+ }
+ if (tmpdir_remained || cachedir_remained) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=helper_returned_with_temp_state "
+ "tmpdir=%d cachedir=%d\n",
+ tmpdir_remained, cachedir_remained);
+ FAIL("rh_index_files must clean temporary directories before returning NULL");
+ }
+
+ PASS();
+}
+
+TEST(repro_harness_cleanup_empty_dbpath_preserves_relative_sidecars) {
+ /* Empty dbpath must be a no-op for sidecars, never a cwd-relative unlink. */
+ char original_cwd[1024];
+ char private_dir[256] = "/tmp/cbm_repro_empty_dbpath_XXXXXX";
+ _Static_assert(sizeof(private_dir) >= 256,
+ "cbm_mkdtemp requires a 256-byte caller buffer on Windows");
+ int entered_private_dir = 0;
+ int wal_created = 0;
+ int shm_created = 0;
+ int wal_survived = 0;
+ int shm_survived = 0;
+
+ if (!getcwd(original_cwd, sizeof(original_cwd))) {
+ FAIL("test could not record the original working directory");
+ }
+ if (!cbm_mkdtemp(private_dir)) {
+ FAIL("test could not create a private temporary working directory");
+ }
+
+ entered_private_dir = chdir(private_dir) == 0;
+ if (entered_private_dir) {
+ wal_created = cleanup_write_sentinel("-wal");
+ shm_created = cleanup_write_sentinel("-shm");
+ if (wal_created && shm_created) {
+ RProj project = {0};
+ rh_cleanup(&project, NULL);
+ wal_survived = cleanup_path_exists("-wal");
+ shm_survived = cleanup_path_exists("-shm");
+ }
+ }
+
+ int restored_cwd = chdir(original_cwd) == 0;
+ int removed_private_dir = th_rmtree(private_dir) == 0;
+
+ if (!entered_private_dir || !wal_created || !shm_created) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=sentinel_setup_failed entered=%d "
+ "wal_created=%d shm_created=%d\n",
+ entered_private_dir, wal_created, shm_created);
+ FAIL("test could not establish the empty-dbpath sidecar preconditions");
+ }
+ if (!restored_cwd || !removed_private_dir) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=test_cleanup_failed restored_cwd=%d "
+ "removed_private_dir=%d\n",
+ restored_cwd, removed_private_dir);
+ FAIL("test did not restore and remove its private working directory");
+ }
+ if (!wal_survived || !shm_survived) {
+ fprintf(stderr,
+ " [repro-harness-cleanup] invariant=empty_dbpath_unlinked_relative_sidecar "
+ "wal_survived=%d shm_survived=%d\n",
+ wal_survived, shm_survived);
+ FAIL("rh_cleanup with an empty dbpath must not unlink relative -wal/-shm files");
+ }
+
+ PASS();
+}
+
+SUITE(repro_harness_cleanup) {
+ RUN_TEST(repro_harness_cleans_temp_project_after_fixture_write_failure);
+ RUN_TEST(repro_harness_cleanup_empty_dbpath_preserves_relative_sidecars);
+}
diff --git a/tests/repro/repro_language_registry.c b/tests/repro/repro_language_registry.c
new file mode 100644
index 000000000..a779a1ba0
--- /dev/null
+++ b/tests/repro/repro_language_registry.c
@@ -0,0 +1,574 @@
+/* Reproductions for CBMLanguage-to-spec registry invariants.
+ *
+ * This ledger classifies raw call-node metadata and generic identifier/reference
+ * vocabulary. It does not claim that every call-capable language can produce an
+ * exact graph CALL_REFERENCE edge; that narrower semantic contract is covered
+ * by the reference-precision suites. */
+#include "test_framework.h"
+#include "lang_specs.h"
+#include "tree_sitter/api.h"
+
+#include <stdio.h>
+#include <string.h>
+
+typedef enum {
+ CAP_UNSET = 0,
+ CAP_CALL_WITH_REFERENCE_VOCAB,
+ CAP_CALL_WITHOUT_REFERENCE_VOCAB,
+ CAP_NO_CALL,
+ CAP_TRANSFORM_ONLY,
+ CAP_UNSUPPORTED,
+ CAP_COUNT
+} LanguageCapability;
+
+typedef struct {
+ LanguageCapability capability;
+ const char *name;
+ const char *reason;
+} LanguageCapabilityEntry;
+
+size_t repro_call_argument_matrix_a_copy_language_ids(CBMLanguage *language_ids, size_t capacity);
+size_t repro_call_argument_matrix_b_copy_language_ids(CBMLanguage *language_ids, size_t capacity);
+
+#define CALL_WITH_REFERENCE_VOCAB(lang) \
+ [CBM_LANG_##lang] = {CAP_CALL_WITH_REFERENCE_VOCAB, #lang, \
+ "call metadata and a currently recognized reference node"}
+#define CALL_WITHOUT_REFERENCE_VOCAB(lang) \
+ [CBM_LANG_##lang] = {CAP_CALL_WITHOUT_REFERENCE_VOCAB, #lang, \
+ "call metadata but no reference node recognized by extract_usages"}
+#define NO_CALL(lang) \
+ [CBM_LANG_##lang] = {CAP_NO_CALL, #lang, "no call-node metadata; callback case inapplicable"}
+#define TRANSFORM_ONLY(lang) \
+ [CBM_LANG_##lang] = {CAP_TRANSFORM_ONLY, #lang, \
+ "source is transformed into another registered language first"}
+#define UNSUPPORTED(lang) \
+ [CBM_LANG_##lang] = {CAP_UNSUPPORTED, #lang, "enum retained without a registered grammar"}
+
+/* Explicit ledger: no default initializer is intentional. A new enum remains
+ * CAP_UNSET until its call-metadata/reference-vocabulary behavior is audited. */
+static const LanguageCapabilityEntry LANGUAGE_CAPABILITIES[CBM_LANG_COUNT] = {
+ CALL_WITH_REFERENCE_VOCAB(GO),
+ CALL_WITH_REFERENCE_VOCAB(PYTHON),
+ CALL_WITH_REFERENCE_VOCAB(JAVASCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(TYPESCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(TSX),
+ CALL_WITH_REFERENCE_VOCAB(RUST),
+ CALL_WITH_REFERENCE_VOCAB(JAVA),
+ CALL_WITH_REFERENCE_VOCAB(CPP),
+ CALL_WITH_REFERENCE_VOCAB(CSHARP),
+ CALL_WITHOUT_REFERENCE_VOCAB(PHP),
+ CALL_WITH_REFERENCE_VOCAB(LUA),
+ CALL_WITH_REFERENCE_VOCAB(SCALA),
+ CALL_WITH_REFERENCE_VOCAB(KOTLIN),
+ CALL_WITH_REFERENCE_VOCAB(RUBY),
+ CALL_WITH_REFERENCE_VOCAB(C),
+ CALL_WITHOUT_REFERENCE_VOCAB(BASH),
+ CALL_WITH_REFERENCE_VOCAB(ZIG),
+ CALL_WITH_REFERENCE_VOCAB(ELIXIR),
+ CALL_WITH_REFERENCE_VOCAB(HASKELL),
+ CALL_WITH_REFERENCE_VOCAB(OCAML),
+ CALL_WITH_REFERENCE_VOCAB(OBJC),
+ CALL_WITH_REFERENCE_VOCAB(SWIFT),
+ CALL_WITH_REFERENCE_VOCAB(DART),
+ CALL_WITHOUT_REFERENCE_VOCAB(PERL),
+ CALL_WITH_REFERENCE_VOCAB(GROOVY),
+ CALL_WITH_REFERENCE_VOCAB(ERLANG),
+ CALL_WITH_REFERENCE_VOCAB(R),
+ NO_CALL(HTML),
+ CALL_WITH_REFERENCE_VOCAB(CSS),
+ CALL_WITH_REFERENCE_VOCAB(SCSS),
+ NO_CALL(YAML),
+ NO_CALL(TOML),
+ CALL_WITH_REFERENCE_VOCAB(HCL),
+ CALL_WITH_REFERENCE_VOCAB(SQL),
+ NO_CALL(DOCKERFILE),
+ CALL_WITHOUT_REFERENCE_VOCAB(CLOJURE),
+ CALL_WITH_REFERENCE_VOCAB(FSHARP),
+ CALL_WITH_REFERENCE_VOCAB(JULIA),
+ CALL_WITH_REFERENCE_VOCAB(VIMSCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(NIX),
+ CALL_WITHOUT_REFERENCE_VOCAB(COMMONLISP),
+ CALL_WITHOUT_REFERENCE_VOCAB(ELM),
+ CALL_WITH_REFERENCE_VOCAB(FORTRAN),
+ CALL_WITH_REFERENCE_VOCAB(CUDA),
+ CALL_WITHOUT_REFERENCE_VOCAB(COBOL),
+ CALL_WITH_REFERENCE_VOCAB(VERILOG),
+ CALL_WITHOUT_REFERENCE_VOCAB(EMACSLISP),
+ NO_CALL(JSON),
+ NO_CALL(XML),
+ NO_CALL(MARKDOWN),
+ CALL_WITHOUT_REFERENCE_VOCAB(MAKEFILE),
+ CALL_WITH_REFERENCE_VOCAB(CMAKE),
+ NO_CALL(PROTOBUF),
+ NO_CALL(GRAPHQL),
+ NO_CALL(VUE),
+ NO_CALL(SVELTE),
+ CALL_WITH_REFERENCE_VOCAB(MESON),
+ CALL_WITH_REFERENCE_VOCAB(GLSL),
+ NO_CALL(INI),
+ CALL_WITH_REFERENCE_VOCAB(MATLAB),
+ CALL_WITH_REFERENCE_VOCAB(LEAN),
+ CALL_WITH_REFERENCE_VOCAB(FORM),
+ CALL_WITH_REFERENCE_VOCAB(MAGMA),
+ CALL_WITHOUT_REFERENCE_VOCAB(WOLFRAM),
+ CALL_WITH_REFERENCE_VOCAB(SOLIDITY),
+ CALL_WITHOUT_REFERENCE_VOCAB(TYPST),
+ CALL_WITH_REFERENCE_VOCAB(GDSCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(GLEAM),
+ CALL_WITHOUT_REFERENCE_VOCAB(POWERSHELL),
+ CALL_WITH_REFERENCE_VOCAB(PASCAL),
+ CALL_WITH_REFERENCE_VOCAB(DLANG),
+ UNSUPPORTED(NIM),
+ CALL_WITHOUT_REFERENCE_VOCAB(SCHEME),
+ CALL_WITHOUT_REFERENCE_VOCAB(FENNEL),
+ CALL_WITHOUT_REFERENCE_VOCAB(FISH),
+ CALL_WITH_REFERENCE_VOCAB(AWK),
+ CALL_WITHOUT_REFERENCE_VOCAB(ZSH),
+ CALL_WITHOUT_REFERENCE_VOCAB(TCL),
+ CALL_WITH_REFERENCE_VOCAB(ADA),
+ CALL_WITHOUT_REFERENCE_VOCAB(AGDA),
+ CALL_WITHOUT_REFERENCE_VOCAB(RACKET),
+ CALL_WITH_REFERENCE_VOCAB(ODIN),
+ CALL_WITH_REFERENCE_VOCAB(RESCRIPT),
+ CALL_WITHOUT_REFERENCE_VOCAB(PURESCRIPT),
+ CALL_WITHOUT_REFERENCE_VOCAB(NICKEL),
+ CALL_WITH_REFERENCE_VOCAB(CRYSTAL),
+ CALL_WITH_REFERENCE_VOCAB(TEAL),
+ CALL_WITH_REFERENCE_VOCAB(HARE),
+ CALL_WITH_REFERENCE_VOCAB(PONY),
+ CALL_WITH_REFERENCE_VOCAB(LUAU),
+ NO_CALL(JANET),
+ CALL_WITH_REFERENCE_VOCAB(SWAY),
+ CALL_WITHOUT_REFERENCE_VOCAB(NASM),
+ NO_CALL(ASSEMBLY),
+ NO_CALL(ASTRO),
+ NO_CALL(BLADE),
+ CALL_WITH_REFERENCE_VOCAB(JUST),
+ CALL_WITH_REFERENCE_VOCAB(GOTEMPLATE),
+ CALL_WITH_REFERENCE_VOCAB(TEMPL),
+ NO_CALL(LIQUID),
+ NO_CALL(JINJA2),
+ CALL_WITH_REFERENCE_VOCAB(PRISMA),
+ NO_CALL(HYPRLANG),
+ NO_CALL(DOTENV),
+ NO_CALL(DIFF),
+ CALL_WITH_REFERENCE_VOCAB(WGSL),
+ NO_CALL(KDL),
+ NO_CALL(JSON5),
+ CALL_WITH_REFERENCE_VOCAB(JSONNET),
+ NO_CALL(RON),
+ NO_CALL(THRIFT),
+ NO_CALL(CAPNP),
+ NO_CALL(PROPERTIES),
+ NO_CALL(SSHCONFIG),
+ NO_CALL(BIBTEX),
+ CALL_WITH_REFERENCE_VOCAB(STARLARK),
+ CALL_WITH_REFERENCE_VOCAB(BICEP),
+ NO_CALL(CSV),
+ NO_CALL(REQUIREMENTS),
+ CALL_WITH_REFERENCE_VOCAB(HLSL),
+ CALL_WITH_REFERENCE_VOCAB(VHDL),
+ CALL_WITH_REFERENCE_VOCAB(SYSTEMVERILOG),
+ CALL_WITH_REFERENCE_VOCAB(DEVICETREE),
+ CALL_WITHOUT_REFERENCE_VOCAB(LINKERSCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(GN),
+ NO_CALL(KCONFIG),
+ CALL_WITH_REFERENCE_VOCAB(BITBAKE),
+ NO_CALL(SMALI),
+ NO_CALL(TABLEGEN),
+ CALL_WITH_REFERENCE_VOCAB(ISPC),
+ CALL_WITH_REFERENCE_VOCAB(CAIRO),
+ CALL_WITH_REFERENCE_VOCAB(MOVE),
+ CALL_WITH_REFERENCE_VOCAB(SQUIRREL),
+ CALL_WITH_REFERENCE_VOCAB(FUNC),
+ NO_CALL(REGEX),
+ NO_CALL(JSDOC),
+ NO_CALL(RST),
+ NO_CALL(BEANCOUNT),
+ NO_CALL(MERMAID),
+ CALL_WITHOUT_REFERENCE_VOCAB(PUPPET),
+ NO_CALL(PO),
+ NO_CALL(GITATTRIBUTES),
+ NO_CALL(GITIGNORE),
+ CALL_WITH_REFERENCE_VOCAB(SLANG),
+ CALL_WITHOUT_REFERENCE_VOCAB(LLVM_IR),
+ NO_CALL(SMITHY),
+ NO_CALL(WIT),
+ CALL_WITH_REFERENCE_VOCAB(TLAPLUS),
+ NO_CALL(PKL),
+ NO_CALL(GOMOD),
+ CALL_WITH_REFERENCE_VOCAB(APEX),
+ NO_CALL(SOQL),
+ NO_CALL(SOSL),
+ NO_CALL(KUSTOMIZE),
+ NO_CALL(K8S),
+ CALL_WITH_REFERENCE_VOCAB(PINE),
+ CALL_WITH_REFERENCE_VOCAB(QML),
+ CALL_WITH_REFERENCE_VOCAB(CFSCRIPT),
+ CALL_WITH_REFERENCE_VOCAB(CFML),
+ CALL_WITH_REFERENCE_VOCAB(MOJO),
+ CALL_WITH_REFERENCE_VOCAB(OBJECTSCRIPT_UDL),
+ CALL_WITH_REFERENCE_VOCAB(OBJECTSCRIPT_ROUTINE),
+ TRANSFORM_ONLY(OBJECTSCRIPT_EXPORT),
+};
+
+#undef CALL_WITH_REFERENCE_VOCAB
+#undef CALL_WITHOUT_REFERENCE_VOCAB
+#undef NO_CALL
+#undef TRANSFORM_ONLY
+#undef UNSUPPORTED
+
+_Static_assert(sizeof(LANGUAGE_CAPABILITIES) / sizeof(LANGUAGE_CAPABILITIES[0]) == CBM_LANG_COUNT,
+ "language capability ledger must track CBM_LANG_COUNT");
+
+static int grammar_has_symbol(const TSLanguage *language, const char *expected_name) {
+ uint32_t symbol_count = ts_language_symbol_count(language);
+ for (TSSymbol symbol = 0; symbol < symbol_count; symbol++) {
+ const char *actual_name = ts_language_symbol_name(language, symbol);
+ if (actual_name && strcmp(actual_name, expected_name) == 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+/* Every enum value must either be unsupported (NULL) or map to a spec tagged
+ * with that exact language. A missing designated initializer must never alias
+ * the zero-initialized CBM_LANG_GO slot. */
+TEST(repro_language_specs_do_not_alias_other_languages) {
+ int failures = 0;
+ for (int value = 0; value < CBM_LANG_COUNT; value++) {
+ CBMLanguage language = (CBMLanguage)value;
+ const CBMLangSpec *spec = cbm_lang_spec(language);
+ if (spec && spec->language != language) {
+ fprintf(
+ stderr,
+ " [language-registry] invariant=spec_language_mismatch requested=%d actual=%d\n",
+ value, (int)spec->language);
+ failures++;
+ }
+ }
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_language_capability_ledger_covers_every_enum) {
+ int failures = 0;
+ int counts[CAP_COUNT] = {0};
+
+ for (int value = 0; value < CBM_LANG_COUNT; value++) {
+ const LanguageCapabilityEntry *entry = &LANGUAGE_CAPABILITIES[value];
+ const CBMLangSpec *spec = cbm_lang_spec((CBMLanguage)value);
+ if (entry->capability <= CAP_UNSET || entry->capability >= CAP_COUNT || !entry->name ||
+ !entry->reason) {
+ fprintf(stderr, " [language-registry] invariant=capability_unset requested=%d\n",
+ value);
+ failures++;
+ continue;
+ }
+ counts[entry->capability]++;
+
+ if (entry->capability == CAP_UNSUPPORTED || entry->capability == CAP_TRANSFORM_ONLY) {
+ if (spec) {
+ fprintf(stderr,
+ " [language-registry] lang=%s "
+ "invariant=non_grammar_capability_spec_nonnull capability=%d actual=%d\n",
+ entry->name, (int)entry->capability, (int)spec->language);
+ failures++;
+ }
+ continue;
+ }
+
+ if (!spec || spec->language != (CBMLanguage)value) {
+ fprintf(stderr, " [language-registry] lang=%s invariant=registered_spec_missing\n",
+ entry->name);
+ failures++;
+ continue;
+ }
+
+ int has_call_metadata = spec->call_node_types && spec->call_node_types[0];
+ int expects_call_metadata = entry->capability == CAP_CALL_WITH_REFERENCE_VOCAB ||
+ entry->capability == CAP_CALL_WITHOUT_REFERENCE_VOCAB;
+ if (has_call_metadata != expects_call_metadata) {
+ fprintf(stderr,
+ " [language-registry] lang=%s invariant=call_capability_mismatch expected=%d "
+ "actual=%d\n",
+ entry->name, expects_call_metadata, has_call_metadata);
+ failures++;
+ }
+ }
+
+ if (counts[CAP_CALL_WITH_REFERENCE_VOCAB] != 86 ||
+ counts[CAP_CALL_WITHOUT_REFERENCE_VOCAB] != 25 || counts[CAP_NO_CALL] != 50 ||
+ counts[CAP_TRANSFORM_ONLY] != 1 || counts[CAP_UNSUPPORTED] != 1) {
+ fprintf(stderr,
+ " [language-registry] invariant=capability_partition call_ref_vocab=%d ref_gap=%d "
+ "no_call=%d transform_only=%d unsupported=%d\n",
+ counts[CAP_CALL_WITH_REFERENCE_VOCAB], counts[CAP_CALL_WITHOUT_REFERENCE_VOCAB],
+ counts[CAP_NO_CALL], counts[CAP_TRANSFORM_ONLY], counts[CAP_UNSUPPORTED]);
+ failures++;
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_call_argument_matrices_equal_call_capability_ledger) {
+ enum {
+ EXPECTED_MATRIX_A_ROWS = 67,
+ EXPECTED_MATRIX_B_ROWS = 46,
+ EXPECTED_CALL_CAPABLE_LANGUAGES = 111,
+ EXPECTED_NON_CALL_LANGUAGES = 52,
+ EXPECTED_NON_CALL_DOMAIN_CONTROLS = 2,
+ };
+ CBMLanguage matrix_a_ids[CBM_LANG_COUNT];
+ CBMLanguage matrix_b_ids[CBM_LANG_COUNT];
+ unsigned int matrix_a_counts[CBM_LANG_COUNT] = {0};
+ unsigned int matrix_b_counts[CBM_LANG_COUNT] = {0};
+ size_t matrix_a_rows = repro_call_argument_matrix_a_copy_language_ids(
+ matrix_a_ids, sizeof(matrix_a_ids) / sizeof(matrix_a_ids[0]));
+ size_t matrix_b_rows = repro_call_argument_matrix_b_copy_language_ids(
+ matrix_b_ids, sizeof(matrix_b_ids) / sizeof(matrix_b_ids[0]));
+ int failures = 0;
+
+ if (matrix_a_rows != EXPECTED_MATRIX_A_ROWS) {
+ fprintf(stderr,
+ " [language-registry] matrix=A invariant=row_count expected=%d actual=%zu\n",
+ EXPECTED_MATRIX_A_ROWS, matrix_a_rows);
+ failures++;
+ }
+ if (matrix_b_rows != EXPECTED_MATRIX_B_ROWS) {
+ fprintf(stderr,
+ " [language-registry] matrix=B invariant=row_count expected=%d actual=%zu\n",
+ EXPECTED_MATRIX_B_ROWS, matrix_b_rows);
+ failures++;
+ }
+
+ size_t matrix_a_copied =
+ matrix_a_rows < CBM_LANG_COUNT ? matrix_a_rows : (size_t)CBM_LANG_COUNT;
+ for (size_t row = 0; row < matrix_a_copied; row++) {
+ int language_id = (int)matrix_a_ids[row];
+ if (language_id < 0 || language_id >= CBM_LANG_COUNT) {
+ fprintf(stderr,
+ " [language-registry] matrix=A row=%zu invariant=language_id_range id=%d\n",
+ row, language_id);
+ failures++;
+ continue;
+ }
+ matrix_a_counts[language_id]++;
+ }
+
+ size_t matrix_b_copied =
+ matrix_b_rows < CBM_LANG_COUNT ? matrix_b_rows : (size_t)CBM_LANG_COUNT;
+ for (size_t row = 0; row < matrix_b_copied; row++) {
+ int language_id = (int)matrix_b_ids[row];
+ if (language_id < 0 || language_id >= CBM_LANG_COUNT) {
+ fprintf(stderr,
+ " [language-registry] matrix=B row=%zu invariant=language_id_range id=%d\n",
+ row, language_id);
+ failures++;
+ continue;
+ }
+ matrix_b_counts[language_id]++;
+ }
+
+ int call_capable_languages = 0;
+ int covered_call_capable_languages = 0;
+ int explicitly_non_call_languages = 0;
+ int covered_non_call_domain_controls = 0;
+ for (int language_id = 0; language_id < CBM_LANG_COUNT; language_id++) {
+ const LanguageCapabilityEntry *entry = &LANGUAGE_CAPABILITIES[language_id];
+ const char *language_name = entry->name ? entry->name : "<unclassified>";
+ unsigned int matrix_a_count = matrix_a_counts[language_id];
+ unsigned int matrix_b_count = matrix_b_counts[language_id];
+ unsigned int total_count = matrix_a_count + matrix_b_count;
+ int call_capable = entry->capability == CAP_CALL_WITH_REFERENCE_VOCAB ||
+ entry->capability == CAP_CALL_WITHOUT_REFERENCE_VOCAB;
+
+ if (matrix_a_count > 1) {
+ fprintf(stderr,
+ " [language-registry] matrix=A lang=%s id=%d invariant=duplicate_language "
+ "actual=%u\n",
+ language_name, language_id, matrix_a_count);
+ failures++;
+ }
+ if (matrix_b_count > 1) {
+ fprintf(stderr,
+ " [language-registry] matrix=B lang=%s id=%d invariant=duplicate_language "
+ "actual=%u\n",
+ language_name, language_id, matrix_b_count);
+ failures++;
+ }
+ if (matrix_a_count && matrix_b_count) {
+ fprintf(stderr,
+ " [language-registry] lang=%s id=%d invariant=matrix_overlap matrix_a=%u "
+ "matrix_b=%u\n",
+ language_name, language_id, matrix_a_count, matrix_b_count);
+ failures++;
+ }
+
+ if (call_capable) {
+ call_capable_languages++;
+ if (total_count == 0) {
+ fprintf(stderr,
+ " [language-registry] lang=%s id=%d "
+ "invariant=call_capability_missing_from_matrices\n",
+ language_name, language_id);
+ failures++;
+ } else {
+ covered_call_capable_languages++;
+ if (total_count != 1) {
+ fprintf(stderr,
+ " [language-registry] lang=%s id=%d "
+ "invariant=call_capability_matrix_count expected=1 actual=%u\n",
+ language_name, language_id, total_count);
+ failures++;
+ }
+ }
+ continue;
+ }
+
+ if (entry->capability != CAP_NO_CALL && entry->capability != CAP_TRANSFORM_ONLY &&
+ entry->capability != CAP_UNSUPPORTED) {
+ fprintf(stderr,
+ " [language-registry] lang=%s id=%d "
+ "invariant=remaining_capability_explicit "
+ "expected=NO_CALL_or_TRANSFORM_ONLY_or_UNSUPPORTED "
+ "actual=%d\n",
+ language_name, language_id, (int)entry->capability);
+ failures++;
+ } else {
+ explicitly_non_call_languages++;
+ }
+ int expected_domain_control =
+ language_id == CBM_LANG_DIFF || language_id == CBM_LANG_BIBTEX;
+ if (expected_domain_control && total_count == 1) {
+ covered_non_call_domain_controls++;
+ } else if (total_count != 0 || expected_domain_control) {
+ fprintf(stderr,
+ " [language-registry] lang=%s id=%d "
+ "invariant=non_call_domain_control_coverage expected=%d "
+ "matrix_a=%u matrix_b=%u\n",
+ language_name, language_id, expected_domain_control, matrix_a_count,
+ matrix_b_count);
+ failures++;
+ }
+ }
+
+ if (call_capable_languages != EXPECTED_CALL_CAPABLE_LANGUAGES ||
+ covered_call_capable_languages != EXPECTED_CALL_CAPABLE_LANGUAGES ||
+ explicitly_non_call_languages != EXPECTED_NON_CALL_LANGUAGES ||
+ covered_non_call_domain_controls != EXPECTED_NON_CALL_DOMAIN_CONTROLS) {
+ fprintf(stderr,
+ " [language-registry] invariant=matrix_ledger_partition "
+ "call_capable_expected=%d call_capable_actual=%d covered_actual=%d "
+ "non_call_expected=%d non_call_actual=%d "
+ "non_call_controls_expected=%d non_call_controls_actual=%d\n",
+ EXPECTED_CALL_CAPABLE_LANGUAGES, call_capable_languages,
+ covered_call_capable_languages, EXPECTED_NON_CALL_LANGUAGES,
+ explicitly_non_call_languages, EXPECTED_NON_CALL_DOMAIN_CONTROLS,
+ covered_non_call_domain_controls);
+ failures++;
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* A call-node registration that does not exist in the compiled grammar can
+ * never match an AST node. Check the compiled language instead of trusting
+ * hand-maintained spec strings or the graph index. */
+TEST(repro_primary_call_metadata_names_exist_in_grammars) {
+ int failures = 0;
+
+ for (int value = 0; value < CBM_LANG_COUNT; value++) {
+ const LanguageCapabilityEntry *entry = &LANGUAGE_CAPABILITIES[value];
+ const CBMLangSpec *spec = cbm_lang_spec((CBMLanguage)value);
+ const TSLanguage *language = cbm_ts_language((CBMLanguage)value);
+ if (!spec || !spec->call_node_types || !spec->call_node_types[0]) {
+ continue;
+ }
+ if (!language) {
+ fprintf(stderr,
+ " [language-registry] lang=%s invariant=call_metadata_grammar_missing\n",
+ entry->name);
+ failures++;
+ continue;
+ }
+
+ for (int i = 0; spec->call_node_types[i]; i++) {
+ const char *call_node_type = spec->call_node_types[i];
+ if (!grammar_has_symbol(language, call_node_type)) {
+ fprintf(stderr,
+ " [language-registry] lang=%s "
+ "invariant=call_node_type_exists node=%s\n",
+ entry->name, call_node_type);
+ failures++;
+ }
+ }
+ }
+
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+/* LinkerScript's compiled grammar root is `linkerscript`, while the language
+ * spec currently registers `source_file`. Path-derived module QNs hide the
+ * mismatch, so exercise the AST-to-metadata contract directly. */
+TEST(repro_linkerscript_root_is_registered_as_module) {
+ static const char source[] = "SECTIONS { .text : { *(.text) } }\n";
+ const CBMLangSpec *spec = cbm_lang_spec(CBM_LANG_LINKERSCRIPT);
+ const TSLanguage *language = cbm_ts_language(CBM_LANG_LINKERSCRIPT);
+ TSParser *parser = ts_parser_new();
+ int failures = 0;
+
+ if (!spec || !language || !parser || !ts_parser_set_language(parser, language)) {
+ fprintf(stderr, " [language-registry] lang=LINKERSCRIPT invariant=parser_setup\n");
+ failures++;
+ } else {
+ TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
+ if (!tree) {
+ fprintf(stderr,
+ " [language-registry] lang=LINKERSCRIPT invariant=parse_tree_nonnull\n");
+ failures++;
+ } else {
+ TSNode root = ts_tree_root_node(tree);
+ const char *root_kind = ts_node_type(root);
+ int registered = 0;
+ if (spec->module_node_types) {
+ for (int i = 0; spec->module_node_types[i]; i++) {
+ if (strcmp(spec->module_node_types[i], root_kind) == 0) {
+ registered = 1;
+ break;
+ }
+ }
+ }
+ if (ts_node_has_error(root)) {
+ fprintf(stderr,
+ " [language-registry] lang=LINKERSCRIPT invariant=valid_fixture\n");
+ failures++;
+ }
+ if (!registered) {
+ fprintf(stderr,
+ " [language-registry] lang=LINKERSCRIPT "
+ "invariant=root_registered_as_module root=%s\n",
+ root_kind);
+ failures++;
+ }
+ ts_tree_delete(tree);
+ }
+ }
+ if (parser) {
+ ts_parser_delete(parser);
+ }
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+SUITE(repro_language_registry) {
+ RUN_TEST(repro_language_specs_do_not_alias_other_languages);
+ RUN_TEST(repro_language_capability_ledger_covers_every_enum);
+ RUN_TEST(repro_call_argument_matrices_equal_call_capability_ledger);
+ RUN_TEST(repro_primary_call_metadata_names_exist_in_grammars);
+ RUN_TEST(repro_linkerscript_root_is_registered_as_module);
+}
diff --git a/tests/repro/repro_lexical_binding_precision.c b/tests/repro/repro_lexical_binding_precision.c
new file mode 100644
index 000000000..6c014c2af
--- /dev/null
+++ b/tests/repro/repro_lexical_binding_precision.c
@@ -0,0 +1,1060 @@
+/*
+ * repro_lexical_binding_precision.c — exact lexical-shadowing contracts.
+ *
+ * These tests inspect raw CBMUsage rows rather than graph edges. A local
+ * binding must block semantic promotion only for the identifier occurrence
+ * whose language scope actually contains that binding. The exact byte span
+ * keeps a declaration, label, or same-spelled occurrence from satisfying the
+ * assertion accidentally.
+ */
+#include "test_framework.h"
+#include "cbm.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+
+typedef struct {
+ int count;
+ int value_count;
+ int candidate_count;
+ int blocked_count;
+ int local_shadow_count;
+} LBBindingSite;
+
+static int lb_qn_ends_with(const char *qn, const char *suffix) {
+ if (!qn || !suffix) {
+ return 0;
+ }
+ size_t qn_len = strlen(qn);
+ size_t suffix_len = strlen(suffix);
+ return qn_len >= suffix_len && strcmp(qn + qn_len - suffix_len, suffix) == 0;
+}
+
+static uint32_t lb_identifier_offset(const char *source, const char *marker,
+ const char *identifier) {
+ const char *occurrence = strstr(source, marker);
+ if (!occurrence) {
+ return UINT32_MAX;
+ }
+ const char *site = strstr(occurrence, identifier);
+ if (!site || site >= occurrence + strlen(marker)) {
+ return UINT32_MAX;
+ }
+ return (uint32_t)(site - source);
+}
+
+static LBBindingSite lb_binding_site(const CBMFileResult *result, const char *caller_suffix,
+ const char *identifier, uint32_t start) {
+ LBBindingSite match = {0};
+ uint32_t end = start + (uint32_t)strlen(identifier);
+ for (int i = 0; result && i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ if (!usage->ref_name || strcmp(usage->ref_name, identifier) != 0 ||
+ (caller_suffix && !lb_qn_ends_with(usage->enclosing_func_qn, caller_suffix)) ||
+ usage->site_start_byte != start || usage->site_end_byte != end) {
+ continue;
+ }
+ match.count++;
+ match.value_count += usage->kind == CBM_USAGE_VALUE;
+ match.candidate_count += usage->may_be_call_reference;
+ match.blocked_count += usage->semantic_reference_blocked;
+ match.local_shadow_count += usage->semantic_reference_local_shadow;
+ }
+ return match;
+}
+
+static CBMFileResult *lb_extract(const char *source, CBMLanguage language, const char *filename) {
+ return cbm_extract_file(source, (int)strlen(source), language, "repro", filename, 0, NULL,
+ NULL);
+}
+
+/* A Python keyword label names the callee's parameter. It does not introduce
+ * a local named `handler` in caller, so the later global function value remains
+ * eligible for exact semantic resolution. */
+TEST(repro_python_keyword_label_does_not_bind_local) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def sink(**kwargs):\n"
+ " pass\n"
+ "def caller():\n"
+ " sink(handler=1)\n"
+ " accept(handler)\n"
+ "def parameter_control(handler):\n"
+ " accept_control(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ uint32_t control_site = lb_identifier_offset(source, "accept_control(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ ASSERT_NEQ(control_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "keyword_label.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ LBBindingSite control = lb_binding_site(result, "parameter_control", "handler", control_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(control.count, 1);
+ ASSERT_EQ(control.blocked_count, 1);
+ ASSERT_EQ(control.local_shadow_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* The declaration identifier belongs to the enclosing scope. Once the
+ * function body is active, visiting that identifier must not make the function
+ * shadow itself. */
+TEST(repro_python_function_name_does_not_shadow_itself) {
+ static const char source[] = "def accept(callback):\n"
+ " pass\n"
+ "def pass_self():\n"
+ " accept(pass_self)\n"
+ "def parameter_control(pass_self):\n"
+ " accept_control(pass_self)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(pass_self)", "pass_self");
+ uint32_t control_site = lb_identifier_offset(source, "accept_control(pass_self)", "pass_self");
+ ASSERT_NEQ(site, UINT32_MAX);
+ ASSERT_NEQ(control_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "self_reference.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "pass_self", "pass_self", site);
+ LBBindingSite control = lb_binding_site(result, "parameter_control", "pass_self", control_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(control.count, 1);
+ ASSERT_EQ(control.blocked_count, 1);
+ ASSERT_EQ(control.local_shadow_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A nested Python def creates a local in its enclosing function. Recording
+ * the declaration name only under the nested function's own QN lets a later
+ * use in outer fall through to an unrelated global callable. */
+TEST(repro_python_nested_function_binds_in_enclosing_function) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def outer():\n"
+ " def handler():\n"
+ " pass\n"
+ " accept(handler)\n"
+ "def parameter_control(handler):\n"
+ " accept_control(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ uint32_t control_site = lb_identifier_offset(source, "accept_control(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ ASSERT_NEQ(control_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "nested_definition.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "outer", "handler", site);
+ LBBindingSite control = lb_binding_site(result, "parameter_control", "handler", control_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(control.count, 1);
+ ASSERT_EQ(control.blocked_count, 1);
+ ASSERT_EQ(control.local_shadow_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* Python determines locals for the whole function at compile time. A read
+ * before the assignment is still a local (and would raise UnboundLocalError at
+ * runtime); it must not resolve to the same-named module function. */
+TEST(repro_python_assignment_blocks_earlier_use_for_whole_function) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept_before(callback):\n"
+ " pass\n"
+ "def accept_after(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " accept_before(handler)\n"
+ " handler = 1\n"
+ " accept_after(handler)\n";
+
+ uint32_t before_site = lb_identifier_offset(source, "accept_before(handler)", "handler");
+ uint32_t after_site = lb_identifier_offset(source, "accept_after(handler)", "handler");
+ ASSERT_NEQ(before_site, UINT32_MAX);
+ ASSERT_NEQ(after_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "whole_function_local.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite before = lb_binding_site(result, "caller", "handler", before_site);
+ LBBindingSite after = lb_binding_site(result, "caller", "handler", after_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(before.count, 1);
+ ASSERT_EQ(before.value_count, 1);
+ ASSERT_EQ(before.candidate_count, 1);
+ ASSERT_EQ(after.count, 1);
+ ASSERT_EQ(after.blocked_count, 1);
+ ASSERT_EQ(after.local_shadow_count, 1);
+ ASSERT_EQ(before.blocked_count, 1);
+ ASSERT_EQ(before.local_shadow_count, 1);
+ PASS();
+}
+
+/* JavaScript `let` is block-scoped. The in-block argument is a local, while
+ * the later argument after the block again denotes the module function. */
+TEST(repro_javascript_block_local_stops_at_block_exit) {
+ static const char source[] = "function handler() {}\n"
+ "function acceptInside(callback) {}\n"
+ "function acceptOutside(callback) {}\n"
+ "function caller(flag) {\n"
+ " if (flag) {\n"
+ " let handler = 1;\n"
+ " acceptInside(handler);\n"
+ " }\n"
+ " acceptOutside(handler);\n"
+ "}\n";
+
+ uint32_t inside_site = lb_identifier_offset(source, "acceptInside(handler)", "handler");
+ uint32_t outside_site = lb_identifier_offset(source, "acceptOutside(handler)", "handler");
+ ASSERT_NEQ(inside_site, UINT32_MAX);
+ ASSERT_NEQ(outside_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_JAVASCRIPT, "block_scope.js");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite inside = lb_binding_site(result, "caller", "handler", inside_site);
+ LBBindingSite outside = lb_binding_site(result, "caller", "handler", outside_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(inside.count, 1);
+ ASSERT_EQ(inside.value_count, 1);
+ ASSERT_EQ(inside.blocked_count, 1);
+ ASSERT_EQ(inside.local_shadow_count, 1);
+ ASSERT_EQ(outside.count, 1);
+ ASSERT_EQ(outside.value_count, 1);
+ ASSERT_EQ(outside.candidate_count, 1);
+ ASSERT_EQ(outside.blocked_count, 0);
+ ASSERT_EQ(outside.local_shadow_count, 0);
+ PASS();
+}
+
+/* Overloads currently share a textual function QN. Parameter bindings are
+ * body instances, not QN-wide facts: the first overload's `handler` parameter
+ * must not shadow the method group used by the second overload. */
+TEST(repro_csharp_overload_bodies_do_not_share_parameter_bindings) {
+ static const char source[] =
+ "using System;\n"
+ "class Sample {\n"
+ " static void handler() {}\n"
+ " static void acceptFirst(Action callback) {}\n"
+ " static void acceptSecond(Action callback) {}\n"
+ " static void overloaded(Action handler) { acceptFirst(handler); }\n"
+ " static void overloaded(int count) { acceptSecond(handler); }\n"
+ "}\n";
+
+ uint32_t first_site = lb_identifier_offset(source, "acceptFirst(handler)", "handler");
+ uint32_t second_site = lb_identifier_offset(source, "acceptSecond(handler)", "handler");
+ ASSERT_NEQ(first_site, UINT32_MAX);
+ ASSERT_NEQ(second_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_CSHARP, "Overloads.cs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite first = lb_binding_site(result, "overloaded", "handler", first_site);
+ LBBindingSite second = lb_binding_site(result, "overloaded", "handler", second_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(first.count, 1);
+ ASSERT_EQ(first.value_count, 1);
+ ASSERT_EQ(first.blocked_count, 1);
+ ASSERT_EQ(first.local_shadow_count, 1);
+ ASSERT_EQ(second.count, 1);
+ ASSERT_EQ(second.value_count, 1);
+ ASSERT_EQ(second.candidate_count, 1);
+ ASSERT_EQ(second.blocked_count, 0);
+ ASSERT_EQ(second.local_shadow_count, 0);
+ PASS();
+}
+
+/* PowerShell variable names are case-insensitive. Normalizing the sigil but
+ * retaining case lets `$handler` evade the `$Handler` parameter binding. */
+TEST(repro_powershell_parameter_shadow_is_case_insensitive) {
+ static const char source[] = "function Handler { }\n"
+ "function Caller {\n"
+ " param($Handler)\n"
+ " Write-Output $Handler\n"
+ " Write-Output $handler\n"
+ "}\n";
+
+ uint32_t exact_site = lb_identifier_offset(source, "Write-Output $Handler", "$Handler");
+ uint32_t folded_site = lb_identifier_offset(source, "Write-Output $handler", "$handler");
+ ASSERT_NEQ(exact_site, UINT32_MAX);
+ ASSERT_NEQ(folded_site, UINT32_MAX);
+
+ CBMFileResult *result = lb_extract(source, CBM_LANG_POWERSHELL, "case_scope.ps1");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite exact = lb_binding_site(result, "Caller", "$Handler", exact_site);
+ LBBindingSite folded = lb_binding_site(result, "Caller", "$handler", folded_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(exact.count, 1);
+ ASSERT_EQ(exact.value_count, 1);
+ ASSERT_EQ(exact.blocked_count, 1);
+ ASSERT_EQ(exact.local_shadow_count, 1);
+ ASSERT_EQ(folded.count, 1);
+ ASSERT_EQ(folded.value_count, 1);
+ ASSERT_EQ(folded.blocked_count, 1);
+ ASSERT_EQ(folded.local_shadow_count, 1);
+ PASS();
+}
+
+/* A class statement executes inside outer(), but its namespace is not outer's
+ * local namespace. Class attributes must not poison a later outer-scope value
+ * reference with the same spelling. */
+TEST(repro_python_local_class_binding_stops_at_class_namespace) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def outer():\n"
+ " class Local:\n"
+ " handler = 1\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "local_class.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "outer", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A method's unqualified lookup skips its containing class namespace. The
+ * class attribute named `handler` therefore must not block the module-level
+ * function value used inside method(). */
+TEST(repro_python_method_lookup_bypasses_class_namespace) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def accept_class(callback):\n"
+ " pass\n"
+ "class Sample:\n"
+ " handler = 1\n"
+ " accept_class(handler)\n"
+ " def method(self):\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ uint32_t class_site = lb_identifier_offset(source, "accept_class(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ ASSERT_NEQ(class_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "method_class_scope.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "method", "handler", site);
+ LBBindingSite class_usage = lb_binding_site(result, NULL, "handler", class_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(class_usage.count, 1);
+ ASSERT_EQ(class_usage.blocked_count, 1);
+ ASSERT_EQ(class_usage.local_shadow_count, 1);
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A method's default expressions are evaluated while the class statement is
+ * executing. Unlike the method body, that expression must therefore see and
+ * be blocked by the class attribute with the same spelling. */
+TEST(repro_python_method_default_uses_class_namespace) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "class Sample:\n"
+ " handler = 1\n"
+ " def method(self, callback=handler):\n"
+ " return callback\n";
+
+ uint32_t site = lb_identifier_offset(source, "callback=handler", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "method_default_class_scope.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "method", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* Imports are bindings even though import subtrees are excluded from ordinary
+ * usage emission. Python local imports obey whole-function local analysis, so
+ * both the read before the statement and the read after it are blocked. */
+TEST(repro_python_local_import_alias_binds_whole_function) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept_before(callback):\n"
+ " pass\n"
+ "def accept_after(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " accept_before(handler)\n"
+ " import external_package as handler\n"
+ " accept_after(handler)\n";
+
+ uint32_t before_site = lb_identifier_offset(source, "accept_before(handler)", "handler");
+ uint32_t after_site = lb_identifier_offset(source, "accept_after(handler)", "handler");
+ ASSERT_NEQ(before_site, UINT32_MAX);
+ ASSERT_NEQ(after_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "local_import_alias.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite before = lb_binding_site(result, "caller", "handler", before_site);
+ LBBindingSite after = lb_binding_site(result, "caller", "handler", after_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(before.count, 1);
+ ASSERT_EQ(before.blocked_count, 1);
+ ASSERT_EQ(before.local_shadow_count, 1);
+ ASSERT_EQ(after.count, 1);
+ ASSERT_EQ(after.blocked_count, 1);
+ ASSERT_EQ(after.local_shadow_count, 1);
+ PASS();
+}
+
+TEST(repro_python_local_from_import_alias_binds_whole_function) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " from external_package import remote_value as handler\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "local_from_import_alias.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* Import source paths are not local declarations. In particular, dotted
+ * imports bind their first component and from-imports bind the imported name,
+ * never the source module spelling. */
+TEST(repro_python_import_source_roles_do_not_bind) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " import package.handler\n"
+ " from handler import imported_value\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "import_source_roles.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A future import is a compiler directive. Its feature name is neither an
+ * ordinary value use nor a local binding. */
+TEST(repro_python_future_import_is_not_binding_or_usage) {
+ static const char source[] = "from __future__ import annotations\n"
+ "def annotations():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " accept(annotations)\n";
+
+ uint32_t directive_site =
+ lb_identifier_offset(source, "from __future__ import annotations", "annotations");
+ uint32_t usage_site = lb_identifier_offset(source, "accept(annotations)", "annotations");
+ ASSERT_NEQ(directive_site, UINT32_MAX);
+ ASSERT_NEQ(usage_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "future_import.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite directive = lb_binding_site(result, NULL, "annotations", directive_site);
+ LBBindingSite usage = lb_binding_site(result, "caller", "annotations", usage_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(directive.count, 0);
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ PASS();
+}
+
+/* CBMImport metadata is consumed independently of lexical blockers. Preserve
+ * the complete dependency path while recording Python's actual local binding. */
+TEST(repro_python_dotted_import_records_root_local_name) {
+ static const char source[] = "import package.child\n";
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "dotted_import.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ ASSERT_EQ(result->imports.count, 1);
+ ASSERT_NOT_NULL(result->imports.items[0].local_name);
+ ASSERT_NOT_NULL(result->imports.items[0].module_path);
+ ASSERT_STR_EQ(result->imports.items[0].local_name, "package");
+ ASSERT_STR_EQ(result->imports.items[0].module_path, "package.child");
+ cbm_free_result(result);
+ PASS();
+}
+
+/* A TypeScript import alias owns the module binding. Without exact semantic
+ * proof, the argument must not raw-name-fallback to an unrelated callable
+ * named `handler`. */
+TEST(repro_typescript_import_alias_blocks_raw_callable_fallback) {
+ static const char source[] = "import { remoteValue as handler } from 'external-package';\n"
+ "function accept(callback: unknown): void {}\n"
+ "export function caller(): void { accept(handler); }\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_TYPESCRIPT, "import_alias.ts");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* The source side of an aliased ES import does not enter local scope. A local
+ * function with that spelling remains eligible for exact semantic proof. */
+TEST(repro_typescript_import_source_name_does_not_bind) {
+ static const char source[] = "import { handler as importedHandler } from './external';\n"
+ "function handler(): void {}\n"
+ "function accept(callback: unknown): void {}\n"
+ "export function caller(): void { accept(handler); }\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_TYPESCRIPT, "import_source_role.ts");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* TypeScript import-equals uses import_require_clause rather than the ES
+ * import_clause family. Its leading identifier still owns the module binding. */
+TEST(repro_typescript_import_require_clause_binds_local) {
+ static const char source[] = "import handler = require('./external');\n"
+ "function accept(callback: unknown): void {}\n"
+ "export function caller(): void { accept(handler); }\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_TYPESCRIPT, "import_require.ts");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* Dynamic lexical-scope storage must preserve blockers beyond the historical
+ * 128-entry inline capacity. */
+TEST(repro_javascript_deep_block_nesting_keeps_lexical_binding) {
+ enum { NESTING = 140, SOURCE_CAP = 8192 };
+ char source[SOURCE_CAP];
+ size_t used = (size_t)snprintf(
+ source, sizeof(source),
+ "function handler() {}\nfunction accept(callback) {}\nfunction caller() {\n");
+ for (int i = 0; i < NESTING; i++) {
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "{\n");
+ }
+ used += (size_t)snprintf(source + used, sizeof(source) - used,
+ "let handler = 1;\naccept(handler);\n");
+ for (int i = 0; i < NESTING; i++) {
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "}\n");
+ }
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "}\n");
+ ASSERT_LT(used, sizeof(source));
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_JAVASCRIPT, "deep_blocks.js");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+TEST(repro_typescript_deep_block_nesting_keeps_lexical_binding) {
+ enum { NESTING = 140, SOURCE_CAP = 8192 };
+ char source[SOURCE_CAP];
+ size_t used = (size_t)snprintf(source, sizeof(source),
+ "function handler(): void {}\n"
+ "function accept(callback: unknown): void {}\n"
+ "function caller(): void {\n");
+ for (int i = 0; i < NESTING; i++) {
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "{\n");
+ }
+ used += (size_t)snprintf(source + used, sizeof(source) - used,
+ "let handler = 1;\naccept(handler);\n");
+ for (int i = 0; i < NESTING; i++) {
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "}\n");
+ }
+ used += (size_t)snprintf(source + used, sizeof(source) - used, "}\n");
+ ASSERT_LT(used, sizeof(source));
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_TYPESCRIPT, "deep_blocks.ts");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* Rust block-local use aliases are lexical bindings as well. */
+TEST(repro_rust_block_use_alias_binds_local_scope) {
+ static const char source[] = "fn handler() {}\n"
+ "mod values { pub const remote_value: i32 = 1; }\n"
+ "fn accept<T>(_callback: T) {}\n"
+ "fn caller() {\n"
+ " use crate::values::remote_value as handler;\n"
+ " accept(handler);\n"
+ "}\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "block_use_alias.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* The terminal source segment of a use-as item is not itself introduced into
+ * scope; only the alias is. */
+TEST(repro_rust_use_source_name_does_not_bind) {
+ static const char source[] = "fn handler() {}\n"
+ "use crate::values::handler as imported_handler;\n"
+ "fn accept<T>(_callback: T) {}\n"
+ "fn caller() { accept(handler); }\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "use_source_role.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* extern-crate aliases put name/alias directly on the import boundary. The
+ * alias binds, while the source crate spelling remains available to a distinct
+ * same-named item. */
+TEST(repro_rust_extern_crate_alias_binds_only_alias) {
+ static const char source[] = "extern crate dependency as handler;\n"
+ "fn dependency() {}\n"
+ "fn accept<T>(_callback: T) {}\n"
+ "fn accept_dependency<T>(_callback: T) {}\n"
+ "fn caller() {\n"
+ " accept(handler);\n"
+ " accept_dependency(dependency);\n"
+ "}\n";
+
+ uint32_t alias_site = lb_identifier_offset(source, "accept(handler)", "handler");
+ uint32_t source_site = lb_identifier_offset(source, "dependency);", "dependency");
+ ASSERT_NEQ(alias_site, UINT32_MAX);
+ ASSERT_NEQ(source_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "extern_alias.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite alias = lb_binding_site(result, "caller", "handler", alias_site);
+ LBBindingSite original = lb_binding_site(result, "caller", "dependency", source_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(alias.count, 1);
+ ASSERT_EQ(alias.blocked_count, 1);
+ ASSERT_EQ(alias.local_shadow_count, 0);
+ ASSERT_EQ(original.count, 1);
+ ASSERT_EQ(original.candidate_count, 1);
+ ASSERT_EQ(original.blocked_count, 0);
+ PASS();
+}
+
+/* A direct self entry imports the prefix module under its terminal segment. */
+TEST(repro_rust_brace_self_binds_prefix) {
+ static const char source[] = "mod values {}\n"
+ "use crate::values::{self};\n"
+ "fn accept<T>(_callback: T) {}\n"
+ "fn caller() { accept(values); }\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(values)", "values");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "brace_self.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "values", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* Rust use declarations are items, so their bindings cover the complete
+ * containing block even when the textual declaration appears later. */
+TEST(repro_rust_use_item_binds_before_declaration) {
+ static const char source[] = "fn accept<T>(_callback: T) {}\n"
+ "fn caller() {\n"
+ " accept(handler);\n"
+ " use crate::values::remote as handler;\n"
+ "}\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "use_before_declaration.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* An inline module owns a distinct import namespace. Its alias blocks inside
+ * that module but must not leak to a sibling function in the file root. */
+TEST(repro_rust_inline_module_import_does_not_leak) {
+ static const char source[] = "fn handler() {}\n"
+ "fn accept<T>(_callback: T) {}\n"
+ "mod inner {\n"
+ " use crate::values::remote as handler;\n"
+ " fn inside() { accept(handler); }\n"
+ "}\n"
+ "fn outside() { accept(handler); }\n";
+
+ uint32_t inside_site = lb_identifier_offset(source, "accept(handler)", "handler");
+ const char *outside_marker = strstr(source, "fn outside()");
+ uint32_t outside_site = outside_marker
+ ? lb_identifier_offset(outside_marker, "accept(handler)", "handler")
+ : UINT32_MAX;
+ if (outside_site != UINT32_MAX) {
+ outside_site += (uint32_t)(outside_marker - source);
+ }
+ ASSERT_NEQ(inside_site, UINT32_MAX);
+ ASSERT_NEQ(outside_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_RUST, "inline_module.rs");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite inside = lb_binding_site(result, "inside", "handler", inside_site);
+ LBBindingSite outside = lb_binding_site(result, "outside", "handler", outside_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(inside.count, 1);
+ ASSERT_EQ(inside.blocked_count, 1);
+ ASSERT_EQ(inside.local_shadow_count, 0);
+ ASSERT_EQ(outside.count, 1);
+ ASSERT_EQ(outside.candidate_count, 1);
+ ASSERT_EQ(outside.blocked_count, 0);
+ ASSERT_EQ(outside.local_shadow_count, 0);
+ PASS();
+}
+
+/* ObjectScript SET targets create routine-local values. The later argument is
+ * not a reference to a same-named routine label. */
+TEST(repro_objectscript_set_target_binds_routine_local) {
+ static const char source[] = "Watched()\n"
+ " Quit\n"
+ "Accept(callback)\n"
+ " Quit\n"
+ "Caller()\n"
+ " Set watched=1\n"
+ " Set result=$$Accept(watched)\n"
+ " Quit result\n";
+
+ uint32_t site = lb_identifier_offset(source, "$$Accept(watched)", "watched");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_OBJECTSCRIPT_ROUTINE, "Binding.mac");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "Caller", "watched", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+TEST(repro_objectscript_udl_set_target_binds_method_local) {
+ static const char source[] = "Class Binding.Sample Extends %RegisteredObject\n"
+ "{\n"
+ "ClassMethod Watched() { Quit }\n"
+ "ClassMethod Accept(callback) { Quit }\n"
+ "ClassMethod Caller()\n"
+ "{\n"
+ " Set watched=1\n"
+ " Set result=..Accept(watched)\n"
+ " Quit result\n"
+ "}\n"
+ "}\n";
+
+ uint32_t site = lb_identifier_offset(source, "..Accept(watched)", "watched");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_OBJECTSCRIPT_UDL, "Binding.cls");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "Caller", "watched", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 1);
+ PASS();
+}
+
+/* Python evaluates a default expression in the enclosing namespace before the
+ * new function's parameter scope exists. `handler=handler` therefore reads the
+ * module function on the right, not the parameter being declared on the left. */
+TEST(repro_python_default_expression_uses_enclosing_namespace) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def outer():\n"
+ " def nested(handler=handler):\n"
+ " return handler\n"
+ " return nested\n";
+
+ uint32_t site = lb_identifier_offset(source, "=handler", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "default_scope.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "nested", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.value_count, 1);
+ ASSERT_EQ(usage.blocked_count, 0);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A global directive changes binding ownership. The reassignment blocks an
+ * unproven callable fallback, but its owner is the module rather than caller's
+ * local function scope. */
+TEST(repro_python_global_assignment_is_module_binding) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def replacement():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " global handler\n"
+ " handler = replacement\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "global_scope.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* Module assignments participate in name lookup too. A later function must
+ * not raw-name-fallback through a module variable to an older same-named
+ * callable declaration. */
+TEST(repro_python_module_assignment_blocks_callable_fallback) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "handler = 1\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " accept(handler)\n";
+
+ uint32_t site = lb_identifier_offset(source, "accept(handler)", "handler");
+ ASSERT_NEQ(site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_PYTHON, "module_binding.py");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite usage = lb_binding_site(result, "caller", "handler", site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(usage.count, 1);
+ ASSERT_EQ(usage.candidate_count, 1);
+ ASSERT_EQ(usage.blocked_count, 1);
+ ASSERT_EQ(usage.local_shadow_count, 0);
+ PASS();
+}
+
+/* A function literal owns its parameters independently. The literal's
+ * `handler` must block inside the closure but disappear after the closure. */
+TEST(repro_go_function_literal_parameter_does_not_leak) {
+ static const char source[] = "package sample\n"
+ "func handler() {}\n"
+ "func acceptInside(value interface{}) {}\n"
+ "func acceptOutside(value interface{}) {}\n"
+ "func caller() {\n"
+ " callback := func(handler int) { acceptInside(handler) }\n"
+ " _ = callback\n"
+ " acceptOutside(handler)\n"
+ "}\n";
+
+ uint32_t inside_site = lb_identifier_offset(source, "acceptInside(handler)", "handler");
+ uint32_t outside_site = lb_identifier_offset(source, "acceptOutside(handler)", "handler");
+ ASSERT_NEQ(inside_site, UINT32_MAX);
+ ASSERT_NEQ(outside_site, UINT32_MAX);
+ CBMFileResult *result = lb_extract(source, CBM_LANG_GO, "literal.go");
+ ASSERT_NOT_NULL(result);
+ ASSERT_FALSE(result->has_error || result->parse_incomplete);
+ LBBindingSite inside = lb_binding_site(result, "caller", "handler", inside_site);
+ LBBindingSite outside = lb_binding_site(result, "caller", "handler", outside_site);
+ cbm_free_result(result);
+
+ ASSERT_EQ(inside.count, 1);
+ ASSERT_EQ(inside.blocked_count, 1);
+ ASSERT_EQ(inside.local_shadow_count, 1);
+ ASSERT_EQ(outside.count, 1);
+ ASSERT_EQ(outside.candidate_count, 1);
+ ASSERT_EQ(outside.blocked_count, 0);
+ ASSERT_EQ(outside.local_shadow_count, 0);
+ PASS();
+}
+
+SUITE(repro_lexical_binding_precision) {
+ RUN_TEST(repro_python_keyword_label_does_not_bind_local);
+ RUN_TEST(repro_python_function_name_does_not_shadow_itself);
+ RUN_TEST(repro_python_nested_function_binds_in_enclosing_function);
+ RUN_TEST(repro_python_assignment_blocks_earlier_use_for_whole_function);
+ RUN_TEST(repro_javascript_block_local_stops_at_block_exit);
+ RUN_TEST(repro_csharp_overload_bodies_do_not_share_parameter_bindings);
+ RUN_TEST(repro_powershell_parameter_shadow_is_case_insensitive);
+ RUN_TEST(repro_python_local_class_binding_stops_at_class_namespace);
+ RUN_TEST(repro_python_method_lookup_bypasses_class_namespace);
+ RUN_TEST(repro_python_method_default_uses_class_namespace);
+ RUN_TEST(repro_python_local_import_alias_binds_whole_function);
+ RUN_TEST(repro_python_local_from_import_alias_binds_whole_function);
+ RUN_TEST(repro_python_import_source_roles_do_not_bind);
+ RUN_TEST(repro_python_future_import_is_not_binding_or_usage);
+ RUN_TEST(repro_python_dotted_import_records_root_local_name);
+ RUN_TEST(repro_typescript_import_alias_blocks_raw_callable_fallback);
+ RUN_TEST(repro_typescript_import_source_name_does_not_bind);
+ RUN_TEST(repro_typescript_import_require_clause_binds_local);
+ RUN_TEST(repro_javascript_deep_block_nesting_keeps_lexical_binding);
+ RUN_TEST(repro_typescript_deep_block_nesting_keeps_lexical_binding);
+ RUN_TEST(repro_rust_block_use_alias_binds_local_scope);
+ RUN_TEST(repro_rust_use_source_name_does_not_bind);
+ RUN_TEST(repro_rust_extern_crate_alias_binds_only_alias);
+ RUN_TEST(repro_rust_brace_self_binds_prefix);
+ RUN_TEST(repro_rust_use_item_binds_before_declaration);
+ RUN_TEST(repro_rust_inline_module_import_does_not_leak);
+ RUN_TEST(repro_objectscript_set_target_binds_routine_local);
+ RUN_TEST(repro_objectscript_udl_set_target_binds_method_local);
+ RUN_TEST(repro_python_default_expression_uses_enclosing_namespace);
+ RUN_TEST(repro_python_global_assignment_is_module_binding);
+ RUN_TEST(repro_python_module_assignment_blocks_callable_fallback);
+ RUN_TEST(repro_go_function_literal_parameter_does_not_leak);
+}
diff --git a/tests/repro/repro_lsp_java_cs.c b/tests/repro/repro_lsp_java_cs.c
index fed8a6121..dbcf1bcee 100644
--- a/tests/repro/repro_lsp_java_cs.c
+++ b/tests/repro/repro_lsp_java_cs.c
@@ -57,9 +57,8 @@
* lsp_static_call (1904) ClassName.staticMethod()
* lsp_interface_resolve (1985) iface-typed call, SOLE concrete impl
* lsp_interface_dispatch (1990) iface-typed call, no sole impl
- * lsp_method_ref_ctor (2591) ClassName::new, ctor indexed
- * lsp_method_ref_ctor_synth(2594) ClassName::new, ctor NOT in registry
- * lsp_method_ref (2614) Type::instanceMethod reference
+ * lsp_method_ref_ctor (2758) ClassName::new, ctor indexed
+ * lsp_method_ref (2783) Type::instanceMethod reference
* lsp_constructor (2787) new Foo(), ctor indexed
* lsp_constructor_synth (2792) new Foo(), ctor NOT in registry
* lsp_unresolved (1801) fallback marker for an unresolved call
@@ -153,6 +152,63 @@ static int assert_lsp_strategy(const char *filename, const char *src,
return rc;
}
+static int count_edges_from_callable(cbm_store_t *store, const char *project, const char *edge_type,
+ const char *callable_name) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, project, edge_type, &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ return 0;
+ }
+
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ if (cbm_store_find_node_by_id(store, edges[i].source_id, &source) == CBM_STORE_OK &&
+ source.name && strcmp(source.name, callable_name) == 0 && source.label &&
+ (strcmp(source.label, "Function") == 0 || strcmp(source.label, "Method") == 0)) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return matches;
+}
+
+static int assert_method_reference_semantics(const char *filename, const char *src,
+ int target_is_materialized) {
+ RProj project;
+ cbm_store_t *store = rh_index(&project, filename, src);
+ if (!store) {
+ printf(" %sFAIL%s %s:%d: method-reference fixture failed to index\n", tf_red(), tf_reset(),
+ __FILE__, __LINE__);
+ rh_cleanup(&project, store);
+ return 1;
+ }
+
+ int references = count_edges_from_callable(store, project.project, "CALL_REFERENCE", "run");
+ int calls = count_edges_from_callable(store, project.project, "CALLS", "run");
+ int usages = count_edges_from_callable(store, project.project, "USAGE", "run");
+ int rc = 0;
+ if (references != (target_is_materialized ? 1 : 0)) {
+ printf(" %sFAIL%s %s:%d: method reference count expected=%d actual=%d\n", tf_red(),
+ tf_reset(), __FILE__, __LINE__, target_is_materialized ? 1 : 0, references);
+ rc = 1;
+ }
+ if (calls != 0) {
+ printf(" %sFAIL%s %s:%d: method reference fabricated %d CALLS edges\n", tf_red(),
+ tf_reset(), __FILE__, __LINE__, calls);
+ rc = 1;
+ }
+ if (!target_is_materialized && usages < 1) {
+ printf(" %sFAIL%s %s:%d: unmaterialized constructor reference lost its USAGE\n", tf_red(),
+ tf_reset(), __FILE__, __LINE__);
+ rc = 1;
+ }
+ rh_cleanup(&project, store);
+ return rc;
+}
+
/*
* assert_no_resolvable_edge — the ACCURATE invariant for a call whose callee is
* genuinely UNRESOLVABLE: undeclared (totallyUnknownFn), an external symbol
@@ -336,9 +392,8 @@ static const char kJavaMethodRefCtor[] =
" Maker run() { return Foo::new; }\n"
"}\n";
-/* lsp_method_ref_ctor_synth — a constructor reference ClassName::new whose ctor
- * is NOT in the registry, so the resolver synthesizes the ctor QN
- * (java_lsp.c:2592-2594). Foo declares no explicit constructor. */
+/* A constructor reference ClassName::new whose ctor is NOT materialized. The
+ * reference must remain ordinary USAGE; a class node is not a callable target. */
static const char kJavaMethodRefCtorSynth[] =
"interface Maker {\n"
" Foo make();\n"
@@ -607,17 +662,15 @@ TEST(repro_lsp_java_interface_dispatch) {
}
TEST(repro_lsp_java_method_ref_ctor) {
- return assert_lsp_strategy("Client.java", kJavaMethodRefCtor,
- "lsp_method_ref_ctor");
+ return assert_method_reference_semantics("Client.java", kJavaMethodRefCtor, 1);
}
TEST(repro_lsp_java_method_ref_ctor_synth) {
- return assert_lsp_strategy("Client.java", kJavaMethodRefCtorSynth,
- "lsp_method_ref_ctor_synth");
+ return assert_method_reference_semantics("Client.java", kJavaMethodRefCtorSynth, 0);
}
TEST(repro_lsp_java_method_ref) {
- return assert_lsp_strategy("Client.java", kJavaMethodRef, "lsp_method_ref");
+ return assert_method_reference_semantics("Client.java", kJavaMethodRef, 1);
}
TEST(repro_lsp_java_constructor) {
diff --git a/tests/repro/repro_lsp_kt_php_rust.c b/tests/repro/repro_lsp_kt_php_rust.c
index d51d517c2..883aca874 100644
--- a/tests/repro/repro_lsp_kt_php_rust.c
+++ b/tests/repro/repro_lsp_kt_php_rust.c
@@ -7,7 +7,8 @@
* same two invariants per (lang,strategy) — (a) inv_count_calls_by_source
* module_sourced == 0 and a callable-sourced CALLS edge exists, and (b)
* inv_edge_has_strategy(store, project, "<strategy>"). One TEST per
- * (lang,strategy); SUITE(repro_lsp_kt_php_rust) at the bottom.
+ * (lang,strategy), plus two Rust dispatch-provenance guards;
+ * SUITE(repro_lsp_kt_php_rust) is at the bottom.
*
* WHAT THIS ASSERTS — the LSP RESOLUTION CONTRACT, one invariant per strategy.
* Each hybrid LSP resolves a call via a specific STRATEGY and tags the
@@ -36,16 +37,14 @@
* - RED = the strategy is dropped, lands Module-sourced, or never reaches
* the graph. The TEST documents the exact gap for the fixer.
*
- * RUST CROSS-LSP IS NOT WIRED (documented gap). src/pipeline/pass_lsp_cross.c
- * has NO CBM_LANG_RUST case in either cbm_pxc_has_cross_lsp (lines 282-298)
- * or the cbm_pxc_run_one dispatch (lines 372-407). Go/C/C++/Python/PHP/Java/
- * Kotlin are wired; Rust is absent. So rust_lsp.c can EMIT every strategy
- * below, but those resolved calls never reach pass_lsp_cross → never become
- * tagged CALLS edges in the graph. Every Rust strategy test is therefore
- * expected RED until rust_lsp.c is wired into the pipeline. We assert the
- * CORRECT (resolved) outcome anyway, per the reproduce-first contract: the
- * red test is the durable record of the gap and turns GREEN the moment Rust
- * is wired and resolving correctly.
+ * RUST CROSS-LSP CONTRACT. src/pipeline/pass_lsp_cross.c dispatches
+ * CBM_LANG_RUST through the project-wide Rust registry, including exact
+ * impl-block provenance and independent `impl Trait for Type` relations for
+ * default-only impls. The Rust cases below are intended GREEN regression
+ * guards. Dispatch follows Rust precedence: an inherent method wins over a
+ * same-named trait method; otherwise an exact trait override or unambiguous
+ * trait default may resolve. Missing or conflicting provenance fails closed:
+ * the resolver must not guess a trait or method from a shared leaf name.
*
* SKIPPED STRATEGIES (documented, not tested):
* Kotlin:
@@ -64,14 +63,15 @@
* synthetic module scope (a `mod foo;` declaration has no
* enclosing callable). It would violate invariant (a)
* (module_sourced == 0) by construction, so the shared
- * runner cannot express it. Also blocked by the unwired-
- * Rust gap above.
+ * runner cannot express it.
* - lsp_deref_dispatch / lsp_bound_dispatch / lsp_prelude_trait /
- * lsp_short_name_unique / lsp_trait_ufcs_amb — emitted on harder-to-
- * fixture paths (Deref chains, type-param bounds, prelude best-effort,
- * crate-prefix short-name scan, multi-impl ambiguity). They are all also
- * blocked by the unwired-Rust gap, so adding fragile fixtures for them
- * buys nothing over the representative dispatch tests below; skipped.
+ * lsp_short_name_unique — emitted on harder-to-fixture paths (Deref
+ * chains, type-param bounds, prelude best-effort, crate-prefix short-name
+ * scan). Representative exact-provenance dispatch is covered below;
+ * these specialized strategies remain skipped. Multi-trait ambiguity is
+ * deliberately not a resolved strategy: without exact qualification,
+ * competing trait methods/defaults fail closed instead of emitting a
+ * guessed CALLS edge.
*
* STRATEGY INVENTORIES — every strategy literal grepped from each source:
* Kotlin (kotlin_lsp.c, grep '"lsp_kt_'):
@@ -113,7 +113,7 @@
* lsp_operator_trait (2443) a + b where T : Add (operator overload)
* lsp_macro (3832) known std macro (println!/vec!/panic!)
* lsp_deref_dispatch / lsp_bound_dispatch / lsp_prelude_trait /
- * lsp_short_name_unique / lsp_trait_ufcs_amb / lsp_mod_decl (skipped, see above)
+ * lsp_short_name_unique / lsp_mod_decl (skipped, see above)
* lsp_unresolved (3393) fallback marker
*
* NOTE: line comments only inside this header (no nested block comments, per
@@ -188,6 +188,92 @@ static int assert_lsp_strategy(const char *filename, const char *src,
return rc;
}
+/* Assert required/forbidden strategy provenance on the SAME Rust CALLS edge.
+ * Restricting by caller and callee avoids a false green from an unrelated edge
+ * elsewhere in a multi-file fixture (for example `mod contract;`). */
+static int assert_rust_dispatch_files(const RFile *files, int nfiles, const char *caller_substr,
+ const char *callee_suffix, const char *required_strategy,
+ const char *forbidden_strategy) {
+ RProj lp;
+ cbm_store_t *store = rh_index_files(&lp, files, nfiles);
+ if (!store) {
+ printf(" %sFAIL%s %s:%d: index failed for Rust %s -> %s dispatch\n", tf_red(), tf_reset(),
+ __FILE__, __LINE__, caller_substr, callee_suffix);
+ rh_cleanup(&lp, store);
+ return 1;
+ }
+
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, lp.project, "CALLS", &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ printf(" %sFAIL%s %s:%d: CALLS query failed for Rust %s -> %s dispatch\n", tf_red(),
+ tf_reset(), __FILE__, __LINE__, caller_substr, callee_suffix);
+ rh_cleanup(&lp, store);
+ return 1;
+ }
+
+ int matching_edges = 0;
+ int required_edges = 0;
+ int forbidden_edges = 0;
+ const char *observed_properties = NULL;
+ size_t suffix_len = strlen(callee_suffix);
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source;
+ cbm_node_t target;
+ if (cbm_store_find_node_by_id(store, edges[i].source_id, &source) != CBM_STORE_OK ||
+ cbm_store_find_node_by_id(store, edges[i].target_id, &target) != CBM_STORE_OK) {
+ continue;
+ }
+ const char *source_label = source.label ? source.label : "";
+ if (strcmp(source_label, "Function") != 0 && strcmp(source_label, "Method") != 0) {
+ continue;
+ }
+ if (!source.qualified_name || !strstr(source.qualified_name, caller_substr) ||
+ !target.qualified_name) {
+ continue;
+ }
+ size_t target_len = strlen(target.qualified_name);
+ if (target_len < suffix_len ||
+ strcmp(target.qualified_name + target_len - suffix_len, callee_suffix) != 0) {
+ continue;
+ }
+
+ matching_edges++;
+ const char *properties = edges[i].properties_json ? edges[i].properties_json : "{}";
+ if (!observed_properties) {
+ observed_properties = properties;
+ }
+ if (strstr(properties, required_strategy)) {
+ required_edges++;
+ }
+ if (forbidden_strategy && strstr(properties, forbidden_strategy)) {
+ forbidden_edges++;
+ }
+ }
+
+ int rc = 0;
+ if (matching_edges == 0 || required_edges == 0) {
+ printf(" %sFAIL%s %s:%d: Rust %s -> *%s has %d matching CALLS edges, "
+ "but none with required strategy %s (observed %s)\n",
+ tf_red(), tf_reset(), __FILE__, __LINE__, caller_substr, callee_suffix,
+ matching_edges, required_strategy,
+ observed_properties ? observed_properties : "<none>");
+ rc = 1;
+ }
+ if (forbidden_edges != 0) {
+ printf(" %sFAIL%s %s:%d: Rust %s -> *%s has %d CALLS edges with "
+ "forbidden strategy %s\n",
+ tf_red(), tf_reset(), __FILE__, __LINE__, caller_substr, callee_suffix,
+ forbidden_edges, forbidden_strategy);
+ rc = 1;
+ }
+
+ cbm_store_free_edges(edges, edge_count);
+ rh_cleanup(&lp, store);
+ return rc;
+}
+
/* ════════════════════════════════════════════════════════════════════════════
* KOTLIN FIXTURES (main.kt) — every fixture keeps the call inside a callable
* (a top-level fun or a method) so callable-sourcing is testable, and the
@@ -399,10 +485,9 @@ static const char kPhpSelfStatic[] =
"}\n";
/* ════════════════════════════════════════════════════════════════════════════
- * RUST FIXTURES (main.rs) — Rust cross-LSP is NOT wired into pass_lsp_cross
- * (see header), so ALL of these are expected RED until rust_lsp.c is wired.
- * Each fixture still exercises exactly the keyed construct so the test turns
- * GREEN the moment Rust resolution reaches the graph.
+ * RUST FIXTURES (main.rs) — Rust cross-LSP is wired through pass_lsp_cross.
+ * These are intended GREEN guards for callable attribution, strategy tags,
+ * exact inherent/trait provenance, and default-only cross-file trait impls.
* ═══════════════════════════════════════════════════════════════════════════ */
/* lsp_direct — plain free-function call (rust_lsp.c:3580: path resolves to a
@@ -439,6 +524,35 @@ static const char kRustTraitDispatch[] =
" d.speak(2)\n"
"}\n";
+/* Inherent methods take precedence over same-named trait methods. The shared
+ * Rust registry must preserve that distinction even though both concrete
+ * definitions have receiver S and the type also implements Pinger. */
+static const char kRustInherentTraitCollision[] = "trait Pinger {\n"
+ " fn ping(&self) -> i32;\n"
+ "}\n"
+ "struct S;\n"
+ "impl Pinger for S {\n"
+ " fn ping(&self) -> i32 { 2 }\n"
+ "}\n"
+ "impl S {\n"
+ " fn ping(&self) -> i32 { 1 }\n"
+ "}\n"
+ "fn caller(s: &S) -> i32 { s.ping() }\n";
+
+/* Cross-file default-only trait dispatch. S has no concrete `ping` Method def;
+ * the project-wide registry must therefore carry `impl Pinger for S` itself,
+ * rather than relying on provenance attached to an overriding method. */
+static const RFile kRustDefaultTraitDispatch[] = {
+ {"contract.rs", "pub trait Pinger {\n"
+ " fn ping(&self) -> i32 { 7 }\n"
+ "}\n"
+ "pub struct S;\n"
+ "impl Pinger for S {}\n"},
+ {"main.rs", "mod contract;\n"
+ "use contract::Pinger;\n"
+ "fn caller(s: &contract::S) -> i32 { s.ping() }\n"},
+};
+
/* lsp_constructor — Type::new() UFCS constructor (rust_lsp.c:3607: UFCS head is
* a type, short_name == "new"). */
static const char kRustConstructor[] =
@@ -594,7 +708,7 @@ TEST(repro_lsp_php_self_static) {
return assert_lsp_strategy("main.php", kPhpSelfStatic, "php_self_static");
}
-/* Rust — all expected RED (cross-LSP not wired; see header). */
+/* Rust — intended GREEN, including exact dispatch-provenance guards. */
TEST(repro_lsp_rust_direct) {
return assert_lsp_strategy("main.rs", kRustDirect, "lsp_direct");
}
@@ -606,6 +720,17 @@ TEST(repro_lsp_rust_trait_dispatch) {
return assert_lsp_strategy("main.rs", kRustTraitDispatch,
"lsp_trait_dispatch");
}
+TEST(repro_lsp_rust_inherent_trait_collision) {
+ RFile file = {"main.rs", kRustInherentTraitCollision};
+ return assert_rust_dispatch_files(&file, 1, "caller", ".ping", "lsp_method_dispatch",
+ "lsp_trait_dispatch");
+}
+TEST(repro_lsp_rust_default_trait_dispatch_cross_file) {
+ return assert_rust_dispatch_files(
+ kRustDefaultTraitDispatch,
+ (int)(sizeof(kRustDefaultTraitDispatch) / sizeof(kRustDefaultTraitDispatch[0])), "caller",
+ ".ping", "lsp_trait_dispatch", "lsp_method_dispatch");
+}
TEST(repro_lsp_rust_constructor) {
return assert_lsp_strategy("main.rs", kRustConstructor, "lsp_constructor");
}
@@ -673,10 +798,12 @@ SUITE(repro_lsp_kt_php_rust) {
RUN_TEST(repro_lsp_php_static_resolved);
RUN_TEST(repro_lsp_php_self_static);
- /* Rust — expected RED (cross-LSP not wired). */
+ /* Rust — eight strategy inventories plus two dispatch-provenance guards. */
RUN_TEST(repro_lsp_rust_direct);
RUN_TEST(repro_lsp_rust_method_dispatch);
RUN_TEST(repro_lsp_rust_trait_dispatch);
+ RUN_TEST(repro_lsp_rust_inherent_trait_collision);
+ RUN_TEST(repro_lsp_rust_default_trait_dispatch_cross_file);
RUN_TEST(repro_lsp_rust_constructor);
RUN_TEST(repro_lsp_rust_ufcs);
RUN_TEST(repro_lsp_rust_trait_ufcs);
diff --git a/tests/repro/repro_lsp_ordered_local.c b/tests/repro/repro_lsp_ordered_local.c
new file mode 100644
index 000000000..eeeb8aaa1
--- /dev/null
+++ b/tests/repro/repro_lsp_ordered_local.c
@@ -0,0 +1,400 @@
+/*
+ * repro_lsp_ordered_local.c — Behaviour-level REDs for positional signatures
+ * after a language's local/post-extraction registry refinement.
+ *
+ * These cases deliberately assert a downstream call target, not merely the
+ * extracted metadata. A GREEN transition therefore means the ordered slots
+ * survived far enough to change resolver selection/type inference. Strategy
+ * and target checks prevent a raw unique-name fallback from satisfying the
+ * oracle accidentally.
+ */
+
+#include "test_framework.h"
+
+#include "arena.h"
+#include "cbm.h"
+#include "lsp/java_lsp.h"
+#include "lsp/ts_lsp.h"
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+static bool ends_with(const char *text, const char *suffix) {
+ if (!text || !suffix)
+ return false;
+ size_t text_len = strlen(text);
+ size_t suffix_len = strlen(suffix);
+ return suffix_len <= text_len && strcmp(text + text_len - suffix_len, suffix) == 0;
+}
+
+static void print_resolved_calls(const CBMResolvedCallArray *calls) {
+ if (!calls)
+ return;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ printf(" %s -> %s [%s %.2f kind=%d]\n", call->caller_qn ? call->caller_qn : "(null)",
+ call->callee_qn ? call->callee_qn : "(null)",
+ call->strategy ? call->strategy : "(null)", call->confidence, (int)call->kind);
+ }
+}
+
+static bool has_resolved_suffix(const CBMResolvedCallArray *calls, const char *caller_sub,
+ const char *callee_suffix, const char *strategy) {
+ if (!calls)
+ return false;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ if (call->kind != CBM_RESOLVED_INVOCATION || call->confidence < 0.5f || !call->caller_qn ||
+ !strstr(call->caller_qn, caller_sub) || !ends_with(call->callee_qn, callee_suffix) ||
+ !call->strategy || strcmp(call->strategy, strategy) != 0) {
+ continue;
+ }
+ return true;
+ }
+ return false;
+}
+
+static bool has_resolved_exact(const CBMResolvedCallArray *calls, const char *caller_sub,
+ const char *callee_qn, const char *strategy) {
+ if (!calls)
+ return false;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ if (call->kind == CBM_RESOLVED_INVOCATION && call->confidence >= 0.5f && call->caller_qn &&
+ strstr(call->caller_qn, caller_sub) && call->callee_qn &&
+ strcmp(call->callee_qn, callee_qn) == 0 && call->strategy &&
+ strcmp(call->strategy, strategy) == 0) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static int assert_local_chained_target(CBMLanguage language, const char *rel_path,
+ const char *source, const char *callee_suffix,
+ const char *strategy) {
+ CBMFileResult *result = cbm_extract_file(source, (int)strlen(source), language,
+ "repro_ordered_local", rel_path, 0, NULL, NULL);
+ if (!result) {
+ printf(" ordered-local: extraction returned NULL for %s\n", rel_path);
+ return 1;
+ }
+ if (result->has_error) {
+ printf(" ordered-local: fixture parse failed for %s\n", rel_path);
+ cbm_free_result(result);
+ return 1;
+ }
+
+ bool found = has_resolved_suffix(&result->resolved_calls, "run", callee_suffix, strategy);
+ if (!found) {
+ printf(" ordered-local: missing run -> *%s via %s for %s (have %d)\n", callee_suffix,
+ strategy, rel_path, result->resolved_calls.count);
+ print_resolved_calls(&result->resolved_calls);
+ }
+ cbm_free_result(result);
+ return found ? 0 : 1;
+}
+
+/* Go's legacy type-usage projection stores [T,U] for `(first, second T,
+ * last U)`. Correct implicit inference requires the ordered [T,T,U] carrier,
+ * including preservation through the AST generic-refinement pass. */
+static const char kGoGroupedGeneric[] =
+ "package main\n"
+ "type Left struct{}\n"
+ "type Right struct{}\n"
+ "func (Right) RightOnly() {}\n"
+ "func PickLast[T any, U any](first, second T, last U) U { return last }\n"
+ "func run(left Left, right Right) {\n"
+ " got := PickLast(left, left, right)\n"
+ " got.RightOnly()\n"
+ "}\n";
+
+TEST(repro_lsp_ordered_local_go_grouped_generic) {
+ /* Go method nodes intentionally use a flat `module.Method` graph QN;
+ * receiver ownership is carried separately by receiver_type/parent_class.
+ * Only Right defines RightOnly, and lsp_type_dispatch therefore proves the
+ * positional generic result was inferred as Right. */
+ return assert_local_chained_target(CBM_LANG_GO, "main.go", kGoGroupedGeneric, "RightOnly",
+ "lsp_type_dispatch");
+}
+
+/* A C++ reference return wraps the function declarator in a
+ * reference_declarator. The local signature extractor must still reach the
+ * nested parameter list; otherwise `operator[](int)` collapses to arity zero
+ * and the exact-arity operator resolver correctly refuses it. */
+static const char kCppReferenceReturnOperator[] =
+ "struct Item {};\n"
+ "struct Vec {\n"
+ " Item& operator[](int index) { static Item item; return item; }\n"
+ "};\n"
+ "void run(Vec& values) { values[0]; }\n";
+
+static int assert_reference_return_operator_arity(CBMLanguage language, const char *rel_path,
+ const char *language_name) {
+ CBMFileResult *result =
+ cbm_extract_file(kCppReferenceReturnOperator, (int)strlen(kCppReferenceReturnOperator),
+ language, "repro_ordered_local", rel_path, 0, NULL, NULL);
+ if (!result || result->has_error) {
+ printf(" ordered-local: %s reference-return fixture extraction failed\n", language_name);
+ if (result)
+ cbm_free_result(result);
+ return 1;
+ }
+
+ bool counted_signature = false;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && strcmp(definition->name, "operator[]") == 0 &&
+ definition->signature_param_count == 1 && definition->signature_param_types &&
+ definition->signature_param_types[0] &&
+ strcmp(definition->signature_param_types[0], "int") == 0) {
+ counted_signature = true;
+ break;
+ }
+ }
+ bool resolved =
+ has_resolved_suffix(&result->resolved_calls, "run", "operator[]", "lsp_operator");
+ if (!counted_signature || !resolved) {
+ printf(" ordered-local: %s reference-return operator counted=%d resolved=%d\n",
+ language_name, counted_signature, resolved);
+ print_resolved_calls(&result->resolved_calls);
+ }
+ cbm_free_result(result);
+ return counted_signature && resolved ? 0 : 1;
+}
+
+TEST(repro_lsp_ordered_local_cpp_reference_return_operator_arity) {
+ return assert_reference_return_operator_arity(CBM_LANG_CPP, "main.cpp", "C++");
+}
+
+/* CUDA uses its own vendored grammar. It aliases this syntax to the same
+ * reference_declarator node shape today, but must retain an independent guard
+ * so a future grammar update cannot silently reintroduce the arity collapse. */
+TEST(repro_lsp_ordered_local_cuda_reference_return_operator_arity) {
+ return assert_reference_return_operator_arity(CBM_LANG_CUDA, "main.cu", "CUDA");
+}
+
+/* The shared C-family name resolver permits eight declarator wrappers, but the
+ * parameter walk historically stopped after five. A five-level pointer return
+ * therefore produced a named function whose signature silently had arity zero.
+ * C, C++, and CUDA each get a real grammar guard; GLSL has no pointer syntax. */
+static const char kDeepPointerReturn[] = "int *****deep(int value) { return 0; }\n";
+
+static int assert_deep_pointer_return_arity(CBMLanguage language, const char *rel_path,
+ const char *language_name) {
+ CBMFileResult *result =
+ cbm_extract_file(kDeepPointerReturn, (int)strlen(kDeepPointerReturn), language,
+ "repro_ordered_local", rel_path, 0, NULL, NULL);
+ if (!result || result->has_error) {
+ printf(" ordered-local: %s deep-pointer fixture extraction failed\n", language_name);
+ if (result)
+ cbm_free_result(result);
+ return 1;
+ }
+
+ bool found = false;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && strcmp(definition->name, "deep") == 0 &&
+ definition->signature_param_count == 1 && definition->signature_param_types &&
+ definition->signature_param_types[0] &&
+ strcmp(definition->signature_param_types[0], "int") == 0) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ printf(" ordered-local: %s deep-pointer return lost parameter arity\n", language_name);
+ }
+ cbm_free_result(result);
+ return found ? 0 : 1;
+}
+
+TEST(repro_lsp_ordered_local_c_deep_pointer_return_arity) {
+ return assert_deep_pointer_return_arity(CBM_LANG_C, "main.c", "C");
+}
+
+TEST(repro_lsp_ordered_local_cpp_deep_pointer_return_arity) {
+ return assert_deep_pointer_return_arity(CBM_LANG_CPP, "main.cpp", "C++");
+}
+
+TEST(repro_lsp_ordered_local_cuda_deep_pointer_return_arity) {
+ return assert_deep_pointer_return_arity(CBM_LANG_CUDA, "main.cu", "CUDA");
+}
+
+/* GREEN controls for the local TypeScript AST-rebuild path. The pseudo `this`
+ * parameter is not an argument and is excluded from the ordered carrier. The
+ * AST rebuild also skips it because it is not an identifier pattern, then
+ * reconstructs [T,T,U], so these pass even before ordered-carrier transport is
+ * adopted. They verify post-AST positional behavior, not transport itself. */
+static const char kTsThisGeneric[] =
+ "class Left {}\n"
+ "class Right { rightOnly(): void {} }\n"
+ "function pickLast<T, U>(this: void, first: T, second: T, last: U): U {\n"
+ " return last;\n"
+ "}\n"
+ "function run(left: Left, right: Right): void {\n"
+ " const got = pickLast(left, left, right);\n"
+ " got.rightOnly();\n"
+ "}\n";
+
+TEST(repro_lsp_ordered_local_control_typescript_this_receiver) {
+ return assert_local_chained_target(CBM_LANG_TYPESCRIPT, "main.ts", kTsThisGeneric,
+ "Right.rightOnly", "lsp_ts_method");
+}
+
+TEST(repro_lsp_ordered_local_control_tsx_this_receiver) {
+ return assert_local_chained_target(CBM_LANG_TSX, "main.tsx", kTsThisGeneric, "Right.rightOnly",
+ "lsp_ts_method");
+}
+
+/* Interface method signatures are synthesized by the TS AST shape sweep rather
+ * than supplied as graph defs. Put the same two parameter types in the wrong
+ * order first, then require the reversed two-argument overload plus a non-first
+ * zero-argument overload. Arity alone cannot pass this: the selected edge and
+ * return-chain type must agree on ordered parameter types, and the post-sweep
+ * overloads must remain visible through a finalized registry. */
+static const char kTsInterfaceOverloadReturnChains[] =
+ "interface Reversed { reversedOnly(): void; }\n"
+ "interface Empty { emptyOnly(): void; }\n"
+ "interface Pair { pairOnly(): void; }\n"
+ "interface Factory {\n"
+ " pick(s: string, n: number): Reversed;\n"
+ " pick(): Empty;\n"
+ " pick(n: number, s: string): Pair;\n"
+ "}\n"
+ "function run(f: Factory): void {\n"
+ " f.pick().emptyOnly();\n"
+ " f.pick(1, 'x').pairOnly();\n"
+ "}\n";
+
+static int assert_ts_interface_overload_return_chains(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const char *const type_names[] = {"Reversed", "Empty", "Pair", "Factory"};
+ CBMLSPDef defs[5];
+ memset(defs, 0, sizeof(defs));
+ for (int i = 0; i < 4; i++) {
+ defs[i].qualified_name = type_names[i];
+ defs[i].short_name = type_names[i];
+ defs[i].label = "Interface";
+ defs[i].def_module_qn = "repro.ts";
+ defs[i].is_interface = true;
+ defs[i].lang = language;
+ }
+ defs[0].qualified_name = "repro.ts.Reversed";
+ defs[1].qualified_name = "repro.ts.Empty";
+ defs[2].qualified_name = "repro.ts.Pair";
+ defs[3].qualified_name = "repro.ts.Factory";
+ defs[4].qualified_name = "repro.ts.run";
+ defs[4].short_name = "run";
+ defs[4].label = "Function";
+ defs[4].def_module_qn = "repro.ts";
+ defs[4].return_types = "void";
+ defs[4].lang = language;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, 5);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(
+ &arena, kTsInterfaceOverloadReturnChains, (int)strlen(kTsInterfaceOverloadReturnChains),
+ "repro.ts", false, jsx_mode, false, registry, defs, 5, NULL, NULL, 0, NULL, &calls);
+ }
+
+ bool empty = has_resolved_suffix(&calls, "run", "Empty.emptyOnly", "lsp_ts_method");
+ bool pair = has_resolved_suffix(&calls, "run", "Pair.pairOnly", "lsp_ts_method");
+ if (!registry || !empty || !pair) {
+ printf(" ordered-local: %s interface overload chains empty=%d pair=%d registry=%d\n",
+ language_name, empty, pair, registry != NULL);
+ print_resolved_calls(&calls);
+ }
+ cbm_arena_destroy(&arena);
+ return registry && empty && pair ? 0 : 1;
+}
+
+TEST(repro_lsp_ordered_local_typescript_interface_overload_return_chains) {
+ return assert_ts_interface_overload_return_chains(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_lsp_ordered_local_tsx_interface_overload_return_chains) {
+ return assert_ts_interface_overload_return_chains(CBM_LANG_TSX, true, "TSX");
+}
+
+/* Java overloads normally share one graph QN, which hides which overload won.
+ * The synthetic suffixes below make the registry choice observable while both
+ * entries retain the source-level short name `pick`. With both signatures
+ * collapsed to zero slots, the three-argument call falls back to the first
+ * registration ($zero); materializing its counted carrier must select $three. */
+TEST(repro_lsp_ordered_local_java_overload_arity) {
+ static const char source[] =
+ "package demo;\n"
+ "public class Caller {\n"
+ " public void callZero(demo.Target t) { t.pick(); }\n"
+ " public void callThree(demo.Target t) { t.pick(1, \"x\", true); }\n"
+ "}\n";
+ const char *three_params[] = {"int", "java.lang.String", "boolean", NULL};
+ CBMLSPDef defs[3];
+ memset(defs, 0, sizeof(defs));
+
+ defs[0].qualified_name = "demo.Target";
+ defs[0].short_name = "Target";
+ defs[0].label = "Class";
+ defs[0].def_module_qn = "demo";
+ defs[0].lang = CBM_LANG_JAVA;
+
+ defs[1].qualified_name = "demo.Target.pick$zero";
+ defs[1].short_name = "pick";
+ defs[1].label = "Method";
+ defs[1].receiver_type = "demo.Target";
+ defs[1].def_module_qn = "demo";
+ defs[1].return_types = "void";
+ defs[1].signature_param_types = NULL;
+ defs[1].signature_param_count = 0;
+ defs[1].lang = CBM_LANG_JAVA;
+
+ defs[2].qualified_name = "demo.Target.pick$three";
+ defs[2].short_name = "pick";
+ defs[2].label = "Method";
+ defs[2].receiver_type = "demo.Target";
+ defs[2].def_module_qn = "demo";
+ defs[2].return_types = "void";
+ defs[2].signature_param_types = three_params;
+ defs[2].signature_param_count = 3;
+ defs[2].lang = CBM_LANG_JAVA;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMResolvedCallArray calls = {0};
+ cbm_run_java_lsp_cross(&arena, source, (int)strlen(source), "demo", defs, 3, NULL, NULL, 0,
+ NULL, &calls);
+
+ bool zero =
+ has_resolved_exact(&calls, "callZero", "demo.Target.pick$zero", "lsp_type_dispatch");
+ bool three =
+ has_resolved_exact(&calls, "callThree", "demo.Target.pick$three", "lsp_type_dispatch");
+ bool wrong =
+ has_resolved_exact(&calls, "callThree", "demo.Target.pick$zero", "lsp_type_dispatch");
+ if (!zero || !three || wrong) {
+ printf(" ordered-local: Java overload selection zero=%d three=%d wrong-zero=%d\n", zero,
+ three, wrong);
+ print_resolved_calls(&calls);
+ }
+ cbm_arena_destroy(&arena);
+ return zero && three && !wrong ? 0 : 1;
+}
+
+SUITE(repro_lsp_ordered_local) {
+ RUN_TEST(repro_lsp_ordered_local_go_grouped_generic);
+ RUN_TEST(repro_lsp_ordered_local_cpp_reference_return_operator_arity);
+ RUN_TEST(repro_lsp_ordered_local_cuda_reference_return_operator_arity);
+ RUN_TEST(repro_lsp_ordered_local_c_deep_pointer_return_arity);
+ RUN_TEST(repro_lsp_ordered_local_cpp_deep_pointer_return_arity);
+ RUN_TEST(repro_lsp_ordered_local_cuda_deep_pointer_return_arity);
+ RUN_TEST(repro_lsp_ordered_local_control_typescript_this_receiver);
+ RUN_TEST(repro_lsp_ordered_local_control_tsx_this_receiver);
+ RUN_TEST(repro_lsp_ordered_local_typescript_interface_overload_return_chains);
+ RUN_TEST(repro_lsp_ordered_local_tsx_interface_overload_return_chains);
+ RUN_TEST(repro_lsp_ordered_local_java_overload_arity);
+}
diff --git a/tests/repro/repro_lsp_ordered_signatures.c b/tests/repro/repro_lsp_ordered_signatures.c
new file mode 100644
index 000000000..88086f61c
--- /dev/null
+++ b/tests/repro/repro_lsp_ordered_signatures.c
@@ -0,0 +1,980 @@
+/*
+ * repro_lsp_ordered_signatures.c — Counted positional signature transport into
+ * the project-wide LSP registries.
+ *
+ * The public CBMDefinition.param_types array is a legacy type-usage projection:
+ * it is not positional. Cross-LSP registration instead receives the internal
+ * CBMLSPDef.signature_param_types + signature_param_count carrier. These tests
+ * start at the production registry-population boundary so a GREEN result means
+ * the registry consumer, not merely extraction, retained every argument slot.
+ *
+ * Contracts exercised per typed language:
+ * - non-palindromic [integer, UNKNOWN, string] catches reordering;
+ * - [integer, integer] catches accidental deduplication;
+ * - [integer, string, UNKNOWN] catches NULL-termination at an unknown slot;
+ * - only the exact text "?" means UNKNOWN; a language-valid nullable type is
+ * still a real, non-UNKNOWN type;
+ * - signature_param_count is authoritative. The non-palindromic carrier has
+ * a fourth, out-of-count bool entry which must not be scanned or merged, and
+ * a non-NULL carrier with count zero must materialize zero parameters.
+ *
+ * JavaScript has no source annotations in its primary carrier, so its contract
+ * is three explicit UNKNOWN slots (rather than silently collapsing to zero).
+ * Every listed frontend now consumes the counted carrier. These cases are
+ * permanent gating guards against reordering, deduplication, or truncation.
+ */
+
+#include "test_framework.h"
+
+#include "arena.h"
+#include "cbm.h"
+#include "lang_specs.h"
+#include "lsp/c_lsp.h"
+#include "lsp/cs_lsp.h"
+#include "lsp/go_lsp.h"
+#include "lsp/java_lsp.h"
+#include "lsp/kotlin_lsp.h"
+#include "lsp/php_lsp.h"
+#include "lsp/py_lsp.h"
+#include "lsp/rust_lsp.h"
+#include "lsp/ts_lsp.h"
+#include "lsp/type_registry.h"
+#include "lsp/type_rep.h"
+#include "tree_sitter/api.h"
+
+#include <string.h>
+
+typedef CBMTypeRegistry *(*CrossRegistryBuilder)(CBMArena *, CBMLSPDef *, int);
+
+typedef struct {
+ const char *tag;
+ CBMLanguage lang;
+ CrossRegistryBuilder build;
+ const char *integer_text;
+ const char *string_text;
+ const char *nullable_text;
+ const char *return_text;
+} OrderedSignatureLanguage;
+
+static TSTree *parse_lsp_fixture(CBMLanguage language, const char *source) {
+ const TSLanguage *grammar = cbm_ts_language(language);
+ TSParser *parser = ts_parser_new();
+ if (!grammar || !parser || !ts_parser_set_language(parser, grammar)) {
+ if (parser)
+ ts_parser_delete(parser);
+ return NULL;
+ }
+ TSTree *tree = ts_parser_parse_string(parser, NULL, source, (uint32_t)strlen(source));
+ ts_parser_delete(parser);
+ return tree;
+}
+
+static TSNode find_first_lsp_node_of_kind(TSNode node, const char *kind) {
+ if (strcmp(ts_node_type(node), kind) == 0)
+ return node;
+
+ uint32_t child_count = ts_node_child_count(node);
+ for (uint32_t i = 0; i < child_count; i++) {
+ TSNode found = find_first_lsp_node_of_kind(ts_node_child(node, i), kind);
+ if (!ts_node_is_null(found))
+ return found;
+ }
+
+ TSNode missing = {0};
+ return missing;
+}
+
+static CBMTypeRegistry *alloc_test_registry(CBMArena *arena) {
+ CBMTypeRegistry *registry = (CBMTypeRegistry *)cbm_arena_alloc(arena, sizeof(*registry));
+ if (!registry)
+ return NULL;
+ cbm_registry_init(registry, arena);
+ return registry;
+}
+
+static CBMTypeRegistry *build_java_cross_registry_for_contract(CBMArena *arena, CBMLSPDef *defs,
+ int def_count) {
+ CBMTypeRegistry *registry = alloc_test_registry(arena);
+ if (registry)
+ cbm_java_register_lsp_defs(arena, registry, defs, def_count);
+ return registry;
+}
+
+static CBMTypeRegistry *build_kotlin_cross_registry_for_contract(CBMArena *arena, CBMLSPDef *defs,
+ int def_count) {
+ CBMTypeRegistry *registry = alloc_test_registry(arena);
+ if (registry)
+ cbm_kotlin_register_lsp_defs(arena, registry, defs, def_count);
+ return registry;
+}
+
+static CBMTypeRegistry *build_php_cross_registry_for_contract(CBMArena *arena, CBMLSPDef *defs,
+ int def_count) {
+ CBMTypeRegistry *registry = alloc_test_registry(arena);
+ if (registry)
+ cbm_php_register_lsp_defs(arena, NULL, registry, defs, def_count);
+ return registry;
+}
+
+static int func_param_count(const CBMType *signature) {
+ if (!signature || signature->kind != CBM_TYPE_FUNC || !signature->data.func.param_types)
+ return 0;
+ int count = 0;
+ while (signature->data.func.param_types[count])
+ count++;
+ return count;
+}
+
+static const char *last_type_component(const char *name) {
+ if (!name)
+ return NULL;
+ const char *leaf = name;
+ for (const char *cursor = name; *cursor; cursor++) {
+ if (*cursor == '.' || *cursor == ':')
+ leaf = cursor + 1;
+ }
+ return leaf;
+}
+
+static const char *type_atom_name(const CBMType *type) {
+ if (!type)
+ return NULL;
+ switch (type->kind) {
+ case CBM_TYPE_BUILTIN:
+ return type->data.builtin.name;
+ case CBM_TYPE_NAMED:
+ return type->data.named.qualified_name;
+ case CBM_TYPE_TYPE_PARAM:
+ return type->data.type_param.name;
+ case CBM_TYPE_TEMPLATE:
+ return type->data.template_type.template_name;
+ case CBM_TYPE_ALIAS:
+ return type->data.alias.alias_qn;
+ default:
+ return NULL;
+ }
+}
+
+static int param_matches(const CBMType *actual, const char *expected) {
+ if (strcmp(expected, "?") == 0)
+ return cbm_type_is_unknown(actual);
+ if (!actual || cbm_type_is_unknown(actual))
+ return 0;
+ const char *name = type_atom_name(actual);
+ const char *leaf = last_type_component(name);
+ return leaf && strcmp(leaf, expected) == 0;
+}
+
+static int check_signature(const CBMTypeRegistry *registry, const char *qualified_name,
+ const char *case_name, const char *const *expected, int expected_count) {
+ const CBMRegisteredFunc *func = cbm_registry_lookup_func(registry, qualified_name);
+ if (!func) {
+ fprintf(stderr, " [ordered-signature] case=%s missing function=%s\n", case_name,
+ qualified_name);
+ return 1;
+ }
+ if (!func->signature || func->signature->kind != CBM_TYPE_FUNC) {
+ fprintf(stderr, " [ordered-signature] case=%s function=%s has no FUNC signature\n",
+ case_name, qualified_name);
+ return 1;
+ }
+
+ int actual_count = func_param_count(func->signature);
+ if (actual_count != expected_count) {
+ fprintf(stderr,
+ " [ordered-signature] case=%s function=%s expected-count=%d actual-count=%d\n",
+ case_name, qualified_name, expected_count, actual_count);
+ return 1;
+ }
+
+ for (int i = 0; i < expected_count; i++) {
+ const CBMType *actual = func->signature->data.func.param_types[i];
+ if (!param_matches(actual, expected[i])) {
+ const char *actual_name = type_atom_name(actual);
+ fprintf(stderr,
+ " [ordered-signature] case=%s function=%s slot=%d expected=%s "
+ "actual=%s kind=%d\n",
+ case_name, qualified_name, i, expected[i],
+ actual_name ? actual_name
+ : (cbm_type_is_unknown(actual) ? "?" : "<structured>"),
+ actual ? (int)actual->kind : -1);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static int check_single_return(const CBMTypeRegistry *registry, const char *qualified_name,
+ const char *case_name, const char *expected) {
+ const CBMRegisteredFunc *func = cbm_registry_lookup_func(registry, qualified_name);
+ if (!func || !func->signature || func->signature->kind != CBM_TYPE_FUNC ||
+ !func->signature->data.func.return_types || !func->signature->data.func.return_types[0]) {
+ fprintf(stderr, " [ordered-signature] case=%s function=%s missing return type\n",
+ case_name, qualified_name);
+ return 1;
+ }
+ const CBMType *actual = func->signature->data.func.return_types[0];
+ if (!param_matches(actual, expected)) {
+ const char *actual_name = type_atom_name(actual);
+ fprintf(stderr,
+ " [ordered-signature] case=%s function=%s expected-return=%s actual=%s kind=%d\n",
+ case_name, qualified_name, expected,
+ actual_name ? actual_name : (cbm_type_is_unknown(actual) ? "?" : "<structured>"),
+ (int)actual->kind);
+ return 1;
+ }
+ return 0;
+}
+
+static int check_nullable_signature(const CBMTypeRegistry *registry, const char *qualified_name,
+ const char *case_name) {
+ const CBMRegisteredFunc *func = cbm_registry_lookup_func(registry, qualified_name);
+ if (!func || !func->signature || func->signature->kind != CBM_TYPE_FUNC) {
+ fprintf(stderr, " [ordered-signature] case=%s missing FUNC signature=%s\n", case_name,
+ qualified_name);
+ return 1;
+ }
+ int actual_count = func_param_count(func->signature);
+ if (actual_count != 1) {
+ fprintf(stderr,
+ " [ordered-signature] case=%s function=%s expected-count=1 actual-count=%d\n",
+ case_name, qualified_name, actual_count);
+ return 1;
+ }
+ if (cbm_type_is_unknown(func->signature->data.func.param_types[0])) {
+ fprintf(stderr,
+ " [ordered-signature] case=%s function=%s nullable type collapsed to UNKNOWN\n",
+ case_name, qualified_name);
+ return 1;
+ }
+ return 0;
+}
+
+static void init_function_def(CBMLSPDef *def, CBMArena *arena,
+ const OrderedSignatureLanguage *language, const char *case_name,
+ const char **param_types, int param_count) {
+ memset(def, 0, sizeof(*def));
+ def->qualified_name = cbm_arena_sprintf(arena, "cbm.ordered.%s.%s", language->tag, case_name);
+ def->short_name = case_name;
+ def->label = "Function";
+ def->def_module_qn = cbm_arena_sprintf(arena, "cbm.ordered.%s", language->tag);
+ def->return_types = language->return_text;
+ def->signature_param_types = param_types;
+ def->signature_param_count = param_count;
+ def->lang = language->lang;
+}
+
+static int run_typed_language_contract(const OrderedSignatureLanguage *language) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+
+ /* The out-of-count bool is deliberate: count=3, so it must never surface. */
+ const char *nonpal_carrier[] = {language->integer_text, "?", language->string_text, "bool",
+ NULL};
+ const char *duplicate_carrier[] = {language->integer_text, language->integer_text, NULL};
+ const char *trailing_carrier[] = {language->integer_text, language->string_text, "?", NULL};
+ const char *nullable_carrier[] = {language->nullable_text, NULL};
+ /* A stale pointer with authoritative count zero must not be scanned. */
+ const char *count_zero_carrier[] = {language->integer_text, language->string_text, NULL};
+
+ CBMLSPDef defs[5];
+ init_function_def(&defs[0], &arena, language, "nonpal", nonpal_carrier, 3);
+ init_function_def(&defs[1], &arena, language, "duplicate", duplicate_carrier, 2);
+ init_function_def(&defs[2], &arena, language, "trailing_unknown", trailing_carrier, 3);
+ init_function_def(&defs[3], &arena, language, "nullable", nullable_carrier, 1);
+ init_function_def(&defs[4], &arena, language, "count_zero", count_zero_carrier, 0);
+
+ CBMTypeRegistry *registry = language->build(&arena, defs, 5);
+ if (!registry) {
+ fprintf(stderr, " [ordered-signature] lang=%s registry build failed\n", language->tag);
+ cbm_arena_destroy(&arena);
+ return 1;
+ }
+
+ /* C# deliberately canonicalizes source aliases in its semantic registry.
+ * Keep feeding valid source spellings (`int`, `string`) while checking the
+ * canonical leaf names, rather than weakening production parsing to satisfy
+ * a spelling-only assertion. */
+ const bool csharp_canonical = strcmp(language->tag, "csharp") == 0;
+ const char *integer_expected = csharp_canonical ? "Int32" : language->integer_text;
+ const char *string_expected = csharp_canonical ? "String" : language->string_text;
+ const char *nonpal_expected[] = {integer_expected, "?", string_expected};
+ const char *duplicate_expected[] = {integer_expected, integer_expected};
+ const char *trailing_expected[] = {integer_expected, string_expected, "?"};
+ int failures = 0;
+ failures += check_signature(registry, defs[0].qualified_name, "nonpal", nonpal_expected, 3);
+ failures +=
+ check_signature(registry, defs[1].qualified_name, "duplicate", duplicate_expected, 2);
+ failures +=
+ check_signature(registry, defs[2].qualified_name, "trailing_unknown", trailing_expected, 3);
+ failures += check_nullable_signature(registry, defs[3].qualified_name, "nullable");
+ failures += check_signature(registry, defs[4].qualified_name, "count_zero", NULL, 0);
+
+ cbm_arena_destroy(&arena);
+ return failures;
+}
+
+static int run_javascript_unknown_contract(const OrderedSignatureLanguage *language) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+
+ const char *unknown_carrier[] = {"?", "?", "?", "number", NULL};
+ const char *count_zero_carrier[] = {"number", NULL};
+ CBMLSPDef defs[2];
+ init_function_def(&defs[0], &arena, language, "three_unknowns", unknown_carrier, 3);
+ init_function_def(&defs[1], &arena, language, "count_zero", count_zero_carrier, 0);
+
+ CBMTypeRegistry *registry = language->build(&arena, defs, 2);
+ if (!registry) {
+ fprintf(stderr, " [ordered-signature] lang=%s registry build failed\n", language->tag);
+ cbm_arena_destroy(&arena);
+ return 1;
+ }
+
+ const char *expected[] = {"?", "?", "?"};
+ int failures = check_signature(registry, defs[0].qualified_name, "three_unknowns", expected, 3);
+ failures += check_signature(registry, defs[1].qualified_name, "count_zero", NULL, 0);
+ cbm_arena_destroy(&arena);
+ return failures;
+}
+
+static const OrderedSignatureLanguage C_LANGUAGE = {
+ "c", CBM_LANG_C, cbm_c_build_cross_registry, "int", "string", "Thing *", "void"};
+static const OrderedSignatureLanguage CPP_LANGUAGE = {
+ "cpp", CBM_LANG_CPP, cbm_c_build_cross_registry, "int", "string", "std::optional<Thing>",
+ "void"};
+static const OrderedSignatureLanguage CUDA_LANGUAGE = {
+ "cuda", CBM_LANG_CUDA, cbm_c_build_cross_registry, "int", "string", "Thing *", "void"};
+static const OrderedSignatureLanguage GO_LANGUAGE = {
+ "go", CBM_LANG_GO, cbm_go_build_cross_registry, "int", "string", "*Thing", "void"};
+static const OrderedSignatureLanguage JS_LANGUAGE = {
+ "javascript", CBM_LANG_JAVASCRIPT, cbm_ts_build_cross_registry, NULL, NULL, NULL, "void"};
+static const OrderedSignatureLanguage TS_LANGUAGE = {"typescript",
+ CBM_LANG_TYPESCRIPT,
+ cbm_ts_build_cross_registry,
+ "number",
+ "string",
+ "Thing | null",
+ "void"};
+static const OrderedSignatureLanguage TSX_LANGUAGE = {
+ "tsx", CBM_LANG_TSX, cbm_ts_build_cross_registry, "number", "string", "Thing | null", "void"};
+static const OrderedSignatureLanguage PYTHON_LANGUAGE = {
+ "python", CBM_LANG_PYTHON, cbm_py_build_cross_registry, "int", "str", "Thing | None", "None"};
+static const OrderedSignatureLanguage CSHARP_LANGUAGE = {
+ "csharp", CBM_LANG_CSHARP, cbm_cs_build_cross_registry, "int", "string", "Thing?", "void"};
+static const OrderedSignatureLanguage RUST_LANGUAGE = {
+ "rust", CBM_LANG_RUST, cbm_rust_build_cross_registry, "i32", "String", "Option<Thing>", "()"};
+static const OrderedSignatureLanguage JAVA_LANGUAGE = {
+ "java", CBM_LANG_JAVA, build_java_cross_registry_for_contract,
+ "int", "String", "java.util.List<?>",
+ "void"};
+static const OrderedSignatureLanguage KOTLIN_LANGUAGE = {
+ "kotlin", CBM_LANG_KOTLIN, build_kotlin_cross_registry_for_contract, "Int", "String",
+ "Thing?", "Unit"};
+static const OrderedSignatureLanguage PHP_LANGUAGE = {
+ "php", CBM_LANG_PHP, build_php_cross_registry_for_contract, "int", "string", "?Thing", "void"};
+
+static void add_fixture_type(CBMTypeRegistry *registry, const char *qualified_name,
+ const char *short_name) {
+ CBMRegisteredType type = {0};
+ type.qualified_name = qualified_name;
+ type.short_name = short_name;
+ cbm_registry_add_type(registry, type);
+}
+
+static void add_php_seeded_method(CBMArena *arena, CBMTypeRegistry *registry,
+ const char *qualified_name, const char *short_name,
+ const char *receiver_type, const char *thing_qn,
+ const CBMType *return_type) {
+ const char *param_names[] = {"first", "middle", "last", NULL};
+ const CBMType *param_types[] = {cbm_type_builtin(arena, "int"), cbm_type_named(arena, thing_qn),
+ cbm_type_builtin(arena, "int"), NULL};
+ const CBMType *return_types[] = {return_type, NULL};
+ CBMRegisteredFunc function = {0};
+ function.qualified_name = qualified_name;
+ function.short_name = short_name;
+ function.receiver_type = receiver_type;
+ function.min_params = 3;
+ function.signature = cbm_type_func(arena, param_names, param_types, return_types);
+ cbm_registry_add_func(registry, function);
+}
+
+static void add_csharp_seeded_method(CBMArena *arena, CBMTypeRegistry *registry,
+ const char *qualified_name, const char *short_name,
+ const char *receiver_type, const char *thing_qn) {
+ const CBMType *param_types[] = {cbm_type_builtin(arena, "int"), cbm_type_named(arena, thing_qn),
+ cbm_type_builtin(arena, "int"), NULL};
+ const CBMType *return_types[] = {cbm_type_unknown(), NULL};
+ CBMRegisteredFunc function = {0};
+ function.qualified_name = qualified_name;
+ function.short_name = short_name;
+ function.receiver_type = receiver_type;
+ function.min_params = 3;
+ function.signature = cbm_type_func(arena, NULL, param_types, return_types);
+ cbm_registry_add_func(registry, function);
+}
+
+typedef struct {
+ int call_count;
+ const char *seen[8];
+} SignatureParserProbe;
+
+static const CBMType *parse_signature_probe_type(CBMArena *arena, const char *text,
+ void *parser_ctx) {
+ SignatureParserProbe *probe = (SignatureParserProbe *)parser_ctx;
+ probe->seen[probe->call_count++] = text;
+ if (strcmp(text, "parser-null") == 0)
+ return NULL;
+ return cbm_type_builtin(arena, text);
+}
+
+TEST(repro_lsp_signature_param_materializer_contract) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+
+ SignatureParserProbe probe = {0};
+ const char *ordered_texts[] = {"int", "?", "string", "outside-count"};
+ const CBMType **ordered = cbm_type_materialize_signature_params(
+ &arena, ordered_texts, 3, parse_signature_probe_type, &probe);
+ ASSERT_NOT_NULL(ordered);
+ ASSERT_EQ(probe.call_count, 2);
+ ASSERT_STR_EQ(probe.seen[0], "int");
+ ASSERT_STR_EQ(probe.seen[1], "string");
+ ASSERT_EQ(ordered[0]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(ordered[0]->data.builtin.name, "int");
+ ASSERT_TRUE(cbm_type_is_unknown(ordered[1]));
+ ASSERT_EQ(ordered[2]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(ordered[2]->data.builtin.name, "string");
+ ASSERT_NULL(ordered[3]);
+
+ memset(&probe, 0, sizeof(probe));
+ const char *duplicate_texts[] = {"int", "int"};
+ const CBMType **duplicates = cbm_type_materialize_signature_params(
+ &arena, duplicate_texts, 2, parse_signature_probe_type, &probe);
+ ASSERT_NOT_NULL(duplicates);
+ ASSERT_EQ(probe.call_count, 2);
+ ASSERT_STR_EQ(duplicates[0]->data.builtin.name, "int");
+ ASSERT_STR_EQ(duplicates[1]->data.builtin.name, "int");
+ ASSERT_NULL(duplicates[2]);
+
+ memset(&probe, 0, sizeof(probe));
+ const char *trailing_texts[] = {"int", "string", "?"};
+ const CBMType **trailing = cbm_type_materialize_signature_params(
+ &arena, trailing_texts, 3, parse_signature_probe_type, &probe);
+ ASSERT_NOT_NULL(trailing);
+ ASSERT_EQ(probe.call_count, 2);
+ ASSERT_STR_EQ(trailing[0]->data.builtin.name, "int");
+ ASSERT_STR_EQ(trailing[1]->data.builtin.name, "string");
+ ASSERT_TRUE(cbm_type_is_unknown(trailing[2]));
+ ASSERT_NULL(trailing[3]);
+
+ memset(&probe, 0, sizeof(probe));
+ const char *sentinel_texts[] = {"?", "?Foo", "Foo?", "parser-null", "", NULL};
+ const CBMType **sentinels = cbm_type_materialize_signature_params(
+ &arena, sentinel_texts, 6, parse_signature_probe_type, &probe);
+ ASSERT_NOT_NULL(sentinels);
+ ASSERT_EQ(probe.call_count, 3);
+ ASSERT_STR_EQ(probe.seen[0], "?Foo");
+ ASSERT_STR_EQ(probe.seen[1], "Foo?");
+ ASSERT_STR_EQ(probe.seen[2], "parser-null");
+ ASSERT_TRUE(cbm_type_is_unknown(sentinels[0]));
+ ASSERT_EQ(sentinels[1]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(sentinels[1]->data.builtin.name, "?Foo");
+ ASSERT_EQ(sentinels[2]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(sentinels[2]->data.builtin.name, "Foo?");
+ ASSERT_TRUE(cbm_type_is_unknown(sentinels[3]));
+ ASSERT_TRUE(cbm_type_is_unknown(sentinels[4]));
+ ASSERT_TRUE(cbm_type_is_unknown(sentinels[5]));
+ ASSERT_NULL(sentinels[6]);
+
+ memset(&probe, 0, sizeof(probe));
+ const CBMType **missing_texts =
+ cbm_type_materialize_signature_params(&arena, NULL, 3, parse_signature_probe_type, &probe);
+ ASSERT_NOT_NULL(missing_texts);
+ ASSERT_EQ(probe.call_count, 0);
+ ASSERT_TRUE(cbm_type_is_unknown(missing_texts[0]));
+ ASSERT_TRUE(cbm_type_is_unknown(missing_texts[1]));
+ ASSERT_TRUE(cbm_type_is_unknown(missing_texts[2]));
+ ASSERT_NULL(missing_texts[3]);
+ ASSERT_NULL(cbm_type_materialize_signature_params(&arena, ordered_texts, 0,
+ parse_signature_probe_type, &probe));
+
+ cbm_arena_destroy(&arena);
+ PASS();
+}
+
+TEST(repro_lsp_func_replace_returns_contract) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+
+ const CBMType *integer = cbm_type_builtin(&arena, "int");
+ const CBMType *string = cbm_type_builtin(&arena, "string");
+ const CBMType *old_return = cbm_type_builtin(&arena, "old-return");
+ const CBMType *new_return = cbm_type_builtin(&arena, "new-return");
+ const char *param_names[] = {"first", "middle", "last", NULL};
+ const CBMType *param_types[] = {integer, cbm_type_unknown(), string, NULL};
+ const CBMType *old_returns[] = {old_return, NULL};
+ const CBMType *old_signature = cbm_type_func(&arena, param_names, param_types, old_returns);
+ ASSERT_NOT_NULL(old_signature);
+ ASSERT_EQ(old_signature->kind, CBM_TYPE_FUNC);
+
+ const CBMType *new_returns[] = {new_return, NULL};
+ const CBMType *replaced = cbm_type_func_replace_returns(&arena, old_signature, new_returns);
+ ASSERT_NOT_NULL(replaced);
+ ASSERT_EQ(replaced->kind, CBM_TYPE_FUNC);
+ ASSERT(replaced != old_signature);
+ ASSERT_STR_EQ(replaced->data.func.param_names[0], "first");
+ ASSERT_STR_EQ(replaced->data.func.param_names[1], "middle");
+ ASSERT_STR_EQ(replaced->data.func.param_names[2], "last");
+ ASSERT_NULL(replaced->data.func.param_names[3]);
+ ASSERT(replaced->data.func.param_types[0] == integer);
+ ASSERT_TRUE(cbm_type_is_unknown(replaced->data.func.param_types[1]));
+ ASSERT(replaced->data.func.param_types[2] == string);
+ ASSERT_NULL(replaced->data.func.param_types[3]);
+ ASSERT(replaced->data.func.return_types[0] == new_return);
+ ASSERT_NULL(replaced->data.func.return_types[1]);
+
+ /* The source signature remains untouched. */
+ ASSERT(old_signature->data.func.return_types[0] == old_return);
+ ASSERT_NULL(old_signature->data.func.return_types[1]);
+ ASSERT_STR_EQ(old_signature->data.func.param_names[1], "middle");
+ ASSERT_TRUE(cbm_type_is_unknown(old_signature->data.func.param_types[1]));
+
+ cbm_arena_destroy(&arena);
+ PASS();
+}
+
+static int run_c_explicit_template_value_signature_contract(const char *source,
+ const char *registered_qn,
+ const char *function_node_kind) {
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_CPP, source);
+ ASSERT_NOT_NULL(tree);
+
+ TSNode call = find_first_lsp_node_of_kind(ts_tree_root_node(tree), "call_expression");
+ ASSERT_FALSE(ts_node_is_null(call));
+ TSNode function = ts_node_child_by_field_name(call, "function", 8);
+ ASSERT_FALSE(ts_node_is_null(function));
+ ASSERT_STR_EQ(ts_node_type(function), function_node_kind);
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_registry_init(&registry, &arena);
+
+ const char *param_names[] = {"value", "enabled", NULL};
+ const CBMType *param_types[] = {cbm_type_builtin(&arena, "long"),
+ cbm_type_builtin(&arena, "bool"), NULL};
+ const CBMType *return_types[] = {cbm_type_type_param(&arena, "T"), NULL};
+ const char *type_params[] = {"T", NULL};
+ CBMRegisteredFunc registered = {0};
+ registered.qualified_name = registered_qn;
+ registered.short_name = "materialize";
+ registered.signature = cbm_type_func(&arena, param_names, param_types, return_types);
+ registered.type_param_names = type_params;
+ registered.min_params = 2;
+ cbm_registry_add_func(&registry, registered);
+
+ CBMResolvedCallArray out = {0};
+ CLSPContext ctx;
+ c_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry, NULL,
+ /*cpp_mode=*/true, &out);
+ const CBMType *value_type = c_eval_expr_type(&ctx, function);
+
+ ASSERT_NOT_NULL(value_type);
+ ASSERT_EQ(value_type->kind, CBM_TYPE_FUNC);
+ ASSERT_NOT_NULL(value_type->data.func.return_types);
+ ASSERT_NOT_NULL(value_type->data.func.return_types[0]);
+ ASSERT_EQ(value_type->data.func.return_types[0]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(value_type->data.func.return_types[0]->data.builtin.name, "int");
+
+ ASSERT_NOT_NULL(value_type->data.func.param_names);
+ ASSERT_STR_EQ(value_type->data.func.param_names[0], "value");
+ ASSERT_STR_EQ(value_type->data.func.param_names[1], "enabled");
+ ASSERT_NULL(value_type->data.func.param_names[2]);
+ ASSERT_NOT_NULL(value_type->data.func.param_types);
+ ASSERT_EQ(value_type->data.func.param_types[0]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(value_type->data.func.param_types[0]->data.builtin.name, "long");
+ ASSERT_EQ(value_type->data.func.param_types[1]->kind, CBM_TYPE_BUILTIN);
+ ASSERT_STR_EQ(value_type->data.func.param_types[1]->data.builtin.name, "bool");
+ ASSERT_NULL(value_type->data.func.param_types[2]);
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ return 0;
+}
+
+TEST(repro_lsp_c_unqualified_explicit_template_value_preserves_signature) {
+ return run_c_explicit_template_value_signature_contract(
+ "void caller(){ materialize<int>(1L, true); }", "materialize", "template_function");
+}
+
+TEST(repro_lsp_c_qualified_explicit_template_value_preserves_signature) {
+ return run_c_explicit_template_value_signature_contract(
+ "void caller(){ ns::materialize<int>(1L, true); }", "ns.materialize",
+ "qualified_identifier");
+}
+
+TEST(repro_lsp_ordered_signatures_c_control) {
+ ASSERT_EQ(run_typed_language_contract(&C_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_cpp_control) {
+ ASSERT_EQ(run_typed_language_contract(&CPP_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_cuda_control) {
+ ASSERT_EQ(run_typed_language_contract(&CUDA_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_go) {
+ ASSERT_EQ(run_typed_language_contract(&GO_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_javascript) {
+ ASSERT_EQ(run_javascript_unknown_contract(&JS_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_typescript) {
+ ASSERT_EQ(run_typed_language_contract(&TS_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_tsx) {
+ ASSERT_EQ(run_typed_language_contract(&TSX_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_python) {
+ ASSERT_EQ(run_typed_language_contract(&PYTHON_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_csharp) {
+ ASSERT_EQ(run_typed_language_contract(&CSHARP_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_csharp_cross_return) {
+ CBMArena arena;
+ cbm_arena_init(&arena);
+
+ CBMLSPDef def;
+ init_function_def(&def, &arena, &CSHARP_LANGUAGE, "cross_return", NULL, 0);
+ def.return_types = "System.String";
+ CBMTypeRegistry *registry = cbm_cs_build_cross_registry(&arena, &def, 1);
+ int failures = registry ? check_single_return(registry, def.qualified_name,
+ "csharp-cross-return", "String")
+ : 1;
+
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_rust) {
+ ASSERT_EQ(run_typed_language_contract(&RUST_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_java) {
+ ASSERT_EQ(run_typed_language_contract(&JAVA_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_kotlin) {
+ ASSERT_EQ(run_typed_language_contract(&KOTLIN_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_php) {
+ ASSERT_EQ(run_typed_language_contract(&PHP_LANGUAGE), 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_csharp_ast_return_refinement) {
+ const char *module_qn = "cbm.ordered.csharp.local";
+ const char *subject_qn = "cbm.ordered.csharp.local.Subject";
+ const char *thing_qn = "cbm.ordered.csharp.local.Thing";
+ const char *result_qn = "cbm.ordered.csharp.local.Result";
+ const char *method_qn = "cbm.ordered.csharp.local.Subject.method";
+ const char *source =
+ "class Thing {}\n"
+ "class Result {}\n"
+ "class Subject {\n"
+ " Result method(int first, Thing middle, int last) { return new Result(); }\n"
+ "}\n";
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_CSHARP, source);
+ ASSERT_NOT_NULL(tree);
+ TSNode root = ts_tree_root_node(tree);
+ ASSERT_FALSE(ts_node_has_error(root));
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_registry_init(&registry, &arena);
+ add_fixture_type(&registry, thing_qn, "Thing");
+ add_fixture_type(&registry, result_qn, "Result");
+ add_fixture_type(&registry, subject_qn, "Subject");
+ add_csharp_seeded_method(&arena, &registry, method_qn, "method", subject_qn, thing_qn);
+
+ CBMResolvedCallArray out = {0};
+ CSLSPContext ctx;
+ cs_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry, module_qn, &out);
+ cbm_cs_refine_ast_return_types(&ctx, &registry, root);
+
+ const char *expected[] = {"int", "Thing", "int"};
+ int failures =
+ check_signature(&registry, method_qn, "csharp-ast-return-refinement", expected, 3);
+ failures += check_single_return(&registry, method_qn, "csharp-ast-return-refinement", "Result");
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_rust_ast_return_refinement) {
+ const char *module_qn = "cbm.ordered.rust.local";
+ const char *thing_qn = "cbm.ordered.rust.local.Thing";
+ const char *result_qn = "cbm.ordered.rust.local.Result";
+ const char *subject_qn = "cbm.ordered.rust.local.Subject";
+ const char *top_qn = "cbm.ordered.rust.local.top";
+ const char *method_qn = "cbm.ordered.rust.local.Subject.method";
+ const char *source =
+ "struct Thing;\n"
+ "struct Result;\n"
+ "struct Subject;\n"
+ "fn top(first: i32, middle: Thing, last: i32) -> Result { Result }\n"
+ "impl Subject {\n"
+ " fn method(&self, first: i32, middle: Thing, last: i32) -> Result { Result }\n"
+ "}\n";
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_RUST, source);
+ ASSERT_NOT_NULL(tree);
+ TSNode root = ts_tree_root_node(tree);
+ ASSERT_FALSE(ts_node_has_error(root));
+
+ const char *params[] = {"i32", "Thing", "i32", NULL};
+ CBMDefinition defs[5] = {0};
+ defs[0].name = "Thing";
+ defs[0].qualified_name = thing_qn;
+ defs[0].label = "Struct";
+ defs[1].name = "Result";
+ defs[1].qualified_name = result_qn;
+ defs[1].label = "Struct";
+ defs[2].name = "Subject";
+ defs[2].qualified_name = subject_qn;
+ defs[2].label = "Struct";
+ defs[3].name = "top";
+ defs[3].qualified_name = top_qn;
+ defs[3].label = "Function";
+ defs[3].param_types = params;
+ defs[3].signature_param_types = params;
+ defs[3].signature_param_count = 3;
+ defs[4].name = "method";
+ defs[4].qualified_name = method_qn;
+ defs[4].label = "Method";
+ defs[4].parent_class = subject_qn;
+ defs[4].param_types = params;
+ defs[4].signature_param_types = params;
+ defs[4].signature_param_count = 3;
+
+ CBMFileResult result = {0};
+ result.module_qn = module_qn;
+ result.defs.items = defs;
+ result.defs.count = 5;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_rust_build_local_registry(&arena, &registry, &result, module_qn, root, source);
+
+ const char *expected[] = {"i32", "Thing", "i32"};
+ int failures = check_signature(&registry, top_qn, "rust-top-return-refinement", expected, 3);
+ failures += check_single_return(&registry, top_qn, "rust-top-return-refinement", "Result");
+ failures += check_signature(&registry, method_qn, "rust-method-return-refinement", expected, 3);
+ failures +=
+ check_single_return(&registry, method_qn, "rust-method-return-refinement", "Result");
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_kotlin_local_registry) {
+ const char *source =
+ "class Thing {}\n"
+ "class Result {}\n"
+ "class Holder {\n"
+ " fun method(first: Int, middle: Thing?, last: Int): Result { return Result() }\n"
+ "}\n"
+ "fun top(first: Int, middle: Thing?, last: Int): Result { return Result() }\n";
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_KOTLIN, source);
+ ASSERT_NOT_NULL(tree);
+ TSNode root = ts_tree_root_node(tree);
+ ASSERT_FALSE(ts_node_has_error(root));
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_registry_init(&registry, &arena);
+ CBMResolvedCallArray out = {0};
+ KotlinLSPContext ctx;
+ kotlin_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry,
+ "cbm.ordered.kotlin.local", "cbm.ordered.kotlin.local", "cbm", "Local.kt",
+ &out);
+ kotlin_lsp_process_file(&ctx, root);
+
+ /* Kotlin intentionally erases nullability in the registry model, but
+ * Thing? must still become the real named Thing rather than UNKNOWN. */
+ const char *expected[] = {"Int", "Thing", "Int"};
+ int failures = check_signature(&registry, "cbm.ordered.kotlin.local.Holder.method",
+ "kotlin-local-method", expected, 3);
+ failures += check_single_return(&registry, "cbm.ordered.kotlin.local.Holder.method",
+ "kotlin-local-method", "Result");
+ failures +=
+ check_signature(&registry, "cbm.ordered.kotlin.local.top", "kotlin-local-top", expected, 3);
+ failures += check_single_return(&registry, "cbm.ordered.kotlin.local.top", "kotlin-local-top",
+ "Result");
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_php_return_refinement) {
+ const char *module_qn = "cbm.ordered.php.local";
+ const char *subject_qn = "cbm.ordered.php.local.Subject";
+ const char *thing_qn = "cbm.ordered.php.local.Thing";
+ const char *result_qn = "cbm.ordered.php.local.Result";
+ const char *source =
+ "<?php\n"
+ "class Thing {}\n"
+ "class Result {}\n"
+ "class Subject {\n"
+ " public function declared(int $first, ?Thing $middle, int $last): Result {\n"
+ " return new Result();\n"
+ " }\n"
+ " /** @return Result */\n"
+ " public function documented(int $first, ?Thing $middle, int $last) {\n"
+ " return new Result();\n"
+ " }\n"
+ "}\n";
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_PHP, source);
+ ASSERT_NOT_NULL(tree);
+ TSNode root = ts_tree_root_node(tree);
+ ASSERT_FALSE(ts_node_has_error(root));
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_registry_init(&registry, &arena);
+ add_fixture_type(&registry, thing_qn, "Thing");
+ add_fixture_type(&registry, result_qn, "Result");
+ add_fixture_type(&registry, subject_qn, "Subject");
+ /* Seed the state expected immediately before AST return refinement. This
+ * isolates whether a declared/PHPDoc return rewrite preserves parameters;
+ * it does not depend on the still-RED PHP registration materializer. */
+ add_php_seeded_method(&arena, &registry, "cbm.ordered.php.local.Subject.declared", "declared",
+ subject_qn, thing_qn, cbm_type_unknown());
+ add_php_seeded_method(&arena, &registry, "cbm.ordered.php.local.Subject.documented",
+ "documented", subject_qn, thing_qn, cbm_type_unknown());
+
+ CBMResolvedCallArray out = {0};
+ PHPLSPContext ctx;
+ php_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry, module_qn, &out);
+ cbm_php_refine_lsp_registry(&ctx, &registry, root);
+
+ const char *expected[] = {"int", "Thing", "int"};
+ int failures = check_signature(&registry, "cbm.ordered.php.local.Subject.declared",
+ "php-declared-return-refinement", expected, 3);
+ failures += check_single_return(&registry, "cbm.ordered.php.local.Subject.declared",
+ "php-declared-return-refinement", "Result");
+ failures += check_signature(&registry, "cbm.ordered.php.local.Subject.documented",
+ "phpdoc-return-refinement", expected, 3);
+ failures += check_single_return(&registry, "cbm.ordered.php.local.Subject.documented",
+ "phpdoc-return-refinement", "Result");
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_lsp_ordered_signatures_php_trait_self_refinement) {
+ const char *module_qn = "cbm.ordered.php.trait";
+ const char *thing_qn = "cbm.ordered.php.trait.Thing";
+ const char *trait_qn = "cbm.ordered.php.trait.Fluent";
+ const char *consumer_qn = "cbm.ordered.php.trait.Consumer";
+ const char *source =
+ "<?php\n"
+ "class Thing {}\n"
+ "trait Fluent {\n"
+ " public function tap(int $first, ?Thing $middle, int $last) { return $this; }\n"
+ "}\n"
+ "class Consumer { use Fluent; }\n";
+ TSTree *tree = parse_lsp_fixture(CBM_LANG_PHP, source);
+ ASSERT_NOT_NULL(tree);
+ TSNode root = ts_tree_root_node(tree);
+ ASSERT_FALSE(ts_node_has_error(root));
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry registry;
+ cbm_registry_init(&registry, &arena);
+ add_fixture_type(&registry, thing_qn, "Thing");
+ add_fixture_type(&registry, trait_qn, "Fluent");
+ add_fixture_type(&registry, consumer_qn, "Consumer");
+ /* No AST return annotation is deliberate: only trait self-substitution
+ * may rebuild this seeded signature, so parameter loss has one cause. */
+ add_php_seeded_method(&arena, &registry, "cbm.ordered.php.trait.Fluent.tap", "tap", trait_qn,
+ thing_qn, cbm_type_named(&arena, trait_qn));
+
+ CBMResolvedCallArray out = {0};
+ PHPLSPContext ctx;
+ php_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry, module_qn, &out);
+ cbm_php_refine_lsp_registry(&ctx, &registry, root);
+
+ const char *expected[] = {"int", "Thing", "int"};
+ int failures = check_signature(&registry, "cbm.ordered.php.trait.Consumer.tap",
+ "php-trait-self-refinement", expected, 3);
+ failures += check_single_return(&registry, "cbm.ordered.php.trait.Consumer.tap",
+ "php-trait-self-refinement", "Consumer");
+
+ ts_tree_delete(tree);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+SUITE(repro_lsp_ordered_signatures) {
+ RUN_TEST(repro_lsp_signature_param_materializer_contract);
+ RUN_TEST(repro_lsp_func_replace_returns_contract);
+ RUN_TEST(repro_lsp_c_unqualified_explicit_template_value_preserves_signature);
+ RUN_TEST(repro_lsp_c_qualified_explicit_template_value_preserves_signature);
+ RUN_TEST(repro_lsp_ordered_signatures_c_control);
+ RUN_TEST(repro_lsp_ordered_signatures_cpp_control);
+ RUN_TEST(repro_lsp_ordered_signatures_cuda_control);
+ RUN_TEST(repro_lsp_ordered_signatures_go);
+ RUN_TEST(repro_lsp_ordered_signatures_javascript);
+ RUN_TEST(repro_lsp_ordered_signatures_typescript);
+ RUN_TEST(repro_lsp_ordered_signatures_tsx);
+ RUN_TEST(repro_lsp_ordered_signatures_python);
+ RUN_TEST(repro_lsp_ordered_signatures_csharp);
+ RUN_TEST(repro_lsp_ordered_signatures_csharp_cross_return);
+ RUN_TEST(repro_lsp_ordered_signatures_rust);
+ RUN_TEST(repro_lsp_ordered_signatures_java);
+ RUN_TEST(repro_lsp_ordered_signatures_kotlin);
+ RUN_TEST(repro_lsp_ordered_signatures_php);
+ RUN_TEST(repro_lsp_ordered_signatures_csharp_ast_return_refinement);
+ RUN_TEST(repro_lsp_ordered_signatures_rust_ast_return_refinement);
+ RUN_TEST(repro_lsp_ordered_signatures_kotlin_local_registry);
+ RUN_TEST(repro_lsp_ordered_signatures_php_return_refinement);
+ RUN_TEST(repro_lsp_ordered_signatures_php_trait_self_refinement);
+}
diff --git a/tests/repro/repro_lsp_ts.c b/tests/repro/repro_lsp_ts.c
index 509679eb6..bedcb33d8 100644
--- a/tests/repro/repro_lsp_ts.c
+++ b/tests/repro/repro_lsp_ts.c
@@ -64,11 +64,8 @@
* registry).
* lsp_ts_jsx_import (ts_lsp.c:2657) <Comp/> JSX element whose tag is an
* imported component (TSX only; tag matches
- * an import local name → synthetic
- * "<module>.<Comp>" QN). NOTE: this site
- * builds the callee QN WITHOUT verifying the
- * symbol exists in the registry, so it can
- * emit even when the import target is absent.
+ * an import local name and the exact
+ * component exists in the registry.
* lsp_ts (ts_lsp.c:116) DEFAULT fallback inside ts_emit_resolved_call
* used only when a caller passes a NULL
* strategy. Every concrete emit site passes a
@@ -311,10 +308,9 @@ static const char kTsxJsx[] =
" return <Widget />;\n"
"}\n";
-/* lsp_ts_jsx_import — <Comp/> JSX element whose tag is an imported component
- * (ts_lsp.c:2652-2657). TSX only; the tag matches an import local name → a
- * synthetic "<module>.<Comp>" callee QN is emitted (this site does NOT verify
- * the symbol is in the registry). Cross-file: widget.tsx exports Widget,
+/* lsp_ts_jsx_import — <Comp/> JSX element whose tag is an imported component.
+ * TSX only; the tag matches an import local name and the cross-file registry
+ * proves the exact component symbol. Cross-file: widget.tsx exports Widget,
* app.tsx imports it and renders <Widget/>. */
static const RFile kTsxJsxImport[] = {
{"widget.tsx",
diff --git a/tests/repro/repro_main.c b/tests/repro/repro_main.c
index fe0ac29f4..3c99a7d7b 100644
--- a/tests/repro/repro_main.c
+++ b/tests/repro/repro_main.c
@@ -2,11 +2,11 @@
* repro_main.c — Entry point for the cumulative BUG-REPRODUCTION suite.
*
* This runner is SEPARATE from the gating `make test` (test-runner). It exists
- * to hold reproduce-first cases for every OPEN bug issue. Each case asserts the
- * CORRECT behaviour, so it is **RED until the bug is fixed** — the redness is the
- * deliverable (proof the bug is real + the permanent regression guard).
+ * to hold reproduce-first cases for OPEN bugs plus the controls needed to prove
+ * their fixtures and oracles are meaningful. Reproduction cases assert the
+ * correct behaviour and stay RED until fixed; controls remain GREEN.
*
- * Because these cases are red by design, they MUST NOT live in `ALL_TEST_SRCS`
+ * Because open reproductions are red by design, these suites MUST NOT live in `ALL_TEST_SRCS`
* (that would turn the PR gate `ci-ok` red and wedge every merge). They are built
* + run only via `make test-repro` and the `bug-repro.yml` workflow, neither of
* which gates branch protection.
@@ -26,33 +26,41 @@ int tf_fail_count = 0;
int tf_skip_count = 0;
#include "test_framework.h"
+#include "repro_runner.h"
#include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */
/* Per-suite summary + filter. RUN_SUITE prints a one-line
* "[SUITE] <name> P passed, F failed" report (greppable for which suites still
- * have reds). When CBM_REPRO_ONLY is set (comma/space list of suite-name
- * substrings), only matching suites run — for fast targeted validation of a
- * single fix without rebuilding intent. */
-static int cbm_suite_enabled(const char *name) {
- const char *only = getenv("CBM_REPRO_ONLY");
- if (!only || !*only)
- return 1;
- return strstr(only, name) != NULL;
-}
+ * have reds). The shared selector implementation lives with its gating tests in
+ * repro_runner_filter.c. */
#undef RUN_SUITE
-#define RUN_SUITE(name) \
- do { \
- if (!cbm_suite_enabled(#name)) \
- break; \
- int _p0 = tf_pass_count, _f0 = tf_fail_count; \
- printf("\n%s=== %s ===%s\n", tf_dim(), #name, tf_reset()); \
- suite_##name(); \
- printf("[SUITE] %-38s %d passed, %d failed\n", #name, tf_pass_count - _p0, \
- tf_fail_count - _f0); \
+#define RUN_SUITE(name) \
+ do { \
+ if (!cbm_suite_enabled(#name)) \
+ break; \
+ int _p0 = tf_pass_count, _f0 = tf_fail_count; \
+ printf("\n%s=== %s ===%s\n", tf_dim(), #name, tf_reset()); \
+ suite_##name(); \
+ printf("[SUITE] %-38s %d passed, %d failed\n", #name, tf_pass_count - _p0, \
+ tf_fail_count - _f0); \
} while (0)
/* ── Repro suites (one per bug cluster / issue) ─────────────────── */
extern void suite_repro_extraction(void);
+extern void suite_repro_runner_filter(void);
+extern void suite_repro_harness_cleanup(void);
+extern void suite_repro_language_registry(void);
+extern void suite_repro_call_node_manifest(void);
+extern void suite_repro_call_scope_usages(void);
+extern void suite_repro_call_argument_usages(void);
+extern void suite_repro_lsp_ordered_signatures(void);
+extern void suite_repro_lsp_ordered_local(void);
+extern void suite_repro_ts_overload_return_chains(void);
+extern void suite_repro_reference_precision(void);
+extern void suite_repro_lexical_binding_precision(void);
+extern void suite_repro_call_argument_matrix_a(void);
+extern void suite_repro_call_argument_matrix_b(void);
+extern void suite_repro_call_node_behaviors(void);
extern void suite_repro_parallel_determinism(void);
extern void suite_repro_issue495(void);
extern void suite_repro_issue521(void);
@@ -132,11 +140,25 @@ int main(void) {
printf("════════════════════════════════════════════════════════════\n");
printf(" CUMULATIVE BUG-REPRODUCTION SUITE\n");
printf(" RED rows are EXPECTED — each is an open bug reproduced.\n");
- printf(" A row that PASSES means that bug appears FIXED → flip it\n");
- printf(" into the gating suite and close the issue with the guard.\n");
+ printf(" PASS rows may be controls or candidate fixes. Verify each\n");
+ printf(" RED→GREEN transition before promotion or issue closure.\n");
printf("════════════════════════════════════════════════════════════\n");
RUN_SUITE(repro_extraction);
+ RUN_SUITE(repro_runner_filter);
+ RUN_SUITE(repro_harness_cleanup);
+ RUN_SUITE(repro_language_registry);
+ RUN_SUITE(repro_call_node_manifest);
+ RUN_SUITE(repro_call_scope_usages);
+ RUN_SUITE(repro_call_argument_usages);
+ RUN_SUITE(repro_lsp_ordered_signatures);
+ RUN_SUITE(repro_lsp_ordered_local);
+ RUN_SUITE(repro_ts_overload_return_chains);
+ RUN_SUITE(repro_reference_precision);
+ RUN_SUITE(repro_lexical_binding_precision);
+ RUN_SUITE(repro_call_argument_matrix_a);
+ RUN_SUITE(repro_call_argument_matrix_b);
+ RUN_SUITE(repro_call_node_behaviors);
RUN_SUITE(repro_parallel_determinism);
RUN_SUITE(repro_issue495);
RUN_SUITE(repro_issue521);
@@ -194,5 +216,10 @@ int main(void) {
RUN_SUITE(repro_lsp_java_cs);
RUN_SUITE(repro_lsp_kt_php_rust);
+ if (tf_pass_count + tf_fail_count + tf_skip_count == 0) {
+ fprintf(stderr, "::error::bug-repro runner executed zero tests\n");
+ return 2;
+ }
+
TEST_SUMMARY();
}
diff --git a/tests/repro/repro_make_tracks_headers.sh b/tests/repro/repro_make_tracks_headers.sh
new file mode 100644
index 000000000..4c9565c75
--- /dev/null
+++ b/tests/repro/repro_make_tracks_headers.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+# Reproduce linked targets ignoring shared test or production-header changes,
+# which can execute a stale binary after a header-only semantic fix.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+MAKE_DB="$(mktemp "${TMPDIR:-/tmp}/cbm-repro-make-db.XXXXXX")"
+trap 'rm -f "$MAKE_DB"' EXIT
+
+cd "$PROJECT_ROOT"
+make -f Makefile.cbm -pn build/c/test-repro-runner >"$MAKE_DB"
+repro_target_line="$(grep '^build/c/test-repro-runner:' "$MAKE_DB" | head -1 || true)"
+test_target_line="$(grep '^build/c/test-runner:' "$MAKE_DB" | head -1 || true)"
+tsan_target_line="$(grep '^build/c/test-runner-tsan:' "$MAKE_DB" | head -1 || true)"
+production_target_line="$(grep '^build/c/codebase-memory-mcp:' "$MAKE_DB" | head -1 || true)"
+
+if [[ "$repro_target_line" != *'tests/repro/repro_harness.h'* ||
+ "$repro_target_line" != *'tests/test_framework.h'* ||
+ "$repro_target_line" != *'tests/test_helpers.h'* ]]; then
+ printf '[repro-make-headers] invariant=shared_headers_missing_from_target\n' >&2
+ exit 1
+fi
+
+missing_test_header=0
+for target_name in build/c/test-runner build/c/test-runner-tsan; do
+ target_line="$test_target_line"
+ if [[ "$target_name" == 'build/c/test-runner-tsan' ]]; then
+ target_line="$tsan_target_line"
+ fi
+ for header in tests/test_framework.h tests/test_helpers.h tests/grammar_cases.h; do
+ if [[ "$target_line" != *"$header"* ]]; then
+ printf '[repro-make-headers] invariant=test_header_missing_from_target target=%s header=%s\n' \
+ "$target_name" "$header" >&2
+ missing_test_header=1
+ fi
+ done
+done
+missing_production_header=0
+for target_name in build/c/test-runner build/c/test-repro-runner build/c/test-runner-tsan \
+ build/c/codebase-memory-mcp; do
+ case "$target_name" in
+ build/c/test-runner) target_line="$test_target_line" ;;
+ build/c/test-repro-runner) target_line="$repro_target_line" ;;
+ build/c/test-runner-tsan) target_line="$tsan_target_line" ;;
+ *) target_line="$production_target_line" ;;
+ esac
+ for header in src/pipeline/lsp_resolve.h internal/cbm/lsp/type_registry.h; do
+ if [[ "$target_line" != *"$header"* ]]; then
+ printf '[repro-make-headers] invariant=production_header_missing_from_target target=%s header=%s\n' \
+ "$target_name" "$header" >&2
+ missing_production_header=1
+ fi
+ done
+done
+if [[ "$missing_test_header" -ne 0 || "$missing_production_header" -ne 0 ]]; then
+ exit 1
+fi
+
+printf '[repro-make-headers] shared headers tracked by runner and production targets\n'
diff --git a/tests/repro/repro_reference_precision.c b/tests/repro/repro_reference_precision.c
new file mode 100644
index 000000000..63558e3e9
--- /dev/null
+++ b/tests/repro/repro_reference_precision.c
@@ -0,0 +1,2200 @@
+/*
+ * repro_reference_precision.c — occurrence- and target-exact reference edges.
+ *
+ * These are valid-syntax, production-pipeline contracts. Explicit reference
+ * syntax earns CALL_REFERENCE only when the semantic pass proves an exact,
+ * materialized callable target at that occurrence. Properties, dynamic names,
+ * shadowed locals without graph nodes, and unimported definitions must not be
+ * promoted by a same-name fallback. Ordinary calls have the same occurrence
+ * requirement when two receiver types expose the same method name.
+ */
+#include "test_framework.h"
+#include "repro_harness.h"
+#include "lsp/rust_lsp.h"
+#include "lsp/ts_lsp.h"
+#include "pipeline/lsp_resolve.h"
+
+#include <store/store.h>
+
+#include <stdio.h>
+#include <string.h>
+
+static int rp_qn_ends_with(const char *qn, const char *suffix) {
+ if (!qn || !suffix)
+ return 0;
+ size_t qn_len = strlen(qn);
+ size_t suffix_len = strlen(suffix);
+ return qn_len >= suffix_len && strcmp(qn + qn_len - suffix_len, suffix) == 0;
+}
+
+static int rp_extracts_clean(const char *source, CBMLanguage language, const char *filename) {
+ CBMFileResult *result =
+ cbm_extract_file(source, (int)strlen(source), language, "repro", filename, 0, NULL, NULL);
+ if (!result)
+ return 0;
+ int clean = !result->has_error && !result->parse_incomplete;
+ cbm_free_result(result);
+ return clean;
+}
+
+static int rp_node_count(cbm_store_t *store, const char *project, const char *label,
+ const char *name, const char *qn_suffix) {
+ cbm_node_t *nodes = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_label(store, project, label, &nodes, &count) != CBM_STORE_OK)
+ return -1;
+ int matches = 0;
+ for (int i = 0; i < count; i++) {
+ if (name && (!nodes[i].name || strcmp(nodes[i].name, name) != 0))
+ continue;
+ if (qn_suffix && !rp_qn_ends_with(nodes[i].qualified_name, qn_suffix))
+ continue;
+ matches++;
+ }
+ cbm_store_free_nodes(nodes, count);
+ return matches;
+}
+
+static int rp_edge_count(cbm_store_t *store, const char *project, const char *edge_type,
+ const char *source_name, const char *target_label, const char *target_name,
+ const char *target_qn_suffix) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, project, edge_type, &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ return -1;
+ }
+
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ int source_ok =
+ cbm_store_find_node_by_id(store, edges[i].source_id, &source) == CBM_STORE_OK;
+ int target_ok =
+ cbm_store_find_node_by_id(store, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok &&
+ (!source_name || (source.name && strcmp(source.name, source_name) == 0)) &&
+ (!target_label || (target.label && strcmp(target.label, target_label) == 0)) &&
+ (!target_name || (target.name && strcmp(target.name, target_name) == 0)) &&
+ (!target_qn_suffix || rp_qn_ends_with(target.qualified_name, target_qn_suffix))) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return matches;
+}
+
+static int rp_is_constructor_node(const cbm_node_t *node, const char *class_name) {
+ if (!node || !node->label || !node->name || !node->qualified_name || !class_name)
+ return 0;
+ int callable_label = strcmp(node->label, "Constructor") == 0 ||
+ strcmp(node->label, "Function") == 0 || strcmp(node->label, "Method") == 0;
+ int constructor_name =
+ strcmp(node->name, class_name) == 0 || strcmp(node->name, "constructor") == 0;
+ char class_segment[128];
+ snprintf(class_segment, sizeof(class_segment), ".%s", class_name);
+ return callable_label && constructor_name && strstr(node->qualified_name, class_segment);
+}
+
+static int rp_constructor_node_count(cbm_store_t *store, const char *project,
+ const char *class_name) {
+ static const char *const labels[] = {"Constructor", "Function", "Method"};
+ int matches = 0;
+ for (size_t li = 0; li < sizeof(labels) / sizeof(labels[0]); li++) {
+ cbm_node_t *nodes = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_label(store, project, labels[li], &nodes, &count) !=
+ CBM_STORE_OK) {
+ return -1;
+ }
+ for (int i = 0; i < count; i++) {
+ if (rp_is_constructor_node(&nodes[i], class_name))
+ matches++;
+ }
+ cbm_store_free_nodes(nodes, count);
+ }
+ return matches;
+}
+
+static int rp_constructor_edge_count(cbm_store_t *store, const char *project, const char *edge_type,
+ const char *source_name, const char *class_name) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, project, edge_type, &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ int source_ok =
+ cbm_store_find_node_by_id(store, edges[i].source_id, &source) == CBM_STORE_OK;
+ int target_ok =
+ cbm_store_find_node_by_id(store, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok && source.name && strcmp(source.name, source_name) == 0 &&
+ rp_is_constructor_node(&target, class_name)) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return matches;
+}
+
+static int rp_raw_usage_count(const CBMFileResult *result, const char *caller, const char *target,
+ CBMUsageKind kind) {
+ int count = 0;
+ for (int i = 0; result && i < result->usages.count; i++) {
+ const CBMUsage *usage = &result->usages.items[i];
+ const char *owner = usage->enclosing_func_qn;
+ const char *owner_name = owner ? strrchr(owner, '.') : NULL;
+ owner_name = owner_name ? owner_name + 1 : owner;
+ if (usage->kind == kind && usage->ref_name && owner_name &&
+ strcmp(owner_name, caller) == 0 && strcmp(usage->ref_name, target) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int rp_raw_source_callable_def_count(const CBMFileResult *result, const char *source_path) {
+ /* Kotlin raw results also contain synthetic kotlin.Any method defs. This
+ * helper verifies the fixture's own source declarations, not builtins. */
+ int count = 0;
+ for (int i = 0; result && i < result->defs.count; i++) {
+ const char *file_path = result->defs.items[i].file_path;
+ if (!file_path || !source_path || strcmp(file_path, source_path) != 0)
+ continue;
+ const char *label = result->defs.items[i].label;
+ if (label && (strcmp(label, "Function") == 0 || strcmp(label, "Method") == 0 ||
+ strcmp(label, "Constructor") == 0)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+TEST(repro_kotlin_property_reference_does_not_borrow_same_name_function) {
+ static const RFile files[] = {
+ {"Holder.kt", "class Holder { val handler: Int = 1 }\n"},
+ {"Functions.kt", "fun handler(): Unit {}\n"},
+ {"Use.kt", "fun propertyReference(holder: Holder): kotlin.reflect.KProperty0<Int> = "
+ "holder::handler\n"},
+ };
+ ASSERT_TRUE(rp_extracts_clean(files[0].content, CBM_LANG_KOTLIN, files[0].name));
+ ASSERT_TRUE(rp_extracts_clean(files[1].content, CBM_LANG_KOTLIN, files[1].name));
+ ASSERT_TRUE(rp_extracts_clean(files[2].content, CBM_LANG_KOTLIN, files[2].name));
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 3);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin property-reference collision fixture did not produce a graph store");
+ }
+ int property_node =
+ rp_node_count(store, project.project, "Variable", "handler", ".Holder.handler");
+ int function_node =
+ rp_node_count(store, project.project, "Function", "handler", ".Functions.handler");
+ int property_usage = rp_edge_count(store, project.project, "USAGE", "propertyReference",
+ "Variable", "handler", ".Holder.handler");
+ int wrong_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "propertyReference", "Function",
+ "handler", ".Functions.handler");
+ int property_promoted =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "propertyReference", "Variable",
+ "handler", ".Holder.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(property_node, 1);
+ ASSERT_GTE(function_node, 1);
+ ASSERT_EQ(property_usage, 1);
+ ASSERT_EQ(wrong_reference, 0);
+ ASSERT_EQ(property_promoted, 0);
+ PASS();
+}
+
+TEST(repro_kotlin_constructor_reference_requires_concrete_constructor) {
+ /* Inferred return types keep the Class occurrence unique to `::Class`;
+ * spelling the class again in an annotation would be a legitimate USAGE. */
+ static const RFile files[] = {{
+ "Constructors.kt",
+ "class Explicit { constructor(seed: Int) {} }\n"
+ "class Implicit\n"
+ "fun explicitReference() = ::Explicit\n"
+ "fun implicitReference() = ::Implicit\n",
+ }};
+ ASSERT_TRUE(rp_extracts_clean(files[0].content, CBM_LANG_KOTLIN, files[0].name));
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 1);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin constructor-reference fixture did not produce a graph store");
+ }
+ int concrete_constructor = rp_constructor_node_count(store, project.project, "Explicit");
+ int explicit_reference = rp_constructor_edge_count(store, project.project, "CALL_REFERENCE",
+ "explicitReference", "Explicit");
+ int explicit_class_usage = rp_edge_count(store, project.project, "USAGE", "explicitReference",
+ "Class", "Explicit", ".Explicit");
+ int implicit_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "implicitReference", NULL, NULL, NULL);
+ int implicit_class_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "implicitReference", "Class",
+ "Implicit", ".Implicit");
+ int implicit_class_usage = rp_edge_count(store, project.project, "USAGE", "implicitReference",
+ "Class", "Implicit", ".Implicit");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(concrete_constructor, 1);
+ ASSERT_EQ(explicit_reference, 1);
+ ASSERT_EQ(explicit_class_usage, 0);
+ ASSERT_EQ(implicit_reference, 0);
+ ASSERT_EQ(implicit_class_reference, 0);
+ ASSERT_EQ(implicit_class_usage, 1);
+ PASS();
+}
+
+TEST(repro_kotlin_local_reference_never_binds_same_name_top_level) {
+ static const RFile files[] = {
+ {"Other.kt", "fun handler(): Unit {}\n"},
+ {"Use.kt", "fun localReference(): Unit {\n"
+ " fun handler(): Unit {}\n"
+ " val callback = ::handler\n"
+ " callback()\n"
+ "}\n"},
+ };
+ ASSERT_TRUE(rp_extracts_clean(files[0].content, CBM_LANG_KOTLIN, files[0].name));
+ ASSERT_TRUE(rp_extracts_clean(files[1].content, CBM_LANG_KOTLIN, files[1].name));
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin local callable-reference fixture did not produce a graph store");
+ }
+ int top_level_node =
+ rp_node_count(store, project.project, "Function", "handler", ".Other.handler");
+ int local_node = rp_node_count(store, project.project, "Function", "handler", ".Use.handler");
+ int local_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "localReference",
+ "Function", "handler", ".Use.handler");
+ int any_precise_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "localReference", NULL, NULL, NULL);
+ int wrong_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "localReference",
+ "Function", "handler", ".Other.handler");
+ int wrong_usage = rp_edge_count(store, project.project, "USAGE", "localReference", "Function",
+ "handler", ".Other.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(top_level_node, 1);
+ ASSERT_EQ(wrong_reference, 0);
+ ASSERT_EQ(wrong_usage, 0);
+ /* A future local-function node may be referenced precisely. Until such a
+ * node exists, the explicit syntax must remain non-precise. */
+ ASSERT_TRUE(local_node > 0 ? local_reference == 1 : any_precise_reference == 0);
+ PASS();
+}
+
+TEST(repro_php_dynamic_first_class_terminal_is_not_precise) {
+ static const char source[] =
+ "<?php\n"
+ "class DynamicTarget { public function concrete(): void {} }\n"
+ "function method(): void {}\n"
+ "function dynamicReference(DynamicTarget $object, string $method): callable {\n"
+ " return $object->$method(...);\n"
+ "}\n";
+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_PHP, "repro",
+ "Dynamic.php", 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ int ordinary_terminal = rp_raw_usage_count(raw, "dynamicReference", "$method", CBM_USAGE_VALUE);
+ int precise_terminal =
+ rp_raw_usage_count(raw, "dynamicReference", "$method", CBM_USAGE_CALL_REFERENCE);
+ cbm_free_result(raw);
+ ASSERT_EQ(ordinary_terminal, 1);
+ ASSERT_EQ(precise_terminal, 0);
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "Dynamic.php", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("PHP dynamic first-class callable fixture did not produce a graph store");
+ }
+ int fabricated_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "dynamicReference", NULL, NULL, NULL);
+ int fabricated_call = rp_edge_count(store, project.project, "CALLS", "dynamicReference",
+ "Function", "method", ".Dynamic.method");
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(fabricated_reference, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(repro_php_static_magic_first_class_reference_targets_callstatic) {
+ static const char source[] =
+ "<?php\n"
+ "class MagicStatic {\n"
+ " public static function __callStatic(string $name, array $arguments): mixed {\n"
+ " return null;\n"
+ " }\n"
+ "}\n"
+ "function staticMagicReference(): callable { return MagicStatic::missing(...); }\n";
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_PHP, "MagicStatic.php"));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "MagicStatic.php", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("PHP __callStatic reference fixture did not produce a graph store");
+ }
+ int magic_node = rp_node_count(store, project.project, "Method", "__callStatic",
+ ".MagicStatic.__callStatic");
+ int magic_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "staticMagicReference", "Method",
+ "__callStatic", ".MagicStatic.__callStatic");
+ int missing_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "staticMagicReference", NULL, "missing", NULL);
+ int magic_call = rp_edge_count(store, project.project, "CALLS", "staticMagicReference",
+ "Method", "__callStatic", ".MagicStatic.__callStatic");
+ int magic_usage = rp_edge_count(store, project.project, "USAGE", "staticMagicReference",
+ "Method", "__callStatic", ".MagicStatic.__callStatic");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(magic_node, 1);
+ ASSERT_EQ(magic_reference, 1);
+ ASSERT_EQ(missing_reference, 0);
+ ASSERT_EQ(magic_call, 0);
+ ASSERT_EQ(magic_usage, 0);
+ PASS();
+}
+
+TEST(repro_php_typed_invokable_first_class_reference_targets_invoke) {
+ static const char source[] =
+ "<?php\n"
+ "class Invokable {\n"
+ " public function __invoke(int $value): int { return $value; }\n"
+ "}\n"
+ "function invokableReference(Invokable $handler): callable { return $handler(...); }\n";
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_PHP, "Invokable.php"));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "Invokable.php", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("PHP invokable-object reference fixture did not produce a graph store");
+ }
+ int invoke_node =
+ rp_node_count(store, project.project, "Method", "__invoke", ".Invokable.__invoke");
+ int invoke_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "invokableReference", "Method",
+ "__invoke", ".Invokable.__invoke");
+ int invoke_call = rp_edge_count(store, project.project, "CALLS", "invokableReference", "Method",
+ "__invoke", ".Invokable.__invoke");
+ int invoke_usage = rp_edge_count(store, project.project, "USAGE", "invokableReference",
+ "Method", "__invoke", ".Invokable.__invoke");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(invoke_node, 1);
+ ASSERT_EQ(invoke_reference, 1);
+ ASSERT_EQ(invoke_call, 0);
+ ASSERT_EQ(invoke_usage, 0);
+ PASS();
+}
+
+TEST(repro_java_same_name_receiver_calls_keep_occurrence_identity) {
+ static const char source[] = "class Alpha { void handle() {} }\n"
+ "class Beta { void handle() {} }\n"
+ "class Calls {\n"
+ " static void callBoth(Alpha alpha, Beta beta) {\n"
+ " alpha.handle();\n"
+ " beta.handle();\n"
+ " }\n"
+ "}\n";
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_JAVA, "Calls.java"));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "Calls.java", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Java same-name receiver-call fixture did not produce a graph store");
+ }
+ int alpha_node = rp_node_count(store, project.project, "Method", "handle", ".Alpha.handle");
+ int beta_node = rp_node_count(store, project.project, "Method", "handle", ".Beta.handle");
+ int alpha_call = rp_edge_count(store, project.project, "CALLS", "callBoth", "Method", "handle",
+ ".Alpha.handle");
+ int beta_call = rp_edge_count(store, project.project, "CALLS", "callBoth", "Method", "handle",
+ ".Beta.handle");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(alpha_node, 1);
+ ASSERT_GTE(beta_node, 1);
+ ASSERT_EQ(alpha_call, 1);
+ ASSERT_EQ(beta_call, 1);
+ PASS();
+}
+
+TEST(repro_typescript_function_value_upgrades_only_with_exact_semantic_target) {
+ static const RFile files[] = {
+ {"target.ts", "export function handler(): void {}\n"},
+ {"use.ts", "import { handler } from './target';\n"
+ "function accept(callback: () => void): void {}\n"
+ "function consume(value: number): void {}\n"
+ "export function exactReference(): void { accept(handler); }\n"
+ "export function shadowedValue(handler: number): void { consume(handler); }\n"},
+ };
+ ASSERT_TRUE(rp_extracts_clean(files[0].content, CBM_LANG_TYPESCRIPT, files[0].name));
+ ASSERT_TRUE(rp_extracts_clean(files[1].content, CBM_LANG_TYPESCRIPT, files[1].name));
+
+ CBMFileResult *raw =
+ cbm_extract_file(files[1].content, (int)strlen(files[1].content), CBM_LANG_TYPESCRIPT,
+ "repro", files[1].name, 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_EQ(rp_raw_usage_count(raw, "exactReference", "handler", CBM_USAGE_VALUE), 1);
+ ASSERT_EQ(rp_raw_usage_count(raw, "exactReference", "handler", CBM_USAGE_CALL_REFERENCE), 0);
+ ASSERT_EQ(rp_raw_usage_count(raw, "shadowedValue", "handler", CBM_USAGE_VALUE), 1);
+ cbm_free_result(raw);
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("TypeScript function-value precision fixture did not produce a graph store");
+ }
+ int function_node =
+ rp_node_count(store, project.project, "Function", "handler", ".target.handler");
+ int exact_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "exactReference",
+ "Function", "handler", ".target.handler");
+ int exact_usage = rp_edge_count(store, project.project, "USAGE", "exactReference", "Function",
+ "handler", ".target.handler");
+ int exact_call = rp_edge_count(store, project.project, "CALLS", "exactReference", "Function",
+ "handler", ".target.handler");
+ int shadow_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "shadowedValue",
+ "Function", "handler", ".target.handler");
+ int shadow_usage = rp_edge_count(store, project.project, "USAGE", "shadowedValue", "Function",
+ "handler", ".target.handler");
+ int shadow_call = rp_edge_count(store, project.project, "CALLS", "shadowedValue", "Function",
+ "handler", ".target.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(function_node, 1);
+ ASSERT_EQ(exact_reference, 1);
+ ASSERT_EQ(exact_usage, 0);
+ ASSERT_EQ(exact_call, 0);
+ ASSERT_EQ(shadow_reference, 0);
+ ASSERT_EQ(shadow_usage, 0);
+ ASSERT_EQ(shadow_call, 0);
+ PASS();
+}
+
+TEST(repro_kotlin_empty_cross_filter_does_not_fail_open) {
+ static const RFile files[] = {
+ {"src/main/kotlin/unrelated/Unrelated.kt", "package unrelated\n"
+ "fun handler(): Unit {}\n"},
+ {"src/main/kotlin/consumer/Use.kt", "package consumer\n"
+ "val leakedReference: () -> Unit = ::handler\n"},
+ };
+ ASSERT_TRUE(rp_extracts_clean(files[0].content, CBM_LANG_KOTLIN, files[0].name));
+ ASSERT_TRUE(rp_extracts_clean(files[1].content, CBM_LANG_KOTLIN, files[1].name));
+
+ CBMFileResult *consumer =
+ cbm_extract_file(files[1].content, (int)strlen(files[1].content), CBM_LANG_KOTLIN, "repro",
+ files[1].name, 0, NULL, NULL);
+ ASSERT_NOT_NULL(consumer);
+ int own_callable_defs = rp_raw_source_callable_def_count(consumer, files[1].name);
+ cbm_free_result(consumer);
+ ASSERT_EQ(own_callable_defs, 0);
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin empty cross-filter fixture did not produce a graph store");
+ }
+ int unrelated_node =
+ rp_node_count(store, project.project, "Function", "handler", ".Unrelated.handler");
+ int leaked_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", NULL, "Function",
+ "handler", ".Unrelated.handler");
+ int leaked_usage = rp_edge_count(store, project.project, "USAGE", NULL, "Function", "handler",
+ ".Unrelated.handler");
+ int leaked_call = rp_edge_count(store, project.project, "CALLS", NULL, "Function", "handler",
+ ".Unrelated.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(unrelated_node, 1);
+ ASSERT_EQ(leaked_reference, 0);
+ ASSERT_EQ(leaked_usage, 0);
+ ASSERT_EQ(leaked_call, 0);
+ PASS();
+}
+
+static int rp_assert_callable_alias_graph(const char *filename, const char *source,
+ CBMLanguage language, const char *caller,
+ const char *callable_label) {
+ ASSERT_TRUE(rp_extracts_clean(source, language, filename));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, filename, source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("callable-alias fixture did not produce a graph store");
+ }
+ int shadowed_node = rp_node_count(store, project.project, callable_label, "shadowed", NULL);
+ int actual_node = rp_node_count(store, project.project, callable_label, "actual", NULL);
+ int wrong_call =
+ rp_edge_count(store, project.project, "CALLS", caller, callable_label, "shadowed", NULL);
+ int exact_call =
+ rp_edge_count(store, project.project, "CALLS", caller, callable_label, "actual", NULL);
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(shadowed_node, 1);
+ ASSERT_GTE(actual_node, 1);
+ ASSERT_EQ(wrong_call, 0);
+ ASSERT_EQ(exact_call, 1);
+ return 0;
+}
+
+TEST(repro_go_callable_alias_invocation_targets_exact_value) {
+ static const char source[] = "package aliases\n"
+ "func shadowed() int { return 1 }\n"
+ "func actual() int { return 2 }\n"
+ "func aliasCaller() int {\n"
+ " shadowed := actual\n"
+ " return shadowed()\n"
+ "}\n";
+ int rc = rp_assert_callable_alias_graph("aliases.go", source, CBM_LANG_GO, "aliasCaller",
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_callable_alias_invocation_targets_exact_value) {
+ static const char source[] = "from typing import Callable\n"
+ "def shadowed() -> int:\n"
+ " return 1\n"
+ "def actual() -> int:\n"
+ " return 2\n"
+ "def aliasCaller() -> int:\n"
+ " shadowed: Callable[[], int] = actual\n"
+ " return shadowed()\n";
+ int rc = rp_assert_callable_alias_graph("aliases.py", source, CBM_LANG_PYTHON, "aliasCaller",
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_callable_alias_invocation_targets_exact_value) {
+ static const char source[] = "fn shadowed() -> i32 { 1 }\n"
+ "fn actual() -> i32 { 2 }\n"
+ "fn aliasCaller() -> i32 {\n"
+ " let shadowed: fn() -> i32 = actual;\n"
+ " shadowed()\n"
+ "}\n";
+ int rc = rp_assert_callable_alias_graph("aliases.rs", source, CBM_LANG_RUST, "aliasCaller",
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_kotlin_callable_alias_invocation_targets_exact_value) {
+ static const char source[] = "fun shadowed(): Int = 1\n"
+ "fun actual(): Int = 2\n"
+ "fun aliasCaller(): Int {\n"
+ " val shadowed = ::actual\n"
+ " return shadowed()\n"
+ "}\n";
+ int rc = rp_assert_callable_alias_graph("Aliases.kt", source, CBM_LANG_KOTLIN, "aliasCaller",
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_csharp_callable_alias_invocation_targets_exact_value) {
+ static const char source[] = "using System;\n"
+ "class Aliases {\n"
+ " static int shadowed() { return 1; }\n"
+ " static int actual() { return 2; }\n"
+ " static int aliasCaller() {\n"
+ " Func<int> shadowed = actual;\n"
+ " return shadowed();\n"
+ " }\n"
+ "}\n";
+ int rc = rp_assert_callable_alias_graph("Aliases.cs", source, CBM_LANG_CSHARP, "aliasCaller",
+ "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+static int rp_assert_exact_function_value_reference(const char *filename, const char *source,
+ CBMLanguage language,
+ const char *callable_label) {
+ ASSERT_TRUE(rp_extracts_clean(source, language, filename));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, filename, source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("function-value fixture did not produce a graph store");
+ }
+ int target_node = rp_node_count(store, project.project, callable_label, "handler", NULL);
+ int precise_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "argument",
+ callable_label, "handler", NULL);
+ int ordinary_usage =
+ rp_edge_count(store, project.project, "USAGE", "argument", callable_label, "handler", NULL);
+ int fabricated_call =
+ rp_edge_count(store, project.project, "CALLS", "argument", callable_label, "handler", NULL);
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(target_node, 1);
+ ASSERT_EQ(precise_reference, 1);
+ ASSERT_EQ(ordinary_usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ return 0;
+}
+
+TEST(repro_go_exact_function_value_is_call_reference) {
+ static const char source[] = "package refs\n"
+ "func handler() {}\n"
+ "func accept(callback func()) {}\n"
+ "func argument() { accept(handler) }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.go", source, CBM_LANG_GO, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_exact_function_value_is_call_reference) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument():\n"
+ " accept(handler)\n";
+ int rc =
+ rp_assert_exact_function_value_reference("refs.py", source, CBM_LANG_PYTHON, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_javascript_exact_function_value_is_call_reference) {
+ static const char source[] = "function handler() {}\n"
+ "function accept(callback) {}\n"
+ "function argument() { accept(handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.js", source, CBM_LANG_JAVASCRIPT,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_c_exact_function_value_is_call_reference) {
+ static const char source[] = "typedef void (*callback_t)(void);\n"
+ "void handler(void) {}\n"
+ "void accept(callback_t callback) {}\n"
+ "void argument(void) { accept(handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.c", source, CBM_LANG_C, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_cpp_exact_function_value_is_call_reference) {
+ static const char source[] = "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void argument() { accept(handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.cpp", source, CBM_LANG_CPP, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_exact_function_value_is_call_reference) {
+ static const char source[] = "fn handler() {}\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn argument() { accept(handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.rs", source, CBM_LANG_RUST, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_direct_scoped_function_value_is_exact_reference) {
+ static const RFile files[] = {
+ {"target.rs", "pub fn handler() {}\n"},
+ {"decoy.rs", "pub fn handler() {}\n"},
+ {"main.rs", "mod target;\n"
+ "mod decoy;\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn scoped_argument() { accept(target::handler); }\n"},
+ };
+ const char *source = files[2].content;
+ for (size_t i = 0; i < sizeof(files) / sizeof(files[0]); i++) {
+ ASSERT_TRUE(rp_extracts_clean(files[i].content, CBM_LANG_RUST, files[i].name));
+ }
+
+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_RUST, "repro",
+ files[2].name, 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+
+ CBMRustLSPDef defs[3];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "repro.target.handler";
+ defs[0].short_name = "handler";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "repro.target";
+ defs[1].qualified_name = "repro.decoy.handler";
+ defs[1].short_name = "handler";
+ defs[1].label = "Function";
+ defs[1].def_module_qn = "repro.decoy";
+ defs[2].qualified_name = "repro.main.accept";
+ defs[2].short_name = "accept";
+ defs[2].label = "Function";
+ defs[2].def_module_qn = "repro.main";
+ cbm_run_rust_lsp_cross(&raw->arena, source, (int)strlen(source), "repro.main", defs, 3, NULL,
+ NULL, 0, NULL, &raw->resolved_calls);
+
+ const char *site = strstr(source, "target::handler");
+ ASSERT_NOT_NULL(site);
+ uint32_t start = (uint32_t)(site - source);
+ uint32_t end = start + (uint32_t)strlen("target::handler");
+ const CBMUsage *site_usage = NULL;
+ for (int i = 0; i < raw->usages.count; i++) {
+ const CBMUsage *usage = &raw->usages.items[i];
+ if (usage->kind == CBM_USAGE_VALUE && usage->ref_name &&
+ strcmp(usage->ref_name, "target::handler") == 0 && usage->enclosing_func_qn &&
+ rp_qn_ends_with(usage->enclosing_func_qn, "scoped_argument") &&
+ usage->site_start_byte == start && usage->site_end_byte == end) {
+ site_usage = usage;
+ break;
+ }
+ }
+
+ int target_reference_rows = 0;
+ int decoy_reference_rows = 0;
+ int target_invocation_rows = 0;
+ for (int i = 0; i < raw->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &raw->resolved_calls.items[i];
+ if (!resolved->caller_qn || !rp_qn_ends_with(resolved->caller_qn, "scoped_argument") ||
+ resolved->site_start_byte != start || resolved->site_end_byte != end ||
+ !resolved->callee_qn) {
+ continue;
+ }
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE &&
+ rp_qn_ends_with(resolved->callee_qn, ".target.handler")) {
+ target_reference_rows++;
+ }
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE &&
+ rp_qn_ends_with(resolved->callee_qn, ".decoy.handler")) {
+ decoy_reference_rows++;
+ }
+ if (resolved->kind == CBM_RESOLVED_INVOCATION &&
+ rp_qn_ends_with(resolved->callee_qn, ".target.handler")) {
+ target_invocation_rows++;
+ }
+ }
+ const CBMResolvedCall *joined =
+ site_usage ? cbm_pipeline_find_lsp_reference(&raw->resolved_calls, site_usage, false)
+ : NULL;
+ bool semantic_join_is_exact = joined && joined->kind == CBM_RESOLVED_CALL_REFERENCE &&
+ joined->callee_qn &&
+ rp_qn_ends_with(joined->callee_qn, ".target.handler");
+ bool has_site_usage = site_usage != NULL;
+ bool site_is_reference_candidate = site_usage && site_usage->may_be_call_reference;
+ cbm_free_result(raw);
+
+ ASSERT_TRUE(has_site_usage);
+ ASSERT_EQ(target_reference_rows, 1);
+ ASSERT_EQ(decoy_reference_rows, 0);
+ ASSERT_EQ(target_invocation_rows, 0);
+ ASSERT_TRUE(semantic_join_is_exact);
+ ASSERT_TRUE(site_is_reference_candidate);
+
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 3);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Rust scoped function-value fixture did not produce a graph store");
+ }
+ int target_node =
+ rp_node_count(store, project.project, "Function", "handler", ".target.handler");
+ int decoy_node = rp_node_count(store, project.project, "Function", "handler", ".decoy.handler");
+ int registrar_call = rp_edge_count(store, project.project, "CALLS", "scoped_argument",
+ "Function", "accept", NULL);
+ int target_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "scoped_argument", "Function",
+ "handler", ".target.handler");
+ int target_usage = rp_edge_count(store, project.project, "USAGE", "scoped_argument", "Function",
+ "handler", ".target.handler");
+ int target_call = rp_edge_count(store, project.project, "CALLS", "scoped_argument", "Function",
+ "handler", ".target.handler");
+ int decoy_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "scoped_argument",
+ "Function", "handler", ".decoy.handler");
+ int decoy_usage = rp_edge_count(store, project.project, "USAGE", "scoped_argument", "Function",
+ "handler", ".decoy.handler");
+ int decoy_call = rp_edge_count(store, project.project, "CALLS", "scoped_argument", "Function",
+ "handler", ".decoy.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(target_node, 1);
+ ASSERT_EQ(decoy_node, 1);
+ ASSERT_EQ(registrar_call, 1);
+ ASSERT_EQ(target_reference, 1);
+ ASSERT_EQ(target_usage, 0);
+ ASSERT_EQ(target_call, 0);
+ ASSERT_EQ(decoy_reference, 0);
+ ASSERT_EQ(decoy_usage, 0);
+ ASSERT_EQ(decoy_call, 0);
+ PASS();
+}
+
+TEST(repro_csharp_exact_function_value_is_call_reference) {
+ static const char source[] = "using System;\n"
+ "class Refs {\n"
+ " static void handler() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void argument() { accept(handler); }\n"
+ "}\n";
+ int rc = rp_assert_exact_function_value_reference("Refs.cs", source, CBM_LANG_CSHARP, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+static int rp_assert_csharp_callable_value_shape(const char *filename, const char *source,
+ const char *caller, const char *target_qn_suffix) {
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_CSHARP, filename));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, filename, source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("C# callable-value shape fixture did not produce a graph store");
+ }
+ int target_node = rp_node_count(store, project.project, "Method", "handler", target_qn_suffix);
+ int precise_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", caller,
+ "Method", "handler", target_qn_suffix);
+ int ordinary_usage = rp_edge_count(store, project.project, "USAGE", caller, "Method", "handler",
+ target_qn_suffix);
+ int fabricated_call = rp_edge_count(store, project.project, "CALLS", caller, "Method",
+ "handler", target_qn_suffix);
+ rh_cleanup(&project, store);
+
+ if (target_node != 1 || precise_reference != 1 || ordinary_usage != 0 || fabricated_call != 0) {
+ fprintf(stderr,
+ " [csharp-reference-shape] caller=%s target=%s node=%d reference=%d "
+ "usage=%d call=%d\n",
+ caller, target_qn_suffix, target_node, precise_reference, ordinary_usage,
+ fabricated_call);
+ }
+
+ ASSERT_EQ(target_node, 1);
+ ASSERT_EQ(precise_reference, 1);
+ ASSERT_EQ(ordinary_usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ return 0;
+}
+
+/* C# callable-value resolution already proves the exact Service.handler
+ * target. The graph contract requires that proof to join the raw carrier at
+ * this member-access occurrence, rather than leaving an ordinary USAGE. */
+TEST(repro_csharp_member_method_group_is_exact_reference) {
+ static const char source[] = "using System;\n"
+ "class Service { public void handler() {} }\n"
+ "class MemberReference {\n"
+ " static void accept(Action callback) {}\n"
+ " static void memberArgument(Service s) { accept(s.handler); }\n"
+ "}\n";
+ int rc = rp_assert_csharp_callable_value_shape("MemberReference.cs", source, "memberArgument",
+ ".Service.handler");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+/* Parentheses do not make a single method group ambiguous. They must not
+ * prevent the exact semantic target from joining the inner raw carrier. */
+TEST(repro_csharp_parenthesized_method_group_is_exact_reference) {
+ static const char source[] = "using System;\n"
+ "class ParenthesizedReference {\n"
+ " static void handler() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void parenthesizedArgument() { accept((handler)); }\n"
+ "}\n";
+ int rc = rp_assert_csharp_callable_value_shape("ParenthesizedReference.cs", source,
+ "parenthesizedArgument",
+ ".ParenthesizedReference.handler");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+/* An explicitly constructed generic method group is one exact callable
+ * value: handler<int> has no overload or inference ambiguity in this fixture. */
+TEST(repro_csharp_generic_method_group_is_exact_reference) {
+ static const char source[] = "using System;\n"
+ "class GenericReference {\n"
+ " static void handler<T>() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void genericArgument() { accept(handler<int>); }\n"
+ "}\n";
+ int rc = rp_assert_csharp_callable_value_shape("GenericReference.cs", source, "genericArgument",
+ ".GenericReference.handler");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+/* Both imported static classes contain an equally applicable method group.
+ * C# must fail closed: the parser keeps an ordinary value usage, but the
+ * semantic pass and graph may not select either target precisely. */
+TEST(repro_csharp_ambiguous_using_static_method_group_is_not_precise) {
+ static const char source[] = "using System;\n"
+ "using static A;\n"
+ "using static B;\n"
+ "class A { public static void handler() {} }\n"
+ "class B { public static void handler() {} }\n"
+ "class AmbiguousStaticReference {\n"
+ " static void accept(Action callback) {}\n"
+ " static void ambiguousArgument() { accept(handler); }\n"
+ "}\n";
+
+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_CSHARP, "repro",
+ "AmbiguousStaticReference.cs", 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ const char *argument = strstr(source, "accept(handler)");
+ ASSERT_NOT_NULL(argument);
+ uint32_t site_start = (uint32_t)(argument - source) + 7U;
+ uint32_t site_end = site_start + (uint32_t)strlen("handler");
+ int ordinary_usage = rp_raw_usage_count(raw, "ambiguousArgument", "handler", CBM_USAGE_VALUE);
+ int precise_rows = 0;
+ int a_rows = 0;
+ int b_rows = 0;
+ for (int i = 0; i < raw->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &raw->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_CALL_REFERENCE || !resolved->caller_qn ||
+ !rp_qn_ends_with(resolved->caller_qn, "ambiguousArgument") ||
+ resolved->site_start_byte != site_start || resolved->site_end_byte != site_end) {
+ continue;
+ }
+ precise_rows++;
+ if (rp_qn_ends_with(resolved->callee_qn, ".A.handler"))
+ a_rows++;
+ if (rp_qn_ends_with(resolved->callee_qn, ".B.handler"))
+ b_rows++;
+ }
+ cbm_free_result(raw);
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "AmbiguousStaticReference.cs", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("ambiguous C# using-static fixture did not produce a graph store");
+ }
+ int a_node = rp_node_count(store, project.project, "Method", "handler", ".A.handler");
+ int b_node = rp_node_count(store, project.project, "Method", "handler", ".B.handler");
+ int a_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "ambiguousArgument",
+ "Method", "handler", ".A.handler");
+ int b_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "ambiguousArgument",
+ "Method", "handler", ".B.handler");
+ int a_call = rp_edge_count(store, project.project, "CALLS", "ambiguousArgument", "Method",
+ "handler", ".A.handler");
+ int b_call = rp_edge_count(store, project.project, "CALLS", "ambiguousArgument", "Method",
+ "handler", ".B.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_GTE(ordinary_usage, 1);
+ ASSERT_EQ(a_node, 1);
+ ASSERT_EQ(b_node, 1);
+ ASSERT_EQ(precise_rows, 0);
+ ASSERT_EQ(a_rows, 0);
+ ASSERT_EQ(b_rows, 0);
+ ASSERT_EQ(a_reference, 0);
+ ASSERT_EQ(b_reference, 0);
+ ASSERT_EQ(a_call, 0);
+ ASSERT_EQ(b_call, 0);
+ PASS();
+}
+
+TEST(repro_cuda_exact_function_value_is_call_reference) {
+ static const char source[] = "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void argument() { accept(handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.cu", source, CBM_LANG_CUDA, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+typedef struct {
+ const char *tag;
+ const char *filename;
+ const char *source;
+ CBMLanguage language;
+} RPExactReferenceSiteCase;
+
+static int rp_check_exact_function_value_lsp_site(const RPExactReferenceSiteCase *c) {
+ CBMFileResult *result = cbm_extract_file(c->source, (int)strlen(c->source), c->language,
+ "repro", c->filename, 0, NULL, NULL);
+ if (!result) {
+ fprintf(stderr, " [reference-site] lang=%s invariant=extract_result\n", c->tag);
+ return 1;
+ }
+ const char *argument = strstr(c->source, "accept(handler)");
+ const uint32_t start = argument ? (uint32_t)(argument - c->source) + 7U : 0U;
+ const uint32_t end = start + (uint32_t)strlen("handler");
+ const bool ts_family = c->language == CBM_LANG_JAVASCRIPT ||
+ c->language == CBM_LANG_TYPESCRIPT || c->language == CBM_LANG_TSX;
+ CBMArena cross_arena;
+ CBMResolvedCallArray cross_resolved = {0};
+ if (ts_family) {
+ /* TS/JS value references intentionally wait for the project-wide pass:
+ * only that registry proves that the target is materialized. Exercise
+ * that production phase while retaining the exact source-site oracle. */
+ CBMLSPDef defs[] = {
+ {.qualified_name = "repro.refs.handler",
+ .short_name = "handler",
+ .label = "Function",
+ .def_module_qn = "repro.refs",
+ .lang = c->language},
+ {.qualified_name = "repro.refs.accept",
+ .short_name = "accept",
+ .label = "Function",
+ .def_module_qn = "repro.refs",
+ .lang = c->language},
+ {.qualified_name = "repro.refs.argument",
+ .short_name = "argument",
+ .label = "Function",
+ .def_module_qn = "repro.refs",
+ .lang = c->language},
+ };
+ cbm_arena_init(&cross_arena);
+ cbm_run_ts_lsp_cross(&cross_arena, c->source, (int)strlen(c->source), "repro.refs",
+ c->language == CBM_LANG_JAVASCRIPT, c->language == CBM_LANG_TSX, false,
+ defs, (int)(sizeof(defs) / sizeof(defs[0])), NULL, NULL, 0, NULL,
+ &cross_resolved);
+ }
+ const CBMResolvedCallArray *resolved_calls =
+ ts_family ? &cross_resolved : &result->resolved_calls;
+ int exact_references = 0;
+ int handler_invocations = 0;
+ for (int i = 0; i < resolved_calls->count; i++) {
+ const CBMResolvedCall *resolved = &resolved_calls->items[i];
+ if (!resolved->caller_qn || !rp_qn_ends_with(resolved->caller_qn, "argument") ||
+ !resolved->callee_qn || !rp_qn_ends_with(resolved->callee_qn, "handler")) {
+ continue;
+ }
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE && resolved->site_start_byte == start &&
+ resolved->site_end_byte == end) {
+ exact_references++;
+ }
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->site_start_byte == start &&
+ resolved->site_end_byte == end) {
+ handler_invocations++;
+ }
+ }
+ int failures = 0;
+ if (result->has_error || result->parse_incomplete) {
+ fprintf(stderr, " [reference-site] lang=%s invariant=valid_fixture\n", c->tag);
+ failures++;
+ }
+ if (exact_references != 1) {
+ fprintf(stderr,
+ " [reference-site] lang=%s invariant=exact_reference expected=1 actual=%d "
+ "site=%u:%u\n",
+ c->tag, exact_references, start, end);
+ failures++;
+ }
+ if (handler_invocations != 0) {
+ fprintf(stderr, " [reference-site] lang=%s invariant=argument_not_invocation actual=%d\n",
+ c->tag, handler_invocations);
+ failures++;
+ }
+ if (ts_family) {
+ cbm_arena_destroy(&cross_arena);
+ }
+ cbm_free_result(result);
+ return failures;
+}
+
+TEST(repro_exact_function_value_lsp_sites) {
+ static const RPExactReferenceSiteCase cases[] = {
+ {"go", "refs.go",
+ "package refs\n"
+ "func handler() {}\n"
+ "func accept(callback func()) {}\n"
+ "func argument() { accept(handler) }\n",
+ CBM_LANG_GO},
+ {"python", "refs.py",
+ "def handler():\n pass\n"
+ "def accept(callback):\n pass\n"
+ "def argument():\n accept(handler)\n",
+ CBM_LANG_PYTHON},
+ {"javascript", "refs.js",
+ "function handler() {}\n"
+ "function accept(callback) {}\n"
+ "function argument() { accept(handler); }\n",
+ CBM_LANG_JAVASCRIPT},
+ {"typescript", "refs.ts",
+ "function handler(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n",
+ CBM_LANG_TYPESCRIPT},
+ {"tsx", "refs.tsx",
+ "function handler(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function argument(): void { accept(handler); }\n",
+ CBM_LANG_TSX},
+ {"c", "refs.c",
+ "typedef void (*callback_t)(void);\n"
+ "void handler(void) {}\n"
+ "void accept(callback_t callback) {}\n"
+ "void argument(void) { accept(handler); }\n",
+ CBM_LANG_C},
+ {"cpp", "refs.cpp",
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void argument() { accept(handler); }\n",
+ CBM_LANG_CPP},
+ {"cuda", "refs.cu",
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void argument() { accept(handler); }\n",
+ CBM_LANG_CUDA},
+ {"rust", "refs.rs",
+ "fn handler() {}\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn argument() { accept(handler); }\n",
+ CBM_LANG_RUST},
+ {"csharp", "Refs.cs",
+ "using System;\n"
+ "class Refs {\n"
+ " static void handler() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void argument() { accept(handler); }\n"
+ "}\n",
+ CBM_LANG_CSHARP},
+ };
+ int failures = 0;
+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
+ failures += rp_check_exact_function_value_lsp_site(&cases[i]);
+ }
+ ASSERT_EQ(failures, 0);
+ PASS();
+}
+
+TEST(repro_typescript_exact_bound_method_is_call_reference) {
+ static const char source[] =
+ "class Service { handler(): void {} }\n"
+ "function accept(callback: () => void): void {}\n"
+ "function argument(service: Service): void { accept(service.handler); }\n";
+ int rc =
+ rp_assert_exact_function_value_reference("bound.ts", source, CBM_LANG_TYPESCRIPT, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_tsx_exact_bound_method_is_call_reference) {
+ static const char source[] =
+ "class Service { handler(): void {} }\n"
+ "function accept(callback: () => void): void {}\n"
+ "function argument(service: Service): void { accept(service.handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("bound.tsx", source, CBM_LANG_TSX, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_perl_exact_coderef_is_call_reference) {
+ static const char source[] = "sub handler {}\n"
+ "sub accept { my ($callback) = @_; }\n"
+ "sub argument { accept(\\&handler); }\n";
+ int rc = rp_assert_exact_function_value_reference("refs.pl", source, CBM_LANG_PERL, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+static int rp_assert_cross_file_exact_function_value(const RFile *files, int file_count,
+ CBMLanguage language,
+ const char *callable_label) {
+ for (int i = 0; i < file_count; i++) {
+ ASSERT_TRUE(rp_extracts_clean(files[i].content, language, files[i].name));
+ }
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, file_count);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("cross-file function-value fixture did not produce a graph store");
+ }
+ int target_node = rp_node_count(store, project.project, callable_label, "handler", NULL);
+ int registrar_call = rp_edge_count(store, project.project, "CALLS", "crossArgument",
+ callable_label, "accept", NULL);
+ int precise_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "crossArgument",
+ callable_label, "handler", NULL);
+ int ordinary_usage = rp_edge_count(store, project.project, "USAGE", "crossArgument",
+ callable_label, "handler", NULL);
+ int fabricated_call = rp_edge_count(store, project.project, "CALLS", "crossArgument",
+ callable_label, "handler", NULL);
+ rh_cleanup(&project, store);
+
+ if (target_node < 1 || registrar_call != 1 || precise_reference != 1 || ordinary_usage != 0 ||
+ fabricated_call != 0) {
+ fprintf(stderr,
+ " [cross-reference] language=%d target=%d registrar=%d reference=%d "
+ "usage=%d call=%d\n",
+ (int)language, target_node, registrar_call, precise_reference, ordinary_usage,
+ fabricated_call);
+ }
+
+ ASSERT_GTE(target_node, 1);
+ ASSERT_EQ(registrar_call, 1);
+ ASSERT_EQ(precise_reference, 1);
+ ASSERT_EQ(ordinary_usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ return 0;
+}
+
+TEST(repro_go_cross_file_exact_function_value_is_call_reference) {
+ static const RFile files[] = {
+ {"target.go", "package refs\nfunc handler() {}\n"},
+ {"use.go", "package refs\n"
+ "func accept(callback func()) {}\n"
+ "func crossArgument() { accept(handler) }\n"},
+ };
+ int rc = rp_assert_cross_file_exact_function_value(files, 2, CBM_LANG_GO, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_cross_file_exact_function_value_is_call_reference) {
+ static const RFile files[] = {
+ {"target.py", "def handler():\n pass\n"},
+ {"use.py", "from target import handler\n"
+ "def accept(callback):\n pass\n"
+ "def crossArgument():\n accept(handler)\n"},
+ };
+ int rc = rp_assert_cross_file_exact_function_value(files, 2, CBM_LANG_PYTHON, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_aliased_import_function_value_is_call_reference) {
+ static const RFile files[] = {
+ {"target.py", "def handler():\n pass\n"},
+ {"use.py", "from target import handler as callback\n"
+ "def accept(fn):\n pass\n"
+ "def crossArgument():\n accept(callback)\n"},
+ };
+ for (int i = 0; i < 2; i++)
+ ASSERT_TRUE(rp_extracts_clean(files[i].content, CBM_LANG_PYTHON, files[i].name));
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Python aliased from-import fixture did not produce a graph store");
+ }
+ int target_node =
+ rp_node_count(store, project.project, "Function", "handler", ".target.handler");
+ int registrar_call = rp_edge_count(store, project.project, "CALLS", "crossArgument",
+ "Function", "accept", ".use.accept");
+ int precise_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "crossArgument", "Function", "handler",
+ ".target.handler");
+ int ordinary_usage = rp_edge_count(store, project.project, "USAGE", "crossArgument",
+ "Function", "handler", ".target.handler");
+ int fabricated_call = rp_edge_count(store, project.project, "CALLS", "crossArgument",
+ "Function", "handler", ".target.handler");
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(target_node, 1);
+ ASSERT_EQ(registrar_call, 1);
+ ASSERT_EQ(precise_reference, 1);
+ ASSERT_EQ(ordinary_usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(repro_python_alias_equal_module_leaf_targets_imported_member) {
+ static const RFile files[] = {
+ {"target.py", "def handler():\n pass\ndef target():\n pass\n"},
+ {"use.py", "from target import handler as target\n"
+ "def accept(fn):\n pass\n"
+ "def crossArgument():\n accept(target)\n"},
+ };
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Python alias/module-leaf collision fixture did not produce a graph store");
+ }
+ int correct_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "crossArgument", "Function", "handler",
+ ".target.handler");
+ int wrong_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "crossArgument", "Function", "target", ".target.target");
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(correct_reference, 1);
+ ASSERT_EQ(wrong_reference, 0);
+ PASS();
+}
+
+TEST(repro_rust_cross_file_exact_function_value_is_call_reference) {
+ static const RFile files[] = {
+ {"target.rs", "pub fn handler() {}\n"},
+ {"main.rs", "mod target;\n"
+ "use target::handler;\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn crossArgument() { accept(handler); }\n"},
+ };
+ int rc = rp_assert_cross_file_exact_function_value(files, 2, CBM_LANG_RUST, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_csharp_cross_file_exact_function_value_is_call_reference) {
+ static const RFile files[] = {
+ {"Target.cs", "class Target { public static void handler() {} }\n"},
+ {"Use.cs", "using System;\n"
+ "using static Target;\n"
+ "class Use {\n"
+ " static void accept(Action callback) {}\n"
+ " static void crossArgument() { accept(handler); }\n"
+ "}\n"},
+ };
+ int rc = rp_assert_cross_file_exact_function_value(files, 2, CBM_LANG_CSHARP, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+static int rp_assert_cross_file_callable_alias_graph(const RFile *files, int file_count,
+ CBMLanguage language,
+ const char *callable_label) {
+ for (int i = 0; i < file_count; i++) {
+ ASSERT_TRUE(rp_extracts_clean(files[i].content, language, files[i].name));
+ }
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, file_count);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("cross-file callable-alias fixture did not produce a graph store");
+ }
+ int wrong_call = rp_edge_count(store, project.project, "CALLS", "crossAliasCaller",
+ callable_label, "shadowed", NULL);
+ int exact_call = rp_edge_count(store, project.project, "CALLS", "crossAliasCaller",
+ callable_label, "actual", NULL);
+ rh_cleanup(&project, store);
+ ASSERT_EQ(wrong_call, 0);
+ ASSERT_EQ(exact_call, 1);
+ return 0;
+}
+
+TEST(repro_csharp_cross_file_callable_alias_invocation_targets_exact_value) {
+ static const RFile files[] = {
+ {"Target.cs", "class Target { public static int actual() { return 2; } }\n"},
+ {"Use.cs", "using System;\n"
+ "using static Target;\n"
+ "class Use {\n"
+ " static int shadowed() { return 1; }\n"
+ " static int crossAliasCaller() {\n"
+ " Func<int> shadowed = actual;\n"
+ " return shadowed();\n"
+ " }\n"
+ "}\n"},
+ };
+ int rc = rp_assert_cross_file_callable_alias_graph(files, 2, CBM_LANG_CSHARP, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_kotlin_cross_file_callable_alias_invocation_targets_exact_value) {
+ static const RFile files[] = {
+ {"Target.kt", "package target\nfun actual(): Int = 2\n"},
+ {"Use.kt", "package use\n"
+ "import target.actual\n"
+ "fun shadowed(): Int = 1\n"
+ "fun crossAliasCaller(): Int {\n"
+ " val shadowed = ::actual\n"
+ " return shadowed()\n"
+ "}\n"},
+ };
+ int rc = rp_assert_cross_file_callable_alias_graph(files, 2, CBM_LANG_KOTLIN, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+static int rp_assert_alias_argument_exact_join(const char *filename, const char *source,
+ CBMLanguage language, const char *caller,
+ const char *target, bool allow_tail_match) {
+ CBMFileResult *raw =
+ cbm_extract_file(source, (int)strlen(source), language, "repro", filename, 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ const char *argument = NULL;
+ const char *scan = source;
+ while ((scan = strstr(scan, "accept(callback)")) != NULL) {
+ argument = scan;
+ scan++;
+ }
+ ASSERT_NOT_NULL(argument);
+ uint32_t start = (uint32_t)(argument - source) + 7U;
+ uint32_t end = start + (uint32_t)strlen("callback");
+ const CBMUsage *site_usage = NULL;
+ for (int i = 0; i < raw->usages.count; i++) {
+ const CBMUsage *usage = &raw->usages.items[i];
+ if (usage->ref_name && strcmp(usage->ref_name, "callback") == 0 &&
+ usage->enclosing_func_qn && rp_qn_ends_with(usage->enclosing_func_qn, caller) &&
+ usage->site_start_byte == start && usage->site_end_byte == end) {
+ site_usage = usage;
+ break;
+ }
+ }
+ const CBMResolvedCall *joined =
+ site_usage
+ ? cbm_pipeline_find_lsp_reference(&raw->resolved_calls, site_usage, allow_tail_match)
+ : NULL;
+ bool exact_target = joined && joined->callee_qn && rp_qn_ends_with(joined->callee_qn, target);
+ cbm_free_result(raw);
+ ASSERT_NOT_NULL(site_usage);
+ ASSERT_TRUE(exact_target);
+ return 0;
+}
+
+TEST(repro_csharp_callable_alias_argument_is_exact_reference) {
+ static const char source[] = "using System;\n"
+ "class AliasArgument {\n"
+ " static void handler() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void argument() {\n"
+ " Action callback = handler;\n"
+ " accept(callback);\n"
+ " }\n"
+ "}\n";
+ int rc = rp_assert_alias_argument_exact_join("AliasArgument.cs", source, CBM_LANG_CSHARP,
+ "argument", "handler", false);
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_kotlin_callable_alias_argument_is_exact_reference) {
+ static const char source[] = "fun handler(): Unit {}\n"
+ "fun accept(callback: () -> Unit): Unit {}\n"
+ "fun argument(): Unit {\n"
+ " val callback = ::handler\n"
+ " accept(callback)\n"
+ "}\n";
+ int rc = rp_assert_alias_argument_exact_join("AliasArgument.kt", source, CBM_LANG_KOTLIN,
+ "argument", "handler", true);
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_kotlin_receiver_bound_alias_invocation_targets_exact_method) {
+ static const char source[] = "class Service { fun run(): Int = 2 }\n"
+ "fun shadowed(): Int = 1\n"
+ "fun receiverAliasCaller(): Int {\n"
+ " val service = Service()\n"
+ " val shadowed = service::run\n"
+ " return shadowed()\n"
+ "}\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "ReceiverAlias.kt", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin receiver-alias fixture did not produce a graph store");
+ }
+ int wrong_call = rp_edge_count(store, project.project, "CALLS", "receiverAliasCaller",
+ "Function", "shadowed", NULL);
+ int exact_call = rp_edge_count(store, project.project, "CALLS", "receiverAliasCaller", "Method",
+ "run", NULL);
+ rh_cleanup(&project, store);
+ ASSERT_EQ(wrong_call, 0);
+ ASSERT_EQ(exact_call, 1);
+ PASS();
+}
+
+TEST(repro_kotlin_unknown_imported_property_is_not_callable_reference) {
+ static const RFile files[] = {
+ {"Values.kt", "package values\nval handler: Int = 1\n"},
+ {"Use.kt", "package consumer\n"
+ "import values.handler\n"
+ "fun importedPropertyReference(): kotlin.reflect.KProperty0<Int> = ::handler\n"},
+ };
+ RProj project;
+ cbm_store_t *store = rh_index_files(&project, files, 2);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("Kotlin imported-property fixture did not produce a graph store");
+ }
+ int property_node = rp_node_count(store, project.project, "Variable", "handler", NULL);
+ int precise_property = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "importedPropertyReference", "Variable", "handler", NULL);
+ int property_usage = rp_edge_count(store, project.project, "USAGE", "importedPropertyReference",
+ "Variable", "handler", NULL);
+ rh_cleanup(&project, store);
+ ASSERT_GTE(property_node, 1);
+ ASSERT_EQ(precise_property, 0);
+ ASSERT_EQ(property_usage, 1);
+ PASS();
+}
+
+/* A branch/map expression can name callable definitions without selecting one
+ * statically at the argument occurrence. Those target mentions remain USAGE;
+ * only an exact single-target value earns CALL_REFERENCE. */
+static int rp_assert_complex_function_values_stay_usage(const char *filename, const char *source,
+ CBMLanguage language,
+ const char *callable_label) {
+ ASSERT_TRUE(rp_extracts_clean(source, language, filename));
+
+ RProj project;
+ cbm_store_t *store = rh_index(&project, filename, source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("complex function-value fixture did not produce a graph store");
+ }
+ int handler_node = rp_node_count(store, project.project, callable_label, "handler", NULL);
+ int alternate_node = rp_node_count(store, project.project, callable_label, "alternate", NULL);
+ int registrar_call =
+ rp_edge_count(store, project.project, "CALLS", "complex", callable_label, "accept", NULL);
+ int handler_usage =
+ rp_edge_count(store, project.project, "USAGE", "complex", callable_label, "handler", NULL);
+ int alternate_usage = rp_edge_count(store, project.project, "USAGE", "complex", callable_label,
+ "alternate", NULL);
+ int handler_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "complex",
+ callable_label, "handler", NULL);
+ int alternate_reference = rp_edge_count(store, project.project, "CALL_REFERENCE", "complex",
+ callable_label, "alternate", NULL);
+ int handler_call =
+ rp_edge_count(store, project.project, "CALLS", "complex", callable_label, "handler", NULL);
+ int alternate_call = rp_edge_count(store, project.project, "CALLS", "complex", callable_label,
+ "alternate", NULL);
+ rh_cleanup(&project, store);
+
+ if (handler_node < 1 || alternate_node < 1 || registrar_call != 1 || handler_usage != 1 ||
+ alternate_usage != 1 || handler_reference != 0 || alternate_reference != 0 ||
+ handler_call != 0 || alternate_call != 0) {
+ fprintf(stderr,
+ " [complex-reference] file=%s nodes=%d/%d registrar=%d usage=%d/%d "
+ "reference=%d/%d calls=%d/%d\n",
+ filename, handler_node, alternate_node, registrar_call, handler_usage,
+ alternate_usage, handler_reference, alternate_reference, handler_call,
+ alternate_call);
+ }
+
+ ASSERT_GTE(handler_node, 1);
+ ASSERT_GTE(alternate_node, 1);
+ ASSERT_EQ(registrar_call, 1);
+ ASSERT_EQ(handler_usage, 1);
+ ASSERT_EQ(alternate_usage, 1);
+ ASSERT_EQ(handler_reference, 0);
+ ASSERT_EQ(alternate_reference, 0);
+ ASSERT_EQ(handler_call, 0);
+ ASSERT_EQ(alternate_call, 0);
+ return 0;
+}
+
+TEST(repro_javascript_complex_function_value_stays_usage) {
+ static const char source[] = "function handler() {}\n"
+ "function alternate() {}\n"
+ "function accept(callback) {}\n"
+ "function complex(flag) { accept(flag ? handler : alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.js", source, CBM_LANG_JAVASCRIPT,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_typescript_complex_function_value_stays_usage) {
+ static const char source[] =
+ "function handler(): void {}\n"
+ "function alternate(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function complex(flag: boolean): void { accept(flag ? handler : alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.ts", source, CBM_LANG_TYPESCRIPT,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_tsx_complex_function_value_stays_usage) {
+ static const char source[] =
+ "function handler(): void {}\n"
+ "function alternate(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function complex(flag: boolean): void { accept(flag ? handler : alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.tsx", source, CBM_LANG_TSX,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_go_complex_function_value_stays_usage) {
+ static const char source[] =
+ "package refs\n"
+ "func handler() {}\n"
+ "func alternate() {}\n"
+ "func accept(callback func()) {}\n"
+ "func complex(flag bool) { "
+ "accept(map[bool]func(){true: handler, false: alternate}[flag]) }\n";
+ int rc =
+ rp_assert_complex_function_values_stay_usage("complex.go", source, CBM_LANG_GO, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_complex_function_value_stays_usage) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def alternate():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def complex(flag):\n"
+ " accept(handler if flag else alternate)\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.py", source, CBM_LANG_PYTHON,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_c_complex_function_value_stays_usage) {
+ static const char source[] = "typedef void (*callback_t)(void);\n"
+ "void handler(void) {}\n"
+ "void alternate(void) {}\n"
+ "void accept(callback_t callback) {}\n"
+ "void complex(int flag) { accept(flag ? handler : alternate); }\n";
+ int rc =
+ rp_assert_complex_function_values_stay_usage("complex.c", source, CBM_LANG_C, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_cpp_complex_function_value_stays_usage) {
+ static const char source[] =
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void alternate() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void complex(bool flag) { accept(flag ? handler : alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.cpp", source, CBM_LANG_CPP,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_cuda_complex_function_value_stays_usage) {
+ static const char source[] =
+ "using Callback = void (*)();\n"
+ "void handler() {}\n"
+ "void alternate() {}\n"
+ "void accept(Callback callback) {}\n"
+ "void complex(bool flag) { accept(flag ? handler : alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.cu", source, CBM_LANG_CUDA,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_complex_function_value_stays_usage) {
+ static const char source[] = "fn handler() {}\n"
+ "fn alternate() {}\n"
+ "fn accept(_callback: fn()) {}\n"
+ "fn complex(flag: bool) { "
+ "accept(if flag { handler } else { alternate }); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.rs", source, CBM_LANG_RUST,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_csharp_complex_function_value_stays_usage) {
+ static const char source[] =
+ "using System;\n"
+ "class Refs {\n"
+ " static void handler() {}\n"
+ " static void alternate() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void complex(bool flag) { accept(flag ? handler : alternate); }\n"
+ "}\n";
+ int rc = rp_assert_complex_function_values_stay_usage("Complex.cs", source, CBM_LANG_CSHARP,
+ "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_java_complex_method_reference_stays_usage) {
+ static const char source[] = "interface Task { void run(); }\n"
+ "class Refs {\n"
+ " static void handler() {}\n"
+ " static void alternate() {}\n"
+ " static void accept(Task callback) {}\n"
+ " static void complex(boolean flag) { "
+ "accept(flag ? Refs::handler : Refs::alternate); }\n"
+ "}\n";
+ int rc =
+ rp_assert_complex_function_values_stay_usage("Refs.java", source, CBM_LANG_JAVA, "Method");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_kotlin_complex_callable_reference_stays_usage) {
+ static const char source[] = "fun handler() {}\n"
+ "fun alternate() {}\n"
+ "fun accept(callback: () -> Unit) {}\n"
+ "fun complex(flag: Boolean) { "
+ "accept(if (flag) ::handler else ::alternate) }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("Refs.kt", source, CBM_LANG_KOTLIN,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_php_complex_first_class_callable_stays_usage) {
+ static const char source[] = "<?php\n"
+ "function handler(): void {}\n"
+ "function alternate(): void {}\n"
+ "function accept(callable $callback): void {}\n"
+ "function complex(bool $flag): void { "
+ "accept($flag ? handler(...) : alternate(...)); }\n";
+ int rc =
+ rp_assert_complex_function_values_stay_usage("refs.php", source, CBM_LANG_PHP, "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_perl_conditional_coderefs_stay_usage) {
+ static const char source[] = "sub handler {}\n"
+ "sub alternate {}\n"
+ "sub accept { my ($callback) = @_; }\n"
+ "sub complex { my ($flag) = @_; "
+ "accept($flag ? \\&handler : \\&alternate); }\n";
+ int rc = rp_assert_complex_function_values_stay_usage("complex.pl", source, CBM_LANG_PERL,
+ "Function");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+/* A function-pointer binding is exact only until an assignment makes its
+ * target multi-valued. Keeping the initializer's target alive here would
+ * fabricate a CALL_REFERENCE for the later argument occurrence. */
+TEST(repro_c_ambiguous_alias_reassignment_drops_stale_target) {
+ static const char source[] = "void actual(void) {}\n"
+ "void alternate(void) {}\n"
+ "void accept(void (*callback)(void)) {}\n"
+ "void staleAliasCaller(int flag) {\n"
+ " void (*callback)(void) = actual;\n"
+ " callback = flag ? actual : alternate;\n"
+ " accept(callback);\n"
+ "}\n";
+
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_C, "stale_alias.c"));
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "stale_alias.c", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("ambiguous C alias fixture did not produce a graph store");
+ }
+ int actual_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "staleAliasCaller", "Function", "actual", NULL);
+ int alternate_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "staleAliasCaller", "Function", "alternate", NULL);
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(actual_reference, 0);
+ ASSERT_EQ(alternate_reference, 0);
+ PASS();
+}
+
+/* A write in only one branch cannot become the unconditional post-branch
+ * callable identity. The merge has two possible targets and must fail closed
+ * to ordinary USAGE at accept(callback). */
+TEST(repro_c_conditional_alias_reassignment_drops_stale_target) {
+ static const char source[] = "void actual(void) {}\n"
+ "void alternate(void) {}\n"
+ "void accept(void (*callback)(void)) {}\n"
+ "void conditionalAliasCaller(int flag) {\n"
+ " void (*callback)(void) = actual;\n"
+ " if (flag) callback = alternate;\n"
+ " accept(callback);\n"
+ "}\n";
+
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_C, "conditional_alias.c"));
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "conditional_alias.c", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("conditional C alias fixture did not produce a graph store");
+ }
+ int actual_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "conditionalAliasCaller", "Function", "actual", NULL);
+ int alternate_reference =
+ rp_edge_count(store, project.project, "CALL_REFERENCE", "conditionalAliasCaller",
+ "Function", "alternate", NULL);
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(actual_reference, 0);
+ ASSERT_EQ(alternate_reference, 0);
+ PASS();
+}
+
+/* The nearest ordinary lexical binding wins even when an outer function
+ * pointer with the same spelling has an exact target. */
+TEST(repro_c_noncallable_shadow_blocks_outer_alias_target) {
+ static const char source[] = "void actual(void) {}\n"
+ "void accept(void (*callback)(void)) {}\n"
+ "void shadowedAliasCaller(void) {\n"
+ " void (*callback)(void) = actual;\n"
+ " {\n"
+ " int callback = 0;\n"
+ " accept(callback);\n"
+ " }\n"
+ "}\n";
+
+ ASSERT_TRUE(rp_extracts_clean(source, CBM_LANG_C, "shadowed_alias.c"));
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "shadowed_alias.c", source);
+ if (!store) {
+ rh_cleanup(&project, store);
+ FAIL("shadowed C alias fixture did not produce a graph store");
+ }
+ int leaked_reference = rp_edge_count(store, project.project, "CALL_REFERENCE",
+ "shadowedAliasCaller", "Function", "actual", NULL);
+ rh_cleanup(&project, store);
+
+ ASSERT_EQ(leaked_reference, 0);
+ PASS();
+}
+
+static int rp_assert_conditional_alias_reference_fails_closed(const char *filename,
+ const char *source,
+ CBMLanguage language,
+ const char *caller) {
+ CBMFileResult *raw =
+ cbm_extract_file(source, (int)strlen(source), language, "repro", filename, 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ const char *argument_call = NULL;
+ const char *scan = source;
+ while ((scan = strstr(scan, "accept(callback)")) != NULL) {
+ argument_call = scan;
+ scan++;
+ }
+ ASSERT_NOT_NULL(argument_call);
+ uint32_t site_start = (uint32_t)(argument_call - source) + 7U;
+ uint32_t site_end = site_start + (uint32_t)strlen("callback");
+ int ordinary_usage = 0;
+ int precise_reference = 0;
+ int fabricated_invocation = 0;
+ for (int i = 0; i < raw->usages.count; i++) {
+ const CBMUsage *usage = &raw->usages.items[i];
+ if (usage->ref_name && strcmp(usage->ref_name, "callback") == 0 &&
+ usage->enclosing_func_qn && rp_qn_ends_with(usage->enclosing_func_qn, caller) &&
+ usage->site_start_byte == site_start && usage->site_end_byte == site_end &&
+ usage->kind == CBM_USAGE_VALUE) {
+ ordinary_usage++;
+ }
+ }
+ for (int i = 0; i < raw->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &raw->resolved_calls.items[i];
+ if (!resolved->caller_qn || !rp_qn_ends_with(resolved->caller_qn, caller) ||
+ resolved->site_start_byte != site_start || resolved->site_end_byte != site_end) {
+ continue;
+ }
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE) {
+ precise_reference++;
+ } else if (resolved->kind == CBM_RESOLVED_INVOCATION) {
+ fabricated_invocation++;
+ }
+ }
+ cbm_free_result(raw);
+
+ ASSERT_GTE(ordinary_usage, 1);
+ ASSERT_EQ(precise_reference, 0);
+ ASSERT_EQ(fabricated_invocation, 0);
+ return 0;
+}
+
+TEST(repro_cpp_conditional_alias_reference_fails_closed) {
+ static const char source[] = "void actual() {}\n"
+ "void alternate() {}\n"
+ "void accept(void (*callback)()) {}\n"
+ "void conditionalAliasCaller(bool flag) {\n"
+ " void (*callback)() = actual;\n"
+ " if (flag) callback = alternate;\n"
+ " accept(callback);\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "conditional_alias.cpp", source, CBM_LANG_CPP, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_cuda_conditional_alias_reference_fails_closed) {
+ static const char source[] = "void actual() {}\n"
+ "void alternate() {}\n"
+ "void accept(void (*callback)()) {}\n"
+ "void conditionalAliasCaller(bool flag) {\n"
+ " void (*callback)() = actual;\n"
+ " if (flag) callback = alternate;\n"
+ " accept(callback);\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "conditional_alias.cu", source, CBM_LANG_CUDA, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_go_conditional_alias_reference_fails_closed) {
+ static const char source[] = "package refs\n"
+ "func actual() {}\n"
+ "func alternate() {}\n"
+ "func accept(callback func()) {}\n"
+ "func conditionalAliasCaller(flag bool) {\n"
+ " callback := actual\n"
+ " if flag { callback = alternate }\n"
+ " accept(callback)\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "conditional_alias.go", source, CBM_LANG_GO, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_python_conditional_alias_reference_fails_closed) {
+ static const char source[] = "def actual():\n pass\n"
+ "def alternate():\n pass\n"
+ "def accept(callback):\n pass\n"
+ "def conditionalAliasCaller(flag):\n"
+ " callback = actual\n"
+ " if flag:\n callback = alternate\n"
+ " accept(callback)\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "conditional_alias.py", source, CBM_LANG_PYTHON, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_conditional_alias_reference_fails_closed) {
+ static const char source[] = "fn actual() {}\n"
+ "fn alternate() {}\n"
+ "fn accept(callback: fn()) {}\n"
+ "fn conditionalAliasCaller(flag: bool) {\n"
+ " let mut callback: fn() = actual;\n"
+ " if flag { callback = alternate; }\n"
+ " accept(callback);\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "conditional_alias.rs", source, CBM_LANG_RUST, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_rust_unconditional_alias_reassignment_tracks_new_exact_target) {
+ static const char source[] = "fn actual() {}\n"
+ "fn alternate() {}\n"
+ "fn accept(callback: fn()) {}\n"
+ "fn exactReassignmentCaller() {\n"
+ " let mut callback: fn() = actual;\n"
+ " callback = alternate;\n"
+ " accept(callback);\n"
+ "}\n";
+
+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_RUST, "repro",
+ "exact_reassignment.rs", 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ const char *argument_call = strstr(source, "accept(callback)");
+ ASSERT_NOT_NULL(argument_call);
+ uint32_t site_start = (uint32_t)(argument_call - source) + 7U;
+ uint32_t site_end = site_start + (uint32_t)strlen("callback");
+ int stale_reference = 0;
+ int exact_reference = 0;
+ for (int i = 0; i < raw->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &raw->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_CALL_REFERENCE ||
+ resolved->site_start_byte != site_start || resolved->site_end_byte != site_end ||
+ !resolved->callee_qn) {
+ continue;
+ }
+ if (rp_qn_ends_with(resolved->callee_qn, "actual")) {
+ stale_reference++;
+ }
+ if (rp_qn_ends_with(resolved->callee_qn, "alternate")) {
+ exact_reference++;
+ }
+ }
+ cbm_free_result(raw);
+
+ ASSERT_EQ(stale_reference, 0);
+ ASSERT_EQ(exact_reference, 1);
+ PASS();
+}
+
+TEST(repro_kotlin_conditional_alias_reference_fails_closed) {
+ static const char source[] = "fun actual(): Unit {}\n"
+ "fun alternate(): Unit {}\n"
+ "fun accept(callback: () -> Unit): Unit {}\n"
+ "fun conditionalAliasCaller(flag: Boolean): Unit {\n"
+ " var callback = ::actual\n"
+ " if (flag) callback = ::alternate\n"
+ " accept(callback)\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "ConditionalAlias.kt", source, CBM_LANG_KOTLIN, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+TEST(repro_csharp_conditional_alias_reference_fails_closed) {
+ static const char source[] = "using System;\n"
+ "class ConditionalAlias {\n"
+ " static void actual() {}\n"
+ " static void alternate() {}\n"
+ " static void accept(Action callback) {}\n"
+ " static void conditionalAliasCaller(bool flag) {\n"
+ " Action callback = actual;\n"
+ " if (flag) callback = alternate;\n"
+ " accept(callback);\n"
+ " }\n"
+ "}\n";
+ int rc = rp_assert_conditional_alias_reference_fails_closed(
+ "ConditionalAlias.cs", source, CBM_LANG_CSHARP, "conditionalAliasCaller");
+ if (rc != 0)
+ return rc;
+ PASS();
+}
+
+/* Branch-gating graph contracts for every frontend that has dedicated exact
+ * callable-reference semantics. Complex/ambiguous expressions must retain an
+ * ordinary USAGE edge instead of being promoted by a name-only match. */
+SUITE(call_reference_language_complex_contract) {
+ RUN_TEST(repro_javascript_complex_function_value_stays_usage);
+ RUN_TEST(repro_typescript_complex_function_value_stays_usage);
+ RUN_TEST(repro_tsx_complex_function_value_stays_usage);
+ RUN_TEST(repro_go_complex_function_value_stays_usage);
+ RUN_TEST(repro_python_complex_function_value_stays_usage);
+ RUN_TEST(repro_c_complex_function_value_stays_usage);
+ RUN_TEST(repro_cpp_complex_function_value_stays_usage);
+ RUN_TEST(repro_cuda_complex_function_value_stays_usage);
+ RUN_TEST(repro_rust_complex_function_value_stays_usage);
+ RUN_TEST(repro_csharp_complex_function_value_stays_usage);
+ RUN_TEST(repro_java_complex_method_reference_stays_usage);
+ RUN_TEST(repro_kotlin_complex_callable_reference_stays_usage);
+ RUN_TEST(repro_php_complex_first_class_callable_stays_usage);
+ RUN_TEST(repro_perl_conditional_coderefs_stay_usage);
+}
+
+SUITE(repro_reference_precision) {
+ RUN_TEST(repro_kotlin_property_reference_does_not_borrow_same_name_function);
+ RUN_TEST(repro_kotlin_constructor_reference_requires_concrete_constructor);
+ RUN_TEST(repro_kotlin_local_reference_never_binds_same_name_top_level);
+ RUN_TEST(repro_php_dynamic_first_class_terminal_is_not_precise);
+ RUN_TEST(repro_php_static_magic_first_class_reference_targets_callstatic);
+ RUN_TEST(repro_php_typed_invokable_first_class_reference_targets_invoke);
+ RUN_TEST(repro_java_same_name_receiver_calls_keep_occurrence_identity);
+ RUN_TEST(repro_typescript_function_value_upgrades_only_with_exact_semantic_target);
+ RUN_TEST(repro_kotlin_empty_cross_filter_does_not_fail_open);
+ RUN_TEST(repro_go_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_python_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_rust_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_kotlin_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_csharp_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_go_exact_function_value_is_call_reference);
+ RUN_TEST(repro_python_exact_function_value_is_call_reference);
+ RUN_TEST(repro_javascript_exact_function_value_is_call_reference);
+ RUN_TEST(repro_c_exact_function_value_is_call_reference);
+ RUN_TEST(repro_cpp_exact_function_value_is_call_reference);
+ RUN_TEST(repro_rust_exact_function_value_is_call_reference);
+ RUN_TEST(repro_rust_direct_scoped_function_value_is_exact_reference);
+ RUN_TEST(repro_csharp_exact_function_value_is_call_reference);
+ RUN_TEST(repro_csharp_member_method_group_is_exact_reference);
+ RUN_TEST(repro_csharp_parenthesized_method_group_is_exact_reference);
+ RUN_TEST(repro_csharp_generic_method_group_is_exact_reference);
+ RUN_TEST(repro_csharp_ambiguous_using_static_method_group_is_not_precise);
+ RUN_TEST(repro_cuda_exact_function_value_is_call_reference);
+ RUN_TEST(repro_exact_function_value_lsp_sites);
+ RUN_TEST(repro_typescript_exact_bound_method_is_call_reference);
+ RUN_TEST(repro_tsx_exact_bound_method_is_call_reference);
+ RUN_TEST(repro_perl_exact_coderef_is_call_reference);
+ RUN_TEST(repro_go_cross_file_exact_function_value_is_call_reference);
+ RUN_TEST(repro_python_cross_file_exact_function_value_is_call_reference);
+ RUN_TEST(repro_python_aliased_import_function_value_is_call_reference);
+ RUN_TEST(repro_python_alias_equal_module_leaf_targets_imported_member);
+ RUN_TEST(repro_rust_cross_file_exact_function_value_is_call_reference);
+ RUN_TEST(repro_csharp_cross_file_exact_function_value_is_call_reference);
+ RUN_TEST(repro_csharp_cross_file_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_kotlin_cross_file_callable_alias_invocation_targets_exact_value);
+ RUN_TEST(repro_csharp_callable_alias_argument_is_exact_reference);
+ RUN_TEST(repro_kotlin_callable_alias_argument_is_exact_reference);
+ RUN_TEST(repro_kotlin_receiver_bound_alias_invocation_targets_exact_method);
+ RUN_TEST(repro_kotlin_unknown_imported_property_is_not_callable_reference);
+ RUN_TEST(repro_javascript_complex_function_value_stays_usage);
+ RUN_TEST(repro_typescript_complex_function_value_stays_usage);
+ RUN_TEST(repro_tsx_complex_function_value_stays_usage);
+ RUN_TEST(repro_go_complex_function_value_stays_usage);
+ RUN_TEST(repro_python_complex_function_value_stays_usage);
+ RUN_TEST(repro_c_complex_function_value_stays_usage);
+ RUN_TEST(repro_cpp_complex_function_value_stays_usage);
+ RUN_TEST(repro_cuda_complex_function_value_stays_usage);
+ RUN_TEST(repro_rust_complex_function_value_stays_usage);
+ RUN_TEST(repro_csharp_complex_function_value_stays_usage);
+ RUN_TEST(repro_java_complex_method_reference_stays_usage);
+ RUN_TEST(repro_kotlin_complex_callable_reference_stays_usage);
+ RUN_TEST(repro_php_complex_first_class_callable_stays_usage);
+ RUN_TEST(repro_perl_conditional_coderefs_stay_usage);
+ RUN_TEST(repro_c_ambiguous_alias_reassignment_drops_stale_target);
+ RUN_TEST(repro_c_conditional_alias_reassignment_drops_stale_target);
+ RUN_TEST(repro_c_noncallable_shadow_blocks_outer_alias_target);
+ RUN_TEST(repro_cpp_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_cuda_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_go_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_python_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_rust_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_rust_unconditional_alias_reassignment_tracks_new_exact_target);
+ RUN_TEST(repro_kotlin_conditional_alias_reference_fails_closed);
+ RUN_TEST(repro_csharp_conditional_alias_reference_fails_closed);
+}
diff --git a/tests/repro/repro_runner.h b/tests/repro/repro_runner.h
new file mode 100644
index 000000000..cf6ad933d
--- /dev/null
+++ b/tests/repro/repro_runner.h
@@ -0,0 +1,6 @@
+#ifndef CBM_TESTS_REPRO_RUNNER_H
+#define CBM_TESTS_REPRO_RUNNER_H
+
+int cbm_suite_enabled(const char *name);
+
+#endif
diff --git a/tests/repro/repro_runner_filter.c b/tests/repro/repro_runner_filter.c
new file mode 100644
index 000000000..e13387fcd
--- /dev/null
+++ b/tests/repro/repro_runner_filter.c
@@ -0,0 +1,130 @@
+/* Reproductions for the cumulative repro runner itself. */
+#include "test_framework.h"
+#include "repro_runner.h"
+#include "foundation/compat.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int selector_delimiter(char value) {
+ return value == ',' || value == ' ' || value == '\t' || value == '\r' || value == '\n';
+}
+
+static int suite_name_contains_token(const char *name, const char *token, size_t token_len) {
+ size_t name_len = strlen(name);
+ if (token_len > name_len) {
+ return 0;
+ }
+ for (size_t offset = 0; offset + token_len <= name_len; offset++) {
+ if (strncmp(name + offset, token, token_len) == 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int cbm_suite_enabled(const char *name) {
+ const char *only = getenv("CBM_REPRO_ONLY");
+ if (!only || !*only) {
+ return 1;
+ }
+
+ const char *cursor = only;
+ while (*cursor) {
+ while (*cursor && selector_delimiter(*cursor)) {
+ cursor++;
+ }
+ const char *token = cursor;
+ while (*cursor && !selector_delimiter(*cursor)) {
+ cursor++;
+ }
+ size_t token_len = (size_t)(cursor - token);
+ if (token_len > 0 && suite_name_contains_token(name, token, token_len)) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static char *save_selector(void) {
+ const char *prior = getenv("CBM_REPRO_ONLY");
+ return prior ? cbm_strdup(prior) : NULL;
+}
+
+static void restore_selector(char *saved) {
+ if (saved) {
+ cbm_setenv("CBM_REPRO_ONLY", saved, 1);
+ free(saved);
+ } else {
+ cbm_unsetenv("CBM_REPRO_ONLY");
+ }
+}
+
+/* The documented selector accepts suite-name substrings. */
+TEST(repro_runner_filter_accepts_suite_substring) {
+ char *saved = save_selector();
+ cbm_setenv("CBM_REPRO_ONLY", "call_argument", 1);
+ int enabled = cbm_suite_enabled("repro_call_argument_usages");
+ restore_selector(saved);
+ if (!enabled)
+ fprintf(stderr, " [repro-filter] invariant=suite_substring_not_matched\n");
+ ASSERT_TRUE(enabled);
+ PASS();
+}
+
+TEST(repro_runner_filter_accepts_comma_list) {
+ char *saved = save_selector();
+ cbm_setenv("CBM_REPRO_ONLY", "language_registry,call_argument", 1);
+ int first = cbm_suite_enabled("repro_language_registry");
+ int second = cbm_suite_enabled("repro_call_argument_usages");
+ restore_selector(saved);
+ if (!first || !second)
+ fprintf(stderr, " [repro-filter] invariant=comma_list_not_matched\n");
+ ASSERT_TRUE(first && second);
+ PASS();
+}
+
+TEST(repro_runner_filter_accepts_space_list) {
+ char *saved = save_selector();
+ cbm_setenv("CBM_REPRO_ONLY", "language_registry call_argument", 1);
+ int first = cbm_suite_enabled("repro_language_registry");
+ int second = cbm_suite_enabled("repro_call_argument_usages");
+ restore_selector(saved);
+ if (!first || !second)
+ fprintf(stderr, " [repro-filter] invariant=space_list_not_matched\n");
+ ASSERT_TRUE(first && second);
+ PASS();
+}
+
+TEST(repro_runner_filter_rejects_nonmatch) {
+ char *saved = save_selector();
+ cbm_setenv("CBM_REPRO_ONLY", "language_registry", 1);
+ int enabled = cbm_suite_enabled("repro_call_argument_usages");
+ restore_selector(saved);
+ if (enabled)
+ fprintf(stderr, " [repro-filter] invariant=nonmatch_enabled\n");
+ ASSERT_FALSE(enabled);
+ PASS();
+}
+
+TEST(repro_runner_filter_unset_or_empty_enables_all) {
+ char *saved = save_selector();
+ cbm_unsetenv("CBM_REPRO_ONLY");
+ int unset_enabled = cbm_suite_enabled("repro_call_argument_usages");
+ cbm_setenv("CBM_REPRO_ONLY", "", 1);
+ int empty_enabled = cbm_suite_enabled("repro_call_argument_usages");
+ restore_selector(saved);
+ if (!unset_enabled || !empty_enabled)
+ fprintf(stderr, " [repro-filter] invariant=unset_or_empty_disabled\n");
+ ASSERT_TRUE(unset_enabled && empty_enabled);
+ PASS();
+}
+
+SUITE(repro_runner_filter) {
+ RUN_TEST(repro_runner_filter_accepts_suite_substring);
+ RUN_TEST(repro_runner_filter_accepts_comma_list);
+ RUN_TEST(repro_runner_filter_accepts_space_list);
+ RUN_TEST(repro_runner_filter_rejects_nonmatch);
+ RUN_TEST(repro_runner_filter_unset_or_empty_enables_all);
+}
diff --git a/tests/repro/repro_runner_passing_semantics.sh b/tests/repro/repro_runner_passing_semantics.sh
new file mode 100644
index 000000000..b52ee68e4
--- /dev/null
+++ b/tests/repro/repro_runner_passing_semantics.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# The compiled repro runner must not claim every passing control is a fixed bug.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+RUNNER="$PROJECT_ROOT/build/c/test-repro-runner"
+
+if [[ ! -x "$RUNNER" ]]; then
+ printf '[repro-runner-semantics] invariant=runner_missing path=%s\n' "$RUNNER" >&2
+ exit 1
+fi
+
+set +e
+output="$(CBM_REPRO_ONLY=repro_runner_filter "$RUNNER" 2>&1)"
+status=$?
+set -e
+
+if [[ $status -ne 0 ]]; then
+ printf '[repro-runner-semantics] invariant=control_suite_failed status=%d\n' "$status" >&2
+ exit 1
+fi
+
+old_claim='A row that PASSES means that bug appears FIXED'
+if [[ "$output" == *"$old_claim"* ]]; then
+ printf '[repro-runner-semantics] invariant=passing_controls_blanket_fixed old_claim=true\n' >&2
+ exit 1
+fi
+
+neutral_claim='PASS rows may be controls or candidate fixes'
+if [[ "$output" != *"$neutral_claim"* ]]; then
+ printf '[repro-runner-semantics] invariant=neutral_passing_semantics_missing\n' >&2
+ exit 1
+fi
+
+printf '[repro-runner-semantics] compiled runner reports neutral passing semantics\n'
diff --git a/tests/repro/repro_runner_zero_selection.sh b/tests/repro/repro_runner_zero_selection.sh
new file mode 100644
index 000000000..a4a048ffc
--- /dev/null
+++ b/tests/repro/repro_runner_zero_selection.sh
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Reproduce the compiled repro runner returning success when a selector matches
+# no suite. This protects direct `make test-repro`, not only scripts/repro.sh.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+RUNNER="$PROJECT_ROOT/build/c/test-repro-runner"
+
+if [[ ! -x "$RUNNER" ]]; then
+ printf '[repro-runner-zero] invariant=runner_missing path=%s\n' "$RUNNER" >&2
+ exit 1
+fi
+
+set +e
+output="$(CBM_REPRO_ONLY='__cbm_no_such_repro_suite__' "$RUNNER" 2>&1)"
+status=$?
+set -e
+
+if [[ $status -eq 0 ]]; then
+ printf '[repro-runner-zero] invariant=compiled_runner_accepted_zero_tests status=%d\n' \
+ "$status" >&2
+ exit 1
+fi
+
+expected='bug-repro runner executed zero tests'
+if [[ "$output" != *"$expected"* ]]; then
+ printf '[repro-runner-zero] invariant=zero_test_diagnostic_missing status=%d\n' \
+ "$status" >&2
+ exit 1
+fi
+
+printf '[repro-runner-zero] compiled runner rejected zero tests correctly\n'
diff --git a/tests/repro/repro_script_missing_summary.sh b/tests/repro/repro_script_missing_summary.sh
new file mode 100644
index 000000000..f930b26da
--- /dev/null
+++ b/tests/repro/repro_script_missing_summary.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+# Reproduce scripts/repro.sh exiting through `set -e -o pipefail` before its
+# explicit build/runner diagnostic when the transcript has no aggregate line.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-missing-summary.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt" "$TMP_ROOT/summary.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+# Model a compile/link failure: make emits a useful error but the test runner
+# never reaches its final aggregate summary.
+make() {
+ printf '%s\n' 'clang: error: linker command failed with exit code 1'
+ return 2
+}
+export -f make
+
+set +e
+output="$(TMPDIR="$TMP_ROOT" CC=true CXX=true GITHUB_STEP_SUMMARY="$TMP_ROOT/summary.txt" \
+ bash "$TMP_ROOT/scripts/repro.sh" 2>&1)"
+status=$?
+set -e
+
+if [[ $status -eq 0 ]]; then
+ printf '[repro-missing-summary] invariant=build_failure_accepted status=%d\n' "$status" >&2
+ exit 1
+fi
+
+linker_marker='clang: error: linker command failed with exit code 1'
+if [[ "$output" != *"$linker_marker"* ]]; then
+ printf '[repro-missing-summary] invariant=mocked_linker_failure_not_observed status=%d\n' \
+ "$status" >&2
+ exit 1
+fi
+
+expected='::error::bug-repro runner did not execute — build or link failure'
+if [[ "$output" != *"$expected"* ]]; then
+ printf '[repro-missing-summary] invariant=explicit_diagnostic_missing status=%d\n' \
+ "$status" >&2
+ exit 1
+fi
+
+printf '[repro-missing-summary] missing aggregate rejected with explicit diagnostic\n'
diff --git a/tests/repro/repro_script_no_workspace_artifact.sh b/tests/repro/repro_script_no_workspace_artifact.sh
new file mode 100644
index 000000000..598743f3a
--- /dev/null
+++ b/tests/repro/repro_script_no_workspace_artifact.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+# Reproduce scripts/repro.sh leaving its generated runner transcript in the
+# repository root after a completed board run.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-artifact.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt" "$TMP_ROOT/summary.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+make() {
+ printf '%s\n' \
+ '────────────────────────────────────────────' \
+ ' 1 passed'
+ return 0
+}
+export -f make
+
+TMPDIR="$TMP_ROOT" CC=true CXX=true GITHUB_STEP_SUMMARY="$TMP_ROOT/summary.txt" \
+ bash "$TMP_ROOT/scripts/repro.sh" >/dev/null 2>&1
+
+if [[ -e "$TMP_ROOT/repro-out.txt" ]]; then
+ printf '[repro-artifact] invariant=workspace_transcript_left_behind path=repro-out.txt\n' >&2
+ exit 1
+fi
+
+printf '[repro-artifact] workspace transcript cleaned correctly\n'
diff --git a/tests/repro/repro_script_skipped_summary.sh b/tests/repro/repro_script_skipped_summary.sh
new file mode 100644
index 000000000..c19650377
--- /dev/null
+++ b/tests/repro/repro_script_skipped_summary.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# Reproduce scripts/repro.sh treating the board as successful even though the
+# test framework's valid final aggregate reports one or more skipped tests.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-skipped.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt" "$TMP_ROOT/summary.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+# TEST_SUMMARY appends the skipped count after pass/fail counts. The board must
+# parse and report the aggregate faithfully, but it must exit nonzero because a
+# board with skipped cases is incomplete.
+make() {
+ printf '%s\n' \
+ '[SUITE] repro_parallel_determinism 0 passed, 2 skipped' \
+ '[SUITE] repro_call_argument_usages 1 passed, 17 failed' \
+ '────────────────────────────────────────────' \
+ ' 1 passed, 17 failed, 2 skipped'
+ return 1
+}
+export -f make
+
+set +e
+output="$(TMPDIR="$TMP_ROOT" CC=true CXX=true GITHUB_STEP_SUMMARY="$TMP_ROOT/summary.txt" \
+ bash "$TMP_ROOT/scripts/repro.sh" 2>&1)"
+status=$?
+set -e
+
+expected_prefix='=== bug-repro board: 17 reproduced (RED), 1 '
+if [[ "$output" != *"$expected_prefix"* ]]; then
+ actual="$(printf '%s\n' "$output" | grep '^=== bug-repro board:' || true)"
+ printf '[repro-skipped] invariant=skipped_aggregate_misreported expected=17/1 actual=%s\n' \
+ "${actual:-missing}" >&2
+ exit 1
+fi
+
+skip_summary='- **2** case(s) SKIPPED — board is incomplete'
+if ! grep -Fq -- "$skip_summary" "$TMP_ROOT/summary.txt"; then
+ printf '[repro-skipped] invariant=skipped_count_hidden expected=2\n' >&2
+ exit 1
+fi
+
+skip_warning='::warning::bug-repro board incomplete — 2 case(s) skipped'
+if [[ "$output" != *"$skip_warning"* ]]; then
+ printf '[repro-skipped] invariant=skipped_warning_hidden expected=2\n' >&2
+ exit 1
+fi
+
+if [[ $status -eq 0 ]]; then
+ printf '[repro-skipped] invariant=incomplete_board_exited_zero expected=nonzero actual=0\n' >&2
+ exit 1
+fi
+
+printf '[repro-skipped] skipped aggregate reported and rejected correctly\n'
diff --git a/tests/repro/repro_script_stderr_summary.sh b/tests/repro/repro_script_stderr_summary.sh
new file mode 100644
index 000000000..7fa9bd2ef
--- /dev/null
+++ b/tests/repro/repro_script_stderr_summary.sh
@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+# Reproduce the no-GITHUB_STEP_SUMMARY fallback writing through /dev/stderr,
+# which can be denied even though the process already has a valid stderr FD.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-stderr.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+make() {
+ printf '%s\n' \
+ '────────────────────────────────────────────' \
+ ' 1 passed, 1 failed'
+ return 1
+}
+export -f make
+
+set +e
+output="$(
+ unset GITHUB_STEP_SUMMARY
+ TMPDIR="$TMP_ROOT" CC=true CXX=true bash "$TMP_ROOT/scripts/repro.sh" 2>&1
+)"
+status=$?
+set -e
+
+if [[ $status -ne 0 ]]; then
+ printf '[repro-stderr] invariant=fallback_run_failed status=%d\n' "$status" >&2
+ exit 1
+fi
+if [[ "$output" == *'Operation not permitted'* ]]; then
+ printf '[repro-stderr] invariant=stderr_fallback_permission_denied\n' >&2
+ exit 1
+fi
+if [[ "$output" != *'## Bug-reproduction board'* ||
+ "$output" != *'**1** open bug(s) still reproduced'* ]]; then
+ printf '[repro-stderr] invariant=stderr_summary_missing\n' >&2
+ exit 1
+fi
+
+printf '[repro-stderr] summary written through stderr correctly\n'
diff --git a/tests/repro/repro_script_summary.sh b/tests/repro/repro_script_summary.sh
new file mode 100644
index 000000000..1a5ef9bd6
--- /dev/null
+++ b/tests/repro/repro_script_summary.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+# Reproduce scripts/repro.sh selecting the first per-suite count instead of the
+# final cumulative total when more than one repro suite runs, while ensuring
+# known-green controls are not blanket-labeled as candidate fixes.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-board.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt" "$TMP_ROOT/summary.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+# The copied production script calls make. This test-local function supplies a
+# deterministic runner transcript while exercising the production board parser.
+make() {
+ printf '%s\n' \
+ '[SUITE] repro_known_green_controls 2 passed' \
+ '[SUITE] repro_runner_filter 0 passed, 1 failed' \
+ '[SUITE] repro_call_argument_usages 0 passed, 17 failed' \
+ '────────────────────────────────────────────' \
+ ' 2 passed, 18 failed'
+ return 1
+}
+export -f make
+
+set +e
+output="$(TMPDIR="$TMP_ROOT" CC=true CXX=true GITHUB_STEP_SUMMARY="$TMP_ROOT/summary.txt" \
+ bash "$TMP_ROOT/scripts/repro.sh" 2>&1)"
+status=$?
+set -e
+
+if [[ $status -ne 0 ]]; then
+ printf '[repro-board] invariant=production_script_did_not_complete status=%d\n' "$status" >&2
+ exit 1
+fi
+
+expected_prefix='=== bug-repro board: 18 reproduced (RED), 2 '
+if [[ "$output" != *"$expected_prefix"* ]]; then
+ actual="$(printf '%s\n' "$output" | grep '^=== bug-repro board:' || true)"
+ printf '[repro-board] invariant=cumulative_total_not_reported expected=18/2 actual=%s\n' \
+ "${actual:-missing}" >&2
+ exit 1
+fi
+
+neutral_label='passing control(s) or candidate-fix candidate(s)'
+if [[ "$output" != *"$neutral_label"* ]] ||
+ ! grep -Fq -- "$neutral_label" "$TMP_ROOT/summary.txt"; then
+ actual="$(printf '%s\n' "$output" | grep '^=== bug-repro board:' || true)"
+ printf '[repro-board] invariant=passing_controls_blanket_candidate_fixed expected=%q actual=%s\n' \
+ "$neutral_label" "${actual:-missing}" >&2
+ exit 1
+fi
+
+if [[ "$output" == *'passing (candidate-fixed)'* ]] ||
+ grep -Fq -- 'PASSING — candidate-fixed' "$TMP_ROOT/summary.txt"; then
+ printf '[repro-board] invariant=passing_controls_blanket_candidate_fixed old_label_present=true\n' >&2
+ exit 1
+fi
+
+printf '[repro-board] cumulative total and neutral passing semantics reported correctly\n'
diff --git a/tests/repro/repro_script_zero_selection.sh b/tests/repro/repro_script_zero_selection.sh
new file mode 100644
index 000000000..00faeb1aa
--- /dev/null
+++ b/tests/repro/repro_script_zero_selection.sh
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+# Reproduce scripts/repro.sh accepting a selector/build transcript in which the
+# runner executes zero tests. A zero-test board proves neither red nor green and
+# must be treated as a runner failure.
+set -euo pipefail
+
+PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
+TMP_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/cbm-repro-zero.XXXXXX")"
+
+cleanup() {
+ rm -f "$TMP_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/env.sh"
+ rm -f "$TMP_ROOT/repro-out.txt" "$TMP_ROOT/summary.txt"
+ rmdir "$TMP_ROOT/scripts" "$TMP_ROOT" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+mkdir -p "$TMP_ROOT/scripts"
+cp "$PROJECT_ROOT/scripts/repro.sh" "$TMP_ROOT/scripts/repro.sh"
+cp "$PROJECT_ROOT/scripts/env.sh" "$TMP_ROOT/scripts/env.sh"
+
+# Supply the exact transcript produced when CBM_REPRO_ONLY matches no suite.
+make() {
+ printf '%s\n' \
+ '────────────────────────────────────────────' \
+ ' 0 passed'
+ return 0
+}
+export -f make
+
+set +e
+output="$(TMPDIR="$TMP_ROOT" CC=true CXX=true GITHUB_STEP_SUMMARY="$TMP_ROOT/summary.txt" \
+ bash "$TMP_ROOT/scripts/repro.sh" 2>&1)"
+status=$?
+set -e
+
+if [[ $status -eq 0 ]]; then
+ board="$(printf '%s\n' "$output" | grep '^=== bug-repro board:' || true)"
+ printf '[repro-zero] invariant=zero_tests_accepted status=%d board=%s\n' \
+ "$status" "${board:-missing}" >&2
+ exit 1
+fi
+
+if [[ "$output" != *'bug-repro runner executed zero tests'* ]]; then
+ printf '[repro-zero] invariant=zero_test_error_missing status=%d\n' "$status" >&2
+ exit 1
+fi
+
+printf '[repro-zero] zero-test transcript rejected correctly\n'
diff --git a/tests/repro/repro_ts_overload_return_chains.c b/tests/repro/repro_ts_overload_return_chains.c
new file mode 100644
index 000000000..ef8d0f8a8
--- /dev/null
+++ b/tests/repro/repro_ts_overload_return_chains.c
@@ -0,0 +1,514 @@
+/*
+ * repro_ts_overload_return_chains.c — REDs for argument-aware return typing
+ * of TypeScript/TSX overloads outside method dispatch.
+ *
+ * Both fixtures register two overloads with the same QN and arity but reversed
+ * positional types. They invoke both orders and assert distinct downstream
+ * method targets. A declaration-order, last-definition, or arity-only fallback
+ * can satisfy at most one chain; both become GREEN only when the call arguments
+ * select the return signature used by expression and contextual callback typing.
+ * Shadow and exact-import cases guard the selector's fail-closed boundaries.
+ *
+ * The shadowing fixtures use untyped parameters on purpose. An UNKNOWN local
+ * binding still owns the lexical name and must block both call-edge promotion
+ * and return-type inheritance from a same-named registry symbol.
+ */
+
+#include "test_framework.h"
+
+#include "arena.h"
+#include "cbm.h"
+#include "lsp/ts_lsp.h"
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+enum { OVERLOAD_DEF_COUNT = 7 };
+
+typedef struct {
+ const char *symbol_module_qn;
+ const char *caller_module_qn;
+ const char *reversed_type_qn;
+ const char *pair_type_qn;
+ const char *reversed_method_qn;
+ const char *pair_method_qn;
+ const char *choose_qn;
+ const char *run_qn;
+} TSOverloadFixtureNames;
+
+static const char *kNumberStringParams[] = {"number", "string"};
+static const char *kStringNumberParams[] = {"string", "number"};
+static const char *kNumberStringPairCallbackParams[] = {"number", "string",
+ "(value: Pair) => void"};
+static const char *kStringNumberReversedCallbackParams[] = {"string", "number",
+ "(value: Reversed) => void"};
+
+static bool ends_with(const char *text, const char *suffix) {
+ if (!text || !suffix)
+ return false;
+ size_t text_len = strlen(text);
+ size_t suffix_len = strlen(suffix);
+ return suffix_len <= text_len && strcmp(text + text_len - suffix_len, suffix) == 0;
+}
+
+static int count_resolved_suffix(const CBMResolvedCallArray *calls, const char *callee_suffix,
+ const char *strategy) {
+ if (!calls)
+ return 0;
+ int count = 0;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ if (call->kind == CBM_RESOLVED_INVOCATION && call->confidence >= 0.5f && call->caller_qn &&
+ strstr(call->caller_qn, "run") && ends_with(call->callee_qn, callee_suffix) &&
+ call->strategy && strcmp(call->strategy, strategy) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static int count_any_callee_suffix(const CBMResolvedCallArray *calls, const char *callee_suffix) {
+ if (!calls)
+ return 0;
+ int count = 0;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ if (call->caller_qn && strstr(call->caller_qn, "run") &&
+ ends_with(call->callee_qn, callee_suffix)) {
+ count++;
+ }
+ }
+ return count;
+}
+
+static void print_resolved_calls(const CBMResolvedCallArray *calls) {
+ if (!calls)
+ return;
+ for (int i = 0; i < calls->count; i++) {
+ const CBMResolvedCall *call = &calls->items[i];
+ printf(" %s -> %s [%s %.2f kind=%d]\n", call->caller_qn ? call->caller_qn : "(null)",
+ call->callee_qn ? call->callee_qn : "(null)",
+ call->strategy ? call->strategy : "(null)", call->confidence, (int)call->kind);
+ }
+}
+
+static void init_overload_defs(CBMLSPDef defs[OVERLOAD_DEF_COUNT], CBMLanguage language,
+ const TSOverloadFixtureNames *names) {
+ memset(defs, 0, (size_t)OVERLOAD_DEF_COUNT * sizeof(*defs));
+
+ defs[0].qualified_name = names->reversed_type_qn;
+ defs[0].short_name = "Reversed";
+ defs[0].label = "Interface";
+ defs[0].def_module_qn = names->symbol_module_qn;
+ defs[0].is_interface = true;
+ defs[0].lang = language;
+
+ defs[1].qualified_name = names->pair_type_qn;
+ defs[1].short_name = "Pair";
+ defs[1].label = "Interface";
+ defs[1].def_module_qn = names->symbol_module_qn;
+ defs[1].is_interface = true;
+ defs[1].lang = language;
+
+ defs[2].qualified_name = names->reversed_method_qn;
+ defs[2].short_name = "reversedOnly";
+ defs[2].label = "Method";
+ defs[2].receiver_type = names->reversed_type_qn;
+ defs[2].def_module_qn = names->symbol_module_qn;
+ defs[2].return_types = "void";
+ defs[2].lang = language;
+
+ defs[3].qualified_name = names->pair_method_qn;
+ defs[3].short_name = "pairOnly";
+ defs[3].label = "Method";
+ defs[3].receiver_type = names->pair_type_qn;
+ defs[3].def_module_qn = names->symbol_module_qn;
+ defs[3].return_types = "void";
+ defs[3].lang = language;
+
+ /* Same QN and arity; only ordered argument types distinguish these. */
+ defs[4].qualified_name = names->choose_qn;
+ defs[4].short_name = "choose";
+ defs[4].label = "Function";
+ defs[4].def_module_qn = names->symbol_module_qn;
+ defs[4].return_types = "Pair";
+ defs[4].signature_param_types = kNumberStringParams;
+ defs[4].signature_param_count = 2;
+ defs[4].lang = language;
+
+ defs[5].qualified_name = names->choose_qn;
+ defs[5].short_name = "choose";
+ defs[5].label = "Function";
+ defs[5].def_module_qn = names->symbol_module_qn;
+ defs[5].return_types = "Reversed";
+ defs[5].signature_param_types = kStringNumberParams;
+ defs[5].signature_param_count = 2;
+ defs[5].lang = language;
+
+ defs[6].qualified_name = names->run_qn;
+ defs[6].short_name = "run";
+ defs[6].label = "Function";
+ defs[6].def_module_qn = names->caller_module_qn;
+ defs[6].return_types = "void";
+ defs[6].lang = language;
+}
+
+static int assert_both_return_chains(const CBMResolvedCallArray *calls, const char *language_name,
+ const char *fixture_name, const char *inner_strategy) {
+ int inner_calls = count_resolved_suffix(calls, "choose", inner_strategy);
+ bool pair = count_resolved_suffix(calls, "Pair.pairOnly", "lsp_ts_method") > 0;
+ bool reversed = count_resolved_suffix(calls, "Reversed.reversedOnly", "lsp_ts_method") > 0;
+ if (inner_calls < 2 || !pair || !reversed) {
+ printf(" ts-overload-return: %s %s inner=%d pair=%d reversed=%d\n", language_name,
+ fixture_name, inner_calls, pair, reversed);
+ print_resolved_calls(calls);
+ }
+ return inner_calls >= 2 && pair && reversed ? 0 : 1;
+}
+
+static const char kFreeFunctionSource[] = "function run(): void {\n"
+ " choose(1, 'x').pairOnly();\n"
+ " choose('x', 1).reversedOnly();\n"
+ "}\n";
+
+static int assert_free_function_overload_returns(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.free",
+ "repro.free",
+ "repro.free.Reversed",
+ "repro.free.Pair",
+ "repro.free.Reversed.reversedOnly",
+ "repro.free.Pair.pairOnly",
+ "repro.free.choose",
+ "repro.free.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(&arena, kFreeFunctionSource,
+ (int)strlen(kFreeFunctionSource), names.caller_module_qn,
+ false, jsx_mode, false, registry, defs,
+ OVERLOAD_DEF_COUNT, NULL, NULL, 0, NULL, &calls);
+ }
+
+ int rc = registry
+ ? assert_both_return_chains(&calls, language_name, "free-function", "lsp_ts_local")
+ : 1;
+ if (!registry)
+ printf(" ts-overload-return: %s free-function registry build failed\n", language_name);
+ cbm_arena_destroy(&arena);
+ return rc;
+}
+
+static const char kNamespaceSource[] = "import * as Lib from './provider';\n"
+ "function run(): void {\n"
+ " Lib.choose(1, 'x').pairOnly();\n"
+ " Lib.choose('x', 1).reversedOnly();\n"
+ "}\n";
+
+static int assert_namespace_overload_returns(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.provider",
+ "repro.consumer",
+ "repro.provider.Reversed",
+ "repro.provider.Pair",
+ "repro.provider.Reversed.reversedOnly",
+ "repro.provider.Pair.pairOnly",
+ "repro.provider.choose",
+ "repro.consumer.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+ const char *import_names[] = {"Lib"};
+ const char *import_qns[] = {names.symbol_module_qn};
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(&arena, kNamespaceSource, (int)strlen(kNamespaceSource),
+ names.caller_module_qn, false, jsx_mode, false, registry,
+ defs, OVERLOAD_DEF_COUNT, import_names, import_qns, 1,
+ NULL, &calls);
+ }
+
+ int rc = registry ? assert_both_return_chains(&calls, language_name, "namespace-import",
+ "lsp_ts_namespace")
+ : 1;
+ if (!registry)
+ printf(" ts-overload-return: %s namespace registry build failed\n", language_name);
+ cbm_arena_destroy(&arena);
+ return rc;
+}
+
+static const char kExactSymbolImportSource[] = "import { choose } from './provider';\n"
+ "function run(): void {\n"
+ " choose(1, 'x').pairOnly();\n"
+ " choose('x', 1).reversedOnly();\n"
+ "}\n";
+
+static int assert_exact_symbol_import_overload_returns(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.exact.provider",
+ "repro.exact.consumer",
+ "repro.exact.provider.Reversed",
+ "repro.exact.provider.Pair",
+ "repro.exact.provider.Reversed.reversedOnly",
+ "repro.exact.provider.Pair.pairOnly",
+ "repro.exact.provider.choose",
+ "repro.exact.consumer.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+ const char *import_names[] = {"choose"};
+ /* Some production import maps already carry the exact exported-symbol QN.
+ * The call lookup must not append the local name a second time. */
+ const char *import_qns[] = {names.choose_qn};
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(
+ &arena, kExactSymbolImportSource, (int)strlen(kExactSymbolImportSource),
+ names.caller_module_qn, false, jsx_mode, false, registry, defs, OVERLOAD_DEF_COUNT,
+ import_names, import_qns, 1, NULL, &calls);
+ }
+
+ int chain_rc = registry ? assert_both_return_chains(&calls, language_name,
+ "exact-symbol-import", "lsp_ts_import")
+ : 1;
+ int doubled = count_any_callee_suffix(&calls, "choose.choose");
+ if (!registry || doubled != 0) {
+ printf(" ts-overload-return: %s exact-symbol-import registry=%d doubled=%d\n",
+ language_name, registry != NULL, doubled);
+ print_resolved_calls(&calls);
+ }
+ cbm_arena_destroy(&arena);
+ return registry && chain_rc == 0 && doubled == 0 ? 0 : 1;
+}
+
+static const char kContextualCallbackOverloadSource[] =
+ "function run(): void {\n"
+ " choose(1, 'x', value => value.pairOnly());\n"
+ " choose('x', 1, value => value.reversedOnly());\n"
+ "}\n";
+
+static int assert_contextual_callback_uses_selected_overload(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.callback",
+ "repro.callback",
+ "repro.callback.Reversed",
+ "repro.callback.Pair",
+ "repro.callback.Reversed.reversedOnly",
+ "repro.callback.Pair.pairOnly",
+ "repro.callback.choose",
+ "repro.callback.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+ defs[4].return_types = "void";
+ defs[4].signature_param_types = kNumberStringPairCallbackParams;
+ defs[4].signature_param_count = 3;
+ defs[5].return_types = "void";
+ defs[5].signature_param_types = kStringNumberReversedCallbackParams;
+ defs[5].signature_param_count = 3;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(&arena, kContextualCallbackOverloadSource,
+ (int)strlen(kContextualCallbackOverloadSource),
+ names.caller_module_qn, false, jsx_mode, false, registry,
+ defs, OVERLOAD_DEF_COUNT, NULL, NULL, 0, NULL, &calls);
+ }
+
+ int outer = count_resolved_suffix(&calls, "choose", "lsp_ts_local");
+ int pair = count_resolved_suffix(&calls, "Pair.pairOnly", "lsp_ts_method");
+ int reversed = count_resolved_suffix(&calls, "Reversed.reversedOnly", "lsp_ts_method");
+ if (!registry || outer < 2 || pair < 1 || reversed < 1) {
+ printf(" ts-overload-return: %s contextual-callback registry=%d outer=%d pair=%d "
+ "reversed=%d\n",
+ language_name, registry != NULL, outer, pair, reversed);
+ print_resolved_calls(&calls);
+ }
+ cbm_arena_destroy(&arena);
+ return registry && outer >= 2 && pair >= 1 && reversed >= 1 ? 0 : 1;
+}
+
+static int assert_no_shadowed_return_chains(const CBMResolvedCallArray *calls,
+ const char *language_name, const char *fixture_name,
+ const char *forbidden_strategy) {
+ int promoted = count_resolved_suffix(calls, "choose", forbidden_strategy);
+ int pair = count_resolved_suffix(calls, "Pair.pairOnly", "lsp_ts_method");
+ int reversed = count_resolved_suffix(calls, "Reversed.reversedOnly", "lsp_ts_method");
+ if (promoted != 0 || pair != 0 || reversed != 0) {
+ printf(" ts-overload-return: %s %s promoted=%d pair=%d reversed=%d\n", language_name,
+ fixture_name, promoted, pair, reversed);
+ print_resolved_calls(calls);
+ }
+ return promoted == 0 && pair == 0 && reversed == 0 ? 0 : 1;
+}
+
+static const char kShadowedFreeFunctionSource[] = "function run(choose): void {\n"
+ " choose(1, 'x').pairOnly();\n"
+ " choose('x', 1).reversedOnly();\n"
+ "}\n";
+
+static int assert_parameter_shadows_free_function(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.shadow.free",
+ "repro.shadow.free",
+ "repro.shadow.free.Reversed",
+ "repro.shadow.free.Pair",
+ "repro.shadow.free.Reversed.reversedOnly",
+ "repro.shadow.free.Pair.pairOnly",
+ "repro.shadow.free.choose",
+ "repro.shadow.free.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(&arena, kShadowedFreeFunctionSource,
+ (int)strlen(kShadowedFreeFunctionSource),
+ names.caller_module_qn, false, jsx_mode, false, registry,
+ defs, OVERLOAD_DEF_COUNT, NULL, NULL, 0, NULL, &calls);
+ }
+
+ int rc = registry ? assert_no_shadowed_return_chains(&calls, language_name,
+ "parameter-shadows-free-function",
+ "lsp_ts_local")
+ : 1;
+ if (!registry)
+ printf(" ts-overload-return: %s free shadow registry build failed\n", language_name);
+ cbm_arena_destroy(&arena);
+ return rc;
+}
+
+static const char kShadowedNamespaceSource[] = "import * as Lib from './provider';\n"
+ "function run(Lib): void {\n"
+ " Lib.choose(1, 'x').pairOnly();\n"
+ " Lib.choose('x', 1).reversedOnly();\n"
+ "}\n";
+
+static int assert_parameter_shadows_namespace(CBMLanguage language, bool jsx_mode,
+ const char *language_name) {
+ static const TSOverloadFixtureNames names = {
+ "repro.shadow.provider",
+ "repro.shadow.consumer",
+ "repro.shadow.provider.Reversed",
+ "repro.shadow.provider.Pair",
+ "repro.shadow.provider.Reversed.reversedOnly",
+ "repro.shadow.provider.Pair.pairOnly",
+ "repro.shadow.provider.choose",
+ "repro.shadow.consumer.run",
+ };
+ CBMLSPDef defs[OVERLOAD_DEF_COUNT];
+ init_overload_defs(defs, language, &names);
+ const char *import_names[] = {"Lib"};
+ const char *import_qns[] = {names.symbol_module_qn};
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = cbm_ts_build_cross_registry(&arena, defs, OVERLOAD_DEF_COUNT);
+ CBMResolvedCallArray calls = {0};
+ if (registry) {
+ cbm_run_ts_lsp_cross_with_registry(
+ &arena, kShadowedNamespaceSource, (int)strlen(kShadowedNamespaceSource),
+ names.caller_module_qn, false, jsx_mode, false, registry, defs, OVERLOAD_DEF_COUNT,
+ import_names, import_qns, 1, NULL, &calls);
+ }
+
+ int rc = registry ? assert_no_shadowed_return_chains(&calls, language_name,
+ "parameter-shadows-namespace",
+ "lsp_ts_namespace")
+ : 1;
+ if (!registry)
+ printf(" ts-overload-return: %s namespace shadow registry build failed\n", language_name);
+ cbm_arena_destroy(&arena);
+ return rc;
+}
+
+TEST(repro_ts_free_function_overload_returns_typescript) {
+ return assert_free_function_overload_returns(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_ts_free_function_overload_returns_tsx) {
+ return assert_free_function_overload_returns(CBM_LANG_TSX, true, "TSX");
+}
+
+TEST(repro_ts_namespace_overload_returns_typescript) {
+ return assert_namespace_overload_returns(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_ts_namespace_overload_returns_tsx) {
+ return assert_namespace_overload_returns(CBM_LANG_TSX, true, "TSX");
+}
+
+TEST(repro_ts_exact_symbol_import_overload_returns_typescript) {
+ return assert_exact_symbol_import_overload_returns(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_ts_exact_symbol_import_overload_returns_tsx) {
+ return assert_exact_symbol_import_overload_returns(CBM_LANG_TSX, true, "TSX");
+}
+
+TEST(repro_ts_contextual_callback_uses_selected_overload_typescript) {
+ return assert_contextual_callback_uses_selected_overload(CBM_LANG_TYPESCRIPT, false,
+ "TypeScript");
+}
+
+TEST(repro_ts_contextual_callback_uses_selected_overload_tsx) {
+ return assert_contextual_callback_uses_selected_overload(CBM_LANG_TSX, true, "TSX");
+}
+
+TEST(repro_ts_parameter_shadows_free_function_typescript) {
+ return assert_parameter_shadows_free_function(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_ts_parameter_shadows_free_function_tsx) {
+ return assert_parameter_shadows_free_function(CBM_LANG_TSX, true, "TSX");
+}
+
+TEST(repro_ts_parameter_shadows_namespace_typescript) {
+ return assert_parameter_shadows_namespace(CBM_LANG_TYPESCRIPT, false, "TypeScript");
+}
+
+TEST(repro_ts_parameter_shadows_namespace_tsx) {
+ return assert_parameter_shadows_namespace(CBM_LANG_TSX, true, "TSX");
+}
+
+SUITE(repro_ts_overload_return_chains) {
+ RUN_TEST(repro_ts_free_function_overload_returns_typescript);
+ RUN_TEST(repro_ts_free_function_overload_returns_tsx);
+ RUN_TEST(repro_ts_namespace_overload_returns_typescript);
+ RUN_TEST(repro_ts_namespace_overload_returns_tsx);
+ RUN_TEST(repro_ts_exact_symbol_import_overload_returns_typescript);
+ RUN_TEST(repro_ts_exact_symbol_import_overload_returns_tsx);
+ RUN_TEST(repro_ts_contextual_callback_uses_selected_overload_typescript);
+ RUN_TEST(repro_ts_contextual_callback_uses_selected_overload_tsx);
+ RUN_TEST(repro_ts_parameter_shadows_free_function_typescript);
+ RUN_TEST(repro_ts_parameter_shadows_free_function_tsx);
+ RUN_TEST(repro_ts_parameter_shadows_namespace_typescript);
+ RUN_TEST(repro_ts_parameter_shadows_namespace_tsx);
+}
diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.c
index e3c1dfb4d..f05cb5962 100644
--- a/tests/test_c_lsp.c
+++ b/tests/test_c_lsp.c
@@ -26,7 +26,9 @@
#include "lsp/ts_lsp.h"
#include "lsp/go_lsp.h"
#include "lsp/type_registry.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "arena.h"
+#include "preprocessor.h"
#include <stdio.h>
#include <stdlib.h>
@@ -62,6 +64,13 @@ static CBMFileResult *extract_cpp(const char *src) {
return cbm_extract_file(src, (int)strlen(src), CBM_LANG_CPP, "test", "main.cpp", 0, NULL, NULL);
}
+static CBMFileResult *extract_c_family(const char *src, CBMLanguage language) {
+ const char *path = language == CBM_LANG_C ? "main.c"
+ : language == CBM_LANG_CUDA ? "main.cu"
+ : "main.cpp";
+ return cbm_extract_file(src, (int)strlen(src), language, "test", path, 0, NULL, NULL);
+}
+
TEST(clsp_simple_var_decl) {
CBMFileResult *r = extract_c("\n"
"struct Foo {\n"
@@ -572,17 +581,18 @@ TEST(clsp_nocrash_template_extra_call_args) {
}
TEST(clsp_nocrash_template_function_multi_param_nested_call) {
- CBMFileResult *r = extract_cpp("\n"
- "void right_aligned_text(int color, int width, const char* fmt, float value) {}\n"
- "\n"
- "template<typename T, typename R = float>\n"
- "R format_units(T value, const char*& unit) { return value; }\n"
- "\n"
- "void f() {\n"
- " const char* unit = nullptr;\n"
- " right_aligned_text(0, 0, \"%.1f\", format_units(1, unit));\n"
- "}\n"
- "");
+ CBMFileResult *r = extract_cpp(
+ "\n"
+ "void right_aligned_text(int color, int width, const char* fmt, float value) {}\n"
+ "\n"
+ "template<typename T, typename R = float>\n"
+ "R format_units(T value, const char*& unit) { return value; }\n"
+ "\n"
+ "void f() {\n"
+ " const char* unit = nullptr;\n"
+ " right_aligned_text(0, 0, \"%.1f\", format_units(1, unit));\n"
+ "}\n"
+ "");
ASSERT_NOT_NULL(r);
ASSERT_GTE(find_resolved(r, "f", "right_aligned_text"), 0);
ASSERT_GTE(find_resolved(r, "f", "format_units"), 0);
@@ -6367,7 +6377,10 @@ TEST(clsp_cross_gap_new_then_method_chain) {
ASSERT_GTE(find_resolved(r, "test", "Service.Service"), 0);
ASSERT_GTE(find_resolved(r, "test", "start"), 0);
ASSERT_GTE(find_resolved(r, "test", "stop"), 0);
- ASSERT_GTE(find_resolved(r, "test", "~Service"), 0);
+ /* Service declares no destructor node. Explicit delete retains its
+ * semantic-only carrier, but the resolver must not fabricate an implicit
+ * ~Service target that the graph cannot materialize. */
+ ASSERT_EQ(find_resolved(r, "test", "~Service"), -1);
cbm_free_result(r);
PASS();
}
@@ -7292,7 +7305,10 @@ TEST(clsp_pattern_auto_ptr_from_new) {
ASSERT_NOT_NULL(r);
ASSERT_GTE(find_resolved(r, "test", "draw"), 0);
ASSERT_GTE(find_resolved(r, "test", "Widget.Widget"), 0);
- ASSERT_GTE(find_resolved(r, "test", "~Widget"), 0);
+ /* Widget has only an implicit destructor, so delete cannot resolve to a
+ * concrete graph target. A declared ~Widget is covered by the dedicated
+ * explicit-destructor test. */
+ ASSERT_EQ(find_resolved(r, "test", "~Widget"), -1);
cbm_free_result(r);
PASS();
}
@@ -15370,7 +15386,7 @@ TEST(seal_py_shared_registry_readonly) {
const char *src = "def helper(x):\n return x + 1\n\ndef caller():\n return helper(1)\n";
CBMResolvedCallArray out = {0};
cbm_run_py_lsp_cross_with_registry(&arena, src, (int)strlen(src), "test.mod", reg, NULL, NULL,
- 0, NULL, &out);
+ 0, NULL, &out, NULL);
ASSERT_EQ(reg->func_count, fb);
ASSERT_EQ(reg->type_count, tb);
cbm_arena_destroy(&arena);
@@ -15436,8 +15452,8 @@ TEST(seal_py_shared_registry_readonly_fields) {
" def m(self):\n"
" self.x = 1\n";
CBMResolvedCallArray out = {0};
- cbm_run_py_lsp_cross_with_registry(&arena, src, (int)strlen(src), "test.mod", reg, NULL, NULL, 0,
- NULL, &out);
+ cbm_run_py_lsp_cross_with_registry(&arena, src, (int)strlen(src), "test.mod", reg, NULL, NULL,
+ 0, NULL, &out, NULL);
/* The sealed registry entry must be untouched by resolve. */
int count_after = 0;
@@ -15502,7 +15518,547 @@ TEST(seal_go_shared_registry_readonly) {
PASS();
}
+static int assert_cpp_family_repeated_method_occurrences(CBMLanguage language) {
+ static const char source[] = "struct Alpha { int render() { return 1; } };\n"
+ "struct Bravo { int render() { return 2; } };\n"
+ "int occurrence_probe() {\n"
+ " Alpha alpha;\n"
+ " Bravo bravo;\n"
+ " return alpha.render() + bravo.render();\n"
+ "}\n";
+ static const char *call_texts[2] = {"alpha.render()", "bravo.render()"};
+ const char *sites[2] = {strstr(source, call_texts[0]), strstr(source, call_texts[1])};
+ ASSERT_NOT_NULL(sites[0]);
+ ASSERT_NOT_NULL(sites[1]);
+ uint32_t starts[2] = {(uint32_t)(sites[0] - source), (uint32_t)(sites[1] - source)};
+ uint32_t ends[2] = {starts[0] + (uint32_t)strlen(call_texts[0]),
+ starts[1] + (uint32_t)strlen(call_texts[1])};
+
+ CBMFileResult *result = extract_c_family(source, language);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *calls[2] = {NULL, NULL};
+ const CBMResolvedCall *semantics[2] = {NULL, NULL};
+ int carrier_count = 0;
+ int semantic_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "occurrence_probe") ||
+ !call->callee_name || strcmp(cbm_lsp_bare_segment(call->callee_name), "render") != 0) {
+ continue;
+ }
+ carrier_count++;
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (call->site_start_byte == starts[occurrence] &&
+ call->site_end_byte == ends[occurrence]) {
+ calls[occurrence] = call;
+ }
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0.0f ||
+ !resolved->caller_qn || !strstr(resolved->caller_qn, "occurrence_probe") ||
+ !resolved->callee_qn ||
+ strcmp(cbm_lsp_bare_segment(resolved->callee_qn), "render") != 0) {
+ continue;
+ }
+ semantic_count++;
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (resolved->site_start_byte == starts[occurrence] &&
+ resolved->site_end_byte == ends[occurrence]) {
+ semantics[occurrence] = resolved;
+ }
+ }
+ }
+
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_NOT_NULL(calls[0]);
+ ASSERT_NOT_NULL(calls[1]);
+ ASSERT_NOT_NULL(semantics[0]);
+ ASSERT_NOT_NULL(semantics[1]);
+ ASSERT_NOT_NULL(strstr(semantics[0]->callee_qn, "Alpha.render"));
+ ASSERT_NOT_NULL(strstr(semantics[1]->callee_qn, "Bravo.render"));
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[0], false) ==
+ semantics[0]);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[1], false) ==
+ semantics[1]);
+ cbm_free_result(result);
+ return 0;
+}
+
+TEST(clsp_cpp_repeated_same_leaf_calls_join_exact_occurrences) {
+ return assert_cpp_family_repeated_method_occurrences(CBM_LANG_CPP);
+}
+
+TEST(clsp_cuda_repeated_same_leaf_calls_join_exact_occurrences) {
+ return assert_cpp_family_repeated_method_occurrences(CBM_LANG_CUDA);
+}
+
+TEST(clsp_c_reassigned_function_pointer_calls_join_exact_occurrences) {
+ static const char source[] = "static int alpha_target(void) { return 1; }\n"
+ "static int bravo_target(void) { return 2; }\n"
+ "int occurrence_probe(void) {\n"
+ " int (*fp)(void) = alpha_target;\n"
+ " int first = fp();\n"
+ " fp = bravo_target;\n"
+ " return first + fp();\n"
+ "}\n";
+ static const char call_text[] = "fp()";
+ const char *first_site = strstr(source, call_text);
+ const char *second_site = first_site ? strstr(first_site + 1, call_text) : NULL;
+ ASSERT_NOT_NULL(first_site);
+ ASSERT_NOT_NULL(second_site);
+ uint32_t starts[2] = {(uint32_t)(first_site - source), (uint32_t)(second_site - source)};
+ uint32_t ends[2] = {starts[0] + (uint32_t)strlen(call_text),
+ starts[1] + (uint32_t)strlen(call_text)};
+
+ CBMFileResult *result = extract_c_family(source, CBM_LANG_C);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *calls[2] = {NULL, NULL};
+ const CBMResolvedCall *semantics[2] = {NULL, NULL};
+ int carrier_count = 0;
+ int semantic_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "occurrence_probe") ||
+ !call->callee_name || strcmp(call->callee_name, "fp") != 0) {
+ continue;
+ }
+ carrier_count++;
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (call->site_start_byte == starts[occurrence] &&
+ call->site_end_byte == ends[occurrence]) {
+ calls[occurrence] = call;
+ }
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0.0f ||
+ !resolved->caller_qn || !strstr(resolved->caller_qn, "occurrence_probe") ||
+ !resolved->reason || strcmp(resolved->reason, "fp") != 0) {
+ continue;
+ }
+ semantic_count++;
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (resolved->site_start_byte == starts[occurrence] &&
+ resolved->site_end_byte == ends[occurrence]) {
+ semantics[occurrence] = resolved;
+ }
+ }
+ }
+
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_NOT_NULL(calls[0]);
+ ASSERT_NOT_NULL(calls[1]);
+ ASSERT_NOT_NULL(semantics[0]);
+ ASSERT_NOT_NULL(semantics[1]);
+ ASSERT_NOT_NULL(strstr(semantics[0]->callee_qn, "alpha_target"));
+ ASSERT_NOT_NULL(strstr(semantics[1]->callee_qn, "bravo_target"));
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[0], false) ==
+ semantics[0]);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[1], false) ==
+ semantics[1]);
+ cbm_free_result(result);
+ PASS();
+}
+
+TEST(clsp_c_nested_function_pointer_shadow_restores_outer_target) {
+ static const char source[] = "static int alpha_target(void) { return 1; }\n"
+ "static int bravo_target(void) { return 2; }\n"
+ "int occurrence_probe(void) {\n"
+ " int (*fp)(void) = alpha_target;\n"
+ " int inner = 0;\n"
+ " {\n"
+ " int (*fp)(void) = bravo_target;\n"
+ " inner = fp();\n"
+ " }\n"
+ " return inner + fp();\n"
+ "}\n";
+ const char *inner_site = strstr(source, "fp();");
+ const char *outer_site = inner_site ? strstr(inner_site + 1, "fp();") : NULL;
+ ASSERT_NOT_NULL(inner_site);
+ ASSERT_NOT_NULL(outer_site);
+ uint32_t inner_start = (uint32_t)(inner_site - source);
+ uint32_t outer_start = (uint32_t)(outer_site - source);
+ uint32_t call_len = (uint32_t)strlen("fp()");
+
+ CBMFileResult *result = extract_c_family(source, CBM_LANG_C);
+ ASSERT_NOT_NULL(result);
+ const CBMResolvedCall *inner_semantic = NULL;
+ const CBMResolvedCall *outer_semantic = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || !resolved->reason ||
+ strcmp(resolved->reason, "fp") != 0 || !resolved->callee_qn) {
+ continue;
+ }
+ if (resolved->site_start_byte == inner_start &&
+ resolved->site_end_byte == inner_start + call_len) {
+ inner_semantic = resolved;
+ }
+ if (resolved->site_start_byte == outer_start &&
+ resolved->site_end_byte == outer_start + call_len) {
+ outer_semantic = resolved;
+ }
+ }
+ ASSERT_NOT_NULL(inner_semantic);
+ ASSERT_NOT_NULL(outer_semantic);
+ ASSERT_NOT_NULL(strstr(inner_semantic->callee_qn, "bravo_target"));
+ ASSERT_NOT_NULL(strstr(outer_semantic->callee_qn, "alpha_target"));
+ cbm_free_result(result);
+ PASS();
+}
+
+TEST(clsp_cpp_new_expression_joins_exact_occurrence) {
+ static const char source[] = "struct Widget { Widget() {} };\n"
+ "Widget* occurrence_probe() { return new Widget(); }\n";
+ const char *site = strstr(source, "new Widget()");
+ ASSERT_NOT_NULL(site);
+ uint32_t start = (uint32_t)(site - source);
+ uint32_t end = start + (uint32_t)strlen("new Widget()");
+
+ CBMFileResult *result = extract_c_family(source, CBM_LANG_CPP);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *carrier = NULL;
+ const CBMResolvedCall *semantic = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->site_start_byte == start && call->site_end_byte == end) {
+ carrier = call;
+ break;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->callee_qn &&
+ strstr(resolved->callee_qn, "Widget.Widget") && resolved->site_start_byte == start &&
+ resolved->site_end_byte == end) {
+ semantic = resolved;
+ break;
+ }
+ }
+ ASSERT_NOT_NULL(carrier);
+ ASSERT_NOT_NULL(semantic);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, carrier, false) ==
+ semantic);
+ cbm_free_result(result);
+ PASS();
+}
+
+TEST(clsp_c_global_initializer_does_not_inherit_previous_function_caller) {
+ static const char source[] = "int helper(void) { return 1; }\n"
+ "void previous(void) {}\n"
+ "int global_value = helper();\n";
+ const char *site = strrchr(source, 'h');
+ ASSERT_NOT_NULL(site);
+ ASSERT_STR_EQ(site, "helper();\n");
+ uint32_t start = (uint32_t)(site - source);
+ uint32_t end = start + (uint32_t)strlen("helper()");
+
+ CBMFileResult *result = extract_c_family(source, CBM_LANG_C);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *carrier = NULL;
+ const CBMResolvedCall *semantic = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->site_start_byte == start && call->site_end_byte == end) {
+ carrier = call;
+ break;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->callee_qn &&
+ strstr(resolved->callee_qn, "helper") && resolved->site_start_byte == start &&
+ resolved->site_end_byte == end) {
+ semantic = resolved;
+ break;
+ }
+ }
+ ASSERT_NOT_NULL(carrier);
+ ASSERT_NOT_NULL(semantic);
+ ASSERT_STR_EQ(semantic->caller_qn, carrier->enclosing_func_qn);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, carrier, false) ==
+ semantic);
+ cbm_free_result(result);
+ PASS();
+}
+
+static int assert_cpp_family_preprocessed_collision_isolated(CBMLanguage language) {
+ /* simplecpp removes the 41-byte comment payload and normalizes tokens. As
+ * verified by the non-vacuity assertions below, raw alpha.render and the
+ * macro-hidden expanded bravo.render both land at numeric span 182:200,
+ * even though those offsets refer to different source texts. */
+ static const char source[] =
+ "struct Alpha { int render(){return 1;} };\n"
+ "struct Bravo { int render(){return 2;} };\n"
+ "int occurrence_probe(){\n"
+ " Alpha alpha; Bravo bravo;\n"
+ " /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/ alpha . render ( );\n"
+ "#define HIDDEN_RENDER(x) x.render()\n"
+ " return HIDDEN_RENDER(bravo);\n"
+ "}\n";
+ const uint32_t collision_start = 182;
+ const uint32_t collision_end = 200;
+ ASSERT_EQ((uint32_t)(strstr(source, "alpha . render ( )") - source), collision_start);
+
+ CBMFileResult *result = extract_c_family(source, language);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *raw_alpha = NULL;
+ const CBMCall *expanded_bravo = NULL;
+ int colliding_carriers = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "occurrence_probe") ||
+ call->site_start_byte != collision_start || call->site_end_byte != collision_end ||
+ !call->callee_name || !strstr(call->callee_name, "render")) {
+ continue;
+ }
+ colliding_carriers++;
+ if (strstr(call->callee_name, "alpha")) {
+ raw_alpha = call;
+ }
+ if (strstr(call->callee_name, "bravo")) {
+ expanded_bravo = call;
+ }
+ }
+ ASSERT_EQ(colliding_carriers, 2);
+ ASSERT_NOT_NULL(raw_alpha);
+ ASSERT_NOT_NULL(expanded_bravo);
+
+ const CBMResolvedCall *raw_alpha_semantic = NULL;
+ const CBMResolvedCall *expanded_bravo_semantic = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0.0f ||
+ resolved->site_start_byte != collision_start ||
+ resolved->site_end_byte != collision_end || !resolved->callee_qn) {
+ continue;
+ }
+ if (strstr(resolved->callee_qn, "Alpha.render")) {
+ raw_alpha_semantic = resolved;
+ }
+ if (strstr(resolved->callee_qn, "Bravo.render")) {
+ expanded_bravo_semantic = resolved;
+ }
+ }
+ ASSERT_NOT_NULL(raw_alpha_semantic);
+ ASSERT_NOT_NULL(expanded_bravo_semantic);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, raw_alpha, false) ==
+ raw_alpha_semantic);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&result->resolved_calls, expanded_bravo, false) ==
+ expanded_bravo_semantic);
+ cbm_free_result(result);
+ return 0;
+}
+
+TEST(clsp_cpp_preprocessed_coordinate_collision_isolated) {
+ return assert_cpp_family_preprocessed_collision_isolated(CBM_LANG_CPP);
+}
+
+TEST(clsp_cuda_preprocessed_coordinate_collision_isolated) {
+ return assert_cpp_family_preprocessed_collision_isolated(CBM_LANG_CUDA);
+}
+
+TEST(clsp_c_preprocessed_coordinate_collision_isolated) {
+ /* The raw fp call and macro-hidden expanded fp call both occupy 206:212,
+ * but data flow resolves them to different targets. */
+ static const char source[] =
+ "static int alpha_target(void){return 1;}\n"
+ "static int bravo_target(void){return 2;}\n"
+ "int occurrence_probe(void){\n"
+ " int (*fp)(void) = alpha_target;\n"
+ " /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/ fp ( );\n"
+ "#define HIDDEN_FP_CALL() (fp = bravo_target, fp())\n"
+ " return HIDDEN_FP_CALL();\n"
+ "}\n";
+ const uint32_t collision_start = 206;
+ const uint32_t collision_end = 212;
+ const char *raw_probe = strstr(source, "occurrence_probe");
+ ASSERT_NOT_NULL(raw_probe);
+ ASSERT_EQ((uint32_t)(strstr(raw_probe, "fp ( )") - source), collision_start);
+
+ CBMFileResult *result = extract_c_family(source, CBM_LANG_C);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *colliding_calls[2] = {NULL, NULL};
+ int colliding_carriers = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "occurrence_probe") &&
+ call->callee_name && strcmp(call->callee_name, "fp") == 0 &&
+ call->site_start_byte == collision_start && call->site_end_byte == collision_end) {
+ if (colliding_carriers < 2) {
+ colliding_calls[colliding_carriers] = call;
+ }
+ colliding_carriers++;
+ }
+ }
+ ASSERT_EQ(colliding_carriers, 2);
+ ASSERT_NOT_NULL(colliding_calls[0]);
+ ASSERT_NOT_NULL(colliding_calls[1]);
+
+ const CBMResolvedCall *alpha_semantic = NULL;
+ const CBMResolvedCall *bravo_semantic = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0.0f ||
+ resolved->site_start_byte != collision_start ||
+ resolved->site_end_byte != collision_end || !resolved->callee_qn || !resolved->reason ||
+ strcmp(resolved->reason, "fp") != 0) {
+ continue;
+ }
+ if (strstr(resolved->callee_qn, "alpha_target")) {
+ alpha_semantic = resolved;
+ }
+ if (strstr(resolved->callee_qn, "bravo_target")) {
+ bravo_semantic = resolved;
+ }
+ }
+ ASSERT_NOT_NULL(alpha_semantic);
+ ASSERT_NOT_NULL(bravo_semantic);
+ const CBMResolvedCall *first_join =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, colliding_calls[0], false);
+ const CBMResolvedCall *second_join =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, colliding_calls[1], false);
+ ASSERT_TRUE((first_join == alpha_semantic && second_join == bravo_semantic) ||
+ (first_join == bravo_semantic && second_join == alpha_semantic));
+ cbm_free_result(result);
+ PASS();
+}
+
+TEST(clsp_preprocessed_destructor_rewrite_respects_origin_during_rewrite) {
+ /* Calibrate the comment padding against simplecpp itself: comments vanish
+ * from the expanded buffer, so one padding length makes the raw
+ * `delete alpha` and macro-expanded `delete bravo` occupy the same numeric
+ * byte span. The names intentionally have equal length.
+ *
+ * The raw destructor carrier is rewritten during the first C-LSP walk. On
+ * the second walk, a preprocessed carrier must be stamped PREPROCESSED
+ * before c_rewrite_proved_destructor_candidates compares it with the
+ * already-present raw semantic rows. Otherwise the earlier raw ~Alpha row
+ * wins this colliding occurrence and rewrites the expanded carrier to the
+ * wrong destructor. */
+ static const char format[] = "struct Alpha { ~Alpha(){} };\n"
+ "struct Bravo { ~Bravo(){} };\n"
+ "void occurrence_probe(){\n"
+ " Alpha* alpha = new Alpha(); Bravo* bravo = new Bravo();\n"
+ " /*%s*/ delete alpha;\n"
+ "#define HIDDEN_DELETE(p) delete p\n"
+ " HIDDEN_DELETE(bravo);\n"
+ "}\n";
+ char padding[1024] = {0};
+ char source[4096];
+ int written = snprintf(source, sizeof(source), format, padding);
+ ASSERT_GT(written, 0);
+ ASSERT_LT((size_t)written, sizeof(source));
+
+ char *expanded = cbm_preprocess(source, written, "main.cpp", NULL, NULL, true);
+ ASSERT_NOT_NULL(expanded);
+ const char *raw_alpha = strstr(source, "delete alpha");
+ const char *expanded_bravo = strstr(expanded, "delete bravo");
+ ASSERT_NOT_NULL(raw_alpha);
+ ASSERT_NOT_NULL(expanded_bravo);
+ ptrdiff_t raw_offset = raw_alpha - source;
+ ptrdiff_t expanded_offset = expanded_bravo - expanded;
+ cbm_preprocess_free(expanded);
+ ASSERT_GTE(expanded_offset, raw_offset);
+ size_t padding_length = (size_t)(expanded_offset - raw_offset);
+ ASSERT_LT(padding_length, sizeof(padding));
+
+ memset(padding, 'x', padding_length);
+ padding[padding_length] = '\0';
+ written = snprintf(source, sizeof(source), format, padding);
+ ASSERT_GT(written, 0);
+ ASSERT_LT((size_t)written, sizeof(source));
+
+ expanded = cbm_preprocess(source, written, "main.cpp", NULL, NULL, true);
+ ASSERT_NOT_NULL(expanded);
+ raw_alpha = strstr(source, "delete alpha");
+ expanded_bravo = strstr(expanded, "delete bravo");
+ ASSERT_NOT_NULL(raw_alpha);
+ ASSERT_NOT_NULL(expanded_bravo);
+ const uint32_t collision_start = (uint32_t)(raw_alpha - source);
+ ASSERT_EQ((uint32_t)(expanded_bravo - expanded), collision_start);
+ const uint32_t collision_end = collision_start + (uint32_t)strlen("delete alpha");
+ cbm_preprocess_free(expanded);
+
+ CBMFileResult *result = extract_cpp(source);
+ ASSERT_NOT_NULL(result);
+ const CBMCall *raw_carrier = NULL;
+ const CBMCall *preprocessed_carrier = NULL;
+ const CBMResolvedCall *raw_semantic = NULL;
+ const CBMResolvedCall *preprocessed_semantic = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->requires_lsp_resolution || call->site_start_byte != collision_start ||
+ call->site_end_byte != collision_end) {
+ continue;
+ }
+ if (call->source_origin == CBM_SOURCE_ORIGIN_RAW) {
+ raw_carrier = call;
+ } else if (call->source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED) {
+ preprocessed_carrier = call;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || !resolved->strategy ||
+ strcmp(resolved->strategy, "lsp_destructor") != 0 || !resolved->callee_qn ||
+ resolved->site_start_byte != collision_start ||
+ resolved->site_end_byte != collision_end) {
+ continue;
+ }
+ if (resolved->source_origin == CBM_SOURCE_ORIGIN_RAW &&
+ strstr(resolved->callee_qn, "~Alpha")) {
+ raw_semantic = resolved;
+ } else if (resolved->source_origin == CBM_SOURCE_ORIGIN_PREPROCESSED &&
+ strstr(resolved->callee_qn, "~Bravo")) {
+ preprocessed_semantic = resolved;
+ }
+ }
+ ASSERT_NOT_NULL(raw_carrier);
+ ASSERT_NOT_NULL(preprocessed_carrier);
+ ASSERT_NOT_NULL(raw_semantic);
+ ASSERT_NOT_NULL(preprocessed_semantic);
+
+ bool raw_name_ok = raw_carrier->callee_name &&
+ strcmp(cbm_lsp_bare_segment(raw_carrier->callee_name), "~Alpha") == 0;
+ bool preprocessed_name_ok =
+ preprocessed_carrier->callee_name &&
+ strcmp(cbm_lsp_bare_segment(preprocessed_carrier->callee_name), "~Bravo") == 0;
+ bool raw_join_ok = cbm_pipeline_find_lsp_resolution(&result->resolved_calls, raw_carrier,
+ false) == raw_semantic;
+ bool preprocessed_join_ok =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, preprocessed_carrier, false) ==
+ preprocessed_semantic;
+ if (!raw_name_ok || !preprocessed_name_ok || !raw_join_ok || !preprocessed_join_ok) {
+ printf(" destructor origin rewrite diagnostic: raw=%s/%d preprocessed=%s/%d\n",
+ raw_carrier->callee_name ? raw_carrier->callee_name : "<null>", raw_join_ok,
+ preprocessed_carrier->callee_name ? preprocessed_carrier->callee_name : "<null>",
+ preprocessed_join_ok);
+ }
+ cbm_free_result(result);
+ ASSERT_TRUE(raw_name_ok);
+ ASSERT_TRUE(preprocessed_name_ok);
+ ASSERT_TRUE(raw_join_ok);
+ ASSERT_TRUE(preprocessed_join_ok);
+ PASS();
+}
+
SUITE(c_lsp) {
+ RUN_TEST(clsp_c_reassigned_function_pointer_calls_join_exact_occurrences);
+ RUN_TEST(clsp_c_nested_function_pointer_shadow_restores_outer_target);
+ RUN_TEST(clsp_cpp_repeated_same_leaf_calls_join_exact_occurrences);
+ RUN_TEST(clsp_cuda_repeated_same_leaf_calls_join_exact_occurrences);
+ RUN_TEST(clsp_cpp_new_expression_joins_exact_occurrence);
+ RUN_TEST(clsp_c_global_initializer_does_not_inherit_previous_function_caller);
+ RUN_TEST(clsp_c_preprocessed_coordinate_collision_isolated);
+ RUN_TEST(clsp_cpp_preprocessed_coordinate_collision_isolated);
+ RUN_TEST(clsp_cuda_preprocessed_coordinate_collision_isolated);
+ RUN_TEST(clsp_preprocessed_destructor_rewrite_respects_origin_during_rewrite);
RUN_TEST(clsp_tier2_shared_registry_readonly_c);
RUN_TEST(clsp_tier2_shared_registry_readonly_cpp);
RUN_TEST(seal_py_shared_registry_readonly);
diff --git a/tests/test_call_reference_contract.c b/tests/test_call_reference_contract.c
new file mode 100644
index 000000000..3a7b3acd1
--- /dev/null
+++ b/tests/test_call_reference_contract.c
@@ -0,0 +1,442 @@
+/* Production-graph contracts for callable values. These tests intentionally
+ * exercise the full MCP indexing path rather than only raw extraction/LSP rows. */
+#include "test_framework.h"
+#include "repro_harness.h"
+
+#include <store/store.h>
+
+#include <string.h>
+
+static int crc_edge_count(cbm_store_t *store, const char *project, const char *type,
+ const char *source_name, const char *target_label,
+ const char *target_name) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(store, project, type, &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ bool source_ok =
+ cbm_store_find_node_by_id(store, edges[i].source_id, &source) == CBM_STORE_OK;
+ bool target_ok =
+ cbm_store_find_node_by_id(store, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok && source.name && target.name &&
+ strcmp(source.name, source_name) == 0 && strcmp(target.name, target_name) == 0 &&
+ (!target_label || (target.label && strcmp(target.label, target_label) == 0))) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return matches;
+}
+
+static int crc_global_handler_edge_count(cbm_store_t *store, const char *project,
+ const char *caller) {
+ int references =
+ crc_edge_count(store, project, "CALL_REFERENCE", caller, "Function", "handler");
+ int calls = crc_edge_count(store, project, "CALLS", caller, "Function", "handler");
+ int usages = crc_edge_count(store, project, "USAGE", caller, "Function", "handler");
+ return references < 0 || calls < 0 || usages < 0 ? -1 : references + calls + usages;
+}
+
+static int crc_function_count(cbm_store_t *store, const char *project, const char *name) {
+ cbm_node_t *nodes = NULL;
+ int node_count = 0;
+ if (cbm_store_find_nodes_by_name(store, project, name, &nodes, &node_count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int functions = 0;
+ for (int i = 0; i < node_count; i++) {
+ if (nodes[i].label && strcmp(nodes[i].label, "Function") == 0) {
+ functions++;
+ }
+ }
+ cbm_store_free_nodes(nodes, node_count);
+ return functions;
+}
+
+TEST(call_reference_typescript_direct_argument_is_exact) {
+ static const char source[] = "function handler(): void {}\n"
+ "function register(callback: () => void): void {}\n"
+ "function bootstrap(): void { register(handler); }\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "main.ts", source);
+ ASSERT_NOT_NULL(store);
+ int registrar =
+ crc_edge_count(store, project.project, "CALLS", "bootstrap", "Function", "register");
+ int reference = crc_edge_count(store, project.project, "CALL_REFERENCE", "bootstrap",
+ "Function", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "bootstrap", "Function", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "bootstrap", "Function", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(registrar, 1);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_kotlin_alias_argument_is_exact) {
+ static const char source[] = "fun handler(): Unit {}\n"
+ "fun accept(callback: () -> Unit): Unit {}\n"
+ "val callback: () -> Unit = ::handler\n"
+ "fun argument(): Unit {\n"
+ " accept(callback)\n"
+ "}\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "AliasArgument.kt", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Function", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Function", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_use_before_local_shadow_is_not_global) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def caller():\n"
+ " accept(handler)\n"
+ " handler = lambda: None\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "shadow.py", source);
+ ASSERT_NOT_NULL(store);
+ int registrar = crc_edge_count(store, project.project, "CALLS", "caller", "Function", "accept");
+ int handler_nodes = crc_function_count(store, project.project, "handler");
+ int global_edges = crc_global_handler_edge_count(store, project.project, "caller");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(registrar, 1);
+ ASSERT_GTE(handler_nodes, 1);
+ ASSERT_EQ(global_edges, 0);
+ PASS();
+}
+
+TEST(call_reference_javascript_use_before_local_shadow_is_not_global) {
+ static const char source[] = "function handler() {}\n"
+ "function accept(callback) {}\n"
+ "function caller() {\n"
+ " accept(handler);\n"
+ " const handler = () => {};\n"
+ "}\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "shadow.js", source);
+ ASSERT_NOT_NULL(store);
+ int registrar = crc_edge_count(store, project.project, "CALLS", "caller", "Function", "accept");
+ int handler_nodes = crc_function_count(store, project.project, "handler");
+ int global_edges = crc_global_handler_edge_count(store, project.project, "caller");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(registrar, 1);
+ ASSERT_GTE(handler_nodes, 1);
+ ASSERT_EQ(global_edges, 0);
+ PASS();
+}
+
+TEST(call_reference_typescript_use_before_local_shadow_is_not_global) {
+ static const char source[] = "function handler(): void {}\n"
+ "function accept(callback: () => void): void {}\n"
+ "function caller(): void {\n"
+ " accept(handler);\n"
+ " const handler = (): void => {};\n"
+ "}\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "shadow.ts", source);
+ ASSERT_NOT_NULL(store);
+ int registrar = crc_edge_count(store, project.project, "CALLS", "caller", "Function", "accept");
+ int handler_nodes = crc_function_count(store, project.project, "handler");
+ int global_edges = crc_global_handler_edge_count(store, project.project, "caller");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(registrar, 1);
+ ASSERT_GTE(handler_nodes, 1);
+ ASSERT_EQ(global_edges, 0);
+ PASS();
+}
+
+TEST(call_reference_python_keyword_argument_is_exact) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def accept(callback=None):\n"
+ " pass\n"
+ "def argument():\n"
+ " accept(callback=handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "keyword.py", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Function", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Function", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_bound_method_argument_is_exact) {
+ static const char source[] = "class Service:\n"
+ " def handler(self):\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept(service.handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "bound.py", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Method", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Method", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_parenthesized_bound_method_is_exact) {
+ static const char source[] = "class Service:\n"
+ " def handler(self):\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept((service.handler))\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "parenthesized.py", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Method", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Method", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_instance_field_shadow_is_not_method) {
+ static const char source[] = "class Service:\n"
+ " def __init__(self):\n"
+ " self.handler = 42\n"
+ " def handler(self):\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept(service.handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "field_shadow.py", source);
+ ASSERT_NOT_NULL(store);
+ int method_reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Method", "handler");
+ int any_reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", NULL, "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", NULL, "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", NULL, "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(method_reference, 0);
+ ASSERT_EQ(any_reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_property_value_stays_usage) {
+ static const char source[] = "class Service:\n"
+ " @property\n"
+ " def handler(self) -> int:\n"
+ " return 42\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept(service.handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "property.py", source);
+ ASSERT_NOT_NULL(store);
+ int accept_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "accept");
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", NULL, "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", NULL, "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(accept_call, 1);
+ ASSERT_EQ(reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_unknown_decorated_value_stays_usage) {
+ static const char source[] = "def replace_with_value(function):\n"
+ " return 42\n"
+ "class Service:\n"
+ " @replace_with_value\n"
+ " def handler(self):\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept(service.handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "unknown_decorator.py", source);
+ ASSERT_NOT_NULL(store);
+ int accept_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "accept");
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", NULL, "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", NULL, "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(accept_call, 1);
+ ASSERT_EQ(reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_later_decorated_function_rebinding_stays_usage) {
+ static const char source[] = "def handler():\n"
+ " pass\n"
+ "def replace_with_value(function):\n"
+ " return 42\n"
+ "@replace_with_value\n"
+ "def handler():\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument():\n"
+ " accept(handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "function_rebinding.py", source);
+ ASSERT_NOT_NULL(store);
+ int accept_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "accept");
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", NULL, "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Function", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", NULL, "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(accept_call, 1);
+ ASSERT_EQ(reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_python_later_decorated_method_rebinding_stays_usage) {
+ static const char source[] = "def replace_with_value(function):\n"
+ " return 42\n"
+ "class Service:\n"
+ " def handler(self):\n"
+ " pass\n"
+ " @replace_with_value\n"
+ " def handler(self):\n"
+ " pass\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def argument(service: Service):\n"
+ " accept(service.handler)\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "method_rebinding.py", source);
+ ASSERT_NOT_NULL(store);
+ int accept_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Function", "accept");
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", NULL, "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", NULL, "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(accept_call, 1);
+ ASSERT_EQ(reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_go_bound_method_argument_is_exact) {
+ static const char source[] = "package refs\n"
+ "type Service struct{}\n"
+ "func (Service) handler() {}\n"
+ "func accept(callback func()) {}\n"
+ "func argument(service Service) { accept(service.handler) }\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "bound.go", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Method", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Method", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 1);
+ ASSERT_EQ(usage, 0);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+TEST(call_reference_go_ambiguous_promoted_method_stays_usage) {
+ static const char source[] = "package refs\n"
+ "type Alpha struct{}\n"
+ "func (Alpha) handler() {}\n"
+ "type Beta struct{}\n"
+ "func (Beta) handler() {}\n"
+ "type Service struct { Alpha; Beta }\n"
+ "func accept(callback func()) {}\n"
+ "func argument(service Service) { accept(service.handler) }\n";
+ RProj project;
+ cbm_store_t *store = rh_index(&project, "ambiguous.go", source);
+ ASSERT_NOT_NULL(store);
+ int reference =
+ crc_edge_count(store, project.project, "CALL_REFERENCE", "argument", "Method", "handler");
+ int usage = crc_edge_count(store, project.project, "USAGE", "argument", "Method", "handler");
+ int fabricated_call =
+ crc_edge_count(store, project.project, "CALLS", "argument", "Method", "handler");
+ rh_cleanup(&project, store);
+ ASSERT_EQ(reference, 0);
+ ASSERT_EQ(usage, 1);
+ ASSERT_EQ(fabricated_call, 0);
+ PASS();
+}
+
+SUITE(call_reference_contract) {
+ RUN_TEST(call_reference_typescript_direct_argument_is_exact);
+ RUN_TEST(call_reference_kotlin_alias_argument_is_exact);
+ RUN_TEST(call_reference_python_use_before_local_shadow_is_not_global);
+ RUN_TEST(call_reference_javascript_use_before_local_shadow_is_not_global);
+ RUN_TEST(call_reference_typescript_use_before_local_shadow_is_not_global);
+ RUN_TEST(call_reference_python_keyword_argument_is_exact);
+ RUN_TEST(call_reference_python_bound_method_argument_is_exact);
+ RUN_TEST(call_reference_python_parenthesized_bound_method_is_exact);
+ RUN_TEST(call_reference_python_instance_field_shadow_is_not_method);
+ RUN_TEST(call_reference_python_property_value_stays_usage);
+ RUN_TEST(call_reference_python_unknown_decorated_value_stays_usage);
+ RUN_TEST(call_reference_python_later_decorated_function_rebinding_stays_usage);
+ RUN_TEST(call_reference_python_later_decorated_method_rebinding_stays_usage);
+ RUN_TEST(call_reference_go_bound_method_argument_is_exact);
+ RUN_TEST(call_reference_go_ambiguous_promoted_method_stays_usage);
+}
diff --git a/tests/test_convergence_probe.c b/tests/test_convergence_probe.c
index b530f60ce..1c850d5c2 100644
--- a/tests/test_convergence_probe.c
+++ b/tests/test_convergence_probe.c
@@ -275,14 +275,36 @@ static int cp_callables(cbm_store_t *store, const char *project) {
}
/* Diagnostic edge histogram (stderr only, so test output stays clean). */
-static const char *CP_ALL_EDGE_TYPES[] = {
- "CALLS", "CONFIGURES", "CONTAINS_FILE", "CONTAINS_FOLDER",
- "DATA_FLOWS", "DECORATES", "DEFINES", "DEFINES_METHOD",
- "DEPENDS_ON", "FILE_CHANGES_WITH", "GRAPHQL_CALLS", "GRPC_CALLS",
- "HANDLES", "HTTP_CALLS", "IMPLEMENTS", "IMPORTS",
- "INHERITS", "INFRA_MAPS", "OVERRIDE", "READS",
- "SEMANTICALLY_RELATED", "SIMILAR_TO", "TESTS_FILE", "TESTS",
- "TRPC_CALLS", "USAGE", "ASYNC_CALLS", "WRITES", NULL};
+static const char *CP_ALL_EDGE_TYPES[] = {"CALLS",
+ "CALL_REFERENCE",
+ "CONFIGURES",
+ "CONTAINS_FILE",
+ "CONTAINS_FOLDER",
+ "DATA_FLOWS",
+ "DECORATES",
+ "DEFINES",
+ "DEFINES_METHOD",
+ "DEPENDS_ON",
+ "FILE_CHANGES_WITH",
+ "GRAPHQL_CALLS",
+ "GRPC_CALLS",
+ "HANDLES",
+ "HTTP_CALLS",
+ "IMPLEMENTS",
+ "IMPORTS",
+ "INHERITS",
+ "INFRA_MAPS",
+ "OVERRIDE",
+ "READS",
+ "SEMANTICALLY_RELATED",
+ "SIMILAR_TO",
+ "TESTS_FILE",
+ "TESTS",
+ "TRPC_CALLS",
+ "USAGE",
+ "ASYNC_CALLS",
+ "WRITES",
+ NULL};
static void cp_diag(cbm_store_t *store, const char *project, const char *label) {
if (!store) { fprintf(stderr, " [CP] %s: no graph DB\n", label); return; }
diff --git a/tests/test_cs_lsp.c b/tests/test_cs_lsp.c
index 912a4d961..6c111ca2d 100644
--- a/tests/test_cs_lsp.c
+++ b/tests/test_cs_lsp.c
@@ -25,6 +25,7 @@
#include "test_framework.h"
#include "cbm.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "lsp/cs_lsp.h"
#include <string.h>
@@ -1131,6 +1132,100 @@ TEST(cslsp_httpclient_chain) {
PASS();
}
+/* Two typed receivers can invoke the same method leaf in one caller. Each
+ * parser carrier and type-aware semantic result must retain the full,
+ * occurrence-specific call span so the bridge cannot join both calls to the
+ * first Render target (or let a legacy zero-span record hijack either one). */
+TEST(cslsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ static const char source[] = "class Alpha { public void Render() {} }\n"
+ "class Beta { public void Render() {} }\n"
+ "class OccurrenceProbe {\n"
+ " public void Run(Alpha alpha, Beta beta) {\n"
+ " alpha.Render();\n"
+ " beta.Render();\n"
+ " }\n"
+ "}\n";
+ static const char alpha_text[] = "alpha.Render()";
+ static const char beta_text[] = "beta.Render()";
+
+ const char *alpha_site = strstr(source, alpha_text);
+ const char *beta_site = strstr(source, beta_text);
+ ASSERT_NOT_NULL(alpha_site);
+ ASSERT_NOT_NULL(beta_site);
+ const uint32_t alpha_start = (uint32_t)(alpha_site - source);
+ const uint32_t alpha_end = alpha_start + (uint32_t)strlen(alpha_text);
+ const uint32_t beta_start = (uint32_t)(beta_site - source);
+ const uint32_t beta_end = beta_start + (uint32_t)strlen(beta_text);
+
+ CBMFileResult *r = extract_cs(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *alpha_call = NULL;
+ const CBMCall *beta_call = NULL;
+ int render_carriers = 0;
+ int zero_span_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "OccurrenceProbe.Run") ||
+ !call->callee_name || !strstr(call->callee_name, "Render")) {
+ continue;
+ }
+ render_carriers++;
+ if (call->site_end_byte <= call->site_start_byte)
+ zero_span_carriers++;
+ if (call->site_start_byte == alpha_start && call->site_end_byte == alpha_end)
+ alpha_call = call;
+ if (call->site_start_byte == beta_start && call->site_end_byte == beta_end)
+ beta_call = call;
+ }
+
+ ASSERT_EQ(render_carriers, 2);
+ ASSERT_EQ(zero_span_carriers, 0);
+ ASSERT_NOT_NULL(alpha_call);
+ ASSERT_NOT_NULL(beta_call);
+ ASSERT_TRUE(alpha_call != beta_call);
+
+ const CBMResolvedCall *alpha_semantic = NULL;
+ const CBMResolvedCall *beta_semantic = NULL;
+ int render_semantics = 0;
+ int zero_span_hijackers = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind != CBM_RESOLVED_INVOCATION || rc->confidence <= 0.0f || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "OccurrenceProbe.Run") || !rc->callee_qn ||
+ !strstr(rc->callee_qn, ".Render")) {
+ continue;
+ }
+ render_semantics++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_hijackers++;
+ if (strstr(rc->callee_qn, "Alpha.Render") && rc->site_start_byte == alpha_start &&
+ rc->site_end_byte == alpha_end) {
+ alpha_semantic = rc;
+ }
+ if (strstr(rc->callee_qn, "Beta.Render") && rc->site_start_byte == beta_start &&
+ rc->site_end_byte == beta_end) {
+ beta_semantic = rc;
+ }
+ }
+
+ ASSERT_EQ(render_semantics, 2);
+ ASSERT_EQ(zero_span_hijackers, 0);
+ ASSERT_NOT_NULL(alpha_semantic);
+ ASSERT_NOT_NULL(beta_semantic);
+ ASSERT_TRUE(alpha_semantic != beta_semantic);
+
+ const CBMResolvedCall *alpha_join =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, alpha_call, false);
+ const CBMResolvedCall *beta_join =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, beta_call, false);
+ ASSERT_TRUE(alpha_join == alpha_semantic);
+ ASSERT_TRUE(beta_join == beta_semantic);
+
+ cbm_free_result(r);
+ PASS();
+}
+
/* ── Suite ─────────────────────────────────────────────────── */
SUITE(cs_lsp) {
@@ -1194,4 +1289,5 @@ SUITE(cs_lsp) {
RUN_TEST(cslsp_using_static_console);
RUN_TEST(cslsp_stringbuilder_chain);
RUN_TEST(cslsp_httpclient_chain);
+ RUN_TEST(cslsp_ordinary_same_leaf_calls_join_by_exact_site);
}
diff --git a/tests/test_edge_structural.c b/tests/test_edge_structural.c
index af9f5bca0..947288124 100644
--- a/tests/test_edge_structural.c
+++ b/tests/test_edge_structural.c
@@ -238,14 +238,34 @@ static void es_lang_cleanup(ES_LangProj *lp, cbm_store_t *store) {
}
/* Every graph edge type the pipeline can emit — used in diagnostic dumps. */
-static const char *ES_ALL_EDGE_TYPES[] = {
- "CALLS", "CONFIGURES", "CONTAINS_FILE", "CONTAINS_FOLDER",
- "DATA_FLOWS", "DECORATES", "DEFINES", "DEFINES_METHOD",
- "DEPENDS_ON", "FILE_CHANGES_WITH", "GRAPHQL_CALLS", "GRPC_CALLS",
- "HANDLES", "HTTP_CALLS", "IMPLEMENTS", "IMPORTS",
- "INHERITS", "INFRA_MAPS", "OVERRIDE", "SEMANTICALLY_RELATED",
- "SIMILAR_TO", "TESTS_FILE", "TESTS", "TRPC_CALLS",
- "USAGE", "ASYNC_CALLS", NULL};
+static const char *ES_ALL_EDGE_TYPES[] = {"CALLS",
+ "CALL_REFERENCE",
+ "CONFIGURES",
+ "CONTAINS_FILE",
+ "CONTAINS_FOLDER",
+ "DATA_FLOWS",
+ "DECORATES",
+ "DEFINES",
+ "DEFINES_METHOD",
+ "DEPENDS_ON",
+ "FILE_CHANGES_WITH",
+ "GRAPHQL_CALLS",
+ "GRPC_CALLS",
+ "HANDLES",
+ "HTTP_CALLS",
+ "IMPLEMENTS",
+ "IMPORTS",
+ "INHERITS",
+ "INFRA_MAPS",
+ "OVERRIDE",
+ "SEMANTICALLY_RELATED",
+ "SIMILAR_TO",
+ "TESTS_FILE",
+ "TESTS",
+ "TRPC_CALLS",
+ "USAGE",
+ "ASYNC_CALLS",
+ NULL};
static void es_dump_edge_histogram(cbm_store_t *store, const char *project) {
if (!store) {
@@ -278,6 +298,40 @@ static int es_edge_present(const ES_LangFile *files, int nfiles, const char *edg
return got >= floor;
}
+static int es_exact_edge_by_name(const ES_LangFile *files, int nfiles, const char *edge_type,
+ const char *source_name, const char *target_name) {
+ ES_LangProj lp;
+ cbm_store_t *store = es_lang_index_files(&lp, files, nfiles);
+ cbm_node_t *sources = NULL;
+ cbm_node_t *targets = NULL;
+ int source_count = 0;
+ int target_count = 0;
+ int matches = -1;
+ if (store &&
+ cbm_store_find_nodes_by_name(store, lp.project, source_name, &sources, &source_count) ==
+ CBM_STORE_OK &&
+ cbm_store_find_nodes_by_name(store, lp.project, target_name, &targets, &target_count) ==
+ CBM_STORE_OK &&
+ source_count == 1 && target_count == 1) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_source_type(store, sources[0].id, edge_type, &edges,
+ &edge_count) == CBM_STORE_OK) {
+ matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ if (edges[i].target_id == targets[0].id) {
+ matches++;
+ }
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ }
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ es_lang_cleanup(&lp, store);
+ return matches;
+}
+
/* ══════════════════════════════════════════════════════════════════
* FAMILY 1: CALLS cross-file
*
@@ -744,16 +798,14 @@ TEST(es_decorates_attribute_csharp) {
* resolves in the registry. pass_usages.c handles this.
* ══════════════════════════════════════════════════════════════════ */
-/* Python cross-file USAGE: main.py uses a class from models.py. */
+/* Python constructor syntax is a CALLS edge to the materialized Class node. */
TEST(es_usage_crossfile_python) {
static const ES_LangFile f[] = {
{"models.py",
"class User:\n def __init__(self, name):\n self.name = name\n"},
{"main.py",
"from .models import User\n\n\ndef create_user(name):\n return User(name)\n"}};
- /* Uncertain: USAGE edges for type instantiation may or may not be
- * extracted for Python. Assert the correct outcome. */
- ASSERT_TRUE(es_edge_present(f, 2, "USAGE", 1));
+ ASSERT_EQ(es_exact_edge_by_name(f, 2, "CALLS", "create_user", "User"), 1);
PASS();
}
diff --git a/tests/test_edge_types_probe.c b/tests/test_edge_types_probe.c
index eae04fd96..f71091ae4 100644
--- a/tests/test_edge_types_probe.c
+++ b/tests/test_edge_types_probe.c
@@ -223,13 +223,11 @@ static cbm_store_t *et_index_parallel(EtProj *lp, const EtFile *meaningful, int
}
/* #1085: count CALLS edges whose target node has `name`, indexing via the
- * PARALLEL path (et_index_parallel pads to >50 files). The parallel resolver
- * used to drop the edge whenever the LSP resolved a callee but its target QN
- * wasn't a gbuf node (JSX component imported through a tsconfig `paths` alias:
- * the TS LSP resolves the element ref to an alias-path QN that never matches a
- * def node) — sequential kept the edge via the registry import_map fallback,
- * so the two pipelines disagreed and ~21% of a Next.js call graph vanished on
- * the default (parallel) path. Needs >50 files to reproduce. */
+ * PARALLEL path (et_index_parallel pads to >50 files). The per-file TS resolver
+ * used to treat a raw tsconfig alias as a confident target. That false row made
+ * the parallel driver skip cross-file resolution, then failed graph target
+ * materialization; the guarded JSX carrier correctly refused name-only
+ * fallback, so the relationship vanished. Needs >50 files to reproduce. */
static int et_calls_to_name_parallel(const EtFile *meaningful, int n_mean, const char *name) {
EtProj lp;
cbm_store_t *store = et_index_parallel(&lp, meaningful, n_mean);
@@ -267,15 +265,16 @@ TEST(calls_jsx_component_via_tsconfig_alias_parallel_issue1085) {
{"src/app/dashboard-b.tsx",
"import { KpiCard } from \"@/components/ui/kpi-card\";\n"
"export function DashboardB() {\n return <KpiCard label=\"b\" />;\n}\n"}};
- /* RED before the fix: 0 (parallel drops alias-JSX). GREEN: both renders
- * resolve, exactly as the sequential path already does. */
+ /* RED before the fix: 0 (parallel drops alias-JSX). GREEN: exactly one
+ * deduplicated edge from each dashboard render. */
int hits = et_calls_to_name_parallel(f, 4, "KpiCard");
- if (hits < 2) {
- fprintf(stderr, " [1085] FAIL CALLS->KpiCard on parallel path = %d (expected >= 2); "
- "alias-imported JSX component edges dropped\n",
+ if (hits != 2) {
+ fprintf(stderr,
+ " [1085] FAIL CALLS->KpiCard on parallel path = %d (expected 2); "
+ "alias-imported JSX component edges dropped\n",
hits);
}
- ASSERT_TRUE(hits >= 2);
+ ASSERT_EQ(hits, 2);
PASS();
}
diff --git a/tests/test_extraction.c b/tests/test_extraction.c
index 93a329984..6fa6d2b08 100644
--- a/tests/test_extraction.c
+++ b/tests/test_extraction.c
@@ -3932,6 +3932,87 @@ TEST(extract_wide_flat_file_is_linear) {
PASS();
}
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+/* A flat block of value-reference statements exercises occurrence-role
+ * classification for every identifier. The old parent/child field lookup
+ * restarts at the block's first child for each statement, so 8x more source
+ * produces about 64x more lookup work. Count work instead of wall time: this
+ * RED is deterministic, sanitizer-independent, and finishes quickly even on
+ * the known-quadratic implementation. */
+static uint64_t extract_wide_reference_field_work(int statement_count, int *out_usages,
+ uint64_t *out_slow_parent_fallbacks) {
+ static const char prefix[] = "function target() {}\nfunction wide() {\n";
+ static const char statement[] = " target;\n";
+ static const char suffix[] = "}\n";
+ size_t capacity = sizeof(prefix) + (size_t)statement_count * sizeof(statement) + sizeof(suffix);
+ char *source = malloc(capacity);
+ if (!source) {
+ return UINT64_MAX;
+ }
+ size_t offset = 0;
+ memcpy(source + offset, prefix, sizeof(prefix) - 1U);
+ offset += sizeof(prefix) - 1U;
+ for (int i = 0; i < statement_count; i++) {
+ memcpy(source + offset, statement, sizeof(statement) - 1U);
+ offset += sizeof(statement) - 1U;
+ }
+ memcpy(source + offset, suffix, sizeof(suffix));
+ offset += sizeof(suffix) - 1U;
+
+ cbm_usage_field_lookup_test_reset();
+ CBMFileResult *result = cbm_extract_file(source, (int)offset, CBM_LANG_JAVASCRIPT, "proj",
+ "wide-references.js", 0, NULL, NULL);
+ free(source);
+ if (!result) {
+ return UINT64_MAX;
+ }
+ int usages = 0;
+ for (int i = 0; i < result->usages.count; i++) {
+ if (result->usages.items[i].ref_name &&
+ strcmp(result->usages.items[i].ref_name, "target") == 0) {
+ usages++;
+ }
+ }
+ uint64_t work = cbm_usage_field_lookup_test_work();
+ *out_slow_parent_fallbacks = cbm_usage_slow_parent_fallback_test_count();
+ cbm_free_result(result);
+ *out_usages = usages;
+ return work;
+}
+
+TEST(extract_wide_flat_reference_fields_are_linear) {
+ enum { SMALL = 128, BIG = 1024, INPUT_GROWTH = 8, WORK_RATIO_MAX = 12 };
+ int small_usages = 0;
+ int big_usages = 0;
+ uint64_t small_slow_parent_fallbacks = 0;
+ uint64_t big_slow_parent_fallbacks = 0;
+ uint64_t small_work =
+ extract_wide_reference_field_work(SMALL, &small_usages, &small_slow_parent_fallbacks);
+ uint64_t big_work =
+ extract_wide_reference_field_work(BIG, &big_usages, &big_slow_parent_fallbacks);
+ ASSERT_TRUE(small_work != UINT64_MAX);
+ ASSERT_TRUE(big_work != UINT64_MAX);
+ ASSERT_EQ(small_usages, SMALL);
+ ASSERT_EQ(big_usages, BIG);
+ ASSERT_EQ(small_slow_parent_fallbacks, 0);
+ ASSERT_EQ(big_slow_parent_fallbacks, 0);
+ ASSERT_GTE(small_work, (uint64_t)SMALL);
+ fprintf(stderr, " [wide-reference-fields] work(%d)=%llu work(%d)=%llu input_growth=%dx\n",
+ SMALL, (unsigned long long)small_work, BIG, (unsigned long long)big_work, INPUT_GROWTH);
+ uint64_t maximum = small_work * WORK_RATIO_MAX + 256U;
+ if (big_work > maximum) {
+ char message[192];
+ snprintf(message, sizeof(message),
+ "wide-reference field lookup grew from %llu to %llu for %dx input "
+ "(maximum %dx + 256) -- quadratic sibling scan",
+ (unsigned long long)small_work, (unsigned long long)big_work, INPUT_GROWTH,
+ WORK_RATIO_MAX);
+ FAIL(message);
+ }
+ PASS();
+}
+#endif
+
/* ===================================================================
* Group H3: ObjectScript return type extraction
* =================================================================== */
@@ -4673,6 +4754,9 @@ SUITE(extraction) {
/* Wide-flat-file linearity (ms-typescript hang) */
RUN_TEST(extract_wide_flat_file_is_linear);
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+ RUN_TEST(extract_wide_flat_reference_fields_are_linear);
+#endif
/* Perl call-graph noise (#459 follow-up) */
RUN_TEST(extract_perl_config_string_not_a_callee);
diff --git a/tests/test_go_lsp.c b/tests/test_go_lsp.c
index a51f5d0f3..c77e5ee80 100644
--- a/tests/test_go_lsp.c
+++ b/tests/test_go_lsp.c
@@ -12,6 +12,7 @@
#include "test_framework.h"
#include "cbm.h"
#include "lsp/go_lsp.h"
+#include "pipeline/lsp_resolve.h"
/* ── Helpers ───────────────────────────────────────────────────── */
@@ -764,8 +765,270 @@ TEST(golsp_interface_method_field_chain) {
PASS();
}
+/* Parser-backed calls already carry their full call-expression spans. The Go
+ * semantic resolver must preserve the same occurrence identity; otherwise two
+ * same-leaf calls in one caller both join whichever Render record appears
+ * first in resolved_calls. Use concrete and ambiguous-interface dispatch so
+ * the targets are distinct under Go's existing flat concrete-method QN model. */
+TEST(golsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ const char *source = "package main\n\n"
+ "type Renderer interface { Render(label string) }\n\n"
+ "type A struct{}\n"
+ "func (A) Render(label string) {}\n\n"
+ "type B struct{}\n"
+ "func (B) Render(label string) {}\n\n"
+ "func run(a A, r Renderer) {\n"
+ "\ta.Render(\"alpha\")\n"
+ "\tr.Render(\"beta\")\n"
+ "}\n";
+ static const char a_text[] = "a.Render(\"alpha\")";
+ static const char b_text[] = "r.Render(\"beta\")";
+
+ const char *a_site = strstr(source, a_text);
+ const char *b_site = strstr(source, b_text);
+ ASSERT_NOT_NULL(a_site);
+ ASSERT_NOT_NULL(b_site);
+ uint32_t a_start = (uint32_t)(a_site - source);
+ uint32_t a_end = a_start + (uint32_t)strlen(a_text);
+ uint32_t b_start = (uint32_t)(b_site - source);
+ uint32_t b_end = b_start + (uint32_t)strlen(b_text);
+
+ CBMFileResult *r = extract_go(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *a_call = NULL;
+ const CBMCall *b_call = NULL;
+ int render_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "run") ||
+ !call->callee_name || !strstr(call->callee_name, "Render")) {
+ continue;
+ }
+ render_carriers++;
+ if (strstr(call->callee_name, "a.Render"))
+ a_call = call;
+ if (strstr(call->callee_name, "r.Render"))
+ b_call = call;
+ }
+
+ ASSERT_EQ(render_carriers, 2);
+ ASSERT_NOT_NULL(a_call);
+ ASSERT_NOT_NULL(b_call);
+ ASSERT_EQ(a_call->site_start_byte, a_start);
+ ASSERT_EQ(a_call->site_end_byte, a_end);
+ ASSERT_EQ(b_call->site_start_byte, b_start);
+ ASSERT_EQ(b_call->site_end_byte, b_end);
+ ASSERT_NEQ(a_call->site_start_byte, b_call->site_start_byte);
+
+ const CBMResolvedCall *a_semantic = NULL;
+ const CBMResolvedCall *b_semantic = NULL;
+ int render_semantics = 0;
+ int zero_span_hijackers = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind != CBM_RESOLVED_INVOCATION || rc->confidence <= 0.0f || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "run") || !rc->callee_qn || !strstr(rc->callee_qn, ".Render")) {
+ continue;
+ }
+ render_semantics++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_hijackers++;
+ if (rc->site_start_byte == a_start && rc->site_end_byte == a_end && rc->strategy &&
+ strcmp(rc->strategy, "lsp_type_dispatch") == 0) {
+ a_semantic = rc;
+ }
+ if (rc->site_start_byte == b_start && rc->site_end_byte == b_end && rc->strategy &&
+ strcmp(rc->strategy, "lsp_interface_dispatch") == 0 &&
+ strstr(rc->callee_qn, ".Renderer.Render")) {
+ b_semantic = rc;
+ }
+ }
+
+ ASSERT_EQ(render_semantics, 2);
+ ASSERT_EQ(zero_span_hijackers, 0);
+ ASSERT_NOT_NULL(a_semantic);
+ ASSERT_NOT_NULL(b_semantic);
+ ASSERT_TRUE(a_semantic != b_semantic);
+ ASSERT_NEQ(a_semantic->site_start_byte, b_semantic->site_start_byte);
+
+ const CBMResolvedCall *a_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, a_call, false);
+ const CBMResolvedCall *b_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, b_call, false);
+ ASSERT_NOT_NULL(a_joined);
+ ASSERT_NOT_NULL(b_joined);
+ ASSERT_TRUE(a_joined == a_semantic);
+ ASSERT_TRUE(b_joined == b_semantic);
+ ASSERT_TRUE(strcmp(a_joined->callee_qn, b_joined->callee_qn) != 0);
+ ASSERT_EQ(a_joined->site_start_byte, a_start);
+ ASSERT_EQ(a_joined->site_end_byte, a_end);
+ ASSERT_EQ(b_joined->site_start_byte, b_start);
+ ASSERT_EQ(b_joined->site_end_byte, b_end);
+
+ cbm_free_result(r);
+ PASS();
+}
+
/* ── Cross-file tests (use cbm_run_go_lsp_cross directly) ──────── */
+/* The production Go Tier-3 path promotes per-file unresolved records through
+ * registry lookups without another AST walk. That promotion must copy the
+ * original occurrence span: with the shared Render leaf, a zero-span promoted
+ * record is otherwise eligible for both textual carriers and hijacks one edge. */
+TEST(golsp_fast_crossfile_same_leaf_calls_preserve_exact_sites) {
+ const char *source = "package main\n\n"
+ "type A struct{}\n"
+ "type B struct{}\n\n"
+ "func run(a A, b B) {\n"
+ "\ta.Render(\"alpha\")\n"
+ "\tb.Render(\"beta\")\n"
+ "}\n";
+ static const char a_text[] = "a.Render(\"alpha\")";
+ static const char b_text[] = "b.Render(\"beta\")";
+
+ const char *a_site = strstr(source, a_text);
+ const char *b_site = strstr(source, b_text);
+ ASSERT_NOT_NULL(a_site);
+ ASSERT_NOT_NULL(b_site);
+ uint32_t a_start = (uint32_t)(a_site - source);
+ uint32_t a_end = a_start + (uint32_t)strlen(a_text);
+ uint32_t b_start = (uint32_t)(b_site - source);
+ uint32_t b_end = b_start + (uint32_t)strlen(b_text);
+
+ CBMFileResult *r = extract_go(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *a_call = NULL;
+ const CBMCall *b_call = NULL;
+ int render_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "run") ||
+ !call->callee_name || !strstr(call->callee_name, "Render")) {
+ continue;
+ }
+ render_carriers++;
+ if (strstr(call->callee_name, "a.Render"))
+ a_call = call;
+ if (strstr(call->callee_name, "b.Render"))
+ b_call = call;
+ }
+
+ ASSERT_EQ(render_carriers, 2);
+ ASSERT_NOT_NULL(a_call);
+ ASSERT_NOT_NULL(b_call);
+ ASSERT_EQ(a_call->site_start_byte, a_start);
+ ASSERT_EQ(a_call->site_end_byte, a_end);
+ ASSERT_EQ(b_call->site_start_byte, b_start);
+ ASSERT_EQ(b_call->site_end_byte, b_end);
+ ASSERT_NEQ(a_call->site_start_byte, b_call->site_start_byte);
+
+ int unresolved_render_semantics = 0;
+ const char *a_unresolved_qn = NULL;
+ const char *b_unresolved_qn = NULL;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->strategy && strcmp(rc->strategy, "lsp_unresolved") == 0 && rc->reason &&
+ strcmp(rc->reason, "method_not_found") == 0 && rc->caller_qn &&
+ strstr(rc->caller_qn, "run") && rc->callee_qn && strstr(rc->callee_qn, ".Render")) {
+ unresolved_render_semantics++;
+ if (strstr(rc->callee_qn, ".A.Render"))
+ a_unresolved_qn = rc->callee_qn;
+ if (strstr(rc->callee_qn, ".B.Render"))
+ b_unresolved_qn = rc->callee_qn;
+ }
+ }
+ ASSERT_EQ(unresolved_render_semantics, 2);
+ ASSERT_NOT_NULL(a_unresolved_qn);
+ ASSERT_NOT_NULL(b_unresolved_qn);
+
+ const char *a_leaf = strrchr(a_unresolved_qn, '.');
+ const char *b_leaf = strrchr(b_unresolved_qn, '.');
+ ASSERT_NOT_NULL(a_leaf);
+ ASSERT_NOT_NULL(b_leaf);
+ const char *a_receiver =
+ cbm_arena_strndup(&r->arena, a_unresolved_qn, (size_t)(a_leaf - a_unresolved_qn));
+ const char *b_receiver =
+ cbm_arena_strndup(&r->arena, b_unresolved_qn, (size_t)(b_leaf - b_unresolved_qn));
+ ASSERT_NOT_NULL(a_receiver);
+ ASSERT_NOT_NULL(b_receiver);
+
+ CBMLSPDef defs[2];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = a_unresolved_qn;
+ defs[0].short_name = "Render";
+ defs[0].label = "Method";
+ defs[0].receiver_type = a_receiver;
+ defs[0].def_module_qn = r->module_qn;
+ defs[0].lang = CBM_LANG_GO;
+ defs[1] = defs[0];
+ defs[1].qualified_name = b_unresolved_qn;
+ defs[1].receiver_type = b_receiver;
+
+ CBMTypeRegistry *reg = cbm_go_build_cross_registry(&r->arena, defs, 2);
+ ASSERT_NOT_NULL(reg);
+ ASSERT_EQ(cbm_go_fast_resolve_qualified_calls(r, reg, NULL, NULL, 0), 0);
+
+ const CBMResolvedCall *a_semantic = NULL;
+ const CBMResolvedCall *b_semantic = NULL;
+ int promoted_render_semantics = 0;
+ int zero_span_hijackers = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (!rc->strategy || strcmp(rc->strategy, "lsp_strategy_cross_file") != 0 ||
+ rc->kind != CBM_RESOLVED_INVOCATION || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "run") || !rc->callee_qn || !strstr(rc->callee_qn, ".Render")) {
+ continue;
+ }
+ promoted_render_semantics++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_hijackers++;
+ if (strcmp(rc->callee_qn, a_unresolved_qn) == 0 && rc->site_start_byte == a_start &&
+ rc->site_end_byte == a_end) {
+ a_semantic = rc;
+ }
+ if (strcmp(rc->callee_qn, b_unresolved_qn) == 0 && rc->site_start_byte == b_start &&
+ rc->site_end_byte == b_end) {
+ b_semantic = rc;
+ }
+ }
+
+ if (promoted_render_semantics != 2) {
+ printf(" fast-cross Render diagnostics (%d records):\n", r->resolved_calls.count);
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ printf(" %s -> %s [%s reason=%s site=%u:%u]\n",
+ rc->caller_qn ? rc->caller_qn : "(null)",
+ rc->callee_qn ? rc->callee_qn : "(null)", rc->strategy ? rc->strategy : "(null)",
+ rc->reason ? rc->reason : "(null)", rc->site_start_byte, rc->site_end_byte);
+ }
+ }
+
+ ASSERT_EQ(promoted_render_semantics, 2);
+ ASSERT_EQ(zero_span_hijackers, 0);
+ ASSERT_NOT_NULL(a_semantic);
+ ASSERT_NOT_NULL(b_semantic);
+ ASSERT_TRUE(a_semantic != b_semantic);
+ ASSERT_NEQ(a_semantic->site_start_byte, b_semantic->site_start_byte);
+
+ const CBMResolvedCall *a_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, a_call, false);
+ const CBMResolvedCall *b_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, b_call, false);
+ ASSERT_NOT_NULL(a_joined);
+ ASSERT_NOT_NULL(b_joined);
+ ASSERT_STR_EQ(a_joined->callee_qn, a_unresolved_qn);
+ ASSERT_STR_EQ(b_joined->callee_qn, b_unresolved_qn);
+ ASSERT_EQ(a_joined->site_start_byte, a_start);
+ ASSERT_EQ(a_joined->site_end_byte, a_end);
+ ASSERT_EQ(b_joined->site_start_byte, b_start);
+ ASSERT_EQ(b_joined->site_end_byte, b_end);
+
+ cbm_free_result(r);
+ PASS();
+}
+
TEST(golsp_crossfile_method_dispatch) {
const char *source = "package main\n\n"
"import \"myapp/db\"\n\n"
@@ -1177,8 +1440,10 @@ SUITE(go_lsp) {
/* Interface method dispatch variants */
RUN_TEST(golsp_interface_method_single_file);
RUN_TEST(golsp_interface_method_field_chain);
+ RUN_TEST(golsp_ordinary_same_leaf_calls_join_by_exact_site);
/* Cross-file */
+ RUN_TEST(golsp_fast_crossfile_same_leaf_calls_preserve_exact_sites);
RUN_TEST(golsp_crossfile_method_dispatch);
RUN_TEST(golsp_crossfile_return_type_chain);
RUN_TEST(golsp_crossfile_interface_dispatch);
diff --git a/tests/test_grammar_labels.c b/tests/test_grammar_labels.c
index b592e3285..64cfe432e 100644
--- a/tests/test_grammar_labels.c
+++ b/tests/test_grammar_labels.c
@@ -100,11 +100,11 @@ static const LabelGolden LABEL_GOLDENS[] = {
{"perl", "Function:2,Module:1"},
{"dart", "Class:1,Function:1,Module:1"},
{"swift", "Class:1,Function:1,Module:1"},
- {"scala", "Class:1,Function:1,Method:1,Module:1"},
+ {"scala", "Class:1,Method:1,Module:1"},
{"gdscript", "Function:1,Module:1"},
{"groovy", "Class:1,Method:1,Module:1"},
{"zig", "Function:2,Module:1"},
- {"solidity", "Class:1,Function:1,Method:1,Module:1"},
+ {"solidity", "Class:1,Method:1,Module:1"},
{"tcl", "Function:2,Module:1"},
{"powershell", "Function:2,Module:1"},
{"r", "Function:2,Module:1"},
diff --git a/tests/test_java_lsp.c b/tests/test_java_lsp.c
index 69fcc3c04..b802c31eb 100644
--- a/tests/test_java_lsp.c
+++ b/tests/test_java_lsp.c
@@ -1049,6 +1049,42 @@ TEST(jlsp_user_class_method) {
PASS();
}
+/* Java's grammar nests enum methods under enum_body_declarations rather than
+ * placing them directly in enum_body. Require both the indexed Method targets
+ * and the receiver-typed calls so a graph-level name fallback cannot mask a
+ * missing enum declaration walk. */
+TEST(jlsp_user_enum_methods) {
+ const char *src = "enum Day {\n"
+ " SAT, SUN;\n"
+ " public String label() { return name(); }\n"
+ " public boolean isWeekend() { return true; }\n"
+ "}\n"
+ "class DayUtil {\n"
+ " static String describe(Day day) {\n"
+ " return day.label() + day.isWeekend();\n"
+ " }\n"
+ "}\n";
+ CBMFileResult *r = extract_java(src);
+ ASSERT_NOT_NULL(r);
+
+ int enum_methods = 0;
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *definition = &r->defs.items[i];
+ if (definition->label && strcmp(definition->label, "Method") == 0 &&
+ definition->parent_class && strstr(definition->parent_class, "Day") &&
+ definition->name &&
+ (strcmp(definition->name, "label") == 0 ||
+ strcmp(definition->name, "isWeekend") == 0)) {
+ enum_methods++;
+ }
+ }
+ ASSERT_EQ(enum_methods, 2);
+ ASSERT_GTE(require_resolved(r, "describe", "Day.label"), 0);
+ ASSERT_GTE(require_resolved(r, "describe", "Day.isWeekend"), 0);
+ cbm_free_result(r);
+ PASS();
+}
+
TEST(jlsp_user_static_method) {
const char *src =
"public class Main {\n"
@@ -1874,6 +1910,7 @@ void suite_java_lsp(void) {
/* User-defined */
RUN_TEST(jlsp_user_class_method);
+ RUN_TEST(jlsp_user_enum_methods);
RUN_TEST(jlsp_user_static_method);
RUN_TEST(jlsp_user_chain);
diff --git a/tests/test_kotlin_lsp.c b/tests/test_kotlin_lsp.c
index ed0f6cf22..f216cafbf 100644
--- a/tests/test_kotlin_lsp.c
+++ b/tests/test_kotlin_lsp.c
@@ -29,7 +29,11 @@
*/
#include "test_framework.h"
#include "cbm.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "lsp/kotlin_lsp.h"
+#include <inttypes.h>
+#include <stdint.h>
+#include <stdio.h>
#include <string.h>
/* ── helpers ───────────────────────────────────────────────── */
@@ -84,6 +88,48 @@ static int count_resolved(const CBMFileResult *r, const char *callerSub, const c
return n;
}
+static int count_exact_resolved_site(const CBMFileResult *r, const char *callerSub,
+ const char *calleeSub, uint32_t start, uint32_t end) {
+ int n = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind == CBM_RESOLVED_INVOCATION && rc->caller_qn &&
+ strstr(rc->caller_qn, callerSub) && rc->callee_qn && strstr(rc->callee_qn, calleeSub) &&
+ rc->strategy && strcmp(rc->strategy, "lsp_kt_delegate_access") == 0 &&
+ rc->site_start_byte == start && rc->site_end_byte == end) {
+ n++;
+ }
+ }
+ return n;
+}
+
+static int count_exact_synthetic_call(const CBMFileResult *r, const char *callerSub,
+ const char *callee, uint32_t start, uint32_t end) {
+ int n = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->requires_lsp_resolution && call->enclosing_func_qn &&
+ strstr(call->enclosing_func_qn, callerSub) && call->callee_name &&
+ strcmp(call->callee_name, callee) == 0 && call->site_start_byte == start &&
+ call->site_end_byte == end) {
+ n++;
+ }
+ }
+ return n;
+}
+
+static int count_synthetic_call(const CBMFileResult *r, const char *callee) {
+ int n = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->requires_lsp_resolution && call->callee_name &&
+ strcmp(call->callee_name, callee) == 0) {
+ n++;
+ }
+ }
+ return n;
+}
+
/* ── 1. Package + import resolution ────────────────────────── */
TEST(ktlsp_package_set) {
@@ -677,6 +723,96 @@ TEST(ktlsp_unknown_external_unresolved) {
PASS();
}
+/* A call_expression contains a navigation_expression, and the Kotlin walker
+ * currently visits both. Keep one occurrence-exact semantic record per full
+ * parser call so same-leaf methods cannot duplicate or join the other target. */
+TEST(ktlsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ const char *source = "class Alpha { fun render(): String = \"alpha\" }\n"
+ "class Beta { fun render(): String = \"beta\" }\n"
+ "fun occurrenceProbe(alpha: Alpha, beta: Beta) {\n"
+ " alpha.render()\n"
+ " beta.render()\n"
+ "}\n";
+ static const char alpha_text[] = "alpha.render()";
+ static const char beta_text[] = "beta.render()";
+ const char *alpha_site = strstr(source, alpha_text);
+ const char *beta_site = strstr(source, beta_text);
+ ASSERT_NOT_NULL(alpha_site);
+ ASSERT_NOT_NULL(beta_site);
+ const uint32_t alpha_start = (uint32_t)(alpha_site - source);
+ const uint32_t alpha_end = alpha_start + (uint32_t)strlen(alpha_text);
+ const uint32_t beta_start = (uint32_t)(beta_site - source);
+ const uint32_t beta_end = beta_start + (uint32_t)strlen(beta_text);
+
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *alpha_call = NULL;
+ const CBMCall *beta_call = NULL;
+ int carrier_count = 0;
+ int zero_span_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "occurrenceProbe") ||
+ !call->callee_name || !strstr(call->callee_name, "render")) {
+ continue;
+ }
+ carrier_count++;
+ if (call->site_end_byte <= call->site_start_byte)
+ zero_span_carriers++;
+ if (call->site_start_byte == alpha_start && call->site_end_byte == alpha_end)
+ alpha_call = call;
+ if (call->site_start_byte == beta_start && call->site_end_byte == beta_end)
+ beta_call = call;
+ }
+
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_EQ(zero_span_carriers, 0);
+ ASSERT_NOT_NULL(alpha_call);
+ ASSERT_NOT_NULL(beta_call);
+ ASSERT_NEQ(alpha_call->site_start_byte, beta_call->site_start_byte);
+
+ const CBMResolvedCall *alpha_semantic = NULL;
+ const CBMResolvedCall *beta_semantic = NULL;
+ int semantic_count = 0;
+ int zero_span_semantics = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind != CBM_RESOLVED_INVOCATION || rc->confidence <= 0.0f || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "occurrenceProbe") || !rc->callee_qn ||
+ !strstr(rc->callee_qn, ".render")) {
+ continue;
+ }
+ semantic_count++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_semantics++;
+ if (strstr(rc->callee_qn, ".Alpha.render") && rc->site_start_byte == alpha_start &&
+ rc->site_end_byte == alpha_end) {
+ alpha_semantic = rc;
+ }
+ if (strstr(rc->callee_qn, ".Beta.render") && rc->site_start_byte == beta_start &&
+ rc->site_end_byte == beta_end) {
+ beta_semantic = rc;
+ }
+ }
+
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_EQ(zero_span_semantics, 0);
+ ASSERT_NOT_NULL(alpha_semantic);
+ ASSERT_NOT_NULL(beta_semantic);
+ ASSERT_TRUE(alpha_semantic != beta_semantic);
+
+ const CBMResolvedCall *alpha_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, alpha_call, false);
+ const CBMResolvedCall *beta_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, beta_call, false);
+ ASSERT_TRUE(alpha_joined == alpha_semantic);
+ ASSERT_TRUE(beta_joined == beta_semantic);
+
+ cbm_free_result(r);
+ PASS();
+}
+
TEST(ktlsp_no_duplicate_emission) {
/* Same call shouldn't emit twice. */
CBMFileResult *r = extract_kotlin("fun main() { println(\"a\"); println(\"b\") }\n");
@@ -888,6 +1024,51 @@ TEST(ktlsp_operator_int_plus) {
PASS();
}
+#if defined(CBM_KOTLIN_DEDUP_TEST_API) && CBM_KOTLIN_DEDUP_TEST_API
+TEST(ktlsp_operator_dedup_comparison_growth_is_linear) {
+ /* Each distinct operator site appends one exact-span carrier. Comparing a
+ * new site with every carrier already emitted costs at least
+ * N*(N-1)/2 comparisons: 18,336 at N=192. A constant-work dedup check
+ * (the duplicate wrapper, when present, is adjacent) stays near N. Count
+ * operations instead of elapsed time so this guard is deterministic under
+ * sanitizers, emulation, and loaded CI hosts. */
+ enum { OPERATOR_SITE_COUNT = 192, SOURCE_CAPACITY = 32768 };
+ char source[SOURCE_CAPACITY];
+ size_t used = 0;
+ int written = snprintf(source, sizeof(source),
+ "class Token {\n"
+ " operator fun plus(other: Token): Token = this\n"
+ "}\n"
+ "fun exercise(a: Token, b: Token) {\n");
+ ASSERT_GT(written, 0);
+ used = (size_t)written;
+
+ for (int i = 0; i < OPERATOR_SITE_COUNT; i++) {
+ written = snprintf(source + used, sizeof(source) - used, " val r%03d = a + b\n", i);
+ ASSERT_GT(written, 0);
+ ASSERT_LT((size_t)written, sizeof(source) - used);
+ used += (size_t)written;
+ }
+ written = snprintf(source + used, sizeof(source) - used, "}\n");
+ ASSERT_GT(written, 0);
+ ASSERT_LT((size_t)written, sizeof(source) - used);
+
+ cbm_kotlin_operator_dedup_test_reset();
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_EQ(count_synthetic_call(r, "plus"), OPERATOR_SITE_COUNT);
+
+ uint64_t comparisons = cbm_kotlin_operator_dedup_test_comparisons();
+ uint64_t linear_budget = (uint64_t)OPERATOR_SITE_COUNT * 8U;
+ printf(" Kotlin operator dedup: %" PRIu64 " comparisons for %d sites "
+ "(linear budget %" PRIu64 ")\n",
+ comparisons, OPERATOR_SITE_COUNT, linear_budget);
+ cbm_free_result(r);
+ ASSERT_LTE(comparisons, linear_budget);
+ PASS();
+}
+#endif
+
/* ── 27. Iterator protocol ──────────────────────────────────── */
TEST(ktlsp_for_iterator_protocol) {
@@ -958,6 +1139,144 @@ TEST(ktlsp_property_delegation_lazy) {
PASS();
}
+/* Access-level delegated-property contract. */
+
+TEST(ktlsp_property_delegate_declaration_emits_no_access_operator) {
+ static const char source[] =
+ "import kotlin.reflect.KProperty\n"
+ "class Slot {\n"
+ " operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = 1\n"
+ " operator fun setValue(thisRef: Any?, property: KProperty<*>, next: Int) {}\n"
+ "}\n"
+ "class Holder {\n"
+ " var value: Int by Slot()\n"
+ "}\n";
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+ /* Declaring a delegated property selects its operators but does not invoke
+ * either one. Access edges belong exclusively to source read/write sites. */
+ ASSERT_EQ(count_resolved(r, "", "getValue"), 0);
+ ASSERT_EQ(count_resolved(r, "", "setValue"), 0);
+ ASSERT_EQ(count_synthetic_call(r, "getValue"), 0);
+ ASSERT_EQ(count_synthetic_call(r, "setValue"), 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(ktlsp_property_delegate_read_emits_exact_get_only) {
+ static const char source[] =
+ "import kotlin.reflect.KProperty\n"
+ "class Slot {\n"
+ " operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = 1\n"
+ " operator fun setValue(thisRef: Any?, property: KProperty<*>, next: Int) {}\n"
+ "}\n"
+ "class Holder {\n"
+ " var value: Int by Slot()\n"
+ " fun read(): Int = value\n"
+ "}\n";
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+ const char *access = strstr(source, "fun read(): Int = value");
+ ASSERT_NOT_NULL(access);
+ uint32_t start = (uint32_t)(access - source) + (uint32_t)strlen("fun read(): Int = ");
+ uint32_t end = start + (uint32_t)strlen("value");
+ ASSERT_EQ(count_exact_resolved_site(r, "read", "getValue", start, end), 1);
+ ASSERT_EQ(count_exact_resolved_site(r, "read", "setValue", start, end), 0);
+ ASSERT_EQ(count_exact_synthetic_call(r, "read", "getValue", start, end), 1);
+ ASSERT_EQ(count_exact_synthetic_call(r, "read", "setValue", start, end), 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(ktlsp_property_delegate_write_emits_exact_set_only) {
+ static const char source[] =
+ "import kotlin.reflect.KProperty\n"
+ "class Slot {\n"
+ " operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = 1\n"
+ " operator fun setValue(thisRef: Any?, property: KProperty<*>, next: Int) {}\n"
+ "}\n"
+ "class Holder {\n"
+ " var value: Int by Slot()\n"
+ " fun write() { value = 2 }\n"
+ "}\n";
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+ const char *access = strstr(source, "value = 2");
+ ASSERT_NOT_NULL(access);
+ uint32_t start = (uint32_t)(access - source);
+ uint32_t end = start + (uint32_t)strlen("value");
+ ASSERT_EQ(count_exact_resolved_site(r, "write", "getValue", start, end), 0);
+ ASSERT_EQ(count_exact_resolved_site(r, "write", "setValue", start, end), 1);
+ ASSERT_EQ(count_exact_synthetic_call(r, "write", "getValue", start, end), 0);
+ ASSERT_EQ(count_exact_synthetic_call(r, "write", "setValue", start, end), 1);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(ktlsp_property_delegate_compound_write_emits_get_and_set) {
+ static const char source[] =
+ "import kotlin.reflect.KProperty\n"
+ "class Slot {\n"
+ " operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = 1\n"
+ " operator fun setValue(thisRef: Any?, property: KProperty<*>, next: Int) {}\n"
+ "}\n"
+ "class Holder {\n"
+ " var value: Int by Slot()\n"
+ " fun increment() { value += 2 }\n"
+ "}\n";
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+ const char *access = strstr(source, "value += 2");
+ ASSERT_NOT_NULL(access);
+ uint32_t start = (uint32_t)(access - source);
+ uint32_t end = start + (uint32_t)strlen("value");
+ /* Compound assignment is read-modify-write in Kotlin, so both operators
+ * are real access-level calls at the same source occurrence. */
+ ASSERT_EQ(count_exact_resolved_site(r, "increment", "getValue", start, end), 1);
+ ASSERT_EQ(count_exact_resolved_site(r, "increment", "setValue", start, end), 1);
+ ASSERT_EQ(count_exact_synthetic_call(r, "increment", "getValue", start, end), 1);
+ ASSERT_EQ(count_exact_synthetic_call(r, "increment", "setValue", start, end), 1);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(ktlsp_local_shadow_does_not_inherit_member_delegate) {
+ static const char source[] =
+ "import kotlin.reflect.KProperty\n"
+ "class Slot {\n"
+ " operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = 1\n"
+ " operator fun setValue(thisRef: Any?, property: KProperty<*>, next: Int) {}\n"
+ "}\n"
+ "class Holder {\n"
+ " var value: Int by Slot()\n"
+ " fun memberRead(): Int = value\n"
+ " fun localRead(): Int {\n"
+ " val value: Int = 7\n"
+ " return value\n"
+ " }\n"
+ "}\n";
+ CBMFileResult *r = extract_kotlin(source);
+ ASSERT_NOT_NULL(r);
+
+ const char *member = strstr(source, "fun memberRead(): Int = value");
+ ASSERT_NOT_NULL(member);
+ uint32_t member_start =
+ (uint32_t)(member - source) + (uint32_t)strlen("fun memberRead(): Int = ");
+ uint32_t member_end = member_start + (uint32_t)strlen("value");
+ ASSERT_EQ(count_exact_resolved_site(r, "memberRead", "getValue", member_start, member_end), 1);
+
+ const char *local = strstr(source, "return value");
+ ASSERT_NOT_NULL(local);
+ uint32_t local_start = (uint32_t)(local - source) + (uint32_t)strlen("return ");
+ uint32_t local_end = local_start + (uint32_t)strlen("value");
+ ASSERT_EQ(count_exact_resolved_site(r, "localRead", "getValue", local_start, local_end), 0);
+ ASSERT_EQ(count_exact_resolved_site(r, "localRead", "setValue", local_start, local_end), 0);
+ ASSERT_EQ(count_exact_synthetic_call(r, "localRead", "getValue", local_start, local_end), 0);
+ ASSERT_EQ(count_exact_synthetic_call(r, "localRead", "setValue", local_start, local_end), 0);
+ cbm_free_result(r);
+ PASS();
+}
+
/* ── 30. String template / interpolation ───────────────────── */
TEST(ktlsp_string_interpolation) {
@@ -1151,6 +1470,7 @@ SUITE(kotlin_lsp) {
RUN_TEST(ktlsp_only_imports);
RUN_TEST(ktlsp_kts_script);
RUN_TEST(ktlsp_unknown_external_unresolved);
+ RUN_TEST(ktlsp_ordinary_same_leaf_calls_join_by_exact_site);
RUN_TEST(ktlsp_no_duplicate_emission);
RUN_TEST(ktlsp_constructor_high_confidence);
RUN_TEST(ktlsp_method_high_confidence);
@@ -1167,6 +1487,9 @@ SUITE(kotlin_lsp) {
RUN_TEST(ktlsp_operator_get);
RUN_TEST(ktlsp_operator_unary);
RUN_TEST(ktlsp_operator_int_plus);
+#if defined(CBM_KOTLIN_DEDUP_TEST_API) && CBM_KOTLIN_DEDUP_TEST_API
+ RUN_TEST(ktlsp_operator_dedup_comparison_growth_is_linear);
+#endif
/* Iterator protocol */
RUN_TEST(ktlsp_for_iterator_protocol);
RUN_TEST(ktlsp_for_range_iterator);
@@ -1175,6 +1498,11 @@ SUITE(kotlin_lsp) {
RUN_TEST(ktlsp_destructuring_data_class);
/* Property delegation */
RUN_TEST(ktlsp_property_delegation_lazy);
+ RUN_TEST(ktlsp_property_delegate_declaration_emits_no_access_operator);
+ RUN_TEST(ktlsp_property_delegate_read_emits_exact_get_only);
+ RUN_TEST(ktlsp_property_delegate_write_emits_exact_set_only);
+ RUN_TEST(ktlsp_property_delegate_compound_write_emits_get_and_set);
+ RUN_TEST(ktlsp_local_shadow_does_not_inherit_member_delegate);
/* String interpolation */
RUN_TEST(ktlsp_string_interpolation);
/* Range */
diff --git a/tests/test_lang_contract.c b/tests/test_lang_contract.c
index 3ce639ded..41539a1a2 100644
--- a/tests/test_lang_contract.c
+++ b/tests/test_lang_contract.c
@@ -852,13 +852,34 @@ TEST(contract_calls_breadth) {
/* Every graph edge type the pipeline can emit — used to print a histogram
* when an edge contract fails, so a regression shows exactly what WAS
* produced instead of the missing type. */
-static const char *ALL_EDGE_TYPES[] = {
- "CALLS", "CONFIGURES", "CONTAINS_FILE", "CONTAINS_FOLDER", "DATA_FLOWS",
- "DECORATES", "DEFINES", "DEFINES_METHOD", "DEPENDS_ON", "FILE_CHANGES_WITH",
- "GRAPHQL_CALLS", "GRPC_CALLS", "HANDLES", "HTTP_CALLS", "IMPLEMENTS",
- "IMPORTS", "INHERITS", "INFRA_MAPS", "OVERRIDE", "SEMANTICALLY_RELATED",
- "SIMILAR_TO", "TESTS_FILE", "TESTS", "TRPC_CALLS", "USAGE",
- "ASYNC_CALLS", NULL};
+static const char *ALL_EDGE_TYPES[] = {"CALLS",
+ "CALL_REFERENCE",
+ "CONFIGURES",
+ "CONTAINS_FILE",
+ "CONTAINS_FOLDER",
+ "DATA_FLOWS",
+ "DECORATES",
+ "DEFINES",
+ "DEFINES_METHOD",
+ "DEPENDS_ON",
+ "FILE_CHANGES_WITH",
+ "GRAPHQL_CALLS",
+ "GRPC_CALLS",
+ "HANDLES",
+ "HTTP_CALLS",
+ "IMPLEMENTS",
+ "IMPORTS",
+ "INHERITS",
+ "INFRA_MAPS",
+ "OVERRIDE",
+ "SEMANTICALLY_RELATED",
+ "SIMILAR_TO",
+ "TESTS_FILE",
+ "TESTS",
+ "TRPC_CALLS",
+ "USAGE",
+ "ASYNC_CALLS",
+ NULL};
static void dump_edge_histogram(cbm_store_t *store, const char *project) {
if (!store) {
diff --git a/tests/test_lsp_resolution_probe.c b/tests/test_lsp_resolution_probe.c
index cac76c41b..3345e1ca7 100644
--- a/tests/test_lsp_resolution_probe.c
+++ b/tests/test_lsp_resolution_probe.c
@@ -184,9 +184,9 @@ static int lrp_usage(LRP_Proj *lp, const LRP_File *files, int nfiles) {
/* Diagnostic: dump edge histogram to stderr on failure. */
static const char *LRP_ALL_EDGE_TYPES[] = {
- "CALLS", "DEFINES", "DEFINES_METHOD", "IMPORTS", "INHERITS", "IMPLEMENTS",
- "USAGE", "DECORATES", "HANDLES", "HTTP_CALLS", "ASYNC_CALLS",
- "OVERRIDE", "TESTS", "TESTS_FILE", "DATA_FLOWS", NULL};
+ "CALLS", "CALL_REFERENCE", "DEFINES", "DEFINES_METHOD", "IMPORTS", "INHERITS",
+ "IMPLEMENTS", "USAGE", "DECORATES", "HANDLES", "HTTP_CALLS", "ASYNC_CALLS",
+ "OVERRIDE", "TESTS", "TESTS_FILE", "DATA_FLOWS", NULL};
static void lrp_diag(cbm_store_t *store, const char *project, const char *scenario) {
if (!store) { fprintf(stderr, " [LRP] %s: no graph DB\n", scenario); return; }
@@ -224,6 +224,93 @@ static int lrp_assert_calls(const LRP_File *files, int nfiles, int min_calls,
return got >= min_calls;
}
+/* Count one exact CALLS relationship by unique source/target node names.
+ * Returning -1 distinguishes a malformed fixture or DB failure from a genuine
+ * missing edge. This prevents broad CALLS totals (including macro/stdlib edges)
+ * from masking a missing source-specific relationship. */
+static int lrp_exact_edge_by_name(cbm_store_t *store, const char *project, const char *edge_type,
+ const char *source_name, const char *target_name) {
+ if (!store || !project || !edge_type || !source_name || !target_name) {
+ return -1;
+ }
+
+ cbm_node_t *sources = NULL;
+ cbm_node_t *targets = NULL;
+ int source_count = 0;
+ int target_count = 0;
+ if (cbm_store_find_nodes_by_name(store, project, source_name, &sources, &source_count) !=
+ CBM_STORE_OK ||
+ cbm_store_find_nodes_by_name(store, project, target_name, &targets, &target_count) !=
+ CBM_STORE_OK ||
+ source_count != 1 || target_count != 1) {
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ return -1;
+ }
+
+ int64_t source_id = sources[0].id;
+ int64_t target_id = targets[0].id;
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_source_type(store, source_id, edge_type, &edges, &edge_count) !=
+ CBM_STORE_OK) {
+ cbm_store_free_edges(edges, edge_count);
+ return -1;
+ }
+
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ if (edges[i].target_id == target_id) {
+ matches++;
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ return matches;
+}
+
+static int lrp_exact_calls_by_name(cbm_store_t *store, const char *project, const char *source_name,
+ const char *target_name) {
+ return lrp_exact_edge_by_name(store, project, "CALLS", source_name, target_name);
+}
+
+static int lrp_exact_edge_by_qn_suffix(cbm_store_t *store, const char *project,
+ const char *edge_type, const char *source_suffix,
+ const char *target_suffix) {
+ cbm_node_t *sources = NULL;
+ cbm_node_t *targets = NULL;
+ int source_count = 0;
+ int target_count = 0;
+ if (!store ||
+ cbm_store_find_nodes_by_qn_suffix(store, project, source_suffix, &sources, &source_count) !=
+ CBM_STORE_OK ||
+ cbm_store_find_nodes_by_qn_suffix(store, project, target_suffix, &targets, &target_count) !=
+ CBM_STORE_OK ||
+ source_count != 1 || target_count != 1) {
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ return -1;
+ }
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ int matches = -1;
+ if (cbm_store_find_edges_by_source_type(store, sources[0].id, edge_type, &edges, &edge_count) ==
+ CBM_STORE_OK) {
+ matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ if (edges[i].target_id == targets[0].id) {
+ matches++;
+ }
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ return matches;
+}
+
/* ══════════════════════════════════════════════════════════════════════
* ─── GROUP 1: GO (lsp_cross WIRED) ──────────────────────────────────
* ══════════════════════════════════════════════════════════════════════
@@ -787,6 +874,35 @@ TEST(lrp_rust_s8_field_call) {
PASS();
}
+/* Cross-file call hidden inside format!'s token tree. The visible() control
+ * proves the target and ordinary cross-file resolution are present; hidden()
+ * requires the Rust LSP's semantic result to be paired with a synthetic
+ * CBMCall carrier before pass_calls can materialize the exact graph edge. */
+TEST(lrp_rust_crossfile_macro_hidden_call_carrier) {
+ static const LRP_File f[] = {
+ {"lib.rs", "pub fn render() -> &'static str { \"ok\" }\n"},
+ {"main.rs", "mod lib;\n\n"
+ "pub fn visible() -> &'static str { lib::render() }\n\n"
+ "pub fn hidden() -> String { format!(\"{}\", lib::render()) }\n"}};
+
+ LRP_Proj lp;
+ cbm_store_t *store = lrp_index(&lp, f, 2);
+ int visible_to_render = lrp_exact_calls_by_name(store, lp.project, "visible", "render");
+ int hidden_to_render = lrp_exact_calls_by_name(store, lp.project, "hidden", "render");
+ if (visible_to_render != 1 || hidden_to_render != 1) {
+ fprintf(stderr,
+ " [LRP] rust/macro_hidden_carrier visible->render=%d "
+ "hidden->render=%d (expected 1 each)\n",
+ visible_to_render, hidden_to_render);
+ lrp_diag(store, lp.project, "rust/macro_hidden_carrier");
+ }
+ lrp_cleanup(&lp, store);
+
+ ASSERT_EQ(visible_to_render, 1); /* ordinary-call control */
+ ASSERT_EQ(hidden_to_render, 1); /* synthetic carrier regression guard */
+ PASS();
+}
+
/* ══════════════════════════════════════════════════════════════════════
* ─── GROUP 5: PYTHON (lsp_cross WIRED) ──────────────────────────────
* ══════════════════════════════════════════════════════════════════════
@@ -913,6 +1029,34 @@ TEST(lrp_python_s8_field_type_hint) {
PASS();
}
+/* A cross-file dunder can resolve semantically only after the project-wide
+ * Python registry is available. Because `left + right` is not a parser call,
+ * the cross resolver must return an exact synthetic carrier as well as the
+ * semantic record or pass_calls has nothing to materialize. */
+TEST(lrp_python_crossfile_dunder_carrier) {
+ static const LRP_File f[] = {{"alpha.py", "class Alpha:\n"
+ " def __add__(self, other):\n"
+ " return self\n"},
+ {"main.py", "from .alpha import Alpha\n\n"
+ "def combine(left: Alpha, right: Alpha):\n"
+ " return left + right\n"}};
+
+ LRP_Proj lp;
+ cbm_store_t *store = lrp_index(&lp, f, 2);
+ int combine_to_add = lrp_exact_calls_by_name(store, lp.project, "combine", "__add__");
+ if (combine_to_add != 1) {
+ fprintf(stderr,
+ " [LRP] python/crossfile_dunder_carrier combine->__add__=%d "
+ "(expected 1)\n",
+ combine_to_add);
+ lrp_diag(store, lp.project, "python/crossfile_dunder_carrier");
+ }
+ lrp_cleanup(&lp, store);
+
+ ASSERT_EQ(combine_to_add, 1);
+ PASS();
+}
+
/* ══════════════════════════════════════════════════════════════════════
* ─── GROUP 6: TYPESCRIPT (lsp_cross WIRED) ───────────────────────────
* ══════════════════════════════════════════════════════════════════════
@@ -1605,9 +1749,8 @@ TEST(lrp_php_s8_field_type_hint) {
/* ══════════════════════════════════════════════════════════════════════
* ─── BONUS: USAGE-EDGE PROBES (type references, not calls) ───────────
* ══════════════════════════════════════════════════════════════════════
- * USAGE edges are created for type references (not calls). These probe
- * whether the LSP pass emits USAGE in addition to CALLS for instantiation
- * and typed-parameter scenarios.
+ * USAGE edges are created for non-call type references. Constructor syntax is
+ * a CALLS relationship; typed-parameter scenarios remain USAGE.
*/
/* Go: struct literal usage of a cross-file type. */
@@ -1626,14 +1769,7 @@ TEST(lrp_go_usage_struct_literal) {
PASS();
}
-/* TypeScript: type reference as parameter annotation.
- * REAL BUG: a cross-file TS TYPE-position reference (the `Config` type_identifier
- * in `cfg: Config`) yields NO USAGE edge → n=0, even though `Config` is a
- * registered Interface node and is_reference_node() accepts "type_identifier".
- * Value-position type refs DO work (lrp_go_usage_struct_literal and
- * lrp_python_usage_instantiation both pass), so the gap is TS type-annotation
- * usage emission/resolution (handle_usages / resolve_usage_edges path) — the
- * type-only parameter annotation is dropped rather than emitted as USAGE. */
+/* TypeScript: exact imported type reference as parameter annotation. */
TEST(lrp_ts_usage_type_param) {
static const LRP_File f[] = {
{"types.ts", "export interface Config { timeout: number; }\n"},
@@ -1641,27 +1777,54 @@ TEST(lrp_ts_usage_type_param) {
"import { Config } from './types';\n\n"
"export function run(cfg: Config): number { return cfg.timeout; }\n"}};
LRP_Proj lp;
- int n = lrp_usage(&lp, f, 2);
- if (n < 1) {
- fprintf(stderr, " [LRP] ts/USAGE/type_param n=%d expected>=1\n", n);
- }
- ASSERT_TRUE(n >= 1);
+ cbm_store_t *store = lrp_index(&lp, f, 2);
+ int exact = store ? lrp_exact_edge_by_name(store, lp.project, "USAGE", "run", "Config") : -1;
+ lrp_cleanup(&lp, store);
+ ASSERT_EQ(exact, 1);
PASS();
}
-/* Python: class instantiation USAGE. */
+static int lrp_ts_imported_type_with_decoy(const char *main_filename) {
+ LRP_File files[] = {
+ {"a/types.ts", "export interface Config { selected: number; }\n"},
+ {"b/types.ts", "export interface Config { decoy: string; }\n"},
+ {main_filename, "import type { Config } from './a/types';\n"
+ "export function choose(cfg: Config): number { return cfg.selected; }\n"},
+ };
+ LRP_Proj lp;
+ cbm_store_t *store = lrp_index(&lp, files, 3);
+ int exact = store ? lrp_exact_edge_by_qn_suffix(store, lp.project, "USAGE", "main.choose",
+ "a.types.Config")
+ : -1;
+ int decoy = store ? lrp_exact_edge_by_qn_suffix(store, lp.project, "USAGE", "main.choose",
+ "b.types.Config")
+ : -1;
+ lrp_cleanup(&lp, store);
+ return exact == 1 && decoy == 0;
+}
+
+/* A duplicate type name must not let unique-name fallback hide import identity. */
+TEST(lrp_ts_usage_import_type_with_decoy) {
+ ASSERT_TRUE(lrp_ts_imported_type_with_decoy("main.ts"));
+ PASS();
+}
+
+TEST(lrp_tsx_usage_import_type_with_decoy) {
+ ASSERT_TRUE(lrp_ts_imported_type_with_decoy("main.tsx"));
+ PASS();
+}
+
+/* Python: constructor syntax is an exact call to the materialized Class node. */
TEST(lrp_python_usage_instantiation) {
static const LRP_File f[] = {
{"model.py", "class User:\n def __init__(self, name):\n self.name = name\n"},
{"main.py",
"from .model import User\n\n\ndef create(name):\n return User(name)\n"}};
LRP_Proj lp;
- int n = lrp_usage(&lp, f, 2);
- /* Uncertain: USAGE edge for Python instantiation. Diagnose but assert correct. */
- if (n < 1) {
- fprintf(stderr, " [LRP] python/USAGE/instantiation n=%d (uncertain)\n", n);
- }
- ASSERT_TRUE(n >= 1);
+ cbm_store_t *store = lrp_index(&lp, f, 2);
+ int exact = store ? lrp_exact_calls_by_name(store, lp.project, "create", "User") : -1;
+ lrp_cleanup(&lp, store);
+ ASSERT_EQ(exact, 1);
PASS();
}
@@ -1710,6 +1873,7 @@ SUITE(lsp_resolution_probe) {
RUN_TEST(lrp_rust_s6_trait_method);
RUN_TEST(lrp_rust_s7_generic);
RUN_TEST(lrp_rust_s8_field_call);
+ RUN_TEST(lrp_rust_crossfile_macro_hidden_call_carrier);
/* ── Python (lsp_cross WIRED) — S1–S5,S7,S8 GREEN; S6 uncertain (extraction bug) ── */
RUN_TEST(lrp_python_s1_crossfile_call);
@@ -1720,6 +1884,7 @@ SUITE(lsp_resolution_probe) {
RUN_TEST(lrp_python_s6_inherited_method);
RUN_TEST(lrp_python_s7_annotated_call);
RUN_TEST(lrp_python_s8_field_type_hint);
+ RUN_TEST(lrp_python_crossfile_dunder_carrier);
/* ── TypeScript (lsp_cross WIRED) — S1–S5,S7,S8 GREEN; S6 uncertain ── */
RUN_TEST(lrp_ts_s1_crossfile_call);
@@ -1775,5 +1940,7 @@ SUITE(lsp_resolution_probe) {
/* ── USAGE-edge bonus probes ── */
RUN_TEST(lrp_go_usage_struct_literal);
RUN_TEST(lrp_ts_usage_type_param);
+ RUN_TEST(lrp_ts_usage_import_type_with_decoy);
+ RUN_TEST(lrp_tsx_usage_import_type_with_decoy);
RUN_TEST(lrp_python_usage_instantiation);
}
diff --git a/tests/test_main.c b/tests/test_main.c
index 64f4b784d..9089242bb 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -212,6 +212,7 @@ extern void suite_discover(void);
extern void suite_graph_buffer(void);
extern void suite_registry(void);
extern void suite_pipeline(void);
+extern void suite_pipeline_semantic_manifest_repro(void);
extern void suite_index_resilience(void);
extern void suite_fqn(void);
extern void suite_route_canon(void);
@@ -255,6 +256,22 @@ extern void suite_config_text_edit(void);
extern void suite_system_info(void);
extern void suite_worker_pool(void);
extern void suite_parallel(void);
+extern void suite_call_reference_language_complex_contract(void);
+extern void suite_repro_call_scope_usages(void);
+extern void suite_repro_call_argument_usages(void);
+extern void suite_repro_reference_precision(void);
+extern void suite_repro_lexical_binding_precision(void);
+extern void suite_repro_call_argument_matrix_a(void);
+extern void suite_repro_call_argument_matrix_b(void);
+extern void suite_repro_call_node_behaviors(void);
+extern void suite_repro_language_registry(void);
+extern void suite_repro_call_node_manifest(void);
+extern void suite_repro_lsp_ordered_signatures(void);
+extern void suite_repro_lsp_ordered_local(void);
+extern void suite_repro_ts_overload_return_chains(void);
+extern void suite_repro_harness_cleanup(void);
+extern void suite_repro_runner_filter(void);
+extern void suite_call_reference_contract(void);
extern void suite_mem(void);
extern void suite_ui(void);
extern void suite_httpd(void);
@@ -386,6 +403,22 @@ int main(int argc, char **argv) {
/* Pipeline (M8) */
RUN_SELECTED_SUITE(registry);
RUN_SELECTED_SUITE(pipeline);
+ RUN_SELECTED_SUITE(pipeline_semantic_manifest_repro);
+ RUN_SELECTED_SUITE(call_reference_contract);
+ RUN_SELECTED_SUITE(call_reference_language_complex_contract);
+ RUN_SELECTED_SUITE(repro_call_scope_usages);
+ RUN_SELECTED_SUITE(repro_call_argument_usages);
+ RUN_SELECTED_SUITE(repro_reference_precision);
+ RUN_SELECTED_SUITE(repro_call_argument_matrix_a);
+ RUN_SELECTED_SUITE(repro_call_argument_matrix_b);
+ RUN_SELECTED_SUITE(repro_call_node_behaviors);
+ RUN_SELECTED_SUITE(repro_language_registry);
+ RUN_SELECTED_SUITE(repro_call_node_manifest);
+ RUN_SELECTED_SUITE(repro_lsp_ordered_signatures);
+ RUN_SELECTED_SUITE(repro_lsp_ordered_local);
+ RUN_SELECTED_SUITE(repro_ts_overload_return_chains);
+ RUN_SELECTED_SUITE(repro_harness_cleanup);
+ RUN_SELECTED_SUITE(repro_runner_filter);
RUN_SELECTED_SUITE(index_resilience);
RUN_SELECTED_SUITE(fqn);
RUN_SELECTED_SUITE(route_canon);
@@ -451,6 +484,9 @@ int main(int argc, char **argv) {
/* Parallel pipeline */
RUN_SELECTED_SUITE(parallel);
+ /* Promoted lexical-resolution regression contracts. */
+ RUN_SELECTED_SUITE(repro_lexical_binding_precision);
+
/* mem + arena + slab integration */
RUN_SELECTED_SUITE(slab_alloc);
RUN_SELECTED_SUITE(mem);
diff --git a/tests/test_matrix_new_constructs.c b/tests/test_matrix_new_constructs.c
index 116910b73..c92b38310 100644
--- a/tests/test_matrix_new_constructs.c
+++ b/tests/test_matrix_new_constructs.c
@@ -127,6 +127,60 @@ static int mn_count_label(cbm_store_t *store, const char *project, const char *l
return count;
}
+static int mn_named_node_match_count(cbm_store_t *store, const char *project, const char *name,
+ const char *label, const char *qn_suffix) {
+ cbm_node_t *nodes = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_name(store, project, name, &nodes, &count) != CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ size_t suffix_len = strlen(qn_suffix);
+ for (int i = 0; i < count; i++) {
+ size_t qn_len = nodes[i].qualified_name ? strlen(nodes[i].qualified_name) : 0;
+ if (nodes[i].label && strcmp(nodes[i].label, label) == 0 && qn_len >= suffix_len &&
+ strcmp(nodes[i].qualified_name + qn_len - suffix_len, qn_suffix) == 0) {
+ matches++;
+ }
+ }
+ cbm_store_free_nodes(nodes, count);
+ return matches;
+}
+
+static int mn_exact_edge_by_qn_suffix(cbm_store_t *store, const char *project,
+ const char *edge_type, const char *source_suffix,
+ const char *target_suffix) {
+ cbm_node_t *sources = NULL;
+ cbm_node_t *targets = NULL;
+ int source_count = 0;
+ int target_count = 0;
+ if (cbm_store_find_nodes_by_qn_suffix(store, project, source_suffix, &sources, &source_count) !=
+ CBM_STORE_OK ||
+ cbm_store_find_nodes_by_qn_suffix(store, project, target_suffix, &targets, &target_count) !=
+ CBM_STORE_OK ||
+ source_count != 1 || target_count != 1) {
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ return -1;
+ }
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ int matches = -1;
+ if (cbm_store_find_edges_by_source_type(store, sources[0].id, edge_type, &edges, &edge_count) ==
+ CBM_STORE_OK) {
+ matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ if (edges[i].target_id == targets[0].id) {
+ matches++;
+ }
+ }
+ }
+ cbm_store_free_edges(edges, edge_count);
+ cbm_store_free_nodes(sources, source_count);
+ cbm_store_free_nodes(targets, target_count);
+ return matches;
+}
+
/* Sum type-like nodes (Class + Struct + Interface + Enum + Trait + Type). */
static int mn_type_nodes(cbm_store_t *store, const char *project) {
static const char *labels[] = {"Class", "Struct", "Interface", "Enum", "Trait", "Type", NULL};
@@ -1319,9 +1373,19 @@ TEST(mn_nested_function_c) {
* must still be attributed to the right callable.
* ══════════════════════════════════════════════════════════════════ */
-/* TypeScript: nested namespace with class and function. */
-TEST(mn_module_ts_namespace) {
- MN_Metrics m = mn_metrics("ns.ts",
+typedef struct {
+ int app_module;
+ int utils_module;
+ int namespace_classes;
+ int config_class;
+ int clamp_function;
+ int normalise_function;
+ int normalise_calls_clamp;
+ int constructor_calls_normalise;
+} MN_TSNamespaceObservation;
+
+static MN_TSNamespaceObservation mn_observe_ts_namespace(const char *filename) {
+ static const char source[] =
"namespace App {\n"
" export namespace Utils {\n"
" export function clamp(v: number, lo: number, hi: number): number {\n"
@@ -1334,13 +1398,59 @@ TEST(mn_module_ts_namespace) {
" constructor(t: number) { this.threshold = Utils.normalise(t); }\n"
" }\n"
"}\n\n"
- "function run(): number { return new App.Config(0.5).threshold; }\n");
- ASSERT_TRUE(m.ok);
- ASSERT_TRUE(m.functions >= 2); /* clamp, normalise, run */
- ASSERT_TRUE(m.types >= 1); /* Config */
- ASSERT_TRUE(m.calls >= 1);
+ "function run(): number { return new App.Config(0.5).threshold; }\n";
+ MN_LangFile file = {filename, source};
+ MN_LangProj lp;
+ cbm_store_t *store = mn_index_files(&lp, &file, 1);
+ MN_TSNamespaceObservation o = {0};
+ if (store) {
+ o.app_module = mn_named_node_match_count(store, lp.project, "App", "Module", ".ns.App");
+ o.utils_module =
+ mn_named_node_match_count(store, lp.project, "Utils", "Module", ".ns.App.Utils");
+ o.namespace_classes =
+ mn_named_node_match_count(store, lp.project, "App", "Class", ".ns.App") +
+ mn_named_node_match_count(store, lp.project, "Utils", "Class", ".ns.App.Utils");
+ o.config_class =
+ mn_named_node_match_count(store, lp.project, "Config", "Class", ".ns.App.Config");
+ o.clamp_function = mn_named_node_match_count(store, lp.project, "clamp", "Function",
+ ".ns.App.Utils.clamp");
+ o.normalise_function = mn_named_node_match_count(store, lp.project, "normalise", "Function",
+ ".ns.App.Utils.normalise");
+ o.normalise_calls_clamp = mn_exact_edge_by_qn_suffix(
+ store, lp.project, "CALLS", "ns.App.Utils.normalise", "ns.App.Utils.clamp");
+ o.constructor_calls_normalise = mn_exact_edge_by_qn_suffix(
+ store, lp.project, "CALLS", "ns.App.Config.constructor", "ns.App.Utils.normalise");
+ }
+ mn_cleanup(&lp, store);
+ return o;
+}
+
+#define MN_ASSERT_TS_NAMESPACE(o) \
+ do { \
+ ASSERT_EQ((o).app_module, 1); \
+ ASSERT_EQ((o).utils_module, 1); \
+ ASSERT_EQ((o).namespace_classes, 0); \
+ ASSERT_EQ((o).config_class, 1); \
+ ASSERT_EQ((o).clamp_function, 1); \
+ ASSERT_EQ((o).normalise_function, 1); \
+ ASSERT_EQ((o).normalise_calls_clamp, 1); \
+ ASSERT_EQ((o).constructor_calls_normalise, 1); \
+ } while (0)
+
+/* TypeScript: nested namespace functions remain free functions with exact QNs. */
+TEST(mn_module_ts_namespace) {
+ MN_TSNamespaceObservation observation = mn_observe_ts_namespace("ns.ts");
+ MN_ASSERT_TS_NAMESPACE(observation);
+ PASS();
+}
+
+/* TSX shares the TypeScript namespace grammar and must retain identical semantics. */
+TEST(mn_module_tsx_namespace) {
+ MN_TSNamespaceObservation observation = mn_observe_ts_namespace("ns.tsx");
+ MN_ASSERT_TS_NAMESPACE(observation);
PASS();
}
+#undef MN_ASSERT_TS_NAMESPACE
/* C++: namespace with nested classes and functions. */
TEST(mn_module_cpp_namespace) {
@@ -1558,6 +1668,7 @@ SUITE(matrix_new_constructs) {
/* Family 10: module/namespace nesting */
printf("\n%s--- Family 10: modules/namespaces ---%s\n", "\033[90m", "\033[0m");
RUN_TEST(mn_module_ts_namespace);
+ RUN_TEST(mn_module_tsx_namespace);
RUN_TEST(mn_module_cpp_namespace);
RUN_TEST(mn_module_csharp_namespace);
RUN_TEST(mn_module_rust_mod);
diff --git a/tests/test_mcp.c b/tests/test_mcp.c
index 82b5469eb..0bde1b712 100644
--- a/tests/test_mcp.c
+++ b/tests/test_mcp.c
@@ -308,6 +308,13 @@ TEST(mcp_tools_list_latest_metadata) {
ASSERT_NOT_NULL(strstr(json, "\"title\":\"Check index coverage\""));
ASSERT_NOT_NULL(strstr(json, "\"outputSchema\":{\"type\":\"object\""));
ASSERT_NOT_NULL(strstr(json, "\"additionalProperties\":true"));
+ /* search_graph's compact degree columns intentionally count the graph
+ * relationships used for call/reference/type centrality, not every edge
+ * family (for example DEFINES or CONTAINS_FILE). Keep the public contract
+ * aligned with the store query. */
+ ASSERT_NOT_NULL(strstr(json, "in/out = selected degree across CALLS, USAGE, CALL_REFERENCE, "
+ "INHERITS, and IMPLEMENTS"));
+ ASSERT_NULL(strstr(json, "TOTAL degree across ALL edge types"));
free(json);
PASS();
}
diff --git a/tests/test_parallel.c b/tests/test_parallel.c
index 9706db2b7..145b9ad38 100644
--- a/tests/test_parallel.c
+++ b/tests/test_parallel.c
@@ -29,6 +29,25 @@
static char g_par_tmpdir[256];
+TEST(usage_semantic_reference_candidate_trusts_marked_producer) {
+ CBMUsage usage = {0};
+ usage.kind = CBM_USAGE_VALUE;
+ usage.may_be_call_reference = true;
+ ASSERT_TRUE(cbm_pipeline_usage_semantic_reference_candidate(&usage));
+
+ usage.may_be_call_reference = false;
+ ASSERT_FALSE(cbm_pipeline_usage_semantic_reference_candidate(&usage));
+
+ usage.kind = CBM_USAGE_CALL_REFERENCE;
+ ASSERT_TRUE(cbm_pipeline_usage_semantic_reference_candidate(&usage));
+
+ /* Lexical evidence gates only the later textual fallback. An exact
+ * occurrence row must still get the chance to prove one callable target. */
+ usage.semantic_reference_blocked = true;
+ ASSERT_TRUE(cbm_pipeline_usage_semantic_reference_candidate(&usage));
+ PASS();
+}
+
static int setup_parallel_repo(void) {
snprintf(g_par_tmpdir, sizeof(g_par_tmpdir), "/tmp/cbm_par_XXXXXX");
if (!cbm_mkdtemp(g_par_tmpdir))
@@ -83,6 +102,29 @@ static void teardown_parallel_repo(void) {
g_par_tmpdir[0] = '\0';
}
+/* The compact parity helpers normally omit the production structure pass.
+ * Tests that exercise graph-derived import maps must seed its File-node
+ * precondition explicitly, without changing legacy parity fixtures. */
+static void seed_test_file_nodes(cbm_gbuf_t *gbuf, const char *project,
+ const cbm_file_info_t *files, int file_count) {
+ if (!gbuf || !project || !files) {
+ return;
+ }
+ for (int i = 0; i < file_count; i++) {
+ const char *rel = files[i].rel_path;
+ if (!rel) {
+ continue;
+ }
+ char *file_qn = cbm_pipeline_fqn_compute(project, rel, "__file__");
+ const char *slash = strrchr(rel, '/');
+ const char *basename = slash ? slash + 1 : rel;
+ if (file_qn) {
+ cbm_gbuf_upsert_node(gbuf, "File", basename, file_qn, rel, 0, 0, "{}");
+ }
+ free(file_qn);
+ }
+}
+
/* ── Run sequential pipeline on files, returning gbuf ─────────────── */
static cbm_gbuf_t *run_sequential(const char *project, const char *repo_path,
@@ -110,12 +152,69 @@ static cbm_gbuf_t *run_sequential(const char *project, const char *repo_path,
return gbuf;
}
+typedef void (*parallel_result_mutator_fn)(CBMFileResult **result_cache, int file_count, void *ud);
+
+/* Production's sequential pipeline retains one extraction cache and runs the
+ * cross-file LSP pass between definitions and edge materialization. Keep this
+ * explicit helper for tests whose semantic target is declared in another file;
+ * the lightweight run_sequential helper above intentionally predates that pass. */
+static cbm_gbuf_t *run_sequential_with_lsp_cross_and_mutator(
+ const char *project, const char *repo_path, cbm_file_info_t *files, int file_count,
+ parallel_result_mutator_fn mutator, void *mutator_ud, bool seed_structure) {
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, repo_path);
+ cbm_registry_t *reg = cbm_registry_new();
+ CBMFileResult **cache = (CBMFileResult **)calloc((size_t)file_count, sizeof(CBMFileResult *));
+ if (!gbuf || !reg || !cache) {
+ cbm_gbuf_free(gbuf);
+ cbm_registry_free(reg);
+ free(cache);
+ return NULL;
+ }
+ atomic_int cancelled;
+ atomic_init(&cancelled, 0);
+ cbm_pipeline_ctx_t ctx = {
+ .project_name = project,
+ .repo_path = repo_path,
+ .gbuf = gbuf,
+ .registry = reg,
+ .cancelled = &cancelled,
+ .result_cache = cache,
+ };
+
+ if (seed_structure) {
+ seed_test_file_nodes(gbuf, project, files, file_count);
+ }
+
+ cbm_init();
+ cbm_pipeline_pass_definitions(&ctx, files, file_count);
+ cbm_pipeline_pass_lsp_cross(&ctx, files, file_count, cache);
+ if (mutator) {
+ mutator(cache, file_count, mutator_ud);
+ }
+ cbm_pipeline_pass_calls(&ctx, files, file_count);
+ cbm_pipeline_pass_usages(&ctx, files, file_count);
+ cbm_pipeline_pass_semantic(&ctx, files, file_count);
+
+ for (int i = 0; i < file_count; i++) {
+ cbm_free_result(cache[i]);
+ }
+ free(cache);
+ cbm_registry_free(reg);
+ return gbuf;
+}
+
+static cbm_gbuf_t *run_sequential_with_lsp_cross(const char *project, const char *repo_path,
+ cbm_file_info_t *files, int file_count) {
+ return run_sequential_with_lsp_cross_and_mutator(project, repo_path, files, file_count, NULL,
+ NULL, false);
+}
+
/* ── Run parallel pipeline on files, returning gbuf ───────────────── */
-static cbm_gbuf_t *run_parallel_with_extract_opts(const char *project, const char *repo_path,
- cbm_file_info_t *files, int file_count,
- int worker_count,
- const cbm_parallel_extract_opts_t *extract_opts) {
+static cbm_gbuf_t *run_parallel_with_extract_opts_and_mutator(
+ const char *project, const char *repo_path, cbm_file_info_t *files, int file_count,
+ int worker_count, const cbm_parallel_extract_opts_t *extract_opts,
+ parallel_result_mutator_fn mutator, void *mutator_ud, bool seed_structure) {
cbm_gbuf_t *gbuf = cbm_gbuf_new(project, repo_path);
cbm_registry_t *reg = cbm_registry_new();
atomic_int cancelled;
@@ -129,6 +228,10 @@ static cbm_gbuf_t *run_parallel_with_extract_opts(const char *project, const cha
.cancelled = &cancelled,
};
+ if (seed_structure) {
+ seed_test_file_nodes(gbuf, project, files, file_count);
+ }
+
_Atomic int64_t shared_ids;
int64_t gbuf_next = cbm_gbuf_next_id(gbuf);
atomic_init(&shared_ids, gbuf_next);
@@ -144,7 +247,15 @@ static cbm_gbuf_t *run_parallel_with_extract_opts(const char *project, const cha
}
cbm_gbuf_set_next_id(gbuf, atomic_load(&shared_ids));
+ if (mutator) {
+ mutator(result_cache, file_count, mutator_ud);
+ }
+
cbm_build_registry_from_cache(&ctx, files, file_count, result_cache);
+ int64_t registry_next = cbm_gbuf_next_id(gbuf);
+ if (registry_next > atomic_load(&shared_ids)) {
+ atomic_store(&shared_ids, registry_next);
+ }
/* Cross-file LSP — mirrors run_parallel_pipeline ordering in pipeline.c.
* Build the project-wide all_defs[] precondition, then feed it into
@@ -182,6 +293,14 @@ static cbm_gbuf_t *run_parallel_with_extract_opts(const char *project, const cha
return gbuf;
}
+static cbm_gbuf_t *run_parallel_with_extract_opts(const char *project, const char *repo_path,
+ cbm_file_info_t *files, int file_count,
+ int worker_count,
+ const cbm_parallel_extract_opts_t *extract_opts) {
+ return run_parallel_with_extract_opts_and_mutator(
+ project, repo_path, files, file_count, worker_count, extract_opts, NULL, NULL, false);
+}
+
static cbm_gbuf_t *run_parallel(const char *project, const char *repo_path, cbm_file_info_t *files,
int file_count, int worker_count) {
return run_parallel_with_extract_opts(project, repo_path, files, file_count, worker_count,
@@ -594,6 +713,84 @@ static const cbm_gbuf_node_t *find_unique_callable_node_by_tail(const cbm_gbuf_t
return match;
}
+static bool qn_has_segment_suffix(const char *qualified_name, const char *suffix) {
+ if (!qualified_name || !suffix) {
+ return false;
+ }
+ size_t qualified_len = strlen(qualified_name);
+ size_t suffix_len = strlen(suffix);
+ if (suffix_len > qualified_len ||
+ strcmp(qualified_name + qualified_len - suffix_len, suffix) != 0) {
+ return false;
+ }
+ return qualified_len == suffix_len || qualified_name[qualified_len - suffix_len - 1] == '.';
+}
+
+static const cbm_gbuf_node_t *find_unique_node_by_name_label_qn_suffix(const cbm_gbuf_t *gbuf,
+ const char *name,
+ const char *label,
+ const char *qn_suffix) {
+ if (!gbuf || !name || !label || !qn_suffix) {
+ return NULL;
+ }
+ const cbm_gbuf_node_t **nodes = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_by_name(gbuf, name, &nodes, &count) != 0) {
+ return NULL;
+ }
+ const cbm_gbuf_node_t *match = NULL;
+ for (int i = 0; i < count; i++) {
+ const cbm_gbuf_node_t *node = nodes[i];
+ if (!node || !node->label || !node->qualified_name || strcmp(node->label, label) != 0 ||
+ !qn_has_segment_suffix(node->qualified_name, qn_suffix)) {
+ continue;
+ }
+ if (match) {
+ return NULL;
+ }
+ match = node;
+ }
+ return match;
+}
+
+static int count_edges_between_nodes(const cbm_gbuf_t *gbuf, const cbm_gbuf_node_t *source,
+ const cbm_gbuf_node_t *target, const char *edge_type) {
+ if (!gbuf || !source || !target || !edge_type) {
+ return -1;
+ }
+ const cbm_gbuf_edge_t **edges = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_edges_by_source_type(gbuf, source->id, edge_type, &edges, &count) != 0) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < count; i++) {
+ if (edges[i] && edges[i]->target_id == target->id) {
+ matches++;
+ }
+ }
+ return matches;
+}
+
+static bool has_edge_from_callable_to_node(const cbm_gbuf_t *gbuf, const char *source_tail,
+ const cbm_gbuf_node_t *target, const char *edge_type) {
+ const cbm_gbuf_node_t *source = find_unique_callable_node_by_tail(gbuf, source_tail);
+ if (!source || !target || !edge_type) {
+ return false;
+ }
+ const cbm_gbuf_edge_t **edges = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_edges_by_source_type(gbuf, source->id, edge_type, &edges, &count) != 0) {
+ return false;
+ }
+ for (int i = 0; i < count; i++) {
+ if (edges[i] && edges[i]->target_id == target->id) {
+ return true;
+ }
+ }
+ return false;
+}
+
static const cbm_gbuf_edge_t *find_calls_edge_by_tails(const cbm_gbuf_t *gbuf,
const char *source_tail,
const char *target_tail) {
@@ -616,122 +813,2013 @@ static const cbm_gbuf_edge_t *find_calls_edge_by_tails(const cbm_gbuf_t *gbuf,
return NULL;
}
-TEST(parallel_java_kotlin_lsp_override_cross_file_emits_lsp_strategy_edges) {
+static bool has_edge_from_callable_to_qn(const cbm_gbuf_t *gbuf, const char *source_tail,
+ const char *target_qn, const char *edge_type) {
+ const cbm_gbuf_node_t *source = find_unique_callable_node_by_tail(gbuf, source_tail);
+ const cbm_gbuf_node_t *target = cbm_gbuf_find_by_qn(gbuf, target_qn);
+ if (!source || !target)
+ return false;
+ const cbm_gbuf_edge_t **edges = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_edges_by_source_type(gbuf, source->id, edge_type, &edges, &count) != 0)
+ return false;
+ for (int i = 0; i < count; i++) {
+ if (edges[i] && edges[i]->target_id == target->id)
+ return true;
+ }
+ return false;
+}
+
+static bool callable_has_call_target_fragment(const cbm_gbuf_t *gbuf, const char *source_tail,
+ const char *target_fragment) {
+ const cbm_gbuf_node_t *source = find_unique_callable_node_by_tail(gbuf, source_tail);
+ if (!source || !target_fragment)
+ return false;
+ const cbm_gbuf_edge_t **edges = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_edges_by_source_type(gbuf, source->id, "CALLS", &edges, &count) != 0)
+ return false;
+ for (int i = 0; i < count; i++) {
+ const cbm_gbuf_node_t *target =
+ edges[i] ? cbm_gbuf_find_by_id(gbuf, edges[i]->target_id) : NULL;
+ if (target && target->qualified_name && strstr(target->qualified_name, target_fragment))
+ return true;
+ }
+ return false;
+}
+
+static int count_calls_edges_to_tail(const cbm_gbuf_t *gbuf, const char *target_tail) {
+ const cbm_gbuf_node_t *target = find_unique_callable_node_by_tail(gbuf, target_tail);
+ if (!target)
+ return -1;
+ const cbm_gbuf_edge_t **edges = NULL;
+ int count = 0;
+ if (cbm_gbuf_find_edges_by_target_type(gbuf, target->id, "CALLS", &edges, &count) != 0)
+ return -1;
+ return count;
+}
+
+typedef struct {
+ bool injected;
+} lsp_legacy_injection_t;
+
+/* Test-only cache mutation: preserve the real exact Alpha.render semantic
+ * record, then append a higher-confidence legacy 0:0 record for Beta.render.
+ * The shared linear matcher and the compact parallel index must both prefer
+ * the exact occurrence. */
+static void inject_higher_confidence_legacy_render(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ lsp_legacy_injection_t *state = (lsp_legacy_injection_t *)ud;
+ if (!state) {
+ return;
+ }
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache ? result_cache[file] : NULL;
+ if (!result) {
+ continue;
+ }
+ const CBMResolvedCall *exact = NULL;
+ const char *beta_qn = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *candidate = &result->resolved_calls.items[i];
+ if (candidate->kind == CBM_RESOLVED_INVOCATION && candidate->caller_qn &&
+ strstr(candidate->caller_qn, "Caller.run") && candidate->callee_qn &&
+ strstr(candidate->callee_qn, "Alpha.render") &&
+ candidate->site_end_byte > candidate->site_start_byte) {
+ exact = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->qualified_name && strstr(definition->qualified_name, "Beta.render")) {
+ beta_qn = definition->qualified_name;
+ break;
+ }
+ }
+ if (!exact || !beta_qn) {
+ continue;
+ }
+ CBMResolvedCall legacy = *exact;
+ legacy.callee_qn = beta_qn;
+ legacy.strategy = "test_legacy_zero_span";
+ legacy.confidence = 0.99f;
+ legacy.site_start_byte = 0;
+ legacy.site_end_byte = 0;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, legacy);
+ state->injected = true;
+ return;
+ }
+}
+
+TEST(parallel_lsp_index_exact_site_beats_legacy_record_in_graph) {
char tmpdir[256];
- snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_jvm_XXXXXX");
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_lsp_site_XXXXXX");
if (!cbm_mkdtemp(tmpdir)) {
FAIL("mkdtemp failed");
}
- char jpath[512];
- snprintf(jpath, sizeof(jpath), "%s/src/main/java/com/example/Example.java", tmpdir);
- char jdir[512];
- snprintf(jdir, sizeof(jdir), "%s/src/main/java/com/example", tmpdir);
- cbm_mkdir_p(jdir, 0755);
- FILE *jf = fopen(jpath, "w");
- if (!jf) {
- FAIL("fopen example.java failed");
- }
- fprintf(jf, "package com.example;\n"
- "\n"
- "class JavaCaller {\n"
- " String call(KotlinService kotlinService) {\n"
- " return kotlinService.ping(new JavaService());\n"
- " }\n"
- "}\n"
- "\n"
- "class JavaService {\n"
- " String pong() {\n"
- " return \"pong\";\n"
- " }\n"
- "}\n");
- fclose(jf);
-
- char kpath[512];
- snprintf(kpath, sizeof(kpath), "%s/src/main/kotlin/com/example/KotlinService.kt", tmpdir);
- char kdir[512];
- snprintf(kdir, sizeof(kdir), "%s/src/main/kotlin/com/example", tmpdir);
- cbm_mkdir_p(kdir, 0755);
- FILE *kf = fopen(kpath, "w");
- if (!kf) {
- unlink(jpath);
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
rmdir(tmpdir);
- FAIL("fopen example.kt failed");
+ FAIL("fopen app.py failed");
}
- fprintf(kf, "package com.example\n"
- "\n"
- "class KotlinService {\n"
- " fun ping(javaService: JavaService): String {\n"
- " return javaService.pong()\n"
- " }\n"
- "}\n");
- fclose(kf);
-
- cbm_file_info_t files[2] = {0};
- files[0].path = jpath;
- files[0].rel_path = (char *)"src/main/java/com/example/Example.java";
- files[0].language = CBM_LANG_JAVA;
- files[1].path = kpath;
- files[1].rel_path = (char *)"src/main/kotlin/com/example/KotlinService.kt";
- files[1].language = CBM_LANG_KOTLIN;
+ fprintf(file, "class Alpha:\n"
+ " def render(self):\n"
+ " return 'alpha'\n"
+ "\n"
+ "class Beta:\n"
+ " def render(self):\n"
+ " return 'beta'\n"
+ "\n"
+ "class Caller:\n"
+ " def run(self):\n"
+ " value = Alpha()\n"
+ " return value.render()\n");
+ fclose(file);
- cbm_gbuf_t *gbuf = run_parallel("com", tmpdir, files, 2, 2);
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"app.py";
+ files[0].language = CBM_LANG_PYTHON;
+ lsp_legacy_injection_t injection = {0};
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_par_lsp_site", tmpdir, files, 1, 1, NULL, inject_higher_confidence_legacy_render,
+ &injection, false);
ASSERT_NOT_NULL(gbuf);
+ ASSERT_TRUE(injection.injected);
- const cbm_gbuf_edge_t *java_to_kotlin =
- find_calls_edge_by_tails(gbuf, "JavaCaller.call", "KotlinService.ping");
- const cbm_gbuf_edge_t *kotlin_to_java =
- find_calls_edge_by_tails(gbuf, "KotlinService.ping", "JavaService.pong");
-
- ASSERT_NOT_NULL(java_to_kotlin);
- ASSERT_NOT_NULL(kotlin_to_java);
- ASSERT_NOT_NULL(java_to_kotlin->properties_json);
- ASSERT_NOT_NULL(kotlin_to_java->properties_json);
- ASSERT_NOT_NULL(strstr(java_to_kotlin->properties_json, "\"strategy\":\"lsp"));
- ASSERT_NOT_NULL(strstr(kotlin_to_java->properties_json, "\"strategy\":\"lsp"));
- ASSERT_TRUE(strstr(java_to_kotlin->properties_json, "\"strategy\":\"callee_suffix\"") == NULL);
- ASSERT_TRUE(strstr(kotlin_to_java->properties_json, "\"strategy\":\"callee_suffix\"") == NULL);
+ const cbm_gbuf_edge_t *exact = find_calls_edge_by_tails(gbuf, "Caller.run", "Alpha.render");
+ const cbm_gbuf_edge_t *wrong = find_calls_edge_by_tails(gbuf, "Caller.run", "Beta.render");
+ if (!exact || wrong) {
+ printf(" lsp index occurrence diagnostic: exact=%s legacy_wrong=%s\n",
+ exact ? "present" : "absent", wrong ? "present" : "absent");
+ }
+ ASSERT_NOT_NULL(exact);
+ ASSERT_NULL(wrong);
cbm_gbuf_free(gbuf);
- unlink(kpath);
- unlink(jpath);
+ unlink(path);
rmdir(tmpdir);
PASS();
}
-/* Gate guard for the JVM-only unique-tail fallbacks (lsp_resolve.h).
- *
- * The tail fallbacks join LSP overrides across QN drift by unique
- * "Class.method" leaf. That is only sound where class-per-file package
- * semantics hold (Java/Kotlin); in any other language a single
- * wrong-module coincidence would fabricate a CALLS edge, so
- * cbm_pipeline_lsp_allow_tail_match must keep the fallbacks OFF there.
- *
- * NOTE: a natural end-to-end non-JVM coincidence fixture is impractical:
- * reaching the fallbacks requires the LSP and the textual extraction to
- * disagree on QN prefixes, which path-derived single-root languages do
- * not produce in a small fixture (that drift is precisely the JVM
- * mixed-source-root symptom the fallback exists for). So this test
- * exercises the gated branches directly: the SAME wrong-module
- * coincidence must resolve with the gate open (JVM) and must NOT with
- * the gate closed. If the gate were removed — fallbacks made
- * unconditional again — the gate-closed assertions below would fail. */
-TEST(parallel_lsp_tail_match_fallbacks_gated_to_jvm) {
- /* Policy: exactly the JVM languages. */
- ASSERT_TRUE(cbm_pipeline_lsp_allow_tail_match(CBM_LANG_JAVA));
- ASSERT_TRUE(cbm_pipeline_lsp_allow_tail_match(CBM_LANG_KOTLIN));
- ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_PYTHON));
- ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_GO));
- ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_TYPESCRIPT));
- ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_CPP));
+typedef struct {
+ bool injected;
+} lsp_exact_ambiguity_injection_t;
+
+/* Append a distinct semantic target at the same exact source occurrence and
+ * make the carrier semantic-only. Both the shared matcher and the compact
+ * parallel index must fail closed; neither confidence nor textual registry
+ * fallback may select one target. */
+static void inject_distinct_exact_render_target(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ lsp_exact_ambiguity_injection_t *state = (lsp_exact_ambiguity_injection_t *)ud;
+ if (!state) {
+ return;
+ }
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache ? result_cache[file] : NULL;
+ if (!result) {
+ continue;
+ }
+ CBMCall *carrier = NULL;
+ const CBMResolvedCall *exact = NULL;
+ const char *beta_qn = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ CBMCall *candidate = &result->calls.items[i];
+ if (candidate->callee_name && candidate->enclosing_func_qn &&
+ strstr(candidate->enclosing_func_qn, "Caller.run") &&
+ strcmp(cbm_pipeline_call_callee_leaf(candidate->callee_name), "render") == 0 &&
+ cbm_pipeline_source_site_present(candidate->site_start_byte,
+ candidate->site_end_byte)) {
+ carrier = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *candidate = &result->resolved_calls.items[i];
+ if (candidate->kind == CBM_RESOLVED_INVOCATION && candidate->caller_qn &&
+ strstr(candidate->caller_qn, "Caller.run") && candidate->callee_qn &&
+ strstr(candidate->callee_qn, "Alpha.render") &&
+ cbm_pipeline_source_site_present(candidate->site_start_byte,
+ candidate->site_end_byte)) {
+ exact = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->qualified_name && strstr(definition->qualified_name, "Beta.render")) {
+ beta_qn = definition->qualified_name;
+ break;
+ }
+ }
+ if (!carrier || !exact || !beta_qn ||
+ !cbm_pipeline_source_site_eq(carrier->site_start_byte, carrier->site_end_byte,
+ exact->site_start_byte, exact->site_end_byte)) {
+ continue;
+ }
+ carrier->requires_lsp_resolution = true;
+ CBMResolvedCall ambiguous = *exact;
+ ambiguous.callee_qn = beta_qn;
+ ambiguous.strategy = "test_distinct_exact_target";
+ ambiguous.confidence = 0.99f;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, ambiguous);
+ state->injected = true;
+ return;
+ }
+}
- /* Wrong-module coincidence: the resolved entry's caller shares only
- * the "Service.handle" tail with the textual call's enclosing
- * function, so the exact caller_qn pass misses and only the tail
- * fallback could join them. */
- CBMResolvedCall rc_item = {0};
- rc_item.caller_qn = "com.example.pkg.Service.handle";
- rc_item.callee_qn = "com.example.pkg.Helper.run";
+TEST(parallel_lsp_index_distinct_exact_targets_fail_closed_in_graph) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_lsp_ambiguous_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen app.py failed");
+ }
+ fprintf(file, "class Alpha:\n"
+ " def render(self): return 'alpha'\n"
+ "class Beta:\n"
+ " def render(self): return 'beta'\n"
+ "class Caller:\n"
+ " def run(self):\n"
+ " value = Alpha()\n"
+ " return value.render()\n");
+ fclose(file);
+
+ cbm_file_info_t file_info = {0};
+ file_info.path = path;
+ file_info.rel_path = (char *)"app.py";
+ file_info.language = CBM_LANG_PYTHON;
+ lsp_exact_ambiguity_injection_t injection = {0};
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_par_lsp_ambiguous", tmpdir, &file_info, 1, 1, NULL,
+ inject_distinct_exact_render_target, &injection, false);
+ ASSERT_NOT_NULL(gbuf);
+ ASSERT_TRUE(injection.injected);
+ ASSERT_NOT_NULL(find_unique_callable_node_by_tail(gbuf, "Alpha.render"));
+ ASSERT_NOT_NULL(find_unique_callable_node_by_tail(gbuf, "Beta.render"));
+ const cbm_gbuf_edge_t *alpha = find_calls_edge_by_tails(gbuf, "Caller.run", "Alpha.render");
+ const cbm_gbuf_edge_t *beta = find_calls_edge_by_tails(gbuf, "Caller.run", "Beta.render");
+ if (alpha || beta) {
+ printf(" lsp exact ambiguity diagnostic: alpha=%s beta=%s\n", alpha ? "present" : "absent",
+ beta ? "present" : "absent");
+ }
+ ASSERT_NULL(alpha);
+ ASSERT_NULL(beta);
+
+ cbm_gbuf_free(gbuf);
+ unlink(path);
+ rmdir(tmpdir);
+ PASS();
+}
+
+typedef struct {
+ lsp_exact_ambiguity_injection_t ambiguity;
+ bool legacy_injected;
+ bool carrier_allows_fallback;
+ bool shared_matcher_failed_closed;
+} lsp_exact_ambiguity_legacy_probe_t;
+
+/* Reuse the exact-ambiguity injection above, then add a unique 0:0 row while
+ * leaving the carrier eligible for legacy resolution. The authoritative
+ * matcher must keep the exact-site ambiguity authoritative; the compact
+ * parallel index must not reinterpret its tombstone as "try legacy". */
+static void inject_legacy_after_exact_render_ambiguity(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ lsp_exact_ambiguity_legacy_probe_t *probe = (lsp_exact_ambiguity_legacy_probe_t *)ud;
+ if (!probe) {
+ return;
+ }
+ inject_distinct_exact_render_target(result_cache, file_count, &probe->ambiguity);
+ if (!probe->ambiguity.injected) {
+ return;
+ }
+
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache ? result_cache[file] : NULL;
+ if (!result) {
+ continue;
+ }
+ CBMCall *carrier = NULL;
+ const CBMResolvedCall *exact = NULL;
+ const char *legacy_qn = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ CBMCall *candidate = &result->calls.items[i];
+ if (candidate->callee_name && candidate->enclosing_func_qn &&
+ strstr(candidate->enclosing_func_qn, "Caller.run") &&
+ strcmp(cbm_pipeline_call_callee_leaf(candidate->callee_name), "render") == 0 &&
+ cbm_pipeline_source_site_present(candidate->site_start_byte,
+ candidate->site_end_byte)) {
+ carrier = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *candidate = &result->resolved_calls.items[i];
+ if (candidate->kind == CBM_RESOLVED_INVOCATION && candidate->caller_qn &&
+ strstr(candidate->caller_qn, "Caller.run") && candidate->callee_qn &&
+ strstr(candidate->callee_qn, "Alpha.render") &&
+ cbm_pipeline_source_site_present(candidate->site_start_byte,
+ candidate->site_end_byte)) {
+ exact = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->qualified_name && strstr(definition->qualified_name, "Legacy.render")) {
+ legacy_qn = definition->qualified_name;
+ break;
+ }
+ }
+ if (!carrier || !exact || !legacy_qn ||
+ !cbm_pipeline_source_site_eq(carrier->site_start_byte, carrier->site_end_byte,
+ exact->site_start_byte, exact->site_end_byte)) {
+ continue;
+ }
+
+ carrier->requires_lsp_resolution = false;
+ CBMResolvedCall legacy = *exact;
+ legacy.callee_qn = legacy_qn;
+ legacy.strategy = "test_legacy_after_exact_ambiguity";
+ legacy.confidence = 0.99f;
+ legacy.site_start_byte = 0;
+ legacy.site_end_byte = 0;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, legacy);
+
+ probe->legacy_injected = true;
+ probe->carrier_allows_fallback = !carrier->requires_lsp_resolution;
+ probe->shared_matcher_failed_closed =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, carrier, false) == NULL;
+ return;
+ }
+}
+
+TEST(parallel_lsp_index_exact_ambiguity_does_not_fall_through_to_legacy) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_lsp_ambiguous_legacy_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen app.py failed");
+ }
+ fprintf(file, "class Alpha:\n"
+ " def render(self): return 'alpha'\n"
+ "class Beta:\n"
+ " def render(self): return 'beta'\n"
+ "class Legacy:\n"
+ " def render(self): return 'legacy'\n"
+ "class Caller:\n"
+ " def run(self):\n"
+ " value = Alpha()\n"
+ " return value.render()\n");
+ fclose(file);
+
+ cbm_file_info_t file_info = {0};
+ file_info.path = path;
+ file_info.rel_path = (char *)"app.py";
+ file_info.language = CBM_LANG_PYTHON;
+ lsp_exact_ambiguity_legacy_probe_t probe = {0};
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_par_lsp_ambiguous_legacy", tmpdir, &file_info, 1, 1, NULL,
+ inject_legacy_after_exact_render_ambiguity, &probe, false);
+ ASSERT_NOT_NULL(gbuf);
+
+ int alpha_edges = count_calls_edges_to_tail(gbuf, "Alpha.render");
+ int beta_edges = count_calls_edges_to_tail(gbuf, "Beta.render");
+ int legacy_edges = count_calls_edges_to_tail(gbuf, "Legacy.render");
+ const cbm_gbuf_edge_t *legacy_edge =
+ find_calls_edge_by_tails(gbuf, "Caller.run", "Legacy.render");
+ if (!probe.ambiguity.injected || !probe.legacy_injected || !probe.carrier_allows_fallback ||
+ !probe.shared_matcher_failed_closed || alpha_edges != 1 || beta_edges != 0 ||
+ legacy_edges != 0) {
+ printf(" exact ambiguity + legacy diagnostic: exact_ambiguity=%d legacy=%d "
+ "fallback_allowed=%d shared_failed_closed=%d alpha=%d beta=%d legacy_edge=%d "
+ "props=%s\n",
+ probe.ambiguity.injected, probe.legacy_injected, probe.carrier_allows_fallback,
+ probe.shared_matcher_failed_closed, alpha_edges, beta_edges, legacy_edges,
+ legacy_edge && legacy_edge->properties_json ? legacy_edge->properties_json : "");
+ }
+
+ cbm_gbuf_free(gbuf);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(probe.ambiguity.injected);
+ ASSERT_TRUE(probe.legacy_injected);
+ ASSERT_TRUE(probe.carrier_allows_fallback);
+ ASSERT_TRUE(probe.shared_matcher_failed_closed);
+ /* The ordinary registry/type fallback may still recover the source-proven
+ * Alpha receiver. Only the lower-ranked legacy semantic row is forbidden. */
+ ASSERT_EQ(alpha_edges, 1);
+ ASSERT_EQ(beta_edges, 0);
+ ASSERT_EQ(legacy_edges, 0);
+ PASS();
+}
+
+typedef struct {
+ bool injected;
+ bool authoritative_exact_wins;
+ bool legacy_key_fits;
+ bool exact_key_overflows;
+} lsp_long_key_probe_t;
+
+static void inject_long_caller_exact_and_legacy(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ lsp_long_key_probe_t *probe = (lsp_long_key_probe_t *)ud;
+ if (!probe)
+ return;
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache ? result_cache[file] : NULL;
+ if (!result)
+ continue;
+ CBMCall *carrier = NULL;
+ CBMResolvedCall *exact = NULL;
+ const char *beta_qn = NULL;
+ for (int i = 0; i < result->calls.count; i++) {
+ CBMCall *candidate = &result->calls.items[i];
+ if (candidate->callee_name &&
+ strcmp(cbm_pipeline_call_callee_leaf(candidate->callee_name), "render") == 0) {
+ carrier = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ CBMResolvedCall *candidate = &result->resolved_calls.items[i];
+ if (candidate->kind == CBM_RESOLVED_INVOCATION && candidate->callee_qn &&
+ strstr(candidate->callee_qn, "Alpha.render") &&
+ candidate->site_end_byte > candidate->site_start_byte) {
+ exact = candidate;
+ break;
+ }
+ }
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->qualified_name && strstr(definition->qualified_name, "Beta.render")) {
+ beta_qn = definition->qualified_name;
+ break;
+ }
+ }
+ if (!carrier || !exact || !beta_qn)
+ continue;
+
+ CBMResolvedCall legacy = *exact;
+ legacy.callee_qn = beta_qn;
+ legacy.strategy = "test_long_key_legacy";
+ legacy.confidence = 0.99f;
+ legacy.site_start_byte = 0;
+ legacy.site_end_byte = 0;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, legacy);
+
+ size_t leaf_len = strlen("render");
+ size_t legacy_len = strlen(carrier->enclosing_func_qn) + 1U + leaf_len;
+ char site_suffix[64];
+ int suffix_len = snprintf(site_suffix, sizeof(site_suffix), "|%u:%u",
+ carrier->site_start_byte, carrier->site_end_byte);
+ size_t exact_len = legacy_len + (suffix_len > 0 ? (size_t)suffix_len : 0U);
+ probe->legacy_key_fits = legacy_len < 1024U;
+ probe->exact_key_overflows = exact_len >= 1024U;
+ const CBMResolvedCall *authoritative =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, carrier, false);
+ probe->authoritative_exact_wins = authoritative && authoritative->callee_qn &&
+ strstr(authoritative->callee_qn, "Alpha.render") != NULL;
+ probe->injected = true;
+ return;
+ }
+}
+
+TEST(parallel_lsp_long_exact_key_never_yields_legacy_target) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_lsp_long_key_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir))
+ FAIL("mkdtemp failed");
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen app.py failed");
+ }
+ enum { FUNCTION_NAME_LEN = 997 };
+ char function_name[FUNCTION_NAME_LEN + 1];
+ memcpy(function_name, "run_", 4);
+ memset(function_name + 4, 'q', FUNCTION_NAME_LEN - 4);
+ function_name[FUNCTION_NAME_LEN] = '\0';
+ fputs("class Alpha:\n"
+ " def render(self):\n"
+ " return 'alpha'\n"
+ "class Beta:\n"
+ " def render(self):\n"
+ " return 'beta'\n",
+ file);
+ fprintf(file, "def %s(value: Alpha):\n return value.render()\n", function_name);
+ fclose(file);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"app.py";
+ files[0].language = CBM_LANG_PYTHON;
+ lsp_long_key_probe_t probe = {0};
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_long_key", tmpdir, files, 1, 1, NULL, inject_long_caller_exact_and_legacy, &probe,
+ false);
+ ASSERT_NOT_NULL(gbuf);
+ int alpha_edges = count_calls_edges_to_tail(gbuf, "Alpha.render");
+ int beta_edges = count_calls_edges_to_tail(gbuf, "Beta.render");
+ if (!probe.injected || !probe.authoritative_exact_wins || !probe.legacy_key_fits ||
+ !probe.exact_key_overflows || alpha_edges < 1 || beta_edges != 0) {
+ printf(" long exact-key diagnostic: injected=%d authoritative=%d legacy_fits=%d "
+ "exact_overflow=%d alpha=%d beta=%d\n",
+ probe.injected, probe.authoritative_exact_wins, probe.legacy_key_fits,
+ probe.exact_key_overflows, alpha_edges, beta_edges);
+ }
+ cbm_gbuf_free(gbuf);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(probe.injected);
+ ASSERT_TRUE(probe.authoritative_exact_wins);
+ ASSERT_TRUE(probe.legacy_key_fits);
+ ASSERT_TRUE(probe.exact_key_overflows);
+ ASSERT_GTE(alpha_edges, 1);
+ ASSERT_EQ(beta_edges, 0);
+ PASS();
+}
+
+typedef struct {
+ int carrier_count;
+ int exact_match_count;
+} lsp_synthetic_index_probe_t;
+
+static void inspect_synthetic_add_occurrences(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ lsp_synthetic_index_probe_t *probe = (lsp_synthetic_index_probe_t *)ud;
+ if (!probe) {
+ return;
+ }
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache[file];
+ if (!result) {
+ continue;
+ }
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->requires_lsp_resolution || !call->callee_name ||
+ strcmp(call->callee_name, "__add__") != 0 ||
+ !cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte)) {
+ continue;
+ }
+ probe->carrier_count++;
+ const CBMResolvedCall *resolved =
+ cbm_pipeline_find_lsp_resolution(&result->resolved_calls, call, false);
+ if (resolved &&
+ cbm_pipeline_source_site_eq(call->site_start_byte, call->site_end_byte,
+ resolved->site_start_byte, resolved->site_end_byte)) {
+ probe->exact_match_count++;
+ }
+ }
+ }
+}
+
+TEST(parallel_lsp_exact_index_handles_repeated_synthetic_occurrences_without_linear_scan) {
+ enum { OCCURRENCES = 128 };
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_lsp_perf_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen app.py failed");
+ }
+ fprintf(file, "class Number:\n"
+ " def __add__(self, other):\n"
+ " return self\n"
+ "\n"
+ "def combine(left: Number, right: Number):\n");
+ for (int i = 0; i < OCCURRENCES; i++) {
+ fprintf(file, " value = left + right\n");
+ }
+ fprintf(file, " return value\n");
+ fclose(file);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"app.py";
+ files[0].language = CBM_LANG_PYTHON;
+ lsp_synthetic_index_probe_t probe = {0};
+ cbm_pp_lsp_linear_fallback_rows_reset();
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_par_lsp_perf", tmpdir, files, 1, 1, NULL, inspect_synthetic_add_occurrences, &probe,
+ false);
+ ASSERT_NOT_NULL(gbuf);
+ ASSERT_EQ(probe.carrier_count, OCCURRENCES);
+ ASSERT_EQ(probe.exact_match_count, OCCURRENCES);
+ ASSERT_NOT_NULL(find_calls_edge_by_tails(gbuf, "app.combine", "Number.__add__"));
+ uint64_t fallback_rows = cbm_pp_lsp_linear_fallback_rows();
+ if (fallback_rows != 0) {
+ printf(" synthetic exact-index diagnostic: occurrences=%d linear_rows=%llu\n", OCCURRENCES,
+ (unsigned long long)fallback_rows);
+ }
+ ASSERT_EQ(fallback_rows, 0);
+
+ cbm_gbuf_free(gbuf);
+ unlink(path);
+ rmdir(tmpdir);
+ PASS();
+}
+
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+enum { CALL_REFERENCE_SCALE_OCCURRENCES = 128 };
+
+typedef struct {
+ bool injected;
+ int reference_count;
+} call_reference_scale_probe_t;
+
+/* Replace incidental extractor usages with a deterministic one-to-one set of
+ * exact callable references. Every target is a real extracted Function node,
+ * so the fused resolver must traverse its ordinary usage-materialization path
+ * and emit 128 distinct CALL_REFERENCE edges. */
+static void inject_call_reference_scale_rows(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ call_reference_scale_probe_t *probe = (call_reference_scale_probe_t *)ud;
+ if (!probe || !result_cache) {
+ return;
+ }
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache[file];
+ if (!result) {
+ continue;
+ }
+ const char *caller_qn = NULL;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && strcmp(definition->name, "scale_caller") == 0) {
+ caller_qn = definition->qualified_name;
+ break;
+ }
+ }
+ if (!caller_qn) {
+ continue;
+ }
+
+ result->usages.count = 0;
+ result->resolved_calls.count = 0;
+ int inserted = 0;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *target = &result->defs.items[i];
+ if (!target->name || !target->qualified_name ||
+ strncmp(target->name, "scale_target_", strlen("scale_target_")) != 0) {
+ continue;
+ }
+ uint32_t start = 10000U + (uint32_t)inserted * 16U;
+ CBMUsage usage = {0};
+ usage.ref_name = target->name;
+ usage.enclosing_func_qn = caller_qn;
+ usage.kind = CBM_USAGE_CALL_REFERENCE;
+ usage.may_be_call_reference = true;
+ /* Exact occurrence proof must win even when lexical evidence
+ * forbids the later raw-name fallback. */
+ usage.semantic_reference_blocked = true;
+ usage.semantic_reference_local_shadow = true;
+ usage.site_start_byte = start;
+ usage.site_end_byte = start + (uint32_t)strlen(target->name);
+ cbm_usages_push(&result->usages, &result->arena, usage);
+
+ CBMResolvedCall resolved = {0};
+ resolved.caller_qn = caller_qn;
+ resolved.callee_qn = target->qualified_name;
+ resolved.strategy = "test_exact_reference_scale";
+ resolved.confidence = 0.95f;
+ resolved.kind = CBM_RESOLVED_CALL_REFERENCE;
+ resolved.site_start_byte = usage.site_start_byte;
+ resolved.site_end_byte = usage.site_end_byte;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, resolved);
+ inserted++;
+ }
+ probe->reference_count = inserted;
+ probe->injected = inserted == CALL_REFERENCE_SCALE_OCCURRENCES;
+ return;
+ }
+}
+
+TEST(parallel_call_reference_lookup_rows_grow_linearly) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_ref_scale_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.py", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen app.py failed");
+ }
+ for (int i = 0; i < CALL_REFERENCE_SCALE_OCCURRENCES; i++) {
+ fprintf(file, "def scale_target_%03d():\n return %d\n", i, i);
+ }
+ fputs("def scale_caller():\n return None\n", file);
+ fclose(file);
+
+ cbm_file_info_t file_info = {0};
+ file_info.path = path;
+ file_info.rel_path = (char *)"app.py";
+ file_info.language = CBM_LANG_PYTHON;
+ call_reference_scale_probe_t probe = {0};
+
+ cbm_pipeline_lsp_reference_lookup_test_reset();
+ cbm_gbuf_t *gbuf = run_parallel_with_extract_opts_and_mutator(
+ "cbm_par_ref_scale", tmpdir, &file_info, 1, 1, NULL, inject_call_reference_scale_rows,
+ &probe, false);
+ uint64_t rows_examined = cbm_pipeline_lsp_reference_lookup_test_rows_examined();
+
+ const cbm_gbuf_node_t *caller =
+ gbuf ? find_unique_callable_node_by_tail(gbuf, "app.scale_caller") : NULL;
+ const cbm_gbuf_edge_t **edges = NULL;
+ int edge_count = 0;
+ int lookup_rc = caller ? cbm_gbuf_find_edges_by_source_type(gbuf, caller->id, "CALL_REFERENCE",
+ &edges, &edge_count)
+ : -1;
+ int exact_target_edges = 0;
+ for (int i = 0; lookup_rc == 0 && i < edge_count; i++) {
+ const cbm_gbuf_node_t *target =
+ edges[i] ? cbm_gbuf_find_by_id(gbuf, edges[i]->target_id) : NULL;
+ if (target && target->name &&
+ strncmp(target->name, "scale_target_", strlen("scale_target_")) == 0) {
+ exact_target_edges++;
+ }
+ }
+
+ uint64_t linear_budget = (uint64_t)CALL_REFERENCE_SCALE_OCCURRENCES * 8U;
+ if (!probe.injected || lookup_rc != 0 || edge_count != CALL_REFERENCE_SCALE_OCCURRENCES ||
+ exact_target_edges != CALL_REFERENCE_SCALE_OCCURRENCES || rows_examined > linear_budget) {
+ printf(" call-reference lookup scale diagnostic: injected=%d references=%d "
+ "edges=%d exact_targets=%d rows=%llu budget=%llu\n",
+ probe.injected, probe.reference_count, edge_count, exact_target_edges,
+ (unsigned long long)rows_examined, (unsigned long long)linear_budget);
+ }
+
+ cbm_gbuf_free(gbuf);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(probe.injected);
+ ASSERT_EQ(probe.reference_count, CALL_REFERENCE_SCALE_OCCURRENCES);
+ ASSERT_EQ(lookup_rc, 0);
+ ASSERT_EQ(edge_count, CALL_REFERENCE_SCALE_OCCURRENCES);
+ ASSERT_EQ(exact_target_edges, CALL_REFERENCE_SCALE_OCCURRENCES);
+ /* The current full scan examines N rows for every one of N usages:
+ * 128*128 = 16,384. A site index should keep this below a small linear
+ * allowance while retaining the exact target/ambiguity checks. */
+ ASSERT_LTE(rows_examined, linear_budget);
+ PASS();
+}
+#endif
+
+/* A lexical callable named like a module component owns the JSX occurrence.
+ * Keep a direct component call as a positive control, and require both graph
+ * builders to reject textual fallback for the shadowed tag. */
+TEST(parallel_tsx_local_component_shadow_has_no_false_call) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_tsx_shadow_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/main.tsx", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen main.tsx failed");
+ }
+ fputs("function Card(): JSX.Element { return <div/>; }\n"
+ "function Good(): JSX.Element { return <Card/>; }\n"
+ "function Shadowed(Card: () => JSX.Element): JSX.Element { return <Card/>; }\n",
+ file);
+ fclose(file);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"main.tsx";
+ files[0].language = CBM_LANG_TSX;
+ cbm_gbuf_t *sequential = run_sequential("cbm_tsx_shadow", tmpdir, files, 1);
+ cbm_gbuf_t *parallel = run_parallel("cbm_tsx_shadow", tmpdir, files, 1, 1);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const bool sequential_nodes = find_unique_callable_node_by_tail(sequential, "main.Card") &&
+ find_unique_callable_node_by_tail(sequential, "main.Good") &&
+ find_unique_callable_node_by_tail(sequential, "main.Shadowed");
+ const bool parallel_nodes = find_unique_callable_node_by_tail(parallel, "main.Card") &&
+ find_unique_callable_node_by_tail(parallel, "main.Good") &&
+ find_unique_callable_node_by_tail(parallel, "main.Shadowed");
+ const bool sequential_good =
+ find_calls_edge_by_tails(sequential, "main.Good", "main.Card") != NULL;
+ const bool parallel_good = find_calls_edge_by_tails(parallel, "main.Good", "main.Card") != NULL;
+ const bool sequential_wrong =
+ find_calls_edge_by_tails(sequential, "main.Shadowed", "main.Card") != NULL;
+ const bool parallel_wrong =
+ find_calls_edge_by_tails(parallel, "main.Shadowed", "main.Card") != NULL;
+ if (!sequential_nodes || !parallel_nodes || !sequential_good || !parallel_good ||
+ sequential_wrong || parallel_wrong) {
+ printf(" TSX shadow graph diagnostic: seq_nodes=%d par_nodes=%d seq_good=%d "
+ "par_good=%d seq_wrong=%d par_wrong=%d\n",
+ sequential_nodes, parallel_nodes, sequential_good, parallel_good, sequential_wrong,
+ parallel_wrong);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(sequential_nodes);
+ ASSERT_TRUE(parallel_nodes);
+ ASSERT_TRUE(sequential_good);
+ ASSERT_TRUE(parallel_good);
+ ASSERT_FALSE(sequential_wrong);
+ ASSERT_FALSE(parallel_wrong);
+ PASS();
+}
+
+typedef struct {
+ bool injected;
+} exact_noncallable_reference_probe_t;
+
+static void inject_exact_noncallable_reference(CBMFileResult **result_cache, int file_count,
+ void *ud) {
+ exact_noncallable_reference_probe_t *probe = (exact_noncallable_reference_probe_t *)ud;
+ if (!probe || !result_cache) {
+ return;
+ }
+ for (int file = 0; file < file_count; file++) {
+ CBMFileResult *result = result_cache[file];
+ if (!result) {
+ continue;
+ }
+ const char *caller_qn = NULL;
+ const char *target_qn = NULL;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (definition->name && definition->qualified_name &&
+ strcmp(definition->name, "carrier") == 0) {
+ caller_qn = definition->qualified_name;
+ }
+ if (definition->name && definition->qualified_name && definition->label &&
+ strcmp(definition->name, "semanticValue") == 0 &&
+ strcmp(definition->label, "Variable") == 0) {
+ target_qn = definition->qualified_name;
+ }
+ }
+ if (!caller_qn || !target_qn) {
+ continue;
+ }
+
+ result->usages.count = 0;
+ result->resolved_calls.count = 0;
+ CBMUsage usage = {0};
+ usage.ref_name = "semanticAlias";
+ usage.enclosing_func_qn = caller_qn;
+ usage.kind = CBM_USAGE_VALUE;
+ usage.may_be_call_reference = true;
+ /* The raw-name path is deliberately unavailable. A resulting USAGE
+ * therefore proves that the exact semantic row was joined and then
+ * classified by the materialized target's non-callable label. */
+ usage.semantic_reference_blocked = true;
+ usage.site_start_byte = 40000U;
+ usage.site_end_byte = 40000U + (uint32_t)strlen(usage.ref_name);
+ cbm_usages_push(&result->usages, &result->arena, usage);
+
+ CBMResolvedCall resolved = {0};
+ resolved.caller_qn = caller_qn;
+ resolved.callee_qn = target_qn;
+ resolved.strategy = "lsp_callable_value_reference";
+ resolved.reason = usage.ref_name;
+ resolved.confidence = 0.99f;
+ resolved.kind = CBM_RESOLVED_CALL_REFERENCE;
+ resolved.site_start_byte = usage.site_start_byte;
+ resolved.site_end_byte = usage.site_end_byte;
+ cbm_resolvedcall_push(&result->resolved_calls, &result->arena, resolved);
+ probe->injected = true;
+ return;
+ }
+}
+
+TEST(parallel_exact_semantic_noncallable_target_stays_usage) {
+ static const char source[] = "const semanticValue = 1;\n"
+ "function consume(value: unknown): void {}\n"
+ "export function carrier(): void { consume(semanticValue); }\n";
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_exact_noncallable_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/app.ts", tmpdir);
+ if (th_write_file(path, source) != 0) {
+ th_rmtree(tmpdir);
+ FAIL("failed to write exact non-callable fixture");
+ }
+ cbm_file_info_t file = {0};
+ file.path = path;
+ file.rel_path = (char *)"app.ts";
+ file.language = CBM_LANG_TYPESCRIPT;
+ exact_noncallable_reference_probe_t sequential_probe = {0};
+ exact_noncallable_reference_probe_t parallel_probe = {0};
+ cbm_gbuf_t *sequential = run_sequential_with_lsp_cross_and_mutator(
+ "cbm_exact_noncallable", tmpdir, &file, 1, inject_exact_noncallable_reference,
+ &sequential_probe, false);
+ cbm_gbuf_t *parallel = run_parallel_with_extract_opts_and_mutator(
+ "cbm_exact_noncallable", tmpdir, &file, 1, 1, NULL, inject_exact_noncallable_reference,
+ &parallel_probe, false);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const cbm_gbuf_node_t *sequential_target = find_unique_node_by_name_label_qn_suffix(
+ sequential, "semanticValue", "Variable", "app.semanticValue");
+ const cbm_gbuf_node_t *parallel_target = find_unique_node_by_name_label_qn_suffix(
+ parallel, "semanticValue", "Variable", "app.semanticValue");
+ const bool sequential_usage =
+ has_edge_from_callable_to_node(sequential, "app.carrier", sequential_target, "USAGE");
+ const bool parallel_usage =
+ has_edge_from_callable_to_node(parallel, "app.carrier", parallel_target, "USAGE");
+ const bool sequential_promoted =
+ has_edge_from_callable_to_node(sequential, "app.carrier", sequential_target,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(sequential, "app.carrier", sequential_target, "CALLS");
+ const bool parallel_promoted =
+ has_edge_from_callable_to_node(parallel, "app.carrier", parallel_target,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(parallel, "app.carrier", parallel_target, "CALLS");
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ th_rmtree(tmpdir);
+ ASSERT_TRUE(sequential_probe.injected);
+ ASSERT_TRUE(parallel_probe.injected);
+ ASSERT_NOT_NULL(sequential_target);
+ ASSERT_NOT_NULL(parallel_target);
+ ASSERT_TRUE(sequential_usage);
+ ASSERT_TRUE(parallel_usage);
+ ASSERT_FALSE(sequential_promoted);
+ ASSERT_FALSE(parallel_promoted);
+ PASS();
+}
+
+/* A value argument whose exact target is a module Variable remains an ordinary
+ * USAGE even when the TS semantic pass marks the occurrence as reference-like.
+ * Conversely, a parameter or local declaration with the same spelling owns its
+ * lexical occurrence and must not fall through to the module Variable. Exercise
+ * both the sequential pass_usages path and the fused parallel resolver. */
+TEST(parallel_typescript_module_value_usage_respects_lexical_shadows) {
+ static const char settings_source[] =
+ "export const config = { enabled: true };\n"
+ "function consumeConfig(value: { enabled: boolean }): void {}\n"
+ "export function moduleArgument(): void { consumeConfig(config); }\n";
+ static const char shadows_source[] =
+ "import { config } from './settings';\n"
+ "function consumeShadow(value: { enabled: boolean }): void {}\n"
+ "export function parameterShadow(config: { enabled: boolean }): void {\n"
+ " consumeShadow(config);\n"
+ "}\n"
+ "export function localShadow(): void {\n"
+ " const config = { enabled: false };\n"
+ " consumeShadow(config);\n"
+ "}\n";
+
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_ts_usage_scope_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char settings_path[512];
+ char shadows_path[512];
+ snprintf(settings_path, sizeof(settings_path), "%s/settings.ts", tmpdir);
+ snprintf(shadows_path, sizeof(shadows_path), "%s/shadows.ts", tmpdir);
+ if (th_write_file(settings_path, settings_source) != 0 ||
+ th_write_file(shadows_path, shadows_source) != 0) {
+ th_rmtree(tmpdir);
+ FAIL("failed to write TypeScript usage-scope fixture");
+ }
+
+ cbm_file_info_t files[2] = {0};
+ files[0].path = settings_path;
+ files[0].rel_path = (char *)"settings.ts";
+ files[0].language = CBM_LANG_TYPESCRIPT;
+ files[1].path = shadows_path;
+ files[1].rel_path = (char *)"shadows.ts";
+ files[1].language = CBM_LANG_TYPESCRIPT;
+ cbm_gbuf_t *sequential = run_sequential("cbm_ts_usage_scope", tmpdir, files, 2);
+ cbm_gbuf_t *parallel = run_parallel("cbm_ts_usage_scope", tmpdir, files, 2, 2);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const cbm_gbuf_node_t *sequential_config = find_unique_node_by_name_label_qn_suffix(
+ sequential, "config", "Variable", "settings.config");
+ const cbm_gbuf_node_t *parallel_config =
+ find_unique_node_by_name_label_qn_suffix(parallel, "config", "Variable", "settings.config");
+ const bool sequential_target = sequential_config != NULL;
+ const bool parallel_target = parallel_config != NULL;
+ const bool sequential_callers =
+ find_unique_callable_node_by_tail(sequential, "settings.moduleArgument") &&
+ find_unique_callable_node_by_tail(sequential, "shadows.parameterShadow") &&
+ find_unique_callable_node_by_tail(sequential, "shadows.localShadow");
+ const bool parallel_callers =
+ find_unique_callable_node_by_tail(parallel, "settings.moduleArgument") &&
+ find_unique_callable_node_by_tail(parallel, "shadows.parameterShadow") &&
+ find_unique_callable_node_by_tail(parallel, "shadows.localShadow");
+
+ const bool sequential_module_usage = has_edge_from_callable_to_node(
+ sequential, "settings.moduleArgument", sequential_config, "USAGE");
+ const bool parallel_module_usage = has_edge_from_callable_to_node(
+ parallel, "settings.moduleArgument", parallel_config, "USAGE");
+ const bool sequential_module_reference =
+ has_edge_from_callable_to_node(sequential, "settings.moduleArgument", sequential_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(sequential, "settings.moduleArgument", sequential_config,
+ "CALLS");
+ const bool parallel_module_reference =
+ has_edge_from_callable_to_node(parallel, "settings.moduleArgument", parallel_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(parallel, "settings.moduleArgument", parallel_config,
+ "CALLS");
+ const bool sequential_parameter_leak =
+ has_edge_from_callable_to_node(sequential, "shadows.parameterShadow", sequential_config,
+ "USAGE") ||
+ has_edge_from_callable_to_node(sequential, "shadows.parameterShadow", sequential_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(sequential, "shadows.parameterShadow", sequential_config,
+ "CALLS");
+ const bool parallel_parameter_leak =
+ has_edge_from_callable_to_node(parallel, "shadows.parameterShadow", parallel_config,
+ "USAGE") ||
+ has_edge_from_callable_to_node(parallel, "shadows.parameterShadow", parallel_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(parallel, "shadows.parameterShadow", parallel_config,
+ "CALLS");
+ const bool sequential_local_leak =
+ has_edge_from_callable_to_node(sequential, "shadows.localShadow", sequential_config,
+ "USAGE") ||
+ has_edge_from_callable_to_node(sequential, "shadows.localShadow", sequential_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(sequential, "shadows.localShadow", sequential_config,
+ "CALLS");
+ const bool parallel_local_leak =
+ has_edge_from_callable_to_node(parallel, "shadows.localShadow", parallel_config, "USAGE") ||
+ has_edge_from_callable_to_node(parallel, "shadows.localShadow", parallel_config,
+ "CALL_REFERENCE") ||
+ has_edge_from_callable_to_node(parallel, "shadows.localShadow", parallel_config, "CALLS");
+
+ if (!sequential_target || !parallel_target || !sequential_callers || !parallel_callers ||
+ !sequential_module_usage || !parallel_module_usage || sequential_module_reference ||
+ parallel_module_reference || sequential_parameter_leak || parallel_parameter_leak ||
+ sequential_local_leak || parallel_local_leak) {
+ printf(" TS module-value diagnostic: target=%d/%d callers=%d/%d usage=%d/%d "
+ "reference=%d/%d parameter_leak=%d/%d local_leak=%d/%d\n",
+ sequential_target, parallel_target, sequential_callers, parallel_callers,
+ sequential_module_usage, parallel_module_usage, sequential_module_reference,
+ parallel_module_reference, sequential_parameter_leak, parallel_parameter_leak,
+ sequential_local_leak, parallel_local_leak);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ th_rmtree(tmpdir);
+ ASSERT_TRUE(sequential_target);
+ ASSERT_TRUE(parallel_target);
+ ASSERT_TRUE(sequential_callers);
+ ASSERT_TRUE(parallel_callers);
+ ASSERT_TRUE(sequential_module_usage);
+ ASSERT_TRUE(parallel_module_usage);
+ ASSERT_FALSE(sequential_module_reference);
+ ASSERT_FALSE(parallel_module_reference);
+ ASSERT_FALSE(sequential_parameter_leak);
+ ASSERT_FALSE(parallel_parameter_leak);
+ ASSERT_FALSE(sequential_local_leak);
+ ASSERT_FALSE(parallel_local_leak);
+ PASS();
+}
+
+enum {
+ TS_EXACT_SELECTED_IMPORT = 0,
+ TS_EXACT_DECOY_IMPORT,
+ TS_EXACT_LOCAL_CLASS,
+ TS_EXACT_NAMESPACE_INNER_CALL,
+ TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL,
+ TS_EXACT_EDGE_COUNT
+};
+
+typedef struct {
+ int edge_counts[2][TS_EXACT_EDGE_COUNT]; /* sequential, parallel */
+} ts_exact_parity_observation_t;
+
+static ts_exact_parity_observation_t run_ts_exact_parity_fixture(CBMLanguage main_language,
+ const char *extension,
+ const char *project) {
+ ts_exact_parity_observation_t observation;
+ for (int route = 0; route < 2; route++) {
+ for (int edge = 0; edge < TS_EXACT_EDGE_COUNT; edge++) {
+ observation.edge_counts[route][edge] = -1;
+ }
+ }
+
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_ts_exact_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ return observation;
+ }
+
+ char selected_path[512];
+ char decoy_path[512];
+ char main_path[512];
+ char main_rel[64];
+ snprintf(selected_path, sizeof(selected_path), "%s/a/types.ts", tmpdir);
+ snprintf(decoy_path, sizeof(decoy_path), "%s/b/types.ts", tmpdir);
+ snprintf(main_path, sizeof(main_path), "%s/main.%s", tmpdir, extension);
+ snprintf(main_rel, sizeof(main_rel), "main.%s", extension);
+
+ static const char type_source[] = "export interface Config { enabled: boolean }\n";
+ static const char main_source[] =
+ "import type { Config } from './a/types';\n"
+ "export function choose(cfg: Config): boolean { return cfg.enabled; }\n"
+ "namespace App {\n"
+ " export namespace Utils {\n"
+ " export function clamp(): number { return 1; }\n"
+ " export function normalise(): number { return clamp(); }\n"
+ " }\n"
+ " export class Config {\n"
+ " constructor() { Utils.normalise(); }\n"
+ " }\n"
+ "}\n";
+ if (th_write_file(selected_path, type_source) != 0 ||
+ th_write_file(decoy_path, type_source) != 0 || th_write_file(main_path, main_source) != 0) {
+ th_rmtree(tmpdir);
+ return observation;
+ }
+
+ cbm_file_info_t files[3] = {0};
+ files[0].path = selected_path;
+ files[0].rel_path = (char *)"a/types.ts";
+ files[0].language = CBM_LANG_TYPESCRIPT;
+ files[1].path = decoy_path;
+ files[1].rel_path = (char *)"b/types.ts";
+ files[1].language = CBM_LANG_TYPESCRIPT;
+ files[2].path = main_path;
+ files[2].rel_path = main_rel;
+ files[2].language = main_language;
+
+ cbm_gbuf_t *graphs[2] = {
+ run_sequential_with_lsp_cross_and_mutator(project, tmpdir, files, 3, NULL, NULL, true),
+ run_parallel_with_extract_opts_and_mutator(project, tmpdir, files, 3, 2, NULL, NULL, NULL,
+ true),
+ };
+ for (int route = 0; route < 2; route++) {
+ cbm_gbuf_t *graph = graphs[route];
+ const cbm_gbuf_node_t *choose =
+ find_unique_node_by_name_label_qn_suffix(graph, "choose", "Function", "main.choose");
+ const cbm_gbuf_node_t *selected = find_unique_node_by_name_label_qn_suffix(
+ graph, "Config", "Interface", "a.types.Config");
+ const cbm_gbuf_node_t *decoy = find_unique_node_by_name_label_qn_suffix(
+ graph, "Config", "Interface", "b.types.Config");
+ const cbm_gbuf_node_t *local_class =
+ find_unique_node_by_name_label_qn_suffix(graph, "Config", "Class", "main.App.Config");
+ const cbm_gbuf_node_t *normalise = find_unique_node_by_name_label_qn_suffix(
+ graph, "normalise", "Function", "main.App.Utils.normalise");
+ const cbm_gbuf_node_t *clamp = find_unique_node_by_name_label_qn_suffix(
+ graph, "clamp", "Function", "main.App.Utils.clamp");
+ const cbm_gbuf_node_t *constructor = find_unique_node_by_name_label_qn_suffix(
+ graph, "constructor", "Method", "main.App.Config.constructor");
+
+ observation.edge_counts[route][TS_EXACT_SELECTED_IMPORT] =
+ count_edges_between_nodes(graph, choose, selected, "USAGE");
+ observation.edge_counts[route][TS_EXACT_DECOY_IMPORT] =
+ count_edges_between_nodes(graph, choose, decoy, "USAGE");
+ observation.edge_counts[route][TS_EXACT_LOCAL_CLASS] =
+ count_edges_between_nodes(graph, choose, local_class, "USAGE");
+ observation.edge_counts[route][TS_EXACT_NAMESPACE_INNER_CALL] =
+ count_edges_between_nodes(graph, normalise, clamp, "CALLS");
+ observation.edge_counts[route][TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL] =
+ count_edges_between_nodes(graph, constructor, normalise, "CALLS");
+ }
+
+ cbm_gbuf_free(graphs[0]);
+ cbm_gbuf_free(graphs[1]);
+ th_rmtree(tmpdir);
+ return observation;
+}
+
+static void print_ts_exact_parity_diagnostic(const char *language,
+ const ts_exact_parity_observation_t *observation) {
+ printf(" %s exact parity: seq=[%d,%d,%d,%d,%d] par=[%d,%d,%d,%d,%d]\n", language,
+ observation->edge_counts[0][TS_EXACT_SELECTED_IMPORT],
+ observation->edge_counts[0][TS_EXACT_DECOY_IMPORT],
+ observation->edge_counts[0][TS_EXACT_LOCAL_CLASS],
+ observation->edge_counts[0][TS_EXACT_NAMESPACE_INNER_CALL],
+ observation->edge_counts[0][TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL],
+ observation->edge_counts[1][TS_EXACT_SELECTED_IMPORT],
+ observation->edge_counts[1][TS_EXACT_DECOY_IMPORT],
+ observation->edge_counts[1][TS_EXACT_LOCAL_CLASS],
+ observation->edge_counts[1][TS_EXACT_NAMESPACE_INNER_CALL],
+ observation->edge_counts[1][TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL]);
+}
+
+TEST(parallel_typescript_import_namespace_exact_parity) {
+ ts_exact_parity_observation_t observation =
+ run_ts_exact_parity_fixture(CBM_LANG_TYPESCRIPT, "ts", "cbm_ts_exact_parity");
+ print_ts_exact_parity_diagnostic("TypeScript", &observation);
+ for (int route = 0; route < 2; route++) {
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_SELECTED_IMPORT], 1);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_DECOY_IMPORT], 0);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_LOCAL_CLASS], 0);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_NAMESPACE_INNER_CALL], 1);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL], 1);
+ }
+ PASS();
+}
+
+TEST(parallel_tsx_import_namespace_exact_parity) {
+ ts_exact_parity_observation_t observation =
+ run_ts_exact_parity_fixture(CBM_LANG_TSX, "tsx", "cbm_tsx_exact_parity");
+ print_ts_exact_parity_diagnostic("TSX", &observation);
+ for (int route = 0; route < 2; route++) {
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_SELECTED_IMPORT], 1);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_DECOY_IMPORT], 0);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_LOCAL_CLASS], 0);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_NAMESPACE_INNER_CALL], 1);
+ ASSERT_EQ(observation.edge_counts[route][TS_EXACT_NAMESPACE_CONSTRUCTOR_CALL], 1);
+ }
+ PASS();
+}
+
+typedef struct {
+ bool carrier;
+ bool semantic;
+ bool exact_join;
+} kotlin_implicit_probe_t;
+
+static kotlin_implicit_probe_t probe_kotlin_implicit_site(const CBMFileResult *result,
+ const char *caller, const char *callee,
+ const char *target_qn,
+ const char *strategy) {
+ kotlin_implicit_probe_t probe = {0};
+ if (!result || !caller || !callee || !target_qn || !strategy) {
+ return probe;
+ }
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ const char *call_caller =
+ call->enclosing_func_qn ? strrchr(call->enclosing_func_qn, '.') : NULL;
+ call_caller = call_caller ? call_caller + 1 : call->enclosing_func_qn;
+ if (!call->requires_lsp_resolution || !call->callee_name || !call_caller ||
+ strcmp(call->callee_name, callee) != 0 || strcmp(call_caller, caller) != 0 ||
+ !cbm_pipeline_source_site_present(call->site_start_byte, call->site_end_byte)) {
+ continue;
+ }
+ probe.carrier = true;
+ }
+ for (int j = 0; j < result->resolved_calls.count; j++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[j];
+ const char *resolved_caller =
+ resolved->caller_qn ? strrchr(resolved->caller_qn, '.') : NULL;
+ resolved_caller = resolved_caller ? resolved_caller + 1 : resolved->caller_qn;
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || !resolved_caller || !resolved->callee_qn ||
+ !resolved->strategy || strcmp(resolved_caller, caller) != 0 ||
+ strcmp(resolved->callee_qn, target_qn) != 0 ||
+ strcmp(resolved->strategy, strategy) != 0) {
+ continue;
+ }
+ probe.semantic = true;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ const char *call_caller =
+ call->enclosing_func_qn ? strrchr(call->enclosing_func_qn, '.') : NULL;
+ call_caller = call_caller ? call_caller + 1 : call->enclosing_func_qn;
+ if (!call->requires_lsp_resolution || !call->callee_name || !call_caller ||
+ strcmp(call->callee_name, callee) != 0 || strcmp(call_caller, caller) != 0) {
+ continue;
+ }
+ if (cbm_pipeline_source_site_eq(call->site_start_byte, call->site_end_byte,
+ resolved->site_start_byte, resolved->site_end_byte)) {
+ probe.exact_join = true;
+ }
+ }
+ }
+ return probe;
+}
+
+/* External Kotlin protocol targets must not borrow a project method merely
+ * because the final Class.method segments agree. Raw assertions prove that the
+ * iterator/destructuring carriers and their stdlib semantic rows really exist;
+ * the graph negatives therefore cannot pass by dropping synthesis. Local alias
+ * and operator calls are positive controls for the narrowed target policy. */
+TEST(parallel_kotlin_external_protocol_does_not_use_project_class_method_tail) {
+ static const char collision_source[] = "package collision\n"
+ "class IntArray {\n"
+ " fun iterator(): IntArray = this\n"
+ "}\n"
+ "class Pair {\n"
+ " operator fun component1(): Int = 0\n"
+ "}\n";
+ static const char main_source[] =
+ "package app\n"
+ "fun loopBuiltIn(values: kotlin.IntArray) {\n"
+ " for (value in values) { println(value) }\n"
+ "}\n"
+ "fun destructureBuiltIn(value: kotlin.Pair<Int, Int>) {\n"
+ " val (left, right) = value\n"
+ "}\n"
+ "fun projectHandler(): Int = 7\n"
+ "fun aliasCaller(): Int {\n"
+ " val callback = ::projectHandler\n"
+ " return callback()\n"
+ "}\n"
+ "class Box { operator fun plus(other: Box): Box = this }\n"
+ "fun operatorCaller(left: Box, right: Box): Box = left + right\n";
+ const char *project = "cbm_kt_target_policy";
+
+ CBMFileResult *raw = cbm_extract_file(main_source, (int)strlen(main_source), CBM_LANG_KOTLIN,
+ project, "app/Main.kt", 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ kotlin_implicit_probe_t iterator = probe_kotlin_implicit_site(
+ raw, "loopBuiltIn", "iterator", "kotlin.IntArray.iterator", "lsp_kt_iterator");
+ kotlin_implicit_probe_t component = probe_kotlin_implicit_site(
+ raw, "destructureBuiltIn", "component1", "kotlin.Pair.component1", "lsp_kt_destructure");
+ cbm_free_result(raw);
+
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_kt_target_policy_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char collision_path[512];
+ char main_path[512];
+ snprintf(collision_path, sizeof(collision_path), "%s/collision/Collisions.kt", tmpdir);
+ snprintf(main_path, sizeof(main_path), "%s/app/Main.kt", tmpdir);
+ if (th_write_file(collision_path, collision_source) != 0 ||
+ th_write_file(main_path, main_source) != 0) {
+ th_rmtree(tmpdir);
+ FAIL("failed to write Kotlin target-policy fixture");
+ }
+
+ cbm_file_info_t files[2] = {0};
+ files[0].path = collision_path;
+ files[0].rel_path = (char *)"collision/Collisions.kt";
+ files[0].language = CBM_LANG_KOTLIN;
+ files[1].path = main_path;
+ files[1].rel_path = (char *)"app/Main.kt";
+ files[1].language = CBM_LANG_KOTLIN;
+ cbm_gbuf_t *sequential = run_sequential_with_lsp_cross(project, tmpdir, files, 2);
+ cbm_gbuf_t *parallel = run_parallel(project, tmpdir, files, 2, 2);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const cbm_gbuf_node_t *sequential_iterator = find_unique_node_by_name_label_qn_suffix(
+ sequential, "iterator", "Method", "Collisions.IntArray.iterator");
+ const cbm_gbuf_node_t *parallel_iterator = find_unique_node_by_name_label_qn_suffix(
+ parallel, "iterator", "Method", "Collisions.IntArray.iterator");
+ const cbm_gbuf_node_t *sequential_component = find_unique_node_by_name_label_qn_suffix(
+ sequential, "component1", "Method", "Collisions.Pair.component1");
+ const cbm_gbuf_node_t *parallel_component = find_unique_node_by_name_label_qn_suffix(
+ parallel, "component1", "Method", "Collisions.Pair.component1");
+ const bool sequential_nodes =
+ sequential_iterator && sequential_component &&
+ find_unique_callable_node_by_tail(sequential, "Main.loopBuiltIn") &&
+ find_unique_callable_node_by_tail(sequential, "Main.destructureBuiltIn");
+ const bool parallel_nodes =
+ parallel_iterator && parallel_component &&
+ find_unique_callable_node_by_tail(parallel, "Main.loopBuiltIn") &&
+ find_unique_callable_node_by_tail(parallel, "Main.destructureBuiltIn");
+ const bool sequential_alias =
+ find_calls_edge_by_tails(sequential, "Main.aliasCaller", "Main.projectHandler") != NULL;
+ const bool parallel_alias =
+ find_calls_edge_by_tails(parallel, "Main.aliasCaller", "Main.projectHandler") != NULL;
+ const bool sequential_operator =
+ find_calls_edge_by_tails(sequential, "Main.operatorCaller", "Box.plus") != NULL;
+ const bool parallel_operator =
+ find_calls_edge_by_tails(parallel, "Main.operatorCaller", "Box.plus") != NULL;
+ const bool sequential_wrong_iterator = has_edge_from_callable_to_node(
+ sequential, "Main.loopBuiltIn", sequential_iterator, "CALLS");
+ const bool parallel_wrong_iterator =
+ has_edge_from_callable_to_node(parallel, "Main.loopBuiltIn", parallel_iterator, "CALLS");
+ const bool sequential_wrong_component = has_edge_from_callable_to_node(
+ sequential, "Main.destructureBuiltIn", sequential_component, "CALLS");
+ const bool parallel_wrong_component = has_edge_from_callable_to_node(
+ parallel, "Main.destructureBuiltIn", parallel_component, "CALLS");
+
+ if (!iterator.carrier || !iterator.semantic || !iterator.exact_join || !component.carrier ||
+ !component.semantic || !component.exact_join || !sequential_nodes || !parallel_nodes ||
+ !sequential_alias || !parallel_alias || !sequential_operator || !parallel_operator ||
+ sequential_wrong_iterator || parallel_wrong_iterator || sequential_wrong_component ||
+ parallel_wrong_component) {
+ printf(" Kotlin target-policy diagnostic: iterator_raw=%d/%d/%d "
+ "component_raw=%d/%d/%d nodes=%d/%d alias=%d/%d operator=%d/%d "
+ "wrong_iterator=%d/%d wrong_component=%d/%d\n",
+ iterator.carrier, iterator.semantic, iterator.exact_join, component.carrier,
+ component.semantic, component.exact_join, sequential_nodes, parallel_nodes,
+ sequential_alias, parallel_alias, sequential_operator, parallel_operator,
+ sequential_wrong_iterator, parallel_wrong_iterator, sequential_wrong_component,
+ parallel_wrong_component);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ th_rmtree(tmpdir);
+ ASSERT_TRUE(iterator.carrier);
+ ASSERT_TRUE(iterator.semantic);
+ ASSERT_TRUE(iterator.exact_join);
+ ASSERT_TRUE(component.carrier);
+ ASSERT_TRUE(component.semantic);
+ ASSERT_TRUE(component.exact_join);
+ ASSERT_TRUE(sequential_nodes);
+ ASSERT_TRUE(parallel_nodes);
+ ASSERT_TRUE(sequential_alias);
+ ASSERT_TRUE(parallel_alias);
+ ASSERT_TRUE(sequential_operator);
+ ASSERT_TRUE(parallel_operator);
+ ASSERT_FALSE(sequential_wrong_iterator);
+ ASSERT_FALSE(parallel_wrong_iterator);
+ ASSERT_FALSE(sequential_wrong_component);
+ ASSERT_FALSE(parallel_wrong_component);
+ PASS();
+}
+
+/* Kotlin's unary, membership, and index conventions are real invocations just
+ * like binary `plus`: the LSP already proves the exact operator method at the
+ * exact expression span. The syntax extractor must provide a matching guarded
+ * CBMCall carrier so both graph paths can materialize CALLS without a textual
+ * guess. This test separately proves carrier, semantic row, exact join, and
+ * graph edge for each syntax family. */
+TEST(parallel_kotlin_nonbinary_operator_carriers_reach_graph) {
+ static const char definitions_source[] =
+ "package app\n"
+ "class UnaryBox { operator fun unaryMinus(): UnaryBox = this }\n"
+ "class Bag { operator fun contains(value: Int): Boolean = true }\n"
+ "class Slots { operator fun get(index: Int): Int = index }\n"
+ "class Counter {\n"
+ " operator fun inc(): Counter = this\n"
+ " operator fun dec(): Counter = this\n"
+ "}\n";
+ static const char callers_source[] = "package app\n"
+ "fun negate(value: UnaryBox): UnaryBox = -value\n"
+ "fun hasValue(bag: Bag): Boolean = 1 in bag\n"
+ "fun lacksValue(bag: Bag): Boolean = 1 !in bag\n"
+ "fun lookup(slots: Slots): Int = slots[0]\n"
+ "fun increment(value: Counter): Counter { var current = "
+ "value; current++; return current }\n"
+ "fun decrement(value: Counter): Counter { var current = "
+ "value; current--; return current }\n"
+ "fun isBag(value: Any): Boolean = value is Bag\n"
+ "fun assign(slots: Slots) { slots[0] = 1 }\n";
+ static const char source[] = "package app\n"
+ "class UnaryBox { operator fun unaryMinus(): UnaryBox = this }\n"
+ "class Bag { operator fun contains(value: Int): Boolean = true }\n"
+ "class Slots { operator fun get(index: Int): Int = index }\n"
+ "class Counter {\n"
+ " operator fun inc(): Counter = this\n"
+ " operator fun dec(): Counter = this\n"
+ "}\n"
+ "fun negate(value: UnaryBox): UnaryBox = -value\n"
+ "fun hasValue(bag: Bag): Boolean = 1 in bag\n"
+ "fun lacksValue(bag: Bag): Boolean = 1 !in bag\n"
+ "fun lookup(slots: Slots): Int = slots[0]\n"
+ "fun increment(value: Counter): Counter { var current = value; "
+ "current++; return current }\n"
+ "fun decrement(value: Counter): Counter { var current = value; "
+ "current--; return current }\n"
+ "fun isBag(value: Any): Boolean = value is Bag\n"
+ "fun assign(slots: Slots) { slots[0] = 1 }\n";
+ const char *project = "cbm_kt_nonbinary_operators";
+
+ CBMFileResult *raw = cbm_extract_file(source, (int)strlen(source), CBM_LANG_KOTLIN, project,
+ "app/Main.kt", 0, NULL, NULL);
+ ASSERT_NOT_NULL(raw);
+ ASSERT_FALSE(raw->has_error || raw->parse_incomplete);
+ kotlin_implicit_probe_t unary = probe_kotlin_implicit_site(
+ raw, "negate", "unaryMinus", "app.UnaryBox.unaryMinus", "lsp_kt_operator");
+ kotlin_implicit_probe_t contains = probe_kotlin_implicit_site(
+ raw, "hasValue", "contains", "app.Bag.contains", "lsp_kt_operator");
+ kotlin_implicit_probe_t not_contains = probe_kotlin_implicit_site(
+ raw, "lacksValue", "contains", "app.Bag.contains", "lsp_kt_operator");
+ kotlin_implicit_probe_t index =
+ probe_kotlin_implicit_site(raw, "lookup", "get", "app.Slots.get", "lsp_kt_operator");
+ kotlin_implicit_probe_t increment =
+ probe_kotlin_implicit_site(raw, "increment", "inc", "app.Counter.inc", "lsp_kt_operator");
+ kotlin_implicit_probe_t decrement =
+ probe_kotlin_implicit_site(raw, "decrement", "dec", "app.Counter.dec", "lsp_kt_operator");
+ kotlin_implicit_probe_t is_negative =
+ probe_kotlin_implicit_site(raw, "isBag", "contains", "app.Bag.contains", "lsp_kt_operator");
+ kotlin_implicit_probe_t assignment_negative =
+ probe_kotlin_implicit_site(raw, "assign", "get", "app.Slots.get", "lsp_kt_operator");
+ cbm_free_result(raw);
+
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_kt_nonbinary_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char definitions_path[512];
+ char callers_path[512];
+ snprintf(definitions_path, sizeof(definitions_path), "%s/app/Operators.kt", tmpdir);
+ snprintf(callers_path, sizeof(callers_path), "%s/app/Main.kt", tmpdir);
+ if (th_write_file(definitions_path, definitions_source) != 0 ||
+ th_write_file(callers_path, callers_source) != 0) {
+ th_rmtree(tmpdir);
+ FAIL("failed to write Kotlin nonbinary-operator fixture");
+ }
+ cbm_file_info_t files[2] = {0};
+ files[0].path = definitions_path;
+ files[0].rel_path = (char *)"app/Operators.kt";
+ files[0].language = CBM_LANG_KOTLIN;
+ files[1].path = callers_path;
+ files[1].rel_path = (char *)"app/Main.kt";
+ files[1].language = CBM_LANG_KOTLIN;
+ cbm_gbuf_t *sequential = run_sequential_with_lsp_cross(project, tmpdir, files, 2);
+ cbm_gbuf_t *parallel = run_parallel(project, tmpdir, files, 2, 2);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const bool sequential_unary =
+ find_calls_edge_by_tails(sequential, "Main.negate", "UnaryBox.unaryMinus") != NULL;
+ const bool parallel_unary =
+ find_calls_edge_by_tails(parallel, "Main.negate", "UnaryBox.unaryMinus") != NULL;
+ const bool sequential_contains =
+ find_calls_edge_by_tails(sequential, "Main.hasValue", "Bag.contains") != NULL;
+ const bool parallel_contains =
+ find_calls_edge_by_tails(parallel, "Main.hasValue", "Bag.contains") != NULL;
+ const bool sequential_not_contains =
+ find_calls_edge_by_tails(sequential, "Main.lacksValue", "Bag.contains") != NULL;
+ const bool parallel_not_contains =
+ find_calls_edge_by_tails(parallel, "Main.lacksValue", "Bag.contains") != NULL;
+ const bool sequential_index =
+ find_calls_edge_by_tails(sequential, "Main.lookup", "Slots.get") != NULL;
+ const bool parallel_index =
+ find_calls_edge_by_tails(parallel, "Main.lookup", "Slots.get") != NULL;
+ const bool sequential_increment =
+ find_calls_edge_by_tails(sequential, "Main.increment", "Counter.inc") != NULL;
+ const bool parallel_increment =
+ find_calls_edge_by_tails(parallel, "Main.increment", "Counter.inc") != NULL;
+ const bool sequential_decrement =
+ find_calls_edge_by_tails(sequential, "Main.decrement", "Counter.dec") != NULL;
+ const bool parallel_decrement =
+ find_calls_edge_by_tails(parallel, "Main.decrement", "Counter.dec") != NULL;
+ const bool sequential_false_contains =
+ find_calls_edge_by_tails(sequential, "Main.isBag", "Bag.contains") != NULL;
+ const bool parallel_false_contains =
+ find_calls_edge_by_tails(parallel, "Main.isBag", "Bag.contains") != NULL;
+ const bool sequential_false_get =
+ find_calls_edge_by_tails(sequential, "Main.assign", "Slots.get") != NULL;
+ const bool parallel_false_get =
+ find_calls_edge_by_tails(parallel, "Main.assign", "Slots.get") != NULL;
+ if (!unary.carrier || !unary.semantic || !unary.exact_join || !contains.carrier ||
+ !contains.semantic || !contains.exact_join || !not_contains.carrier ||
+ !not_contains.semantic || !not_contains.exact_join || !index.carrier || !index.semantic ||
+ !index.exact_join || !increment.carrier || !increment.semantic || !increment.exact_join ||
+ !decrement.carrier || !decrement.semantic || !decrement.exact_join || is_negative.carrier ||
+ is_negative.semantic || assignment_negative.carrier || !sequential_unary ||
+ !parallel_unary || !sequential_contains || !parallel_contains || !sequential_not_contains ||
+ !parallel_not_contains || !sequential_index || !parallel_index || !sequential_increment ||
+ !parallel_increment || !sequential_decrement || !parallel_decrement ||
+ sequential_false_contains || parallel_false_contains || sequential_false_get ||
+ parallel_false_get) {
+ printf(" Kotlin nonbinary diagnostic: unary=%d/%d/%d/%d/%d "
+ "contains=%d/%d/%d/%d/%d notin=%d/%d/%d/%d/%d "
+ "index=%d/%d/%d/%d/%d inc=%d/%d/%d/%d/%d dec=%d/%d/%d/%d/%d "
+ "negative=%d/%d/%d/%d/%d/%d\n",
+ unary.carrier, unary.semantic, unary.exact_join, sequential_unary, parallel_unary,
+ contains.carrier, contains.semantic, contains.exact_join, sequential_contains,
+ parallel_contains, not_contains.carrier, not_contains.semantic,
+ not_contains.exact_join, sequential_not_contains, parallel_not_contains,
+ index.carrier, index.semantic, index.exact_join, sequential_index, parallel_index,
+ increment.carrier, increment.semantic, increment.exact_join, sequential_increment,
+ parallel_increment, decrement.carrier, decrement.semantic, decrement.exact_join,
+ sequential_decrement, parallel_decrement, is_negative.carrier, is_negative.semantic,
+ assignment_negative.carrier, sequential_false_contains, parallel_false_contains,
+ sequential_false_get || parallel_false_get);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ th_rmtree(tmpdir);
+ ASSERT_TRUE(unary.carrier);
+ ASSERT_TRUE(unary.semantic);
+ ASSERT_TRUE(unary.exact_join);
+ ASSERT_TRUE(contains.carrier);
+ ASSERT_TRUE(contains.semantic);
+ ASSERT_TRUE(contains.exact_join);
+ ASSERT_TRUE(not_contains.carrier);
+ ASSERT_TRUE(not_contains.semantic);
+ ASSERT_TRUE(not_contains.exact_join);
+ ASSERT_TRUE(index.carrier);
+ ASSERT_TRUE(index.semantic);
+ ASSERT_TRUE(index.exact_join);
+ ASSERT_TRUE(increment.carrier);
+ ASSERT_TRUE(increment.semantic);
+ ASSERT_TRUE(increment.exact_join);
+ ASSERT_TRUE(decrement.carrier);
+ ASSERT_TRUE(decrement.semantic);
+ ASSERT_TRUE(decrement.exact_join);
+ ASSERT_FALSE(is_negative.carrier);
+ ASSERT_FALSE(is_negative.semantic);
+ ASSERT_FALSE(assignment_negative.carrier);
+ ASSERT_TRUE(sequential_unary);
+ ASSERT_TRUE(parallel_unary);
+ ASSERT_TRUE(sequential_contains);
+ ASSERT_TRUE(parallel_contains);
+ ASSERT_TRUE(sequential_not_contains);
+ ASSERT_TRUE(parallel_not_contains);
+ ASSERT_TRUE(sequential_index);
+ ASSERT_TRUE(parallel_index);
+ ASSERT_TRUE(sequential_increment);
+ ASSERT_TRUE(parallel_increment);
+ ASSERT_TRUE(sequential_decrement);
+ ASSERT_TRUE(parallel_decrement);
+ ASSERT_FALSE(sequential_false_contains);
+ ASSERT_FALSE(parallel_false_contains);
+ ASSERT_FALSE(sequential_false_get);
+ ASSERT_FALSE(parallel_false_get);
+ PASS();
+}
+
+/* A known external macro semantic owns its parser occurrence even when the
+ * external target is not materialized as a graph node. It must not fall back
+ * to a same-named local function in either pipeline. */
+TEST(parallel_rust_known_macro_does_not_fallback_to_local_function) {
+ static const char source[] = "fn println() {}\nfn run() { println!(\"macro\"); }\n";
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_rust_macro_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/main.rs", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen main.rs failed");
+ }
+ fputs(source, file);
+ fclose(file);
+
+ CBMFileResult *extracted = cbm_extract_file(source, (int)strlen(source), CBM_LANG_RUST,
+ "cbm_rust_macro", "main.rs", 0, NULL, NULL);
+ ASSERT_NOT_NULL(extracted);
+ const char *site = strstr(source, "println!(\"macro\")");
+ const uint32_t start = site ? (uint32_t)(site - source) : 0;
+ const uint32_t end = start + (uint32_t)strlen("println!(\"macro\")");
+ bool semantic_owner = false;
+ bool exact_gated_carrier = false;
+ for (int i = 0; i < extracted->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &extracted->resolved_calls.items[i];
+ if (resolved->caller_qn && strstr(resolved->caller_qn, "run") && resolved->callee_qn &&
+ strcmp(resolved->callee_qn, "std.macros.println") == 0 && resolved->strategy &&
+ strcmp(resolved->strategy, "lsp_macro") == 0) {
+ semantic_owner = true;
+ }
+ }
+ for (int i = 0; i < extracted->calls.count; i++) {
+ const CBMCall *call = &extracted->calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "run") &&
+ call->callee_name && strcmp(call->callee_name, "println") == 0 &&
+ call->site_start_byte == start && call->site_end_byte == end &&
+ call->requires_lsp_resolution) {
+ exact_gated_carrier = true;
+ }
+ }
+ cbm_free_result(extracted);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"main.rs";
+ files[0].language = CBM_LANG_RUST;
+ cbm_gbuf_t *sequential = run_sequential("cbm_rust_macro", tmpdir, files, 1);
+ cbm_gbuf_t *parallel = run_parallel("cbm_rust_macro", tmpdir, files, 1, 1);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const bool sequential_nodes = find_unique_callable_node_by_tail(sequential, "main.run") &&
+ find_unique_callable_node_by_tail(sequential, "main.println");
+ const bool parallel_nodes = find_unique_callable_node_by_tail(parallel, "main.run") &&
+ find_unique_callable_node_by_tail(parallel, "main.println");
+ const bool sequential_wrong =
+ find_calls_edge_by_tails(sequential, "main.run", "main.println") != NULL;
+ const bool parallel_wrong =
+ find_calls_edge_by_tails(parallel, "main.run", "main.println") != NULL;
+ if (!semantic_owner || !exact_gated_carrier || !sequential_nodes || !parallel_nodes ||
+ sequential_wrong || parallel_wrong) {
+ printf(" Rust macro fallback diagnostic: semantic=%d gated_carrier=%d seq_nodes=%d "
+ "par_nodes=%d seq_wrong=%d par_wrong=%d\n",
+ semantic_owner, exact_gated_carrier, sequential_nodes, parallel_nodes,
+ sequential_wrong, parallel_wrong);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(semantic_owner);
+ ASSERT_TRUE(exact_gated_carrier);
+ ASSERT_TRUE(sequential_nodes);
+ ASSERT_TRUE(parallel_nodes);
+ ASSERT_FALSE(sequential_wrong);
+ ASSERT_FALSE(parallel_wrong);
+ PASS();
+}
+
+/* Attribute proc-macros are source-level decorator references. Both pipelines
+ * must represent them as DECORATES + USAGE and must not fabricate calls to
+ * implementation details that are knowable only by executing the macro. */
+TEST(parallel_rust_proc_macros_are_decorates_and_usage_only) {
+ static const char source[] = "#[tokio::main]\nasync fn main() {}\n"
+ "#[tracing::instrument]\nfn work() {}\n";
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_rust_proc_macro_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char path[512];
+ snprintf(path, sizeof(path), "%s/main.rs", tmpdir);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen main.rs failed");
+ }
+ fputs(source, file);
+ fclose(file);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = (char *)"main.rs";
+ files[0].language = CBM_LANG_RUST;
+ cbm_gbuf_t *sequential = run_sequential("cbm_rust_proc_macro", tmpdir, files, 1);
+ cbm_gbuf_t *parallel = run_parallel("cbm_rust_proc_macro", tmpdir, files, 1, 1);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const bool seq_tokio_decorates = has_edge_from_callable_to_qn(
+ sequential, "main.main", "<decorator:tokio::main>", "DECORATES");
+ const bool seq_tokio_usage =
+ has_edge_from_callable_to_qn(sequential, "main.main", "<decorator:tokio::main>", "USAGE");
+ const bool par_tokio_decorates =
+ has_edge_from_callable_to_qn(parallel, "main.main", "<decorator:tokio::main>", "DECORATES");
+ const bool par_tokio_usage =
+ has_edge_from_callable_to_qn(parallel, "main.main", "<decorator:tokio::main>", "USAGE");
+ const bool seq_tracing_decorates = has_edge_from_callable_to_qn(
+ sequential, "main.work", "<decorator:tracing::instrument>", "DECORATES");
+ const bool seq_tracing_usage = has_edge_from_callable_to_qn(
+ sequential, "main.work", "<decorator:tracing::instrument>", "USAGE");
+ const bool par_tracing_decorates = has_edge_from_callable_to_qn(
+ parallel, "main.work", "<decorator:tracing::instrument>", "DECORATES");
+ const bool par_tracing_usage = has_edge_from_callable_to_qn(
+ parallel, "main.work", "<decorator:tracing::instrument>", "USAGE");
+ const bool seq_fake = callable_has_call_target_fragment(sequential, "main.main", "Runtime") ||
+ callable_has_call_target_fragment(sequential, "main.work", "Span.enter");
+ const bool par_fake = callable_has_call_target_fragment(parallel, "main.main", "Runtime") ||
+ callable_has_call_target_fragment(parallel, "main.work", "Span.enter");
+
+ if (!seq_tokio_decorates || !seq_tokio_usage || !par_tokio_decorates || !par_tokio_usage ||
+ !seq_tracing_decorates || !seq_tracing_usage || !par_tracing_decorates ||
+ !par_tracing_usage || seq_fake || par_fake) {
+ printf(" Rust proc-macro policy diagnostic: tokio seq=%d/%d par=%d/%d "
+ "tracing seq=%d/%d par=%d/%d fake=%d/%d\n",
+ seq_tokio_decorates, seq_tokio_usage, par_tokio_decorates, par_tokio_usage,
+ seq_tracing_decorates, seq_tracing_usage, par_tracing_decorates, par_tracing_usage,
+ seq_fake, par_fake);
+ }
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ unlink(path);
+ rmdir(tmpdir);
+ ASSERT_TRUE(seq_tokio_decorates);
+ ASSERT_TRUE(seq_tokio_usage);
+ ASSERT_TRUE(par_tokio_decorates);
+ ASSERT_TRUE(par_tokio_usage);
+ ASSERT_TRUE(seq_tracing_decorates);
+ ASSERT_TRUE(seq_tracing_usage);
+ ASSERT_TRUE(par_tracing_decorates);
+ ASSERT_TRUE(par_tracing_usage);
+ ASSERT_FALSE(seq_fake);
+ ASSERT_FALSE(par_fake);
+ PASS();
+}
+
+static int assert_c_family_preprocessed_collision_graph(CBMLanguage language, const char *extension,
+ const char *project, const char *source,
+ const char *target_tail) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_c_origin_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+ char rel_path[64];
+ snprintf(rel_path, sizeof(rel_path), "main.%s", extension);
+ char path[512];
+ snprintf(path, sizeof(path), "%s/%s", tmpdir, rel_path);
+ FILE *file = cbm_fopen(path, "w");
+ if (!file) {
+ rmdir(tmpdir);
+ FAIL("fopen C-family fixture failed");
+ }
+ fputs(source, file);
+ fclose(file);
+
+ cbm_file_info_t files[1] = {0};
+ files[0].path = path;
+ files[0].rel_path = rel_path;
+ files[0].language = language;
+ cbm_gbuf_t *sequential = run_sequential(project, tmpdir, files, 1);
+ cbm_gbuf_t *parallel = run_parallel(project, tmpdir, files, 1, 1);
+ ASSERT_NOT_NULL(sequential);
+ ASSERT_NOT_NULL(parallel);
+
+ const cbm_gbuf_edge_t *sequential_edge =
+ find_calls_edge_by_tails(sequential, "main.occurrence_probe", target_tail);
+ const cbm_gbuf_edge_t *parallel_edge =
+ find_calls_edge_by_tails(parallel, "main.occurrence_probe", target_tail);
+ if (!sequential_edge || !parallel_edge) {
+ printf(" C-family origin diagnostic (%s): sequential=%s parallel=%s\n", extension,
+ sequential_edge ? "present" : "absent", parallel_edge ? "present" : "absent");
+ }
+ ASSERT_NOT_NULL(sequential_edge);
+ ASSERT_NOT_NULL(parallel_edge);
+
+ cbm_gbuf_free(sequential);
+ cbm_gbuf_free(parallel);
+ unlink(path);
+ rmdir(tmpdir);
+ return 0;
+}
+
+TEST(parallel_c_preprocessed_coordinate_collision_preserves_hidden_target) {
+ static const char source[] =
+ "static int alpha_target(void){return 1;}\n"
+ "static int bravo_target(void){return 2;}\n"
+ "int occurrence_probe(void){\n"
+ " int (*fp)(void) = alpha_target;\n"
+ " /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/ fp ( );\n"
+ "#define HIDDEN_FP_CALL() (fp = bravo_target, fp())\n"
+ " return HIDDEN_FP_CALL();\n"
+ "}\n";
+ return assert_c_family_preprocessed_collision_graph(CBM_LANG_C, "c", "cbm_c_origin", source,
+ "main.bravo_target");
+}
+
+static int assert_cpp_like_preprocessed_collision_graph(CBMLanguage language, const char *extension,
+ const char *project) {
+ static const char source[] =
+ "struct Alpha { int render(){return 1;} };\n"
+ "struct Bravo { int render(){return 2;} };\n"
+ "int occurrence_probe(){\n"
+ " Alpha alpha; Bravo bravo;\n"
+ " /*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/ alpha . render ( );\n"
+ "#define HIDDEN_RENDER(x) x.render()\n"
+ " return HIDDEN_RENDER(bravo);\n"
+ "}\n";
+ return assert_c_family_preprocessed_collision_graph(language, extension, project, source,
+ "Bravo.render");
+}
+
+TEST(parallel_cpp_preprocessed_coordinate_collision_preserves_hidden_target) {
+ return assert_cpp_like_preprocessed_collision_graph(CBM_LANG_CPP, "cpp", "cbm_cpp_origin");
+}
+
+TEST(parallel_cuda_preprocessed_coordinate_collision_preserves_hidden_target) {
+ return assert_cpp_like_preprocessed_collision_graph(CBM_LANG_CUDA, "cu", "cbm_cuda_origin");
+}
+
+TEST(parallel_java_kotlin_lsp_override_cross_file_emits_lsp_strategy_edges) {
+ char tmpdir[256];
+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_jvm_XXXXXX");
+ if (!cbm_mkdtemp(tmpdir)) {
+ FAIL("mkdtemp failed");
+ }
+
+ char jpath[512];
+ snprintf(jpath, sizeof(jpath), "%s/src/main/java/com/example/Example.java", tmpdir);
+ char jdir[512];
+ snprintf(jdir, sizeof(jdir), "%s/src/main/java/com/example", tmpdir);
+ cbm_mkdir_p(jdir, 0755);
+ FILE *jf = cbm_fopen(jpath, "w");
+ if (!jf) {
+ FAIL("fopen example.java failed");
+ }
+ fprintf(jf, "package com.example;\n"
+ "\n"
+ "class JavaCaller {\n"
+ " String call(KotlinService kotlinService) {\n"
+ " return kotlinService.ping(new JavaService());\n"
+ " }\n"
+ "}\n"
+ "\n"
+ "class JavaService {\n"
+ " String pong() {\n"
+ " return \"pong\";\n"
+ " }\n"
+ "}\n");
+ fclose(jf);
+
+ char kpath[512];
+ snprintf(kpath, sizeof(kpath), "%s/src/main/kotlin/com/example/KotlinService.kt", tmpdir);
+ char kdir[512];
+ snprintf(kdir, sizeof(kdir), "%s/src/main/kotlin/com/example", tmpdir);
+ cbm_mkdir_p(kdir, 0755);
+ FILE *kf = cbm_fopen(kpath, "w");
+ if (!kf) {
+ unlink(jpath);
+ rmdir(tmpdir);
+ FAIL("fopen example.kt failed");
+ }
+ fprintf(kf, "package com.example\n"
+ "\n"
+ "class KotlinService {\n"
+ " fun ping(javaService: JavaService): String {\n"
+ " return javaService.pong()\n"
+ " }\n"
+ "}\n");
+ fclose(kf);
+
+ cbm_file_info_t files[2] = {0};
+ files[0].path = jpath;
+ files[0].rel_path = (char *)"src/main/java/com/example/Example.java";
+ files[0].language = CBM_LANG_JAVA;
+ files[1].path = kpath;
+ files[1].rel_path = (char *)"src/main/kotlin/com/example/KotlinService.kt";
+ files[1].language = CBM_LANG_KOTLIN;
+
+ cbm_gbuf_t *gbuf = run_parallel("com", tmpdir, files, 2, 2);
+ ASSERT_NOT_NULL(gbuf);
+
+ const cbm_gbuf_edge_t *java_to_kotlin =
+ find_calls_edge_by_tails(gbuf, "JavaCaller.call", "KotlinService.ping");
+ const cbm_gbuf_edge_t *kotlin_to_java =
+ find_calls_edge_by_tails(gbuf, "KotlinService.ping", "JavaService.pong");
+
+ ASSERT_NOT_NULL(java_to_kotlin);
+ ASSERT_NOT_NULL(kotlin_to_java);
+ ASSERT_NOT_NULL(java_to_kotlin->properties_json);
+ ASSERT_NOT_NULL(kotlin_to_java->properties_json);
+ ASSERT_NOT_NULL(strstr(java_to_kotlin->properties_json, "\"strategy\":\"lsp"));
+ ASSERT_NOT_NULL(strstr(kotlin_to_java->properties_json, "\"strategy\":\"lsp"));
+ ASSERT_TRUE(strstr(java_to_kotlin->properties_json, "\"strategy\":\"callee_suffix\"") == NULL);
+ ASSERT_TRUE(strstr(kotlin_to_java->properties_json, "\"strategy\":\"callee_suffix\"") == NULL);
+
+ cbm_gbuf_free(gbuf);
+ unlink(kpath);
+ unlink(jpath);
+ rmdir(tmpdir);
+ PASS();
+}
+
+/* Gate guard for the JVM-only unique-tail fallbacks (lsp_resolve.h).
+ *
+ * The tail fallbacks join LSP overrides across QN drift by unique
+ * "Class.method" leaf. That is only sound where class-per-file package
+ * semantics hold (Java/Kotlin); in any other language a single
+ * wrong-module coincidence would fabricate a CALLS edge, so
+ * cbm_pipeline_lsp_allow_tail_match must keep the fallbacks OFF there.
+ *
+ * NOTE: a natural end-to-end non-JVM coincidence fixture is impractical:
+ * reaching the fallbacks requires the LSP and the textual extraction to
+ * disagree on QN prefixes, which path-derived single-root languages do
+ * not produce in a small fixture (that drift is precisely the JVM
+ * mixed-source-root symptom the fallback exists for). So this test
+ * exercises the gated branches directly: the SAME wrong-module
+ * coincidence must resolve with the gate open (JVM) and must NOT with
+ * the gate closed. If the gate were removed — fallbacks made
+ * unconditional again — the gate-closed assertions below would fail. */
+TEST(parallel_lsp_tail_match_fallbacks_gated_to_jvm) {
+ /* Policy: exactly the JVM languages. */
+ ASSERT_TRUE(cbm_pipeline_lsp_allow_tail_match(CBM_LANG_JAVA));
+ ASSERT_TRUE(cbm_pipeline_lsp_allow_tail_match(CBM_LANG_KOTLIN));
+ ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_PYTHON));
+ ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_GO));
+ ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_TYPESCRIPT));
+ ASSERT_TRUE(!cbm_pipeline_lsp_allow_tail_match(CBM_LANG_CPP));
+
+ /* Wrong-module coincidence: the resolved entry's caller shares only
+ * the "Service.handle" tail with the textual call's enclosing
+ * function, so the exact caller_qn pass misses and only the tail
+ * fallback could join them. */
+ CBMResolvedCall rc_item = {0};
+ rc_item.caller_qn = "com.example.pkg.Service.handle";
+ rc_item.callee_qn = "com.example.pkg.Helper.run";
rc_item.strategy = "lsp";
rc_item.confidence = 0.9f;
CBMResolvedCallArray arr = {0};
@@ -746,6 +2834,44 @@ TEST(parallel_lsp_tail_match_fallbacks_gated_to_jvm) {
ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&arr, &call, false) == NULL);
ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&arr, &call, true) == &rc_item);
+ /* Kotlin top-level functions have one more legitimate QN drift: the graph
+ * owner is file-shaped (`...Main.operatorCaller`) while the semantic owner
+ * is package-shaped (`app.operatorCaller`). An exact source occurrence and
+ * equal caller leaf may reconcile that JVM-only drift; the non-JVM policy
+ * remains closed, a different caller leaf remains closed, and distinct
+ * semantic targets at the same occurrence remain ambiguous. */
+ CBMResolvedCall top_level_rows[2] = {0};
+ top_level_rows[0].caller_qn = "app.operatorCaller";
+ top_level_rows[0].callee_qn = "app.Box.plus";
+ top_level_rows[0].strategy = "lsp_kt_operator";
+ top_level_rows[0].confidence = 0.9f;
+ top_level_rows[0].site_start_byte = 80;
+ top_level_rows[0].site_end_byte = 92;
+ top_level_rows[0].source_origin = CBM_SOURCE_ORIGIN_RAW;
+ CBMResolvedCallArray top_level_arr = {0};
+ top_level_arr.items = top_level_rows;
+ top_level_arr.count = 1;
+ top_level_arr.cap = 2;
+
+ CBMCall top_level_call = {0};
+ top_level_call.enclosing_func_qn = "proj.app.Main.operatorCaller";
+ top_level_call.callee_name = "plus";
+ top_level_call.site_start_byte = 80;
+ top_level_call.site_end_byte = 92;
+ top_level_call.source_origin = CBM_SOURCE_ORIGIN_RAW;
+ top_level_call.requires_lsp_resolution = true;
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&top_level_arr, &top_level_call, false) == NULL);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&top_level_arr, &top_level_call, true) ==
+ &top_level_rows[0]);
+
+ top_level_call.enclosing_func_qn = "proj.app.Main.differentCaller";
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&top_level_arr, &top_level_call, true) == NULL);
+ top_level_call.enclosing_func_qn = "proj.app.Main.operatorCaller";
+ top_level_rows[1] = top_level_rows[0];
+ top_level_rows[1].callee_qn = "app.Other.plus";
+ top_level_arr.count = 2;
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&top_level_arr, &top_level_call, true) == NULL);
+
/* Target-node fallback: callee_qn misses both as-is and
* project-prefixed; exactly one node coincidentally shares the
* "Helper.run" tail in an unrelated module. */
@@ -759,6 +2885,11 @@ TEST(parallel_lsp_tail_match_fallbacks_gated_to_jvm) {
cbm_pipeline_lsp_target_node(tgbuf, "proj", "com.other.Helper.run", true);
ASSERT_NOT_NULL(jvm_hit);
ASSERT_TRUE(strcmp(jvm_hit->qualified_name, "proj.zeta.Helper.run") == 0);
+ /* A synthetic external protocol target has no source-level evidence for
+ * that Class.method-tail equivalence. Its strict lookup must therefore
+ * remain exact and fail closed on the same coincidence. */
+ ASSERT_TRUE(cbm_pipeline_lsp_target_node_strict(tgbuf, "proj", "com.other.Helper.run", true) ==
+ NULL);
cbm_gbuf_free(tgbuf);
PASS();
}
@@ -1069,7 +3200,7 @@ TEST(grpc_no_phantom_route_from_plain_var_issue294) {
* mis-attribution edge case (two same-named subs from different namespaces) is
* bounded by caller-QN equality + the confidence floor. */
static CBMResolvedCall make_rc(const char *caller, const char *callee, float conf) {
- CBMResolvedCall rc;
+ CBMResolvedCall rc = {0};
memset(&rc, 0, sizeof(rc));
rc.caller_qn = caller;
rc.callee_qn = callee;
@@ -1086,6 +3217,15 @@ static CBMCall make_call(const char *enclosing, const char *callee_name) {
return c;
}
+TEST(lsp_bare_segment_skips_preprocessor_spacing) {
+ /* simplecpp serializes macro-expanded member access with spaces around the
+ * separator (for example `bravo . render`). The shared semantic join must
+ * still compare the identifier leaf, not the whitespace-prefixed suffix. */
+ ASSERT_STR_EQ(cbm_lsp_bare_segment("bravo . render"), "render");
+ ASSERT_STR_EQ(cbm_lsp_bare_segment("ptr -> run"), "run");
+ PASS();
+}
+
TEST(lsp_resolve_qualified_static_call_normalizes_colons) {
/* A qualified static call `Pkg::sub` (callee_name keeps the package
* prefix) must still match a resolved entry whose callee_qn short-name is
@@ -1108,13 +3248,10 @@ TEST(lsp_resolve_qualified_static_call_normalizes_colons) {
PASS();
}
-TEST(lsp_resolve_misattribution_is_bounded) {
- /* Two same-named subs from different namespaces (A::foo, B::foo) resolved
- * within the same enclosing function. Both resolved short-names normalize
- * to `foo`, so a textual `B::foo` matches both by short-name — the
- * theoretical mis-attribution. The function bounds this: it returns the
- * highest-confidence match (deterministic, never both), and the bound is
- * enforced by caller-QN equality + the confidence floor. */
+TEST(lsp_resolve_distinct_exact_caller_targets_fail_closed) {
+ /* Two same-named targets from different namespaces at the same caller and
+ * legacy occurrence are semantic ambiguity, not a confidence contest.
+ * Choosing the higher score would fabricate one exact CALLS target. */
CBMResolvedCall items[] = {
make_rc("proj.mod.caller", "proj.A.foo", 0.7f),
make_rc("proj.mod.caller", "proj.B.foo", 0.9f),
@@ -1126,10 +3263,7 @@ TEST(lsp_resolve_misattribution_is_bounded) {
CBMResolvedCallArray arr = {items, 4, 4};
CBMCall call = make_call("proj.mod.caller", "B::foo");
const CBMResolvedCall *hit = cbm_pipeline_find_lsp_resolution(&arr, &call, false);
- ASSERT(hit != NULL);
- /* Highest-confidence qualifying entry wins; the cross-caller 0.95 entry is
- * excluded by caller-QN equality, the 0.3 entry by the floor. */
- ASSERT(strcmp(hit->callee_qn, "proj.B.foo") == 0);
+ ASSERT_NULL(hit);
/* The cross-caller high-confidence entry only matches its own caller. */
CBMCall other = make_call("proj.mod.other", "D::foo");
@@ -1144,11 +3278,549 @@ TEST(lsp_resolve_misattribution_is_bounded) {
PASS();
}
+TEST(lsp_resolve_duplicate_exact_caller_rows_same_target_are_not_ambiguous) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 75;
+ call.site_end_byte = 91;
+ CBMResolvedCall low = make_rc("proj.mod.caller", "proj.Alpha.render", 0.75f);
+ low.site_start_byte = call.site_start_byte;
+ low.site_end_byte = call.site_end_byte;
+ CBMResolvedCall high = low;
+ high.confidence = 0.95f;
+ CBMResolvedCall items[] = {low, high};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_resolution(&arr, &call, false) == &items[1]);
+ PASS();
+}
+
+TEST(lsp_resolve_distinct_exact_caller_site_targets_are_ambiguous) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 92;
+ call.site_end_byte = 108;
+ call.requires_lsp_resolution = true;
+ CBMResolvedCall alpha = make_rc("proj.mod.caller", "proj.Alpha.render", 0.75f);
+ alpha.site_start_byte = call.site_start_byte;
+ alpha.site_end_byte = call.site_end_byte;
+ CBMResolvedCall beta = make_rc("proj.mod.caller", "proj.Beta.render", 0.99f);
+ beta.site_start_byte = call.site_start_byte;
+ beta.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {alpha, beta};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT_NULL(cbm_pipeline_find_lsp_resolution(&arr, &call, false));
+ PASS();
+}
+
+/* Per-file and project-wide passes may spell one exact non-JVM invocation
+ * target with and without the project prefix. Graph identity, not raw string
+ * identity, decides whether those occurrence-identical rows conflict. */
+TEST(lsp_resolve_project_prefixed_duplicate_is_not_ambiguous) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t target_id = cbm_gbuf_upsert_node(gbuf, "Function", "handler",
+ "proj.mod.Target.handler", "target.py", 1, 1, "{}");
+ ASSERT_GT(target_id, 0);
+
+ CBMCall call = make_call("proj.mod.Caller.run", "handler");
+ call.site_start_byte = 110;
+ call.site_end_byte = 119;
+ CBMResolvedCall raw = make_rc("proj.mod.Caller.run", "mod.Target.handler", 0.75f);
+ raw.site_start_byte = call.site_start_byte;
+ raw.site_end_byte = call.site_end_byte;
+ CBMResolvedCall prefixed =
+ make_rc("proj.mod.Caller.run", "proj.mod.Target.handler", 0.90f);
+ prefixed.site_start_byte = call.site_start_byte;
+ prefixed.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {raw, prefixed};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_resolution_in_graph(&arr, &call, false, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT(hit == &items[1]);
+ PASS();
+}
+
+TEST(lsp_resolve_project_prefix_spellings_stay_ambiguous_when_both_nodes_exist) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t raw_id = cbm_gbuf_upsert_node(gbuf, "Function", "handler", "mod.Target.handler",
+ "raw.py", 1, 1, "{}");
+ int64_t prefixed_id = cbm_gbuf_upsert_node(gbuf, "Function", "handler",
+ "proj.mod.Target.handler", "prefixed.py", 1, 1,
+ "{}");
+ ASSERT_GT(raw_id, 0);
+ ASSERT_GT(prefixed_id, 0);
+ ASSERT(raw_id != prefixed_id);
+
+ CBMCall call = make_call("proj.mod.Caller.run", "handler");
+ call.site_start_byte = 120;
+ call.site_end_byte = 129;
+ CBMResolvedCall raw = make_rc("proj.mod.Caller.run", "mod.Target.handler", 0.75f);
+ raw.site_start_byte = call.site_start_byte;
+ raw.site_end_byte = call.site_end_byte;
+ CBMResolvedCall prefixed =
+ make_rc("proj.mod.Caller.run", "proj.mod.Target.handler", 0.90f);
+ prefixed.site_start_byte = call.site_start_byte;
+ prefixed.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {raw, prefixed};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_resolution_in_graph(&arr, &call, false, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT_NULL(hit);
+ PASS();
+}
+
+TEST(lsp_resolve_jvm_package_alias_of_materialized_target_is_not_ambiguous) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t target_id =
+ cbm_gbuf_upsert_node(gbuf, "Method", "twice", "proj.Util.twice", "Util.java", 1, 1, "{}");
+ ASSERT_GT(target_id, 0);
+
+ CBMCall call = make_call("proj.Client.run", "twice");
+ call.site_start_byte = 120;
+ call.site_end_byte = 128;
+ CBMResolvedCall local = make_rc("proj.Client.run", "proj.Util.twice", 0.92f);
+ local.site_start_byte = call.site_start_byte;
+ local.site_end_byte = call.site_end_byte;
+ CBMResolvedCall package = make_rc("proj.Client.run", "demo.Util.twice", 0.92f);
+ package.site_start_byte = call.site_start_byte;
+ package.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {local, package};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_resolution_in_graph(&arr, &call, true, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT_NOT_NULL(hit);
+ PASS();
+}
+
+TEST(lsp_resolve_jvm_two_tail_only_packages_stay_ambiguous) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t target_id = cbm_gbuf_upsert_node(gbuf, "Method", "run", "proj.generated.Service.run",
+ "Service.java", 1, 1, "{}");
+ ASSERT_GT(target_id, 0);
+
+ CBMCall call = make_call("proj.Client.call", "run");
+ call.site_start_byte = 130;
+ call.site_end_byte = 138;
+ CBMResolvedCall first = make_rc("proj.Client.call", "pkg1.Service.run", 0.80f);
+ first.site_start_byte = call.site_start_byte;
+ first.site_end_byte = call.site_end_byte;
+ CBMResolvedCall second = make_rc("proj.Client.call", "pkg2.Service.run", 0.90f);
+ second.site_start_byte = call.site_start_byte;
+ second.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {first, second};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_resolution_in_graph(&arr, &call, true, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT_NULL(hit);
+ PASS();
+}
+
+TEST(lsp_resolve_exact_site_beats_higher_confidence_legacy_record) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 100;
+ call.site_end_byte = 117;
+
+ CBMResolvedCall exact = make_rc("proj.mod.caller", "proj.Alpha.render", 0.80f);
+ exact.site_start_byte = call.site_start_byte;
+ exact.site_end_byte = call.site_end_byte;
+
+ /* A legacy resolver record has no occurrence span. Even with greater
+ * confidence it must not override the semantic record for this exact
+ * carrier occurrence. */
+ CBMResolvedCall legacy = make_rc("proj.mod.caller", "proj.Beta.render", 0.95f);
+ CBMResolvedCall items[] = {exact, legacy};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit = cbm_pipeline_find_lsp_resolution(&arr, &call, false);
+ ASSERT(hit == &items[0]);
+ ASSERT(strcmp(hit->callee_qn, "proj.Alpha.render") == 0);
+ PASS();
+}
+
+TEST(lsp_resolve_exact_site_beats_equal_confidence_legacy_record) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 200;
+ call.site_end_byte = 217;
+
+ /* Put the legacy record first to prove equal-confidence selection is not
+ * an array-order accident: occurrence exactness is the primary key. */
+ CBMResolvedCall legacy = make_rc("proj.mod.caller", "proj.Beta.render", 0.90f);
+ CBMResolvedCall exact = make_rc("proj.mod.caller", "proj.Alpha.render", 0.90f);
+ exact.site_start_byte = call.site_start_byte;
+ exact.site_end_byte = call.site_end_byte;
+ CBMResolvedCall items[] = {legacy, exact};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit = cbm_pipeline_find_lsp_resolution(&arr, &call, false);
+ ASSERT(hit == &items[1]);
+ ASSERT(strcmp(hit->callee_qn, "proj.Alpha.render") == 0);
+ PASS();
+}
+
+TEST(lsp_resolve_malformed_span_is_not_legacy_compatible) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 300;
+ call.site_end_byte = 317;
+
+ /* A reversed/partial span is corrupt occurrence metadata, not a legacy
+ * 0:0 record. It must be rejected even when it has greater confidence. */
+ CBMResolvedCall malformed = make_rc("proj.mod.caller", "proj.Wrong.render", 0.99f);
+ malformed.site_start_byte = 317;
+ malformed.site_end_byte = 300;
+ CBMResolvedCall legacy = make_rc("proj.mod.caller", "proj.Legacy.render", 0.75f);
+ CBMResolvedCall items[] = {malformed, legacy};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit = cbm_pipeline_find_lsp_resolution(&arr, &call, false);
+ ASSERT(hit == &items[1]);
+ PASS();
+}
+
+TEST(lsp_resolve_below_floor_exact_does_not_block_legacy) {
+ CBMCall call = make_call("proj.mod.caller", "receiver.render");
+ call.site_start_byte = 400;
+ call.site_end_byte = 417;
+
+ CBMResolvedCall below_floor = make_rc("proj.mod.caller", "proj.Exact.render", 0.55f);
+ below_floor.site_start_byte = call.site_start_byte;
+ below_floor.site_end_byte = call.site_end_byte;
+ CBMResolvedCall legacy = make_rc("proj.mod.caller", "proj.Legacy.render", 0.70f);
+ CBMResolvedCall items[] = {below_floor, legacy};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_resolution(&arr, &call, false) == &items[1]);
+ PASS();
+}
+
+static CBMCall make_tail_call(uint32_t start, uint32_t end) {
+ CBMCall call = make_call("proj.raw.Service.handle", "helper.run");
+ call.site_start_byte = start;
+ call.site_end_byte = end;
+ return call;
+}
+
+static CBMResolvedCall make_tail_rc(const char *callee, float confidence, uint32_t start,
+ uint32_t end) {
+ CBMResolvedCall resolved = make_rc("com.example.generated.Service.handle", callee, confidence);
+ resolved.site_start_byte = start;
+ resolved.site_end_byte = end;
+ return resolved;
+}
+
+TEST(lsp_tail_exact_site_beats_legacy_regardless_of_order) {
+ CBMCall call = make_tail_call(500, 512);
+ CBMResolvedCall exact = make_tail_rc("com.example.Alpha.run", 0.80f, 500, 512);
+ CBMResolvedCall legacy = make_tail_rc("com.example.Beta.run", 0.99f, 0, 0);
+ CBMResolvedCall exact_first[] = {exact, legacy};
+ CBMResolvedCall legacy_first[] = {legacy, exact};
+ CBMResolvedCallArray first = {exact_first, 2, 2};
+ CBMResolvedCallArray second = {legacy_first, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_resolution(&first, &call, true) == &exact_first[0]);
+ ASSERT(cbm_pipeline_find_lsp_resolution(&second, &call, true) == &legacy_first[1]);
+ PASS();
+}
+
+TEST(lsp_tail_duplicate_exact_rows_same_target_are_not_ambiguous) {
+ CBMCall call = make_tail_call(600, 612);
+ CBMResolvedCall low = make_tail_rc("com.example.Helper.run", 0.75f, 600, 612);
+ CBMResolvedCall high = make_tail_rc("com.example.Helper.run", 0.90f, 600, 612);
+ CBMResolvedCall items[] = {low, high};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_resolution(&arr, &call, true) == &items[1]);
+ PASS();
+}
+
+TEST(lsp_tail_distinct_exact_targets_are_ambiguous) {
+ CBMCall call = make_tail_call(700, 712);
+ CBMResolvedCall alpha = make_tail_rc("com.example.Alpha.run", 0.75f, 700, 712);
+ CBMResolvedCall beta = make_tail_rc("com.example.Beta.run", 0.99f, 700, 712);
+ CBMResolvedCall items[] = {alpha, beta};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT_NULL(cbm_pipeline_find_lsp_resolution(&arr, &call, true));
+ PASS();
+}
+
+TEST(lsp_tail_duplicate_legacy_rows_same_target_are_not_ambiguous) {
+ CBMCall call = make_tail_call(800, 812);
+ CBMResolvedCall low = make_tail_rc("com.example.Helper.run", 0.75f, 0, 0);
+ CBMResolvedCall high = make_tail_rc("com.example.Helper.run", 0.90f, 0, 0);
+ CBMResolvedCall items[] = {low, high};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_resolution(&arr, &call, true) == &items[1]);
+ PASS();
+}
+
+TEST(lsp_tail_distinct_legacy_targets_are_ambiguous) {
+ CBMCall call = make_tail_call(900, 912);
+ CBMResolvedCall alpha = make_tail_rc("com.example.Alpha.run", 0.75f, 0, 0);
+ CBMResolvedCall beta = make_tail_rc("com.example.Beta.run", 0.99f, 0, 0);
+ CBMResolvedCall items[] = {alpha, beta};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT_NULL(cbm_pipeline_find_lsp_resolution(&arr, &call, true));
+ PASS();
+}
+
+static CBMUsage make_reference_usage(const char *caller, const char *name, uint32_t start,
+ uint32_t end) {
+ CBMUsage usage = {0};
+ usage.enclosing_func_qn = caller;
+ usage.ref_name = name;
+ usage.kind = CBM_USAGE_CALL_REFERENCE;
+ usage.site_start_byte = start;
+ usage.site_end_byte = end;
+ return usage;
+}
+
+static CBMResolvedCall make_reference_rc(const char *caller, const char *callee, float confidence,
+ uint32_t start, uint32_t end) {
+ CBMResolvedCall resolved = make_rc(caller, callee, confidence);
+ resolved.kind = CBM_RESOLVED_CALL_REFERENCE;
+ resolved.site_start_byte = start;
+ resolved.site_end_byte = end;
+ return resolved;
+}
+
+TEST(lsp_reference_duplicate_exact_rows_same_target_are_not_ambiguous) {
+ CBMUsage usage = make_reference_usage("proj.mod.Caller.run", "handler", 1000, 1007);
+ CBMResolvedCall low =
+ make_reference_rc("proj.mod.Caller.run", "proj.Target.handler", 0.75f, 1000, 1007);
+ CBMResolvedCall high =
+ make_reference_rc("proj.mod.Caller.run", "proj.Target.handler", 0.90f, 1000, 1007);
+ CBMResolvedCall items[] = {low, high};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_reference(&arr, &usage, false) == &items[1]);
+ PASS();
+}
+
+/* Per-file LSP rows may carry a package-shaped target while a cross-file row
+ * carries the same graph QN with the project prefix already attached. Those
+ * spellings identify one target and must not trip the distinct-target
+ * ambiguity guard. */
+TEST(lsp_reference_project_prefixed_duplicate_is_not_ambiguous) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t target_id = cbm_gbuf_upsert_node(gbuf, "Function", "handler", "proj.mod.Target.handler",
+ "target.go", 1, 1, "{}");
+ ASSERT_GT(target_id, 0);
+ const cbm_gbuf_node_t *raw_target =
+ cbm_pipeline_lsp_target_node(gbuf, project, "mod.Target.handler", false);
+ const cbm_gbuf_node_t *prefixed_target =
+ cbm_pipeline_lsp_target_node(gbuf, project, "proj.mod.Target.handler", false);
+ ASSERT_NOT_NULL(raw_target);
+ ASSERT_NOT_NULL(prefixed_target);
+ ASSERT_EQ(raw_target->id, prefixed_target->id);
+
+ CBMUsage usage = make_reference_usage("proj.mod.Caller.run", "handler", 1050, 1057);
+ CBMResolvedCall raw =
+ make_reference_rc("proj.mod.Caller.run", "mod.Target.handler", 0.75f, 1050, 1057);
+ CBMResolvedCall prefixed =
+ make_reference_rc("proj.mod.Caller.run", "proj.mod.Target.handler", 0.90f, 1050, 1057);
+ CBMResolvedCall items[] = {raw, prefixed};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_reference_in_graph(&arr, &usage, false, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT(hit == &items[1]);
+ PASS();
+}
+
+TEST(lsp_reference_project_prefix_spellings_stay_ambiguous_when_both_nodes_exist) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t raw_id = cbm_gbuf_upsert_node(gbuf, "Function", "handler", "mod.Target.handler",
+ "raw.go", 1, 1, "{}");
+ int64_t prefixed_id = cbm_gbuf_upsert_node(
+ gbuf, "Function", "handler", "proj.mod.Target.handler", "prefixed.go", 1, 1, "{}");
+ ASSERT_GT(raw_id, 0);
+ ASSERT_GT(prefixed_id, 0);
+ ASSERT(raw_id != prefixed_id);
+
+ CBMUsage usage = make_reference_usage("proj.mod.Caller.run", "handler", 1070, 1077);
+ CBMResolvedCall raw =
+ make_reference_rc("proj.mod.Caller.run", "mod.Target.handler", 0.75f, 1070, 1077);
+ CBMResolvedCall prefixed =
+ make_reference_rc("proj.mod.Caller.run", "proj.mod.Target.handler", 0.90f, 1070, 1077);
+ CBMResolvedCall items[] = {raw, prefixed};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ const CBMResolvedCall *hit =
+ cbm_pipeline_find_lsp_reference_in_graph(&arr, &usage, false, gbuf, project);
+ cbm_gbuf_free(gbuf);
+ ASSERT_NULL(hit);
+ PASS();
+}
+
+/* A JVM tail lookup may recover one materialized graph node when package- and
+ * path-shaped QNs drift, but it must not erase semantic disagreement between
+ * two resolver rows. `pkg1.Service.handler` and `pkg2.Service.handler` are
+ * distinct source targets even when each independently falls back to the same
+ * unique `Service.handler` graph node. Collapsing them would let row order or
+ * confidence fabricate an exact CALL_REFERENCE instead of failing closed. */
+TEST(lsp_reference_jvm_distinct_packages_do_not_collapse_via_tail_node) {
+ const char *project = "proj";
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t materialized_id = cbm_gbuf_upsert_node(
+ gbuf, "Method", "handler", "proj.generated.Service.handler", "Service.kt", 1, 1, "{}");
+ ASSERT_GT(materialized_id, 0);
+
+ CBMUsage usage = make_reference_usage("proj.consumer.Caller.run", "handler", 1080, 1087);
+ CBMResolvedCall pkg1 =
+ make_reference_rc("proj.consumer.Caller.run", "pkg1.Service.handler", 0.75f, 1080, 1087);
+ CBMResolvedCall pkg2 =
+ make_reference_rc("proj.consumer.Caller.run", "pkg2.Service.handler", 0.90f, 1080, 1087);
+ CBMResolvedCall pkg1_first[] = {pkg1, pkg2};
+ CBMResolvedCall pkg2_first[] = {pkg2, pkg1};
+ CBMResolvedCallArray first = {pkg1_first, 2, 2};
+ CBMResolvedCallArray second = {pkg2_first, 2, 2};
+
+ const cbm_gbuf_node_t *pkg1_tail =
+ cbm_pipeline_lsp_target_node(gbuf, project, pkg1.callee_qn, true);
+ const cbm_gbuf_node_t *pkg2_tail =
+ cbm_pipeline_lsp_target_node(gbuf, project, pkg2.callee_qn, true);
+ bool same_tail_node = pkg1_tail && pkg2_tail && pkg1_tail->id == materialized_id &&
+ pkg2_tail->id == materialized_id;
+ const CBMResolvedCall *first_hit =
+ cbm_pipeline_find_lsp_reference_in_graph(&first, &usage, true, gbuf, project);
+ const CBMResolvedCall *second_hit =
+ cbm_pipeline_find_lsp_reference_in_graph(&second, &usage, true, gbuf, project);
+ cbm_gbuf_free(gbuf);
+
+ ASSERT_TRUE(same_tail_node);
+ ASSERT_NULL(first_hit);
+ ASSERT_NULL(second_hit);
+ PASS();
+}
+
+TEST(lsp_reference_distinct_exact_targets_are_order_invariant) {
+ CBMUsage usage = make_reference_usage("proj.mod.Caller.run", "handler", 1100, 1107);
+ CBMResolvedCall alpha =
+ make_reference_rc("proj.mod.Caller.run", "proj.Alpha.handler", 0.90f, 1100, 1107);
+ CBMResolvedCall beta =
+ make_reference_rc("proj.mod.Caller.run", "proj.Beta.handler", 0.90f, 1100, 1107);
+ CBMResolvedCall alpha_first[] = {alpha, beta};
+ CBMResolvedCall beta_first[] = {beta, alpha};
+ CBMResolvedCallArray first = {alpha_first, 2, 2};
+ CBMResolvedCallArray second = {beta_first, 2, 2};
+
+ const CBMResolvedCall *first_hit = cbm_pipeline_find_lsp_reference(&first, &usage, false);
+ const CBMResolvedCall *second_hit = cbm_pipeline_find_lsp_reference(&second, &usage, false);
+ bool invariant = (!first_hit && !second_hit) ||
+ (first_hit && second_hit && first_hit->callee_qn && second_hit->callee_qn &&
+ strcmp(first_hit->callee_qn, second_hit->callee_qn) == 0);
+ ASSERT_TRUE(invariant);
+ PASS();
+}
+
+TEST(lsp_reference_duplicate_tail_rows_same_target_are_not_ambiguous) {
+ CBMUsage usage = make_reference_usage("proj.raw.Service.handle", "handler", 1200, 1207);
+ CBMResolvedCall low =
+ make_reference_rc("com.generated.Service.handle", "com.Target.handler", 0.75f, 1200, 1207);
+ CBMResolvedCall high =
+ make_reference_rc("com.generated.Service.handle", "com.Target.handler", 0.90f, 1200, 1207);
+ CBMResolvedCall items[] = {low, high};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT(cbm_pipeline_find_lsp_reference(&arr, &usage, true) == &items[1]);
+ PASS();
+}
+
+TEST(lsp_reference_distinct_tail_targets_are_ambiguous) {
+ CBMUsage usage = make_reference_usage("proj.raw.Service.handle", "handler", 1300, 1307);
+ CBMResolvedCall alpha =
+ make_reference_rc("com.generated.Service.handle", "com.Alpha.handler", 0.75f, 1300, 1307);
+ CBMResolvedCall beta =
+ make_reference_rc("com.generated.Service.handle", "com.Beta.handler", 0.99f, 1300, 1307);
+ CBMResolvedCall items[] = {alpha, beta};
+ CBMResolvedCallArray arr = {items, 2, 2};
+
+ ASSERT_NULL(cbm_pipeline_find_lsp_reference(&arr, &usage, true));
+ PASS();
+}
+
+TEST(lsp_target_node_supports_long_prefixed_qualified_name) {
+ const char *project = "long_project";
+ enum { CALLEE_LEN = 1100 };
+ char *callee = malloc(CALLEE_LEN + 1U);
+ char *qualified = malloc(strlen(project) + 1U + CALLEE_LEN + 1U);
+ ASSERT_NOT_NULL(callee);
+ ASSERT_NOT_NULL(qualified);
+ memset(callee, 'n', CALLEE_LEN);
+ callee[CALLEE_LEN] = '\0';
+ snprintf(qualified, strlen(project) + 1U + CALLEE_LEN + 1U, "%s.%s", project, callee);
+
+ cbm_gbuf_t *gbuf = cbm_gbuf_new(project, "/tmp");
+ ASSERT_NOT_NULL(gbuf);
+ int64_t id =
+ cbm_gbuf_upsert_node(gbuf, "Function", "target", qualified, "target.c", 1, 1, "{}");
+ ASSERT_GT(id, 0);
+ const cbm_gbuf_node_t *found = cbm_pipeline_lsp_target_node(gbuf, project, callee, false);
+ if (!found) {
+ printf(" long target-QN diagnostic: project=%zu callee=%zu combined=%zu\n",
+ strlen(project), strlen(callee), strlen(qualified));
+ }
+ bool same_node = found && found->id == id;
+ cbm_gbuf_free(gbuf);
+ free(qualified);
+ free(callee);
+ ASSERT_TRUE(same_node);
+ PASS();
+}
+
/* ── Suite Registration ──────────────────────────────────────────── */
SUITE(parallel) {
+ RUN_TEST(usage_semantic_reference_candidate_trusts_marked_producer);
+ RUN_TEST(lsp_bare_segment_skips_preprocessor_spacing);
RUN_TEST(lsp_resolve_qualified_static_call_normalizes_colons);
- RUN_TEST(lsp_resolve_misattribution_is_bounded);
+ RUN_TEST(lsp_resolve_distinct_exact_caller_targets_fail_closed);
+ RUN_TEST(lsp_resolve_duplicate_exact_caller_rows_same_target_are_not_ambiguous);
+ RUN_TEST(lsp_resolve_distinct_exact_caller_site_targets_are_ambiguous);
+ RUN_TEST(lsp_resolve_project_prefixed_duplicate_is_not_ambiguous);
+ RUN_TEST(lsp_resolve_project_prefix_spellings_stay_ambiguous_when_both_nodes_exist);
+ RUN_TEST(lsp_resolve_jvm_package_alias_of_materialized_target_is_not_ambiguous);
+ RUN_TEST(lsp_resolve_jvm_two_tail_only_packages_stay_ambiguous);
+ RUN_TEST(lsp_resolve_exact_site_beats_higher_confidence_legacy_record);
+ RUN_TEST(lsp_resolve_exact_site_beats_equal_confidence_legacy_record);
+ RUN_TEST(lsp_resolve_malformed_span_is_not_legacy_compatible);
+ RUN_TEST(lsp_resolve_below_floor_exact_does_not_block_legacy);
+ RUN_TEST(lsp_tail_exact_site_beats_legacy_regardless_of_order);
+ RUN_TEST(lsp_tail_duplicate_exact_rows_same_target_are_not_ambiguous);
+ RUN_TEST(lsp_tail_distinct_exact_targets_are_ambiguous);
+ RUN_TEST(lsp_tail_duplicate_legacy_rows_same_target_are_not_ambiguous);
+ RUN_TEST(lsp_tail_distinct_legacy_targets_are_ambiguous);
+ RUN_TEST(lsp_reference_duplicate_exact_rows_same_target_are_not_ambiguous);
+ RUN_TEST(lsp_reference_project_prefixed_duplicate_is_not_ambiguous);
+ RUN_TEST(lsp_reference_project_prefix_spellings_stay_ambiguous_when_both_nodes_exist);
+ RUN_TEST(lsp_reference_jvm_distinct_packages_do_not_collapse_via_tail_node);
+ RUN_TEST(lsp_reference_distinct_exact_targets_are_order_invariant);
+ RUN_TEST(lsp_reference_duplicate_tail_rows_same_target_are_not_ambiguous);
+ RUN_TEST(lsp_reference_distinct_tail_targets_are_ambiguous);
+ RUN_TEST(lsp_target_node_supports_long_prefixed_qualified_name);
RUN_TEST(grpc_service_name_preserves_service_suffix_issue294);
RUN_TEST(grpc_no_phantom_route_from_plain_var_issue294);
/* Graph buffer merge/shared-ID tests */
@@ -1162,6 +3834,26 @@ SUITE(parallel) {
/* Parallel pipeline parity tests */
RUN_TEST(parallel_node_count);
RUN_TEST(parallel_python_lsp_override_emits_lsp_strategy_edges);
+ RUN_TEST(parallel_lsp_index_exact_site_beats_legacy_record_in_graph);
+ RUN_TEST(parallel_lsp_index_distinct_exact_targets_fail_closed_in_graph);
+ RUN_TEST(parallel_lsp_index_exact_ambiguity_does_not_fall_through_to_legacy);
+ RUN_TEST(parallel_lsp_long_exact_key_never_yields_legacy_target);
+ RUN_TEST(parallel_lsp_exact_index_handles_repeated_synthetic_occurrences_without_linear_scan);
+#if defined(CBM_CALL_REFERENCE_LOOKUP_TEST_API) && CBM_CALL_REFERENCE_LOOKUP_TEST_API
+ RUN_TEST(parallel_call_reference_lookup_rows_grow_linearly);
+#endif
+ RUN_TEST(parallel_tsx_local_component_shadow_has_no_false_call);
+ RUN_TEST(parallel_exact_semantic_noncallable_target_stays_usage);
+ RUN_TEST(parallel_typescript_module_value_usage_respects_lexical_shadows);
+ RUN_TEST(parallel_typescript_import_namespace_exact_parity);
+ RUN_TEST(parallel_tsx_import_namespace_exact_parity);
+ RUN_TEST(parallel_kotlin_external_protocol_does_not_use_project_class_method_tail);
+ RUN_TEST(parallel_kotlin_nonbinary_operator_carriers_reach_graph);
+ RUN_TEST(parallel_rust_known_macro_does_not_fallback_to_local_function);
+ RUN_TEST(parallel_rust_proc_macros_are_decorates_and_usage_only);
+ RUN_TEST(parallel_c_preprocessed_coordinate_collision_preserves_hidden_target);
+ RUN_TEST(parallel_cpp_preprocessed_coordinate_collision_preserves_hidden_target);
+ RUN_TEST(parallel_cuda_preprocessed_coordinate_collision_preserves_hidden_target);
RUN_TEST(parallel_python_lsp_override_cross_file_emits_lsp_strategy_edges);
RUN_TEST(parallel_cross_file_reread_preserves_unretained_edges);
RUN_TEST(parallel_java_kotlin_lsp_override_cross_file_emits_lsp_strategy_edges);
diff --git a/tests/test_perl_lsp.c b/tests/test_perl_lsp.c
index 50c02c466..a42911af9 100644
--- a/tests/test_perl_lsp.c
+++ b/tests/test_perl_lsp.c
@@ -26,6 +26,7 @@
*/
#include "test_framework.h"
#include "cbm.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "lsp/perl_lsp.h"
#include <string.h>
@@ -372,6 +373,197 @@ TEST(perllsp_unindexed_receiver_emits_block) {
PASS();
}
+/* Occurrence identity is independent of the pending public-QN decision. This
+ * deliberately invokes the same Widget method twice, so both sites resolve to
+ * one target under today's flat QNs and would still share one target if that QN
+ * later becomes package-qualified. Each semantic record must nevertheless be
+ * tied to its own full parser occurrence. */
+TEST(perllsp_repeated_target_calls_join_by_exact_site) {
+ static const char source[] = "package Widget;\n"
+ "sub render { return 1; }\n"
+ "package main;\n"
+ "sub occurrence_probe {\n"
+ " Widget->render();\n"
+ " Widget->render();\n"
+ "}\n";
+ static const char call_text[] = "Widget->render()";
+
+ const char *first_site = strstr(source, call_text);
+ const char *second_site = first_site ? strstr(first_site + 1, call_text) : NULL;
+ ASSERT_NOT_NULL(first_site);
+ ASSERT_NOT_NULL(second_site);
+ const uint32_t first_start = (uint32_t)(first_site - source);
+ const uint32_t first_end = first_start + (uint32_t)strlen(call_text);
+ const uint32_t second_start = (uint32_t)(second_site - source);
+ const uint32_t second_end = second_start + (uint32_t)strlen(call_text);
+
+ CBMFileResult *r = extract_perl(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *first_call = NULL;
+ const CBMCall *second_call = NULL;
+ int render_carriers = 0;
+ int zero_span_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "main.occurrence_probe") ||
+ !call->callee_name || !strstr(call->callee_name, "render")) {
+ continue;
+ }
+ render_carriers++;
+ if (call->site_end_byte <= call->site_start_byte)
+ zero_span_carriers++;
+ if (call->site_start_byte == first_start && call->site_end_byte == first_end)
+ first_call = call;
+ if (call->site_start_byte == second_start && call->site_end_byte == second_end)
+ second_call = call;
+ }
+
+ ASSERT_EQ(render_carriers, 2);
+ ASSERT_EQ(zero_span_carriers, 0);
+ ASSERT_NOT_NULL(first_call);
+ ASSERT_NOT_NULL(second_call);
+ ASSERT_TRUE(first_call != second_call);
+
+ const CBMResolvedCall *first_semantic = NULL;
+ const CBMResolvedCall *second_semantic = NULL;
+ int render_semantics = 0;
+ int zero_span_semantics = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind != CBM_RESOLVED_INVOCATION || rc->confidence <= 0.0f || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "main.occurrence_probe") || !rc->callee_qn ||
+ !strstr(rc->callee_qn, "render")) {
+ continue;
+ }
+ render_semantics++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_semantics++;
+ if (rc->site_start_byte == first_start && rc->site_end_byte == first_end)
+ first_semantic = rc;
+ if (rc->site_start_byte == second_start && rc->site_end_byte == second_end)
+ second_semantic = rc;
+ }
+
+ ASSERT_EQ(render_semantics, 2);
+ ASSERT_EQ(zero_span_semantics, 0);
+ ASSERT_NOT_NULL(first_semantic);
+ ASSERT_NOT_NULL(second_semantic);
+ ASSERT_TRUE(first_semantic != second_semantic);
+ ASSERT_STR_EQ(first_semantic->callee_qn, second_semantic->callee_qn);
+
+ const CBMResolvedCall *first_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, first_call, false);
+ const CBMResolvedCall *second_joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, second_call, false);
+ ASSERT_TRUE(first_joined == first_semantic);
+ ASSERT_TRUE(second_joined == second_semantic);
+
+ cbm_free_result(r);
+ PASS();
+}
+
+/* Keep the other ordinary resolver branches under the same occurrence
+ * contract. The first regression above is a static method-call expression;
+ * this helper also exercises function-call expressions and typed/inherited
+ * method dispatch without coupling the tests to the pending package-QN
+ * decision. */
+static int assert_perl_repeated_exact_join(const char *source, const char *caller_fragment,
+ const char *callee_fragment, const char *call_text) {
+ const char *first_site = strstr(source, call_text);
+ const char *second_site = first_site ? strstr(first_site + 1, call_text) : NULL;
+ ASSERT_NOT_NULL(first_site);
+ ASSERT_NOT_NULL(second_site);
+ const uint32_t starts[2] = {(uint32_t)(first_site - source), (uint32_t)(second_site - source)};
+ const uint32_t ends[2] = {starts[0] + (uint32_t)strlen(call_text),
+ starts[1] + (uint32_t)strlen(call_text)};
+
+ CBMFileResult *r = extract_perl(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *calls[2] = {NULL, NULL};
+ int carrier_count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, caller_fragment) ||
+ !call->callee_name || !strstr(call->callee_name, callee_fragment)) {
+ continue;
+ }
+ carrier_count++;
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (call->site_start_byte == starts[occurrence] &&
+ call->site_end_byte == ends[occurrence]) {
+ calls[occurrence] = call;
+ }
+ }
+ }
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_NOT_NULL(calls[0]);
+ ASSERT_NOT_NULL(calls[1]);
+
+ const CBMResolvedCall *semantics[2] = {NULL, NULL};
+ int semantic_count = 0;
+ int zero_span_semantics = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &r->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0.0f ||
+ !resolved->caller_qn || !strstr(resolved->caller_qn, caller_fragment) ||
+ !resolved->callee_qn || !strstr(resolved->callee_qn, callee_fragment)) {
+ continue;
+ }
+ semantic_count++;
+ if (resolved->site_end_byte <= resolved->site_start_byte) {
+ zero_span_semantics++;
+ }
+ for (int occurrence = 0; occurrence < 2; occurrence++) {
+ if (resolved->site_start_byte == starts[occurrence] &&
+ resolved->site_end_byte == ends[occurrence]) {
+ semantics[occurrence] = resolved;
+ }
+ }
+ }
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_EQ(zero_span_semantics, 0);
+ ASSERT_NOT_NULL(semantics[0]);
+ ASSERT_NOT_NULL(semantics[1]);
+ ASSERT_STR_EQ(semantics[0]->callee_qn, semantics[1]->callee_qn);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&r->resolved_calls, calls[0], false) ==
+ semantics[0]);
+ ASSERT_TRUE(cbm_pipeline_find_lsp_resolution(&r->resolved_calls, calls[1], false) ==
+ semantics[1]);
+
+ cbm_free_result(r);
+ return 0;
+}
+
+TEST(perllsp_repeated_static_function_calls_join_by_exact_site) {
+ static const char source[] = "package Helper;\n"
+ "sub work { return 1; }\n"
+ "package main;\n"
+ "sub function_occurrence_probe {\n"
+ " Helper::work();\n"
+ " Helper::work();\n"
+ "}\n";
+ return assert_perl_repeated_exact_join(source, "main.function_occurrence_probe", "work",
+ "Helper::work()");
+}
+
+TEST(perllsp_repeated_inherited_method_calls_join_by_exact_site) {
+ static const char source[] = "package Base;\n"
+ "sub greet { return 1; }\n"
+ "package Child;\n"
+ "our @ISA = ('Base');\n"
+ "sub new { my $class = shift; return bless {}, $class; }\n"
+ "package main;\n"
+ "sub inherited_occurrence_probe {\n"
+ " my $child = Child->new();\n"
+ " $child->greet();\n"
+ " $child->greet();\n"
+ "}\n";
+ return assert_perl_repeated_exact_join(source, "main.inherited_occurrence_probe", "greet",
+ "$child->greet()");
+}
+
/* ── Suite registration ────────────────────────────────────────── */
SUITE(perl_lsp) {
@@ -389,4 +581,7 @@ SUITE(perl_lsp) {
RUN_TEST(perllsp_super_dispatch);
RUN_TEST(perllsp_super_no_parent_no_edge);
RUN_TEST(perllsp_unindexed_receiver_emits_block);
+ RUN_TEST(perllsp_repeated_target_calls_join_by_exact_site);
+ RUN_TEST(perllsp_repeated_static_function_calls_join_by_exact_site);
+ RUN_TEST(perllsp_repeated_inherited_method_calls_join_by_exact_site);
}
diff --git a/tests/test_php_lsp.c b/tests/test_php_lsp.c
index 592ff114f..906bababc 100644
--- a/tests/test_php_lsp.c
+++ b/tests/test_php_lsp.c
@@ -17,6 +17,7 @@
*/
#include "test_framework.h"
#include "cbm.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "lsp/php_lsp.h"
#include <string.h>
@@ -5213,6 +5214,100 @@ TEST(phplsp_realistic_eloquent_model) {
PASS();
}
+/* Same-leaf typed dispatch must preserve occurrence identity through the PHP
+ * semantic pass. Full parser-carrier spans and target-specific semantic spans
+ * keep the two render calls from both joining the first resolved target. */
+TEST(phplsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ static const char source[] = "<?php\n"
+ "class Alpha { public function render(): void {} }\n"
+ "class Beta { public function render(): void {} }\n"
+ "class OccurrenceProbe {\n"
+ " public function run(Alpha $alpha, Beta $beta): void {\n"
+ " $alpha->render();\n"
+ " $beta->render();\n"
+ " }\n"
+ "}\n";
+ static const char alpha_text[] = "$alpha->render()";
+ static const char beta_text[] = "$beta->render()";
+
+ const char *alpha_site = strstr(source, alpha_text);
+ const char *beta_site = strstr(source, beta_text);
+ ASSERT_NOT_NULL(alpha_site);
+ ASSERT_NOT_NULL(beta_site);
+ const uint32_t alpha_start = (uint32_t)(alpha_site - source);
+ const uint32_t alpha_end = alpha_start + (uint32_t)strlen(alpha_text);
+ const uint32_t beta_start = (uint32_t)(beta_site - source);
+ const uint32_t beta_end = beta_start + (uint32_t)strlen(beta_text);
+
+ CBMFileResult *r = extract_php(source);
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *alpha_call = NULL;
+ const CBMCall *beta_call = NULL;
+ int render_carriers = 0;
+ int zero_span_carriers = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "OccurrenceProbe.run") ||
+ !call->callee_name || !strstr(call->callee_name, "render")) {
+ continue;
+ }
+ render_carriers++;
+ if (call->site_end_byte <= call->site_start_byte)
+ zero_span_carriers++;
+ if (call->site_start_byte == alpha_start && call->site_end_byte == alpha_end)
+ alpha_call = call;
+ if (call->site_start_byte == beta_start && call->site_end_byte == beta_end)
+ beta_call = call;
+ }
+
+ ASSERT_EQ(render_carriers, 2);
+ ASSERT_EQ(zero_span_carriers, 0);
+ ASSERT_NOT_NULL(alpha_call);
+ ASSERT_NOT_NULL(beta_call);
+ ASSERT_TRUE(alpha_call != beta_call);
+
+ const CBMResolvedCall *alpha_semantic = NULL;
+ const CBMResolvedCall *beta_semantic = NULL;
+ int render_semantics = 0;
+ int zero_span_hijackers = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->kind != CBM_RESOLVED_INVOCATION || rc->confidence <= 0.0f || !rc->caller_qn ||
+ !strstr(rc->caller_qn, "OccurrenceProbe.run") || !rc->callee_qn ||
+ !strstr(rc->callee_qn, ".render")) {
+ continue;
+ }
+ render_semantics++;
+ if (rc->site_end_byte <= rc->site_start_byte)
+ zero_span_hijackers++;
+ if (strstr(rc->callee_qn, "Alpha.render") && rc->site_start_byte == alpha_start &&
+ rc->site_end_byte == alpha_end) {
+ alpha_semantic = rc;
+ }
+ if (strstr(rc->callee_qn, "Beta.render") && rc->site_start_byte == beta_start &&
+ rc->site_end_byte == beta_end) {
+ beta_semantic = rc;
+ }
+ }
+
+ ASSERT_EQ(render_semantics, 2);
+ ASSERT_EQ(zero_span_hijackers, 0);
+ ASSERT_NOT_NULL(alpha_semantic);
+ ASSERT_NOT_NULL(beta_semantic);
+ ASSERT_TRUE(alpha_semantic != beta_semantic);
+
+ const CBMResolvedCall *alpha_join =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, alpha_call, false);
+ const CBMResolvedCall *beta_join =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, beta_call, false);
+ ASSERT_TRUE(alpha_join == alpha_semantic);
+ ASSERT_TRUE(beta_join == beta_semantic);
+
+ cbm_free_result(r);
+ PASS();
+}
+
/* ── Suite ─────────────────────────────────────────────────────── */
SUITE(php_lsp) {
@@ -5506,4 +5601,5 @@ SUITE(php_lsp) {
RUN_TEST(phplsp_realistic_logger_chain_with_context);
RUN_TEST(phplsp_realistic_carbon_chain_in_method);
RUN_TEST(phplsp_realistic_eloquent_model);
+ RUN_TEST(phplsp_ordinary_same_leaf_calls_join_by_exact_site);
}
diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c
index 4f095f385..34178540e 100644
--- a/tests/test_pipeline.c
+++ b/tests/test_pipeline.c
@@ -11,11 +11,16 @@
#include "foundation/mem.h" // cbm_mem_init/budget (back-pressure futile-nap test)
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
+#include "pipeline/artifact.h"
#include "store/store.h"
#include "git/git_context.h"
#include "foundation/dump_verify.h"
+#include "foundation/sha256.h"
+#include "foundation/compat_fs.h"
+#include "discover/userconfig.h"
#include <stdlib.h>
+#include <stdarg.h>
#include <string.h>
#include <stdatomic.h>
#include "foundation/compat_thread.h"
@@ -851,6 +856,46 @@ static bool cross_file_call_exists(cbm_store_t *s, const char *project, const ch
return found;
}
+/* True iff the exact named CALLS edge exists and its serialized strategy
+ * contains `strategy_fragment`. Parallel synthetic-carrier regressions use
+ * this on a separate ordinary-call control: it proves the cross-file LSP ran
+ * successfully for the language/target, rather than letting a registry-only
+ * edge make a broken fixture look healthy. */
+static bool cross_file_call_has_strategy(cbm_store_t *s, const char *project, const char *src_name,
+ const char *tgt_name, const char *strategy_fragment) {
+ cbm_node_t *srcs = NULL;
+ cbm_node_t *tgts = NULL;
+ int sc = 0;
+ int tc = 0;
+ cbm_store_find_nodes_by_name(s, project, src_name, &srcs, &sc);
+ cbm_store_find_nodes_by_name(s, project, tgt_name, &tgts, &tc);
+ bool found = false;
+ for (int i = 0; i < sc && !found; i++) {
+ cbm_edge_t *edges = NULL;
+ int ec = 0;
+ cbm_store_find_edges_by_source_type(s, srcs[i].id, "CALLS", &edges, &ec);
+ for (int j = 0; j < ec && !found; j++) {
+ for (int k = 0; k < tc; k++) {
+ if (edges[j].target_id == tgts[k].id && edges[j].properties_json &&
+ strstr(edges[j].properties_json, strategy_fragment)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, ec);
+ }
+ }
+ if (srcs) {
+ cbm_store_free_nodes(srcs, sc);
+ }
+ if (tgts) {
+ cbm_store_free_nodes(tgts, tc);
+ }
+ return found;
+}
+
/* Regression: incremental re-index of an edited file must NOT drop inbound
* cross-file CALLS edges whose source lives in an UNCHANGED file.
*
@@ -865,58 +910,2771 @@ TEST(pipeline_incremental_preserves_cross_file_calls) {
}
char db_path[512];
- snprintf(db_path, sizeof(db_path), "%s/test_incr_calls.db", g_tmpdir);
+ snprintf(db_path, sizeof(db_path), "%s/test_incr_calls.db", g_tmpdir);
+
+ /* 1. Full index. */
+ cbm_pipeline_t *p1 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p1);
+ ASSERT_EQ(cbm_pipeline_run(p1), 0);
+ const char *project = cbm_pipeline_project_name(p1);
+
+ cbm_store_t *s1 = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s1);
+ int calls_before = cbm_store_count_edges_by_type(s1, project, "CALLS");
+ ASSERT_GTE(calls_before, 2); /* main->Serve and Serve->Help at minimum */
+ ASSERT_TRUE(cross_file_call_exists(s1, project, "Serve", "Help"));
+ cbm_store_close(s1);
+ cbm_pipeline_free(p1);
+
+ /* 2. Edit the callee's file so the incremental classifier marks it changed
+ * (mtime+size differ). Help's symbol + qualified name are unchanged. */
+ char helper[512];
+ snprintf(helper, sizeof(helper), "%s/pkg/util/helper.go", g_tmpdir);
+ ASSERT_EQ(th_append_file(helper, "\n// incremental regression marker\n"), 0);
+
+ /* 3. Re-run on the SAME db_path → auto-routes to incremental re-index. */
+ cbm_pipeline_t *p2 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p2);
+ ASSERT_EQ(cbm_pipeline_run(p2), 0);
+
+ /* 4. The inbound cross-file CALLS edge must survive and the total CALLS
+ * count must not regress. (Before the fix: Serve->Help is dropped.)
+ * NOTE: query with p2's project name — p1 (and the `project` pointer it
+ * owned) was freed above; p1 and p2 derive the same name from g_tmpdir. */
+ const char *project2 = cbm_pipeline_project_name(p2);
+ cbm_store_t *s2 = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(s2);
+ int calls_after = cbm_store_count_edges_by_type(s2, project2, "CALLS");
+ ASSERT_EQ(calls_after, calls_before);
+ ASSERT_TRUE(cross_file_call_exists(s2, project2, "Serve", "Help"));
+ cbm_store_close(s2);
+ cbm_pipeline_free(p2);
+
+ teardown_test_repo();
+ PASS();
+}
+
+/* TS/JS receiver-aware weak-strategy suppression (#592/#606 direction; Perl
+ * precedent #477). A member call x.foo() whose receiver TYPE the TS-LSP cannot
+ * resolve (a regex literal `re.test()`) must NOT be bound to a same-named
+ * project method by a weak short-name strategy — that fabricates a CALLS edge.
+ * Type-resolved receivers (`c.test()` on a typed SalesforceRestClient) and bare
+ * local calls must still resolve. < 50 files → sequential path (pass_calls.c).
+ * RED before the fix: checkFormat->test exists via unique_name/suffix_match. */
+static void write_temp_file(const char *dir, const char *name, const char *content);
+
+typedef struct {
+ const char *source_name;
+ const char *target_name;
+} PreciseReferencePair;
+
+/* Count only edges of `edge_type` between the exact named source/target nodes.
+ * The parity and incremental guards deliberately use unique symbol names, so
+ * this canonicalizes across independent stores without depending on node IDs
+ * or project-prefixed qualified names. */
+static int named_edge_count(cbm_store_t *s, const char *project, const char *edge_type,
+ const char *source_name, const char *target_name) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(s, project, edge_type, &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ int source_ok = cbm_store_find_node_by_id(s, edges[i].source_id, &source) == CBM_STORE_OK;
+ int target_ok = cbm_store_find_node_by_id(s, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok && source.name && target.name &&
+ strcmp(source.name, source_name) == 0 && strcmp(target.name, target_name) == 0) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return matches;
+}
+
+/* Like named_edge_count, but distinguish same-named targets by their source
+ * file. Semantic-control fixtures intentionally keep the exported short name
+ * identical in two modules so a project-wide unique-name fallback cannot make
+ * an alias-mapping assertion pass accidentally. */
+static int named_edge_to_file_count(cbm_store_t *s, const char *project, const char *edge_type,
+ const char *source_name, const char *target_name,
+ const char *target_file_path) {
+ cbm_edge_t *edges = NULL;
+ int edge_count = 0;
+ if (cbm_store_find_edges_by_type(s, project, edge_type, &edges, &edge_count) != CBM_STORE_OK) {
+ return -1;
+ }
+
+ int matches = 0;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t source = {0};
+ cbm_node_t target = {0};
+ int source_ok = cbm_store_find_node_by_id(s, edges[i].source_id, &source) == CBM_STORE_OK;
+ int target_ok = cbm_store_find_node_by_id(s, edges[i].target_id, &target) == CBM_STORE_OK;
+ if (source_ok && target_ok && source.name && target.name && target.file_path &&
+ strcmp(source.name, source_name) == 0 && strcmp(target.name, target_name) == 0 &&
+ strcmp(target.file_path, target_file_path) == 0) {
+ matches++;
+ }
+ cbm_node_free_fields(&source);
+ cbm_node_free_fields(&target);
+ }
+ if (edges) {
+ cbm_store_free_edges(edges, edge_count);
+ }
+ return matches;
+}
+
+/* Count exact-name nodes without depending on project-prefixed qualified names.
+ * Export-XML relationship tests use this as an anti-vacuous guard: the
+ * transcoded methods must exist even when their extracted relationships were
+ * accidentally discarded. */
+static int named_node_count(cbm_store_t *s, const char *project, const char *name) {
+ cbm_node_t *nodes = NULL;
+ int count = 0;
+ if (cbm_store_find_nodes_by_name(s, project, name, &nodes, &count) != CBM_STORE_OK) {
+ return -1;
+ }
+ if (nodes) {
+ cbm_store_free_nodes(nodes, count);
+ }
+ return count;
+}
+
+typedef struct {
+ int run_rc;
+ bool store_opened;
+ int run_nodes;
+ int execute_nodes;
+ int run_execute_calls;
+ int shared_payload_nodes;
+ int run_shared_payload_usages;
+} ObjectScriptExportObservation;
+
+static ObjectScriptExportObservation observe_objectscript_export(const char *repo_path,
+ const char *db_name) {
+ ObjectScriptExportObservation observation = {
+ .run_rc = -1,
+ .store_opened = false,
+ .run_nodes = -1,
+ .execute_nodes = -1,
+ .run_execute_calls = -1,
+ .shared_payload_nodes = -1,
+ .run_shared_payload_usages = -1,
+ };
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", repo_path, db_name);
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(repo_path, db_path, CBM_MODE_FULL);
+ if (!pipeline) {
+ return observation;
+ }
+
+ observation.run_rc = cbm_pipeline_run(pipeline);
+ const char *project = cbm_pipeline_project_name(pipeline);
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ observation.store_opened = store != NULL;
+ if (store && project) {
+ observation.run_nodes = named_node_count(store, project, "Run");
+ observation.execute_nodes = named_node_count(store, project, "Execute");
+ observation.run_execute_calls = named_edge_count(store, project, "CALLS", "Run", "Execute");
+ observation.shared_payload_nodes = named_node_count(store, project, "SharedPayload");
+ observation.run_shared_payload_usages =
+ named_edge_count(store, project, "USAGE", "Run", "SharedPayload");
+ }
+ if (store) {
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(pipeline);
+ return observation;
+}
+
+/* Studio Export XML is transformed into ObjectScript UDL during extraction.
+ * The transformed definitions already survive, but the old sequential and
+ * fused-parallel special cases freed each transformed result after inserting
+ * only its definitions. Calls/usages therefore vanished even though direct
+ * extraction of the same generated UDL found them.
+ *
+ * One shared multi-class fixture is indexed through both execution paths. The
+ * 50 filler files only select the fused path; CBM_INDEX_SINGLE_THREAD forces
+ * the first run through the sequential path without duplicating setup.
+ * RED before the fix: Run and Execute each exist once, Run -> Execute is 0 in
+ * both stores. GREEN requires exactly one CALLS edge in each store. */
+TEST(pipeline_objectscript_export_preserves_calls_sequential_parallel) {
+ static const char export_xml[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<Export generator=\"Cache\" version=\"25\">\n"
+ "<Class name=\"Test.Worker\">\n"
+ "<Method name=\"Execute\">\n"
+ "<ClassMethod>1</ClassMethod>\n"
+ "<FormalSpec>pValue:%String</FormalSpec>\n"
+ "<ReturnType>%Status</ReturnType>\n"
+ "<Implementation><![CDATA[\n"
+ " Quit $$$OK\n"
+ "]]></Implementation>\n"
+ "</Method>\n"
+ "</Class>\n"
+ "<Class name=\"Test.Caller\">\n"
+ "<Method name=\"Run\">\n"
+ "<ClassMethod>1</ClassMethod>\n"
+ "<FormalSpec>pPayload:%String</FormalSpec>\n"
+ "<ReturnType>%Status</ReturnType>\n"
+ "<Implementation><![CDATA[\n"
+ " Do ##class(Test.Worker).Execute(pPayload)\n"
+ " Quit $$$OK\n"
+ "]]></Implementation>\n"
+ "</Method>\n"
+ "</Class>\n"
+ "</Export>\n";
+
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_export_rel_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ char export_path[512];
+ snprintf(export_path, sizeof(export_path), "%s/studio-export.xml", tmp);
+ if (th_write_file(export_path, export_xml) != 0) {
+ th_rmtree(tmp);
+ FAIL("failed to write Studio Export fixture");
+ }
+
+ /* Export XML plus 50 trackable fillers exceeds MIN_FILES_FOR_PARALLEL. */
+ for (int i = 0; i < 50; i++) {
+ char filename[64];
+ char path[512];
+ char source[128];
+ snprintf(filename, sizeof(filename), "export_pad_%02d.ts", i);
+ snprintf(path, sizeof(path), "%s/%s", tmp, filename);
+ snprintf(source, sizeof(source), "export function exportPad%02d(): number { return %d; }\n",
+ i, i);
+ if (th_write_file(path, source) != 0) {
+ th_rmtree(tmp);
+ FAIL("failed to write parallel-selection fixture");
+ }
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ ObjectScriptExportObservation sequential =
+ observe_objectscript_export(tmp, "export-sequential.db");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ ObjectScriptExportObservation parallel = observe_objectscript_export(tmp, "export-parallel.db");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential.run_rc, 0);
+ ASSERT_TRUE(sequential.store_opened);
+ ASSERT_EQ(sequential.run_nodes, 1);
+ ASSERT_EQ(sequential.execute_nodes, 1);
+
+ ASSERT_EQ(parallel.run_rc, 0);
+ ASSERT_TRUE(parallel.store_opened);
+ ASSERT_EQ(parallel.run_nodes, 1);
+ ASSERT_EQ(parallel.execute_nodes, 1);
+ if (sequential.run_execute_calls != 1 || parallel.run_execute_calls != 1) {
+ fprintf(stderr,
+ " [objectscript-export] invariant=transformed_calls_preserved "
+ "expected=1/1 actual=%d/%d\n",
+ sequential.run_execute_calls, parallel.run_execute_calls);
+ }
+ ASSERT_TRUE(sequential.run_execute_calls == 1 && parallel.run_execute_calls == 1);
+ PASS();
+}
+
+static int format_objectscript_export_lifecycle_fixture(char *xml, size_t xml_capacity,
+ const char *default_value) {
+ int written = snprintf(xml, xml_capacity,
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<Export generator=\"Cache\" version=\"25\">\n"
+ "<Class name=\"Test.Worker\">\n"
+ "<Method name=\"Execute\">\n"
+ "<ClassMethod>1</ClassMethod>\n"
+ "<FormalSpec>pValue:%%String</FormalSpec>\n"
+ "<ReturnType>%%Status</ReturnType>\n"
+ "<Implementation><![CDATA[\n"
+ " Quit $$$OK\n"
+ "]]></Implementation>\n"
+ "</Method>\n"
+ "</Class>\n"
+ "<Class name=\"Test.Caller\">\n"
+ "<Parameter name=\"SharedPayload\"><Default>%s</Default></Parameter>\n"
+ "<Method name=\"Run\">\n"
+ "<ClassMethod>1</ClassMethod>\n"
+ "<FormalSpec>watched:%%String</FormalSpec>\n"
+ "<ReturnType>%%Status</ReturnType>\n"
+ "<Implementation><![CDATA[\n"
+ " Do ##class(Test.Worker).Execute(watched)\n"
+ " Quit $$$OK\n"
+ "]]></Implementation>\n"
+ "</Method>\n"
+ "</Class>\n"
+ "</Export>\n",
+ default_value);
+ if (written <= 0 || (size_t)written >= xml_capacity) {
+ return -1;
+ }
+ return written;
+}
+
+static int write_objectscript_export_lifecycle_fixture(const char *path,
+ const char *default_value) {
+ char xml[4096];
+ int written = format_objectscript_export_lifecycle_fixture(xml, sizeof(xml), default_value);
+ if (written < 0) {
+ return -1;
+ }
+ return th_write_file(path, xml);
+}
+
+/* A changed Studio Export file must keep its transformed carriers alive for
+ * every incremental resolution pass. Compare the incrementally rebuilt graph
+ * with a clean full sequential build of the same replacement XML. Direct
+ * extraction separately proves that the transformed aggregate retains the
+ * method-argument USAGE carrier; formal parameters are not graph targets, so
+ * graph resolution of that carrier is outside this lifecycle regression.
+ * ObjectScript has no per-file or cross-file LSP dispatcher, so it cannot
+ * produce a resolved_calls semantic carrier to assert here.
+ *
+ * RED before the incremental cache lifecycle fix: definitions survived, but
+ * the changed Export was re-read as raw XML by later passes, so Run->Execute
+ * CALLS was absent from the incremental graph. */
+TEST(pipeline_objectscript_export_incremental_matches_full_relationships) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_export_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ char export_path[512];
+ snprintf(export_path, sizeof(export_path), "%s/studio-export.xml", tmp);
+ if (write_objectscript_export_lifecycle_fixture(export_path, "initial") != 0) {
+ th_rmtree(tmp);
+ FAIL("failed to write initial Studio Export fixture");
+ }
+
+ char carrier_xml[4096];
+ int carrier_xml_len =
+ format_objectscript_export_lifecycle_fixture(carrier_xml, sizeof(carrier_xml), "initial");
+ if (carrier_xml_len < 0) {
+ th_rmtree(tmp);
+ FAIL("failed to format Studio Export carrier fixture");
+ }
+ cbm_init();
+ CBMFileResult *carrier_result = cbm_pipeline_extract_objectscript_export(
+ carrier_xml, carrier_xml_len, "export-lifecycle", "studio-export.xml", NULL, NULL);
+ if (!carrier_result) {
+ th_rmtree(tmp);
+ FAIL("failed to extract Studio Export carrier fixture");
+ }
+ bool found_argument_usage = false;
+ for (int i = 0; i < carrier_result->usages.count; i++) {
+ const CBMUsage *usage = &carrier_result->usages.items[i];
+ if (usage->ref_name && strcmp(usage->ref_name, "watched") == 0 &&
+ usage->enclosing_func_qn && strstr(usage->enclosing_func_qn, ".Run")) {
+ found_argument_usage = true;
+ break;
+ }
+ }
+ cbm_free_result(carrier_result);
+ if (!found_argument_usage) {
+ th_rmtree(tmp);
+ FAIL("Studio Export aggregate lost method-argument USAGE carrier");
+ }
+
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+
+ ObjectScriptExportObservation initial =
+ observe_objectscript_export(tmp, "export-incremental.db");
+
+ if (write_objectscript_export_lifecycle_fixture(export_path,
+ "replacement-with-a-different-size") != 0) {
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+ FAIL("failed to write replacement Studio Export fixture");
+ }
+
+ /* Same DB routes through incremental; a fresh DB is the full reference. */
+ ObjectScriptExportObservation incremental =
+ observe_objectscript_export(tmp, "export-incremental.db");
+ ObjectScriptExportObservation full =
+ observe_objectscript_export(tmp, "export-full-reference.db");
+
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(initial.run_rc, 0);
+ ASSERT_TRUE(initial.store_opened);
+ ASSERT_EQ(initial.run_execute_calls, 1);
+
+ ASSERT_EQ(incremental.run_rc, 0);
+ ASSERT_TRUE(incremental.store_opened);
+ ASSERT_EQ(full.run_rc, 0);
+ ASSERT_TRUE(full.store_opened);
+ ASSERT_EQ(incremental.run_nodes, full.run_nodes);
+ ASSERT_EQ(incremental.execute_nodes, full.execute_nodes);
+ ASSERT_EQ(incremental.shared_payload_nodes, full.shared_payload_nodes);
+ ASSERT_EQ(incremental.run_execute_calls, full.run_execute_calls);
+ ASSERT_EQ(incremental.run_shared_payload_usages, full.run_shared_payload_usages);
+ ASSERT_EQ(full.run_nodes, 1);
+ ASSERT_EQ(full.execute_nodes, 1);
+ ASSERT_EQ(full.shared_payload_nodes, 1);
+ ASSERT_EQ(full.run_execute_calls, 1);
+ PASS();
+}
+
+static bool test_buffer_appendf(char *buffer, size_t capacity, size_t *used, const char *format,
+ ...) {
+ if (!buffer || !used || *used >= capacity) {
+ return false;
+ }
+ va_list args;
+ va_start(args, format);
+ int written = vsnprintf(buffer + *used, capacity - *used, format, args);
+ va_end(args);
+ if (written < 0 || (size_t)written >= capacity - *used) {
+ return false;
+ }
+ *used += (size_t)written;
+ return true;
+}
+
+/* Each extracted class owns a separate arena. A CBMCall includes eight argument
+ * slots, so growing its call array through the 513th item requires at least four
+ * arena blocks per class. Sixty-four classes therefore exceed the aggregate's
+ * fixed 256-block adoption table even before aggregate-array growth is counted,
+ * while staying within the Studio Export transcoder's existing 64-class cap.
+ *
+ * RED with fixed-block ownership transfer: aggregation returns NULL before all
+ * 64 classes can be composed. GREEN requires one result containing every class,
+ * method, and call carrier without raising the class limit. */
+TEST(pipeline_objectscript_export_aggregate_exceeds_arena_block_table) {
+ enum {
+ STRESS_CLASS_COUNT = 64,
+ STRESS_CALLS_PER_CLASS = 513,
+ STRESS_XML_CAPACITY = 4 * 1024 * 1024,
+ };
+ char *xml = (char *)malloc(STRESS_XML_CAPACITY);
+ if (!xml) {
+ FAIL("stress XML allocation");
+ }
+ size_t used = 0;
+ bool complete = test_buffer_appendf(xml, STRESS_XML_CAPACITY, &used,
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<Export generator=\"Cache\" version=\"25\">\n");
+ for (int ci = 0; ci < STRESS_CLASS_COUNT && complete; ci++) {
+ complete = test_buffer_appendf(xml, STRESS_XML_CAPACITY, &used,
+ "<Class name=\"Arena.Stress%02d\">\n"
+ "<Method name=\"Run%02d\">\n"
+ "<ClassMethod>1</ClassMethod>\n"
+ "<Implementation><![CDATA[\n",
+ ci, ci);
+ for (int call = 0; call < STRESS_CALLS_PER_CLASS && complete; call++) {
+ complete = test_buffer_appendf(xml, STRESS_XML_CAPACITY, &used,
+ " Do ##class(Arena.Target).Execute()\n");
+ }
+ complete = complete && test_buffer_appendf(xml, STRESS_XML_CAPACITY, &used,
+ " Quit\n"
+ "]]></Implementation>\n"
+ "</Method>\n"
+ "</Class>\n");
+ }
+ complete = complete && test_buffer_appendf(xml, STRESS_XML_CAPACITY, &used, "</Export>\n");
+ if (!complete) {
+ free(xml);
+ FAIL("stress XML capacity");
+ }
+
+ cbm_init();
+ CBMFileResult *aggregate = cbm_pipeline_extract_objectscript_export(
+ xml, (int)used, "arena-stress", "studio-export.xml", NULL, NULL);
+ free(xml);
+ ASSERT_NOT_NULL(aggregate);
+
+ bool found_last_method = false;
+ for (int i = 0; i < aggregate->defs.count; i++) {
+ const CBMDefinition *def = &aggregate->defs.items[i];
+ if (def->name && strcmp(def->name, "Run63") == 0) {
+ found_last_method = true;
+ break;
+ }
+ }
+ int expected_calls = STRESS_CLASS_COUNT * STRESS_CALLS_PER_CLASS;
+ int actual_calls = aggregate->calls.count;
+ int actual_defs = aggregate->defs.count;
+ cbm_free_result(aggregate);
+
+ ASSERT_TRUE(found_last_method);
+ ASSERT_EQ(actual_calls, expected_calls);
+ ASSERT_GTE(actual_defs, STRESS_CLASS_COUNT * 2);
+ PASS();
+}
+
+typedef struct {
+ int run_rc;
+ bool store_opened;
+ int source_nodes;
+ int target_nodes;
+ int edge_count;
+} NamedEdgeObservation;
+
+static NamedEdgeObservation observe_named_edge(const char *repo_path, const char *db_name,
+ const char *edge_type, const char *source_name,
+ const char *target_name) {
+ NamedEdgeObservation observation = {
+ .run_rc = -1,
+ .store_opened = false,
+ .source_nodes = -1,
+ .target_nodes = -1,
+ .edge_count = -1,
+ };
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/%s", repo_path, db_name);
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(repo_path, db_path, CBM_MODE_FULL);
+ if (!pipeline) {
+ return observation;
+ }
+ observation.run_rc = cbm_pipeline_run(pipeline);
+ const char *project = cbm_pipeline_project_name(pipeline);
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ observation.store_opened = store != NULL;
+ if (store && project) {
+ observation.source_nodes = named_node_count(store, project, source_name);
+ observation.target_nodes = named_node_count(store, project, target_name);
+ observation.edge_count =
+ named_edge_count(store, project, edge_type, source_name, target_name);
+ }
+ if (store) {
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(pipeline);
+ return observation;
+}
+
+/* env_accesses are extracted independently from calls and must materialize the
+ * same EnvVar + CONFIGURES relationship in both pipeline implementations.
+ *
+ * RED before the fused-path consumer is added: sequential definition insertion
+ * creates envParityRead -> CBM_PARITY_TOKEN, while cbm_build_registry_from_cache
+ * ignores result->env_accesses and the parallel graph contains neither target
+ * nor edge. */
+TEST(pipeline_env_access_configures_sequential_parallel_parity) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_env_parity_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+ char source_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/env.go", tmp);
+ if (th_write_file(source_path, "package envparity\n\n"
+ "import \"os\"\n\n"
+ "func envParityRead() string {\n"
+ " return os.Getenv(\"CBM_PARITY_TOKEN\")\n"
+ "}\n") != 0) {
+ th_rmtree(tmp);
+ FAIL("failed to write env-access fixture");
+ }
+ for (int i = 0; i < 50; i++) {
+ char filename[64];
+ char path[512];
+ char source[128];
+ snprintf(filename, sizeof(filename), "env_pad_%02d.ts", i);
+ snprintf(path, sizeof(path), "%s/%s", tmp, filename);
+ snprintf(source, sizeof(source), "export function envPad%02d(): number { return %d; }\n", i,
+ i);
+ if (th_write_file(path, source) != 0) {
+ th_rmtree(tmp);
+ FAIL("failed to write env parity filler");
+ }
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ NamedEdgeObservation sequential = observe_named_edge(tmp, "env-sequential.db", "CONFIGURES",
+ "envParityRead", "CBM_PARITY_TOKEN");
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ NamedEdgeObservation parallel = observe_named_edge(tmp, "env-parallel.db", "CONFIGURES",
+ "envParityRead", "CBM_PARITY_TOKEN");
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential.run_rc, 0);
+ ASSERT_TRUE(sequential.store_opened);
+ ASSERT_EQ(sequential.source_nodes, 1);
+ ASSERT_EQ(sequential.target_nodes, 1);
+ ASSERT_EQ(sequential.edge_count, 1);
+
+ ASSERT_EQ(parallel.run_rc, 0);
+ ASSERT_TRUE(parallel.store_opened);
+ ASSERT_EQ(parallel.source_nodes, sequential.source_nodes);
+ ASSERT_EQ(parallel.target_nodes, sequential.target_nodes);
+ ASSERT_EQ(parallel.edge_count, sequential.edge_count);
+ PASS();
+}
+
+/* Sequential and fused-parallel resolution must materialize the same precise
+ * CALL_REFERENCE edge set. The table covers each independently implemented
+ * resolver family involved in callable-value/reference semantics; sibling
+ * frontends share those resolvers (JS/TSX -> TS, C++/CUDA -> C).
+ *
+ * Every pair uses a globally unique source and target name. That lets the test
+ * compare the semantic edge multiset across stores while ignoring unstable DB
+ * IDs and project-name prefixes. The fixture exceeds MIN_FILES_FOR_PARALLEL;
+ * CBM_INDEX_SINGLE_THREAD forces the first run through the sequential path and
+ * CBM_WORKERS forces the second through pass_parallel.c. */
+TEST(pipeline_call_reference_sequential_parallel_edge_set_parity) {
+ static const PreciseReferencePair pairs[] = {
+ {"goReferenceSite", "goReferenceTarget"},
+ {"pythonReferenceSite", "pythonReferenceTarget"},
+ {"cReferenceSite", "cReferenceTarget"},
+ {"rustReferenceSite", "rustReferenceTarget"},
+ {"csharpReferenceSite", "csharpReferenceTarget"},
+ {"javascriptReferenceSite", "javascriptReferenceTarget"},
+ {"typescriptReferenceSite", "typescriptReferenceTarget"},
+ {"tsxReferenceSite", "tsxReferenceTarget"},
+ {"cppReferenceSite", "cppReferenceTarget"},
+ {"cudaReferenceSite", "cudaReferenceTarget"},
+ {"javaReferenceSite", "javaReferenceTarget"},
+ {"kotlinReferenceSite", "kotlinReferenceTarget"},
+ {"phpReferenceSite", "phpReferenceTarget"},
+ {"perlReferenceSite", "perlReferenceTarget"},
+ };
+ enum { pair_count = (int)(sizeof(pairs) / sizeof(pairs[0])) };
+ static const PreciseReferencePair shadow_pairs[] = {
+ {"pythonShadowSite", "pythonShadowTarget"},
+ {"javascriptShadowSite", "javascriptShadowTarget"},
+ {"typescriptShadowSite", "typescriptShadowTarget"},
+ };
+ static const PreciseReferencePair shadow_controls[] = {
+ {"pythonShadowSite", "pythonShadowAccept"},
+ {"javascriptShadowSite", "javascriptShadowAccept"},
+ {"typescriptShadowSite", "typescriptShadowAccept"},
+ };
+ enum { shadow_count = (int)(sizeof(shadow_pairs) / sizeof(shadow_pairs[0])) };
+
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_parity_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "parity.go",
+ "package parity\n"
+ "func goReferenceTarget() {}\n"
+ "func goReferenceAccept(callback func()) {}\n"
+ "func goReferenceSite() { goReferenceAccept(goReferenceTarget) }\n");
+ write_temp_file(tmp, "python_target.py",
+ "def pythonReferenceTarget():\n"
+ " pass\n");
+ write_temp_file(tmp, "parity.py",
+ "from python_target import pythonReferenceTarget as pythonReferenceAlias\n"
+ "def pythonReferenceAccept(callback):\n"
+ " pass\n"
+ "def pythonReferenceSite():\n"
+ " pythonReferenceAccept(pythonReferenceAlias)\n");
+ write_temp_file(tmp, "parity.c",
+ "typedef void (*c_reference_callback_t)(void);\n"
+ "void cReferenceTarget(void) {}\n"
+ "void cReferenceAccept(c_reference_callback_t callback) {}\n"
+ "void cReferenceSite(void) { cReferenceAccept(cReferenceTarget); }\n");
+ write_temp_file(tmp, "parity.rs",
+ "fn rustReferenceTarget() {}\n"
+ "fn rustReferenceAccept(_callback: fn()) {}\n"
+ "fn rustReferenceSite() { rustReferenceAccept(rustReferenceTarget); }\n");
+ write_temp_file(tmp, "Parity.cs",
+ "using System;\n"
+ "class CSharpParity {\n"
+ " static void csharpReferenceTarget() {}\n"
+ " static void csharpReferenceAccept(Action callback) {}\n"
+ " static void csharpReferenceSite() { "
+ "csharpReferenceAccept(csharpReferenceTarget); }\n"
+ "}\n");
+ write_temp_file(tmp, "parity.js",
+ "function javascriptReferenceTarget() {}\n"
+ "function javascriptReferenceAccept(callback) {}\n"
+ "function javascriptReferenceSite() {\n"
+ " javascriptReferenceAccept(javascriptReferenceTarget);\n"
+ "}\n");
+ write_temp_file(tmp, "parity.ts",
+ "class TypeScriptParity { typescriptReferenceTarget(): void {} }\n"
+ "function typescriptReferenceAccept(callback: () => void): void {}\n"
+ "function typescriptReferenceSite(service: TypeScriptParity): void {\n"
+ " typescriptReferenceAccept(service.typescriptReferenceTarget);\n"
+ "}\n");
+ write_temp_file(tmp, "parity.tsx",
+ "function tsxReferenceTarget(): void {}\n"
+ "function tsxReferenceAccept(callback: () => void): void {}\n"
+ "function tsxReferenceSite(): void {\n"
+ " tsxReferenceAccept(tsxReferenceTarget);\n"
+ "}\n");
+ write_temp_file(tmp, "parity.cpp",
+ "using cpp_reference_callback_t = void (*)();\n"
+ "void cppReferenceTarget() {}\n"
+ "void cppReferenceAccept(cpp_reference_callback_t callback) {}\n"
+ "void cppReferenceSite() { cppReferenceAccept(cppReferenceTarget); }\n");
+ write_temp_file(tmp, "parity.cu",
+ "typedef void (*cuda_reference_callback_t)(void);\n"
+ "__device__ void cudaReferenceTarget(void) {}\n"
+ "__device__ void cudaReferenceAccept(cuda_reference_callback_t callback) {}\n"
+ "__device__ void cudaReferenceSite(void) {\n"
+ " cudaReferenceAccept(cudaReferenceTarget);\n"
+ "}\n");
+ write_temp_file(tmp, "JavaParity.java",
+ "interface JavaParityTask { void run(); }\n"
+ "class JavaParity {\n"
+ " static void javaReferenceTarget() {}\n"
+ " static void javaReferenceAccept(JavaParityTask callback) {}\n"
+ " static void javaReferenceSite() { "
+ "javaReferenceAccept(JavaParity::javaReferenceTarget); }\n"
+ "}\n");
+ write_temp_file(tmp, "parity.kt",
+ "fun kotlinReferenceTarget(): Unit {}\n"
+ "fun kotlinReferenceAccept(callback: () -> Unit): Unit {}\n"
+ "fun kotlinReferenceSite(): Unit { "
+ "kotlinReferenceAccept(::kotlinReferenceTarget) }\n");
+ write_temp_file(tmp, "parity.php",
+ "<?php\n"
+ "function phpReferenceTarget(): void {}\n"
+ "function phpReferenceAccept(callable $callback): void {}\n"
+ "function phpReferenceSite(): void { "
+ "phpReferenceAccept(phpReferenceTarget(...)); }\n");
+ write_temp_file(tmp, "parity.pl",
+ "sub perlReferenceTarget {}\n"
+ "sub perlReferenceAccept { my ($callback) = @_; }\n"
+ "sub perlReferenceSite { "
+ "perlReferenceAccept(\\&perlReferenceTarget); }\n");
+
+ write_temp_file(tmp, "shadow.py",
+ "def pythonShadowTarget():\n"
+ " pass\n"
+ "def pythonShadowAccept(callback):\n"
+ " pass\n"
+ "def pythonShadowSite():\n"
+ " pythonShadowAccept(pythonShadowTarget)\n"
+ " pythonShadowTarget = lambda: None\n");
+ write_temp_file(tmp, "shadow.js",
+ "function javascriptShadowTarget() {}\n"
+ "function javascriptShadowAccept(callback) {}\n"
+ "function javascriptShadowSite() {\n"
+ " javascriptShadowAccept(javascriptShadowTarget);\n"
+ " const javascriptShadowTarget = () => {};\n"
+ "}\n");
+ write_temp_file(tmp, "shadow.ts",
+ "function typescriptShadowTarget(): void {}\n"
+ "function typescriptShadowAccept(callback: () => void): void {}\n"
+ "function typescriptShadowSite(): void {\n"
+ " typescriptShadowAccept(typescriptShadowTarget);\n"
+ " const typescriptShadowTarget = (): void => {};\n"
+ "}\n");
+
+ /* Fourteen positive and three shadow fixtures plus 34 source fillers exceed
+ * the 50-file fused threshold without making the test larger than needed. */
+ for (int i = 0; i < 34; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "parity_pad_%02d.ts", i);
+ snprintf(body, sizeof(body), "export function parityPad%02d(): number { return %d; }\n", i,
+ i);
+ write_temp_file(tmp, name, body);
+ }
+
+ int sequential_reference[pair_count];
+ int sequential_usage[pair_count];
+ int sequential_calls[pair_count];
+ int parallel_reference[pair_count];
+ int parallel_usage[pair_count];
+ int parallel_calls[pair_count];
+ int sequential_shadow_leaks[shadow_count];
+ int parallel_shadow_leaks[shadow_count];
+ int sequential_shadow_controls[shadow_count];
+ int parallel_shadow_controls[shadow_count];
+ for (int i = 0; i < pair_count; i++) {
+ sequential_reference[i] = sequential_usage[i] = sequential_calls[i] = -1;
+ parallel_reference[i] = parallel_usage[i] = parallel_calls[i] = -1;
+ }
+ for (int i = 0; i < shadow_count; i++) {
+ sequential_shadow_leaks[i] = parallel_shadow_leaks[i] = -1;
+ sequential_shadow_controls[i] = parallel_shadow_controls[i] = -1;
+ }
+ int sequential_total = -1;
+ int parallel_total = -1;
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ char sequential_db_path[512];
+ snprintf(sequential_db_path, sizeof(sequential_db_path), "%s/reference_sequential.db", tmp);
+ cbm_pipeline_t *sequential = cbm_pipeline_new(tmp, sequential_db_path, CBM_MODE_FULL);
+ int sequential_run_rc = sequential ? cbm_pipeline_run(sequential) : -1;
+ const char *sequential_project = sequential ? cbm_pipeline_project_name(sequential) : NULL;
+ cbm_store_t *sequential_store = cbm_store_open_path(sequential_db_path);
+ bool sequential_store_opened = sequential_store != NULL;
+ if (sequential_store && sequential_project) {
+ sequential_total =
+ cbm_store_count_edges_by_type(sequential_store, sequential_project, "CALL_REFERENCE");
+ for (int i = 0; i < pair_count; i++) {
+ sequential_reference[i] =
+ named_edge_count(sequential_store, sequential_project, "CALL_REFERENCE",
+ pairs[i].source_name, pairs[i].target_name);
+ sequential_usage[i] = named_edge_count(sequential_store, sequential_project, "USAGE",
+ pairs[i].source_name, pairs[i].target_name);
+ sequential_calls[i] = named_edge_count(sequential_store, sequential_project, "CALLS",
+ pairs[i].source_name, pairs[i].target_name);
+ }
+ for (int i = 0; i < shadow_count; i++) {
+ sequential_shadow_leaks[i] =
+ named_edge_count(sequential_store, sequential_project, "CALL_REFERENCE",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name) +
+ named_edge_count(sequential_store, sequential_project, "USAGE",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name) +
+ named_edge_count(sequential_store, sequential_project, "CALLS",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name);
+ sequential_shadow_controls[i] =
+ named_edge_count(sequential_store, sequential_project, "CALLS",
+ shadow_controls[i].source_name, shadow_controls[i].target_name);
+ }
+ cbm_store_close(sequential_store);
+ }
+ cbm_pipeline_free(sequential);
+
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+ char parallel_db_path[512];
+ snprintf(parallel_db_path, sizeof(parallel_db_path), "%s/reference_parallel.db", tmp);
+ cbm_pipeline_t *parallel = cbm_pipeline_new(tmp, parallel_db_path, CBM_MODE_FULL);
+ int parallel_run_rc = parallel ? cbm_pipeline_run(parallel) : -1;
+ const char *parallel_project = parallel ? cbm_pipeline_project_name(parallel) : NULL;
+ cbm_store_t *parallel_store = cbm_store_open_path(parallel_db_path);
+ bool parallel_store_opened = parallel_store != NULL;
+ if (parallel_store && parallel_project) {
+ parallel_total =
+ cbm_store_count_edges_by_type(parallel_store, parallel_project, "CALL_REFERENCE");
+ for (int i = 0; i < pair_count; i++) {
+ parallel_reference[i] =
+ named_edge_count(parallel_store, parallel_project, "CALL_REFERENCE",
+ pairs[i].source_name, pairs[i].target_name);
+ parallel_usage[i] = named_edge_count(parallel_store, parallel_project, "USAGE",
+ pairs[i].source_name, pairs[i].target_name);
+ parallel_calls[i] = named_edge_count(parallel_store, parallel_project, "CALLS",
+ pairs[i].source_name, pairs[i].target_name);
+ }
+ for (int i = 0; i < shadow_count; i++) {
+ parallel_shadow_leaks[i] =
+ named_edge_count(parallel_store, parallel_project, "CALL_REFERENCE",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name) +
+ named_edge_count(parallel_store, parallel_project, "USAGE",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name) +
+ named_edge_count(parallel_store, parallel_project, "CALLS",
+ shadow_pairs[i].source_name, shadow_pairs[i].target_name);
+ parallel_shadow_controls[i] =
+ named_edge_count(parallel_store, parallel_project, "CALLS",
+ shadow_controls[i].source_name, shadow_controls[i].target_name);
+ }
+ cbm_store_close(parallel_store);
+ }
+ cbm_pipeline_free(parallel);
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(sequential_run_rc, 0);
+ ASSERT_TRUE(sequential_store_opened);
+ ASSERT_EQ(parallel_run_rc, 0);
+ ASSERT_TRUE(parallel_store_opened);
+ ASSERT_EQ(parallel_total, sequential_total);
+ int expected_total = 0;
+ for (int i = 0; i < pair_count; i++) {
+ ASSERT_GT(sequential_reference[i], 0);
+ ASSERT_EQ(parallel_reference[i], sequential_reference[i]);
+ ASSERT_EQ(sequential_usage[i], 0);
+ ASSERT_EQ(parallel_usage[i], 0);
+ ASSERT_EQ(sequential_calls[i], 0);
+ ASSERT_EQ(parallel_calls[i], 0);
+ expected_total += sequential_reference[i];
+ }
+ for (int i = 0; i < shadow_count; i++) {
+ ASSERT_EQ(sequential_shadow_controls[i], 1);
+ ASSERT_EQ(parallel_shadow_controls[i], 1);
+ ASSERT_EQ(sequential_shadow_leaks[i], 0);
+ ASSERT_EQ(parallel_shadow_leaks[i], 0);
+ }
+ ASSERT_EQ(sequential_total, expected_total);
+ PASS();
+}
+
+static int pipeline_test_set_mtime(const char *path, time_t seconds, long nanoseconds) {
+ struct timespec times[2] = {{.tv_sec = seconds, .tv_nsec = nanoseconds},
+ {.tv_sec = seconds, .tv_nsec = nanoseconds}};
+ return utimensat(AT_FDCWD, path, times, 0);
+}
+
+/* Reindexing a changed callable-value occurrence must replace its exact target,
+ * not preserve the old CALL_REFERENCE alongside the new one or regress the new
+ * occurrence to USAGE/CALLS. Equal-length source generations use the exact same
+ * mtime so metadata heuristics cannot make the test pass: byte hashes must route
+ * the semantic change to a full rebuild. A metadata-only mtime change is a true
+ * no-op and must not rebuild. */
+TEST(pipeline_incremental_repoints_call_reference_without_stale_edge) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char initial_source[] = "package refs\n"
+ "func alphaReferenceTarget() {}\n"
+ "func bravoReferenceTarget() {}\n"
+ "func incrementalReferenceAccept(callback func()) {}\n"
+ "func incrementalReferenceSite() { "
+ "incrementalReferenceAccept(alphaReferenceTarget) }\n";
+ static const char replacement_source[] = "package refs\n"
+ "func alphaReferenceTarget() {}\n"
+ "func bravoReferenceTarget() {}\n"
+ "func incrementalReferenceAccept(callback func()) {}\n"
+ "func incrementalReferenceSite() { "
+ "incrementalReferenceAccept(bravoReferenceTarget) }\n";
+ ASSERT_EQ(sizeof(initial_source), sizeof(replacement_source));
+ write_temp_file(tmp, "refs.go", initial_source);
+ char source_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/refs.go", tmp);
+ const time_t fixed_mtime = 1700000000;
+ ASSERT_EQ(pipeline_test_set_mtime(source_path, fixed_mtime, 123456789L), 0);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/reference_incremental.db", tmp);
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(first);
+ ASSERT_EQ(cbm_pipeline_run(first), 0);
+ const char *first_project = cbm_pipeline_project_name(first);
+ cbm_store_t *first_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(first_store);
+ ASSERT_EQ(named_edge_count(first_store, first_project, "CALL_REFERENCE",
+ "incrementalReferenceSite", "alphaReferenceTarget"),
+ 1);
+ ASSERT_EQ(named_edge_count(first_store, first_project, "CALL_REFERENCE",
+ "incrementalReferenceSite", "bravoReferenceTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(first_store, first_project, "USAGE", "incrementalReferenceSite",
+ "alphaReferenceTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(first_store, first_project, "CALLS", "incrementalReferenceSite",
+ "alphaReferenceTarget"),
+ 0);
+ cbm_file_hash_t stored_hash = {0};
+ ASSERT_EQ(cbm_store_get_file_hash(first_store, first_project, "refs.go", &stored_hash),
+ CBM_STORE_OK);
+ char expected_hash[CBM_SHA256_HEX_LEN + 1];
+ cbm_sha256_hex(initial_source, strlen(initial_source), expected_hash);
+ ASSERT_NOT_NULL(stored_hash.sha256);
+ ASSERT_STR_EQ(stored_hash.sha256, expected_hash);
+ cbm_store_clear_file_hash(&stored_hash);
+ cbm_coverage_meta_t baseline_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(first_store, first_project, &baseline_meta),
+ CBM_STORE_OK);
+ ASSERT_EQ(baseline_meta.coverage_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(baseline_meta.hash_records_complete);
+ cbm_store_coverage_meta_clear(&baseline_meta);
+ cbm_store_close(first_store);
+ cbm_pipeline_free(first);
+
+ /* Same bytes, metadata only: exact manifest equality is a no-op. */
+ ASSERT_EQ(pipeline_test_set_mtime(source_path, fixed_mtime + 1, 123456789L), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *metadata_only = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(metadata_only);
+ ASSERT_EQ(cbm_pipeline_run(metadata_only), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_NOOP);
+ cbm_pipeline_free(metadata_only);
+
+ write_temp_file(tmp, "refs.go", replacement_source);
+ ASSERT_EQ(pipeline_test_set_mtime(source_path, fixed_mtime, 123456789L), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(second);
+ ASSERT_EQ(cbm_pipeline_run(second), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ const char *second_project = cbm_pipeline_project_name(second);
+ cbm_store_t *second_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(second_store);
+ ASSERT_EQ(named_edge_count(second_store, second_project, "CALL_REFERENCE",
+ "incrementalReferenceSite", "alphaReferenceTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(second_store, second_project, "CALL_REFERENCE",
+ "incrementalReferenceSite", "bravoReferenceTarget"),
+ 1);
+ ASSERT_EQ(named_edge_count(second_store, second_project, "USAGE", "incrementalReferenceSite",
+ "bravoReferenceTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(second_store, second_project, "CALLS", "incrementalReferenceSite",
+ "bravoReferenceTarget"),
+ 0);
+ cbm_store_close(second_store);
+ cbm_pipeline_free(second);
+ th_rmtree(tmp);
+ PASS();
+}
+
+/* Re-indexing only the caller must retain cross-file semantic proof for a
+ * callable value whose definition lives in an unchanged file. A fresh full
+ * index of the edited sources is the convergence oracle: incremental output
+ * must not downgrade the exact CALL_REFERENCE to a generic USAGE. */
+TEST(pipeline_incremental_cross_file_call_reference_matches_fresh_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_cross_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char target_source[] = "export function importedIncrementalHandler(): void {}\n";
+ static const char initial_caller_source[] =
+ "import { importedIncrementalHandler } from './plugin';\n"
+ "function acceptIncrementalReference(callback: () => void): void {}\n"
+ "export function incrementalImportedArgument(): void {\n"
+ " acceptIncrementalReference(importedIncrementalHandler);\n"
+ "}\n";
+ static const char edited_caller_source[] =
+ "import { importedIncrementalHandler } from './plugin';\n"
+ "function acceptIncrementalReference(callback: () => void): void {}\n"
+ "export function incrementalImportedArgument(): void {\n"
+ " acceptIncrementalReference(importedIncrementalHandler);\n"
+ "}\n"
+ "// caller-only size-changing edit\n";
+
+ write_temp_file(tmp, "plugin.ts", target_source);
+ write_temp_file(tmp, "main.ts", initial_caller_source);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/cross-reference-incremental.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ const char *baseline_project = cbm_pipeline_project_name(baseline);
+ cbm_store_t *baseline_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(baseline_store);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 1);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler"),
+ 0);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "main.ts", edited_caller_source);
+
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ ASSERT_EQ(cbm_pipeline_run(incremental), 0);
+ const char *incremental_project = cbm_pipeline_project_name(incremental);
+ cbm_store_t *incremental_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(incremental_store);
+ int incremental_reference =
+ named_edge_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int incremental_usage =
+ named_edge_count(incremental_store, incremental_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int incremental_calls =
+ named_edge_count(incremental_store, incremental_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/cross-reference-full.db", tmp);
+ cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(full);
+ ASSERT_EQ(cbm_pipeline_run(full), 0);
+ const char *full_project = cbm_pipeline_project_name(full);
+ cbm_store_t *full_store = cbm_store_open_path(full_db);
+ ASSERT_NOT_NULL(full_store);
+ int full_reference =
+ named_edge_count(full_store, full_project, "CALL_REFERENCE", "incrementalImportedArgument",
+ "importedIncrementalHandler");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS",
+ "incrementalImportedArgument", "importedIncrementalHandler");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_reference, 1);
+ ASSERT_EQ(full_usage, 0);
+ ASSERT_EQ(full_calls, 0);
+ ASSERT_EQ(incremental_reference, full_reference);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+}
+
+/* A semantic control file can change an unchanged source file's exact target.
+ * Both target modules deliberately export the same short name: without the
+ * tsconfig path mapping, project-wide unique-name fallback is ambiguous and
+ * cannot make this test pass. The clean full index after the config-only edit
+ * is therefore an exact oracle for which module owns the CALL_REFERENCE.
+ *
+ * RED: incremental hashing tracks source inputs but not the semantic influence
+ * of tsconfig.json. Changing only the alias mapping leaves the same-DB graph
+ * pointed at target_a.ts while a fresh full index points at target_b.ts. */
+TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_tsconfig_incr_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char target_a_source[] = "export function semanticControlHandler(): void {\n"
+ " const selected = 'a';\n"
+ " void selected;\n"
+ "}\n";
+ static const char target_b_source[] = "export function semanticControlHandler(): void {\n"
+ " const selected = 'b';\n"
+ " void selected;\n"
+ "}\n";
+ static const char caller_source[] =
+ "import { semanticControlHandler } from '@semantic-target';\n"
+ "function acceptSemanticControl(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function semanticControlCaller(): void {\n"
+ " acceptSemanticControl(semanticControlHandler);\n"
+ "}\n";
+ static const char initial_tsconfig[] =
+ "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@semantic-target\": [\"./target_a\"]}\n"
+ " }\n"
+ "}\n";
+ static const char replacement_tsconfig[] =
+ "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@semantic-target\": [\"./target_b\"]}\n"
+ " }\n"
+ "}\n";
+ static const char initial_jsconfig[] = "{\"compilerOptions\":{\"baseUrl\":\"./one\"}}\n";
+ static const char replacement_jsconfig[] = "{\"compilerOptions\":{\"baseUrl\":\"./two\"}}\n";
+ ASSERT_EQ(sizeof(initial_tsconfig), sizeof(replacement_tsconfig));
+ ASSERT_EQ(sizeof(initial_jsconfig), sizeof(replacement_jsconfig));
+
+ write_temp_file(tmp, "target_a.ts", target_a_source);
+ write_temp_file(tmp, "target_b.ts", target_b_source);
+ write_temp_file(tmp, "caller.ts", caller_source);
+ write_temp_file(tmp, "tsconfig.json", initial_tsconfig);
+ write_temp_file(tmp, "jsconfig.json", initial_jsconfig);
+ char tsconfig_path[512];
+ char jsconfig_path[512];
+ snprintf(tsconfig_path, sizeof(tsconfig_path), "%s/tsconfig.json", tmp);
+ snprintf(jsconfig_path, sizeof(jsconfig_path), "%s/jsconfig.json", tmp);
+ const time_t fixed_config_mtime = 1700000100;
+ ASSERT_EQ(pipeline_test_set_mtime(tsconfig_path, fixed_config_mtime, 222222222L), 0);
+ ASSERT_EQ(pipeline_test_set_mtime(jsconfig_path, fixed_config_mtime, 333333333L), 0);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/tsconfig-reference-incremental.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ const char *baseline_project = cbm_pipeline_project_name(baseline);
+ cbm_store_t *baseline_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(baseline_store);
+ ASSERT_EQ(named_node_count(baseline_store, baseline_project, "semanticControlHandler"), 2);
+ ASSERT_EQ(named_edge_to_file_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler",
+ "target_a.ts"),
+ 1);
+ ASSERT_EQ(named_edge_to_file_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler",
+ "target_b.ts"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE", "semanticControlCaller",
+ "semanticControlHandler"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS", "semanticControlCaller",
+ "semanticControlHandler"),
+ 0);
+ cbm_file_hash_t selected_config_hash = {0};
+ ASSERT_EQ(cbm_store_get_file_hash(baseline_store, baseline_project, "tsconfig.json",
+ &selected_config_hash),
+ CBM_STORE_OK);
+ char expected_config_hash[CBM_SHA256_HEX_LEN + 1];
+ cbm_sha256_hex(initial_tsconfig, strlen(initial_tsconfig), expected_config_hash);
+ ASSERT_NOT_NULL(selected_config_hash.sha256);
+ ASSERT_STR_EQ(selected_config_hash.sha256, expected_config_hash);
+ cbm_store_clear_file_hash(&selected_config_hash);
+ cbm_file_hash_t unselected_config_hash = {0};
+ ASSERT_EQ(cbm_store_get_file_hash(baseline_store, baseline_project, "jsconfig.json",
+ &unselected_config_hash),
+ CBM_STORE_NOT_FOUND);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ /* The lower-priority jsconfig is not a semantic input while tsconfig is
+ * present in the same directory. Its byte change must remain a no-op. */
+ write_temp_file(tmp, "jsconfig.json", replacement_jsconfig);
+ ASSERT_EQ(pipeline_test_set_mtime(jsconfig_path, fixed_config_mtime, 333333333L), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unselected = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(unselected);
+ ASSERT_EQ(cbm_pipeline_run(unselected), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_NOOP);
+ cbm_pipeline_free(unselected);
+
+ /* The source files remain byte-for-byte unchanged; selected control bytes
+ * change at the same length and mtime. */
+ write_temp_file(tmp, "tsconfig.json", replacement_tsconfig);
+ ASSERT_EQ(pipeline_test_set_mtime(tsconfig_path, fixed_config_mtime, 222222222L), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ ASSERT_EQ(cbm_pipeline_run(incremental), 0);
+ ASSERT_EQ(cbm_pipeline_incremental_test_last_route(), CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ const char *incremental_project = cbm_pipeline_project_name(incremental);
+ cbm_store_t *incremental_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(incremental_store);
+ int incremental_reference_a =
+ named_edge_to_file_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_a.ts");
+ int incremental_reference_b =
+ named_edge_to_file_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_b.ts");
+ int incremental_usage = named_edge_count(incremental_store, incremental_project, "USAGE",
+ "semanticControlCaller", "semanticControlHandler");
+ int incremental_calls = named_edge_count(incremental_store, incremental_project, "CALLS",
+ "semanticControlCaller", "semanticControlHandler");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/tsconfig-reference-full.db", tmp);
+ cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(full);
+ ASSERT_EQ(cbm_pipeline_run(full), 0);
+ const char *full_project = cbm_pipeline_project_name(full);
+ cbm_store_t *full_store = cbm_store_open_path(full_db);
+ ASSERT_NOT_NULL(full_store);
+ int full_reference_a =
+ named_edge_to_file_count(full_store, full_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_a.ts");
+ int full_reference_b =
+ named_edge_to_file_count(full_store, full_project, "CALL_REFERENCE",
+ "semanticControlCaller", "semanticControlHandler", "target_b.ts");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE", "semanticControlCaller",
+ "semanticControlHandler");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS", "semanticControlCaller",
+ "semanticControlHandler");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ /* Prove the fresh oracle changed only because the alias now selects B. */
+ ASSERT_EQ(full_reference_a, 0);
+ ASSERT_EQ(full_reference_b, 1);
+ ASSERT_EQ(full_usage, 0);
+ ASSERT_EQ(full_calls, 0);
+
+ /* Incremental output must converge exactly on the fresh target and kind. */
+ ASSERT_EQ(incremental_reference_a, full_reference_a);
+ ASSERT_EQ(incremental_reference_b, full_reference_b);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+}
+
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+static void observe_named_generation(const char *db_path, const char *project,
+ const char *before_name, const char *after_name,
+ int *before_count, int *after_count) {
+ *before_count = -1;
+ *after_count = -1;
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store) {
+ return;
+ }
+ *before_count = named_node_count(store, project, before_name);
+ *after_count = named_node_count(store, project, after_name);
+ cbm_store_close(store);
+}
+
+static int count_generation_stage_artifacts(const char *dir_path, const char *db_basename) {
+ cbm_dir_t *dir = cbm_opendir(dir_path);
+ if (!dir) {
+ return -1;
+ }
+ char prefix[256];
+ snprintf(prefix, sizeof(prefix), "%s.stage.", db_basename);
+ size_t prefix_len = strlen(prefix);
+ int count = 0;
+ cbm_dirent_t *entry;
+ while ((entry = cbm_readdir(dir)) != NULL) {
+ if (strncmp(entry->name, prefix, prefix_len) == 0) {
+ count++;
+ }
+ }
+ cbm_closedir(dir);
+ return count;
+}
+
+typedef struct {
+ const char *path;
+ const char *replacement;
+ int write_rc;
+} manifest_race_mutation_t;
+
+static void mutate_semantic_input_before_final_manifest(void *userdata) {
+ manifest_race_mutation_t *mutation = (manifest_race_mutation_t *)userdata;
+ mutation->write_rc = th_write_file(mutation->path, mutation->replacement);
+}
+
+/* A graph and its exact manifest are one generation. If source bytes change
+ * after extraction but before publication, the mixed generation must be
+ * rejected and the previous live DB preserved. */
+TEST(pipeline_source_mutation_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_generation_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char db_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def StableGeneration():\n return 1\n"), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ ASSERT_EQ(th_write_file(source_path, "def ExtractedGeneration():\n return 2\n"), 0);
+ manifest_race_mutation_t mutation = {
+ .path = source_path,
+ .replacement = "def FinalGeneration():\n return 3\n",
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+ int raced_stable = -1;
+ int raced_extracted = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "ExtractedGeneration",
+ &raced_stable, &raced_extracted);
+ int raced_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_pipeline_free(retry);
+ int retry_stable = -1;
+ int retry_final = -1;
+ observe_named_generation(db_path, project, "StableGeneration", "FinalGeneration", &retry_stable,
+ &retry_final);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable, 1);
+ ASSERT_EQ(raced_extracted, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_stable, 0);
+ ASSERT_EQ(retry_final, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+}
+
+/* Discovery and extraction must describe the same immutable generation. A
+ * source file created after extraction is not present in the original file
+ * list, so merely re-hashing that list cannot detect the race. Publication
+ * must abort, leave the old DB intact, and let a clean retry discover both
+ * files. */
+TEST(pipeline_source_addition_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_addition_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char late_path[512];
+ char db_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(late_path, sizeof(late_path), "%s/late.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def StableAdditionGeneration():\n return 1\n"), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ ASSERT_EQ(th_write_file(source_path, "def ExtractedAdditionGeneration():\n return 2\n"), 0);
+ manifest_race_mutation_t mutation = {
+ .path = late_path,
+ .replacement = "def LateDiscoveredGeneration():\n return 3\n",
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+
+ int raced_stable = -1;
+ int raced_extracted = -1;
+ int raced_late = -1;
+ cbm_store_t *raced_store = cbm_store_open_path(db_path);
+ if (raced_store) {
+ raced_stable = named_node_count(raced_store, project, "StableAdditionGeneration");
+ raced_extracted = named_node_count(raced_store, project, "ExtractedAdditionGeneration");
+ raced_late = named_node_count(raced_store, project, "LateDiscoveredGeneration");
+ cbm_store_close(raced_store);
+ }
+ int raced_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+
+ int retry_stable = -1;
+ int retry_extracted = -1;
+ int retry_late = -1;
+ cbm_store_t *retry_store = cbm_store_open_path(db_path);
+ if (retry_store) {
+ retry_stable = named_node_count(retry_store, project, "StableAdditionGeneration");
+ retry_extracted = named_node_count(retry_store, project, "ExtractedAdditionGeneration");
+ retry_late = named_node_count(retry_store, project, "LateDiscoveredGeneration");
+ cbm_store_close(retry_store);
+ }
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable, 1);
+ ASSERT_EQ(raced_extracted, 0);
+ ASSERT_EQ(raced_late, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_stable, 0);
+ ASSERT_EQ(retry_extracted, 1);
+ ASSERT_EQ(retry_late, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+}
+
+/* A selected path-alias config is an extraction input, not just manifest
+ * metadata. Rewriting it after extraction must not publish an A-resolved graph
+ * beside a B-hashed manifest; that combination would make the next run a
+ * false no-op and permanently retain the stale target. */
+TEST(pipeline_tsconfig_mutation_before_publication_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_tsconfig_race_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+
+ static const char target_a_source[] = "export function publicationRaceHandler(): void {\n"
+ " const selected = 'a';\n"
+ " void selected;\n"
+ "}\n";
+ static const char target_b_source[] = "export function publicationRaceHandler(): void {\n"
+ " const selected = 'b';\n"
+ " void selected;\n"
+ "}\n";
+ static const char stable_caller_source[] =
+ "import { publicationRaceHandler } from '@publication-race';\n"
+ "function acceptPublicationRace(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function PublicationRaceStableCaller(): void {\n"
+ " acceptPublicationRace(publicationRaceHandler);\n"
+ "}\n";
+ static const char extracted_caller_source[] =
+ "import { publicationRaceHandler } from '@publication-race';\n"
+ "function acceptPublicationRace(callback: () => void): void {\n"
+ " void callback;\n"
+ "}\n"
+ "export function PublicationRaceExtractedCaller(): void {\n"
+ " acceptPublicationRace(publicationRaceHandler);\n"
+ "}\n";
+ static const char tsconfig_a[] = "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@publication-race\": [\"./target_a\"]}\n"
+ " }\n"
+ "}\n";
+ static const char tsconfig_b[] = "{\n"
+ " \"compilerOptions\": {\n"
+ " \"baseUrl\": \".\",\n"
+ " \"paths\": {\"@publication-race\": [\"./target_b\"]}\n"
+ " }\n"
+ "}\n";
+
+ write_temp_file(tmp, "target_a.ts", target_a_source);
+ write_temp_file(tmp, "target_b.ts", target_b_source);
+ write_temp_file(tmp, "caller.ts", stable_caller_source);
+ write_temp_file(tmp, "tsconfig.json", tsconfig_a);
+ char caller_path[512];
+ char tsconfig_path[512];
+ char db_path[512];
+ snprintf(caller_path, sizeof(caller_path), "%s/caller.ts", tmp);
+ snprintf(tsconfig_path, sizeof(tsconfig_path), "%s/tsconfig.json", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ ASSERT_EQ(th_write_file(caller_path, extracted_caller_source), 0);
+ manifest_race_mutation_t mutation = {
+ .path = tsconfig_path,
+ .replacement = tsconfig_b,
+ .write_rc = -1,
+ };
+ cbm_pipeline_incremental_test_before_final_manifest_once(
+ mutate_semantic_input_before_final_manifest, &mutation);
+ cbm_pipeline_t *raced = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(raced);
+ int raced_rc = cbm_pipeline_run(raced);
+ cbm_pipeline_free(raced);
+
+ int raced_stable_a = -1;
+ int raced_stable_b = -1;
+ int raced_extracted_nodes = -1;
+ cbm_store_t *raced_store = cbm_store_open_path(db_path);
+ if (raced_store) {
+ raced_stable_a = named_edge_to_file_count(raced_store, project, "CALL_REFERENCE",
+ "PublicationRaceStableCaller",
+ "publicationRaceHandler", "target_a.ts");
+ raced_stable_b = named_edge_to_file_count(raced_store, project, "CALL_REFERENCE",
+ "PublicationRaceStableCaller",
+ "publicationRaceHandler", "target_b.ts");
+ raced_extracted_nodes =
+ named_node_count(raced_store, project, "PublicationRaceExtractedCaller");
+ cbm_store_close(raced_store);
+ }
+ int raced_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+
+ int retry_stable_nodes = -1;
+ int retry_extracted_a = -1;
+ int retry_extracted_b = -1;
+ int retry_extracted_usage = -1;
+ int retry_extracted_calls = -1;
+ cbm_store_t *retry_store = cbm_store_open_path(db_path);
+ if (retry_store) {
+ retry_stable_nodes = named_node_count(retry_store, project, "PublicationRaceStableCaller");
+ retry_extracted_a = named_edge_to_file_count(retry_store, project, "CALL_REFERENCE",
+ "PublicationRaceExtractedCaller",
+ "publicationRaceHandler", "target_a.ts");
+ retry_extracted_b = named_edge_to_file_count(retry_store, project, "CALL_REFERENCE",
+ "PublicationRaceExtractedCaller",
+ "publicationRaceHandler", "target_b.ts");
+ retry_extracted_usage =
+ named_edge_count(retry_store, project, "USAGE", "PublicationRaceExtractedCaller",
+ "publicationRaceHandler");
+ retry_extracted_calls =
+ named_edge_count(retry_store, project, "CALLS", "PublicationRaceExtractedCaller",
+ "publicationRaceHandler");
+ cbm_store_close(retry_store);
+ }
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(mutation.write_rc, 0);
+ ASSERT_EQ(raced_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(raced_stable_a, 1);
+ ASSERT_EQ(raced_stable_b, 0);
+ ASSERT_EQ(raced_extracted_nodes, 0);
+ ASSERT_EQ(raced_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_stable_nodes, 0);
+ ASSERT_EQ(retry_extracted_a, 0);
+ ASSERT_EQ(retry_extracted_b, 1);
+ ASSERT_EQ(retry_extracted_usage, 0);
+ ASSERT_EQ(retry_extracted_calls, 0);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+}
+
+/* Metadata participates in exact-input compatibility. Old coverage schema or
+ * an upgrade to a more comprehensive discovery/index mode must force a
+ * complete replacement even when every semantic-input byte is unchanged; the
+ * replacement must write current metadata so the next identical run is a
+ * true no-op. Cheaper requests retain fuller published coverage separately. */
+TEST(pipeline_exact_inputs_migrate_coverage_metadata_and_index_mode) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_metadata_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def ExactMetadataGeneration():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *exact_before_migration = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(exact_before_migration);
+ ASSERT_EQ(cbm_pipeline_run(exact_before_migration), 0);
+ cbm_incremental_route_t exact_before_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(exact_before_migration);
+
+ cbm_store_t *metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_row_t *coverage_rows = NULL;
+ int coverage_count = 0;
+ ASSERT_EQ(cbm_store_coverage_get(metadata_store, project, &coverage_rows, &coverage_count),
+ CBM_STORE_OK);
+ cbm_coverage_meta_t current_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &current_meta), CBM_STORE_OK);
+ cbm_coverage_meta_t legacy_meta = current_meta;
+ legacy_meta.coverage_version = 1;
+ ASSERT_EQ(cbm_store_coverage_replace_ex(metadata_store, project, coverage_rows, coverage_count,
+ &legacy_meta),
+ CBM_STORE_OK);
+ cbm_store_free_coverage(coverage_rows, coverage_count);
+ cbm_store_coverage_meta_clear(&current_meta);
+ cbm_store_close(metadata_store);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *migration = cbm_pipeline_new(tmp, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(migration);
+ ASSERT_EQ(cbm_pipeline_run(migration), 0);
+ cbm_incremental_route_t migration_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(migration);
+
+ metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_meta_t migrated_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &migrated_meta), CBM_STORE_OK);
+ int migrated_version = migrated_meta.coverage_version;
+ bool migrated_hashes_complete = migrated_meta.hash_records_complete;
+ char migrated_mode[32];
+ snprintf(migrated_mode, sizeof(migrated_mode), "%s",
+ migrated_meta.index_mode ? migrated_meta.index_mode : "");
+ cbm_store_coverage_meta_clear(&migrated_meta);
+ cbm_store_close(metadata_store);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *mode_change = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(mode_change);
+ ASSERT_EQ(cbm_pipeline_run(mode_change), 0);
+ cbm_incremental_route_t mode_change_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(mode_change);
+
+ metadata_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(metadata_store);
+ cbm_coverage_meta_t full_meta = {0};
+ ASSERT_EQ(cbm_store_coverage_meta_get(metadata_store, project, &full_meta), CBM_STORE_OK);
+ int full_version = full_meta.coverage_version;
+ bool full_hashes_complete = full_meta.hash_records_complete;
+ char full_mode[32];
+ snprintf(full_mode, sizeof(full_mode), "%s", full_meta.index_mode ? full_meta.index_mode : "");
+ cbm_store_coverage_meta_clear(&full_meta);
+ cbm_store_close(metadata_store);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *exact_full = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(exact_full);
+ ASSERT_EQ(cbm_pipeline_run(exact_full), 0);
+ cbm_incremental_route_t exact_full_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(exact_full);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(exact_before_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_EQ(migration_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(migrated_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(migrated_hashes_complete);
+ ASSERT_STR_EQ(migrated_mode, "fast");
+ ASSERT_EQ(mode_change_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(full_version, CBM_SEMANTIC_INDEX_VERSION);
+ ASSERT_TRUE(full_hashes_complete);
+ ASSERT_STR_EQ(full_mode, "full");
+ ASSERT_EQ(exact_full_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ PASS();
+}
+
+/* Once a repository contains a shared artifact, every subsequently published
+ * full generation must refresh it, even when persistence was not explicitly
+ * requested on that invocation. Otherwise the live DB advances while a clean
+ * teammate import silently restores the previous graph. */
+TEST(pipeline_existing_artifact_refreshes_after_default_forced_full_reindex) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_artifact_refresh_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ char source_path[512];
+ char db_path[512];
+ char imported_path[512];
+ snprintf(source_path, sizeof(source_path), "%s/generation.py", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ snprintf(imported_path, sizeof(imported_path), "%s/imported.db", tmp);
+ ASSERT_EQ(th_write_file(source_path, "def ArtifactGenerationBefore():\n return 1\n"), 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ cbm_pipeline_set_persistence(baseline, true);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+ ASSERT_TRUE(cbm_artifact_exists(tmp));
+
+ ASSERT_EQ(th_write_file(source_path, "def ArtifactGenerationAfter():\n return 2\n"), 0);
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *default_reindex = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(default_reindex);
+ int reindex_rc = cbm_pipeline_run(default_reindex);
+ cbm_incremental_route_t reindex_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(default_reindex);
+
+ /* A derived artifact must not become an input that forces another rebuild,
+ * and refreshing it must not switch the authoritative DB back to WAL. */
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(unchanged);
+ int unchanged_rc = cbm_pipeline_run(unchanged);
+ cbm_incremental_route_t unchanged_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(unchanged);
+
+ char journal_mode[16] = {0};
+ sqlite3 *raw = NULL;
+ sqlite3_stmt *journal_stmt = NULL;
+ int journal_ok =
+ sqlite3_open_v2(db_path, &raw, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK &&
+ sqlite3_prepare_v2(raw, "PRAGMA journal_mode;", -1, &journal_stmt, NULL) == SQLITE_OK &&
+ sqlite3_step(journal_stmt) == SQLITE_ROW;
+ if (journal_ok) {
+ const unsigned char *mode = sqlite3_column_text(journal_stmt, 0);
+ if (!mode || snprintf(journal_mode, sizeof(journal_mode), "%s", (const char *)mode) >=
+ (int)sizeof(journal_mode)) {
+ journal_ok = 0;
+ }
+ }
+ sqlite3_finalize(journal_stmt);
+ if (raw) {
+ sqlite3_close(raw);
+ }
+
+ int live_before = -1;
+ int live_after = -1;
+ cbm_store_t *live_store = cbm_store_open_path(db_path);
+ if (live_store) {
+ live_before = named_node_count(live_store, project, "ArtifactGenerationBefore");
+ live_after = named_node_count(live_store, project, "ArtifactGenerationAfter");
+ cbm_store_close(live_store);
+ }
+
+ int import_rc = cbm_artifact_import(tmp, imported_path);
+ int artifact_before = -1;
+ int artifact_after = -1;
+ cbm_store_t *artifact_store = import_rc == 0 ? cbm_store_open_path(imported_path) : NULL;
+ if (artifact_store) {
+ artifact_before = named_node_count(artifact_store, project, "ArtifactGenerationBefore");
+ artifact_after = named_node_count(artifact_store, project, "ArtifactGenerationAfter");
+ cbm_store_close(artifact_store);
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(reindex_rc, 0);
+ ASSERT_EQ(reindex_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(unchanged_rc, 0);
+ ASSERT_EQ(unchanged_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ ASSERT_TRUE(journal_ok);
+ ASSERT_STR_EQ(journal_mode, "delete");
+ ASSERT_EQ(live_before, 0);
+ ASSERT_EQ(live_after, 1);
+ ASSERT_EQ(import_rc, 0);
+ ASSERT_EQ(artifact_before, 0);
+ ASSERT_EQ(artifact_after, 1);
+ PASS();
+}
+
+/* Cancellation observed after predump must be an explicit preserved abort,
+ * never a false success. The retry then publishes the edited generation. */
+TEST(pipeline_full_cancel_after_predump_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_cancel_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ static const char before_source[] = "def BeforeCancel():\n return 1\n";
+ static const char after_source[] = "def AfterCancel():\n return 2\n# changed\n";
+ write_temp_file(tmp, "generation.py", before_source);
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py", after_source);
+ cbm_pipeline_incremental_test_cancel_after_predump_once();
+ cbm_pipeline_t *cancelled = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(cancelled);
+ int cancelled_rc = cbm_pipeline_run(cancelled);
+ cbm_incremental_route_t cancelled_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(cancelled);
+ int cancelled_before = -1;
+ int cancelled_after = -1;
+ observe_named_generation(db_path, project, "BeforeCancel", "AfterCancel", &cancelled_before,
+ &cancelled_after);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeCancel", "AfterCancel", &retry_before,
+ &retry_after);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(cancelled_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(cancelled_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(cancelled_before, 1);
+ ASSERT_EQ(cancelled_after, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+}
+
+/* Cancellation can arrive while the destination DB is being quiesced. It must
+ * still be observed at the final commit boundary, before the atomic rename. */
+TEST(pipeline_full_cancel_after_destination_prepare_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_late_cancel_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeLateCancel():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py", "def AfterLateCancel():\n return 2\n# changed\n");
+ cbm_pipeline_incremental_test_cancel_after_destination_prepare_once();
+ cbm_pipeline_t *cancelled = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(cancelled);
+ int cancelled_rc = cbm_pipeline_run(cancelled);
+ cbm_pipeline_free(cancelled);
+
+ int before_count = -1;
+ int after_count = -1;
+ observe_named_generation(db_path, project, "BeforeLateCancel", "AfterLateCancel", &before_count,
+ &after_count);
+ int stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(cancelled_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(before_count, 1);
+ ASSERT_EQ(after_count, 0);
+ ASSERT_EQ(stage_count, 0);
+ PASS();
+}
+
+/* A failure after graph serialization but before metadata/publication must
+ * discard only the staged generation. The final path remains the complete old
+ * graph and a clean retry converges. */
+TEST(pipeline_full_persist_failure_after_stage_dump_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_full_fail_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeFullPersist():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterFullPersist():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_fail_after_stage_dump_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_pipeline_free(faulted);
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeFullPersist", "AfterFullPersist",
+ &faulted_before, &faulted_after);
+ int faulted_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeFullPersist", "AfterFullPersist",
+ &retry_before, &retry_after);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_PERSIST_FAILED);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_EQ(faulted_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+}
+
+/* Keep the legacy partial route test-only so its fail-closed behavior remains
+ * covered even though production semantic changes now force a full rebuild. */
+TEST(pipeline_incremental_persist_failure_preserves_previous_generation_and_retries) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_incr_fail_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeIncrementalPersist():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterIncrementalPersist():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_incremental_test_fail_after_stage_dump_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_incremental_route_t faulted_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(faulted);
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeIncrementalPersist",
+ "AfterIncrementalPersist", &faulted_before, &faulted_after);
+ int faulted_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_incremental_route_t retry_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeIncrementalPersist",
+ "AfterIncrementalPersist", &retry_before, &retry_after);
+ int retry_stage_count = count_generation_stage_artifacts(tmp, "generation.db");
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_PERSIST_FAILED);
+ ASSERT_EQ(faulted_route, CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_EQ(faulted_stage_count, 0);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_EQ(retry_stage_count, 0);
+ PASS();
+}
+
+TEST(pipeline_incremental_successful_publication_preserves_adr) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_incr_adr_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeAdrIncremental():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+ static const char adr_text[] = "# Decision\nPreserve across publication.";
+ cbm_store_t *adr_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(adr_store);
+ ASSERT_EQ(cbm_store_adr_store(adr_store, project, adr_text), CBM_STORE_OK);
+ cbm_store_close(adr_store);
+
+ write_temp_file(tmp, "generation.py",
+ "def AfterAdrIncremental():\n return 2\n# changed generation\n");
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ int run_rc = cbm_pipeline_run(incremental);
+ cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(incremental);
+ cbm_store_t *published = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(published);
+ cbm_adr_t adr = {0};
+ int adr_rc = cbm_store_adr_get(published, project, &adr);
+ bool adr_matches = adr_rc == CBM_STORE_OK && adr.content && strcmp(adr.content, adr_text) == 0;
+ cbm_store_adr_free(&adr);
+ cbm_store_close(published);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_LEGACY_PARTIAL);
+ ASSERT_TRUE(adr_matches);
+ PASS();
+}
+
+/* A forced-full rebuild must never erase an ADR merely because the old
+ * generation could not be read completely. The capture is part of the
+ * publication transaction: failure preserves both graph and ADR. */
+TEST(pipeline_full_adr_capture_failure_preserves_previous_generation) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_adr_capture_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "generation.py", "def BeforeAdrCapture():\n return 1\n");
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ static const char adr_text[] = "# Decision\nADR capture is fail-closed.";
+ cbm_store_t *adr_store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(adr_store);
+ ASSERT_EQ(cbm_store_adr_store(adr_store, project, adr_text), CBM_STORE_OK);
+ cbm_store_close(adr_store);
+
+ write_temp_file(tmp, "generation.py", "def AfterAdrCapture():\n return 2\n");
+ cbm_pipeline_incremental_test_fail_adr_capture_once();
+ cbm_pipeline_t *faulted = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(faulted);
+ int faulted_rc = cbm_pipeline_run(faulted);
+ cbm_pipeline_free(faulted);
+
+ int faulted_before = -1;
+ int faulted_after = -1;
+ observe_named_generation(db_path, project, "BeforeAdrCapture", "AfterAdrCapture",
+ &faulted_before, &faulted_after);
+ cbm_store_t *preserved = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(preserved);
+ cbm_adr_t preserved_adr = {0};
+ int preserved_adr_rc = cbm_store_adr_get(preserved, project, &preserved_adr);
+ bool preserved_adr_matches = preserved_adr_rc == CBM_STORE_OK && preserved_adr.content &&
+ strcmp(preserved_adr.content, adr_text) == 0;
+ cbm_store_adr_free(&preserved_adr);
+ cbm_store_close(preserved);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *retry = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(retry);
+ int retry_rc = cbm_pipeline_run(retry);
+ cbm_pipeline_free(retry);
+ int retry_before = -1;
+ int retry_after = -1;
+ observe_named_generation(db_path, project, "BeforeAdrCapture", "AfterAdrCapture", &retry_before,
+ &retry_after);
+ cbm_store_t *published = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(published);
+ cbm_adr_t published_adr = {0};
+ int published_adr_rc = cbm_store_adr_get(published, project, &published_adr);
+ bool published_adr_matches = published_adr_rc == CBM_STORE_OK && published_adr.content &&
+ strcmp(published_adr.content, adr_text) == 0;
+ cbm_store_adr_free(&published_adr);
+ cbm_store_close(published);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(faulted_rc, CBM_PIPELINE_ABORT_PRESERVE_DB);
+ ASSERT_EQ(faulted_before, 1);
+ ASSERT_EQ(faulted_after, 0);
+ ASSERT_TRUE(preserved_adr_matches);
+ ASSERT_EQ(retry_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, 1);
+ ASSERT_TRUE(published_adr_matches);
+ PASS();
+}
+
+/* An exact semantic manifest must fail closed when its repository root cannot
+ * be traversed. A regular file is a deterministic cross-platform opendir
+ * failure that does not depend on process permissions. */
+TEST(pipeline_semantic_manifest_rejects_non_directory_root) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_manifest_not_dir_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "not-a-directory", "manifest root sentinel\n");
+ char root_path[512];
+ snprintf(root_path, sizeof(root_path), "%s/not-a-directory", tmp);
+
+ cbm_file_hash_t *manifest = NULL;
+ int manifest_count = -1;
+ int rc = cbm_pipeline_build_semantic_manifest("manifest-fail-closed", root_path, NULL, 0, NULL,
+ 0, NULL, NULL, &manifest, &manifest_count);
+ cbm_pipeline_free_semantic_manifest(manifest, manifest_count > 0 ? manifest_count : 0);
+ th_rmtree(tmp);
+
+ ASSERT_TRUE(rc != 0);
+ ASSERT_EQ(manifest_count, 0);
+ PASS();
+}
+
+/* A fully validated staged graph must be able to recover from a definitely
+ * non-SQLite destination without deleting evidence or overwriting an earlier
+ * quarantine. The replacement happens only after the corrupt bytes are moved. */
+TEST(pipeline_full_reindex_quarantines_corrupt_destination_without_overwrite) {
+ static const char corrupt_bytes[] = "not a sqlite database\n";
+ static const char previous_backup[] = "older quarantine\n";
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_corrupt_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "fresh.py", "def FreshAfterCorruption():\n return 1\n");
+ write_temp_file(tmp, "generation.db", corrupt_bytes);
+ write_temp_file(tmp, "generation.db.corrupt", previous_backup);
+
+ char db_path[512];
+ char old_backup_path[512];
+ char new_backup_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ snprintf(old_backup_path, sizeof(old_backup_path), "%s.corrupt", db_path);
+ snprintf(new_backup_path, sizeof(new_backup_path), "%s.corrupt.1", db_path);
+
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(pipeline);
+ int run_rc = cbm_pipeline_run(pipeline);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(pipeline));
+ cbm_pipeline_free(pipeline);
+
+ char old_observed[64] = {0};
+ char new_observed[64] = {0};
+ FILE *old_backup_file = cbm_fopen(old_backup_path, "rb");
+ FILE *new_backup_file = cbm_fopen(new_backup_path, "rb");
+ size_t old_size =
+ old_backup_file ? fread(old_observed, 1, sizeof(old_observed) - 1, old_backup_file) : 0;
+ size_t new_size =
+ new_backup_file ? fread(new_observed, 1, sizeof(new_observed) - 1, new_backup_file) : 0;
+ if (old_backup_file) {
+ fclose(old_backup_file);
+ }
+ if (new_backup_file) {
+ fclose(new_backup_file);
+ }
+
+ int fresh_nodes = -1;
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (store) {
+ fresh_nodes = named_node_count(store, project, "FreshAfterCorruption");
+ cbm_store_close(store);
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ((int)old_size, (int)strlen(previous_backup));
+ ASSERT_STR_EQ(old_observed, previous_backup);
+ ASSERT_EQ((int)new_size, (int)strlen(corrupt_bytes));
+ ASSERT_STR_EQ(new_observed, corrupt_bytes);
+ ASSERT_EQ(fresh_nodes, 1);
+ PASS();
+}
+
+/* Readable legacy graphs are replaceable generations, not corruption. The
+ * publication boundary must neither run current-schema migration against the
+ * old edges table nor require an ADR table that did not exist yet. */
+TEST(pipeline_full_reindex_replaces_legacy_schema_without_quarantine) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_publish_legacy_XXXXXX");
+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
+ write_temp_file(tmp, "fresh.py", "def FreshAfterLegacy():\n return 1\n");
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/generation.db", tmp);
+ sqlite3 *legacy = NULL;
+ ASSERT_EQ(sqlite3_open_v2(db_path, &legacy, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL),
+ SQLITE_OK);
+ const char *legacy_schema =
+ "CREATE TABLE projects(name TEXT PRIMARY KEY,indexed_at TEXT NOT NULL,root_path TEXT NOT "
+ "NULL);"
+ "CREATE TABLE file_hashes(project TEXT NOT NULL,rel_path TEXT NOT NULL,sha256 TEXT NOT "
+ "NULL,mtime_ns INTEGER NOT NULL DEFAULT 0,size INTEGER NOT NULL DEFAULT 0,PRIMARY KEY "
+ "(project,rel_path));"
+ "CREATE TABLE nodes(id INTEGER PRIMARY KEY,project TEXT NOT NULL,label TEXT NOT NULL,name "
+ "TEXT NOT NULL,qualified_name TEXT NOT NULL,file_path TEXT,start_line INTEGER,end_line "
+ "INTEGER,properties TEXT DEFAULT '{}');"
+ "CREATE TABLE edges(id INTEGER PRIMARY KEY,project TEXT NOT NULL,source_id INTEGER NOT "
+ "NULL,target_id INTEGER NOT NULL,type TEXT NOT NULL,properties TEXT DEFAULT '{}',UNIQUE "
+ "(source_id,target_id,type));";
+ ASSERT_EQ(sqlite3_exec(legacy, legacy_schema, NULL, NULL, NULL), SQLITE_OK);
+ sqlite3_stmt *insert_project = NULL;
+ ASSERT_EQ(sqlite3_prepare_v2(
+ legacy, "INSERT INTO projects(name,indexed_at,root_path) VALUES(?1,'legacy',?2);",
+ -1, &insert_project, NULL),
+ SQLITE_OK);
+ const char *project_name = strrchr(tmp, '/');
+ project_name = project_name ? project_name + 1 : tmp;
+ ASSERT_EQ(sqlite3_bind_text(insert_project, 1, project_name, -1, SQLITE_TRANSIENT), SQLITE_OK);
+ ASSERT_EQ(sqlite3_bind_text(insert_project, 2, tmp, -1, SQLITE_TRANSIENT), SQLITE_OK);
+ ASSERT_EQ(sqlite3_step(insert_project), SQLITE_DONE);
+ sqlite3_finalize(insert_project);
+ sqlite3_close(legacy);
+
+ cbm_pipeline_t *pipeline = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(pipeline);
+ int run_rc = cbm_pipeline_run(pipeline);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(pipeline));
+ cbm_pipeline_free(pipeline);
+
+ int fresh_nodes = -1;
+ cbm_store_t *store = cbm_store_open_path_query(db_path);
+ if (store) {
+ fresh_nodes = named_node_count(store, project, "FreshAfterLegacy");
+ cbm_store_close(store);
+ }
+ int generated_column_count = 0;
+ sqlite3 *current = NULL;
+ sqlite3_stmt *column_query = NULL;
+ if (sqlite3_open_v2(db_path, &current, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK &&
+ sqlite3_prepare_v2(current,
+ "SELECT count(*) FROM pragma_table_xinfo('edges') "
+ "WHERE name='local_name_gen';",
+ -1, &column_query, NULL) == SQLITE_OK &&
+ sqlite3_step(column_query) == SQLITE_ROW) {
+ generated_column_count = sqlite3_column_int(column_query, 0);
+ }
+ sqlite3_finalize(column_query);
+ if (current) {
+ sqlite3_close(current);
+ }
+ char quarantine_path[512];
+ snprintf(quarantine_path, sizeof(quarantine_path), "%s.corrupt", db_path);
+ cbm_path_info_t quarantine_info;
+ bool quarantined = cbm_path_info_utf8(quarantine_path, &quarantine_info) == 0;
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_EQ(fresh_nodes, 1);
+ ASSERT_EQ(generated_column_count, 1);
+ ASSERT_FALSE(quarantined);
+ PASS();
+}
+#endif
+
+/* Re-indexing only a target whose qualified name survives a callable-to-value
+ * edit must not restore the unchanged caller's stale inbound CALL_REFERENCE
+ * snapshot. A fresh full index of the edited sources is the convergence oracle:
+ * the now-non-callable identifier remains a USAGE, never a call relationship. */
+TEST(pipeline_incremental_changed_target_invalidates_stale_inbound_call_reference) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_ref_stale_inbound_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ static const char callable_target_source[] = "export function staleSemanticTarget(): void {}\n";
+ static const char value_target_source[] = "export const staleSemanticTarget = 42;\n";
+ static const char caller_source[] =
+ "import { staleSemanticTarget } from './target';\n"
+ "function acceptStaleSemanticReference(callback: () => void): void {}\n"
+ "export function staleSemanticCaller(): void {\n"
+ " acceptStaleSemanticReference(staleSemanticTarget);\n"
+ "}\n";
+
+ write_temp_file(tmp, "target.ts", callable_target_source);
+ write_temp_file(tmp, "caller.ts", caller_source);
+
+ char incremental_db[512];
+ snprintf(incremental_db, sizeof(incremental_db), "%s/stale-inbound-incremental.db", tmp);
+ cbm_pipeline_t *baseline = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ const char *baseline_project = cbm_pipeline_project_name(baseline);
+ cbm_store_t *baseline_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(baseline_store);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget"),
+ 1);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "USAGE", "staleSemanticCaller",
+ "staleSemanticTarget"),
+ 0);
+ ASSERT_EQ(named_edge_count(baseline_store, baseline_project, "CALLS", "staleSemanticCaller",
+ "staleSemanticTarget"),
+ 0);
+ cbm_store_close(baseline_store);
+ cbm_pipeline_free(baseline);
+
+ write_temp_file(tmp, "target.ts", value_target_source);
+
+ cbm_pipeline_t *incremental = cbm_pipeline_new(tmp, incremental_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(incremental);
+ ASSERT_EQ(cbm_pipeline_run(incremental), 0);
+ const char *incremental_project = cbm_pipeline_project_name(incremental);
+ cbm_store_t *incremental_store = cbm_store_open_path(incremental_db);
+ ASSERT_NOT_NULL(incremental_store);
+ int incremental_reference =
+ named_edge_count(incremental_store, incremental_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int incremental_usage = named_edge_count(incremental_store, incremental_project, "USAGE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int incremental_calls = named_edge_count(incremental_store, incremental_project, "CALLS",
+ "staleSemanticCaller", "staleSemanticTarget");
+ cbm_store_close(incremental_store);
+ cbm_pipeline_free(incremental);
+
+ char full_db[512];
+ snprintf(full_db, sizeof(full_db), "%s/stale-inbound-full.db", tmp);
+ cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(full);
+ ASSERT_EQ(cbm_pipeline_run(full), 0);
+ const char *full_project = cbm_pipeline_project_name(full);
+ cbm_store_t *full_store = cbm_store_open_path(full_db);
+ ASSERT_NOT_NULL(full_store);
+ int full_reference = named_edge_count(full_store, full_project, "CALL_REFERENCE",
+ "staleSemanticCaller", "staleSemanticTarget");
+ int full_usage = named_edge_count(full_store, full_project, "USAGE", "staleSemanticCaller",
+ "staleSemanticTarget");
+ int full_calls = named_edge_count(full_store, full_project, "CALLS", "staleSemanticCaller",
+ "staleSemanticTarget");
+ cbm_store_close(full_store);
+ cbm_pipeline_free(full);
+ th_rmtree(tmp);
+
+ ASSERT_EQ(full_reference, 0);
+ ASSERT_EQ(full_usage, 1);
+ ASSERT_EQ(full_calls, 0);
+ ASSERT_EQ(incremental_reference, full_reference);
+ ASSERT_EQ(incremental_usage, full_usage);
+ ASSERT_EQ(incremental_calls, full_calls);
+ PASS();
+}
+
+/* Registry construction in incremental-parallel mode can materialize serial
+ * resource nodes after extraction establishes the workers' shared-ID
+ * watermark. A subsequent worker-created synthetic node must not reuse that
+ * ID: duplicate temporary IDs make dump-time edge remapping point CONFIGURES
+ * or DECORATES at the wrong target. The second run changes all 51 files so the
+ * production incremental path crosses MIN_FILES_FOR_PARALLEL_INCR. */
+TEST(pipeline_incremental_parallel_registry_nodes_advance_shared_ids) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_incr_ids_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ char collision_path[512];
+ snprintf(collision_path, sizeof(collision_path), "%s/00_collision.py", tmp);
+ int setup_ok =
+ th_write_file(collision_path, "import os\n"
+ "def incrementalCollisionTarget(): return 1\n"
+ "def incrementalCollisionAccept(callback): pass\n"
+ "@old_marker\n"
+ "def incrementalCollisionCarrier():\n"
+ " incrementalCollisionTarget()\n"
+ " incrementalCollisionAccept(incrementalCollisionTarget)\n"
+ " return os.getenv(\"OLD_TOKEN\")\n") == 0;
+ for (int i = 0; setup_ok && i < 50; i++) {
+ char path[512];
+ char source[128];
+ snprintf(path, sizeof(path), "%s/z_pad_%02d.ts", tmp, i);
+ snprintf(source, sizeof(source), "// initial incremental ID pad %02d\n", i);
+ setup_ok = th_write_file(path, source) == 0;
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/incremental-ids.db", tmp);
+ int first_rc = -1;
+ int second_rc = -1;
+ int env_edge_count = -1;
+ int decorator_edge_count = -1;
+ int misdirected_env_edge_count = -1;
+ int reference_edge_count = -1;
+ int env_node_count = -1;
+ int decorator_node_count = -1;
+
+ if (setup_ok) {
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (first) {
+ first_rc = cbm_pipeline_run(first);
+ cbm_pipeline_free(first);
+ }
+ }
- /* 1. Full index. */
- cbm_pipeline_t *p1 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p1);
- ASSERT_EQ(cbm_pipeline_run(p1), 0);
- const char *project = cbm_pipeline_project_name(p1);
+ int update_ok =
+ setup_ok && first_rc == 0 &&
+ th_write_file(collision_path, "import os\n"
+ "def incrementalCollisionTarget(): return 1\n"
+ "def incrementalCollisionAccept(callback): pass\n"
+ "@new_marker\n"
+ "def incrementalCollisionCarrier():\n"
+ " incrementalCollisionTarget()\n"
+ " incrementalCollisionAccept(incrementalCollisionTarget)\n"
+ " return os.getenv(\"NEW_TOKEN\")\n"
+ "# incremental size marker\n") == 0;
+ for (int i = 0; update_ok && i < 50; i++) {
+ char path[512];
+ char source[160];
+ snprintf(path, sizeof(path), "%s/z_pad_%02d.ts", tmp, i);
+ snprintf(source, sizeof(source), "// changed incremental ID pad %02d with marker\n", i);
+ update_ok = th_write_file(path, source) == 0;
+ }
+
+ if (update_ok) {
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (second) {
+ second_rc = cbm_pipeline_run(second);
+ const char *project = cbm_pipeline_project_name(second);
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (store && project) {
+ env_edge_count = named_edge_count(store, project, "CONFIGURES",
+ "incrementalCollisionCarrier", "NEW_TOKEN");
+ decorator_edge_count = named_edge_count(
+ store, project, "DECORATES", "incrementalCollisionCarrier", "new_marker");
+ misdirected_env_edge_count = named_edge_count(
+ store, project, "CONFIGURES", "incrementalCollisionCarrier", "new_marker");
+ reference_edge_count =
+ named_edge_count(store, project, "CALL_REFERENCE",
+ "incrementalCollisionCarrier", "incrementalCollisionTarget");
+ env_node_count = named_node_count(store, project, "NEW_TOKEN");
+ decorator_node_count = named_node_count(store, project, "new_marker");
+ }
+ if (store) {
+ cbm_store_close(store);
+ }
+ cbm_pipeline_free(second);
+ }
+ }
- cbm_store_t *s1 = cbm_store_open_path(db_path);
- ASSERT_NOT_NULL(s1);
- int calls_before = cbm_store_count_edges_by_type(s1, project, "CALLS");
- ASSERT_GTE(calls_before, 2); /* main->Serve and Serve->Help at minimum */
- ASSERT_TRUE(cross_file_call_exists(s1, project, "Serve", "Help"));
- cbm_store_close(s1);
- cbm_pipeline_free(p1);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
- /* 2. Edit the callee's file so the incremental classifier marks it changed
- * (mtime+size differ). Help's symbol + qualified name are unchanged. */
- char helper[512];
- snprintf(helper, sizeof(helper), "%s/pkg/util/helper.go", g_tmpdir);
- ASSERT_EQ(th_append_file(helper, "\n// incremental regression marker\n"), 0);
+ if (env_node_count != 1 || decorator_node_count != 1 || env_edge_count != 1 ||
+ decorator_edge_count != 1 || misdirected_env_edge_count != 0 || reference_edge_count != 1) {
+ printf(" incremental ID diagnostic: env_node=%d decorator_node=%d "
+ "configures_env=%d decorates=%d configures_decorator=%d call_reference=%d\n",
+ env_node_count, decorator_node_count, env_edge_count, decorator_edge_count,
+ misdirected_env_edge_count, reference_edge_count);
+ }
+
+ ASSERT_TRUE(setup_ok);
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_TRUE(update_ok);
+ ASSERT_EQ(second_rc, 0);
+ ASSERT_EQ(env_node_count, 1);
+ ASSERT_EQ(decorator_node_count, 1);
+ ASSERT_EQ(env_edge_count, 1);
+ ASSERT_EQ(decorator_edge_count, 1);
+ ASSERT_EQ(misdirected_env_edge_count, 0);
+ ASSERT_EQ(reference_edge_count, 1);
+ PASS();
+}
+
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+static void observe_incremental_generation(const char *db_path, const char *project,
+ int generation_size, int *before_count,
+ int *after_count) {
+ *before_count = -1;
+ *after_count = -1;
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ if (!store || !project) {
+ if (store) {
+ cbm_store_close(store);
+ }
+ return;
+ }
+
+ int before = 0;
+ int after = 0;
+ for (int i = 0; i < generation_size; i++) {
+ char before_name[32];
+ char after_name[32];
+ snprintf(before_name, sizeof(before_name), "Before%02d", i);
+ snprintf(after_name, sizeof(after_name), "After%02d", i);
+ int before_nodes = named_node_count(store, project, before_name);
+ int after_nodes = named_node_count(store, project, after_name);
+ if (before_nodes < 0 || after_nodes < 0) {
+ cbm_store_close(store);
+ return;
+ }
+ before += before_nodes;
+ after += after_nodes;
+ }
+ cbm_store_close(store);
+ *before_count = before;
+ *after_count = after;
+}
- /* 3. Re-run on the SAME db_path → auto-routes to incremental re-index. */
- cbm_pipeline_t *p2 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
- ASSERT_NOT_NULL(p2);
- ASSERT_EQ(cbm_pipeline_run(p2), 0);
+/* A parallel incremental run must preserve its prior database when the
+ * per-file result cache cannot be allocated. A clean retry must then converge
+ * to the new generation.
+ *
+ * RED before fail-closed propagation: the injected allocation failure skips
+ * extract/resolve, but the caller dumps the already-purged graph, advances all
+ * file hashes, and returns 0. The second graph is empty and the third run is a
+ * no-op instead of recovering the missing definitions. */
+TEST(pipeline_incremental_parallel_result_cache_alloc_failure_preserves_db_and_retries) {
+ enum { GENERATION_SIZE = 51 };
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_incr_cache_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
- /* 4. The inbound cross-file CALLS edge must survive and the total CALLS
- * count must not regress. (Before the fix: Serve->Help is dropped.)
- * NOTE: query with p2's project name — p1 (and the `project` pointer it
- * owned) was freed above; p1 and p2 derive the same name from g_tmpdir. */
- const char *project2 = cbm_pipeline_project_name(p2);
- cbm_store_t *s2 = cbm_store_open_path(db_path);
- ASSERT_NOT_NULL(s2);
- int calls_after = cbm_store_count_edges_by_type(s2, project2, "CALLS");
- ASSERT_EQ(calls_after, calls_before);
- ASSERT_TRUE(cross_file_call_exists(s2, project2, "Serve", "Help"));
- cbm_store_close(s2);
- cbm_pipeline_free(p2);
+ cbm_pipeline_incremental_test_reset_faults();
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ int setup_ok = 1;
+ for (int i = 0; setup_ok && i < GENERATION_SIZE; i++) {
+ char path[512];
+ char source[128];
+ snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
+ snprintf(source, sizeof(source), "def Before%02d():\n return %d\n", i, i);
+ setup_ok = th_write_file(path, source) == 0;
+ }
- teardown_test_repo();
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/incremental-cache.db", tmp);
+ int first_rc = -1;
+ int baseline_before = -1;
+ int baseline_after = -1;
+ if (setup_ok) {
+ cbm_pipeline_t *first = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (first) {
+ first_rc = cbm_pipeline_run(first);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(first),
+ GENERATION_SIZE, &baseline_before, &baseline_after);
+ cbm_pipeline_free(first);
+ }
+ }
+
+ int edit_ok = setup_ok && first_rc == 0;
+ for (int i = 0; edit_ok && i < GENERATION_SIZE; i++) {
+ char path[512];
+ char source[160];
+ snprintf(path, sizeof(path), "%s/generation_%02d.py", tmp, i);
+ snprintf(source, sizeof(source),
+ "def After%02d():\n return %d\n# edited generation %02d\n", i, i, i);
+ edit_ok = th_write_file(path, source) == 0;
+ }
+
+ int second_rc = -1;
+ int second_before = -1;
+ int second_after = -1;
+ if (edit_ok) {
+ cbm_pipeline_incremental_test_fail_result_cache_alloc_once();
+ cbm_pipeline_incremental_test_force_legacy_partial_once();
+ cbm_pipeline_t *second = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (second) {
+ second_rc = cbm_pipeline_run(second);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(second),
+ GENERATION_SIZE, &second_before, &second_after);
+ cbm_pipeline_free(second);
+ }
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+
+ int third_rc = -1;
+ int retry_before = -1;
+ int retry_after = -1;
+ if (edit_ok) {
+ cbm_pipeline_t *third = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ if (third) {
+ third_rc = cbm_pipeline_run(third);
+ observe_incremental_generation(db_path, cbm_pipeline_project_name(third),
+ GENERATION_SIZE, &retry_before, &retry_after);
+ cbm_pipeline_free(third);
+ }
+ }
+ cbm_pipeline_incremental_test_reset_faults();
+
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ bool second_is_preserved_failure = second_rc == CBM_PIPELINE_ABORT_PRESERVE_DB &&
+ second_before == GENERATION_SIZE && second_after == 0;
+ if (!second_is_preserved_failure) {
+ printf(" incremental cache failure diagnostic: rc=%d before=%d after=%d\n", second_rc,
+ second_before, second_after);
+ }
+
+ ASSERT_TRUE(setup_ok);
+ ASSERT_EQ(first_rc, 0);
+ ASSERT_EQ(baseline_before, GENERATION_SIZE);
+ ASSERT_EQ(baseline_after, 0);
+ ASSERT_TRUE(edit_ok);
+ ASSERT_TRUE(second_is_preserved_failure);
+ ASSERT_EQ(third_rc, 0);
+ ASSERT_EQ(retry_before, 0);
+ ASSERT_EQ(retry_after, GENERATION_SIZE);
PASS();
}
+#endif
-/* TS/JS receiver-aware weak-strategy suppression (#592/#606 direction; Perl
- * precedent #477). A member call x.foo() whose receiver TYPE the TS-LSP cannot
- * resolve (a regex literal `re.test()`) must NOT be bound to a same-named
- * project method by a weak short-name strategy — that fabricates a CALLS edge.
- * Type-resolved receivers (`c.test()` on a typed SalesforceRestClient) and bare
- * local calls must still resolve. < 50 files → sequential path (pass_calls.c).
- * RED before the fix: checkFormat->test exists via unique_name/suffix_match. */
-static void write_temp_file(const char *dir, const char *name, const char *content);
TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_tsjs_recv_XXXXXX");
@@ -1129,6 +3887,179 @@ TEST(pipeline_tsjs_receiver_parallel_keeps_service_edges) {
PASS();
}
+/* Reproduce-first: pass_parallel's fused cross-LSP eligibility currently counts
+ * only parser-backed calls/call references. A Python binary operator has no
+ * parser CBMCall; its __add__ semantic record and carrier are created together
+ * only by the cross resolver. Consequently combine.py looks like it has zero
+ * semantic sites and the fused pass skips it before that carrier can exist.
+ *
+ * `visible()` is deliberately in a different file. Its ordinary method-call
+ * carrier makes THAT file cross-LSP eligible and its lsp_* edge proves that the
+ * Alpha definition, import map, shared registry, and cross resolver are all
+ * healthy. Putting the control call in combine.py would hide the bug by making
+ * the broken file eligible. The 52 fillers plus three fixture files exceed
+ * MIN_FILES_FOR_PARALLEL (50), and CBM_WORKERS=4 forces the production fused
+ * path independent of host core count. */
+TEST(pipeline_parallel_python_cross_only_dunder_gets_synthetic_carrier) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_py_syn_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "alpha.py",
+ "class Alpha:\n"
+ " def __add__(self, other):\n"
+ " return self\n");
+ write_temp_file(tmp, "visible.py",
+ "from .alpha import Alpha\n\n"
+ "def visible(left: Alpha, right: Alpha):\n"
+ " return left.__add__(right)\n");
+ write_temp_file(tmp, "combine.py",
+ "from .alpha import Alpha\n\n"
+ "def combine(left: Alpha, right: Alpha):\n"
+ " return left + right\n");
+ for (int i = 0; i < 52; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "py_pad_%02d.py", i);
+ snprintf(body, sizeof(body), "def py_pad_%02d():\n return %d\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/python_parallel.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ int run_rc = cbm_pipeline_run(p);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ bool store_opened = s != NULL;
+ bool control_lsp = false;
+ bool combine_to_add = false;
+ if (s) {
+ control_lsp =
+ cross_file_call_has_strategy(s, project, "visible", "__add__", "\"strategy\":\"lsp_");
+ combine_to_add = cross_file_call_exists(s, project, "combine", "__add__");
+ cbm_store_close(s);
+ }
+
+ cbm_pipeline_free(p);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(store_opened);
+ ASSERT_TRUE(control_lsp); /* non-vacuity: cross LSP + target are healthy */
+ ASSERT_TRUE(combine_to_add); /* RED: fused eligibility skips combine.py */
+ PASS();
+}
+
+/* Same fused-eligibility hole for Rust built-in macro arguments. The parser
+ * exposes format! but not render() inside its token tree. Per-file LSP already
+ * qualifies every parser-backed site in hidden.rs, so the fused heuristic sees
+ * no remaining work and never runs the cross pass that would discover both the
+ * semantic render target and its exact synthetic carrier.
+ *
+ * The exact same 55-file fixture is indexed once through the sequential path
+ * first. A hidden() -> render CALLS edge there is a strong non-vacuity control:
+ * only the sequential cross-LSP pass can discover both the macro-hidden call
+ * and its synthetic carrier. The parallel run must preserve that result. */
+TEST(pipeline_parallel_rust_cross_only_macro_hidden_gets_synthetic_carrier) {
+ char tmp[256];
+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_rs_syn_par_XXXXXX");
+ if (!cbm_mkdtemp(tmp)) {
+ FAIL("tmpdir");
+ }
+
+ write_temp_file(tmp, "lib.rs", "pub fn render() -> &'static str { \"ok\" }\n");
+ write_temp_file(tmp, "main.rs",
+ "mod lib;\n\n"
+ "pub fn hidden() -> String { format!(\"{}\", lib::render()) }\n");
+ for (int i = 0; i < 53; i++) {
+ char name[64];
+ char body[128];
+ snprintf(name, sizeof(name), "rust_pad_%02d.rs", i);
+ snprintf(body, sizeof(body), "pub fn rust_pad_%02d() -> i32 { %d }\n", i, i);
+ write_temp_file(tmp, name, body);
+ }
+
+ char *old_workers = getenv("CBM_WORKERS");
+ char *saved_workers = old_workers ? strdup(old_workers) : NULL;
+ char *old_single = getenv("CBM_INDEX_SINGLE_THREAD");
+ char *saved_single = old_single ? strdup(old_single) : NULL;
+
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", "1", 1);
+ char seq_db_path[512];
+ snprintf(seq_db_path, sizeof(seq_db_path), "%s/rust_sequential.db", tmp);
+ cbm_pipeline_t *seq = cbm_pipeline_new(tmp, seq_db_path, CBM_MODE_FULL);
+ int seq_run_rc = seq ? cbm_pipeline_run(seq) : -1;
+ const char *seq_project = seq ? cbm_pipeline_project_name(seq) : NULL;
+ cbm_store_t *seq_store = cbm_store_open_path(seq_db_path);
+ bool seq_store_opened = seq_store != NULL;
+ bool seq_hidden_to_render = false;
+ if (seq_store && seq_project) {
+ seq_hidden_to_render = cross_file_call_exists(seq_store, seq_project, "hidden", "render");
+ cbm_store_close(seq_store);
+ }
+ cbm_pipeline_free(seq);
+
+ /* The parallel half must not inherit a caller-level single-thread override,
+ * even when the surrounding test process was launched with one. Restore it
+ * after both halves complete. */
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ cbm_setenv("CBM_WORKERS", "4", 1);
+
+ char db_path[512];
+ snprintf(db_path, sizeof(db_path), "%s/rust_parallel.db", tmp);
+ cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL);
+ ASSERT_NOT_NULL(p);
+ int run_rc = cbm_pipeline_run(p);
+ const char *project = cbm_pipeline_project_name(p);
+ cbm_store_t *s = cbm_store_open_path(db_path);
+ bool store_opened = s != NULL;
+ bool render_target_present = false;
+ bool hidden_to_render = false;
+ if (s) {
+ render_target_present = count_nodes_named(s, project, "render") > 0;
+ hidden_to_render = cross_file_call_exists(s, project, "hidden", "render");
+ cbm_store_close(s);
+ }
+
+ cbm_pipeline_free(p);
+ if (saved_workers) {
+ cbm_setenv("CBM_WORKERS", saved_workers, 1);
+ free(saved_workers);
+ } else {
+ cbm_unsetenv("CBM_WORKERS");
+ }
+ if (saved_single) {
+ cbm_setenv("CBM_INDEX_SINGLE_THREAD", saved_single, 1);
+ free(saved_single);
+ } else {
+ cbm_unsetenv("CBM_INDEX_SINGLE_THREAD");
+ }
+ th_rmtree(tmp);
+
+ ASSERT_EQ(seq_run_rc, 0);
+ ASSERT_TRUE(seq_store_opened);
+ ASSERT_TRUE(seq_hidden_to_render); /* same fixture is semantically resolvable */
+ ASSERT_EQ(run_rc, 0);
+ ASSERT_TRUE(store_opened);
+ ASSERT_TRUE(render_target_present); /* target is present in the parallel graph */
+ ASSERT_TRUE(hidden_to_render); /* RED: fused eligibility skips hidden.rs */
+ PASS();
+}
+
/* Native `fetch()` (#856), sequential path (< 50 files → pass_calls.c). A bare
* unqualified call to the global fetch API has no import and no local
* definition anywhere in this project, so registry resolution comes back
@@ -1859,7 +4790,7 @@ TEST(calls_edge_carries_call_site_line) {
TEST(usages_kotlin_creates_edges) {
/* Port of TestPassUsagesKotlinCreatesEdges.
- * Kotlin source with callback reference → USAGE edge. */
+ * Explicit Kotlin callable syntax produces CALL_REFERENCE, not USAGE. */
const char *kt_source = "fun process(data: String): String {\n"
" return data\n"
"}\n\n"
@@ -1883,15 +4814,44 @@ TEST(usages_kotlin_creates_edges) {
ASSERT_NOT_NULL(s);
const char *project = cbm_pipeline_project_name(p);
- /* Check USAGE edges exist (Kotlin extraction may or may not produce them
- * depending on extraction support — just verify no crash and valid counts) */
+ /* The explicit reference is resolved and classified exclusively. */
cbm_edge_t *edges = NULL;
int edge_count = 0;
+ rc = cbm_store_find_edges_by_type(s, project, "CALL_REFERENCE", &edges, &edge_count);
+ ASSERT_EQ(rc, CBM_STORE_OK);
+ bool found_reference = false;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0}, tgt = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &src) == CBM_STORE_OK &&
+ cbm_store_find_node_by_id(s, edges[i].target_id, &tgt) == CBM_STORE_OK && src.name &&
+ tgt.name && strcmp(src.name, "register") == 0 && strcmp(tgt.name, "process") == 0) {
+ found_reference = true;
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&tgt);
+ }
+ if (edges)
+ cbm_store_free_edges(edges, edge_count);
+ ASSERT_TRUE(found_reference);
+
+ edges = NULL;
+ edge_count = 0;
rc = cbm_store_find_edges_by_type(s, project, "USAGE", &edges, &edge_count);
ASSERT_EQ(rc, CBM_STORE_OK);
- /* Note: The Go test just logs, doesn't assert — same behavior here */
+ bool duplicated_as_usage = false;
+ for (int i = 0; i < edge_count; i++) {
+ cbm_node_t src = {0}, tgt = {0};
+ if (cbm_store_find_node_by_id(s, edges[i].source_id, &src) == CBM_STORE_OK &&
+ cbm_store_find_node_by_id(s, edges[i].target_id, &tgt) == CBM_STORE_OK && src.name &&
+ tgt.name && strcmp(src.name, "register") == 0 && strcmp(tgt.name, "process") == 0) {
+ duplicated_as_usage = true;
+ }
+ cbm_node_free_fields(&src);
+ cbm_node_free_fields(&tgt);
+ }
if (edges)
cbm_store_free_edges(edges, edge_count);
+ ASSERT_FALSE(duplicated_as_usage);
cbm_store_close(s);
cbm_pipeline_free(p);
@@ -2996,6 +5956,231 @@ TEST(git_context_linked_worktree) {
PASS();
}
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+static int branch_head_match_count(cbm_store_t *store, const char *project, const char *head_sha) {
+ cbm_node_t *branches = NULL;
+ int branch_count = 0;
+ if (!store || !project || !head_sha ||
+ cbm_store_find_nodes_by_label(store, project, "Branch", &branches, &branch_count) !=
+ CBM_STORE_OK) {
+ return -1;
+ }
+ int matches = 0;
+ for (int i = 0; i < branch_count; i++) {
+ if (branches[i].properties_json && strstr(branches[i].properties_json, head_sha)) {
+ matches++;
+ }
+ }
+ cbm_store_free_nodes(branches, branch_count);
+ return matches;
+}
+
+/* Git context is graph input even when every repository file is unchanged.
+ * Construct the second pipeline before moving HEAD so the test also proves
+ * that run start refreshes the snapshot captured by cbm_pipeline_new(). */
+TEST(pipeline_git_context_change_forces_full_and_refreshes_branch) {
+ if (!git_available()) {
+ FAIL("git unavailable");
+ }
+
+ char tmp[256];
+ char *created = th_mktempdir("cbm_manifest_git_context");
+ ASSERT_NOT_NULL(created);
+ snprintf(tmp, sizeof(tmp), "%s", created);
+
+ char repo[512], db_path[512], cmd[2048];
+ snprintf(repo, sizeof(repo), "%s/repo", tmp);
+ snprintf(db_path, sizeof(db_path), "%s/context.db", tmp);
+ ASSERT_EQ(th_mkdir_p(repo), 0);
+ ASSERT_EQ(th_write_file(TH_PATH(repo, "stable.py"), "def StableGitContext():\n return 1\n"),
+ 0);
+ const char *null_dev = test_null_dev();
+ snprintf(cmd, sizeof(cmd), "git -C \"%s\" init >%s 2>&1", repo, null_dev);
+ ASSERT_EQ(run_cmd(cmd), 0);
+ snprintf(cmd, sizeof(cmd), "git -C \"%s\" add stable.py >%s 2>&1", repo, null_dev);
+ ASSERT_EQ(run_cmd(cmd), 0);
+ snprintf(cmd, sizeof(cmd),
+ "git -C \"%s\" -c user.name=\"CBM Test\" "
+ "-c user.email=\"[email protected]\" commit -m \"initial\" >%s 2>&1",
+ repo, null_dev);
+ ASSERT_EQ(run_cmd(cmd), 0);
+
+ cbm_git_context_t initial_ctx = {0};
+ ASSERT_EQ(cbm_git_context_resolve(repo, &initial_ctx), 0);
+ ASSERT_NOT_NULL(initial_ctx.head_sha);
+ char initial_head[128];
+ snprintf(initial_head, sizeof(initial_head), "%s", initial_ctx.head_sha);
+ cbm_git_context_free(&initial_ctx);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(baseline);
+ ASSERT_EQ(cbm_pipeline_run(baseline), 0);
+ char project[256];
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+
+ cbm_pipeline_t *after_head_move = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(after_head_move);
+ snprintf(cmd, sizeof(cmd),
+ "git -C \"%s\" -c user.name=\"CBM Test\" "
+ "-c user.email=\"[email protected]\" commit --allow-empty "
+ "-m \"head-only change\" >%s 2>&1",
+ repo, null_dev);
+ ASSERT_EQ(run_cmd(cmd), 0);
+ cbm_git_context_t changed_ctx = {0};
+ ASSERT_EQ(cbm_git_context_resolve(repo, &changed_ctx), 0);
+ ASSERT_NOT_NULL(changed_ctx.head_sha);
+ char changed_head[128];
+ snprintf(changed_head, sizeof(changed_head), "%s", changed_ctx.head_sha);
+ cbm_git_context_free(&changed_ctx);
+ ASSERT_TRUE(strcmp(initial_head, changed_head) != 0);
+
+ cbm_pipeline_incremental_test_reset_faults();
+ int changed_rc = cbm_pipeline_run(after_head_move);
+ cbm_incremental_route_t changed_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(after_head_move);
+
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ int changed_branch_matches = store ? branch_head_match_count(store, project, changed_head) : -1;
+ int stale_branch_matches = store ? branch_head_match_count(store, project, initial_head) : -1;
+ cbm_file_hash_t git_input = {0};
+ int git_input_rc =
+ store ? cbm_store_get_file_hash(
+ store, project, ".codebase-memory/.semantic-input/git-context-v1", &git_input)
+ : CBM_STORE_NOT_FOUND;
+ cbm_store_clear_file_hash(&git_input);
+ if (store) {
+ cbm_store_close(store);
+ }
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ ASSERT_NOT_NULL(unchanged);
+ int unchanged_rc = cbm_pipeline_run(unchanged);
+ cbm_incremental_route_t unchanged_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(unchanged);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(changed_rc, 0);
+ ASSERT_EQ(changed_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(changed_branch_matches, 1);
+ ASSERT_EQ(stale_branch_matches, 0);
+ ASSERT_EQ(git_input_rc, CBM_STORE_OK);
+ ASSERT_EQ(unchanged_rc, 0);
+ ASSERT_EQ(unchanged_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ PASS();
+}
+
+/* The global extension config lives outside the repository but changes both
+ * discovery and parsing. Its exact consumed bytes therefore belong to the
+ * same semantic generation as the graph they selected. */
+TEST(pipeline_global_extension_config_change_forces_full) {
+ char tmp[256];
+ char *created = th_mktempdir("cbm_manifest_global_config");
+ ASSERT_NOT_NULL(created);
+ snprintf(tmp, sizeof(tmp), "%s", created);
+
+ char repo[512], config_root[512], app_dir[768], config_path[1024], db_path[512];
+ snprintf(repo, sizeof(repo), "%s/repo", tmp);
+ snprintf(config_root, sizeof(config_root), "%s/config-root", tmp);
+ snprintf(app_dir, sizeof(app_dir), "%s/codebase-memory-mcp", config_root);
+ snprintf(config_path, sizeof(config_path), "%s/config.json", app_dir);
+ snprintf(db_path, sizeof(db_path), "%s/config.db", tmp);
+ ASSERT_EQ(th_mkdir_p(repo), 0);
+ ASSERT_EQ(th_mkdir_p(app_dir), 0);
+ ASSERT_EQ(th_write_file(TH_PATH(repo, "fixture.cbmfixture"),
+ "def GlobalExtensionTarget():\n return 1\n"),
+ 0);
+ ASSERT_EQ(th_write_file(config_path, "{\"extra_extensions\":{\".cbmfixture\":\"python\"}}\n"),
+ 0);
+
+#ifdef _WIN32
+ const char *env_name = "APPDATA";
+#else
+ const char *env_name = "XDG_CONFIG_HOME";
+#endif
+ char old_env[CBM_SZ_1K] = {0};
+ bool had_old_env = cbm_safe_getenv(env_name, old_env, sizeof(old_env), NULL) != NULL;
+
+ int setenv_rc = cbm_setenv(env_name, config_root, 1);
+ int baseline_rc = -1;
+ int initial_nodes = -1;
+ int changed_rc = -1;
+ cbm_incremental_route_t changed_route = CBM_INCREMENTAL_ROUTE_NONE;
+ int changed_nodes = -1;
+ int config_input_rc = CBM_STORE_NOT_FOUND;
+ int unchanged_rc = -1;
+ cbm_incremental_route_t unchanged_route = CBM_INCREMENTAL_ROUTE_NONE;
+ char project[256] = {0};
+
+ if (setenv_rc == 0) {
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *baseline = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ if (baseline) {
+ baseline_rc = cbm_pipeline_run(baseline);
+ snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(baseline));
+ cbm_pipeline_free(baseline);
+ }
+ cbm_store_t *baseline_store = cbm_store_open_path(db_path);
+ if (baseline_store) {
+ initial_nodes = named_node_count(baseline_store, project, "GlobalExtensionTarget");
+ cbm_store_close(baseline_store);
+ }
+
+ if (th_write_file(config_path, "{\"extra_extensions\":{\".cbmfixture\":\"json\"}}\n") ==
+ 0) {
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *changed = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ if (changed) {
+ changed_rc = cbm_pipeline_run(changed);
+ changed_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(changed);
+ }
+ cbm_store_t *changed_store = cbm_store_open_path(db_path);
+ if (changed_store) {
+ changed_nodes = named_node_count(changed_store, project, "GlobalExtensionTarget");
+ cbm_file_hash_t config_input = {0};
+ config_input_rc = cbm_store_get_file_hash(
+ changed_store, project,
+ ".codebase-memory/.semantic-input/global-extension-config-v1", &config_input);
+ cbm_store_clear_file_hash(&config_input);
+ cbm_store_close(changed_store);
+ }
+
+ cbm_pipeline_incremental_test_reset_faults();
+ cbm_pipeline_t *unchanged = cbm_pipeline_new(repo, db_path, CBM_MODE_FAST);
+ if (unchanged) {
+ unchanged_rc = cbm_pipeline_run(unchanged);
+ unchanged_route = cbm_pipeline_incremental_test_last_route();
+ cbm_pipeline_free(unchanged);
+ }
+ }
+ }
+
+ if (had_old_env) {
+ cbm_setenv(env_name, old_env, 1);
+ } else {
+ cbm_unsetenv(env_name);
+ }
+ cbm_set_user_lang_config(NULL);
+ cbm_pipeline_incremental_test_reset_faults();
+ th_rmtree(tmp);
+
+ ASSERT_EQ(setenv_rc, 0);
+ ASSERT_EQ(baseline_rc, 0);
+ ASSERT_EQ(initial_nodes, 1);
+ ASSERT_EQ(changed_rc, 0);
+ ASSERT_EQ(changed_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
+ ASSERT_EQ(changed_nodes, 0);
+ ASSERT_EQ(config_input_rc, CBM_STORE_OK);
+ ASSERT_EQ(unchanged_rc, 0);
+ ASSERT_EQ(unchanged_route, CBM_INCREMENTAL_ROUTE_NOOP);
+ PASS();
+}
+#endif
+
TEST(project_name_uniqueness) {
/* Port of TestProjectNameUniqueness */
char *a = cbm_project_name_from_path("/tmp/bench/zig/lib/std");
@@ -5687,7 +8872,7 @@ TEST(incremental_detects_changed_file) {
PASS();
}
-TEST(incremental_aborts_when_previous_coverage_is_unreadable) {
+TEST(full_reindex_recovers_when_previous_coverage_is_unreadable) {
if (setup_incremental_repo() != 0) {
FAIL("setup failed");
}
@@ -5718,14 +8903,21 @@ TEST(incremental_aborts_when_previous_coverage_is_unreadable) {
p = cbm_pipeline_new(g_incr_tmpdir, g_incr_dbpath, CBM_MODE_FULL);
ASSERT_NOT_NULL(p);
- ASSERT_TRUE(cbm_pipeline_run(p) != 0);
+ ASSERT_EQ(cbm_pipeline_run(p), 0);
cbm_pipeline_free(p);
- /* Failure happens before the dump/replacement boundary, preserving the
- * original graph rather than publishing a falsely complete generation. */
+ /* An exact-manifest delta routes to an isolated full generation, which
+ * does not depend on the damaged coverage table and repairs it atomically. */
s = cbm_store_open_path(g_incr_dbpath);
ASSERT_NOT_NULL(s);
- ASSERT_EQ(cbm_store_count_nodes(s, project), nodes_before);
+ ASSERT_GT(cbm_store_count_nodes(s, project), nodes_before);
+ cbm_node_t *recovered = NULL;
+ int recovered_count = 0;
+ ASSERT_EQ(
+ cbm_store_find_nodes_by_name(s, project, "MustNotBeIndexed", &recovered, &recovered_count),
+ CBM_STORE_OK);
+ ASSERT_EQ(recovered_count, 1);
+ cbm_store_free_nodes(recovered, recovered_count);
cbm_store_close(s);
free(project);
@@ -6920,8 +10112,21 @@ SUITE(pipeline) {
/* Calls pass */
RUN_TEST(pipeline_calls_resolution);
RUN_TEST(pipeline_incremental_preserves_cross_file_calls);
+ RUN_TEST(pipeline_objectscript_export_preserves_calls_sequential_parallel);
+ RUN_TEST(pipeline_objectscript_export_incremental_matches_full_relationships);
+ RUN_TEST(pipeline_objectscript_export_aggregate_exceeds_arena_block_table);
+ RUN_TEST(pipeline_env_access_configures_sequential_parallel_parity);
+ RUN_TEST(pipeline_call_reference_sequential_parallel_edge_set_parity);
+ RUN_TEST(pipeline_incremental_cross_file_call_reference_matches_fresh_full);
+ RUN_TEST(pipeline_incremental_changed_target_invalidates_stale_inbound_call_reference);
+ RUN_TEST(pipeline_incremental_parallel_registry_nodes_advance_shared_ids);
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ RUN_TEST(pipeline_incremental_parallel_result_cache_alloc_failure_preserves_db_and_retries);
+#endif
RUN_TEST(pipeline_tsjs_receiver_suppresses_weak_method_edge);
RUN_TEST(pipeline_tsjs_receiver_parallel_keeps_service_edges);
+ RUN_TEST(pipeline_parallel_python_cross_only_dunder_gets_synthetic_carrier);
+ RUN_TEST(pipeline_parallel_rust_cross_only_macro_hidden_gets_synthetic_carrier);
RUN_TEST(pipeline_native_fetch_classified_as_http_calls);
RUN_TEST(pipeline_native_fetch_parallel_classified_as_http_calls);
RUN_TEST(pipeline_local_fetch_shadow_not_classified_as_http);
@@ -7092,7 +10297,7 @@ SUITE(pipeline) {
/* Incremental */
RUN_TEST(incremental_full_then_noop);
RUN_TEST(incremental_detects_changed_file);
- RUN_TEST(incremental_aborts_when_previous_coverage_is_unreadable);
+ RUN_TEST(full_reindex_recovers_when_previous_coverage_is_unreadable);
RUN_TEST(incremental_detects_deleted_file);
RUN_TEST(incremental_new_file_added);
RUN_TEST(incremental_fast_preserves_mode_skipped_tools_dir);
@@ -7158,3 +10363,29 @@ SUITE(pipeline) {
RUN_TEST(project_name_special_chars);
RUN_TEST(project_name_trailing_slash);
}
+
+/* Focused semantic-manifest and publication contracts. Kept separate from the
+ * broad pipeline suite so RED/GREEN iterations exercise only this boundary;
+ * the default all-suite run still executes it. */
+SUITE(pipeline_semantic_manifest_repro) {
+ RUN_TEST(pipeline_incremental_repoints_call_reference_without_stale_edge);
+ RUN_TEST(pipeline_incremental_tsconfig_alias_change_matches_fresh_full);
+#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
+ RUN_TEST(pipeline_git_context_change_forces_full_and_refreshes_branch);
+ RUN_TEST(pipeline_global_extension_config_change_forces_full);
+ RUN_TEST(pipeline_source_mutation_before_publication_preserves_previous_generation);
+ RUN_TEST(pipeline_source_addition_before_publication_preserves_previous_generation);
+ RUN_TEST(pipeline_tsconfig_mutation_before_publication_preserves_previous_generation);
+ RUN_TEST(pipeline_exact_inputs_migrate_coverage_metadata_and_index_mode);
+ RUN_TEST(pipeline_existing_artifact_refreshes_after_default_forced_full_reindex);
+ RUN_TEST(pipeline_full_cancel_after_predump_preserves_previous_generation);
+ RUN_TEST(pipeline_full_cancel_after_destination_prepare_preserves_previous_generation);
+ RUN_TEST(pipeline_full_persist_failure_after_stage_dump_preserves_previous_generation);
+ RUN_TEST(pipeline_incremental_persist_failure_preserves_previous_generation_and_retries);
+ RUN_TEST(pipeline_incremental_successful_publication_preserves_adr);
+ RUN_TEST(pipeline_full_adr_capture_failure_preserves_previous_generation);
+ RUN_TEST(pipeline_semantic_manifest_rejects_non_directory_root);
+ RUN_TEST(pipeline_full_reindex_quarantines_corrupt_destination_without_overwrite);
+ RUN_TEST(pipeline_full_reindex_replaces_legacy_schema_without_quarantine);
+#endif
+}
diff --git a/tests/test_py_lsp.c b/tests/test_py_lsp.c
index 818e75f59..c803a91bd 100644
--- a/tests/test_py_lsp.c
+++ b/tests/test_py_lsp.c
@@ -10,6 +10,8 @@
#include "test_framework.h"
#include "cbm.h"
#include "lsp/py_lsp.h"
+#include "pipeline/lsp_resolve.h"
+#include "pipeline/pass_lsp_cross.h"
/* ── Helpers — same shape as test_go_lsp.c ──────────────────────── */
@@ -515,6 +517,32 @@ static int find_resolved_arr(const CBMResolvedCallArray *arr, const char *caller
return -1;
}
+typedef struct {
+ int target_count;
+ int first_site_count;
+ int second_site_count;
+} PyResolvedSiteCounts;
+
+static PyResolvedSiteCounts count_invocation_sites(const CBMResolvedCallArray *arr,
+ const char *caller_sub, const char *callee_sub,
+ uint32_t first_start, uint32_t first_end,
+ uint32_t second_start, uint32_t second_end) {
+ PyResolvedSiteCounts counts = {0};
+ 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 ||
+ !strstr(rc->caller_qn, caller_sub) || !strstr(rc->callee_qn, callee_sub)) {
+ continue;
+ }
+ counts.target_count++;
+ if (rc->site_start_byte == first_start && rc->site_end_byte == first_end)
+ counts.first_site_count++;
+ if (rc->site_start_byte == second_start && rc->site_end_byte == second_end)
+ counts.second_site_count++;
+ }
+ return counts;
+}
+
TEST(pylsp_crossfile_method_dispatch) {
/* file svc.py defines class RedisStore with Get(); file main.py calls
* the method on a typed parameter. Reuses CBMLSPDef to feed the
@@ -544,8 +572,8 @@ TEST(pylsp_crossfile_method_dispatch) {
cbm_arena_init(&arena);
CBMResolvedCallArray out = {0};
- cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.main",
- defs, 2, imp_names, imp_qns, 1, NULL, &out);
+ cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.main", defs, 2, imp_names,
+ imp_qns, 1, NULL, &out, NULL);
ASSERT_GTE(find_resolved_arr(&out, "process", "Get"), 0);
cbm_arena_destroy(&arena);
@@ -595,8 +623,8 @@ TEST(pylsp_fused_self_attr_chain_via_overlay) {
" def run(self):\n"
" return self.b.work()\n";
CBMResolvedCallArray out = {0};
- cbm_run_py_lsp_cross_with_registry(&arena, src, (int)strlen(src), "test.mod", reg, NULL, NULL, 0,
- NULL, &out);
+ cbm_run_py_lsp_cross_with_registry(&arena, src, (int)strlen(src), "test.mod", reg, NULL, NULL,
+ 0, NULL, &out, NULL);
/* Overlay preserves the attribute-chain edge. */
ASSERT_GTE(find_resolved_arr(&out, "run", "work"), 0);
@@ -640,7 +668,7 @@ TEST(pylsp_crossfile_classmethod_on_class_issue228) {
CBMResolvedCallArray out = {0};
cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.main", defs, 2, imp_names,
- imp_qns, 1, NULL, &out);
+ imp_qns, 1, NULL, &out, NULL);
ASSERT_GTE(find_resolved_arr(&out, "run_plain_flow", "build_from_text"), 0);
cbm_arena_destroy(&arena);
@@ -689,8 +717,8 @@ TEST(pylsp_crossfile_inheritance) {
cbm_arena_init(&arena);
CBMResolvedCallArray out = {0};
- cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.main",
- defs, 4, imp_names, imp_qns, 1, NULL, &out);
+ cbm_run_py_lsp_cross(&arena, source, (int)strlen(source), "test.main", defs, 4, imp_names,
+ imp_qns, 1, NULL, &out, NULL);
ASSERT_GTE(find_resolved_arr(&out, "go", "shared"), 0);
cbm_arena_destroy(&arena);
@@ -759,15 +787,452 @@ TEST(pylsp_batch_two_files) {
PASS();
}
+static int pylsp_exact_reference_count(const CBMResolvedCallArray *out, const char *caller,
+ const char *callee_qn, const char *reason,
+ uint32_t site_start, uint32_t site_end) {
+ int count = 0;
+ for (int i = 0; out && i < out->count; i++) {
+ const CBMResolvedCall *resolved = &out->items[i];
+ if (resolved->kind == CBM_RESOLVED_CALL_REFERENCE && resolved->caller_qn &&
+ strstr(resolved->caller_qn, caller) && resolved->callee_qn &&
+ strcmp(resolved->callee_qn, callee_qn) == 0 &&
+ resolved->confidence >= CBM_LSP_CONFIDENCE_FLOOR &&
+ resolved->site_start_byte == site_start && resolved->site_end_byte == site_end &&
+ (!reason || (resolved->reason && strcmp(resolved->reason, reason) == 0))) {
+ count++;
+ }
+ }
+ return count;
+}
+
+typedef struct {
+ int first_target;
+ int second_target;
+} PyImportReferenceCounts;
+
+static PyImportReferenceCounts pylsp_import_reference_counts(
+ const char *source, const char *local_name, const char *import_qn, const char *first_target_qn,
+ const char *second_target_qn) {
+ PyImportReferenceCounts counts = {0};
+ const char *call = strstr(source, " accept(");
+ if (!call)
+ return counts;
+ uint32_t site_start = (uint32_t)(call - source) + (uint32_t)strlen(" accept(");
+ uint32_t site_end = site_start + (uint32_t)strlen(local_name);
+
+ CBMLSPDef defs[4];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = first_target_qn;
+ defs[0].short_name = cbm_lsp_bare_segment(first_target_qn);
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "project.target";
+ int def_count = 1;
+ if (second_target_qn) {
+ defs[1].qualified_name = second_target_qn;
+ defs[1].short_name = cbm_lsp_bare_segment(second_target_qn);
+ defs[1].label = "Function";
+ defs[1].def_module_qn = "project.target";
+ def_count++;
+ }
+ defs[def_count].qualified_name = "project.use.accept";
+ defs[def_count].short_name = "accept";
+ defs[def_count].label = "Function";
+ defs[def_count].def_module_qn = "project.use";
+ def_count++;
+ defs[def_count].qualified_name = "project.use.crossArgument";
+ defs[def_count].short_name = "crossArgument";
+ defs[def_count].label = "Function";
+ defs[def_count].def_module_qn = "project.use";
+ def_count++;
+
+ const char *import_names[] = {local_name};
+ const char *import_qns[] = {import_qn};
+ CBMBatchPyLSPFile file = {0};
+ file.source = source;
+ file.source_len = (int)strlen(source);
+ file.module_qn = "project.use";
+ file.defs = defs;
+ file.def_count = def_count;
+ file.import_names = import_names;
+ file.import_qns = import_qns;
+ file.import_count = 1;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMResolvedCallArray out = {0};
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+ counts.first_target = pylsp_exact_reference_count(
+ &out, "crossArgument", first_target_qn, local_name, site_start, site_end);
+ if (second_target_qn) {
+ counts.second_target = pylsp_exact_reference_count(
+ &out, "crossArgument", second_target_qn, local_name, site_start, site_end);
+ }
+ cbm_arena_destroy(&arena);
+ return counts;
+}
+
+TEST(pylsp_from_import_alias_equal_module_leaf_targets_imported_member) {
+ static const char source[] = "from target import handler as target\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(target)\n";
+ PyImportReferenceCounts counts = pylsp_import_reference_counts(
+ source, "target", "project.target", "project.target.handler", "project.target.target");
+ ASSERT_EQ(counts.first_target, 1);
+ ASSERT_EQ(counts.second_target, 0);
+ PASS();
+}
+
+TEST(pylsp_project_prefixed_direct_alias_same_tail_is_not_from_import_reference) {
+ static const char source[] = "import target.handler as handler\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(handler)\n";
+ PyImportReferenceCounts counts = pylsp_import_reference_counts(
+ source, "handler", "project.target.handler", "project.target.handler", NULL);
+ ASSERT_EQ(counts.first_target, 0);
+ PASS();
+}
+
+TEST(pylsp_competing_import_forms_for_same_local_fail_closed) {
+ static const char source[] = "from target import handler as callback\n"
+ "import target.handler as callback\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(callback)\n";
+ PyImportReferenceCounts counts = pylsp_import_reference_counts(
+ source, "callback", "project.target", "project.target.handler", NULL);
+ ASSERT_EQ(counts.first_target, 0);
+ PASS();
+}
+
+TEST(pylsp_later_plain_import_rebinding_same_local_fails_closed) {
+ static const char source[] = "from target import handler as target\n"
+ "import target\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(target)\n";
+ PyImportReferenceCounts counts = pylsp_import_reference_counts(
+ source, "target", "project.target.handler", "project.target.handler", NULL);
+ ASSERT_EQ(counts.first_target, 0);
+ PASS();
+}
+
+TEST(pylsp_batch_cross_file_callable_value_preserves_exact_reference_site) {
+ static const char source[] = "from target import handler\n"
+ "def accept(callback):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(handler)\n";
+ const char *argument = strstr(source, "accept(handler)");
+ ASSERT_NOT_NULL(argument);
+ uint32_t site_start = (uint32_t)(argument - source) + 7U;
+ uint32_t site_end = site_start + (uint32_t)strlen("handler");
+
+ CBMLSPDef defs[3];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "target.handler";
+ defs[0].short_name = "handler";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "target";
+ defs[1].qualified_name = "use.accept";
+ defs[1].short_name = "accept";
+ defs[1].label = "Function";
+ defs[1].def_module_qn = "use";
+ defs[2].qualified_name = "use.crossArgument";
+ defs[2].short_name = "crossArgument";
+ defs[2].label = "Function";
+ defs[2].def_module_qn = "use";
+ const char *import_names[] = {"handler"};
+ const char *import_qns[] = {"target.handler"};
+
+ CBMBatchPyLSPFile file;
+ memset(&file, 0, sizeof(file));
+ file.source = source;
+ file.source_len = (int)strlen(source);
+ file.module_qn = "use";
+ file.defs = defs;
+ file.def_count = 3;
+ file.import_names = import_names;
+ file.import_qns = import_qns;
+ file.import_count = 1;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMResolvedCallArray out = {0};
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+
+ int exact = pylsp_exact_reference_count(&out, "crossArgument", "target.handler", NULL,
+ site_start, site_end);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(exact, 1);
+
+ static const char alias_source[] = "from target import handler as callback\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(callback)\n";
+ const char *alias_argument = strstr(alias_source, "accept(callback)");
+ ASSERT_NOT_NULL(alias_argument);
+ site_start = (uint32_t)(alias_argument - alias_source) + 7U;
+ site_end = site_start + (uint32_t)strlen("callback");
+ const char *alias_import_names[] = {"callback"};
+ const char *alias_import_qns[] = {"project.target"};
+ defs[0].qualified_name = "project.target.handler";
+ defs[0].def_module_qn = "project.target";
+ defs[1].qualified_name = "project.use.accept";
+ defs[1].def_module_qn = "project.use";
+ defs[2].qualified_name = "project.use.crossArgument";
+ defs[2].def_module_qn = "project.use";
+ file.source = alias_source;
+ file.source_len = (int)strlen(alias_source);
+ file.module_qn = "project.use";
+ file.import_names = alias_import_names;
+ file.import_qns = alias_import_qns;
+ memset(&out, 0, sizeof(out));
+ cbm_arena_init(&arena);
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+
+ int alias_exact = pylsp_exact_reference_count(&out, "crossArgument",
+ "project.target.handler", "callback",
+ site_start, site_end);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(alias_exact, 1);
+
+ /* The module and imported member may have the same leaf. Matching only
+ * leaves would keep `project.handler` and lose the member; the parsed
+ * from-import must canonicalize it to `project.handler.handler`. */
+ static const char same_name_source[] = "from handler import handler as callback\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(callback)\n";
+ const char *same_name_argument = strstr(same_name_source, "accept(callback)");
+ ASSERT_NOT_NULL(same_name_argument);
+ site_start = (uint32_t)(same_name_argument - same_name_source) + 7U;
+ site_end = site_start + (uint32_t)strlen("callback");
+ const char *same_name_import_qns[] = {"project.handler"};
+ defs[0].qualified_name = "project.handler.handler";
+ defs[0].def_module_qn = "project.handler";
+ file.source = same_name_source;
+ file.source_len = (int)strlen(same_name_source);
+ file.import_qns = same_name_import_qns;
+ memset(&out, 0, sizeof(out));
+ cbm_arena_init(&arena);
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+ int same_name_exact = pylsp_exact_reference_count(
+ &out, "crossArgument", "project.handler.handler", "callback", site_start, site_end);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(same_name_exact, 1);
+
+ /* Identical extraction metadata can also come from a direct module alias.
+ * Its import_statement must never be upgraded to the same-named function. */
+ static const char module_alias_source[] = "import target.handler as callback\n"
+ "def accept(fn):\n"
+ " pass\n"
+ "def crossArgument():\n"
+ " accept(callback)\n";
+ const char *module_alias_argument = strstr(module_alias_source, "accept(callback)");
+ ASSERT_NOT_NULL(module_alias_argument);
+ site_start = (uint32_t)(module_alias_argument - module_alias_source) + 7U;
+ site_end = site_start + (uint32_t)strlen("callback");
+ defs[0].qualified_name = "project.target.handler";
+ defs[0].def_module_qn = "project.target";
+ file.source = module_alias_source;
+ file.source_len = (int)strlen(module_alias_source);
+ file.import_qns = alias_import_qns;
+ memset(&out, 0, sizeof(out));
+ cbm_arena_init(&arena);
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+ int module_alias_reference = pylsp_exact_reference_count(
+ &out, "crossArgument", "project.target.handler", "callback", site_start, site_end);
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(module_alias_reference, 0);
+
+ /* Syntax alone is not callable proof: decorators can replace the runtime
+ * binding with any value. Canonicalization must still pass through the
+ * registry's exact-callable eligibility gate. */
+ const char *decorators[] = {"@replace_with_value", NULL};
+ defs[0].decorators = decorators;
+ file.source = alias_source;
+ file.source_len = (int)strlen(alias_source);
+ memset(&out, 0, sizeof(out));
+ cbm_arena_init(&arena);
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+ int decorated_reference = pylsp_exact_reference_count(
+ &out, "crossArgument", "project.target.handler", "callback",
+ (uint32_t)(alias_argument - alias_source) + 7U,
+ (uint32_t)(alias_argument - alias_source) + 7U + (uint32_t)strlen("callback"));
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(decorated_reference, 0);
+ PASS();
+}
+
+/* A semantic invocation is an occurrence, not merely a caller/callee pair.
+ * Calling one target twice in one function must therefore retain two records,
+ * each stamped with the full `target(...)` expression that caused it. */
+TEST(pylsp_same_target_calls_have_distinct_exact_semantic_sites) {
+ static const char source[] = "def target(value):\n"
+ " return value\n"
+ "def caller():\n"
+ " first = target(1)\n"
+ " second = target(22)\n"
+ " return first + second\n";
+ static const char first_text[] = "target(1)";
+ static const char second_text[] = "target(22)";
+ const char *first = strstr(source, first_text);
+ const char *second = strstr(source, second_text);
+ ASSERT_NOT_NULL(first);
+ ASSERT_NOT_NULL(second);
+
+ CBMFileResult *r = extract_py(source);
+ ASSERT_NOT_NULL(r);
+ uint32_t first_start = (uint32_t)(first - source);
+ uint32_t second_start = (uint32_t)(second - source);
+ PyResolvedSiteCounts counts =
+ count_invocation_sites(&r->resolved_calls, "caller", ".target", first_start,
+ first_start + (uint32_t)strlen(first_text), second_start,
+ second_start + (uint32_t)strlen(second_text));
+
+ ASSERT_EQ(counts.target_count, 2);
+ ASSERT_EQ(counts.first_site_count, 1);
+ ASSERT_EQ(counts.second_site_count, 1);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* cbm_batch_py_lsp_cross resolves in a temporary per-file arena, then copies
+ * semantic records into the caller arena. Both occurrence spans must survive
+ * that copy; caller/callee-only dedup must not collapse the two calls. */
+TEST(pylsp_batch_preserves_two_same_target_semantic_sites) {
+ static const char source[] = "def target(value):\n"
+ " return value\n"
+ "def caller():\n"
+ " first = target(1)\n"
+ " second = target(22)\n"
+ " return first + second\n";
+ static const char first_text[] = "target(1)";
+ static const char second_text[] = "target(22)";
+ const char *first = strstr(source, first_text);
+ const char *second = strstr(source, second_text);
+ ASSERT_NOT_NULL(first);
+ ASSERT_NOT_NULL(second);
+
+ CBMLSPDef defs[2];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "batch.target";
+ defs[0].short_name = "target";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "batch";
+ defs[1].qualified_name = "batch.caller";
+ defs[1].short_name = "caller";
+ defs[1].label = "Function";
+ defs[1].def_module_qn = "batch";
+
+ CBMBatchPyLSPFile file;
+ memset(&file, 0, sizeof(file));
+ file.source = source;
+ file.source_len = (int)strlen(source);
+ file.module_qn = "batch";
+ file.defs = defs;
+ file.def_count = 2;
+
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMResolvedCallArray out = {0};
+ cbm_batch_py_lsp_cross(&arena, &file, 1, &out);
+
+ uint32_t first_start = (uint32_t)(first - source);
+ uint32_t second_start = (uint32_t)(second - source);
+ PyResolvedSiteCounts counts = count_invocation_sites(
+ &out, "caller", ".target", first_start, first_start + (uint32_t)strlen(first_text),
+ second_start, second_start + (uint32_t)strlen(second_text));
+ ASSERT_EQ(counts.target_count, 2);
+ ASSERT_EQ(counts.first_site_count, 1);
+ ASSERT_EQ(counts.second_site_count, 1);
+
+ cbm_arena_destroy(&arena);
+ PASS();
+}
+
+/* The fallback cross pass resolves in a scratch arena that is destroyed
+ * inside cbm_pxc_run_one. A Python dunder carrier created only by that cross
+ * resolver must be deep-copied into result.arena, remain occurrence-exact,
+ * and still join its semantic target after the function returns. */
+TEST(pylsp_scratch_cross_dunder_carrier_survives_copy) {
+ static const char source[] = "class Number:\n"
+ " def __add__(self, other):\n"
+ " return self\n"
+ "def combine(left: Number, right: Number):\n"
+ " return left + right\n";
+ static const char site_text[] = "left + right";
+
+ CBMLSPDef defs[3];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "scratch.Number";
+ defs[0].short_name = "Number";
+ defs[0].label = "Class";
+ defs[0].def_module_qn = "scratch";
+ defs[0].lang = CBM_LANG_PYTHON;
+ defs[1].qualified_name = "scratch.Number.__add__";
+ defs[1].short_name = "__add__";
+ defs[1].label = "Method";
+ defs[1].receiver_type = "scratch.Number";
+ defs[1].def_module_qn = "scratch";
+ defs[1].lang = CBM_LANG_PYTHON;
+ defs[2].qualified_name = "scratch.combine";
+ defs[2].short_name = "combine";
+ defs[2].label = "Function";
+ defs[2].def_module_qn = "scratch";
+ defs[2].lang = CBM_LANG_PYTHON;
+
+ CBMFileResult result;
+ memset(&result, 0, sizeof(result));
+ cbm_arena_init(&result.arena);
+ cbm_pxc_run_one(CBM_LANG_PYTHON, &result, source, (int)strlen(source), "scratch", defs, 3, NULL,
+ NULL, 0);
+
+ const CBMCall *carrier = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < result.calls.count; i++) {
+ const CBMCall *call = &result.calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "__add__") == 0 &&
+ call->enclosing_func_qn && strstr(call->enclosing_func_qn, "combine")) {
+ carrier = call;
+ carrier_count++;
+ }
+ }
+ const char *site = strstr(source, site_text);
+ ASSERT_NOT_NULL(site);
+ uint32_t expected_start = (uint32_t)(site - source);
+ uint32_t expected_end = expected_start + (uint32_t)strlen(site_text);
+ ASSERT_EQ(carrier_count, 1);
+ ASSERT_NOT_NULL(carrier);
+ ASSERT_STR_EQ(carrier->callee_name, "__add__");
+ ASSERT_TRUE(strstr(carrier->enclosing_func_qn, "combine") != NULL);
+ ASSERT_TRUE(carrier->requires_lsp_resolution);
+ ASSERT_EQ(carrier->site_start_byte, expected_start);
+ ASSERT_EQ(carrier->site_end_byte, expected_end);
+
+ const CBMResolvedCall *joined =
+ cbm_pipeline_find_lsp_resolution(&result.resolved_calls, carrier, false);
+ ASSERT_NOT_NULL(joined);
+ ASSERT_STR_EQ(joined->callee_qn, "scratch.Number.__add__");
+ ASSERT_EQ(joined->site_start_byte, expected_start);
+ ASSERT_EQ(joined->site_end_byte, expected_end);
+
+ cbm_arena_destroy(&result.arena);
+ PASS();
+}
+
/* ── Phase 10 — stdlib resolution ─────────────────────────────── */
TEST(pylsp_stdlib_os_getcwd) {
- /* Top-level module attribute resolution against the stdlib registry.
- * Note: `import os.path` only binds `path` in scope (the leaf binding
- * extracted from the dotted import) — full submodule traversal of
- * `os.path.join` style accesses needs a Phase 10.5 follow-up where we
- * also stamp parent-module bindings. For v1, top-level module calls
- * resolve correctly. */
+ /* Top-level module attribute resolution against the stdlib registry. */
CBMFileResult *r = extract_py(
"import os\n"
"def use():\n"
@@ -827,6 +1292,26 @@ TEST(pylsp_round1_dotted_import_walk) {
"def use():\n"
" return os.path.join('a', 'b')\n");
ASSERT_NOT_NULL(r);
+ ASSERT_EQ(r->imports.count, 1);
+ ASSERT_STR_EQ(r->imports.items[0].local_name, "os");
+ ASSERT_STR_EQ(r->imports.items[0].module_path, "os.path");
+ int idx = find_resolved(r, "use", "join");
+ ASSERT_GTE(idx, 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(pylsp_round1_dotted_import_alias_matching_root) {
+ /* The metadata pair (local=os, module=os.path) is also possible for an
+ * explicit alias. Unlike the unaliased form above, this binds `os`
+ * directly to MODULE(os.path), so os.join resolves os.path.join. */
+ CBMFileResult *r = extract_py("import os.path as os\n"
+ "def use():\n"
+ " return os.join('a', 'b')\n");
+ ASSERT_NOT_NULL(r);
+ ASSERT_EQ(r->imports.count, 1);
+ ASSERT_STR_EQ(r->imports.items[0].local_name, "os");
+ ASSERT_STR_EQ(r->imports.items[0].module_path, "os.path");
int idx = find_resolved(r, "use", "join");
ASSERT_GTE(idx, 0);
cbm_free_result(r);
@@ -1236,6 +1721,221 @@ TEST(pylsp_round5_super_init) {
PASS();
}
+/* Synthetic dunder calls have no ordinary tree-sitter `call` carrier. Two
+ * different receiver classes can therefore produce the same textual leaf in
+ * one caller. The synthetic carrier and semantic record must retain the exact
+ * operator occurrence so the pipeline cannot bind both `__add__` calls to the
+ * first class it happens to inspect. */
+TEST(pylsp_dunder_same_leaf_occurrences_join_by_exact_site) {
+ static const char source[] =
+ "class Alpha:\n"
+ " def __add__(self, other):\n"
+ " return self\n"
+ "class Beta:\n"
+ " def __add__(self, other):\n"
+ " return self\n"
+ "def combine(left_a: Alpha, left_b: Alpha, right_a: Beta, right_b: Beta):\n"
+ " first = left_a + left_b\n"
+ " second = right_a + right_b\n"
+ " return first, second\n";
+ static const char alpha_text[] = "left_a + left_b";
+ static const char beta_text[] = "right_a + right_b";
+
+ const char *alpha_site = strstr(source, alpha_text);
+ const char *beta_site = strstr(source, beta_text);
+ ASSERT_NOT_NULL(alpha_site);
+ ASSERT_NOT_NULL(beta_site);
+
+ CBMFileResult *r = extract_py(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error || r->parse_incomplete);
+
+ const CBMCall *dunder_calls[2] = {0};
+ int dunder_count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "__add__") == 0 &&
+ call->enclosing_func_qn && strstr(call->enclosing_func_qn, "combine")) {
+ if (dunder_count < 2)
+ dunder_calls[dunder_count] = call;
+ dunder_count++;
+ }
+ }
+ ASSERT_EQ(dunder_count, 2);
+ ASSERT_NOT_NULL(dunder_calls[0]);
+ ASSERT_NOT_NULL(dunder_calls[1]);
+
+ const CBMCall *alpha_call = dunder_calls[0];
+ const CBMCall *beta_call = dunder_calls[1];
+ if (alpha_call->site_start_byte > beta_call->site_start_byte) {
+ const CBMCall *tmp = alpha_call;
+ alpha_call = beta_call;
+ beta_call = tmp;
+ }
+
+ uint32_t alpha_start = (uint32_t)(alpha_site - source);
+ uint32_t alpha_end = alpha_start + (uint32_t)strlen(alpha_text);
+ uint32_t beta_start = (uint32_t)(beta_site - source);
+ uint32_t beta_end = beta_start + (uint32_t)strlen(beta_text);
+
+ ASSERT_GT(alpha_call->site_end_byte, alpha_call->site_start_byte);
+ ASSERT_GT(beta_call->site_end_byte, beta_call->site_start_byte);
+ ASSERT_NEQ(alpha_call->site_start_byte, beta_call->site_start_byte);
+ ASSERT_EQ(alpha_call->site_start_byte, alpha_start);
+ ASSERT_EQ(alpha_call->site_end_byte, alpha_end);
+ ASSERT_EQ(beta_call->site_start_byte, beta_start);
+ ASSERT_EQ(beta_call->site_end_byte, beta_end);
+ ASSERT_TRUE(alpha_call->requires_lsp_resolution);
+ ASSERT_TRUE(beta_call->requires_lsp_resolution);
+
+ const CBMResolvedCall *alpha_resolution =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, alpha_call, false);
+ const CBMResolvedCall *beta_resolution =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, beta_call, false);
+ ASSERT_NOT_NULL(alpha_resolution);
+ ASSERT_NOT_NULL(beta_resolution);
+ ASSERT_TRUE(alpha_resolution != beta_resolution);
+ ASSERT_TRUE(strstr(alpha_resolution->callee_qn, ".Alpha.__add__") != NULL);
+ ASSERT_TRUE(strstr(beta_resolution->callee_qn, ".Beta.__add__") != NULL);
+ ASSERT_EQ(alpha_resolution->site_start_byte, alpha_call->site_start_byte);
+ ASSERT_EQ(alpha_resolution->site_end_byte, alpha_call->site_end_byte);
+ ASSERT_EQ(beta_resolution->site_start_byte, beta_call->site_start_byte);
+ ASSERT_EQ(beta_resolution->site_end_byte, beta_call->site_end_byte);
+
+ cbm_free_result(r);
+ PASS();
+}
+
+/* A named lambda body is re-walked once per invocation so its parameters can
+ * inherit the call-site argument types. Both walks below visit the same single
+ * `a + b` AST occurrence. That occurrence must produce one semantic record and
+ * one synthetic carrier, not one carrier per re-walk. */
+TEST(pylsp_lambda_rewalk_dedupes_dunder_occurrence) {
+ static const char source[] = "class Number:\n"
+ " def __add__(self, other):\n"
+ " return self\n"
+ "def combine(left: Number, right: Number):\n"
+ " add = lambda a, b: a + b\n"
+ " first = add(left, right)\n"
+ " second = add(left, right)\n"
+ " return first, second\n";
+ static const char site_text[] = "a + b";
+ const char *site = strstr(source, site_text);
+ ASSERT_NOT_NULL(site);
+ uint32_t expected_start = (uint32_t)(site - source);
+ uint32_t expected_end = expected_start + (uint32_t)strlen(site_text);
+
+ CBMFileResult *r = extract_py(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error || r->parse_incomplete);
+
+ const CBMCall *carrier = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "__add__") == 0 &&
+ call->enclosing_func_qn && strstr(call->enclosing_func_qn, "<lambda>")) {
+ carrier = call;
+ carrier_count++;
+ }
+ }
+
+ const CBMResolvedCall *semantic = NULL;
+ int semantic_count = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (rc->caller_qn && strstr(rc->caller_qn, "<lambda>") && rc->callee_qn &&
+ strstr(rc->callee_qn, ".Number.__add__")) {
+ semantic = rc;
+ semantic_count++;
+ }
+ }
+
+ ASSERT_EQ(semantic_count, 1);
+ ASSERT_NOT_NULL(semantic);
+ ASSERT_EQ(semantic->kind, CBM_RESOLVED_INVOCATION);
+ ASSERT_EQ(semantic->site_start_byte, expected_start);
+ ASSERT_EQ(semantic->site_end_byte, expected_end);
+
+ if (carrier_count != 1) {
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "__add__") == 0) {
+ fprintf(stderr, " [PY-LAMBDA-CARRIER] caller=%s site=%u:%u requires_lsp=%d\n",
+ call->enclosing_func_qn ? call->enclosing_func_qn : "(null)",
+ call->site_start_byte, call->site_end_byte,
+ call->requires_lsp_resolution ? 1 : 0);
+ }
+ }
+ }
+ ASSERT_EQ(carrier_count, 1);
+ ASSERT_NOT_NULL(carrier);
+ ASSERT_TRUE(carrier->requires_lsp_resolution);
+ ASSERT_EQ(carrier->site_start_byte, expected_start);
+ ASSERT_EQ(carrier->site_end_byte, expected_end);
+
+ const CBMResolvedCall *joined =
+ cbm_pipeline_find_lsp_resolution(&r->resolved_calls, carrier, false);
+ ASSERT_NOT_NULL(joined);
+ ASSERT_TRUE(joined == semantic);
+ ASSERT_TRUE(strstr(joined->callee_qn, ".Number.__add__") != NULL);
+ ASSERT_EQ(joined->site_start_byte, expected_start);
+ ASSERT_EQ(joined->site_end_byte, expected_end);
+
+ cbm_free_result(r);
+ PASS();
+}
+
+/* Parser-backed Python calls have the same occurrence-identity requirement as
+ * synthetic dunders. Distinct typed receivers can expose the same method leaf
+ * in one caller; each CBMCall must join the semantic record for its own site. */
+TEST(pylsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ CBMFileResult *r = extract_py("class Alpha:\n"
+ " def render(self):\n"
+ " return 1\n"
+ "class Beta:\n"
+ " def render(self):\n"
+ " return 2\n"
+ "def combine(a: Alpha, b: Beta):\n"
+ " return a.render(), b.render()\n");
+ ASSERT_NOT_NULL(r);
+
+ const CBMCall *calls[2] = {0};
+ int call_count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "combine") &&
+ call->callee_name && strstr(call->callee_name, "render")) {
+ if (call_count < 2)
+ calls[call_count] = call;
+ call_count++;
+ }
+ }
+ if (calls[0] && calls[1] && calls[0]->site_start_byte > calls[1]->site_start_byte) {
+ const CBMCall *tmp = calls[0];
+ calls[0] = calls[1];
+ calls[1] = tmp;
+ }
+ const CBMResolvedCall *alpha_hit =
+ calls[0] ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, calls[0], false) : NULL;
+ const CBMResolvedCall *beta_hit =
+ calls[1] ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, calls[1], false) : NULL;
+ bool alpha_exact = alpha_hit && alpha_hit->callee_qn &&
+ strstr(alpha_hit->callee_qn, ".Alpha.render") &&
+ alpha_hit->site_start_byte == calls[0]->site_start_byte &&
+ alpha_hit->site_end_byte == calls[0]->site_end_byte;
+ bool beta_exact = beta_hit && beta_hit->callee_qn &&
+ strstr(beta_hit->callee_qn, ".Beta.render") &&
+ beta_hit->site_start_byte == calls[1]->site_start_byte &&
+ beta_hit->site_end_byte == calls[1]->site_end_byte;
+
+ cbm_free_result(r);
+ ASSERT_EQ(call_count, 2);
+ ASSERT_TRUE(alpha_exact);
+ ASSERT_TRUE(beta_exact);
+ PASS();
+}
+
/* ── Round 6 — generators, dataclasses, decorator flags ───────── */
TEST(pylsp_round6_generator_yields_iterable) {
@@ -1452,6 +2152,14 @@ SUITE(py_lsp) {
RUN_TEST(pylsp_crossfile_classmethod_on_class_issue228);
RUN_TEST(pylsp_crossfile_inheritance);
RUN_TEST(pylsp_batch_two_files);
+ RUN_TEST(pylsp_from_import_alias_equal_module_leaf_targets_imported_member);
+ RUN_TEST(pylsp_project_prefixed_direct_alias_same_tail_is_not_from_import_reference);
+ RUN_TEST(pylsp_competing_import_forms_for_same_local_fail_closed);
+ RUN_TEST(pylsp_later_plain_import_rebinding_same_local_fails_closed);
+ RUN_TEST(pylsp_batch_cross_file_callable_value_preserves_exact_reference_site);
+ RUN_TEST(pylsp_same_target_calls_have_distinct_exact_semantic_sites);
+ RUN_TEST(pylsp_batch_preserves_two_same_target_semantic_sites);
+ RUN_TEST(pylsp_scratch_cross_dunder_carrier_survives_copy);
/* Phase 10 — stdlib resolution */
RUN_TEST(pylsp_stdlib_os_getcwd);
RUN_TEST(pylsp_stdlib_collections_defaultdict);
@@ -1459,6 +2167,7 @@ SUITE(py_lsp) {
RUN_TEST(pylsp_stdlib_logging_getlogger);
/* Round 1 — parity push */
RUN_TEST(pylsp_round1_dotted_import_walk);
+ RUN_TEST(pylsp_round1_dotted_import_alias_matching_root);
RUN_TEST(pylsp_round1_typing_cast);
RUN_TEST(pylsp_round1_assert_type_passthrough);
RUN_TEST(pylsp_round1_forward_reference);
@@ -1484,6 +2193,9 @@ SUITE(py_lsp) {
RUN_TEST(pylsp_round5_dict_subscript_value_type);
RUN_TEST(pylsp_round5_list_subscript_value_type);
RUN_TEST(pylsp_round5_super_init);
+ RUN_TEST(pylsp_dunder_same_leaf_occurrences_join_by_exact_site);
+ RUN_TEST(pylsp_lambda_rewalk_dedupes_dunder_occurrence);
+ RUN_TEST(pylsp_ordinary_same_leaf_calls_join_by_exact_site);
/* Round 6 — generators, dataclasses, properties */
RUN_TEST(pylsp_round6_generator_yields_iterable);
RUN_TEST(pylsp_round6_dataclass_field_access);
diff --git a/tests/test_rust_lsp.c b/tests/test_rust_lsp.c
index fbdd7b681..3c5483915 100644
--- a/tests/test_rust_lsp.c
+++ b/tests/test_rust_lsp.c
@@ -20,6 +20,8 @@
#include "test_framework.h"
#include "cbm.h"
#include "lsp/rust_lsp.h"
+#include "pipeline/lsp_resolve.h"
+#include "pipeline/pass_lsp_cross.h"
/* ── Helpers ───────────────────────────────────────────────────── */
@@ -28,6 +30,10 @@ static CBMFileResult *extract_rust(const char *source) {
"test", "src/main.rs", 0, NULL, NULL);
}
+static CBMTypeRegistry *rustlsp_return_shared_registry(void *ctx) {
+ return (CBMTypeRegistry *)ctx;
+}
+
static int find_resolved(const CBMFileResult *r, const char *callerSub,
const char *calleeSub) {
for (int i = 0; i < r->resolved_calls.count; i++) {
@@ -70,6 +76,41 @@ static int count_resolved(const CBMFileResult *r, const char *callerSub,
return n;
}
+static bool rustlsp_definition_has_decorator(const CBMFileResult *result,
+ const char *definition_name,
+ const char *decorator_text) {
+ if (!result || !definition_name || !decorator_text)
+ return false;
+ for (int i = 0; i < result->defs.count; i++) {
+ const CBMDefinition *definition = &result->defs.items[i];
+ if (!definition->name || strcmp(definition->name, definition_name) != 0 ||
+ !definition->decorators) {
+ continue;
+ }
+ for (int d = 0; definition->decorators[d]; d++) {
+ if (strcmp(definition->decorators[d], decorator_text) == 0)
+ return true;
+ }
+ }
+ return false;
+}
+
+static int rustlsp_count_proc_macro_pseudo_calls(const CBMFileResult *result) {
+ int count = 0;
+ if (!result)
+ return 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if ((resolved->strategy && strcmp(resolved->strategy, "lsp_proc_macro") == 0) ||
+ (resolved->callee_qn && (strstr(resolved->callee_qn, "Runtime.new") ||
+ strstr(resolved->callee_qn, "Runtime.block_on") ||
+ strstr(resolved->callee_qn, "Span.enter")))) {
+ count++;
+ }
+ }
+ return count;
+}
+
/* Confident = confidence >= the LSP override floor (0.6). */
static int find_confident(const CBMResolvedCallArray *arr, const char *callerSub,
const char *calleeSub) {
@@ -83,6 +124,17 @@ static int find_confident(const CBMResolvedCallArray *arr, const char *callerSub
return -1;
}
+static int count_confident_strategy(const CBMResolvedCallArray *arr, const char *strategy) {
+ int count = 0;
+ for (int i = 0; arr && i < arr->count; i++) {
+ const CBMResolvedCall *rc = &arr->items[i];
+ if (rc->confidence >= 0.6f && rc->strategy && strcmp(rc->strategy, strategy) == 0) {
+ count++;
+ }
+ }
+ return count;
+}
+
/* ── Category 1: Free function calls + module path ─────────────── */
TEST(rustlsp_free_function_call) {
@@ -551,7 +603,7 @@ TEST(rustlsp_shared_registry_resolves_like_per_file) {
memset(&out, 0, sizeof(out));
cbm_run_rust_lsp_cross_with_registry(&a, caller, (int)strlen(caller), "test.caller", reg,
imp_names, imp_qns, 1, NULL, /*manifest=*/NULL, &out,
- /*result=*/NULL);
+ /*synthetic_calls=*/NULL);
ASSERT_GTE(find_confident(&out, "run", "Database.query"), 0);
@@ -559,6 +611,762 @@ TEST(rustlsp_shared_registry_resolves_like_per_file) {
PASS();
}
+static CBMTypeRegistry *rustlsp_default_trait_registry(CBMArena *arena, bool add_ambiguous_type) {
+ CBMLSPDef defs[5];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "test.contract.Pinger";
+ defs[0].short_name = "Pinger";
+ defs[0].label = "Trait";
+ defs[0].def_module_qn = "test.contract";
+ defs[0].lang = CBM_LANG_RUST;
+ defs[1].qualified_name = "test.contract.Pinger.ping";
+ defs[1].short_name = "ping";
+ defs[1].label = "Method";
+ defs[1].receiver_type = "test.contract.Pinger";
+ defs[1].def_module_qn = "test.contract";
+ defs[1].lang = CBM_LANG_RUST;
+ defs[2].qualified_name = "test.contract.S";
+ defs[2].short_name = "S";
+ defs[2].label = "Struct";
+ defs[2].def_module_qn = "test.contract";
+ defs[2].lang = CBM_LANG_RUST;
+ defs[3].qualified_name = "test.contract.S";
+ defs[3].short_name = "S";
+ defs[3].label = "RustImpl";
+ defs[3].receiver_type = "test.contract.S";
+ defs[3].def_module_qn = "test.contract";
+ defs[3].trait_qn = "test.contract.Pinger";
+ defs[3].is_rust_impl_relation = true;
+ defs[3].lang = CBM_LANG_RUST;
+ defs[4].qualified_name = "test.main.contract.S";
+ defs[4].short_name = "S";
+ defs[4].label = "Struct";
+ defs[4].def_module_qn = "test.main.contract";
+ defs[4].lang = CBM_LANG_RUST;
+ return cbm_rust_build_cross_registry(arena, defs, add_ambiguous_type ? 5 : 4);
+}
+
+TEST(rustlsp_relative_type_requires_declared_module) {
+ const char *caller = "fn caller(s: &contract::S) -> i32 { s.ping() }\n";
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = rustlsp_default_trait_registry(&arena, false);
+ ASSERT_NOT_NULL(registry);
+ CBMResolvedCallArray out = {0};
+ cbm_run_rust_lsp_cross_with_registry(&arena, caller, (int)strlen(caller), "test.main", registry,
+ NULL, NULL, 0, NULL, NULL, &out, NULL);
+ int stolen = count_confident_strategy(&out, "lsp_trait_dispatch");
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(stolen, 0);
+ PASS();
+}
+
+TEST(rustlsp_relative_type_ambiguous_graph_paths_fail_closed) {
+ const char *caller = "mod contract;\n"
+ "fn caller(s: &contract::S) -> i32 { s.ping() }\n";
+ CBMArena arena;
+ cbm_arena_init(&arena);
+ CBMTypeRegistry *registry = rustlsp_default_trait_registry(&arena, true);
+ ASSERT_NOT_NULL(registry);
+ CBMResolvedCallArray out = {0};
+ cbm_run_rust_lsp_cross_with_registry(&arena, caller, (int)strlen(caller), "test.main", registry,
+ NULL, NULL, 0, NULL, NULL, &out, NULL);
+ int guessed = count_confident_strategy(&out, "lsp_trait_dispatch");
+ cbm_arena_destroy(&arena);
+ ASSERT_EQ(guessed, 0);
+ PASS();
+}
+
+/* A call hidden in a built-in macro's token tree can resolve only after the
+ * project-wide registry is available. The semantic record alone is not enough:
+ * pass_calls iterates CBMCall entries, so the cross resolver must also return a
+ * matching synthetic carrier to the owning CBMFileResult. */
+TEST(rustlsp_shared_registry_macro_hidden_call_has_carrier) {
+ const char *caller = "fn hidden() -> String { format!(\"{}\", lib::render()) }\n";
+
+ CBMFileResult result;
+ memset(&result, 0, sizeof(result));
+ cbm_arena_init(&result.arena);
+
+ CBMLSPDef defs[1];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "test.lib.render";
+ defs[0].short_name = "render";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "test.lib";
+ defs[0].return_types = "str";
+
+ const char *imp_names[] = {"lib"};
+ const char *imp_qns[] = {"test::lib"};
+
+ CBMTypeRegistry *reg = cbm_rust_build_cross_registry(&result.arena, defs, 1);
+ ASSERT_NOT_NULL(reg);
+
+ cbm_run_rust_lsp_cross_with_registry(&result.arena, caller, (int)strlen(caller), "test.main",
+ reg, imp_names, imp_qns, 1, NULL, /*manifest=*/NULL,
+ &result.resolved_calls, &result.calls);
+
+ int resolved = find_confident(&result.resolved_calls, "hidden", "lib.render");
+ int carriers = 0;
+ const CBMCall *carrier = NULL;
+ for (int i = 0; i < result.calls.count; i++) {
+ const CBMCall *call = &result.calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "hidden") &&
+ call->callee_name && strcmp(call->callee_name, "render") == 0) {
+ carriers++;
+ carrier = call;
+ }
+ }
+
+ const char *site = strstr(caller, "lib::render()");
+ uint32_t expected_start = site ? (uint32_t)(site - caller) : 0;
+ uint32_t expected_end = expected_start + (uint32_t)strlen("lib::render()");
+ bool exact_carrier = carrier && carrier->requires_lsp_resolution &&
+ carrier->site_start_byte == expected_start &&
+ carrier->site_end_byte == expected_end;
+ bool exact_semantic = resolved >= 0 &&
+ result.resolved_calls.items[resolved].site_start_byte == expected_start &&
+ result.resolved_calls.items[resolved].site_end_byte == expected_end;
+ const CBMResolvedCall *joined =
+ carrier ? cbm_pipeline_find_lsp_resolution(&result.resolved_calls, carrier, false) : NULL;
+ bool joined_target =
+ joined && joined->callee_qn && strcmp(joined->callee_qn, "test.lib.render") == 0;
+
+ cbm_arena_destroy(&result.arena);
+
+ /* Control: semantic cross-file resolution already succeeds today. */
+ ASSERT_GTE(resolved, 0);
+ /* RED: the corresponding exact CBMCall carrier is currently never returned. */
+ ASSERT_EQ(carriers, 1);
+ ASSERT_TRUE(exact_carrier);
+ ASSERT_TRUE(exact_semantic);
+ ASSERT_TRUE(joined_target);
+ PASS();
+}
+
+/* The production shared-registry dispatcher receives a file result that
+ * already contains Tier-1/local semantic records. Rewalking the whole Rust
+ * source against the project registry must merge those exact occurrences,
+ * while adding only the cross-file deficit and its source-exact carrier. */
+TEST(rustlsp_shared_dispatch_merges_existing_exact_occurrence) {
+ const char *source = "fn local() {}\n"
+ "fn run() { local(); let _ = format!(\"{}\", lib::render()); }\n";
+ const char *local_site = strstr(source, "local();");
+ const char *render_site = strstr(source, "lib::render()");
+ ASSERT_NOT_NULL(local_site);
+ ASSERT_NOT_NULL(render_site);
+ uint32_t local_start = (uint32_t)(local_site - source);
+ uint32_t local_end = local_start + (uint32_t)strlen("local()");
+ uint32_t render_start = (uint32_t)(render_site - source);
+ uint32_t render_end = render_start + (uint32_t)strlen("lib::render()");
+
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+ ASSERT_NOT_NULL(result->module_qn);
+
+ int local_before = 0;
+ const char *local_target = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &result->resolved_calls.items[i];
+ if (rc->confidence >= 0.6f && rc->callee_qn && rc->site_start_byte == local_start &&
+ rc->site_end_byte == local_end) {
+ local_before++;
+ local_target = rc->callee_qn;
+ }
+ }
+ ASSERT_EQ(local_before, 1);
+ ASSERT_NOT_NULL(local_target);
+
+ CBMLSPDef defs[2];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = local_target;
+ defs[0].short_name = "local";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = result->module_qn;
+ defs[0].lang = CBM_LANG_RUST;
+ defs[1].qualified_name = "test.lib.render";
+ defs[1].short_name = "render";
+ defs[1].label = "Function";
+ defs[1].def_module_qn = "test.lib";
+ defs[1].return_types = "str";
+ defs[1].lang = CBM_LANG_RUST;
+
+ CBMArena shared_arena;
+ cbm_arena_init(&shared_arena);
+ CBMTypeRegistry *shared = cbm_rust_build_cross_registry(&shared_arena, defs, 2);
+ ASSERT_NOT_NULL(shared);
+ const char *imp_names[] = {"lib"};
+ const char *imp_qns[] = {"test::lib"};
+
+ cbm_pxc_dispatch_file(CBM_LANG_RUST, result, source, (int)strlen(source), "src/main.rs",
+ result->module_qn, NULL, NULL, defs, 2, imp_names, imp_qns, 1,
+ rustlsp_return_shared_registry, shared);
+
+ int local_after = 0;
+ int render_semantics = 0;
+ int render_carriers = 0;
+ const CBMCall *render_carrier = NULL;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &result->resolved_calls.items[i];
+ if (rc->confidence < 0.6f || !rc->callee_qn)
+ continue;
+ if (strcmp(rc->callee_qn, local_target) == 0 && rc->site_start_byte == local_start &&
+ rc->site_end_byte == local_end) {
+ local_after++;
+ }
+ if (strcmp(rc->callee_qn, "test.lib.render") == 0 && rc->site_start_byte == render_start &&
+ rc->site_end_byte == render_end) {
+ render_semantics++;
+ }
+ }
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "render") == 0 &&
+ call->site_start_byte == render_start && call->site_end_byte == render_end) {
+ render_carriers++;
+ render_carrier = call;
+ }
+ }
+ const CBMResolvedCall *joined =
+ render_carrier
+ ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, render_carrier, false)
+ : NULL;
+ bool exact_join = render_carrier && render_carrier->requires_lsp_resolution && joined &&
+ joined->callee_qn && strcmp(joined->callee_qn, "test.lib.render") == 0;
+
+ cbm_arena_destroy(&shared_arena);
+
+ if (local_after != 1) {
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &result->resolved_calls.items[i];
+ if (rc->callee_qn && strcmp(rc->callee_qn, local_target) == 0) {
+ fprintf(stderr,
+ " [RUST-SHARED-MERGE] kind=%d caller=%s callee=%s site=%u:%u "
+ "strategy=%s confidence=%.2f\n",
+ (int)rc->kind, rc->caller_qn ? rc->caller_qn : "(null)", rc->callee_qn,
+ rc->site_start_byte, rc->site_end_byte,
+ rc->strategy ? rc->strategy : "(null)", rc->confidence);
+ }
+ }
+ }
+ cbm_free_result(result);
+
+ /* RED today: the shared branch appends directly and emits local() twice. */
+ ASSERT_EQ(local_after, 1);
+ ASSERT_EQ(render_semantics, 1);
+ ASSERT_EQ(render_carriers, 1);
+ ASSERT_TRUE(exact_join);
+ PASS();
+}
+
+/* The sequential small-project path resolves Rust in a scratch arena. A
+ * carrier allocated there must be deep-copied into the file-result arena
+ * before the scratch arena is destroyed. This test dereferences all populated
+ * strings after cbm_pxc_run_one returns, making ownership bugs visible under
+ * ASan as well as exercising the production fallback path. */
+TEST(rustlsp_scratch_cross_macro_carrier_survives_copy) {
+ const char *caller = "fn hidden() -> String { format!(\"{}\", lib::render()) }\n";
+
+ CBMFileResult result;
+ memset(&result, 0, sizeof(result));
+ cbm_arena_init(&result.arena);
+
+ CBMLSPDef defs[1];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "test.lib.render";
+ defs[0].short_name = "render";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "test.lib";
+ defs[0].return_types = "str";
+ defs[0].lang = CBM_LANG_RUST;
+
+ const char *imp_names[] = {"lib"};
+ const char *imp_qns[] = {"test::lib"};
+ cbm_pxc_run_one(CBM_LANG_RUST, &result, caller, (int)strlen(caller), "test.main", defs, 1,
+ imp_names, imp_qns, 1);
+
+ const CBMCall *carrier = NULL;
+ for (int i = 0; i < result.calls.count; i++) {
+ const CBMCall *call = &result.calls.items[i];
+ if (call->callee_name && strcmp(call->callee_name, "render") == 0) {
+ carrier = call;
+ break;
+ }
+ }
+ const char *site = strstr(caller, "lib::render()");
+ uint32_t expected_start = site ? (uint32_t)(site - caller) : 0;
+ uint32_t expected_end = expected_start + (uint32_t)strlen("lib::render()");
+ bool copied = carrier && carrier->callee_name && carrier->enclosing_func_qn &&
+ strcmp(carrier->callee_name, "render") == 0 &&
+ strstr(carrier->enclosing_func_qn, "hidden") &&
+ carrier->requires_lsp_resolution && carrier->site_start_byte == expected_start &&
+ carrier->site_end_byte == expected_end;
+ const CBMResolvedCall *joined =
+ carrier ? cbm_pipeline_find_lsp_resolution(&result.resolved_calls, carrier, false) : NULL;
+ bool joined_target =
+ joined && joined->callee_qn && strcmp(joined->callee_qn, "test.lib.render") == 0;
+
+ cbm_arena_destroy(&result.arena);
+ ASSERT_TRUE(copied);
+ ASSERT_TRUE(joined_target);
+ PASS();
+}
+
+/* Two same-leaf calls inside one token tree must not cross-pair through the
+ * legacy (caller, leaf-name) join. Their exact original-source occurrences are
+ * the identity that pins each synthetic carrier to its semantic target. */
+TEST(rustlsp_macro_same_leaf_carriers_are_occurrence_exact) {
+ const char *caller = "fn hidden() -> String { format!(\"{} {}\", a::render(), b::render()) }\n";
+
+ CBMFileResult result;
+ memset(&result, 0, sizeof(result));
+ cbm_arena_init(&result.arena);
+
+ CBMLSPDef defs[2];
+ memset(defs, 0, sizeof(defs));
+ defs[0].qualified_name = "test.a.render";
+ defs[0].short_name = "render";
+ defs[0].label = "Function";
+ defs[0].def_module_qn = "test.a";
+ defs[0].return_types = "str";
+ defs[0].lang = CBM_LANG_RUST;
+ defs[1] = defs[0];
+ defs[1].qualified_name = "test.b.render";
+ defs[1].def_module_qn = "test.b";
+
+ const char *imp_names[] = {"a", "b"};
+ const char *imp_qns[] = {"test::a", "test::b"};
+ CBMTypeRegistry *reg = cbm_rust_build_cross_registry(&result.arena, defs, 2);
+ ASSERT_NOT_NULL(reg);
+ cbm_run_rust_lsp_cross_with_registry(&result.arena, caller, (int)strlen(caller), "test.main",
+ reg, imp_names, imp_qns, 2, NULL, /*manifest=*/NULL,
+ &result.resolved_calls, &result.calls);
+
+ const char *a_site = strstr(caller, "a::render()");
+ const char *b_site = strstr(caller, "b::render()");
+ uint32_t a_start = a_site ? (uint32_t)(a_site - caller) : 0;
+ uint32_t b_start = b_site ? (uint32_t)(b_site - caller) : 0;
+ const CBMCall *a_call = NULL;
+ const CBMCall *b_call = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < result.calls.count; i++) {
+ const CBMCall *call = &result.calls.items[i];
+ if (!call->callee_name || strcmp(call->callee_name, "render") != 0)
+ continue;
+ carrier_count++;
+ if (call->site_start_byte == a_start)
+ a_call = call;
+ if (call->site_start_byte == b_start)
+ b_call = call;
+ }
+ const CBMResolvedCall *a_hit =
+ a_call ? cbm_pipeline_find_lsp_resolution(&result.resolved_calls, a_call, false) : NULL;
+ const CBMResolvedCall *b_hit =
+ b_call ? cbm_pipeline_find_lsp_resolution(&result.resolved_calls, b_call, false) : NULL;
+ bool a_exact = a_call && a_call->requires_lsp_resolution &&
+ a_call->site_end_byte == a_start + strlen("a::render()") && a_hit &&
+ a_hit->callee_qn && strcmp(a_hit->callee_qn, "test.a.render") == 0;
+ bool b_exact = b_call && b_call->requires_lsp_resolution &&
+ b_call->site_end_byte == b_start + strlen("b::render()") && b_hit &&
+ b_hit->callee_qn && strcmp(b_hit->callee_qn, "test.b.render") == 0;
+
+ cbm_arena_destroy(&result.arena);
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_TRUE(a_exact);
+ ASSERT_TRUE(b_exact);
+ PASS();
+}
+
+/* Rust operator desugaring has the same carrier join hazard. With two `add`
+ * targets in one caller, zero-span carriers both join the first semantic
+ * record. Exact spans must preserve one Alpha edge and one Beta edge. */
+TEST(rustlsp_operator_carriers_are_occurrence_exact) {
+ const char *source =
+ "use std::ops::Add;\n"
+ "struct Alpha;\n"
+ "impl Add for Alpha { type Output = Alpha; fn add(self, _: Alpha) -> Alpha { self } }\n"
+ "struct Beta;\n"
+ "impl Add for Beta { type Output = Beta; fn add(self, _: Beta) -> Beta { self } }\n"
+ "fn run(a: Alpha, b: Alpha, x: Beta, y: Beta) { let _ = a + b; let _ = x + y; }\n";
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+
+ const char *alpha_site = strstr(source, "a + b");
+ const char *beta_site = strstr(source, "x + y");
+ uint32_t alpha_start = alpha_site ? (uint32_t)(alpha_site - source) : 0;
+ uint32_t beta_start = beta_site ? (uint32_t)(beta_site - source) : 0;
+ const CBMCall *alpha_call = NULL;
+ const CBMCall *beta_call = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "run") ||
+ !call->callee_name || strcmp(call->callee_name, "add") != 0)
+ continue;
+ carrier_count++;
+ if (call->site_start_byte == alpha_start)
+ alpha_call = call;
+ if (call->site_start_byte == beta_start)
+ beta_call = call;
+ }
+ const CBMResolvedCall *alpha_hit =
+ alpha_call ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, alpha_call, false)
+ : NULL;
+ const CBMResolvedCall *beta_hit =
+ beta_call ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, beta_call, false)
+ : NULL;
+ bool alpha_exact = alpha_call && alpha_call->requires_lsp_resolution &&
+ alpha_call->site_end_byte == alpha_start + strlen("a + b") && alpha_hit &&
+ alpha_hit->callee_qn && strstr(alpha_hit->callee_qn, "Alpha.add");
+ bool beta_exact = beta_call && beta_call->requires_lsp_resolution &&
+ beta_call->site_end_byte == beta_start + strlen("x + y") && beta_hit &&
+ beta_hit->callee_qn && strstr(beta_hit->callee_qn, "Beta.add");
+
+ cbm_free_result(result);
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_TRUE(alpha_exact);
+ ASSERT_TRUE(beta_exact);
+ PASS();
+}
+
+/* Built-in expression macros reparse their token tree, so operator carriers
+ * need the same synthetic-to-original span mapping as ordinary hidden calls.
+ * The injection hook and the explicit operator carrier must also cooperate:
+ * exactly one source-exact carrier may survive for the occurrence. */
+TEST(rustlsp_macro_operator_has_one_exact_carrier) {
+ const char *source =
+ "use std::ops::Add;\n"
+ "struct Alpha;\n"
+ "impl Add for Alpha { type Output = Alpha; fn add(self, _: Alpha) -> Alpha { self } }\n"
+ "fn run(a: Alpha, b: Alpha) { let _ = format!(\"{}\", a + b); }\n";
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+
+ const char *site = strstr(source, "a + b");
+ uint32_t start = site ? (uint32_t)(site - source) : 0;
+ const CBMCall *carrier = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "run") ||
+ !call->callee_name || strcmp(call->callee_name, "add") != 0) {
+ continue;
+ }
+ carrier_count++;
+ carrier = call;
+ }
+ const CBMResolvedCall *hit =
+ carrier ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, carrier, false) : NULL;
+ bool exact = carrier && carrier->requires_lsp_resolution && carrier->site_start_byte == start &&
+ carrier->site_end_byte == start + strlen("a + b") && hit && hit->callee_qn &&
+ strstr(hit->callee_qn, "Alpha.add");
+
+ cbm_free_result(result);
+ ASSERT_EQ(carrier_count, 1);
+ ASSERT_TRUE(exact);
+ PASS();
+}
+
+/* Known std-macro semantic records must identify the source occurrence even
+ * before graph joining. Zero-span records cannot distinguish repetitions. */
+TEST(rustlsp_known_std_macro_resolutions_have_exact_sites) {
+ const char *source = "fn run() {\n"
+ " println!(\"a\");\n"
+ " println!(\"b\");\n"
+ "}\n";
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+
+ const char *first_site = strstr(source, "println!(\"a\")");
+ const char *second_site = strstr(source, "println!(\"b\")");
+ const uint32_t first_start = first_site ? (uint32_t)(first_site - source) : 0;
+ const uint32_t first_end = first_start + (uint32_t)strlen("println!(\"a\")");
+ const uint32_t second_start = second_site ? (uint32_t)(second_site - source) : 0;
+ const uint32_t second_end = second_start + (uint32_t)strlen("println!(\"b\")");
+ int semantic_count = 0;
+ bool first_exact = false;
+ bool second_exact = false;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || !resolved->caller_qn ||
+ !strstr(resolved->caller_qn, "run") || !resolved->callee_qn ||
+ strcmp(resolved->callee_qn, "std.macros.println") != 0 || !resolved->strategy ||
+ strcmp(resolved->strategy, "lsp_macro") != 0) {
+ continue;
+ }
+ semantic_count++;
+ if (resolved->site_start_byte == first_start && resolved->site_end_byte == first_end)
+ first_exact = true;
+ if (resolved->site_start_byte == second_start && resolved->site_end_byte == second_end)
+ second_exact = true;
+ }
+ if (semantic_count != 2 || !first_exact || !second_exact) {
+ printf(" Rust macro semantic-site diagnostic: semantics=%d first_exact=%d "
+ "second_exact=%d\n",
+ semantic_count, first_exact, second_exact);
+ }
+ cbm_free_result(result);
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_TRUE(first_exact);
+ ASSERT_TRUE(second_exact);
+ PASS();
+}
+
+/* Known std macros are declared primary call nodes in the language manifest.
+ * Their parser carriers must exist, demand semantic resolution, and join the
+ * matching occurrence rather than a legacy name-only record. */
+TEST(rustlsp_known_std_macro_carriers_join_exact_sites) {
+ const char *source = "fn run() {\n"
+ " println!(\"a\");\n"
+ " println!(\"b\");\n"
+ "}\n";
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+
+ const char *first_site = strstr(source, "println!(\"a\")");
+ const char *second_site = strstr(source, "println!(\"b\")");
+ const uint32_t first_start = first_site ? (uint32_t)(first_site - source) : 0;
+ const uint32_t first_end = first_start + (uint32_t)strlen("println!(\"a\")");
+ const uint32_t second_start = second_site ? (uint32_t)(second_site - source) : 0;
+ const uint32_t second_end = second_start + (uint32_t)strlen("println!(\"b\")");
+ const CBMCall *first_call = NULL;
+ const CBMCall *second_call = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "run") ||
+ !call->callee_name || strcmp(call->callee_name, "println") != 0) {
+ continue;
+ }
+ carrier_count++;
+ if (call->site_start_byte == first_start && call->site_end_byte == first_end)
+ first_call = call;
+ if (call->site_start_byte == second_start && call->site_end_byte == second_end)
+ second_call = call;
+ }
+ int semantic_count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->caller_qn &&
+ strstr(resolved->caller_qn, "run") && resolved->callee_qn &&
+ strcmp(resolved->callee_qn, "std.macros.println") == 0 && resolved->strategy &&
+ strcmp(resolved->strategy, "lsp_macro") == 0) {
+ semantic_count++;
+ }
+ }
+ const CBMResolvedCall *first_join =
+ first_call ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, first_call, false)
+ : NULL;
+ const CBMResolvedCall *second_join =
+ second_call ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, second_call, false)
+ : NULL;
+ const bool first_exact = first_call && first_call->requires_lsp_resolution && first_join &&
+ first_join->site_start_byte == first_start &&
+ first_join->site_end_byte == first_end;
+ const bool second_exact = second_call && second_call->requires_lsp_resolution && second_join &&
+ second_join->site_start_byte == second_start &&
+ second_join->site_end_byte == second_end;
+
+ if (carrier_count != 2 || semantic_count != 2 || !first_exact || !second_exact) {
+ printf(" Rust macro occurrence diagnostic: carriers=%d semantics=%d first_exact=%d "
+ "second_exact=%d\n",
+ carrier_count, semantic_count, first_exact, second_exact);
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ printf(" carrier[%d] %s %u:%u caller=%s\n", i,
+ call->callee_name ? call->callee_name : "(null)", call->site_start_byte,
+ call->site_end_byte,
+ call->enclosing_func_qn ? call->enclosing_func_qn : "(null)");
+ }
+ }
+ cbm_free_result(result);
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_TRUE(first_exact);
+ ASSERT_TRUE(second_exact);
+ PASS();
+}
+
+/* A local macro_rules! definition has lexical precedence over a prelude macro
+ * with the same name. Expanding it must reveal the local target and must not
+ * also fabricate the canonical std macro semantic. */
+TEST(rustlsp_local_macro_shadows_known_std_macro) {
+ CBMFileResult *result = extract_rust("macro_rules! println { () => { local_target() } }\n"
+ "fn local_target() {}\n"
+ "fn run() { println!(); }\n");
+ ASSERT_NOT_NULL(result);
+
+ int local_count = 0;
+ int std_count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (!resolved->caller_qn || !strstr(resolved->caller_qn, "run") || !resolved->callee_qn) {
+ continue;
+ }
+ if (strstr(resolved->callee_qn, "local_target"))
+ local_count++;
+ if (strcmp(resolved->callee_qn, "std.macros.println") == 0)
+ std_count++;
+ }
+ if (local_count == 0 || std_count != 0) {
+ printf(" Rust macro shadow diagnostic: local=%d std=%d\n", local_count, std_count);
+ }
+ cbm_free_result(result);
+ ASSERT_GTE(local_count, 1);
+ ASSERT_EQ(std_count, 0);
+ PASS();
+}
+
+/* macro_rules! is textually scoped. A definition that appears after the
+ * invocation cannot retroactively replace the prelude macro. */
+TEST(rustlsp_later_macro_does_not_shadow_earlier_std_macro) {
+ CBMFileResult *result = extract_rust("fn run() { println!(); }\n"
+ "macro_rules! println { () => { local_target() } }\n"
+ "fn local_target() {}\n");
+ ASSERT_NOT_NULL(result);
+
+ int local_count = 0;
+ int std_count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (!resolved->caller_qn || !strstr(resolved->caller_qn, "run") || !resolved->callee_qn) {
+ continue;
+ }
+ if (strstr(resolved->callee_qn, "local_target"))
+ local_count++;
+ if (strcmp(resolved->callee_qn, "std.macros.println") == 0)
+ std_count++;
+ }
+ cbm_free_result(result);
+ ASSERT_EQ(local_count, 0);
+ ASSERT_EQ(std_count, 1);
+ PASS();
+}
+
+/* A macro defined in a nested module shadows the prelude only inside that
+ * module. Leaving the module restores the outer macro namespace. */
+TEST(rustlsp_nested_macro_scope_does_not_leak) {
+ CBMFileResult *result = extract_rust("mod nested {\n"
+ " macro_rules! println { () => { nested_target() } }\n"
+ " fn nested_target() {}\n"
+ " fn nested_run() { println!(); }\n"
+ "}\n"
+ "fn outer_run() { println!(); }\n");
+ ASSERT_NOT_NULL(result);
+
+ int nested_local = 0;
+ int nested_std = 0;
+ int outer_local = 0;
+ int outer_std = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &result->resolved_calls.items[i];
+ if (!resolved->caller_qn || !resolved->callee_qn)
+ continue;
+ if (strstr(resolved->caller_qn, "nested_run")) {
+ if (strstr(resolved->callee_qn, "nested_target"))
+ nested_local++;
+ if (strcmp(resolved->callee_qn, "std.macros.println") == 0)
+ nested_std++;
+ }
+ if (strstr(resolved->caller_qn, "outer_run")) {
+ if (strstr(resolved->callee_qn, "nested_target"))
+ outer_local++;
+ if (strcmp(resolved->callee_qn, "std.macros.println") == 0)
+ outer_std++;
+ }
+ }
+ cbm_free_result(result);
+ ASSERT_GTE(nested_local, 1);
+ ASSERT_EQ(nested_std, 0);
+ ASSERT_EQ(outer_local, 0);
+ ASSERT_EQ(outer_std, 1);
+ PASS();
+}
+
+/* A macro_rules! transcriber is generated source, even when its invocation is
+ * discovered while reparsing a built-in macro's real argument tokens. It must
+ * not inherit that outer affine map and fabricate an exact occurrence (or a
+ * graph carrier) for a call that has no one-to-one source span. */
+TEST(rustlsp_nested_macro_rules_call_does_not_inherit_outer_site_map) {
+ const char *source =
+ "macro_rules! hidden { () => {{ let _pad0 = 0; let _pad1 = 1; hidden_target() }}; }\n"
+ "fn hidden_target() {}\n"
+ "fn run() { let _ = format!(\"........................................................\", "
+ "hidden!()); }\n";
+ CBMFileResult *result = extract_rust(source);
+ ASSERT_NOT_NULL(result);
+
+ int semantic_count = 0;
+ int exact_semantic_count = 0;
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &result->resolved_calls.items[i];
+ if (!rc->callee_qn || !strstr(rc->callee_qn, "hidden_target"))
+ continue;
+ semantic_count++;
+ if (rc->site_end_byte > rc->site_start_byte)
+ exact_semantic_count++;
+ }
+ int carrier_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->callee_name && strstr(call->callee_name, "hidden_target"))
+ carrier_count++;
+ }
+
+ cbm_free_result(result);
+ ASSERT_GTE(semantic_count, 1);
+ ASSERT_EQ(exact_semantic_count, 0);
+ ASSERT_EQ(carrier_count, 0);
+ PASS();
+}
+
+/* Ordinary parser-backed calls need occurrence spans too. Without them, two
+ * same-leaf method calls in one caller both join the first Rust semantic
+ * record even though tree-sitter produced two distinct CBMCall sites. */
+TEST(rustlsp_ordinary_same_leaf_calls_join_by_exact_site) {
+ CBMFileResult *result = extract_rust("struct Alpha; impl Alpha { fn render(&self) {} }\n"
+ "struct Beta; impl Beta { fn render(&self) {} }\n"
+ "fn run(a: Alpha, b: Beta) { a.render(); b.render(); }\n");
+ ASSERT_NOT_NULL(result);
+
+ const CBMCall *calls[2] = {0};
+ int call_count = 0;
+ for (int i = 0; i < result->calls.count; i++) {
+ const CBMCall *call = &result->calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "run") &&
+ call->callee_name && strstr(call->callee_name, "render")) {
+ if (call_count < 2)
+ calls[call_count] = call;
+ call_count++;
+ }
+ }
+ if (calls[0] && calls[1] && calls[0]->site_start_byte > calls[1]->site_start_byte) {
+ const CBMCall *tmp = calls[0];
+ calls[0] = calls[1];
+ calls[1] = tmp;
+ }
+ const CBMResolvedCall *alpha_hit =
+ calls[0] ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[0], false)
+ : NULL;
+ const CBMResolvedCall *beta_hit =
+ calls[1] ? cbm_pipeline_find_lsp_resolution(&result->resolved_calls, calls[1], false)
+ : NULL;
+ bool alpha_exact = alpha_hit && alpha_hit->callee_qn &&
+ strstr(alpha_hit->callee_qn, "Alpha.render") &&
+ alpha_hit->site_start_byte == calls[0]->site_start_byte &&
+ alpha_hit->site_end_byte == calls[0]->site_end_byte;
+ bool beta_exact = beta_hit && beta_hit->callee_qn &&
+ strstr(beta_hit->callee_qn, "Beta.render") &&
+ beta_hit->site_start_byte == calls[1]->site_start_byte &&
+ beta_hit->site_end_byte == calls[1]->site_end_byte;
+
+ cbm_free_result(result);
+ ASSERT_EQ(call_count, 2);
+ ASSERT_TRUE(alpha_exact);
+ ASSERT_TRUE(beta_exact);
+ PASS();
+}
+
TEST(rustlsp_crossfile_free_function) {
const char *caller = "fn main() { utils::greet(\"x\"); }\n";
CBMArena a;
@@ -5713,21 +6521,15 @@ TEST(rustlsp_extra_cargo_wires_external_dep) {
PASS();
}
-/* Option B: attribute proc-macro synthesis. */
+/* Proc-macro attributes stay on the definition. The semantic graph passes
+ * consume this field to emit DECORATES + USAGE; Rust LSP must not invent calls
+ * to implementation details that only executing the proc-macro could prove. */
TEST(rustlsp_extra_proc_macro_tokio_main) {
CBMFileResult *r = extract_rust(
"#[tokio::main]\nasync fn main() { let _ = 1; }\n");
ASSERT_NOT_NULL(r);
- /* Synthetic edges from `main` to tokio::runtime::Runtime::new/block_on. */
- bool found_new = false, found_block = false;
- for (int i = 0; i < r->resolved_calls.count; i++) {
- const CBMResolvedCall* rc = &r->resolved_calls.items[i];
- if (!rc->callee_qn) continue;
- if (strstr(rc->callee_qn, "Runtime.new")) found_new = true;
- if (strstr(rc->callee_qn, "Runtime.block_on")) found_block = true;
- }
- ASSERT_EQ(true, found_new);
- ASSERT_EQ(true, found_block);
+ ASSERT_TRUE(rustlsp_definition_has_decorator(r, "main", "#[tokio::main]"));
+ ASSERT_EQ(rustlsp_count_proc_macro_pseudo_calls(r), 0);
cbm_free_result(r); PASS();
}
@@ -5735,14 +6537,8 @@ TEST(rustlsp_extra_proc_macro_tokio_test) {
CBMFileResult *r = extract_rust(
"#[tokio::test]\nasync fn my_test() { let _ = 1; }\n");
ASSERT_NOT_NULL(r);
- bool found_block = false;
- for (int i = 0; i < r->resolved_calls.count; i++) {
- const CBMResolvedCall* rc = &r->resolved_calls.items[i];
- if (rc->callee_qn && strstr(rc->callee_qn, "Runtime.block_on")) {
- found_block = true; break;
- }
- }
- ASSERT_EQ(true, found_block);
+ ASSERT_TRUE(rustlsp_definition_has_decorator(r, "my_test", "#[tokio::test]"));
+ ASSERT_EQ(rustlsp_count_proc_macro_pseudo_calls(r), 0);
cbm_free_result(r); PASS();
}
@@ -5750,14 +6546,8 @@ TEST(rustlsp_extra_proc_macro_tracing_instrument) {
CBMFileResult *r = extract_rust(
"#[tracing::instrument]\nfn work() { let _ = 1; }\n");
ASSERT_NOT_NULL(r);
- bool found = false;
- for (int i = 0; i < r->resolved_calls.count; i++) {
- const CBMResolvedCall* rc = &r->resolved_calls.items[i];
- if (rc->callee_qn && strstr(rc->callee_qn, "Span.enter")) {
- found = true; break;
- }
- }
- ASSERT_EQ(true, found);
+ ASSERT_TRUE(rustlsp_definition_has_decorator(r, "work", "#[tracing::instrument]"));
+ ASSERT_EQ(rustlsp_count_proc_macro_pseudo_calls(r), 0);
cbm_free_result(r); PASS();
}
@@ -5766,16 +6556,23 @@ TEST(rustlsp_extra_proc_macro_unknown_attr_no_false_edge) {
CBMFileResult *r = extract_rust(
"#[my_weird_macro]\nfn main() { let _ = 1; }\n");
ASSERT_NOT_NULL(r);
- for (int i = 0; i < r->resolved_calls.count; i++) {
- const CBMResolvedCall* rc = &r->resolved_calls.items[i];
- if (!rc->callee_qn) continue;
- /* No synthetic Runtime/Span/etc. should appear. */
- ASSERT_EQ(NULL, strstr(rc->callee_qn, "Runtime"));
- ASSERT_EQ(NULL, strstr(rc->callee_qn, "Span.enter"));
- }
+ ASSERT_TRUE(rustlsp_definition_has_decorator(r, "main", "#[my_weird_macro]"));
+ ASSERT_EQ(rustlsp_count_proc_macro_pseudo_calls(r), 0);
cbm_free_result(r); PASS();
}
+/* Similar-looking paths are retained verbatim as attributes, with no hidden
+ * substring matcher capable of manufacturing runtime calls. */
+TEST(rustlsp_proc_macro_match_requires_exact_attribute_path) {
+ CBMFileResult *r = extract_rust("#[not_tokio::main_wrapper]\nasync fn main() {}\n");
+ ASSERT_NOT_NULL(r);
+ ASSERT_TRUE(rustlsp_definition_has_decorator(r, "main", "#[not_tokio::main_wrapper]"));
+ int runtime_records = rustlsp_count_proc_macro_pseudo_calls(r);
+ cbm_free_result(r);
+ ASSERT_EQ(runtime_records, 0);
+ PASS();
+}
+
/* Option A: rustdoc JSON ingestion. */
TEST(rustlsp_extra_rustdoc_ingest_basic_function) {
CBMArena a; cbm_arena_init(&a);
@@ -6015,6 +6812,21 @@ void suite_rust_lsp(void) {
/* Cross-file */
RUN_TEST(rustlsp_crossfile_method_dispatch);
RUN_TEST(rustlsp_shared_registry_resolves_like_per_file);
+ RUN_TEST(rustlsp_relative_type_requires_declared_module);
+ RUN_TEST(rustlsp_relative_type_ambiguous_graph_paths_fail_closed);
+ RUN_TEST(rustlsp_shared_registry_macro_hidden_call_has_carrier);
+ RUN_TEST(rustlsp_shared_dispatch_merges_existing_exact_occurrence);
+ RUN_TEST(rustlsp_scratch_cross_macro_carrier_survives_copy);
+ RUN_TEST(rustlsp_macro_same_leaf_carriers_are_occurrence_exact);
+ RUN_TEST(rustlsp_operator_carriers_are_occurrence_exact);
+ RUN_TEST(rustlsp_macro_operator_has_one_exact_carrier);
+ RUN_TEST(rustlsp_known_std_macro_resolutions_have_exact_sites);
+ RUN_TEST(rustlsp_known_std_macro_carriers_join_exact_sites);
+ RUN_TEST(rustlsp_local_macro_shadows_known_std_macro);
+ RUN_TEST(rustlsp_later_macro_does_not_shadow_earlier_std_macro);
+ RUN_TEST(rustlsp_nested_macro_scope_does_not_leak);
+ RUN_TEST(rustlsp_nested_macro_rules_call_does_not_inherit_outer_site_map);
+ RUN_TEST(rustlsp_ordinary_same_leaf_calls_join_by_exact_site);
RUN_TEST(rustlsp_crossfile_free_function);
/* Robustness */
@@ -6546,6 +7358,7 @@ void suite_rust_lsp(void) {
RUN_TEST(rustlsp_extra_proc_macro_tokio_test);
RUN_TEST(rustlsp_extra_proc_macro_tracing_instrument);
RUN_TEST(rustlsp_extra_proc_macro_unknown_attr_no_false_edge);
+ RUN_TEST(rustlsp_proc_macro_match_requires_exact_attribute_path);
RUN_TEST(rustlsp_extra_rustdoc_ingest_basic_function);
RUN_TEST(rustlsp_extra_rustdoc_ingest_struct_and_trait);
RUN_TEST(rustlsp_extra_rustdoc_handles_malformed);
diff --git a/tests/test_scope.c b/tests/test_scope.c
index b64630a4b..728a77327 100644
--- a/tests/test_scope.c
+++ b/tests/test_scope.c
@@ -108,6 +108,47 @@ TEST(scope_child_shadows_parent) {
PASS();
}
+TEST(scope_callable_identity_follows_nearest_binding) {
+ CBMArena a;
+ cbm_arena_init(&a);
+ CBMScope *root = cbm_scope_push(&a, NULL);
+ CBMScope *child = cbm_scope_push(&a, root);
+ const CBMType *callback_type = named_t(&a, "Callback");
+ cbm_scope_bind_callable(root, "callback", callback_type, "pkg.actual");
+ ASSERT_TRUE(cbm_scope_contains(child, "callback"));
+ ASSERT_STR_EQ(cbm_scope_lookup_callable(child, "callback"), "pkg.actual");
+
+ cbm_scope_bind(child, "callback", named_t(&a, "int"));
+ ASSERT_NULL(cbm_scope_lookup_callable(child, "callback"));
+ ASSERT_STR_EQ(cbm_scope_lookup_callable(root, "callback"), "pkg.actual");
+ cbm_arena_destroy(&a);
+ PASS();
+}
+
+TEST(scope_assignment_updates_or_clears_nearest_callable_only) {
+ CBMArena a;
+ cbm_arena_init(&a);
+ CBMScope *root = cbm_scope_push(&a, NULL);
+ CBMScope *child = cbm_scope_push(&a, root);
+ const CBMType *callback_type = named_t(&a, "Callback");
+ cbm_scope_bind_callable(root, "callback", callback_type, "pkg.actual");
+
+ ASSERT_TRUE(cbm_scope_update_callable(child, "callback", "pkg.alternate"));
+ ASSERT_STR_EQ(cbm_scope_lookup_callable(root, "callback"), "pkg.alternate");
+ ASSERT(cbm_scope_lookup(root, "callback") == callback_type);
+ ASSERT_TRUE(cbm_scope_update_callable(child, "callback", NULL));
+ ASSERT_NULL(cbm_scope_lookup_callable(root, "callback"));
+ ASSERT_FALSE(cbm_scope_update_callable(child, "missing", "pkg.never"));
+
+ cbm_scope_bind_callable(root, "callback", callback_type, "pkg.restored");
+ cbm_scope_bind_callable(child, "callback", callback_type, "pkg.child");
+ ASSERT_TRUE(cbm_scope_update_callable(child, "callback", "pkg.child_new"));
+ ASSERT_STR_EQ(cbm_scope_lookup_callable(child, "callback"), "pkg.child_new");
+ ASSERT_STR_EQ(cbm_scope_lookup_callable(root, "callback"), "pkg.restored");
+ cbm_arena_destroy(&a);
+ PASS();
+}
+
/* ── Dynamic growth — the Phase 0 win ───────────────────────────── */
TEST(scope_dynamic_growth_300_bindings) {
@@ -190,6 +231,8 @@ SUITE(scope) {
RUN_TEST(scope_rebind_overwrites_in_place);
RUN_TEST(scope_lookup_walks_parent_chain);
RUN_TEST(scope_child_shadows_parent);
+ RUN_TEST(scope_callable_identity_follows_nearest_binding);
+ RUN_TEST(scope_assignment_updates_or_clears_nearest_callable_only);
RUN_TEST(scope_dynamic_growth_300_bindings);
RUN_TEST(scope_growth_chunk_boundary);
RUN_TEST(scope_rebind_in_old_chunk);
diff --git a/tests/test_store_checkpoint.c b/tests/test_store_checkpoint.c
index 9097befd7..b581641c4 100644
--- a/tests/test_store_checkpoint.c
+++ b/tests/test_store_checkpoint.c
@@ -13,12 +13,88 @@
#include "test_framework.h"
#include "test_helpers.h"
#include <store/store.h>
+#include <errno.h>
+#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
+static void tsc_cleanup_db(const char *db_path) {
+ char sidecar[512];
+ unlink(db_path);
+ snprintf(sidecar, sizeof(sidecar), "%s-wal", db_path);
+ unlink(sidecar);
+ snprintf(sidecar, sizeof(sidecar), "%s-shm", db_path);
+ unlink(sidecar);
+}
+
+static int tsc_raw_journal_mode(const char *db_path, char *mode, size_t mode_size) {
+ sqlite3 *db = NULL;
+ sqlite3_stmt *stmt = NULL;
+ int ok = 0;
+
+ if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
+ goto done;
+ }
+ if (sqlite3_prepare_v2(db, "PRAGMA journal_mode;", -1, &stmt, NULL) != SQLITE_OK) {
+ goto done;
+ }
+ if (sqlite3_step(stmt) != SQLITE_ROW) {
+ goto done;
+ }
+ const unsigned char *value = sqlite3_column_text(stmt, 0);
+ if (!value || snprintf(mode, mode_size, "%s", (const char *)value) >= (int)mode_size) {
+ goto done;
+ }
+ ok = 1;
+
+done:
+ sqlite3_finalize(stmt);
+ if (db) {
+ sqlite3_close(db);
+ }
+ return ok;
+}
+
+static int tsc_raw_project_count(const char *db_path, const char *project) {
+ sqlite3 *db = NULL;
+ sqlite3_stmt *stmt = NULL;
+ int count = -1;
+
+ if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
+ goto done;
+ }
+ if (sqlite3_prepare_v2(db, "SELECT count(*) FROM projects WHERE name=?1;", -1, &stmt, NULL) !=
+ SQLITE_OK) {
+ goto done;
+ }
+ if (sqlite3_bind_text(stmt, 1, project, -1, SQLITE_STATIC) != SQLITE_OK) {
+ goto done;
+ }
+ if (sqlite3_step(stmt) == SQLITE_ROW) {
+ count = sqlite3_column_int(stmt, 0);
+ }
+
+done:
+ sqlite3_finalize(stmt);
+ if (db) {
+ sqlite3_close(db);
+ }
+ return count;
+}
+
+static int tsc_wal_absent_or_empty(const char *db_path) {
+ char wal_path[512];
+ struct stat st = {0};
+ snprintf(wal_path, sizeof(wal_path), "%s-wal", db_path);
+ if (stat(wal_path, &st) == 0) {
+ return st.st_size == 0;
+ }
+ return errno == ENOENT;
+}
+
TEST(checkpoint_does_not_truncate_wal) {
enum { N_ROWS = 100, PATH_BUF = 256, PATH_BUF_EXT = 300 };
char db_path[PATH_BUF];
@@ -74,6 +150,163 @@ TEST(checkpoint_does_not_truncate_wal) {
PASS();
}
+TEST(seal_for_atomic_publish_makes_main_file_self_contained) {
+ char db_path[256];
+ char wal_path[300];
+ snprintf(db_path, sizeof(db_path), "%s/cbm_test_seal_%d.db", cbm_tmpdir(), (int)getpid());
+ snprintf(wal_path, sizeof(wal_path), "%s-wal", db_path);
+ tsc_cleanup_db(db_path);
+
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(store);
+ ASSERT_EQ(cbm_store_upsert_project(store, "sealed", "/tmp/sealed"), CBM_STORE_OK);
+
+ /* Prove this exercises a live WAL, rather than an already self-contained
+ * database that would make the checkpoint assertion vacuous. */
+ struct stat wal_before = {0};
+ ASSERT_EQ(stat(wal_path, &wal_before), 0);
+ ASSERT_TRUE(wal_before.st_size > 0);
+
+ ASSERT_EQ(cbm_store_seal_for_atomic_publish(store), CBM_STORE_OK);
+
+ /* Verify through an independent raw connection. The marker must be in the
+ * main file and the mode returned by SQLite itself must be DELETE. */
+ char mode[16] = {0};
+ ASSERT_TRUE(tsc_raw_journal_mode(db_path, mode, sizeof(mode)));
+ ASSERT_STR_EQ(mode, "delete");
+ ASSERT_TRUE(tsc_wal_absent_or_empty(db_path));
+ ASSERT_EQ(tsc_raw_project_count(db_path, "sealed"), 1);
+
+ cbm_store_close(store);
+ tsc_cleanup_db(db_path);
+ PASS();
+}
+
+TEST(seal_for_atomic_publish_fails_closed_while_reader_pins_wal) {
+ char db_path[256];
+ char wal_path[300];
+ snprintf(db_path, sizeof(db_path), "%s/cbm_test_seal_busy_%d.db", cbm_tmpdir(), (int)getpid());
+ snprintf(wal_path, sizeof(wal_path), "%s-wal", db_path);
+ tsc_cleanup_db(db_path);
+
+ cbm_store_t *store = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(store);
+ ASSERT_EQ(cbm_store_upsert_project(store, "reader_snapshot", "/tmp/reader"), CBM_STORE_OK);
+
+ /* Hold an actual SELECT row so the raw connection pins its WAL snapshot. */
+ sqlite3 *reader = NULL;
+ sqlite3_stmt *pin = NULL;
+ ASSERT_EQ(sqlite3_open_v2(db_path, &reader, SQLITE_OPEN_READONLY, NULL), SQLITE_OK);
+ ASSERT_EQ(sqlite3_exec(reader, "BEGIN;", NULL, NULL, NULL), SQLITE_OK);
+ ASSERT_EQ(sqlite3_prepare_v2(reader, "SELECT name FROM projects;", -1, &pin, NULL), SQLITE_OK);
+ ASSERT_EQ(sqlite3_step(pin), SQLITE_ROW);
+
+ /* This later frame cannot be folded into the main file while the older
+ * reader snapshot remains pinned. Disable the test connection's timeout so
+ * SQLITE_BUSY is deterministic and immediate. */
+ ASSERT_EQ(cbm_store_upsert_project(store, "after_snapshot", "/tmp/after"), CBM_STORE_OK);
+ ASSERT_EQ(cbm_store_exec(store, "PRAGMA busy_timeout=0;"), CBM_STORE_OK);
+ struct stat wal_before = {0};
+ ASSERT_EQ(stat(wal_path, &wal_before), 0);
+ ASSERT_TRUE(wal_before.st_size > 0);
+ ASSERT_EQ(cbm_store_seal_for_atomic_publish(store), CBM_STORE_ERR);
+
+ /* Releasing the reader must make the exact same store sealable. */
+ ASSERT_EQ(sqlite3_finalize(pin), SQLITE_OK);
+ pin = NULL;
+ ASSERT_EQ(sqlite3_exec(reader, "COMMIT;", NULL, NULL, NULL), SQLITE_OK);
+ ASSERT_EQ(sqlite3_close(reader), SQLITE_OK);
+ reader = NULL;
+ ASSERT_EQ(cbm_store_seal_for_atomic_publish(store), CBM_STORE_OK);
+
+ char mode[16] = {0};
+ ASSERT_TRUE(tsc_raw_journal_mode(db_path, mode, sizeof(mode)));
+ ASSERT_STR_EQ(mode, "delete");
+ ASSERT_TRUE(tsc_wal_absent_or_empty(db_path));
+ ASSERT_EQ(tsc_raw_project_count(db_path, "reader_snapshot"), 1);
+ ASSERT_EQ(tsc_raw_project_count(db_path, "after_snapshot"), 1);
+
+ cbm_store_close(store);
+ tsc_cleanup_db(db_path);
+ PASS();
+}
+
+TEST(cached_count_queries_release_delete_mode_reader_lock) {
+ char db_path[256];
+ snprintf(db_path, sizeof(db_path), "%s/cbm_test_count_lock_%d.db", cbm_tmpdir(), (int)getpid());
+ tsc_cleanup_db(db_path);
+
+ cbm_store_t *setup = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(setup);
+ ASSERT_EQ(cbm_store_upsert_project(setup, "count_lock", "/tmp/count_lock"), CBM_STORE_OK);
+ cbm_node_t node = {.project = "count_lock",
+ .label = "Function",
+ .name = "target",
+ .qualified_name = "count_lock.target",
+ .file_path = "target.c",
+ .start_line = 1,
+ .end_line = 1};
+ ASSERT_TRUE(cbm_store_upsert_node(setup, &node) > 0);
+ ASSERT_EQ(cbm_store_seal_for_atomic_publish(setup), CBM_STORE_OK);
+ cbm_store_close(setup);
+
+ /* index_repository opens a query connection to verify the newly published
+ * DELETE-mode DB. Cached COUNT statements must not remain parked on their
+ * result row, otherwise a following writer cannot switch the DB back to WAL. */
+ cbm_store_t *reader = cbm_store_open_path_query(db_path);
+ ASSERT_NOT_NULL(reader);
+ ASSERT_EQ(cbm_store_count_nodes(reader, "count_lock"), 1);
+ ASSERT_EQ(cbm_store_count_edges(reader, "count_lock"), 0);
+
+ cbm_store_t *writer = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(writer);
+
+ cbm_store_close(writer);
+ cbm_store_close(reader);
+ tsc_cleanup_db(db_path);
+ PASS();
+}
+
+TEST(cached_node_lookups_release_delete_mode_reader_lock) {
+ char db_path[256];
+ snprintf(db_path, sizeof(db_path), "%s/cbm_test_lookup_lock_%d.db", cbm_tmpdir(),
+ (int)getpid());
+ tsc_cleanup_db(db_path);
+
+ cbm_store_t *setup = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(setup);
+ ASSERT_EQ(cbm_store_upsert_project(setup, "lookup_lock", "/tmp/lookup_lock"), CBM_STORE_OK);
+ cbm_node_t node = {.project = "lookup_lock",
+ .label = "Function",
+ .name = "target",
+ .qualified_name = "lookup_lock.target",
+ .file_path = "target.c",
+ .start_line = 1,
+ .end_line = 1};
+ int64_t node_id = cbm_store_upsert_node(setup, &node);
+ ASSERT_TRUE(node_id > 0);
+ ASSERT_EQ(cbm_store_seal_for_atomic_publish(setup), CBM_STORE_OK);
+ cbm_store_close(setup);
+
+ cbm_store_t *reader = cbm_store_open_path_query(db_path);
+ ASSERT_NOT_NULL(reader);
+ cbm_node_t found = {0};
+ ASSERT_EQ(cbm_store_find_node_by_id(reader, node_id, &found), CBM_STORE_OK);
+ cbm_node_free_fields(&found);
+ ASSERT_EQ(cbm_store_find_node_by_qn(reader, "lookup_lock", "lookup_lock.target", &found),
+ CBM_STORE_OK);
+ cbm_node_free_fields(&found);
+ ASSERT_EQ(cbm_store_find_node_by_qn_any(reader, "lookup_lock.target", &found), CBM_STORE_OK);
+ cbm_node_free_fields(&found);
+
+ cbm_store_t *writer = cbm_store_open_path(db_path);
+ ASSERT_NOT_NULL(writer);
+
+ cbm_store_close(writer);
+ cbm_store_close(reader);
+ tsc_cleanup_db(db_path);
+ PASS();
+}
/* #897: any code path installing a fresh DB file must delete the
* destination's -wal/-shm first. SQLite decides whether to replay a WAL
@@ -185,5 +418,9 @@ TEST(dump_install_ignores_stale_wal_sidecar) {
SUITE(store_checkpoint) {
RUN_TEST(checkpoint_does_not_truncate_wal);
+ RUN_TEST(seal_for_atomic_publish_makes_main_file_self_contained);
+ RUN_TEST(seal_for_atomic_publish_fails_closed_while_reader_pins_wal);
+ RUN_TEST(cached_count_queries_release_delete_mode_reader_lock);
+ RUN_TEST(cached_node_lookups_release_delete_mode_reader_lock);
RUN_TEST(dump_install_ignores_stale_wal_sidecar);
}
diff --git a/tests/test_ts_lsp.c b/tests/test_ts_lsp.c
index cc150cc3e..47d3b1d83 100644
--- a/tests/test_ts_lsp.c
+++ b/tests/test_ts_lsp.c
@@ -24,6 +24,7 @@
#include "test_framework.h"
#include "cbm.h"
#include "../src/foundation/compat.h"
+#include "../src/pipeline/lsp_resolve.h"
#include "lsp/ts_lsp.h"
/* ── Helpers ───────────────────────────────────────────────────────────────── */
@@ -73,6 +74,88 @@ static int require_resolved(const CBMFileResult *r, const char *callerSub, const
return idx;
}
+/* Verify that two parser-backed calls with the same method leaf retain their
+ * own source occurrence all the way through semantic resolution. A leaf-only
+ * join can otherwise attach both carriers to whichever `render` target was
+ * emitted first. */
+static bool ts_same_leaf_render_occurrences_are_exact(const CBMFileResult *r, const char *source) {
+ static const char alpha_text[] = "a.render()";
+ static const char beta_text[] = "b.render()";
+ const char *alpha_site = source ? strstr(source, alpha_text) : NULL;
+ const char *beta_site = source ? strstr(source, beta_text) : NULL;
+ if (!r || !alpha_site || !beta_site)
+ return false;
+
+ const uint32_t alpha_start = (uint32_t)(alpha_site - source);
+ const uint32_t alpha_end = alpha_start + (uint32_t)strlen(alpha_text);
+ const uint32_t beta_start = (uint32_t)(beta_site - source);
+ const uint32_t beta_end = beta_start + (uint32_t)strlen(beta_text);
+ const CBMCall *alpha_call = NULL;
+ const CBMCall *beta_call = NULL;
+ int carrier_count = 0;
+ int zero_span_carriers = 0;
+
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "occurrenceProbe") ||
+ !call->callee_name || !strstr(call->callee_name, "render")) {
+ continue;
+ }
+ carrier_count++;
+ if (call->site_end_byte <= call->site_start_byte)
+ zero_span_carriers++;
+ if (call->site_start_byte == alpha_start && call->site_end_byte == alpha_end)
+ alpha_call = call;
+ if (call->site_start_byte == beta_start && call->site_end_byte == beta_end)
+ beta_call = call;
+ }
+
+ const CBMResolvedCall *alpha_semantic = NULL;
+ const CBMResolvedCall *beta_semantic = NULL;
+ int semantic_count = 0;
+ int zero_span_semantics = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &r->resolved_calls.items[i];
+ if (resolved->kind != CBM_RESOLVED_INVOCATION || resolved->confidence <= 0 ||
+ !resolved->caller_qn || !strstr(resolved->caller_qn, "occurrenceProbe") ||
+ !resolved->callee_qn || !strstr(resolved->callee_qn, ".render")) {
+ continue;
+ }
+ semantic_count++;
+ if (resolved->site_end_byte <= resolved->site_start_byte)
+ zero_span_semantics++;
+ if (strstr(resolved->callee_qn, ".Alpha.render"))
+ alpha_semantic = resolved;
+ if (strstr(resolved->callee_qn, ".Beta.render"))
+ beta_semantic = resolved;
+ }
+
+ const CBMResolvedCall *alpha_join =
+ alpha_call ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, alpha_call, false) : NULL;
+ const CBMResolvedCall *beta_join =
+ beta_call ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, beta_call, false) : NULL;
+
+ const bool alpha_exact = alpha_call && alpha_semantic && alpha_join == alpha_semantic &&
+ alpha_semantic->site_start_byte == alpha_call->site_start_byte &&
+ alpha_semantic->site_end_byte == alpha_call->site_end_byte;
+ const bool beta_exact = beta_call && beta_semantic && beta_join == beta_semantic &&
+ beta_semantic->site_start_byte == beta_call->site_start_byte &&
+ beta_semantic->site_end_byte == beta_call->site_end_byte;
+ const bool distinct = alpha_call && beta_call && alpha_semantic && beta_semantic &&
+ alpha_call != beta_call && alpha_semantic != beta_semantic &&
+ alpha_call->site_start_byte != beta_call->site_start_byte;
+
+ if (carrier_count != 2 || semantic_count != 2 || zero_span_carriers != 0 ||
+ zero_span_semantics != 0 || !alpha_exact || !beta_exact || !distinct) {
+ printf(" same-leaf occurrence identity: carriers=%d zero_carriers=%d semantics=%d "
+ "zero_semantics=%d alpha_exact=%d beta_exact=%d distinct=%d\n",
+ carrier_count, zero_span_carriers, semantic_count, zero_span_semantics, alpha_exact,
+ beta_exact, distinct);
+ }
+ return carrier_count == 2 && semantic_count == 2 && zero_span_carriers == 0 &&
+ zero_span_semantics == 0 && alpha_exact && beta_exact && distinct;
+}
+
/* ── Category 0: smoke (Phase 1 carryover) ─────────────────────────────────── */
TEST(tslsp_smoke_empty_file) {
@@ -943,6 +1026,147 @@ TEST(tslsp_jsx_component_with_children) {
PASS();
}
+/* An import binding proves lexical ownership, but the raw module specifier is
+ * not itself proof that the imported component exists. Keep the site
+ * unresolved until the cross-file registry materializes the exact symbol; a
+ * guessed `<specifier>.MissingCard` target can otherwise suppress that pass and
+ * disappear (or point at a fabricated callable) in the graph builder. */
+TEST(tslsp_jsx_import_requires_registered_component) {
+ CBMFileResult *r = extract_tsx("import { MissingCard } from '@app/missing-card';\n"
+ "function App(): JSX.Element { return <MissingCard />; }\n");
+ ASSERT_NOT_NULL(r);
+
+ int confident = 0;
+ int unresolved = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &r->resolved_calls.items[i];
+ if (!resolved->caller_qn || !strstr(resolved->caller_qn, "App") || !resolved->callee_qn ||
+ !strstr(resolved->callee_qn, "MissingCard")) {
+ continue;
+ }
+ if (resolved->kind == CBM_RESOLVED_INVOCATION &&
+ resolved->confidence >= CBM_LSP_CONFIDENCE_FLOOR) {
+ confident++;
+ }
+ if (resolved->strategy && strcmp(resolved->strategy, "lsp_unresolved") == 0 &&
+ resolved->reason && strcmp(resolved->reason, "jsx_component_not_in_registry") == 0) {
+ unresolved++;
+ }
+ }
+
+ cbm_free_result(r);
+ ASSERT_EQ(confident, 0);
+ ASSERT_EQ(unresolved, 1);
+ PASS();
+}
+
+/* JSX components are parser-backed call occurrences. Repeated components in
+ * one caller must retain the opening tag that produced each semantic record;
+ * a legacy 0:0 record can join both carriers to the first matching target. */
+TEST(tslsp_jsx_component_resolutions_join_exact_tag_sites) {
+ const char *source =
+ "function Card(): JSX.Element { return <span/>; }\n"
+ "function App(): JSX.Element { return <div><Card/><Card>child</Card></div>; }\n";
+ CBMFileResult *r = extract_tsx(source);
+ ASSERT_NOT_NULL(r);
+
+ const char *self_site = strstr(source, "<Card/>");
+ const char *open_site = strstr(source, "<Card>child");
+ const uint32_t self_start = self_site ? (uint32_t)(self_site - source) : 0;
+ const uint32_t self_end = self_start + (uint32_t)strlen("<Card/>");
+ const uint32_t open_start = open_site ? (uint32_t)(open_site - source) : 0;
+ const uint32_t open_end = open_start + (uint32_t)strlen("<Card>");
+ const CBMCall *self_call = NULL;
+ const CBMCall *open_call = NULL;
+ int carrier_count = 0;
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (!call->enclosing_func_qn || !strstr(call->enclosing_func_qn, "App") ||
+ !call->callee_name || strcmp(call->callee_name, "Card") != 0) {
+ continue;
+ }
+ carrier_count++;
+ if (call->site_start_byte == self_start && call->site_end_byte == self_end)
+ self_call = call;
+ if (call->site_start_byte == open_start && call->site_end_byte == open_end)
+ open_call = call;
+ }
+
+ int semantic_count = 0;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &r->resolved_calls.items[i];
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->caller_qn &&
+ strstr(resolved->caller_qn, "App") && resolved->callee_qn &&
+ strstr(resolved->callee_qn, ".Card") && resolved->strategy &&
+ strcmp(resolved->strategy, "lsp_ts_jsx") == 0) {
+ semantic_count++;
+ }
+ }
+ const CBMResolvedCall *self_join =
+ self_call ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, self_call, false) : NULL;
+ const CBMResolvedCall *open_join =
+ open_call ? cbm_pipeline_find_lsp_resolution(&r->resolved_calls, open_call, false) : NULL;
+ const bool self_exact = self_join && self_join->site_start_byte == self_start &&
+ self_join->site_end_byte == self_end;
+ const bool open_exact = open_join && open_join->site_start_byte == open_start &&
+ open_join->site_end_byte == open_end;
+
+ if (carrier_count != 2 || semantic_count != 2 || !self_exact || !open_exact) {
+ printf(" JSX occurrence diagnostic: carriers=%d semantics=%d self_exact=%d "
+ "open_exact=%d\n",
+ carrier_count, semantic_count, self_exact, open_exact);
+ }
+ cbm_free_result(r);
+ ASSERT_EQ(carrier_count, 2);
+ ASSERT_EQ(semantic_count, 2);
+ ASSERT_TRUE(self_exact);
+ ASSERT_TRUE(open_exact);
+ PASS();
+}
+
+/* A callable value named like a module component owns the JSX tag. The LSP
+ * pass must not confidently redirect it to the module function, and the
+ * carrier must require semantic resolution so graph construction cannot do
+ * the same redirect via textual fallback. */
+TEST(tslsp_jsx_local_tag_shadow_blocks_module_component) {
+ const char *source =
+ "function Card(): JSX.Element { return <div/>; }\n"
+ "function Shadowed(Card: () => JSX.Element): JSX.Element { return <Card/>; }\n";
+ CBMFileResult *r = extract_tsx(source);
+ ASSERT_NOT_NULL(r);
+
+ const char *site = strstr(source, "<Card/>");
+ const uint32_t start = site ? (uint32_t)(site - source) : 0;
+ const uint32_t end = start + (uint32_t)strlen("<Card/>");
+ int wrong_semantics = 0;
+ bool gated_carrier = false;
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *resolved = &r->resolved_calls.items[i];
+ if (resolved->kind == CBM_RESOLVED_INVOCATION && resolved->confidence >= 0.6f &&
+ resolved->caller_qn && strstr(resolved->caller_qn, "Shadowed") && resolved->callee_qn &&
+ strstr(resolved->callee_qn, ".Card")) {
+ wrong_semantics++;
+ }
+ }
+ for (int i = 0; i < r->calls.count; i++) {
+ const CBMCall *call = &r->calls.items[i];
+ if (call->enclosing_func_qn && strstr(call->enclosing_func_qn, "Shadowed") &&
+ call->callee_name && strcmp(call->callee_name, "Card") == 0 &&
+ call->site_start_byte == start && call->site_end_byte == end &&
+ call->requires_lsp_resolution) {
+ gated_carrier = true;
+ }
+ }
+ if (wrong_semantics != 0 || !gated_carrier) {
+ printf(" JSX shadow diagnostic: wrong_semantics=%d gated_carrier=%d\n", wrong_semantics,
+ gated_carrier);
+ }
+ cbm_free_result(r);
+ ASSERT_EQ(wrong_semantics, 0);
+ ASSERT_TRUE(gated_carrier);
+ PASS();
+}
+
TEST(tslsp_jsx_intrinsic_skipped) {
CBMFileResult *r = extract_tsx("function go(): JSX.Element { return <div>plain</div>; }\n");
ASSERT_NOT_NULL(r);
@@ -1270,6 +1494,34 @@ TEST(tslsp_nocrash_namespace) {
CBMFileResult *r = extract_ts("namespace MyNS { export function inner(): void {} }\n"
"function go() { MyNS.inner(); }\n");
ASSERT_NOT_NULL(r);
+ ASSERT_GTE(require_resolved(r, ".go", ".MyNS.inner"), 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(tslsp_imported_namespace_shadows_local_namespace) {
+ CBMFileResult *r = extract_ts("import * as MyNS from './external';\n"
+ "namespace MyNS { export function inner(): void {} }\n"
+ "function go() { MyNS.inner(); }\n");
+ ASSERT_NOT_NULL(r);
+ ASSERT_EQ(find_resolved(r, ".go", ".MyNS.inner"), -1);
+ cbm_free_result(r);
+ PASS();
+}
+
+TEST(tslsp_nested_namespace_preserves_exact_callers) {
+ CBMFileResult *r = extract_ts("namespace App {\n"
+ " export namespace Utils {\n"
+ " export function clamp(): number { return 1; }\n"
+ " export function normalise(): number { return clamp(); }\n"
+ " }\n"
+ " export class Config {\n"
+ " constructor() { Utils.normalise(); }\n"
+ " }\n"
+ "}\n");
+ ASSERT_NOT_NULL(r);
+ ASSERT_GTE(require_resolved(r, ".App.Utils.normalise", ".App.Utils.clamp"), 0);
+ ASSERT_GTE(require_resolved(r, ".App.Config.constructor", ".App.Utils.normalise"), 0);
cbm_free_result(r);
PASS();
}
@@ -3501,6 +3753,24 @@ TEST(tslsp_hash_registry_post_finalize_adds) {
t.qualified_name = "test.A";
t.short_name = "A";
cbm_registry_add_type(&reg, t);
+
+ const CBMType *zero_param_signature = cbm_type_func(&arena, NULL, NULL, NULL);
+ CBMRegisteredFunc seed_method;
+ memset(&seed_method, 0, sizeof(seed_method));
+ seed_method.qualified_name = "test.A.seed";
+ seed_method.short_name = "seed";
+ seed_method.receiver_type = "test.A";
+ seed_method.signature = zero_param_signature;
+ seed_method.min_params = 0;
+ cbm_registry_add_func(&reg, seed_method);
+
+ CBMRegisteredFunc seed_free;
+ memset(&seed_free, 0, sizeof(seed_free));
+ seed_free.qualified_name = "test.seed";
+ seed_free.short_name = "seed";
+ seed_free.signature = zero_param_signature;
+ seed_free.min_params = 0;
+ cbm_registry_add_func(&reg, seed_free);
cbm_registry_finalize(&reg);
/* Post-finalize additions — the stub-registration pattern. */
@@ -3515,17 +3785,41 @@ TEST(tslsp_hash_registry_post_finalize_adds) {
f2.qualified_name = "test.LateStub.run";
f2.short_name = "run";
f2.receiver_type = "test.LateStub";
- f2.min_params = -1;
+ f2.signature = zero_param_signature;
+ f2.min_params = 0;
cbm_registry_add_func(&reg, f2);
+ CBMRegisteredFunc late_free;
+ memset(&late_free, 0, sizeof(late_free));
+ late_free.qualified_name = "test.lateFree";
+ late_free.short_name = "lateFree";
+ late_free.signature = zero_param_signature;
+ late_free.min_params = 0;
+ cbm_registry_add_func(&reg, late_free);
+
ASSERT_NOT_NULL(cbm_registry_lookup_type(&reg, "test.A"));
ASSERT_NOT_NULL(cbm_registry_lookup_type(&reg, "test.LateStub"));
ASSERT_NOT_NULL(cbm_registry_lookup_func(&reg, "test.LateStub.run"));
+ const CBMType *no_arg_types[1] = {NULL};
+ bool method_args = cbm_registry_lookup_method_by_args(&reg, "test.LateStub", "run", 0) != NULL;
+ bool method_types =
+ cbm_registry_lookup_method_by_types(&reg, "test.LateStub", "run", no_arg_types, 0) != NULL;
+ bool symbol_args = cbm_registry_lookup_symbol_by_args(&reg, "test", "lateFree", 0) != NULL;
+ bool symbol_types =
+ cbm_registry_lookup_symbol_by_types(&reg, "test", "lateFree", no_arg_types, 0) != NULL;
+ if (!method_args || !method_types || !symbol_args || !symbol_types) {
+ printf(" post-finalize overload tail: method_args=%d method_types=%d "
+ "symbol_args=%d symbol_types=%d\n",
+ method_args, method_types, symbol_args, symbol_types);
+ }
+ ASSERT(method_args && method_types && symbol_args && symbol_types);
/* Re-finalize folds the tail into the buckets; still findable. */
cbm_registry_finalize(&reg);
ASSERT_NOT_NULL(cbm_registry_lookup_type(&reg, "test.LateStub"));
ASSERT_NOT_NULL(cbm_registry_lookup_func(&reg, "test.LateStub.run"));
+ ASSERT_NOT_NULL(cbm_registry_lookup_method_by_args(&reg, "test.LateStub", "run", 0));
+ ASSERT_NOT_NULL(cbm_registry_lookup_symbol_by_args(&reg, "test", "lateFree", 0));
cbm_arena_destroy(&arena);
PASS();
@@ -3834,6 +4128,59 @@ TEST(tslsp_nested_class_resolution) {
PASS();
}
+/* JavaScript relies on local `new` inference here, while TypeScript and TSX use
+ * explicit parameter types below. All three parser modes must preserve the
+ * full ordinary call-expression span, independent of JSX-specific behavior. */
+TEST(tslsp_js_ordinary_same_leaf_calls_join_by_exact_site) {
+ static const char source[] = "class Alpha { render() {} }\n"
+ "class Beta { render() {} }\n"
+ "function occurrenceProbe() {\n"
+ " const a = new Alpha();\n"
+ " const b = new Beta();\n"
+ " a.render();\n"
+ " b.render();\n"
+ "}\n";
+ CBMFileResult *r = extract_js(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error || r->parse_incomplete);
+ const bool exact = ts_same_leaf_render_occurrences_are_exact(r, source);
+ cbm_free_result(r);
+ ASSERT_TRUE(exact);
+ PASS();
+}
+
+TEST(tslsp_ts_ordinary_same_leaf_calls_join_by_exact_site) {
+ static const char source[] = "class Alpha { render(): void {} }\n"
+ "class Beta { render(): void {} }\n"
+ "function occurrenceProbe(a: Alpha, b: Beta): void {\n"
+ " a.render();\n"
+ " b.render();\n"
+ "}\n";
+ CBMFileResult *r = extract_ts(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error || r->parse_incomplete);
+ const bool exact = ts_same_leaf_render_occurrences_are_exact(r, source);
+ cbm_free_result(r);
+ ASSERT_TRUE(exact);
+ PASS();
+}
+
+TEST(tslsp_tsx_ordinary_same_leaf_calls_join_by_exact_site) {
+ static const char source[] = "class Alpha { render(): void {} }\n"
+ "class Beta { render(): void {} }\n"
+ "function occurrenceProbe(a: Alpha, b: Beta): void {\n"
+ " a.render();\n"
+ " b.render();\n"
+ "}\n";
+ CBMFileResult *r = extract_tsx(source);
+ ASSERT_NOT_NULL(r);
+ ASSERT_FALSE(r->has_error || r->parse_incomplete);
+ const bool exact = ts_same_leaf_render_occurrences_are_exact(r, source);
+ cbm_free_result(r);
+ ASSERT_TRUE(exact);
+ PASS();
+}
+
/* ── Suite registration ────────────────────────────────────────────────────── */
SUITE(ts_lsp) {
@@ -3973,6 +4320,9 @@ SUITE(ts_lsp) {
/* Category 22: JSX */
RUN_TEST(tslsp_jsx_component_self_closing);
RUN_TEST(tslsp_jsx_component_with_children);
+ RUN_TEST(tslsp_jsx_import_requires_registered_component);
+ RUN_TEST(tslsp_jsx_component_resolutions_join_exact_tag_sites);
+ RUN_TEST(tslsp_jsx_local_tag_shadow_blocks_module_component);
RUN_TEST(tslsp_jsx_intrinsic_skipped);
RUN_TEST(tslsp_jsx_nested_component);
@@ -4018,6 +4368,8 @@ SUITE(ts_lsp) {
/* More crash-safety */
RUN_TEST(tslsp_nocrash_enum_basic);
RUN_TEST(tslsp_nocrash_namespace);
+ RUN_TEST(tslsp_imported_namespace_shadows_local_namespace);
+ RUN_TEST(tslsp_nested_namespace_preserves_exact_callers);
RUN_TEST(tslsp_nocrash_async_generator);
RUN_TEST(tslsp_nocrash_template_literal_expr);
RUN_TEST(tslsp_nocrash_complex_generic_constraint);
@@ -4288,4 +4640,9 @@ SUITE(ts_lsp) {
RUN_TEST(tslsp_optional_property_chain);
RUN_TEST(tslsp_void_returning_method);
RUN_TEST(tslsp_nested_class_resolution);
+
+ /* Ordinary same-leaf occurrence identity (JS / TS / TSX). */
+ RUN_TEST(tslsp_js_ordinary_same_leaf_calls_join_by_exact_site);
+ RUN_TEST(tslsp_ts_ordinary_same_leaf_calls_join_by_exact_site);
+ RUN_TEST(tslsp_tsx_ordinary_same_leaf_calls_join_by_exact_site);
}