mirror of
https://github.com/DeusData/codebase-memory-mcp.git
synced 2026-12-02 04:17:04 +08:00
Merge origin/main into feat/vbnet-structural-extraction
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
This commit is contained in:
+33
-4
@@ -532,6 +532,7 @@ PIPELINE_SRCS = \
|
||||
src/pipeline/pass_calls.c \
|
||||
src/pipeline/pass_spawns.c \
|
||||
src/pipeline/pass_lsp_cross.c \
|
||||
src/pipeline/type_scope.c \
|
||||
src/pipeline/pass_usages.c \
|
||||
src/pipeline/pass_semantic.c \
|
||||
src/pipeline/pass_tests.c \
|
||||
@@ -848,7 +849,8 @@ TEST_DAEMON_SRCS = \
|
||||
tests/test_daemon_application.c \
|
||||
tests/test_daemon_frontend.c \
|
||||
tests/test_daemon_bootstrap.c \
|
||||
tests/test_daemon_ipc.c
|
||||
tests/test_daemon_ipc.c \
|
||||
tests/image_probe_roles.c
|
||||
|
||||
TEST_DISCOVER_SRCS = \
|
||||
tests/test_language.c \
|
||||
@@ -870,7 +872,7 @@ TEST_DISCOVER_SRCS = \
|
||||
|
||||
TEST_GRAPH_BUFFER_SRCS = tests/test_graph_buffer.c
|
||||
|
||||
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c
|
||||
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c
|
||||
|
||||
TEST_WATCHER_SRCS = tests/test_watcher.c tests/test_svn_state.c
|
||||
|
||||
@@ -1213,7 +1215,34 @@ $(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) $(PROJECT_HDRS) | $(BUILD_DIR)
|
||||
# ── Image probe (tests/test_image_probe.h) ──────────────────────
|
||||
# The small executable that copied-image and install tests run or publish
|
||||
# instead of a copy of the runner: the daemon runtime, foundation and the probe
|
||||
# roles, ~5 MB against ~800 MB for the sanitized runner, every full SHA-256 of
|
||||
# which costs 70-95 s on some hosted x86 CPUs. One beside each runner flavour,
|
||||
# built with that flavour's flags and found by the runner's own name
|
||||
# (<runner>-image-probe), so every venue that builds a runner builds its probe:
|
||||
# each runner rule lists its probe as an order-only prerequisite. Coverage
|
||||
# instrumentation stays out: the probe's profile must never land in the
|
||||
# per-test profile of the runner that started it.
|
||||
# workspace.c (needs mcp.c's path check) and slab_alloc.c (needs the tree-sitter
|
||||
# runtime) serve the indexer, not the daemon runtime, so the probe leaves them out.
|
||||
IMAGE_PROBE_FOUNDATION_SRCS = $(filter-out src/foundation/workspace.c src/foundation/slab_alloc.c,$(FOUNDATION_SRCS))
|
||||
IMAGE_PROBE_SRCS = tests/image_probe_main.c tests/image_probe_roles.c \
|
||||
src/daemon/daemon.c src/daemon/ipc.c src/daemon/runtime.c \
|
||||
src/daemon/service.c $(IMAGE_PROBE_FOUNDATION_SRCS)
|
||||
CFLAGS_IMAGE_PROBE = $(filter-out $(TEST_COVERAGE_FLAGS) $(TEST_COVERAGE_DEFINE),$(CFLAGS_TEST))
|
||||
|
||||
# TRE_OBJ_* is empty except on Windows, where compat_regex.c is backed by TRE.
|
||||
$(BUILD_DIR)/test-runner-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) $(TRE_OBJ_TEST) $(PROJECT_HDRS) | $(BUILD_DIR)
|
||||
$(CC) $(CFLAGS_IMAGE_PROBE) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TEST) \
|
||||
$(TRE_OBJ_TEST) $(LDFLAGS_TEST)
|
||||
|
||||
$(BUILD_DIR)/test-runner-tsan-image-probe: $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR)
|
||||
$(CC) $(CFLAGS_TSAN) -Itests -o $@ $(IMAGE_PROBE_SRCS) $(MIMALLOC_OBJ_TSAN) $(TRE_OBJ_TSAN) \
|
||||
$(LDFLAGS_TSAN)
|
||||
|
||||
$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-image-probe
|
||||
$(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \
|
||||
$(ALL_TEST_SRCS) $(PROD_SRCS) \
|
||||
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
|
||||
@@ -1301,7 +1330,7 @@ TSAN_OPTIONS ?= halt_on_error=1:report_thread_leaks=0
|
||||
# Normal ASan/native/soak paths remain uncapped. High-worker TSan diagnostics
|
||||
# invoke test-runner-tsan directly so release gates cannot drift accidentally.
|
||||
|
||||
$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR)
|
||||
$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR) $(BUILD_DIR)/test-runner-tsan-image-probe
|
||||
$(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -o $@ \
|
||||
$(ALL_TEST_SRCS) $(PROD_SRCS) \
|
||||
$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \
|
||||
|
||||
+132
-15
@@ -28,6 +28,7 @@
|
||||
#include "cpp_branch_views.h"
|
||||
#include "foundation/compat.h"
|
||||
#include "foundation/compat_fs.h" // cbm_fopen — crash-supervisor per-file marker write
|
||||
#include "foundation/limits.h" // cbm_max_file_bytes — headers read by the #include lookup
|
||||
#include "foundation/hash_table.h" // CBMHashTable — crash-supervisor quarantine set
|
||||
#include "foundation/str_util.h" // cbm_json_escape — variants file_path
|
||||
#include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState
|
||||
@@ -3319,15 +3320,59 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguage
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The grammars built on tree-sitter-c: same set as cbm_conditional_block_types
|
||||
* minus C#, which has no backslash line splices. */
|
||||
static bool c_splice_lang(CBMLanguage language) {
|
||||
return language == CBM_LANG_C || language == CBM_LANG_CPP || language == CBM_LANG_CUDA ||
|
||||
language == CBM_LANG_OBJC || language == CBM_LANG_GLSL || language == CBM_LANG_HLSL ||
|
||||
language == CBM_LANG_ISPC || language == CBM_LANG_SLANG;
|
||||
}
|
||||
|
||||
/* #1546: these grammars read a backslash line splice inside a string literal
|
||||
* as an escape_sequence, `\` plus one character. With CRLF line endings that
|
||||
* character is the CR, the LF then ends the literal, and the rest of the
|
||||
* function, often the rest of the file, becomes one ERROR region.
|
||||
* Each `\` CR LF becomes space `\` LF: the same length, the line break in the
|
||||
* same place, so offsets and line numbers still refer to the file on disk and
|
||||
* the next line is byte-identical. Copied only when a splice is found. The
|
||||
* cross-file C/C++ LSP pass reads the file again and applies it too. */
|
||||
const char *cbm_c_mask_crlf_splices(CBMArena *a, const char *source, int source_len) {
|
||||
if (!a || !source) {
|
||||
return source;
|
||||
}
|
||||
char *out = NULL;
|
||||
for (int i = 0; i + PAIR_LEN < source_len; i++) {
|
||||
if (source[i] != '\\' || source[i + SKIP_ONE] != '\r' || source[i + PAIR_LEN] != '\n') {
|
||||
continue;
|
||||
}
|
||||
if (!out) {
|
||||
out = (char *)cbm_arena_alloc(a, (size_t)source_len + SKIP_ONE);
|
||||
if (!out) {
|
||||
return source;
|
||||
}
|
||||
memcpy(out, source, (size_t)source_len);
|
||||
out[source_len] = '\0';
|
||||
}
|
||||
out[i] = ' ';
|
||||
out[i + SKIP_ONE] = '\\';
|
||||
i += PAIR_LEN;
|
||||
}
|
||||
return out ? out : source;
|
||||
}
|
||||
|
||||
/* The bytes the grammar parses. PHP that leaves PHP mode (`?> markup <?php`)
|
||||
* is parsed with its markup blanked (#2000); the rewrite keeps the length and
|
||||
* every line break, so offsets and line numbers still refer to the file on
|
||||
* disk. Every other language parses the file as it is. */
|
||||
* is parsed with its markup blanked (#2000), and a C-family line splice before
|
||||
* a CRLF is rewritten (#1546); both rewrites keep the length and every line
|
||||
* break, so offsets and line numbers still refer to the file on disk. Every
|
||||
* other language parses the file as it is. */
|
||||
static const char *extract_parse_bytes(CBMArena *a, CBMLanguage language, const char *source,
|
||||
int source_len) {
|
||||
if (language == CBM_LANG_PHP) {
|
||||
return cbm_php_mask_inline_html(a, source, source_len);
|
||||
}
|
||||
if (c_splice_lang(language)) {
|
||||
return cbm_c_mask_crlf_splices(a, source, source_len);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
@@ -3779,14 +3824,81 @@ static void cbm_swift_type_imports(CBMFileResult *result, CBMLanguage language)
|
||||
}
|
||||
}
|
||||
|
||||
static CBMFileResult *extract_file_ex_body(const char *source, int source_len, CBMLanguage language,
|
||||
const char *project, const char *rel_path,
|
||||
int64_t timeout_micros, const char **extra_defines,
|
||||
const char **include_paths,
|
||||
const CBMMacroTable *macro_table,
|
||||
const CBMReturnTypeTable *return_type_table,
|
||||
CBMArena *scratch,
|
||||
const cbm_test_declarations_t *test_declarations) {
|
||||
/* ── #include lookup of the preprocessed pass (#2993) ──────────────
|
||||
* Quoted #include names of the C-family second pass resolve against the
|
||||
* indexed repository: preprocessor.cpp hands over a normalised, root-relative
|
||||
* name, and the header is read only when it is one of the files the index run
|
||||
* covers (CBMIncludeScope.is_indexed; discovery has already applied its rules:
|
||||
* no symlinks or junctions, ignore files, skipped directories), within the
|
||||
* per-file size cap. Every file the expansion depends on is therefore in the
|
||||
* run's manifest. Paths are UTF-8, opened through cbm_fopen. */
|
||||
static char *include_tree_read(const void *userdata, const char *rel_path, size_t *out_len) {
|
||||
const CBMIncludeScope *scope = (const CBMIncludeScope *)userdata;
|
||||
if (!rel_path[0] || !scope->is_indexed || !scope->is_indexed(scope->userdata, rel_path)) {
|
||||
return NULL;
|
||||
}
|
||||
size_t root_len = strlen(scope->root);
|
||||
bool sep =
|
||||
root_len > 0 && scope->root[root_len - 1] != '/' && scope->root[root_len - 1] != '\\';
|
||||
char path[CBM_SZ_4K];
|
||||
int written = snprintf(path, sizeof(path), "%s%s%s", scope->root, sep ? "/" : "", rel_path);
|
||||
if (written < 0 || (size_t)written >= sizeof(path)) {
|
||||
return NULL;
|
||||
}
|
||||
FILE *f = cbm_fopen(path, "rb");
|
||||
if (!f) {
|
||||
return NULL;
|
||||
}
|
||||
long size = fseek(f, 0, SEEK_END) == 0 ? ftell(f) : -1;
|
||||
if (size < 0 || size > cbm_max_file_bytes() || fseek(f, 0, SEEK_SET) != 0) {
|
||||
(void)fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
char *data = (char *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)size + 1);
|
||||
size_t got = data && size > 0 ? fread(data, 1, (size_t)size, f) : 0;
|
||||
(void)fclose(f);
|
||||
if (data) {
|
||||
data[got] = '\0';
|
||||
*out_len = got;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
static void include_tree_release(const void *userdata, char *data) {
|
||||
(void)userdata;
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, data);
|
||||
}
|
||||
|
||||
/* result->included_files from what the preprocessed pass's lookup read. An
|
||||
* allocation failure marks the result as failed: a missing list would let an
|
||||
* incremental refresh skip this file after one of its headers changed. */
|
||||
static void record_included_files(CBMArena *a, CBMFileResult *result,
|
||||
const CBMPreprocessedSource *pp) {
|
||||
if (!pp || pp->included_count <= 0) {
|
||||
return;
|
||||
}
|
||||
const char **list =
|
||||
(const char **)cbm_arena_alloc(a, ((size_t)pp->included_count + 1) * sizeof(char *));
|
||||
for (int i = 0; list && i < pp->included_count; i++) {
|
||||
list[i] = cbm_arena_strdup(a, pp->included_files[i]);
|
||||
if (!list[i]) {
|
||||
list = NULL;
|
||||
}
|
||||
}
|
||||
if (!list) {
|
||||
result->has_error = true;
|
||||
return;
|
||||
}
|
||||
list[pp->included_count] = NULL;
|
||||
result->included_files = list;
|
||||
}
|
||||
|
||||
static CBMFileResult *extract_file_ex_body(
|
||||
const char *source, int source_len, CBMLanguage language, const char *project,
|
||||
const char *rel_path, int64_t timeout_micros, const char **extra_defines,
|
||||
const char **include_paths, const CBMMacroTable *macro_table,
|
||||
const CBMReturnTypeTable *return_type_table, CBMArena *scratch,
|
||||
const cbm_test_declarations_t *test_declarations, const CBMIncludeScope *include_scope) {
|
||||
// Allocate result on heap (arena inside for all string data)
|
||||
CBMFileResult *result = cbm_result_alloc();
|
||||
if (!result) {
|
||||
@@ -4179,8 +4291,12 @@ static CBMFileResult *extract_file_ex_body(const char *source, int source_len, C
|
||||
char export_cands[CBM_EXPORT_MACRO_MAX][CBM_EXPORT_MACRO_NAME_MAX];
|
||||
int export_cand_count =
|
||||
cbm_export_macro_candidates(source, source_len, export_cands, CBM_EXPORT_MACRO_MAX);
|
||||
CBMIncludeReader include_reader = {include_tree_read, include_tree_release, include_scope};
|
||||
bool include_lookup = include_scope && include_scope->root && include_scope->root[0];
|
||||
CBMPreprocessedSource *preprocessed = cbm_preprocess_with_map(
|
||||
source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C);
|
||||
source, source_len, rel_path, extra_defines, include_paths, language != CBM_LANG_C,
|
||||
include_lookup ? &include_reader : NULL);
|
||||
record_included_files(a, result, preprocessed);
|
||||
if (preprocessed && preprocessed->source) {
|
||||
char *expanded = preprocessed->source;
|
||||
int expanded_len = (int)strlen(expanded);
|
||||
@@ -4849,14 +4965,15 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
|
||||
const CBMReturnTypeTable *return_type_table) {
|
||||
return cbm_extract_file_ex_with_tests(source, source_len, language, project, rel_path,
|
||||
timeout_micros, extra_defines, include_paths, macro_table,
|
||||
return_type_table, NULL);
|
||||
return_type_table, NULL, NULL);
|
||||
}
|
||||
|
||||
CBMFileResult *cbm_extract_file_ex_with_tests(
|
||||
const char *source, int source_len, CBMLanguage language, const char *project,
|
||||
const char *rel_path, int64_t timeout_micros, const char **extra_defines,
|
||||
const char **include_paths, const CBMMacroTable *macro_table,
|
||||
const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations) {
|
||||
const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations,
|
||||
const CBMIncludeScope *include_scope) {
|
||||
CBMArena scratch;
|
||||
if (tl_scratch_live && tl_scratch_slot) {
|
||||
scratch = *tl_scratch_slot;
|
||||
@@ -4867,7 +4984,7 @@ CBMFileResult *cbm_extract_file_ex_with_tests(
|
||||
}
|
||||
CBMFileResult *result = extract_file_ex_body(
|
||||
source, source_len, language, project, rel_path, timeout_micros, extra_defines,
|
||||
include_paths, macro_table, return_type_table, &scratch, test_declarations);
|
||||
include_paths, macro_table, return_type_table, &scratch, test_declarations, include_scope);
|
||||
/* Even early parse/quarantine exits publish conservative Python metadata.
|
||||
* No tree is reparsed, and existing best-effort extraction flags stay intact. */
|
||||
if (result && language == CBM_LANG_PYTHON &&
|
||||
|
||||
+65
-2
@@ -329,8 +329,44 @@ typedef struct {
|
||||
* for a defined type `type A B` (its method set is its own) and in every
|
||||
* other language. Tail field: zero-init stays valid. */
|
||||
const char *alias_target;
|
||||
/* Go and Python only: the facts the declared-type scope step and the
|
||||
* cross-file registrars read (CBMDefTypeFacts), in the result arena; NULL
|
||||
* for a definition without one and in every other language. One pointer,
|
||||
* so the other languages pay 8 bytes per definition. Tail field:
|
||||
* zero-init stays valid. */
|
||||
const struct CBMDefTypeFacts *type_facts;
|
||||
} CBMDefinition;
|
||||
|
||||
/* Facts of one Go or Python definition that no graph property carries; only
|
||||
* the cross-file step reads them (src/pipeline/type_scope.h, the Go and
|
||||
* Python cross registrars). Every field is NULL when absent. */
|
||||
typedef struct CBMDefTypeFacts {
|
||||
/* The names its type parameter lists declare, '|'-joined: Python PEP 695
|
||||
* (`def f[T, *Ts, **P]`, `class C[T]`), Go (`func F[K, V any]`, a generic
|
||||
* receiver `(s *Set[T])`, `type Box[T any]`). They never name a type of
|
||||
* the project. */
|
||||
const char *type_params;
|
||||
/* Go: the type a package-level `var`/`const` declares, or the type its
|
||||
* single initializer spells (`T{}` is T, `&T{}` and `new(T)` are *T, a
|
||||
* const block's bare spec repeats the previous one's): the Variable's
|
||||
* type in the cross-file LSP (go_lsp.c, package-level values). */
|
||||
const char *value_type;
|
||||
/* Go: the types a struct embeds, '|'-joined as written
|
||||
* ("logging.LogHolder|*Base"): the cross-file LSP promotes their members
|
||||
* and names them as fields (go_lsp.c, embedded-member hook). */
|
||||
const char *go_embedded;
|
||||
/* Python class: the names its body binds other than by a nested def or
|
||||
* class (assignments, annotated assignments with a value, imports,
|
||||
* for/with/except/match targets, walrus, global/nonlocal/del; an
|
||||
* annotation alone binds nothing), '|'-joined. A method annotation naming
|
||||
* one of them means the class attribute, not the module's name. */
|
||||
const char *class_bindings;
|
||||
/* Python function or class: the names its body declares `global` and
|
||||
* binds, '|'-joined. The body rebinds them in the module, so no
|
||||
* annotation of the file names them through the module's other binding. */
|
||||
const char *global_names;
|
||||
} CBMDefTypeFacts;
|
||||
|
||||
/* extra_props key of a generated member, one the compiler writes and the
|
||||
* source never spells: a Java record's implicit accessor carries
|
||||
* `generated: record`. The node keeps the property, and the pipeline registers
|
||||
@@ -932,6 +968,11 @@ typedef struct CBMFileResult {
|
||||
const char **constants; // NULL-terminated (NULL if none)
|
||||
const char **global_vars; // NULL-terminated (NULL if none)
|
||||
const char **macros; // NULL-terminated, C/C++ only (NULL if none)
|
||||
/* C, C++, CUDA: the repository files the preprocessed pass's #include
|
||||
* lookup read (repository-relative, sorted, NULL-terminated; NULL if none).
|
||||
* The file's graph depends on their bytes as well as its own, so an
|
||||
* incremental refresh re-extracts the file when one of them changes. */
|
||||
const char **included_files;
|
||||
|
||||
bool has_error;
|
||||
const char *error_msg;
|
||||
@@ -1280,15 +1321,29 @@ CBMFileResult *cbm_extract_file_ex(
|
||||
const CBMReturnTypeTable *return_type_table // OS return types, or NULL
|
||||
);
|
||||
|
||||
/* The indexed repository as the C-family preprocessed pass's #include lookup
|
||||
* sees it (#2993): `root` is the directory rel_path is relative to, and a
|
||||
* quoted include resolves only to a file is_indexed() accepts -- one of the
|
||||
* files the index run covers -- so the expansion is a function of the indexed
|
||||
* tree alone, never of the process working directory. */
|
||||
typedef struct {
|
||||
const char *root;
|
||||
bool (*is_indexed)(const void *userdata, const char *rel_path);
|
||||
const void *userdata;
|
||||
} CBMIncludeScope;
|
||||
|
||||
/* Additive immutable-snapshot entry point. NULL preserves legacy behavior.
|
||||
* Snapshot must outlive this call; returned data is independently result-owned.
|
||||
* A non-OK result status is an explicit configured-mapping failure, not a
|
||||
* successful empty inventory. error_msg may be NULL on diagnostic OOM. */
|
||||
* successful empty inventory. error_msg may be NULL on diagnostic OOM.
|
||||
* include_scope: where quoted #include names resolve (preprocessor.h); NULL
|
||||
* resolves none. */
|
||||
CBMFileResult *cbm_extract_file_ex_with_tests(
|
||||
const char *source, int source_len, CBMLanguage language, const char *project,
|
||||
const char *rel_path, int64_t timeout_micros, const char **extra_defines,
|
||||
const char **include_paths, const CBMMacroTable *macro_table,
|
||||
const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations);
|
||||
const CBMReturnTypeTable *return_type_table, const cbm_test_declarations_t *test_declarations,
|
||||
const CBMIncludeScope *include_scope);
|
||||
|
||||
// Free all memory associated with a result.
|
||||
void cbm_free_result(CBMFileResult *result);
|
||||
@@ -1388,6 +1443,9 @@ bool cbm_py_namespace_facts_copy(CBMArena *arena, const CBMPyNamespaceFacts *sou
|
||||
#ifdef CBM_ENABLE_TEST_SEAMS
|
||||
void cbm_py_namespace_test_capture_fail_after(int successful_allocations);
|
||||
void cbm_py_namespace_test_copy_fail_after(int successful_allocations);
|
||||
/* Work of building Go structs' embedded-type texts (field-list entries
|
||||
* visited plus spelling bytes): the growth test counts it at three sizes. */
|
||||
uint64_t cbm_extract_test_go_embedded_work(void);
|
||||
#endif
|
||||
|
||||
// Growable array push functions (arena-allocated, no individual free needed).
|
||||
@@ -1438,6 +1496,11 @@ void cbm_extract_dbt(CBMExtractCtx *ctx);
|
||||
// parse past `?>` (#2000). Same length and line breaks as the input; returns
|
||||
// `source` itself when nothing needs rewriting. Defined in php_inline_html.c.
|
||||
const char *cbm_php_mask_inline_html(CBMArena *arena, const char *source, int source_len);
|
||||
// C-family source with each `\` CR LF line splice rewritten as space `\` LF so
|
||||
// the grammars built on tree-sitter-c read it as they read the LF splice
|
||||
// (#1546). Same length and line breaks as the input; returns `source` itself
|
||||
// when there is no such splice. Defined in cbm.c.
|
||||
const char *cbm_c_mask_crlf_splices(CBMArena *arena, const char *source, int source_len);
|
||||
void cbm_extract_imports(CBMExtractCtx *ctx);
|
||||
void cbm_extract_usages(CBMExtractCtx *ctx);
|
||||
void cbm_extract_semantic(CBMExtractCtx *ctx);
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "semantic/ast_profile.h"
|
||||
#include "tree_sitter/api.h" // TSNode, ts_node_*
|
||||
#include <limits.h> // INT_MAX
|
||||
#include <stdatomic.h> // test-seam work counters
|
||||
#include <stdint.h> // uint32_t, SIZE_MAX
|
||||
#include <stdio.h> // snprintf (ObjectScript storage/trigger sidecars)
|
||||
#include <stdlib.h> // malloc/free (child-collection scratch)
|
||||
@@ -6985,6 +6986,543 @@ static bool make_rule_sets_variable(TSNode rule, const char *src) {
|
||||
(strchr("+?!", src[p]) && p + SKIP_ONE < end && src[p + SKIP_ONE] == '='));
|
||||
}
|
||||
|
||||
/* Python: the names a PEP 695 type parameter list declares on a function or
|
||||
* class definition (`def f[T, *Ts, **P]`, `class C[T: Base]`), '|'-joined, or
|
||||
* NULL. Each parameter is a `type` whose first identifier is its name. */
|
||||
static TSNode py_type_param_ident(TSNode param) {
|
||||
while (!ts_node_is_null(param) && strcmp(ts_node_type(param), "identifier") != 0) {
|
||||
param = ts_node_named_child_count(param) ? ts_node_named_child(param, 0) : (TSNode){0};
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
||||
static const char *py_type_param_names(CBMArena *a, TSNode node, const char *source) {
|
||||
if (strcmp(ts_node_type(node), "decorated_definition") == 0) {
|
||||
node = ts_node_child_by_field_name(node, TS_FIELD("definition"));
|
||||
}
|
||||
TSNode list = ts_node_is_null(node)
|
||||
? node
|
||||
: ts_node_child_by_field_name(node, TS_FIELD("type_parameters"));
|
||||
uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list);
|
||||
size_t total = 0; /* every name plus one separator or the terminator */
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode id = py_type_param_ident(ts_node_named_child(list, i));
|
||||
total += ts_node_is_null(id) ? 0 : ts_node_end_byte(id) - ts_node_start_byte(id) + 1;
|
||||
}
|
||||
char *out = total ? (char *)cbm_arena_alloc(a, total) : NULL;
|
||||
if (!out) {
|
||||
return NULL;
|
||||
}
|
||||
size_t at = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode id = py_type_param_ident(ts_node_named_child(list, i));
|
||||
if (ts_node_is_null(id)) {
|
||||
continue;
|
||||
}
|
||||
if (at) {
|
||||
out[at++] = '|';
|
||||
}
|
||||
size_t len = ts_node_end_byte(id) - ts_node_start_byte(id);
|
||||
memcpy(out + at, source + ts_node_start_byte(id), len);
|
||||
at += len;
|
||||
}
|
||||
out[at] = '\0';
|
||||
return at ? out : NULL;
|
||||
}
|
||||
|
||||
/* ── Facts only the declared-type scope step reads (CBMDefTypeFacts) ── */
|
||||
|
||||
/* The record of a definition being built, allocated on first use. */
|
||||
static CBMDefTypeFacts *def_type_facts(CBMArena *a, CBMDefinition *def) {
|
||||
if (!def->type_facts) {
|
||||
CBMDefTypeFacts *f = (CBMDefTypeFacts *)cbm_arena_alloc(a, sizeof(*f));
|
||||
if (!f) {
|
||||
return NULL;
|
||||
}
|
||||
memset(f, 0, sizeof(*f));
|
||||
def->type_facts = f;
|
||||
}
|
||||
return (CBMDefTypeFacts *)def->type_facts;
|
||||
}
|
||||
|
||||
static void def_set_type_params(CBMArena *a, CBMDefinition *def, const char *names) {
|
||||
CBMDefTypeFacts *f = names && names[0] ? def_type_facts(a, def) : NULL;
|
||||
if (f) {
|
||||
f->type_params = names;
|
||||
}
|
||||
}
|
||||
|
||||
static void def_set_global_names(CBMArena *a, CBMDefinition *def, const char *names) {
|
||||
CBMDefTypeFacts *f = names && names[0] ? def_type_facts(a, def) : NULL;
|
||||
if (f) {
|
||||
f->global_names = names;
|
||||
}
|
||||
}
|
||||
|
||||
/* A '|'-joined list of names built in the arena (the grown buffers stay in
|
||||
* the arena: at most twice the final size). */
|
||||
typedef struct {
|
||||
CBMArena *a;
|
||||
char *buf;
|
||||
size_t len;
|
||||
size_t cap;
|
||||
/* Python binding walks: what a body binds in the module through names it
|
||||
* declares `global` (py_body_global_names) -- `del`, `except ... as`, a
|
||||
* nested def's or class's name bind; the declaration itself does not. */
|
||||
bool module;
|
||||
} tf_names_t;
|
||||
|
||||
static void tf_names_add(tf_names_t *b, const char *s, size_t n) {
|
||||
if (!s || n == 0) {
|
||||
return;
|
||||
}
|
||||
size_t need = b->len + n + 2;
|
||||
if (need > b->cap) {
|
||||
size_t cap = b->cap ? b->cap * 2 : 64;
|
||||
while (cap < need) {
|
||||
cap *= 2;
|
||||
}
|
||||
char *grown = (char *)cbm_arena_alloc(b->a, cap);
|
||||
if (!grown) {
|
||||
return;
|
||||
}
|
||||
if (b->len) {
|
||||
memcpy(grown, b->buf, b->len);
|
||||
}
|
||||
b->buf = grown;
|
||||
b->cap = cap;
|
||||
}
|
||||
if (b->len) {
|
||||
b->buf[b->len++] = '|';
|
||||
}
|
||||
memcpy(b->buf + b->len, s, n);
|
||||
b->len += n;
|
||||
b->buf[b->len] = '\0';
|
||||
}
|
||||
|
||||
static void tf_names_node(tf_names_t *b, TSNode node, const char *source) {
|
||||
if (!ts_node_is_null(node)) {
|
||||
tf_names_add(b, source + ts_node_start_byte(node),
|
||||
ts_node_end_byte(node) - ts_node_start_byte(node));
|
||||
}
|
||||
}
|
||||
|
||||
enum { TF_BIND_DEPTH = 64 }; /* statement and pattern nesting the binders follow */
|
||||
|
||||
/* Go: `[K comparable, V any]` declares K and V (every `name` of every
|
||||
* type_parameter_declaration). */
|
||||
static void go_type_param_list(tf_names_t *b, TSNode list, const char *source) {
|
||||
uint32_t n = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode decl = ts_node_named_child(list, i);
|
||||
if (strcmp(ts_node_type(decl), "type_parameter_declaration") != 0) {
|
||||
continue;
|
||||
}
|
||||
uint32_t cc = ts_node_child_count(decl);
|
||||
for (uint32_t k = 0; k < cc; k++) {
|
||||
const char *field = ts_node_field_name_for_child(decl, k);
|
||||
if (field && strcmp(field, "name") == 0) {
|
||||
tf_names_node(b, ts_node_child(decl, k), source);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Go: a generic receiver `(s *Set[K, V])` declares K and V. */
|
||||
static void go_receiver_type_params(tf_names_t *b, TSNode node, bool in_args, int depth,
|
||||
const char *source) {
|
||||
if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) {
|
||||
return;
|
||||
}
|
||||
const char *kind = ts_node_type(node);
|
||||
if (in_args && strcmp(kind, "type_identifier") == 0) {
|
||||
tf_names_node(b, node, source);
|
||||
return;
|
||||
}
|
||||
bool args = in_args || strcmp(kind, "type_arguments") == 0;
|
||||
uint32_t n = ts_node_named_child_count(node);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
go_receiver_type_params(b, ts_node_named_child(node, i), args, depth + 1, source);
|
||||
}
|
||||
}
|
||||
|
||||
/* Go: the type parameter names of a function, a method (its receiver's) or
|
||||
* a type spec, '|'-joined, or NULL. */
|
||||
static const char *go_type_param_names(CBMArena *a, TSNode node, const char *source) {
|
||||
tf_names_t b = {.a = a};
|
||||
go_type_param_list(&b, ts_node_child_by_field_name(node, TS_FIELD("type_parameters")), source);
|
||||
if (strcmp(ts_node_type(node), "method_declaration") == 0) {
|
||||
go_receiver_type_params(&b, ts_node_child_by_field_name(node, TS_FIELD("receiver")), false,
|
||||
0, source);
|
||||
}
|
||||
return b.len ? b.buf : NULL;
|
||||
}
|
||||
|
||||
/* Python: the identifiers a binding target binds (`a`, `a, (b, *c)`,
|
||||
* `[d]`); an attribute or subscript target binds no name of the scope. */
|
||||
static void py_bind_target(tf_names_t *b, TSNode t, const char *source, int depth) {
|
||||
if (ts_node_is_null(t) || depth > TF_BIND_DEPTH) {
|
||||
return;
|
||||
}
|
||||
const char *kind = ts_node_type(t);
|
||||
if (strcmp(kind, "identifier") == 0) {
|
||||
tf_names_node(b, t, source);
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "attribute") == 0 || strcmp(kind, "subscript") == 0) {
|
||||
return;
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(t);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
py_bind_target(b, ts_node_named_child(t, i), source, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Python: walrus names (`(x := ...)`) inside an expression of the class body
|
||||
* itself, not inside a nested scope (lambda, comprehension, def, class). */
|
||||
static void py_bind_walrus(tf_names_t *b, TSNode e, const char *source, int depth) {
|
||||
if (ts_node_is_null(e) || depth > TF_BIND_DEPTH * 2) {
|
||||
return;
|
||||
}
|
||||
const char *kind = ts_node_type(e);
|
||||
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 || strcmp(kind, "function_definition") == 0 ||
|
||||
strcmp(kind, "class_definition") == 0 || strcmp(kind, "decorated_definition") == 0) {
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "named_expression") == 0) {
|
||||
tf_names_node(b, ts_node_child_by_field_name(e, TS_FIELD("name")), source);
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(e);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
py_bind_walrus(b, ts_node_named_child(e, i), source, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Python: the targets after an `as` among a node's children (with items,
|
||||
* except clauses, as-patterns), and every identifier of a match pattern. */
|
||||
static void py_bind_as_targets(tf_names_t *b, TSNode node, const char *source, int depth) {
|
||||
if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) {
|
||||
return;
|
||||
}
|
||||
const char *kind = ts_node_type(node);
|
||||
if (strcmp(kind, "block") == 0) {
|
||||
return; /* a clause body: its statements are walked as statements */
|
||||
}
|
||||
if (strcmp(kind, "case_pattern") == 0) {
|
||||
py_bind_target(b, node, source, depth + 1); /* captures: every name, over-listed */
|
||||
return;
|
||||
}
|
||||
bool after_as = false;
|
||||
uint32_t n = ts_node_child_count(node);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode c = ts_node_child(node, i);
|
||||
if (!ts_node_is_named(c)) {
|
||||
after_as = strcmp(ts_node_type(c), "as") == 0;
|
||||
continue;
|
||||
}
|
||||
if (after_as) {
|
||||
py_bind_target(b, c, source, depth + 1);
|
||||
after_as = false;
|
||||
continue;
|
||||
}
|
||||
py_bind_as_targets(b, c, source, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int depth);
|
||||
|
||||
static bool py_defines_kind(const char *kind) {
|
||||
return strcmp(kind, "function_definition") == 0 || strcmp(kind, "class_definition") == 0 ||
|
||||
strcmp(kind, "decorated_definition") == 0;
|
||||
}
|
||||
|
||||
/* Statement-level nodes a scope's statements nest in (not expressions). */
|
||||
static bool py_statement_level(const char *kind) {
|
||||
return strcmp(kind, "block") == 0 || strstr(kind, "_statement") != NULL ||
|
||||
strstr(kind, "_clause") != NULL;
|
||||
}
|
||||
|
||||
/* Whether a definition stands among the statements of `node`. */
|
||||
static bool py_has_def(TSNode node, int depth) {
|
||||
if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) {
|
||||
return false;
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(node);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode c = ts_node_named_child(node, i);
|
||||
const char *ck = ts_node_type(c);
|
||||
if (py_defines_kind(ck) || (py_statement_level(ck) && py_has_def(c, depth + 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Python: the names one statement of a class body binds (it recurses into
|
||||
* compound statements, whose bodies are the same scope). `del` binds nothing
|
||||
* (py_class_body_bindings unbinds at the body's top level), and neither does
|
||||
* `except ... as E`: Python unbinds E when the clause ends, so it is a binding
|
||||
* only for a definition inside the clause. */
|
||||
static void py_bind_statement(tf_names_t *b, TSNode s, const char *source, int depth) {
|
||||
if (ts_node_is_null(s) || depth > TF_BIND_DEPTH) {
|
||||
return;
|
||||
}
|
||||
const char *kind = ts_node_type(s);
|
||||
if (py_defines_kind(kind)) {
|
||||
if (b->module) {
|
||||
TSNode def = strcmp(kind, "decorated_definition") == 0
|
||||
? ts_node_child_by_field_name(s, TS_FIELD("definition"))
|
||||
: s;
|
||||
if (!ts_node_is_null(def)) {
|
||||
tf_names_node(b, ts_node_child_by_field_name(def, TS_FIELD("name")), source);
|
||||
}
|
||||
}
|
||||
return; /* definitions of the class: the step sees them as such */
|
||||
}
|
||||
if (strcmp(kind, "expression_statement") == 0) {
|
||||
uint32_t n = ts_node_named_child_count(s);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode e = ts_node_named_child(s, i);
|
||||
/* `a = b = v`: each assignment's left side, down the chain. An
|
||||
* annotation alone (`x: T`) binds nothing (Python records it in
|
||||
* __annotations__ only). */
|
||||
for (int chain = 0; !ts_node_is_null(e) && chain < TF_BIND_DEPTH; chain++) {
|
||||
const char *ek = ts_node_type(e);
|
||||
if (strcmp(ek, "assignment") != 0 && strcmp(ek, "augmented_assignment") != 0) {
|
||||
py_bind_walrus(b, e, source, depth + 1);
|
||||
break;
|
||||
}
|
||||
TSNode right = ts_node_child_by_field_name(e, TS_FIELD("right"));
|
||||
if (ts_node_is_null(right)) {
|
||||
break;
|
||||
}
|
||||
py_bind_target(b, ts_node_child_by_field_name(e, TS_FIELD("left")), source,
|
||||
depth + 1);
|
||||
e = right;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "import_statement") == 0 || strcmp(kind, "import_from_statement") == 0) {
|
||||
bool from = kind[7] == 'f';
|
||||
uint32_t cc = ts_node_child_count(s);
|
||||
for (uint32_t i = 0; i < cc; i++) {
|
||||
const char *field = ts_node_field_name_for_child(s, i);
|
||||
if (!field || strcmp(field, "name") != 0) {
|
||||
continue;
|
||||
}
|
||||
TSNode name = ts_node_child(s, i);
|
||||
TSNode alias = strcmp(ts_node_type(name), "aliased_import") == 0
|
||||
? ts_node_child_by_field_name(name, TS_FIELD("alias"))
|
||||
: (TSNode){0};
|
||||
if (!ts_node_is_null(alias)) {
|
||||
tf_names_node(b, alias, source);
|
||||
continue;
|
||||
}
|
||||
TSNode dotted = strcmp(ts_node_type(name), "aliased_import") == 0
|
||||
? ts_node_child_by_field_name(name, TS_FIELD("name"))
|
||||
: name;
|
||||
/* `import a.b` binds `a`; `from m import x` binds `x` */
|
||||
TSNode first = !from && ts_node_named_child_count(dotted) > 0
|
||||
? ts_node_named_child(dotted, 0)
|
||||
: dotted;
|
||||
tf_names_node(b, first, source);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "global_statement") == 0 || strcmp(kind, "nonlocal_statement") == 0) {
|
||||
if (!b->module) {
|
||||
py_bind_target(b, s, source, depth + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "delete_statement") == 0) {
|
||||
if (b->module) {
|
||||
py_bind_target(b, s, source, depth + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "type_alias_statement") == 0) {
|
||||
py_bind_target(b, ts_node_child_by_field_name(s, TS_FIELD("left")), source, depth + 1);
|
||||
return;
|
||||
}
|
||||
if (strcmp(kind, "for_statement") == 0) {
|
||||
py_bind_target(b, ts_node_child_by_field_name(s, TS_FIELD("left")), source, depth + 1);
|
||||
}
|
||||
/* A compound statement: walrus names and `as` targets of its headers,
|
||||
* then the statements of every block and clause. */
|
||||
uint32_t n = ts_node_named_child_count(s);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode c = ts_node_named_child(s, i);
|
||||
const char *ck = ts_node_type(c);
|
||||
if (strcmp(ck, "block") == 0) {
|
||||
py_bind_block(b, c, source, depth + 1);
|
||||
} else if (strncmp(ck, "except", 6) == 0 && strstr(ck, "_clause") != NULL) {
|
||||
if (b->module || py_has_def(c, depth + 1)) {
|
||||
py_bind_as_targets(b, c, source, depth + 1);
|
||||
}
|
||||
uint32_t m = ts_node_named_child_count(c);
|
||||
for (uint32_t j = 0; j < m; j++) {
|
||||
TSNode part = ts_node_named_child(c, j);
|
||||
if (strcmp(ts_node_type(part), "block") == 0) {
|
||||
py_bind_block(b, part, source, depth + 2);
|
||||
} else {
|
||||
py_bind_walrus(b, part, source, depth + 2);
|
||||
}
|
||||
}
|
||||
} else if (strstr(ck, "_clause") != NULL) {
|
||||
py_bind_as_targets(b, c, source, depth + 1);
|
||||
py_bind_statement(b, c, source, depth + 1);
|
||||
} else {
|
||||
py_bind_walrus(b, c, source, depth + 1);
|
||||
py_bind_as_targets(b, c, source, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void py_bind_block(tf_names_t *b, TSNode block, const char *source, int depth) {
|
||||
uint32_t n = ts_node_is_null(block) ? 0 : ts_node_named_child_count(block);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
py_bind_statement(b, ts_node_named_child(block, i), source, depth);
|
||||
}
|
||||
}
|
||||
|
||||
static TSNode py_def_body(TSNode node) {
|
||||
if (strcmp(ts_node_type(node), "decorated_definition") == 0) {
|
||||
node = ts_node_child_by_field_name(node, TS_FIELD("definition"));
|
||||
}
|
||||
return ts_node_is_null(node) ? node : ts_node_child_by_field_name(node, TS_FIELD("body"));
|
||||
}
|
||||
|
||||
/* Python: the names a class body binds besides its nested definitions,
|
||||
* '|'-joined, each once, or NULL. The top-level statements are taken in
|
||||
* order: a binding holds from its statement on, and a later top-level `del`
|
||||
* unbinds it -- unless a definition stands between the two, which saw the
|
||||
* name bound when its annotations were evaluated at definition time (a
|
||||
* top-level one: a definition inside a compound statement is no method the
|
||||
* extractor lists). A `del` inside a compound statement may not run: the name
|
||||
* stays bound. */
|
||||
static const char *py_class_body_bindings(CBMArena *a, TSNode node, const char *source) {
|
||||
TSNode body = py_def_body(node);
|
||||
if (ts_node_is_null(body)) {
|
||||
return NULL;
|
||||
}
|
||||
CBMHashTable *state = cbm_ht_create(32); /* name -> epoch of its binding, or 1: unbound */
|
||||
if (!state) {
|
||||
return NULL;
|
||||
}
|
||||
tf_names_t order = {.a = a}; /* every name bound once, in first-binding order */
|
||||
uintptr_t epoch = 2; /* moves on at each definition */
|
||||
TSTreeCursor cur = ts_tree_cursor_new(body);
|
||||
for (bool ok = ts_tree_cursor_goto_first_child(&cur); ok;
|
||||
ok = ts_tree_cursor_goto_next_sibling(&cur)) {
|
||||
TSNode s = ts_tree_cursor_current_node(&cur);
|
||||
if (!ts_node_is_named(s)) {
|
||||
continue;
|
||||
}
|
||||
const char *kind = ts_node_type(s);
|
||||
if (py_defines_kind(kind)) {
|
||||
epoch++;
|
||||
continue;
|
||||
}
|
||||
tf_names_t one = {.a = a};
|
||||
bool del = strcmp(kind, "delete_statement") == 0;
|
||||
if (del) {
|
||||
py_bind_target(&one, s, source, 1);
|
||||
} else {
|
||||
py_bind_statement(&one, s, source, 0);
|
||||
}
|
||||
for (const char *p = one.buf; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
char *name = cbm_arena_strndup(a, p, len);
|
||||
uintptr_t was = name ? (uintptr_t)cbm_ht_get(state, name) : 0;
|
||||
if (name && del) {
|
||||
if (was == epoch) {
|
||||
cbm_ht_set(state, name, (void *)(uintptr_t)1);
|
||||
}
|
||||
} else if (name) {
|
||||
if (!was) {
|
||||
tf_names_add(&order, name, len);
|
||||
}
|
||||
cbm_ht_set(state, name, (void *)epoch);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
}
|
||||
ts_tree_cursor_delete(&cur);
|
||||
tf_names_t out = {.a = a};
|
||||
for (const char *p = order.buf; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
char *name = cbm_arena_strndup(a, p, len);
|
||||
if (name && (uintptr_t)cbm_ht_get(state, name) > 1) {
|
||||
tf_names_add(&out, name, len);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
cbm_ht_free(state);
|
||||
return out.len ? out.buf : NULL;
|
||||
}
|
||||
|
||||
/* The names declared `global` among a scope's statements (compound ones
|
||||
* included, nested definitions not: they are scopes of their own). */
|
||||
static void py_global_statements(tf_names_t *b, TSNode node, const char *source, int depth) {
|
||||
if (ts_node_is_null(node) || depth > TF_BIND_DEPTH) {
|
||||
return;
|
||||
}
|
||||
uint32_t n = ts_node_named_child_count(node);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode c = ts_node_named_child(node, i);
|
||||
const char *ck = ts_node_type(c);
|
||||
if (strcmp(ck, "global_statement") == 0) {
|
||||
py_bind_target(b, c, source, depth + 1);
|
||||
} else if (!py_defines_kind(ck) && py_statement_level(ck)) {
|
||||
py_global_statements(b, c, source, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Python: the names a function's or class's body declares `global` and
|
||||
* binds, '|'-joined, or NULL: the body rebinds them in the module. */
|
||||
static const char *py_body_global_names(CBMArena *a, TSNode node, const char *source) {
|
||||
TSNode body = py_def_body(node);
|
||||
tf_names_t declared = {.a = a};
|
||||
py_global_statements(&declared, body, source, 0);
|
||||
if (!declared.len) {
|
||||
return NULL;
|
||||
}
|
||||
tf_names_t bound = {.a = a, .module = true};
|
||||
py_bind_block(&bound, body, source, 0);
|
||||
CBMHashTable *binds = bound.len ? cbm_ht_create(16) : NULL;
|
||||
if (!binds) {
|
||||
return NULL;
|
||||
}
|
||||
for (const char *p = bound.buf; *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
char *name = cbm_arena_strndup(a, p, len);
|
||||
if (name) {
|
||||
cbm_ht_set(binds, name, name);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
tf_names_t out = {.a = a};
|
||||
for (const char *p = declared.buf; *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
char *name = cbm_arena_strndup(a, p, len);
|
||||
if (name && cbm_ht_get(binds, name)) {
|
||||
tf_names_add(&out, name, len);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
cbm_ht_free(binds);
|
||||
return out.len ? out.buf : NULL;
|
||||
}
|
||||
|
||||
/* Make: a rule names several targets (`up down: deps`), each a goal
|
||||
* `make <target>` runs. The rule's definition carries the first target;
|
||||
* every further one gets a definition of its own over the same rule span --
|
||||
@@ -7296,6 +7834,12 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
|
||||
// Decorators + route extraction from decorator AST
|
||||
def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec);
|
||||
extract_route_from_decorators(a, node, ctx->source, spec, &def.route_path, &def.route_method);
|
||||
if (ctx->language == CBM_LANG_PYTHON) {
|
||||
def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source));
|
||||
def_set_global_names(a, &def, py_body_global_names(a, node, ctx->source));
|
||||
} else if (ctx->language == CBM_LANG_GO) {
|
||||
def_set_type_params(a, &def, go_type_param_names(a, node, ctx->source));
|
||||
}
|
||||
|
||||
// Rust: cfg-gated twins (#[cfg(windows)] fn f / #[cfg(not(windows))] fn f)
|
||||
// keep the plain QN: they are variants of ONE definition, and the graph
|
||||
@@ -8588,6 +9132,87 @@ static const char *cs_type_decl_namespace(CBMExtractCtx *ctx, TSNode node) {
|
||||
return ts_node_has_error(top) ? NULL : "";
|
||||
}
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
static _Atomic uint64_t g_go_embedded_text_work;
|
||||
uint64_t cbm_extract_test_go_embedded_work(void) {
|
||||
return atomic_load_explicit(&g_go_embedded_text_work, memory_order_relaxed);
|
||||
}
|
||||
#define GO_EMBEDDED_TEXT_WORK(n) \
|
||||
atomic_fetch_add_explicit(&g_go_embedded_text_work, (uint64_t)(n), memory_order_relaxed)
|
||||
#else
|
||||
#define GO_EMBEDDED_TEXT_WORK(n) ((void)0)
|
||||
#endif
|
||||
|
||||
/* The type of an embedded field (an unnamed field declaration) of a struct's
|
||||
* field list, or a null node. */
|
||||
static TSNode go_embedded_field_type(TSNode field) {
|
||||
if (strcmp(ts_node_type(field), "field_declaration") != 0 ||
|
||||
!ts_node_is_null(ts_node_child_by_field_name(field, TS_FIELD("name")))) {
|
||||
return (TSNode){0};
|
||||
}
|
||||
return ts_node_child_by_field_name(field, TS_FIELD("type"));
|
||||
}
|
||||
|
||||
/* Its spelling's span when it can join a '|'-list (non-empty, no '|'). */
|
||||
static bool go_embedded_span(TSNode type, const char *source, uint32_t *start, uint32_t *len) {
|
||||
if (ts_node_is_null(type)) {
|
||||
return false;
|
||||
}
|
||||
*start = ts_node_start_byte(type);
|
||||
*len = ts_node_end_byte(type) - *start;
|
||||
GO_EMBEDDED_TEXT_WORK(*len);
|
||||
return *len > 0 && !memchr(source + *start, '|', *len);
|
||||
}
|
||||
|
||||
/* Go: the types a struct type_spec embeds (its unnamed field declarations),
|
||||
* '|'-joined as written, or NULL. Two passes over the field list with a
|
||||
* cursor (measure, then copy once): linear in the struct's size. */
|
||||
static const char *go_struct_embedded_text(CBMArena *a, TSNode spec, const char *source) {
|
||||
TSNode st = ts_node_child_by_field_name(spec, TS_FIELD("type"));
|
||||
if (ts_node_is_null(st) || strcmp(ts_node_type(st), "struct_type") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
TSNode list = cbm_find_child_by_kind(st, "field_declaration_list");
|
||||
if (ts_node_is_null(list)) {
|
||||
return NULL;
|
||||
}
|
||||
size_t total = 0;
|
||||
char *out = NULL;
|
||||
size_t at = 0;
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
TSTreeCursor cur = ts_tree_cursor_new(list);
|
||||
for (bool ok = ts_tree_cursor_goto_first_child(&cur); ok;
|
||||
ok = ts_tree_cursor_goto_next_sibling(&cur)) {
|
||||
GO_EMBEDDED_TEXT_WORK(1);
|
||||
uint32_t start = 0;
|
||||
uint32_t len = 0;
|
||||
TSNode field = ts_tree_cursor_current_node(&cur);
|
||||
if (!ts_node_is_named(field) ||
|
||||
!go_embedded_span(go_embedded_field_type(field), source, &start, &len)) {
|
||||
continue;
|
||||
}
|
||||
if (pass == 0) {
|
||||
total += len + 1;
|
||||
continue;
|
||||
}
|
||||
if (at) {
|
||||
out[at++] = '|';
|
||||
}
|
||||
memcpy(out + at, source + start, len);
|
||||
at += len;
|
||||
}
|
||||
ts_tree_cursor_delete(&cur);
|
||||
if (pass == 0) {
|
||||
out = total ? (char *)cbm_arena_alloc(a, total) : NULL;
|
||||
if (!out) {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
out[at] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec) {
|
||||
CBMArena *a = ctx->arena;
|
||||
const char *kind = ts_node_type(node);
|
||||
@@ -9019,6 +9644,23 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s
|
||||
}
|
||||
def.decorators = extract_decorators(a, node, ctx->source, ctx->language, spec);
|
||||
def.docstring = extract_docstring(ctx, node, name);
|
||||
if (ctx->language == CBM_LANG_PYTHON) {
|
||||
def_set_type_params(a, &def, py_type_param_names(a, node, ctx->source));
|
||||
def_set_global_names(a, &def, py_body_global_names(a, node, ctx->source));
|
||||
const char *bound = py_class_body_bindings(a, node, ctx->source);
|
||||
CBMDefTypeFacts *facts = bound ? def_type_facts(a, &def) : NULL;
|
||||
if (facts) {
|
||||
facts->class_bindings = bound;
|
||||
}
|
||||
}
|
||||
if (ctx->language == CBM_LANG_GO) {
|
||||
def_set_type_params(a, &def, go_type_param_names(a, node, ctx->source));
|
||||
const char *embedded = go_struct_embedded_text(a, node, ctx->source);
|
||||
CBMDefTypeFacts *facts = embedded && embedded[0] ? def_type_facts(a, &def) : NULL;
|
||||
if (facts) {
|
||||
facts->go_embedded = embedded;
|
||||
}
|
||||
}
|
||||
|
||||
cbm_defs_push(&ctx->result->defs, a, def);
|
||||
|
||||
@@ -9561,6 +10203,12 @@ static void push_method_def_named(CBMExtractCtx *ctx, TSNode child, TSNode class
|
||||
|
||||
def.decorators = extract_decorators(a, child, ctx->source, ctx->language, spec);
|
||||
extract_route_from_decorators(a, child, ctx->source, spec, &def.route_path, &def.route_method);
|
||||
if (ctx->language == CBM_LANG_PYTHON) {
|
||||
def_set_type_params(a, &def, py_type_param_names(a, child, ctx->source));
|
||||
def_set_global_names(a, &def, py_body_global_names(a, child, ctx->source));
|
||||
} else if (ctx->language == CBM_LANG_GO) {
|
||||
def_set_type_params(a, &def, go_type_param_names(a, child, ctx->source));
|
||||
}
|
||||
const char *client_path = NULL;
|
||||
const char *client_method = NULL;
|
||||
/* Retrofit services must be interfaces; Pippo and Rapidoid put the path in
|
||||
@@ -11087,6 +11735,53 @@ static void extract_js_vars(CBMExtractCtx *ctx, TSNode node, CBMArena *a) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Go: the type a package-level `var`/`const` spec declares, else the type
|
||||
* its single initializer spells: `T{...}` is T, `&T{...}` is *T, `new(T)` is
|
||||
* *T. NULL for anything else (a call's result, an arithmetic expression):
|
||||
* nothing is inferred. */
|
||||
static const char *go_value_type_text(CBMArena *a, TSNode spec, const char *source) {
|
||||
TSNode type = ts_node_child_by_field_name(spec, TS_FIELD("type"));
|
||||
if (!ts_node_is_null(type)) {
|
||||
return cbm_node_text(a, type, source);
|
||||
}
|
||||
TSNode value = ts_node_child_by_field_name(spec, TS_FIELD("value"));
|
||||
if (!ts_node_is_null(value) && strcmp(ts_node_type(value), "expression_list") == 0) {
|
||||
value = ts_node_named_child_count(value) == 1 ? ts_node_named_child(value, 0) : (TSNode){0};
|
||||
}
|
||||
if (ts_node_is_null(value)) {
|
||||
return NULL;
|
||||
}
|
||||
bool pointer = false;
|
||||
if (strcmp(ts_node_type(value), "unary_expression") == 0) {
|
||||
TSNode op = ts_node_child_by_field_name(value, TS_FIELD("operator"));
|
||||
const char *ot = ts_node_is_null(op) ? NULL : cbm_node_text(a, op, source);
|
||||
if (!ot || strcmp(ot, "&") != 0) {
|
||||
return NULL;
|
||||
}
|
||||
value = ts_node_child_by_field_name(value, TS_FIELD("operand"));
|
||||
pointer = true;
|
||||
if (ts_node_is_null(value)) {
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
const char *vk = ts_node_type(value);
|
||||
const char *text = NULL;
|
||||
if (strcmp(vk, "composite_literal") == 0) {
|
||||
TSNode t = ts_node_child_by_field_name(value, TS_FIELD("type"));
|
||||
text = ts_node_is_null(t) ? NULL : cbm_node_text(a, t, source);
|
||||
} else if (!pointer && strcmp(vk, "call_expression") == 0) {
|
||||
TSNode fn = ts_node_child_by_field_name(value, TS_FIELD("function"));
|
||||
TSNode args = ts_node_child_by_field_name(value, TS_FIELD("arguments"));
|
||||
const char *fname = ts_node_is_null(fn) ? NULL : cbm_node_text(a, fn, source);
|
||||
if (fname && strcmp(fname, "new") == 0 && !ts_node_is_null(args) &&
|
||||
ts_node_named_child_count(args) == 1) {
|
||||
text = cbm_node_text(a, ts_node_named_child(args, 0), source);
|
||||
pointer = true;
|
||||
}
|
||||
}
|
||||
return text && pointer ? cbm_arena_sprintf(a, "*%s", text) : text;
|
||||
}
|
||||
|
||||
static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a,
|
||||
const char *kind) {
|
||||
(void)kind;
|
||||
@@ -11115,13 +11810,31 @@ static void extract_vars_mainstream(CBMExtractCtx *ctx, TSNode node, CBMArena *a
|
||||
}
|
||||
case CBM_LANG_GO: {
|
||||
uint32_t n = ts_node_named_child_count(node);
|
||||
/* In a const block a spec with neither type nor value repeats the
|
||||
* previous spec's (`A Kind = iota; B; C`). */
|
||||
const char *repeated = NULL;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
TSNode child = ts_node_named_child(node, i);
|
||||
const char *ck = ts_node_type(child);
|
||||
if (strcmp(ck, "var_spec") == 0 || strcmp(ck, "const_spec") == 0) {
|
||||
bool bare = strcmp(ck, "const_spec") == 0 &&
|
||||
ts_node_is_null(ts_node_child_by_field_name(child, TS_FIELD("type"))) &&
|
||||
ts_node_is_null(ts_node_child_by_field_name(child, TS_FIELD("value")));
|
||||
const char *vtype = bare ? repeated : go_value_type_text(a, child, ctx->source);
|
||||
repeated = vtype;
|
||||
TSNode vname = ts_node_child_by_field_name(child, TS_FIELD("name"));
|
||||
if (!ts_node_is_null(vname)) {
|
||||
int before = ctx->result->defs.count;
|
||||
push_var_def(ctx, cbm_node_text(a, vname, ctx->source), child);
|
||||
/* The value's type reaches other files (pkg.V.Method()),
|
||||
* never the graph (CBMDefTypeFacts.value_type). */
|
||||
CBMDefTypeFacts *facts =
|
||||
vtype && ctx->result->defs.count == before + 1
|
||||
? def_type_facts(a, &ctx->result->defs.items[before])
|
||||
: NULL;
|
||||
if (facts) {
|
||||
facts->value_type = vtype;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7228,6 +7228,10 @@ static bool c_lsp_cross_with_registry_run(CBMArena *arena, const char *source, i
|
||||
const CBMFileResult *test_owners,
|
||||
CBMLSPStatus *status) {
|
||||
*status = CBM_LSP_COMPLETE;
|
||||
/* The retained or re-read source is the file on disk; read it the way the
|
||||
* per-file extract did (#1546), so the owner digest, the cached tree and
|
||||
* node text agree. */
|
||||
source = cbm_c_mask_crlf_splices(arena, source, source_len);
|
||||
if ((test_owners && test_owners->has_test_definition_owners &&
|
||||
source_origin != CBM_SOURCE_ORIGIN_RAW) ||
|
||||
!cbm_test_definition_owners_match(test_owners, source, source_len, cpp_mode,
|
||||
@@ -7319,6 +7323,9 @@ static bool c_lsp_cross_run(CBMArena *arena, const char *source, int source_len,
|
||||
CBMSourceOrigin source_origin, const CBMFileResult *test_owners,
|
||||
CBMLSPStatus *status) {
|
||||
*status = CBM_LSP_COMPLETE;
|
||||
/* Same bytes as the per-file extract (#1546); see
|
||||
* c_lsp_cross_with_registry_run. */
|
||||
source = cbm_c_mask_crlf_splices(arena, source, source_len);
|
||||
if ((test_owners && test_owners->has_test_definition_owners &&
|
||||
source_origin != CBM_SOURCE_ORIGIN_RAW) ||
|
||||
!cbm_test_definition_owners_match(test_owners, source, source_len, cpp_mode,
|
||||
|
||||
+980
-303
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,9 @@ typedef struct {
|
||||
|
||||
// Current function context
|
||||
const char* enclosing_func_qn;
|
||||
// Walking a function body: a type declaration met there shadows the
|
||||
// package's type of its name in the current block (go_shadow_add).
|
||||
bool in_function;
|
||||
const char* package_qn; // module QN for this file
|
||||
const char* rel_path; // repo-relative file path: init() QN suffix (#1910); NULL = flat
|
||||
|
||||
@@ -111,6 +114,11 @@ typedef struct {
|
||||
* by the registrar against def_module_qn like return_types. NULL = not an
|
||||
* identity alias. */
|
||||
const char *alias_target;
|
||||
/* Identities of the type names this def's declared types write, resolved
|
||||
* once in the scope of the file that wrote them (src/pipeline/type_scope.h):
|
||||
* "spelling=QN|spelling=QN". Read with cbm_type_scope_find (type_rep.h).
|
||||
* NULL = no name needs one; the engine then qualifies as before. */
|
||||
const char *type_scope;
|
||||
} CBMLSPDef;
|
||||
|
||||
// Parse source, build registry from defs + stdlib, run LSP.
|
||||
|
||||
@@ -4420,6 +4420,12 @@ static const char **py_split_subscript_args(CBMArena *arena, const char *s, int
|
||||
return out;
|
||||
}
|
||||
|
||||
/* The resolved type identities of the cross-file def whose annotations are
|
||||
* being parsed (CBMLSPDef.type_scope, resolved once in the scope of the module
|
||||
* that wrote them, indexed). Bound by py_register_lsp_defs around one def's
|
||||
* texts only; NULL for every parse of the walked file's own source. */
|
||||
static _Thread_local const cbm_type_scope_index_t *g_py_type_scope;
|
||||
|
||||
static const CBMType *py_parse_type_text_qn(CBMArena *arena, const char *ann,
|
||||
const char *module_qn) {
|
||||
if (!ann || !ann[0])
|
||||
@@ -4575,6 +4581,11 @@ static const CBMType *py_parse_type_text_qn(CBMArena *arena, const char *ann,
|
||||
return cbm_type_builtin(arena, ann);
|
||||
}
|
||||
}
|
||||
// A name the defining module's scope resolved (its import, or its own class).
|
||||
const char *scoped = cbm_type_scope_find(g_py_type_scope, ann, strlen(ann));
|
||||
if (scoped) {
|
||||
return cbm_type_named(arena, scoped);
|
||||
}
|
||||
// Bare unqualified name: qualify with module_qn if it doesn't already
|
||||
// contain a dot. Skips obvious typing-module names so `Optional` /
|
||||
// `Self` / etc. don't end up qualified to the consumer's module.
|
||||
@@ -6453,9 +6464,20 @@ static bool py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
|
||||
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);
|
||||
/* this def's annotations only */
|
||||
g_py_type_scope = cbm_type_scope_index(arena, d->type_scope);
|
||||
// Build FUNC type from "|"-separated return types. A def whose
|
||||
// annotations carry resolved identities is one annotation, parsed
|
||||
// as the per-file registrar parses it (`T | None` is a union).
|
||||
const char **ret_strs = g_py_type_scope ? NULL : py_split_pipe(arena, d->return_types);
|
||||
const CBMType **ret_types = NULL;
|
||||
if (g_py_type_scope && d->return_types && d->return_types[0]) {
|
||||
ret_types = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(const CBMType *));
|
||||
if (ret_types) {
|
||||
ret_types[0] = py_parse_type_text_qn(arena, d->return_types, NULL);
|
||||
ret_types[1] = NULL;
|
||||
}
|
||||
}
|
||||
if (ret_strs) {
|
||||
int n = 0;
|
||||
while (ret_strs[n])
|
||||
@@ -6473,12 +6495,15 @@ static bool py_register_lsp_defs(CBMArena *arena, CBMArena *idx_arena, CBMTypeRe
|
||||
/* Fallback definitions can be mixed-language. Only authoritative
|
||||
* Python metadata opts into package scope normalization. */
|
||||
if (d->lang == CBM_LANG_PYTHON &&
|
||||
!py_symbol_scope(arena, d->def_module_qn, "register", &symbol_scope))
|
||||
!py_symbol_scope(arena, d->def_module_qn, "register", &symbol_scope)) {
|
||||
g_py_type_scope = NULL;
|
||||
return false;
|
||||
}
|
||||
PySignatureParamParserContext parser_ctx = {.module_qn = symbol_scope};
|
||||
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);
|
||||
g_py_type_scope = NULL;
|
||||
rf.signature = cbm_type_func(arena, NULL, param_types, ret_types);
|
||||
|
||||
if (strcmp(d->label, "Method") == 0 && d->receiver_type && d->receiver_type[0]) {
|
||||
|
||||
@@ -24,6 +24,10 @@ typedef enum {
|
||||
* 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,
|
||||
/* Go only: a package-level value (`var`/`const`), registered so `pkg.V`
|
||||
* and a bare `V` of another file have its declared type: the signature's
|
||||
* single result. Never a call target. */
|
||||
CBM_FUNC_FLAG_VALUE = 1 << 11,
|
||||
} CBMFuncFlags;
|
||||
|
||||
// Registered function/method with full type signature.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "type_rep.h"
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
@@ -963,3 +964,128 @@ const CBMType *cbm_type_substitute(CBMArena *a, const CBMType *t, const char **t
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Declared-type identities of one definition ─────────────────── */
|
||||
|
||||
/* One identity: offsets into the index's copy of the scope, where '=' and '|'
|
||||
* are cut to NULs (12 bytes; len 0 = an empty slot). */
|
||||
typedef struct {
|
||||
uint32_t name;
|
||||
uint32_t len;
|
||||
uint32_t qn;
|
||||
} cbm_type_scope_entry_t;
|
||||
|
||||
/* Up to TYPE_SCOPE_LIST_MAX identities (most definitions have one to three)
|
||||
* are a plain list a lookup scans, a bounded cost; more are an open-addressing
|
||||
* table of a power-of-two size. Same answers either way. */
|
||||
enum { TYPE_SCOPE_LIST_MAX = 4 };
|
||||
|
||||
struct cbm_type_scope_index {
|
||||
const char *text; /* the copy the entries point into */
|
||||
cbm_type_scope_entry_t *slots; /* the list (mask 0) or the table */
|
||||
uint32_t mask; /* table size - 1, or 0 for a list */
|
||||
uint32_t count; /* list entries */
|
||||
};
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
static _Atomic uint64_t g_type_scope_index_work;
|
||||
uint64_t cbm_type_scope_index_test_work(void) {
|
||||
return atomic_load_explicit(&g_type_scope_index_work, memory_order_relaxed);
|
||||
}
|
||||
#define TYPE_SCOPE_INDEX_WORK(n) \
|
||||
atomic_fetch_add_explicit(&g_type_scope_index_work, (uint64_t)(n), memory_order_relaxed)
|
||||
#else
|
||||
#define TYPE_SCOPE_INDEX_WORK(n) ((void)0)
|
||||
#endif
|
||||
|
||||
static uint32_t type_scope_hash(const char *s, size_t len) {
|
||||
uint32_t h = 2166136261u;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
h = (h ^ (unsigned char)s[i]) * 16777619u;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope) {
|
||||
if (!a || !scope || !scope[0]) {
|
||||
return NULL;
|
||||
}
|
||||
size_t n = strlen(scope);
|
||||
TYPE_SCOPE_INDEX_WORK(n);
|
||||
if (n >= UINT32_MAX) {
|
||||
return NULL;
|
||||
}
|
||||
uint32_t entries = 1;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
entries += scope[i] == '|';
|
||||
}
|
||||
bool list = entries <= TYPE_SCOPE_LIST_MAX;
|
||||
uint32_t size = list ? entries : 4;
|
||||
while (!list && size < entries * 2) {
|
||||
size *= 2;
|
||||
}
|
||||
char *copy = cbm_arena_strndup(a, scope, n);
|
||||
cbm_type_scope_index_t *ix = (cbm_type_scope_index_t *)cbm_arena_alloc(a, sizeof(*ix));
|
||||
cbm_type_scope_entry_t *slots =
|
||||
(cbm_type_scope_entry_t *)cbm_arena_alloc(a, (size_t)size * sizeof(*slots));
|
||||
if (!copy || !ix || !slots) {
|
||||
return NULL;
|
||||
}
|
||||
memset(slots, 0, (size_t)size * sizeof(*slots));
|
||||
*ix = (cbm_type_scope_index_t){.text = copy, .slots = slots, .mask = list ? 0 : size - 1};
|
||||
for (char *p = copy; p && *p;) {
|
||||
char *bar = strchr(p, '|');
|
||||
if (bar) {
|
||||
*bar = '\0';
|
||||
}
|
||||
char *eq = strchr(p, '=');
|
||||
if (eq && eq > p && eq[1]) {
|
||||
*eq = '\0';
|
||||
uint32_t len = (uint32_t)(eq - p);
|
||||
cbm_type_scope_entry_t e = {
|
||||
.name = (uint32_t)(p - copy), .len = len, .qn = (uint32_t)(eq + 1 - copy)};
|
||||
uint32_t at = list ? 0 : type_scope_hash(p, len) & ix->mask;
|
||||
uint32_t end = list ? ix->count : UINT32_MAX;
|
||||
/* the first entry of a spelling stands */
|
||||
while (at < end && slots[at].len &&
|
||||
!(slots[at].len == len && memcmp(copy + slots[at].name, p, len) == 0)) {
|
||||
TYPE_SCOPE_INDEX_WORK(1);
|
||||
at = list ? at + 1 : (at + 1) & ix->mask;
|
||||
}
|
||||
if (list && at == ix->count) {
|
||||
slots[ix->count++] = e;
|
||||
} else if (!list && !slots[at].len) {
|
||||
slots[at] = e;
|
||||
}
|
||||
}
|
||||
p = bar ? bar + 1 : NULL;
|
||||
}
|
||||
return ix;
|
||||
}
|
||||
|
||||
const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *name,
|
||||
size_t name_len) {
|
||||
if (!ix || !name || name_len == 0) {
|
||||
return NULL;
|
||||
}
|
||||
TYPE_SCOPE_INDEX_WORK(name_len);
|
||||
const cbm_type_scope_entry_t *slots = ix->slots;
|
||||
if (ix->mask == 0) {
|
||||
for (uint32_t i = 0; i < ix->count; i++) {
|
||||
TYPE_SCOPE_INDEX_WORK(1);
|
||||
if (slots[i].len == name_len && memcmp(ix->text + slots[i].name, name, name_len) == 0) {
|
||||
return ix->text + slots[i].qn;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
uint32_t at = type_scope_hash(name, name_len) & ix->mask;
|
||||
while (slots[at].len) {
|
||||
TYPE_SCOPE_INDEX_WORK(1);
|
||||
if (slots[at].len == name_len && memcmp(ix->text + slots[at].name, name, name_len) == 0) {
|
||||
return ix->text + slots[at].qn;
|
||||
}
|
||||
at = (at + 1) & ix->mask;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -235,4 +235,25 @@ const CBMType* cbm_type_resolve_alias(const CBMType* t);
|
||||
const CBMType* cbm_type_substitute(CBMArena* a, const CBMType* t,
|
||||
const char** type_params, const CBMType** type_args);
|
||||
|
||||
// The identities of the type names one definition's declared types write
|
||||
// ("spelling=QN|spelling=QN", CBMLSPDef.type_scope, resolved once in the scope
|
||||
// of the file that wrote it by the pipeline's type-scope step), indexed once
|
||||
// per definition: a short list (up to 4 identities, most definitions) or a
|
||||
// hash table, 12 bytes an entry, so each lookup is bounded work. NULL for a
|
||||
// NULL or empty scope (or on allocation failure: the engine then qualifies as
|
||||
// before).
|
||||
typedef struct cbm_type_scope_index cbm_type_scope_index_t;
|
||||
const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope);
|
||||
|
||||
// The identity of one spelling exactly as the type text writes it (name_len
|
||||
// bytes): the QN (owned by the index's arena), or NULL when the def has none
|
||||
// for it (the engine then qualifies as before). NULL index = none.
|
||||
const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *name,
|
||||
size_t name_len);
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
// Work counter for the growth tests: bytes hashed and slots probed.
|
||||
uint64_t cbm_type_scope_index_test_work(void);
|
||||
#endif
|
||||
|
||||
#endif // CBM_LSP_TYPE_REP_H
|
||||
|
||||
+382
-24
@@ -5,13 +5,267 @@
|
||||
#include "preprocessor.h"
|
||||
#include "vendored/simplecpp/simplecpp.h"
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
|
||||
// ── #include lookup against the indexed repository root (#2993) ────────────
|
||||
// simplecpp looks a quoted header up as `dirPath(includer) + name` and opens it
|
||||
// relative to the process working directory, so the expansion depended on the
|
||||
// directory the indexer was started from. Here every #include and
|
||||
// __has_include of the file, and of each header it reaches, is resolved before
|
||||
// simplecpp runs: a quoted name in the including file's directory within the
|
||||
// repository root, read through the caller's CBMIncludeReader; an angle-bracket
|
||||
// name resolves to nothing, as no include directories are configured. The
|
||||
// result is stored in simplecpp's FileDataCache under the exact key its own
|
||||
// lookup (FileDataCache::get) computes, so simplecpp opens no file itself and
|
||||
// the expansion is a function of the indexed tree alone.
|
||||
namespace {
|
||||
|
||||
// A computed `#include MACRO` line names its header only after macro expansion,
|
||||
// which no lookup made ahead of simplecpp can see. Its directive is renamed to
|
||||
// one simplecpp does not know, and an unknown directive includes nothing.
|
||||
const char kUnresolvedIncludeDirective[] = "cbm_unresolved_include";
|
||||
|
||||
// True when `key`, the normalised name an include resolves to, names a file
|
||||
// within the indexed repository root: the name was written relative to the
|
||||
// including file, and every component of the normalised result names an entry
|
||||
// of the tree. The rule is the same on every platform, so one tree resolves the
|
||||
// same way everywhere.
|
||||
bool names_tree_file(const std::string &header, const std::string &key) {
|
||||
if (header.empty() || header[0] == '/' || header[0] == '\\' ||
|
||||
(header.size() >= 2U && header[1] == ':')) {
|
||||
return false;
|
||||
}
|
||||
if (key.empty() || key[0] == '/' || key.find(':') != std::string::npos ||
|
||||
key.find('\\') != std::string::npos || key.find('\0') != std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
std::string::size_type start = 0;
|
||||
for (;;) {
|
||||
const std::string::size_type end = key.find('/', start);
|
||||
const std::string part =
|
||||
key.substr(start, end == std::string::npos ? std::string::npos : end - start);
|
||||
if (part == "..") {
|
||||
return false;
|
||||
}
|
||||
if (end == std::string::npos) {
|
||||
return true;
|
||||
}
|
||||
start = end + 1U;
|
||||
}
|
||||
}
|
||||
|
||||
// The first non-comment token after `tok` on the same line, or nullptr.
|
||||
simplecpp::Token *next_on_line(simplecpp::Token *tok) {
|
||||
simplecpp::Token *next = tok->next;
|
||||
while (next && next->comment) {
|
||||
next = next->next;
|
||||
}
|
||||
return sameline(tok, next) ? next : nullptr;
|
||||
}
|
||||
|
||||
class IncludeTree {
|
||||
public:
|
||||
IncludeTree(const CBMIncludeReader *reader, std::vector<std::string> &files,
|
||||
simplecpp::FileDataCache &cache)
|
||||
: reader_(reader), files_(files), cache_(cache) {}
|
||||
|
||||
// Resolve everything the main file reaches. Every file name its own
|
||||
// tokens registered (itself, and names from its #line directives) is the
|
||||
// main file's; every later one belongs to a header.
|
||||
void add_main_file(simplecpp::TokenList &tokens) {
|
||||
first_header_file_ = static_cast<unsigned int>(files_.size());
|
||||
prepare(tokens);
|
||||
while (!pending_.empty()) {
|
||||
Pending next = std::move(pending_.front());
|
||||
pending_.pop_front();
|
||||
prepare(next.tokens);
|
||||
cache_.insert(simplecpp::FileData{next.key, std::move(next.tokens)});
|
||||
}
|
||||
}
|
||||
|
||||
// Tokens whose file index is at or above this came from a header.
|
||||
unsigned int first_header_file() const {
|
||||
return first_header_file_;
|
||||
}
|
||||
|
||||
// The repository files the lookup read, sorted (the map's order).
|
||||
void read_files(std::vector<std::string> *out) const {
|
||||
for (std::map<std::string, bool>::const_iterator it = loaded_.begin(); it != loaded_.end();
|
||||
++it) {
|
||||
if (it->second) {
|
||||
out->push_back(it->first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
struct Pending {
|
||||
std::string key;
|
||||
simplecpp::TokenList tokens;
|
||||
};
|
||||
|
||||
// Rewrite one file's __has_include tests and computed includes, and
|
||||
// resolve the headers its #include lines name.
|
||||
void prepare(simplecpp::TokenList &tokens) {
|
||||
for (simplecpp::Token *tok = tokens.front(); tok; tok = tok->next) {
|
||||
if (tok->str() == HAS_INCLUDE) {
|
||||
rewrite_has_include(tokens, tok);
|
||||
} else if (tok->op == '#' && !sameline(tok->previousSkipComments(), tok)) {
|
||||
simplecpp::Token *directive = next_on_line(tok);
|
||||
if (directive && directive->str() == INCLUDE) {
|
||||
resolve_include(directive);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `#include "name"` / `#include <name>` as simplecpp's preprocess reads it:
|
||||
// the first non-comment token after the directive, quotes or brackets
|
||||
// stripped.
|
||||
void resolve_include(simplecpp::Token *directive) {
|
||||
const simplecpp::Token *operand = next_on_line(directive);
|
||||
if (!operand) {
|
||||
return; // no header name: simplecpp reports it and opens nothing
|
||||
}
|
||||
if (operand->name) {
|
||||
directive->setstr(kUnresolvedIncludeDirective);
|
||||
return;
|
||||
}
|
||||
const std::string &spelled = operand->str();
|
||||
if (spelled.size() <= 2U) {
|
||||
return; // no header name: simplecpp reports it and opens nothing
|
||||
}
|
||||
(void)lookup(file_of(directive), spelled.substr(1U, spelled.size() - 2U),
|
||||
spelled[0] == '<');
|
||||
}
|
||||
|
||||
// `__has_include ( name )` (or without the parentheses) as simplecpp's #if
|
||||
// evaluation reads it becomes the literal 1 or 0 of the same lookup. The
|
||||
// operand of `defined` / `#ifdef` / `#ifndef` stays as it is. A form that
|
||||
// does not close on its line keeps its operand, and its #if still fails to
|
||||
// evaluate, as it did before.
|
||||
void rewrite_has_include(simplecpp::TokenList &tokens, simplecpp::Token *tok) {
|
||||
const simplecpp::Token *before = tok->previousSkipComments();
|
||||
if (before && before->op == '(' && sameline(before, tok)) {
|
||||
before = before->previousSkipComments();
|
||||
}
|
||||
if (before && sameline(before, tok) &&
|
||||
(before->str() == DEFINED || before->str() == IFDEF || before->str() == IFNDEF)) {
|
||||
return;
|
||||
}
|
||||
simplecpp::Token *operand = next_on_line(tok);
|
||||
const bool par = operand && operand->op == '(';
|
||||
if (par) {
|
||||
operand = next_on_line(operand);
|
||||
}
|
||||
bool found = false;
|
||||
simplecpp::Token *last = operand;
|
||||
if (operand && operand->op == '<') {
|
||||
while (last && last->op != '>') {
|
||||
last = next_on_line(last);
|
||||
}
|
||||
} else if (operand && operand->str().size() > 2U && operand->str()[0] == '"') {
|
||||
const std::string &spelled = operand->str();
|
||||
found = lookup(file_of(tok), spelled.substr(1U, spelled.size() - 2U), false);
|
||||
}
|
||||
if (last && par) {
|
||||
last = next_on_line(last);
|
||||
if (last && last->op != ')') {
|
||||
last = nullptr;
|
||||
}
|
||||
}
|
||||
tok->setstr(found ? "1" : "0");
|
||||
if (!last) {
|
||||
return;
|
||||
}
|
||||
while (tok->next != last) {
|
||||
tokens.deleteToken(tok->next);
|
||||
}
|
||||
tokens.deleteToken(last);
|
||||
}
|
||||
|
||||
const std::string &file_of(const simplecpp::Token *tok) const {
|
||||
static const std::string none;
|
||||
return tok->location.fileIndex < files_.size() ? files_[tok->location.fileIndex] : none;
|
||||
}
|
||||
|
||||
// Key the name the way simplecpp's FileDataCache::get does and make sure
|
||||
// the cache holds that key, so get() finds it instead of opening a file.
|
||||
// True when the name resolved to a file of the indexed tree.
|
||||
bool lookup(const std::string &sourcefile, const std::string &header, bool system) {
|
||||
if (simplecpp::isAbsolutePath(header)) {
|
||||
return load(simplecpp::simplifyPath(header), false);
|
||||
}
|
||||
if (system) {
|
||||
return false; // no include directories: get() opens nothing
|
||||
}
|
||||
const std::string key = simplecpp::simplifyPath(dirPath(sourcefile) + header);
|
||||
return load(key, names_tree_file(header, key));
|
||||
}
|
||||
|
||||
// Cache `key` once: its tokens when the tree holds it, an empty token list
|
||||
// otherwise (the include then adds nothing). The main file never resolves
|
||||
// as a header: its tokens are the expansion itself.
|
||||
bool load(const std::string &key, bool in_tree) {
|
||||
const std::map<std::string, bool>::const_iterator seen = loaded_.find(key);
|
||||
if (seen != loaded_.end()) {
|
||||
return seen->second;
|
||||
}
|
||||
std::string text;
|
||||
const bool found = in_tree && !names_main_file(key) && read(key, &text);
|
||||
loaded_[key] = found;
|
||||
if (!found) {
|
||||
cache_.insert(simplecpp::FileData{key, simplecpp::TokenList(files_)});
|
||||
return false;
|
||||
}
|
||||
std::istringstream istr(text);
|
||||
pending_.push_back(Pending{key, simplecpp::TokenList(istr, files_, key)});
|
||||
return true;
|
||||
}
|
||||
|
||||
bool names_main_file(const std::string &key) const {
|
||||
for (unsigned int i = 0; i < first_header_file_ && i < files_.size(); i++) {
|
||||
if (files_[i] == key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool read(const std::string &key, std::string *out) const {
|
||||
if (!reader_ || !reader_->read) {
|
||||
return false;
|
||||
}
|
||||
size_t len = 0;
|
||||
char *data = reader_->read(reader_->userdata, key.c_str(), &len);
|
||||
if (!data) {
|
||||
return false;
|
||||
}
|
||||
out->assign(data, len);
|
||||
if (reader_->release) {
|
||||
reader_->release(reader_->userdata, data);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const CBMIncludeReader *reader_;
|
||||
std::vector<std::string> &files_;
|
||||
simplecpp::FileDataCache &cache_;
|
||||
std::map<std::string, bool> loaded_;
|
||||
std::deque<Pending> pending_;
|
||||
unsigned int first_header_file_ = 0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
static bool has_preprocessor_work(const char *source, int source_len) {
|
||||
@@ -407,11 +661,23 @@ static bool tokens_source_adjacent(const simplecpp::Token *prev, const simplecpp
|
||||
// scopes, C-LSP class scopes) minted a second node for the same definition, the
|
||||
// QN dedup (strcmp) missing it. A gap that held whitespace or a comment is still
|
||||
// one space, as before.
|
||||
static std::string stringify_source_spacing(const simplecpp::TokenList &tokens) {
|
||||
//
|
||||
// Tokens of an included header's body (file index at or above
|
||||
// first_header_file) are left out: the header is indexed as its own file, and
|
||||
// its calls, usages and writes are its own, never the includer's. What the
|
||||
// header defines still shapes the main file's tokens, since macro expansions
|
||||
// carry the location of their use. With no header body in the buffer, the main
|
||||
// file's lines keep their own numbers, as they do when nothing is included.
|
||||
static std::string stringify_source_spacing(const simplecpp::TokenList &tokens,
|
||||
unsigned int first_header_file) {
|
||||
std::ostringstream ret;
|
||||
simplecpp::Location loc;
|
||||
loc.line = 1;
|
||||
const simplecpp::Token *prev = nullptr;
|
||||
for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) {
|
||||
if (tok->location.fileIndex >= first_header_file) {
|
||||
continue;
|
||||
}
|
||||
if (tok->location.line < loc.line || tok->location.fileIndex != loc.fileIndex) {
|
||||
ret << "\n#line " << tok->location.line << " \"" << tokens.file(tok->location)
|
||||
<< "\"\n";
|
||||
@@ -421,16 +687,113 @@ static std::string stringify_source_spacing(const simplecpp::TokenList &tokens)
|
||||
ret << '\n';
|
||||
loc.line++;
|
||||
}
|
||||
const simplecpp::Token *prev = tok->previous;
|
||||
if (prev && prev->location.sameline(tok->location) && !tokens_source_adjacent(prev, tok)) {
|
||||
ret << ' ';
|
||||
}
|
||||
ret << tok->str();
|
||||
loc.adjust(tok->str());
|
||||
prev = tok;
|
||||
}
|
||||
return ret.str();
|
||||
}
|
||||
|
||||
// simplecpp drops the whole expansion when it stops at #error, or at a
|
||||
// directive it cannot read or evaluate: the output list is cleared and an
|
||||
// ERROR or SYNTAX_ERROR is reported.
|
||||
static bool expansion_discarded(const simplecpp::TokenList &output,
|
||||
const simplecpp::OutputList &outputs) {
|
||||
if (!output.empty()) {
|
||||
return false;
|
||||
}
|
||||
for (simplecpp::OutputList::const_iterator it = outputs.begin(); it != outputs.end(); ++it) {
|
||||
if (it->type == simplecpp::Output::ERROR || it->type == simplecpp::Output::SYNTAX_ERROR) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// One simplecpp run over the file. Every header its #include and
|
||||
// __has_include lines reach is resolved through `reader` first (none when it
|
||||
// is NULL); `read` (may be NULL) receives the repository files the lookup
|
||||
// read, also when the run fails. Returns false when simplecpp discarded the
|
||||
// expansion.
|
||||
static bool preprocess_file(const std::string &src, const std::string &main_name,
|
||||
const simplecpp::DUI &dui, const CBMIncludeReader *reader,
|
||||
std::string *expanded, std::vector<std::string> *read) {
|
||||
std::vector<std::string> files;
|
||||
files.push_back(main_name);
|
||||
std::istringstream istr(src);
|
||||
simplecpp::TokenList rawtokens(istr, files, files[0]);
|
||||
simplecpp::FileDataCache cache;
|
||||
IncludeTree tree(reader, files, cache);
|
||||
bool kept = false;
|
||||
try {
|
||||
tree.add_main_file(rawtokens);
|
||||
simplecpp::TokenList output(files);
|
||||
simplecpp::OutputList outputs;
|
||||
simplecpp::preprocess(output, rawtokens, files, cache, dui, &outputs);
|
||||
kept = !expansion_discarded(output, outputs);
|
||||
*expanded = stringify_source_spacing(output, tree.first_header_file());
|
||||
} catch (...) {
|
||||
if (read) {
|
||||
tree.read_files(read);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
if (read) {
|
||||
tree.read_files(read);
|
||||
}
|
||||
simplecpp::cleanup(cache);
|
||||
return kept;
|
||||
}
|
||||
|
||||
// The file's expansion with its includes followed. When what an include
|
||||
// brought in stops simplecpp (an #error reached inside a header, a header
|
||||
// directive it cannot evaluate, a failure while reading one), the file keeps
|
||||
// its expansion without includes instead of losing it. `read` receives the
|
||||
// repository files the include-following run read.
|
||||
static std::string preprocess_with_fallback(const std::string &src, const std::string &main_name,
|
||||
const simplecpp::DUI &dui,
|
||||
const CBMIncludeReader *reader,
|
||||
std::vector<std::string> *read) {
|
||||
std::string expanded;
|
||||
if (reader) {
|
||||
try {
|
||||
if (preprocess_file(src, main_name, dui, reader, &expanded, read)) {
|
||||
return expanded;
|
||||
}
|
||||
} catch (...) {
|
||||
// fall through to the expansion without includes
|
||||
}
|
||||
expanded.clear();
|
||||
}
|
||||
(void)preprocess_file(src, main_name, dui, nullptr, &expanded, nullptr);
|
||||
return expanded;
|
||||
}
|
||||
|
||||
// A malloc'd copy of `read` for CBMPreprocessedSource.included_files; false on
|
||||
// allocation failure (everything copied so far is released by the caller).
|
||||
static bool copy_included_files(const std::vector<std::string> &read, CBMPreprocessedSource *pp) {
|
||||
if (read.empty()) {
|
||||
return true;
|
||||
}
|
||||
pp->included_files = (char **)calloc(read.size(), sizeof(char *));
|
||||
if (!pp->included_files) {
|
||||
return false;
|
||||
}
|
||||
for (size_t i = 0; i < read.size(); i++) {
|
||||
char *copy = (char *)malloc(read[i].size() + 1);
|
||||
if (!copy) {
|
||||
return false;
|
||||
}
|
||||
memcpy(copy, read[i].c_str(), read[i].size() + 1);
|
||||
pp->included_files[i] = copy;
|
||||
pp->included_count = (int)i + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool build_line_map(const std::string &expanded, const std::string &main_file,
|
||||
uint32_t *original_line_by_expanded_line,
|
||||
uint8_t *belongs_to_main_file) {
|
||||
@@ -472,7 +835,9 @@ static bool build_line_map(const std::string &expanded, const std::string &main_
|
||||
|
||||
CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_len,
|
||||
const char *filename, const char **extra_defines,
|
||||
const char **include_paths, int cpp_mode) {
|
||||
const char **include_paths, int cpp_mode,
|
||||
const CBMIncludeReader *reader) {
|
||||
(void)include_paths; // lookups resolve through `reader` only (preprocessor.h)
|
||||
// Run the second pass when there are directives to evaluate OR when the file
|
||||
// carries export-macro-shaped identifiers to predefine empty (#1989) — a UE
|
||||
// plugin header with only `#pragma once` + `#include` lines still needs it.
|
||||
@@ -509,32 +874,21 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le
|
||||
dui.defines.push_back(std::string(export_cands[i]) + "=");
|
||||
}
|
||||
}
|
||||
if (include_paths) {
|
||||
for (int i = 0; include_paths[i]; i++)
|
||||
dui.includePaths.push_back(include_paths[i]);
|
||||
}
|
||||
dui.std = cpp_mode ? "c++17" : "c11";
|
||||
|
||||
std::string src(source, source_len);
|
||||
std::istringstream istr(src);
|
||||
std::vector<std::string> files;
|
||||
files.push_back(filename ? filename : "<input>");
|
||||
|
||||
simplecpp::TokenList rawtokens(istr, files, files[0]);
|
||||
simplecpp::TokenList output(files);
|
||||
simplecpp::FileDataCache filedata = simplecpp::load(rawtokens, files, dui);
|
||||
|
||||
simplecpp::preprocess(output, rawtokens, files, filedata, dui);
|
||||
|
||||
std::string result = stringify_source_spacing(output);
|
||||
|
||||
// Clean up loaded file data
|
||||
simplecpp::cleanup(filedata);
|
||||
const std::string src(source, source_len);
|
||||
const std::string main_name(filename ? filename : "<input>");
|
||||
std::vector<std::string> read;
|
||||
std::string result = preprocess_with_fallback(src, main_name, dui, reader, &read);
|
||||
|
||||
CBMPreprocessedSource *pp = (CBMPreprocessedSource *)calloc(1, sizeof(*pp));
|
||||
if (!pp) {
|
||||
return NULL;
|
||||
}
|
||||
if (!copy_included_files(read, pp)) {
|
||||
cbm_preprocessed_source_free(pp);
|
||||
return NULL;
|
||||
}
|
||||
int line_count = count_expanded_lines(result);
|
||||
pp->source = (char *)malloc(result.size() + 1);
|
||||
pp->original_line_by_expanded_line =
|
||||
@@ -546,7 +900,7 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le
|
||||
return NULL;
|
||||
}
|
||||
memcpy(pp->source, result.c_str(), result.size() + 1);
|
||||
if (!build_line_map(result, files[0], pp->original_line_by_expanded_line,
|
||||
if (!build_line_map(result, main_name, pp->original_line_by_expanded_line,
|
||||
pp->belongs_to_main_file)) {
|
||||
cbm_preprocessed_source_free(pp);
|
||||
return NULL;
|
||||
@@ -561,7 +915,7 @@ CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_le
|
||||
char *cbm_preprocess(const char *source, int source_len, const char *filename,
|
||||
const char **extra_defines, const char **include_paths, int cpp_mode) {
|
||||
CBMPreprocessedSource *pp = cbm_preprocess_with_map(source, source_len, filename, extra_defines,
|
||||
include_paths, cpp_mode);
|
||||
include_paths, cpp_mode, NULL);
|
||||
if (!pp) {
|
||||
return NULL;
|
||||
}
|
||||
@@ -582,6 +936,10 @@ void cbm_preprocessed_source_free(CBMPreprocessedSource *pp) {
|
||||
free(pp->source);
|
||||
free(pp->original_line_by_expanded_line);
|
||||
free(pp->belongs_to_main_file);
|
||||
for (int i = 0; i < pp->included_count; i++) {
|
||||
free(pp->included_files[i]);
|
||||
}
|
||||
free(pp->included_files);
|
||||
free(pp);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,28 +22,55 @@ typedef struct {
|
||||
uint32_t *original_line_by_expanded_line; // 1-based; 0 means directive/unmapped.
|
||||
uint8_t *belongs_to_main_file; // 1-based; true only for the original input file.
|
||||
int expanded_line_count;
|
||||
/* The repository files the #include lookup read (repository-relative,
|
||||
* sorted, each once), whether or not the run that followed includes kept
|
||||
* its expansion: the expansion depends on their bytes either way. */
|
||||
char **included_files;
|
||||
int included_count;
|
||||
} CBMPreprocessedSource;
|
||||
|
||||
/* Supplies the files of the indexed repository to the #include lookup of the
|
||||
* preprocessed pass. rel_path is relative to the repository root, '/'-separated
|
||||
* and normalised. read returns a buffer of *out_len bytes, handed back to
|
||||
* release once consumed, or NULL when the repository holds no such file. */
|
||||
typedef struct {
|
||||
char *(*read)(const void *userdata, const char *rel_path, size_t *out_len);
|
||||
void (*release)(const void *userdata, char *data);
|
||||
const void *userdata;
|
||||
} CBMIncludeReader;
|
||||
|
||||
// Collect conventional export-macro-shaped identifiers (ALL_CAPS ending in
|
||||
// _API/_EXPORT/_IMPORT/_DLLEXPORT/_DEPRECATED) from the source, up to max_out
|
||||
// unique names. Returns the number of names stored in out.
|
||||
int cbm_export_macro_candidates(const char *source, int source_len,
|
||||
char (*out)[CBM_EXPORT_MACRO_NAME_MAX], int max_out);
|
||||
|
||||
// Preprocess C/C++ source: expand macros, evaluate #ifdef, resolve #include.
|
||||
// Preprocess C/C++ source: expand macros, evaluate #ifdef. #include is not
|
||||
// followed (no include reader): every included header contributes nothing.
|
||||
// Returns malloc-allocated expanded source, or NULL if no expansion needed/on failure.
|
||||
// extra_defines: NULL-terminated array of "NAME=VALUE" strings (can be NULL).
|
||||
// include_paths: NULL-terminated array of directory paths for #include resolution (can be NULL).
|
||||
// include_paths: kept for API compatibility; not consulted (see cbm_preprocess_with_map).
|
||||
// The returned string must be freed with cbm_preprocess_free().
|
||||
char *cbm_preprocess(const char *source, int source_len, const char *filename,
|
||||
const char **extra_defines, const char **include_paths, int cpp_mode);
|
||||
|
||||
// Preprocess and return source plus expanded-line -> original-line ownership map.
|
||||
// filename is the file's path relative to the indexed repository root. Quoted
|
||||
// #include and __has_include names resolve through `reader` only, in the
|
||||
// including file's directory within the repository root; a NULL reader
|
||||
// resolves nothing. Angle-bracket names and computed #include lines resolve to
|
||||
// nothing, and include_paths is not consulted, so the expansion is a function
|
||||
// of the indexed tree alone. The expanded buffer holds the main file's own
|
||||
// tokens only: what an included header defines (macros, #if state) shapes it,
|
||||
// but the header's body is not part of it; the header is indexed as its own
|
||||
// file. When the run that follows includes ends in #error (or another stop that
|
||||
// discards the expansion), the file falls back to its expansion without includes.
|
||||
// Returns NULL if no expansion is needed or preprocessing fails.
|
||||
// Free with cbm_preprocessed_source_free().
|
||||
CBMPreprocessedSource *cbm_preprocess_with_map(const char *source, int source_len,
|
||||
const char *filename, const char **extra_defines,
|
||||
const char **include_paths, int cpp_mode);
|
||||
const char **include_paths, int cpp_mode,
|
||||
const CBMIncludeReader *reader);
|
||||
|
||||
// Free preprocessed source returned by cbm_preprocess.
|
||||
void cbm_preprocess_free(char *expanded);
|
||||
|
||||
@@ -282,6 +282,16 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) {
|
||||
cr_str(c, &d->decl_namespace);
|
||||
cr_str(c, &d->variant_key);
|
||||
cr_str(c, &d->alias_target);
|
||||
/* The type-facts record: one record, then its strings. */
|
||||
cr_array(c, (void **)&d->type_facts, d->type_facts ? 1 : 0, sizeof(CBMDefTypeFacts));
|
||||
CBMDefTypeFacts *facts = (CBMDefTypeFacts *)d->type_facts;
|
||||
if (facts) {
|
||||
cr_str(c, &facts->type_params);
|
||||
cr_str(c, &facts->value_type);
|
||||
cr_str(c, &facts->go_embedded);
|
||||
cr_str(c, &facts->class_bindings);
|
||||
cr_str(c, &facts->global_names);
|
||||
}
|
||||
}
|
||||
|
||||
static void cr_walk_call(cr_ctx_t *c, CBMCall *call) {
|
||||
@@ -461,6 +471,7 @@ static void cr_walk(cr_ctx_t *c, CBMFileResult *r) {
|
||||
cr_list(c, &r->constants);
|
||||
cr_list(c, &r->global_vars);
|
||||
cr_list(c, &r->macros);
|
||||
cr_list(c, &r->included_files);
|
||||
cr_str(c, &r->error_msg);
|
||||
cr_str(c, &r->error_ranges);
|
||||
cr_str(c, &r->module_doc);
|
||||
|
||||
@@ -55,7 +55,7 @@ src/mcp/mcp.c 765
|
||||
src/pipeline/artifact.c 38
|
||||
src/pipeline/fqn.c 23
|
||||
src/pipeline/lsp_resolve.h 4
|
||||
src/pipeline/lsp_surface.c 5
|
||||
src/pipeline/lsp_surface.c 4
|
||||
src/pipeline/pass_calls.c 22
|
||||
src/pipeline/pass_compile_commands.c 17
|
||||
src/pipeline/pass_configlink.c 3
|
||||
|
||||
+333
-19
@@ -32,15 +32,24 @@
|
||||
#include "foundation/log.h"
|
||||
#include "foundation/mem_core.h"
|
||||
#include "foundation/sha256.h"
|
||||
#include "pipeline/doc_links.h" /* cbm_doclinks_storable_scope */
|
||||
#include "pipeline/doc_links.h" /* cbm_doclinks_storable_scope */
|
||||
#include "pipeline/type_scope.h" /* the type labels identities may name */
|
||||
#include "pipeline/worker_pool.h"
|
||||
#include "yyjson/yyjson.h"
|
||||
|
||||
/* 3: Go defs carry their parsed result list `|`-joined in "ret" (F-G8 D1);
|
||||
* a version-2 surface holds the raw result text and must be re-extracted.
|
||||
* 4: Go identity aliases carry their target in "al" (#2033); a version-3
|
||||
* surface has no alias targets and must be re-extracted. */
|
||||
enum { SURFACE_CODEC_VERSION = 4 };
|
||||
* surface has no alias targets and must be re-extracted.
|
||||
* 5: defs carry their declared types' identities in "ty" (type_scope.h); a
|
||||
* version-4 surface has none, and a dependent re-resolved against it would
|
||||
* lose the calls a full index makes through them. The surface hash and the
|
||||
* Python namespace comparison leave "ty" out: they judge the identities'
|
||||
* inputs (the def's type texts, the file's imports in "dl" / "py"), which
|
||||
* the planner's probe computes exactly as a full index does; the outputs
|
||||
* also depend on other files' type definitions, which the planner gates
|
||||
* itself (closure_identity_decline, pipeline_incremental.c). */
|
||||
enum { SURFACE_CODEC_VERSION = 5 };
|
||||
|
||||
/* Labels the incremental name registry serves that pxc_map_label does NOT
|
||||
* carry into the CBMLSPDef set. Their (name, qn, label) triple must still
|
||||
@@ -328,6 +337,72 @@ int cbm_lsp_surface_python_namespace_from_json(CBMArena *arena, const char *json
|
||||
return status;
|
||||
}
|
||||
|
||||
/* Two objects equal member by member, in order, leaving out the members named
|
||||
* `skip` (NULL skips none). */
|
||||
static bool surface_obj_equal_except(yyjson_val *a, yyjson_val *b, const char *skip) {
|
||||
if (!yyjson_is_obj(a) || !yyjson_is_obj(b)) {
|
||||
return yyjson_equals(a, b);
|
||||
}
|
||||
yyjson_obj_iter ia = yyjson_obj_iter_with(a);
|
||||
yyjson_obj_iter ib = yyjson_obj_iter_with(b);
|
||||
for (;;) {
|
||||
yyjson_val *ka = yyjson_obj_iter_next(&ia);
|
||||
while (ka && skip && yyjson_equals_str(ka, skip)) {
|
||||
ka = yyjson_obj_iter_next(&ia);
|
||||
}
|
||||
yyjson_val *kb = yyjson_obj_iter_next(&ib);
|
||||
while (kb && skip && yyjson_equals_str(kb, skip)) {
|
||||
kb = yyjson_obj_iter_next(&ib);
|
||||
}
|
||||
if (!ka || !kb) {
|
||||
return !ka && !kb;
|
||||
}
|
||||
if (!yyjson_equals(ka, kb) ||
|
||||
!yyjson_equals(yyjson_obj_iter_get_val(ka), yyjson_obj_iter_get_val(kb))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Two surface rows equal but for their declared-type identities ("ty" in
|
||||
* each "lsp" def), which the comparisons leave out (SURFACE_CODEC_VERSION). */
|
||||
static bool surface_rows_equal_without_identities(yyjson_val *a, yyjson_val *b) {
|
||||
if (!yyjson_is_obj(a) || !yyjson_is_obj(b)) {
|
||||
return yyjson_equals(a, b);
|
||||
}
|
||||
yyjson_obj_iter ia = yyjson_obj_iter_with(a);
|
||||
yyjson_obj_iter ib = yyjson_obj_iter_with(b);
|
||||
for (;;) {
|
||||
yyjson_val *ka = yyjson_obj_iter_next(&ia);
|
||||
yyjson_val *kb = yyjson_obj_iter_next(&ib);
|
||||
if (!ka || !kb) {
|
||||
return !ka && !kb;
|
||||
}
|
||||
if (!yyjson_equals(ka, kb)) {
|
||||
return false;
|
||||
}
|
||||
yyjson_val *va = yyjson_obj_iter_get_val(ka);
|
||||
yyjson_val *vb = yyjson_obj_iter_get_val(kb);
|
||||
if (!yyjson_equals_str(ka, "lsp") || !yyjson_is_arr(va) || !yyjson_is_arr(vb)) {
|
||||
if (!yyjson_equals(va, vb)) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (yyjson_arr_size(va) != yyjson_arr_size(vb)) {
|
||||
return false;
|
||||
}
|
||||
yyjson_arr_iter da = yyjson_arr_iter_with(va);
|
||||
yyjson_arr_iter db = yyjson_arr_iter_with(vb);
|
||||
for (yyjson_val *x = yyjson_arr_iter_next(&da), *y = yyjson_arr_iter_next(&db); x && y;
|
||||
x = yyjson_arr_iter_next(&da), y = yyjson_arr_iter_next(&db)) {
|
||||
if (!surface_obj_equal_except(x, y, "ty")) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) {
|
||||
if (!old_json) {
|
||||
return -1;
|
||||
@@ -349,9 +424,12 @@ int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) {
|
||||
: 0;
|
||||
int result = -1;
|
||||
if (old_state >= 0 && new_state >= 0) {
|
||||
result = (old_state == 0 && new_state == 0) ? 0
|
||||
: (old_state != new_state || !new_json || strcmp(old_json, new_json) != 0) ? 1
|
||||
: 0;
|
||||
result = (old_state == 0 && new_state == 0) ? 0
|
||||
: (old_state != new_state || !new_doc ||
|
||||
!surface_rows_equal_without_identities(yyjson_doc_get_root(old_doc),
|
||||
yyjson_doc_get_root(new_doc)))
|
||||
? 1
|
||||
: 0;
|
||||
}
|
||||
cbm_arena_destroy(&scratch);
|
||||
yyjson_doc_free(old_doc);
|
||||
@@ -359,12 +437,185 @@ int cbm_lsp_surface_python_change(const char *old_json, const char *new_json) {
|
||||
return result;
|
||||
}
|
||||
|
||||
/* ── Declared-type identities across a repair ─────────────────────── */
|
||||
|
||||
static bool surface_type_label(int lang, const char *label) {
|
||||
const cbm_type_scope_lang_t *row =
|
||||
lang >= 0 && lang < (int)CBM_LANG_COUNT ? cbm_type_scope_lang((CBMLanguage)lang) : NULL;
|
||||
for (const char *const *l = row && label ? row->labels : NULL; l && *l; l++) {
|
||||
if (strcmp(*l, label) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Hash one row's type definitions: QN -> its def object (both borrowed from
|
||||
* the returned doc, which the caller frees). A row that does not parse
|
||||
* returns NULL; the planner has validated every row it passes. */
|
||||
static yyjson_doc *surface_row_types(const char *json, CBMHashTable *types, uint64_t *work) {
|
||||
yyjson_doc *doc = json ? yyjson_read(json, strlen(json), 0) : NULL;
|
||||
yyjson_val *lsp = doc ? yyjson_obj_get(yyjson_doc_get_root(doc), "lsp") : NULL;
|
||||
if (!yyjson_is_arr(lsp)) {
|
||||
return doc;
|
||||
}
|
||||
yyjson_arr_iter it = yyjson_arr_iter_with(lsp);
|
||||
for (yyjson_val *d = yyjson_arr_iter_next(&it); d; d = yyjson_arr_iter_next(&it)) {
|
||||
if (work) {
|
||||
(*work)++;
|
||||
}
|
||||
const char *qn = yyjson_get_str(yyjson_obj_get(d, "qn"));
|
||||
if (qn &&
|
||||
surface_type_label(yyjson_get_int(yyjson_obj_get(d, "lg")),
|
||||
yyjson_get_str(yyjson_obj_get(d, "lb"))) &&
|
||||
!cbm_ht_get(types, qn)) {
|
||||
cbm_ht_set(types, qn, d);
|
||||
}
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
const CBMHashTable *other; /* the row's types on the other side */
|
||||
CBMHashTable *gone; /* QNs whose type definition changed or left (owned keys) */
|
||||
bool appeared;
|
||||
} surface_type_cmp_t;
|
||||
|
||||
static void surface_type_appeared(const char *qn, void *val, void *ud) {
|
||||
(void)val;
|
||||
surface_type_cmp_t *c = (surface_type_cmp_t *)ud;
|
||||
if (!cbm_ht_get(c->other, qn)) {
|
||||
c->appeared = true;
|
||||
}
|
||||
}
|
||||
|
||||
static void surface_type_changed(const char *qn, void *val, void *ud) {
|
||||
surface_type_cmp_t *c = (surface_type_cmp_t *)ud;
|
||||
yyjson_val *now = (yyjson_val *)cbm_ht_get(c->other, qn);
|
||||
if ((now && surface_obj_equal_except((yyjson_val *)val, now, "ty")) ||
|
||||
cbm_ht_get(c->gone, qn)) {
|
||||
return;
|
||||
}
|
||||
char *key = cbm_alloc(CBM_MEM_CLASS_OTHER, strlen(qn) + 1);
|
||||
if (key) {
|
||||
memcpy(key, qn, strlen(qn) + 1);
|
||||
cbm_ht_set(c->gone, key, key);
|
||||
}
|
||||
}
|
||||
|
||||
static void surface_free_key(const char *key, void *val, void *ud) {
|
||||
(void)val;
|
||||
(void)ud;
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, (void *)key);
|
||||
}
|
||||
|
||||
/* True when one of the identities stored in `ty` ("spelling=QN|...") names a
|
||||
* QN of `gone`. */
|
||||
static bool surface_names_gone(const char *ty, const CBMHashTable *gone, char **buf, size_t *cap,
|
||||
uint64_t *work) {
|
||||
for (const char *p = ty; p && *p;) {
|
||||
const char *eq = strchr(p, '=');
|
||||
if (!eq) {
|
||||
return false;
|
||||
}
|
||||
const char *bar = strchr(eq, '|');
|
||||
size_t len = bar ? (size_t)(bar - eq - 1) : strlen(eq + 1);
|
||||
if (work) {
|
||||
*work += (uint64_t)(len + (size_t)(eq - p) + 1);
|
||||
}
|
||||
if (len + 1 > *cap) {
|
||||
size_t grown_cap = (len + 1) * 2;
|
||||
char *grown = cbm_realloc(CBM_MEM_CLASS_OTHER, *buf, grown_cap);
|
||||
if (!grown) {
|
||||
return true; /* cannot tell: decline */
|
||||
}
|
||||
*buf = grown;
|
||||
*cap = grown_cap;
|
||||
}
|
||||
memcpy(*buf, eq + 1, len);
|
||||
(*buf)[len] = '\0';
|
||||
if (cbm_ht_get(gone, *buf)) {
|
||||
return true;
|
||||
}
|
||||
p = bar ? bar + 1 : eq + 1 + len;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const char *cbm_lsp_surface_identity_decline(const char *const *old_rows,
|
||||
const char *const *new_rows, int changed_count,
|
||||
const cbm_lsp_surface_row_t *stored, int stored_count,
|
||||
uint64_t *work) {
|
||||
const char *decline = NULL;
|
||||
CBMHashTable *gone = cbm_ht_create(CBM_SZ_64);
|
||||
if (!gone) {
|
||||
return "alloc";
|
||||
}
|
||||
for (int i = 0; i < changed_count && !decline; i++) {
|
||||
CBMHashTable *before = cbm_ht_create(CBM_SZ_64);
|
||||
CBMHashTable *after = cbm_ht_create(CBM_SZ_64);
|
||||
yyjson_doc *old_doc = before ? surface_row_types(old_rows[i], before, work) : NULL;
|
||||
yyjson_doc *new_doc =
|
||||
after && new_rows[i] ? surface_row_types(new_rows[i], after, work) : NULL;
|
||||
if (!before || !after) {
|
||||
decline = "alloc";
|
||||
} else if (!old_doc || (new_rows[i] && !new_doc)) {
|
||||
decline = "surface_row_unreadable";
|
||||
} else {
|
||||
surface_type_cmp_t appear = {.other = before};
|
||||
cbm_ht_foreach(after, surface_type_appeared, &appear);
|
||||
surface_type_cmp_t change = {.other = after, .gone = gone};
|
||||
cbm_ht_foreach(before, surface_type_changed, &change);
|
||||
if (appear.appeared) {
|
||||
decline = "declared_types_changed";
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(old_doc);
|
||||
yyjson_doc_free(new_doc);
|
||||
cbm_ht_free(before);
|
||||
cbm_ht_free(after);
|
||||
}
|
||||
/* A changed or departed type matters only when an identity names it:
|
||||
* read the stored identities (only rows that hold one are parsed). */
|
||||
char *buf = NULL;
|
||||
size_t cap = 0;
|
||||
for (int r = 0; r < stored_count && !decline && cbm_ht_count(gone) > 0; r++) {
|
||||
const char *json = stored[r].defs_json;
|
||||
if (work && json) {
|
||||
*work += (uint64_t)strlen(json);
|
||||
}
|
||||
if (!json || !strstr(json, "\"ty\":")) {
|
||||
continue;
|
||||
}
|
||||
yyjson_doc *doc = yyjson_read(json, strlen(json), 0);
|
||||
yyjson_val *lsp = doc ? yyjson_obj_get(yyjson_doc_get_root(doc), "lsp") : NULL;
|
||||
if (!doc) {
|
||||
decline = "surface_row_unreadable";
|
||||
}
|
||||
yyjson_arr_iter it = yyjson_arr_iter_with(lsp);
|
||||
for (yyjson_val *d = lsp ? yyjson_arr_iter_next(&it) : NULL; d && !decline;
|
||||
d = yyjson_arr_iter_next(&it)) {
|
||||
const char *ty = yyjson_get_str(yyjson_obj_get(d, "ty"));
|
||||
if (ty && surface_names_gone(ty, gone, &buf, &cap, work)) {
|
||||
decline = "identity_target_changed";
|
||||
}
|
||||
}
|
||||
yyjson_doc_free(doc);
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, buf);
|
||||
cbm_ht_foreach(gone, surface_free_key, NULL);
|
||||
cbm_ht_free(gone);
|
||||
return decline;
|
||||
}
|
||||
|
||||
/* Serialize one file's surface: its slice of all_defs plus the registry-only
|
||||
* symbols from its raw extraction defs. Returns a malloc'd JSON string and its
|
||||
* length. */
|
||||
* symbols from its raw extraction defs. Returns the JSON string (malloc'd, or
|
||||
* from `alc` when given) and its length. With identities, each def's
|
||||
* declared-type identities ("ty") are written as well: the stored row carries
|
||||
* them, the hashed bytes do not. */
|
||||
static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage language,
|
||||
const char *rel_path, const CBMLSPDef *defs, int def_count,
|
||||
size_t *out_len) {
|
||||
bool identities, const yyjson_alc *alc, size_t *out_len) {
|
||||
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
|
||||
if (!doc) {
|
||||
return NULL;
|
||||
@@ -400,6 +651,11 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu
|
||||
yyjson_mut_obj_add_bool(doc, o, "ab", d->is_abstract);
|
||||
add_str_array_or_null(doc, o, "dec", d->decorators, -1);
|
||||
add_str_or_null(doc, o, "al", d->alias_target);
|
||||
/* Stored for the routes that resolve against this row without
|
||||
* re-extracting it; never hashed (see SURFACE_CODEC_VERSION). */
|
||||
if (identities && d->type_scope) {
|
||||
yyjson_mut_obj_add_str(doc, o, "ty", d->type_scope);
|
||||
}
|
||||
yyjson_mut_arr_add_val(lsp, o);
|
||||
}
|
||||
yyjson_mut_obj_add_val(doc, root, "lsp", lsp);
|
||||
@@ -498,7 +754,7 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu
|
||||
}
|
||||
/* Names, types and strings come from source text, which need not be UTF-8:
|
||||
* one such byte must not cost the repository every surface row. */
|
||||
char *json = cbm_json_write_text(doc, NULL, out_len);
|
||||
char *json = cbm_json_write_text(doc, alc, out_len);
|
||||
yyjson_mut_doc_free(doc);
|
||||
return json;
|
||||
}
|
||||
@@ -519,6 +775,42 @@ typedef struct {
|
||||
_Atomic bool failed;
|
||||
} surface_job_t;
|
||||
|
||||
/* Row strings are released with cbm_store_free_lsp_surfaces (free), so they
|
||||
* come from the C heap: one place allocates them. */
|
||||
static char *surface_row_alloc(size_t n) {
|
||||
return malloc(n);
|
||||
}
|
||||
|
||||
static char *surface_row_strdup(const char *s) {
|
||||
size_t n = strlen(s);
|
||||
char *copy = surface_row_alloc(n + 1);
|
||||
if (copy) {
|
||||
memcpy(copy, s, n + 1);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
/* CBMFileResult.included_files, one file per line ("" when none). */
|
||||
static char *surface_row_included_files(const CBMFileResult *fr) {
|
||||
size_t len = 0;
|
||||
for (const char *const *f = fr->included_files; f && *f; f++) {
|
||||
len += strlen(*f) + 1;
|
||||
}
|
||||
char *out = surface_row_alloc(len + 1);
|
||||
if (!out) {
|
||||
return NULL;
|
||||
}
|
||||
size_t at = 0;
|
||||
for (const char *const *f = fr->included_files; f && *f; f++) {
|
||||
size_t n = strlen(*f);
|
||||
memcpy(out + at, *f, n);
|
||||
at += n;
|
||||
out[at++] = '\n';
|
||||
}
|
||||
out[at] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
static void surface_row_build(int i, void *arg) {
|
||||
surface_job_t *job = (surface_job_t *)arg;
|
||||
if (atomic_load_explicit(&job->failed, memory_order_relaxed)) {
|
||||
@@ -535,25 +827,46 @@ static void surface_row_build(int i, void *arg) {
|
||||
}
|
||||
int start = job->def_starts ? job->def_starts[i] : 0;
|
||||
int end = job->def_starts ? job->def_starts[i + 1] : 0;
|
||||
const CBMLSPDef *slice = job->all_defs ? job->all_defs + start : NULL;
|
||||
bool identities = false;
|
||||
for (int d = 0; slice && d < end - start && !identities; d++) {
|
||||
identities = slice[d].type_scope != NULL;
|
||||
}
|
||||
size_t json_len = 0;
|
||||
/* The hash covers the row without identities; a row that has some is
|
||||
* written a second time with them, for storage (the hashed text is then
|
||||
* a memory-core buffer, released here). */
|
||||
char *json =
|
||||
surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path,
|
||||
job->all_defs ? job->all_defs + start : NULL, end - start, &json_len);
|
||||
surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path, slice, end - start,
|
||||
false, identities ? cbm_json_writer_allocator() : NULL, &json_len);
|
||||
char sha[CBM_SHA256_HEX_LEN + 1];
|
||||
if (json) {
|
||||
cbm_sha256_hex(json, json_len, sha);
|
||||
}
|
||||
if (json && identities) {
|
||||
size_t stored_len = 0;
|
||||
char *stored = surface_file_to_json(fr, job->files[i].language, job->files[i].rel_path,
|
||||
slice, end - start, true, NULL, &stored_len);
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, json);
|
||||
json = stored;
|
||||
}
|
||||
char *included = surface_row_included_files(fr);
|
||||
cbm_pipeline_result_release(fr, loaded);
|
||||
if (!json) {
|
||||
if (!json || !included) {
|
||||
free(json);
|
||||
free(included);
|
||||
atomic_store_explicit(&job->failed, true, memory_order_relaxed);
|
||||
return;
|
||||
}
|
||||
char sha[CBM_SHA256_HEX_LEN + 1];
|
||||
cbm_sha256_hex(json, json_len, sha);
|
||||
cbm_lsp_surface_row_t *r = &job->rows[i];
|
||||
r->defs_json = json; /* set first: it marks the row present for the compaction */
|
||||
r->project = strdup(job->project);
|
||||
r->rel_path = strdup(job->files[i].rel_path);
|
||||
r->surface_sha = strdup(sha);
|
||||
r->project = surface_row_strdup(job->project);
|
||||
r->rel_path = surface_row_strdup(job->files[i].rel_path);
|
||||
r->surface_sha = surface_row_strdup(sha);
|
||||
r->ref_bloom = NULL;
|
||||
r->ref_bloom_len = 0;
|
||||
r->config_ctx = strdup("");
|
||||
r->config_ctx = surface_row_strdup("");
|
||||
r->included_files = included;
|
||||
if (!r->project || !r->rel_path || !r->surface_sha || !r->config_ctx) {
|
||||
atomic_store_explicit(&job->failed, true, memory_order_relaxed);
|
||||
}
|
||||
@@ -749,6 +1062,7 @@ int cbm_lsp_surface_defs_from_json(CBMArena *arena, const char *defs_json, CBMLS
|
||||
int dec_count = 0;
|
||||
d->decorators = arena_str_array(arena, yyjson_obj_get(o, "dec"), true, &dec_count);
|
||||
d->alias_target = arena_str_or_null(arena, yyjson_obj_get(o, "al"));
|
||||
d->type_scope = arena_str_or_null(arena, yyjson_obj_get(o, "ty"));
|
||||
if (!d->qualified_name || !d->short_name || !d->label) {
|
||||
/* A def the writer could not have produced: qn/sn/label are
|
||||
* unconditionally present in build_lsp_def output. Corrupt row. */
|
||||
|
||||
@@ -15,8 +15,11 @@
|
||||
* events and unknown effects; other languages carry an explicit null.
|
||||
* Field order and array order are fixed by the writer, so byte equality of the
|
||||
* serialization is surface equality; the sha256 of these bytes is the
|
||||
* stored surface_sha. Rows written by a different codec version fail the
|
||||
* "v" check on load and route the run to a full rebuild.
|
||||
* stored surface_sha. A def's declared-type identities ("ty", type_scope.h)
|
||||
* are stored in the row but are not part of the hashed bytes nor of the
|
||||
* Python comparison: they are not file content (see
|
||||
* cbm_lsp_surface_identity_decline). Rows written by a different codec
|
||||
* version fail the "v" check on load and route the run to a full rebuild.
|
||||
*/
|
||||
#ifndef CBM_PIPELINE_LSP_SURFACE_H
|
||||
#define CBM_PIPELINE_LSP_SURFACE_H
|
||||
@@ -68,6 +71,27 @@ int cbm_lsp_surface_python_namespace_from_json(CBMArena *arena, const char *json
|
||||
*/
|
||||
int cbm_lsp_surface_python_change(const char *old_json, const char *new_json);
|
||||
|
||||
/* Whether a closure repair keeps every stored declared-type identity valid.
|
||||
* An identity depends on the writing file's own content, which the surface
|
||||
* hash covers, and on which project definitions are types of the label its
|
||||
* language row allows; a repair cannot recompute the second for files it does
|
||||
* not re-extract, so the planner declines when it changes:
|
||||
* - "declared_types_changed": a changed file now has a type definition (a
|
||||
* QN of a type label of its language's row) it did not have;
|
||||
* - "identity_target_changed": a type definition some stored identity names
|
||||
* left a changed or deleted file, or its definition changed (an alias
|
||||
* that became a defined type, another label, other fields or embedded
|
||||
* types): the files resolving through that identity are not the type's
|
||||
* dependents in the graph.
|
||||
* old_rows/new_rows: the stored and the fresh row of each changed file whose
|
||||
* surface changed (new NULL for a deleted file); stored: the whole previous
|
||||
* generation. Returns NULL when the repair keeps them, else the reason. *work
|
||||
* (may be NULL) counts the defs and identity entries examined. */
|
||||
const char *cbm_lsp_surface_identity_decline(const char *const *old_rows,
|
||||
const char *const *new_rows, int changed_count,
|
||||
const cbm_lsp_surface_row_t *stored, int stored_count,
|
||||
uint64_t *work);
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
/* Bracket each file callback, including skipped/error rows. Install only with
|
||||
* no surface build running; clear after the observed build returns. */
|
||||
|
||||
@@ -1560,12 +1560,13 @@ static CBMFileResult *calls_get_or_extract(cbm_pipeline_ctx_t *ctx, int idx,
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
CBMFileResult *r =
|
||||
cbm_pipeline_test_force_extract_null(ctx, fi->language)
|
||||
? NULL
|
||||
: cbm_extract_file_ex_with_tests(
|
||||
src, slen, fi->language, ctx->project_name, fi->rel_path, CBM_EXTRACT_BUDGET,
|
||||
NULL, NULL, ctx->macro_table, ctx->return_type_table, ctx->test_declarations);
|
||||
CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx);
|
||||
CBMFileResult *r = cbm_pipeline_test_force_extract_null(ctx, fi->language)
|
||||
? NULL
|
||||
: cbm_extract_file_ex_with_tests(
|
||||
src, slen, fi->language, ctx->project_name, fi->rel_path,
|
||||
CBM_EXTRACT_BUDGET, NULL, NULL, ctx->macro_table,
|
||||
ctx->return_type_table, ctx->test_declarations, &include_scope);
|
||||
free(src);
|
||||
(void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r);
|
||||
if (r) {
|
||||
|
||||
@@ -1098,15 +1098,16 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
|
||||
|
||||
/* Studio Export XML is transformed to one cacheable aggregate so later
|
||||
* passes see the same calls/usages/semantic carriers as native UDL. */
|
||||
CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx);
|
||||
CBMFileResult *result =
|
||||
cbm_pipeline_test_force_extract_null(ctx, lang) ? NULL
|
||||
: 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_with_tests(source, source_len, lang, ctx->project_name, rel,
|
||||
CBM_EXTRACT_BUDGET, NULL,
|
||||
NULL /* no extra defines or include paths */,
|
||||
ctx->macro_table, NULL, ctx->test_declarations);
|
||||
: cbm_extract_file_ex_with_tests(
|
||||
source, source_len, lang, ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL,
|
||||
NULL /* no extra defines or include paths */, ctx->macro_table, NULL,
|
||||
ctx->test_declarations, &include_scope);
|
||||
free(source);
|
||||
|
||||
if (!cbm_pipeline_test_extraction_ok(ctx, lang, result)) {
|
||||
|
||||
+378
-32
@@ -21,6 +21,7 @@
|
||||
#include "resolve_stats.h"
|
||||
#include "pipeline/pipeline_internal.h"
|
||||
#include "pipeline/lsp_resolve.h"
|
||||
#include "pipeline/type_scope.h"
|
||||
#include "callable_sig.h"
|
||||
#include "lsp/go_lsp.h"
|
||||
#include "lsp/c_lsp.h"
|
||||
@@ -648,6 +649,74 @@ static const char *pxc_qn_leaf(const char *name) {
|
||||
return leaf;
|
||||
}
|
||||
|
||||
static bool pxc_go_ident_byte(unsigned char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' ||
|
||||
c >= 0x80;
|
||||
}
|
||||
|
||||
/* Whether the '|'-joined name list holds exactly `name[0..len)`. */
|
||||
static bool pxc_pipe_list_has(const char *list, const char *name, size_t len) {
|
||||
for (const char *p = list; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t n = bar ? (size_t)(bar - p) : strlen(p);
|
||||
if (n == len && memcmp(p, name, len) == 0) {
|
||||
return true;
|
||||
}
|
||||
p = bar ? bar + 1 : p + n;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* A Go type text with every bare identifier that names one of the
|
||||
* definition's type parameters (`T` in `[]T`, `map[K]V`, `func(T) T`, not the
|
||||
* `T` of `pkg.T`) spelled `any`: the registrars then type it as nothing of the
|
||||
* project instead of the package's own type of that name. The text itself,
|
||||
* unchanged, when it names none. */
|
||||
static const char *pxc_go_mask_type_params(CBMArena *arena, const char *text, const char *params) {
|
||||
if (!text || !text[0] || !params || !params[0]) {
|
||||
return text;
|
||||
}
|
||||
size_t n = strlen(text);
|
||||
char *out = NULL;
|
||||
size_t at = 0;
|
||||
for (size_t i = 0; i < n;) {
|
||||
if (!pxc_go_ident_byte((unsigned char)text[i])) {
|
||||
if (out) {
|
||||
out[at++] = text[i];
|
||||
}
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
size_t start = i; /* a whole identifier, qualified (`pkg.T`) or bare */
|
||||
while (i < n && pxc_go_ident_byte((unsigned char)text[i])) {
|
||||
i++;
|
||||
}
|
||||
bool param = (start == 0 || text[start - 1] != '.') &&
|
||||
pxc_pipe_list_has(params, text + start, i - start);
|
||||
if (param && !out) {
|
||||
/* Worst case: every byte a one-byte parameter, 3 bytes each. */
|
||||
out = (char *)cbm_arena_alloc(arena, n * 3 + 1);
|
||||
if (!out) {
|
||||
return text;
|
||||
}
|
||||
memcpy(out, text, start);
|
||||
at = start;
|
||||
}
|
||||
if (param) {
|
||||
memcpy(out + at, "any", 3);
|
||||
at += 3;
|
||||
} else if (out) {
|
||||
memcpy(out + at, text + start, i - start);
|
||||
at += i - start;
|
||||
}
|
||||
}
|
||||
if (!out) {
|
||||
return text;
|
||||
}
|
||||
out[at] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
@@ -693,6 +762,12 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
|
||||
} else {
|
||||
dst->return_types = src->return_type ? cbm_arena_strdup(arena, src->return_type) : NULL;
|
||||
}
|
||||
const CBMDefTypeFacts *facts = src->type_facts;
|
||||
if (lang == CBM_LANG_GO && !dst->return_types && facts && facts->value_type) {
|
||||
/* A Go package-level value's type: the Go registrars register the
|
||||
* Variable as a value of it (go_lsp.c); the graph never sees it. */
|
||||
dst->return_types = cbm_arena_strdup(arena, facts->value_type);
|
||||
}
|
||||
/* Languages whose cross registrars read embedded_types as QNs get their
|
||||
* bases resolved against the project registry; everyone else keeps the
|
||||
* raw source spelling their own registrar already knows how to handle. */
|
||||
@@ -700,6 +775,14 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
|
||||
(bs && bs->reg && pxc_lang_resolves_base_qns(lang))
|
||||
? pxc_join_base_qns(arena, src->base_classes, bs, module_qn, src->qualified_name)
|
||||
: pxc_join_pipe(arena, src->base_classes);
|
||||
if (lang == CBM_LANG_GO && facts && facts->go_embedded && facts->go_embedded[0]) {
|
||||
/* A Go struct's embedded types, as written; the Go registrar promotes
|
||||
* their members (the embedded-member hook, go_lsp.c). */
|
||||
dst->embedded_types =
|
||||
dst->embedded_types && dst->embedded_types[0]
|
||||
? cbm_arena_sprintf(arena, "%s|%s", dst->embedded_types, facts->go_embedded)
|
||||
: cbm_arena_strdup(arena, facts->go_embedded);
|
||||
}
|
||||
dst->signature_param_types = NULL;
|
||||
dst->signature_param_count = 0;
|
||||
if (src->signature_param_types && src->signature_param_count > 0) {
|
||||
@@ -715,6 +798,15 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
|
||||
dst->signature_param_count = src->signature_param_count;
|
||||
}
|
||||
}
|
||||
if (lang == CBM_LANG_GO && facts && facts->type_params) {
|
||||
/* A type parameter is never the package's type of its name: the
|
||||
* registrars see `any` for it (pxc_go_mask_type_params). */
|
||||
dst->return_types = pxc_go_mask_type_params(arena, dst->return_types, facts->type_params);
|
||||
for (int i = 0; i < dst->signature_param_count; i++) {
|
||||
dst->signature_param_types[i] =
|
||||
pxc_go_mask_type_params(arena, dst->signature_param_types[i], facts->type_params);
|
||||
}
|
||||
}
|
||||
dst->lang = lang;
|
||||
dst->alias_target = (lang == CBM_LANG_GO && src->alias_target)
|
||||
? cbm_arena_strdup(arena, src->alias_target)
|
||||
@@ -949,6 +1041,143 @@ static void pxc_fold_py_field_types(CBMArena *arena, const CBMFileResult *result
|
||||
}
|
||||
}
|
||||
|
||||
/* Go: a generic type's field_defs ("name:type|...") with its type parameters
|
||||
* masked in the type parts (pxc_go_mask_type_params), never in the names. */
|
||||
static const char *pxc_go_mask_field_types(CBMArena *arena, const char *field_defs,
|
||||
const char *params) {
|
||||
if (!field_defs || !field_defs[0]) {
|
||||
return field_defs;
|
||||
}
|
||||
char *copy = cbm_arena_strdup(arena, field_defs);
|
||||
size_t cap = strlen(field_defs) * 3 + 1;
|
||||
char *out = copy ? (char *)cbm_arena_alloc(arena, cap) : NULL;
|
||||
if (!out) {
|
||||
return field_defs;
|
||||
}
|
||||
size_t at = 0;
|
||||
for (char *p = copy; p && *p;) {
|
||||
char *bar = strchr(p, '|');
|
||||
if (bar) {
|
||||
*bar = '\0';
|
||||
}
|
||||
char *colon = strchr(p, ':');
|
||||
const char *type = colon ? pxc_go_mask_type_params(arena, colon + 1, params) : NULL;
|
||||
size_t name_len = colon ? (size_t)(colon - p) + 1 : strlen(p);
|
||||
if (at) {
|
||||
out[at++] = '|';
|
||||
}
|
||||
memcpy(out + at, p, name_len);
|
||||
at += name_len;
|
||||
if (type) {
|
||||
size_t tl = strlen(type);
|
||||
memcpy(out + at, type, tl);
|
||||
at += tl;
|
||||
}
|
||||
p = bar ? bar + 1 : NULL;
|
||||
}
|
||||
out[at] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Python: a class's field_defs with each name its body binds (other than its
|
||||
* nested definitions) added as `name:` -- an attribute of unknown type the
|
||||
* registrar skips (py_split_field_defs keeps typed fields only). The names
|
||||
* decide this file's identities (type_scope.h), so they must be part of its
|
||||
* stored row, which the incremental planner compares. */
|
||||
static const char *pxc_py_add_class_bindings(CBMArena *arena, const char *field_defs,
|
||||
const char *bindings) {
|
||||
size_t total = (field_defs ? strlen(field_defs) : 0) + 2 * strlen(bindings) + 2;
|
||||
char *out = (char *)cbm_arena_alloc(arena, total);
|
||||
CBMHashTable *have = cbm_ht_create(16);
|
||||
if (!out || !have) {
|
||||
cbm_ht_free(have);
|
||||
return field_defs;
|
||||
}
|
||||
size_t at = 0;
|
||||
for (const char *p = field_defs; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t n = bar ? (size_t)(bar - p) : strlen(p);
|
||||
const char *colon = memchr(p, ':', n);
|
||||
const char *name = cbm_arena_strndup(arena, p, colon ? (size_t)(colon - p) : n);
|
||||
if (name) {
|
||||
cbm_ht_set(have, name, (void *)name);
|
||||
}
|
||||
memcpy(out + at, p, n);
|
||||
at += n;
|
||||
out[at++] = '|';
|
||||
p = bar ? bar + 1 : p + n;
|
||||
}
|
||||
for (const char *p = bindings; *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t n = bar ? (size_t)(bar - p) : strlen(p);
|
||||
const char *name = n ? cbm_arena_strndup(arena, p, n) : NULL;
|
||||
if (name && !cbm_ht_get(have, name)) {
|
||||
cbm_ht_set(have, name, (void *)name);
|
||||
memcpy(out + at, p, n);
|
||||
at += n;
|
||||
out[at++] = ':';
|
||||
out[at++] = '|';
|
||||
}
|
||||
p = bar ? bar + 1 : p + n;
|
||||
}
|
||||
cbm_ht_free(have);
|
||||
if (at > 0) {
|
||||
at--; /* the last separator */
|
||||
}
|
||||
out[at] = '\0';
|
||||
return at ? out : field_defs;
|
||||
}
|
||||
|
||||
/* The facts only the cross-file step reads (CBMDefTypeFacts), on the file's
|
||||
* LSP defs after the field folds: a Go generic type's field types name its
|
||||
* type parameters as `any`; a Python class body's bindings and a Python
|
||||
* body's `global` names join its field_defs (as `name:`, no type), so they are
|
||||
* part of the stored row the planner compares. One hash of the file's defs,
|
||||
* built only when one applies. */
|
||||
static void pxc_apply_type_facts(CBMArena *arena, const CBMFileResult *fr, CBMLSPDef *defs,
|
||||
int start, int end, CBMLanguage lang) {
|
||||
if (!fr || (lang != CBM_LANG_GO && lang != CBM_LANG_PYTHON) || start >= end) {
|
||||
return;
|
||||
}
|
||||
CBMHashTable *by_qn = NULL;
|
||||
for (int di = 0; di < fr->defs.count; di++) {
|
||||
const CBMDefinition *d = &fr->defs.items[di];
|
||||
const CBMDefTypeFacts *f = d->type_facts;
|
||||
if (!f || !d->qualified_name || !d->label) {
|
||||
continue;
|
||||
}
|
||||
bool type_like = cbm_label_is_type_like(d->label);
|
||||
bool go_generic = lang == CBM_LANG_GO && type_like && f->type_params;
|
||||
bool py_bound = lang == CBM_LANG_PYTHON && type_like && f->class_bindings;
|
||||
bool py_global = lang == CBM_LANG_PYTHON && f->global_names;
|
||||
if (!go_generic && !py_bound && !py_global) {
|
||||
continue;
|
||||
}
|
||||
if (!by_qn) {
|
||||
by_qn = cbm_ht_create((uint32_t)(end - start + 1));
|
||||
for (int si = start; by_qn && si < end; si++) {
|
||||
if (defs[si].qualified_name && !cbm_ht_get(by_qn, defs[si].qualified_name)) {
|
||||
cbm_ht_set(by_qn, defs[si].qualified_name, &defs[si]);
|
||||
}
|
||||
}
|
||||
}
|
||||
CBMLSPDef *dst = by_qn ? (CBMLSPDef *)cbm_ht_get(by_qn, d->qualified_name) : NULL;
|
||||
if (!dst) {
|
||||
continue;
|
||||
}
|
||||
if (go_generic) {
|
||||
dst->field_defs = pxc_go_mask_field_types(arena, dst->field_defs, f->type_params);
|
||||
}
|
||||
if (py_bound) {
|
||||
dst->field_defs = pxc_py_add_class_bindings(arena, dst->field_defs, f->class_bindings);
|
||||
}
|
||||
if (py_global) {
|
||||
dst->field_defs = pxc_py_add_class_bindings(arena, dst->field_defs, f->global_names);
|
||||
}
|
||||
}
|
||||
cbm_ht_free(by_qn);
|
||||
}
|
||||
|
||||
/* 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
|
||||
@@ -1290,15 +1519,21 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
|
||||
.project_name = project_name,
|
||||
.rel = files[fi].rel_path,
|
||||
.lang = files[fi].language};
|
||||
if (ctx && ctx->registry && pxc_lang_resolves_base_qns(files[fi].language)) {
|
||||
bs.reg = ctx->registry;
|
||||
bs.gbuf = ctx->gbuf;
|
||||
/* The declared-type scope step (type_scope.h) reads the same map. */
|
||||
const cbm_type_scope_lang_t *scope_lang =
|
||||
ctx && ctx->registry ? cbm_type_scope_lang(files[fi].language) : NULL;
|
||||
bool resolve_bases = ctx && ctx->registry && pxc_lang_resolves_base_qns(files[fi].language);
|
||||
if (resolve_bases || scope_lang) {
|
||||
/* Bases and field annotations resolve through annotation-only
|
||||
* imports too: `if TYPE_CHECKING:` exists for them (#1277). */
|
||||
cbm_pxc_build_import_map_ex(ctx->gbuf, project_name, files[fi].rel_path,
|
||||
files[fi].language, fr, true, &bs.imp_keys, &bs.imp_vals,
|
||||
&bs.imp_count);
|
||||
}
|
||||
if (resolve_bases) {
|
||||
bs.reg = ctx->registry;
|
||||
bs.gbuf = ctx->gbuf;
|
||||
}
|
||||
for (int di = 0; di < fr->defs.count; di++) {
|
||||
if (pxc_build_lsp_def(arena, &fr->defs.items[di], def_modules[fi], namespace_name,
|
||||
files[fi].language, &defs[idx], bs.reg ? &bs : NULL) == 0) {
|
||||
@@ -1315,7 +1550,6 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
|
||||
idx += pxc_build_py_namespace_records(arena, fr, def_modules[fi], &defs[idx]);
|
||||
}
|
||||
}
|
||||
cbm_pxc_free_import_map(bs.imp_keys, bs.imp_vals, bs.imp_count); /* NULL-safe */
|
||||
if (files[fi].language == CBM_LANG_GO) {
|
||||
pxc_fold_struct_fields(arena, fr, defs, file_start, idx, "Struct");
|
||||
} else if (files[fi].language == CBM_LANG_C || files[fi].language == CBM_LANG_CPP) {
|
||||
@@ -1323,6 +1557,8 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
|
||||
* the structs its `.c` files access. */
|
||||
pxc_fold_struct_fields(arena, fr, defs, file_start, idx, "Class");
|
||||
}
|
||||
/* Go generic types and Python class bodies (CBMDefTypeFacts). */
|
||||
pxc_apply_type_facts(arena, fr, defs, file_start, idx, files[fi].language);
|
||||
if (files[fi].language == CBM_LANG_RUST) {
|
||||
for (int ii = 0; ii < fr->impl_traits.count; ii++) {
|
||||
if (pxc_build_rust_impl_relation(arena, &fr->impl_traits.items[ii], project_name,
|
||||
@@ -1332,6 +1568,29 @@ CBMLSPDef *cbm_pxc_collect_all_defs(const cbm_pipeline_ctx_t *ctx, CBMArena *are
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Every declared type this file wrote, resolved once in this file's
|
||||
* scope; the identities travel with the defs (and their surface). */
|
||||
if (scope_lang) {
|
||||
cbm_type_scope_t scope = {.reg = ctx->registry,
|
||||
.module_qn = def_modules[fi],
|
||||
.imp_keys = bs.imp_keys,
|
||||
.imp_vals = bs.imp_vals,
|
||||
.imp_count = bs.imp_count};
|
||||
if (scope_lang->lexical_scopes) {
|
||||
/* The file's own scopes: its definitions and the module's
|
||||
* ordered namespace facts. */
|
||||
scope.file_defs = fr->defs.items;
|
||||
scope.file_def_count = fr->defs.count;
|
||||
scope.module_facts = &fr->py_namespace;
|
||||
scope.graph = ctx->gbuf; /* the graph the import map read */
|
||||
}
|
||||
cbm_type_scope_file_t *ts_file = cbm_type_scope_file_begin(scope_lang, &scope);
|
||||
for (int di = file_start; ts_file && di < idx; di++) {
|
||||
cbm_type_scope_attach(ts_file, arena, &defs[di]);
|
||||
}
|
||||
cbm_type_scope_file_end(ts_file);
|
||||
}
|
||||
cbm_pxc_free_import_map(bs.imp_keys, bs.imp_vals, bs.imp_count); /* NULL-safe */
|
||||
if (fr_loaded) {
|
||||
cbm_free_result(fr);
|
||||
}
|
||||
@@ -3059,53 +3318,140 @@ static const pxc_module_entry_t *pxc_py_spec_entry(const CBMModuleDefIndex *idx,
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The index entry of the module that declares the definition `qn`: its
|
||||
* nearest proper module prefix (a Python package through its __init__), or
|
||||
* NULL. */
|
||||
static const pxc_module_entry_t *pxc_module_of_qn(const CBMModuleDefIndex *idx, const char *qn,
|
||||
size_t len, CBMLanguage lang) {
|
||||
char key[CBM_SZ_1K];
|
||||
if (len + sizeof(".__init__") > sizeof(key)) {
|
||||
return NULL;
|
||||
}
|
||||
memcpy(key, qn, len);
|
||||
key[len] = '\0';
|
||||
for (;;) {
|
||||
char *dot = strrchr(key, '.');
|
||||
if (!dot) {
|
||||
return NULL;
|
||||
}
|
||||
*dot = '\0';
|
||||
const pxc_module_entry_t *e = (const pxc_module_entry_t *)cbm_ht_get(idx->ht, key);
|
||||
if (!e && lang == CBM_LANG_PYTHON) {
|
||||
e = pxc_py_module_entry(idx, key, strlen(key));
|
||||
}
|
||||
if (e) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* A def the selection reaches through: a Python namespace record, or a def
|
||||
* whose declared types carry identities (type_scope.h). */
|
||||
static bool pxc_def_reaches(const CBMLSPDef *d) {
|
||||
return pxc_is_py_reexport_record(d) || d->type_scope;
|
||||
}
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
static _Atomic uint64_t g_pxc_reach_work;
|
||||
uint64_t cbm_pxc_test_reach_work(void) {
|
||||
return atomic_load_explicit(&g_pxc_reach_work, memory_order_relaxed);
|
||||
}
|
||||
#define PXC_REACH_WORK(n) \
|
||||
atomic_fetch_add_explicit(&g_pxc_reach_work, (uint64_t)(n), memory_order_relaxed)
|
||||
#else
|
||||
#define PXC_REACH_WORK(n) ((void)0)
|
||||
#endif
|
||||
|
||||
/* Select every def of module entry `e` the caller can use and queue the ones
|
||||
* that reach further (each def is queued at most once). Module entries
|
||||
* partition the defs (one def_module_qn each), so an entry is known by its
|
||||
* first def: each entry is walked once, however many defs point at it. */
|
||||
static void pxc_mark_reached_entry(const pxc_module_entry_t *e, bool *selected,
|
||||
const CBMLSPDef *all_defs, CBMLanguage caller_lang, bool *queued,
|
||||
bool *entry_done, int *work, int *n, int *total) {
|
||||
if (!e || e->count <= 0 || entry_done[e->indices[0]]) {
|
||||
return;
|
||||
}
|
||||
entry_done[e->indices[0]] = true;
|
||||
PXC_REACH_WORK(e->count);
|
||||
for (int j = 0; j < e->count; j++) {
|
||||
int di = e->indices[j];
|
||||
const CBMLSPDef *d = &all_defs[di];
|
||||
if (!pxc_def_lang_matches(caller_lang, d->lang) ||
|
||||
(caller_lang == CBM_LANG_PYTHON && d->lang != CBM_LANG_PYTHON)) {
|
||||
continue;
|
||||
}
|
||||
if (!selected[di]) {
|
||||
selected[di] = true;
|
||||
(*total)++;
|
||||
}
|
||||
if (!queued[di] && pxc_def_reaches(d)) {
|
||||
queued[di] = true;
|
||||
work[(*n)++] = di;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* A per-file selection holds the defs of the caller's own and imported
|
||||
* modules. A Python package that re-exports a name keeps only the record;
|
||||
* the definition lives in the module the record points at, possibly through
|
||||
* further re-exports. Select those modules' defs too, following every
|
||||
* selected record once (a worklist over def indices: linear in the defs it
|
||||
* reaches), so the per-file LSP can fold the chain as the shared registry
|
||||
* does. */
|
||||
static void pxc_mark_reexport_targets(const CBMModuleDefIndex *idx, bool *selected,
|
||||
const CBMLSPDef *all_defs, int *total) {
|
||||
* modules. Two kinds of selected def point further:
|
||||
* - A Python package that re-exports a name keeps only the record; the
|
||||
* definition lives in the module the record points at, possibly through
|
||||
* further re-exports.
|
||||
* - A def's declared-type identity names a type in a module the caller
|
||||
* neither owns nor imports (the return type the callee's file imported).
|
||||
* Select those modules' defs too, following every reaching def once and
|
||||
* walking every module entry once (a worklist over def indices: linear in the
|
||||
* defs it reaches and the identities they hold), so the per-file LSP sees what
|
||||
* the shared registry holds for a full index. */
|
||||
static void pxc_mark_reached_targets(const CBMModuleDefIndex *idx, bool *selected,
|
||||
const CBMLSPDef *all_defs, CBMLanguage caller_lang,
|
||||
int *total) {
|
||||
int cap = idx->def_count;
|
||||
int *work = (int *)cbm_alloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(int));
|
||||
bool *queued = (bool *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(bool));
|
||||
if (!work || !queued) {
|
||||
bool *entry_done = (bool *)cbm_calloc(CBM_MEM_CLASS_EXTRACT, (size_t)cap * sizeof(bool));
|
||||
if (!work || !queued || !entry_done) {
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, work);
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, queued);
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, entry_done);
|
||||
return;
|
||||
}
|
||||
int n = 0;
|
||||
for (int i = 0; i < cap; i++) {
|
||||
if (selected[i] && pxc_is_py_reexport_record(&all_defs[i])) {
|
||||
if (selected[i] && pxc_def_reaches(&all_defs[i])) {
|
||||
queued[i] = true;
|
||||
work[n++] = i;
|
||||
}
|
||||
}
|
||||
for (int w = 0; w < n; w++) {
|
||||
const CBMLSPDef *r = &all_defs[work[w]];
|
||||
bool star = strcmp(r->label, "PyStarImport") == 0;
|
||||
const pxc_module_entry_t *e =
|
||||
r->def_module_qn ? pxc_py_spec_entry(idx, r->def_module_qn, r->receiver_type,
|
||||
star ? NULL : r->method_names_str)
|
||||
: NULL;
|
||||
for (int j = 0; e && j < e->count; j++) {
|
||||
int di = e->indices[j];
|
||||
if (di < 0 || di >= cap || all_defs[di].lang != CBM_LANG_PYTHON)
|
||||
continue;
|
||||
if (!selected[di]) {
|
||||
selected[di] = true;
|
||||
(*total)++;
|
||||
}
|
||||
if (!queued[di] && pxc_is_py_reexport_record(&all_defs[di])) {
|
||||
queued[di] = true;
|
||||
work[n++] = di;
|
||||
/* The modules this def points at: one for a record, one per identity. */
|
||||
if (caller_lang == CBM_LANG_PYTHON && pxc_is_py_reexport_record(r)) {
|
||||
bool star = strcmp(r->label, "PyStarImport") == 0;
|
||||
const pxc_module_entry_t *e =
|
||||
r->def_module_qn ? pxc_py_spec_entry(idx, r->def_module_qn, r->receiver_type,
|
||||
star ? NULL : r->method_names_str)
|
||||
: NULL;
|
||||
pxc_mark_reached_entry(e, selected, all_defs, caller_lang, queued, entry_done, work, &n,
|
||||
total);
|
||||
}
|
||||
for (const char *p = r->type_scope; p && *p;) {
|
||||
const char *eq = strchr(p, '=');
|
||||
if (!eq) {
|
||||
break;
|
||||
}
|
||||
const char *bar = strchr(eq, '|');
|
||||
size_t qn_len = bar ? (size_t)(bar - eq - 1) : strlen(eq + 1);
|
||||
PXC_REACH_WORK(1);
|
||||
const pxc_module_entry_t *e = pxc_module_of_qn(idx, eq + 1, qn_len, caller_lang);
|
||||
pxc_mark_reached_entry(e, selected, all_defs, caller_lang, queued, entry_done, work, &n,
|
||||
total);
|
||||
p = bar ? bar + 1 : eq + 1 + qn_len;
|
||||
}
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, work);
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, queued);
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, entry_done);
|
||||
}
|
||||
|
||||
CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef *all_defs,
|
||||
@@ -3140,8 +3486,8 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
|
||||
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 (caller_lang == CBM_LANG_PYTHON) {
|
||||
pxc_mark_reexport_targets(idx, selected, all_defs, &total);
|
||||
if (caller_lang == CBM_LANG_PYTHON || cbm_type_scope_lang(caller_lang)) {
|
||||
pxc_mark_reached_targets(idx, selected, all_defs, caller_lang, &total);
|
||||
}
|
||||
|
||||
if (total == 0) {
|
||||
|
||||
@@ -134,6 +134,12 @@ CBMLSPDef *cbm_pxc_filter_defs_for_file(const CBMModuleDefIndex *idx, CBMLSPDef
|
||||
const char *own_module, const char *const *imp_qns,
|
||||
int imp_count, int *out_count, bool *out_success);
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
/* Work counter for the growth tests: module-entry defs walked and identities
|
||||
* followed by the per-file selection's worklist. Test builds only. */
|
||||
uint64_t cbm_pxc_test_reach_work(void);
|
||||
#endif
|
||||
|
||||
/* ── Tier 2 full: pre-built per-language cross-LSP registries ─────
|
||||
*
|
||||
* Each non-NULL registry is built ONCE in pipeline.c (in a dedicated
|
||||
|
||||
@@ -1361,6 +1361,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
|
||||
/* 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. */
|
||||
CBMIncludeScope include_scope = cbm_pipeline_include_scope(ec->pctx);
|
||||
CBMFileResult *result =
|
||||
cbm_pipeline_test_force_extract_null(ec->pctx, fi->language) ? NULL
|
||||
: fi->language == CBM_LANG_OBJECTSCRIPT_EXPORT
|
||||
@@ -1370,7 +1371,7 @@ static void extract_worker(int worker_id, void *ctx_ptr) {
|
||||
: cbm_extract_file_ex_with_tests(source, source_len, fi->language, ec->project_name,
|
||||
fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL,
|
||||
ec->macro_table, ec->return_type_table,
|
||||
ec->pctx->test_declarations);
|
||||
ec->pctx->test_declarations, &include_scope);
|
||||
|
||||
uint64_t file_elapsed_ms = (extract_now_ns() - file_t0) / PP_USEC_PER_MS;
|
||||
|
||||
|
||||
@@ -154,9 +154,17 @@ static int build_import_map(cbm_pipeline_ctx_t *ctx, const char *rel_path,
|
||||
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++;
|
||||
/* free_import_map releases every key through the memory core,
|
||||
* so this key comes from it too, like the fast path's. */
|
||||
size_t len = (size_t)(end - start);
|
||||
char *key = cbm_alloc(CBM_MEM_CLASS_SEMANTIC, len + SKIP_ONE);
|
||||
if (key) {
|
||||
memcpy(key, start, len);
|
||||
key[len] = '\0';
|
||||
keys[count] = key;
|
||||
vals[count] = target->qualified_name;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -694,12 +702,13 @@ static CBMFileResult *sem_get_or_extract(cbm_pipeline_ctx_t *ctx, int file_idx,
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx);
|
||||
CBMFileResult *r =
|
||||
cbm_pipeline_test_force_extract_null(ctx, fi->language)
|
||||
? NULL
|
||||
: cbm_extract_file_ex_with_tests(source, source_len, fi->language, ctx->project_name,
|
||||
fi->rel_path, CBM_EXTRACT_BUDGET, NULL, NULL, NULL,
|
||||
NULL, ctx->test_declarations);
|
||||
NULL, ctx->test_declarations, &include_scope);
|
||||
cbm_free(CBM_MEM_CLASS_SEMANTIC, source);
|
||||
(void)cbm_pipeline_test_extraction_ok(ctx, fi->language, r);
|
||||
if (r) {
|
||||
|
||||
@@ -477,11 +477,13 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
|
||||
errors++;
|
||||
continue;
|
||||
}
|
||||
CBMIncludeScope include_scope = cbm_pipeline_include_scope(ctx);
|
||||
result = cbm_pipeline_test_force_extract_null(ctx, files[i].language)
|
||||
? NULL
|
||||
: cbm_extract_file_ex_with_tests(
|
||||
source, source_len, files[i].language, ctx->project_name, rel,
|
||||
CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations);
|
||||
CBM_EXTRACT_BUDGET, NULL, NULL, NULL, NULL, ctx->test_declarations,
|
||||
&include_scope);
|
||||
free(source);
|
||||
if (!cbm_pipeline_test_extraction_ok(ctx, files[i].language, result)) {
|
||||
cbm_free_result(result);
|
||||
|
||||
@@ -1007,6 +1007,27 @@ bool cbm_pipeline_set_project_name(cbm_pipeline_t *p, const char *name) {
|
||||
return true;
|
||||
}
|
||||
|
||||
CBMHashTable *cbm_pipeline_indexed_files_new(const cbm_file_info_t *files, int file_count) {
|
||||
CBMHashTable *set = cbm_ht_create((uint32_t)((size_t)file_count * PAIR_LEN + CBM_SZ_64));
|
||||
for (int i = 0; set && i < file_count; i++) {
|
||||
cbm_ht_set(set, files[i].rel_path, (void *)&files[i]);
|
||||
}
|
||||
return set;
|
||||
}
|
||||
|
||||
static bool pipeline_file_is_indexed(const void *userdata, const char *rel_path) {
|
||||
return userdata && cbm_ht_get((const CBMHashTable *)userdata, rel_path) != NULL;
|
||||
}
|
||||
|
||||
CBMIncludeScope cbm_pipeline_include_scope(const cbm_pipeline_ctx_t *ctx) {
|
||||
CBMIncludeScope scope = {
|
||||
.root = ctx ? ctx->repo_path : NULL,
|
||||
.is_indexed = pipeline_file_is_indexed,
|
||||
.userdata = ctx ? ctx->indexed_files : NULL,
|
||||
};
|
||||
return scope;
|
||||
}
|
||||
|
||||
void cbm_pipeline_set_lsp_surfaces(cbm_pipeline_t *p, cbm_lsp_surface_row_t *rows, int count) {
|
||||
if (!p) {
|
||||
cbm_store_free_lsp_surfaces(rows, count);
|
||||
@@ -2609,6 +2630,14 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
|
||||
census_len(def->http_base_url) + census_list(def->extra_props) +
|
||||
census_len(def->decl_namespace) + census_len(def->variant_key) +
|
||||
census_len(def->alias_target);
|
||||
if (def->type_facts) {
|
||||
str_def_misc += sizeof(*def->type_facts) +
|
||||
census_len(def->type_facts->type_params) +
|
||||
census_len(def->type_facts->value_type) +
|
||||
census_len(def->type_facts->go_embedded) +
|
||||
census_len(def->type_facts->class_bindings) +
|
||||
census_len(def->type_facts->global_names);
|
||||
}
|
||||
}
|
||||
for (int c = 0; c < r->calls.count; c++) {
|
||||
const CBMCall *call = &r->calls.items[c];
|
||||
@@ -4386,6 +4415,7 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
|
||||
struct timespec t0;
|
||||
cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
|
||||
cbm_path_alias_collection_t *path_aliases = NULL;
|
||||
CBMHashTable *indexed_files = NULL;
|
||||
cbm_file_hash_t *baseline_manifest = NULL;
|
||||
int baseline_count = 0;
|
||||
char **requested_excluded_dirs = NULL;
|
||||
@@ -4551,11 +4581,17 @@ static int cbm_pipeline_run_staged(cbm_pipeline_t *p) {
|
||||
* when no usable configs are found — non-TS projects pay nothing. */
|
||||
path_aliases =
|
||||
cbm_load_path_aliases_excluded(p->repo_path, p->excluded_dirs, p->excluded_count);
|
||||
indexed_files = cbm_pipeline_indexed_files_new(files, file_count);
|
||||
if (!indexed_files) {
|
||||
rc = CBM_NOT_FOUND;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Build shared context for pass functions */
|
||||
cbm_pipeline_ctx_t ctx = {
|
||||
.project_name = p->project_name,
|
||||
.repo_path = p->repo_path,
|
||||
.indexed_files = indexed_files,
|
||||
.gbuf = p->gbuf,
|
||||
.registry = p->registry,
|
||||
.cancelled = p->cancelled,
|
||||
@@ -4601,6 +4637,7 @@ cleanup:
|
||||
cbm_registry_free(p->registry);
|
||||
p->registry = NULL;
|
||||
cbm_path_alias_collection_free(path_aliases);
|
||||
cbm_ht_free(indexed_files); /* keys borrowed from files */
|
||||
if (restore_requested_discovery) {
|
||||
cbm_discover_free_excluded(p->excluded_dirs, p->excluded_count);
|
||||
cbm_discover_free_ignored(p->ignored_files, p->ignored_count);
|
||||
|
||||
@@ -71,10 +71,33 @@ cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void) {
|
||||
return (cbm_incremental_route_t)atomic_load(&g_incr_test_last_route);
|
||||
}
|
||||
|
||||
/* The last closure plan's counters (an accepted plan) or decline reason. */
|
||||
static atomic_int g_incr_test_plan_files = -1;
|
||||
static atomic_int g_incr_test_plan_surface_changed = -1;
|
||||
static atomic_int g_incr_test_plan_dependents = -1;
|
||||
static _Atomic(const char *) g_incr_test_plan_decline = NULL;
|
||||
|
||||
cbm_incremental_closure_plan_t cbm_pipeline_incremental_test_last_closure_plan(void) {
|
||||
return (cbm_incremental_closure_plan_t){.files = atomic_load(&g_incr_test_plan_files),
|
||||
.surface_changed =
|
||||
atomic_load(&g_incr_test_plan_surface_changed),
|
||||
.dependents = atomic_load(&g_incr_test_plan_dependents),
|
||||
.decline = atomic_load(&g_incr_test_plan_decline)};
|
||||
}
|
||||
|
||||
static void incr_test_note_plan(int files, int surface_changed, int dependents,
|
||||
const char *decline) {
|
||||
atomic_store(&g_incr_test_plan_files, files);
|
||||
atomic_store(&g_incr_test_plan_surface_changed, surface_changed);
|
||||
atomic_store(&g_incr_test_plan_dependents, dependents);
|
||||
atomic_store(&g_incr_test_plan_decline, decline);
|
||||
}
|
||||
|
||||
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);
|
||||
incr_test_note_plan(-1, -1, -1, NULL);
|
||||
cbm_pipeline_persist_test_reset_faults();
|
||||
}
|
||||
|
||||
@@ -1470,7 +1493,11 @@ static void free_incremental_result_cache(CBMFileResult **cache, int count) {
|
||||
* recomputed; a surface change pulls in exactly the files with edges into
|
||||
* it. Per-file extraction is a pure function of file content, so an
|
||||
* unchanged dependent can never be surface-changed in turn — the closure is
|
||||
* structurally depth-1 and needs no fixpoint. Every uncertain case declines
|
||||
* structurally depth-1 and needs no fixpoint. The one part of a stored row
|
||||
* that is not file content, its declared-type identities (type_scope.h), is
|
||||
* kept out of the hash and stays valid because the plan declines whenever the
|
||||
* type definitions they depend on change (cbm_lsp_surface_identity_decline).
|
||||
* Every uncertain case declines
|
||||
* to a FULL rebuild: new files, added definition names (yesterday's graph
|
||||
* cannot know tomorrow's referencers), virtual/config manifest entries,
|
||||
* missing or unreadable surface rows, dependents outside discovery, or a
|
||||
@@ -2361,6 +2388,7 @@ static void *rehydrate_worker(void *arg) {
|
||||
* correctness stays trivially reasoned. Returns heap rows via out. */
|
||||
static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project,
|
||||
cbm_file_info_t *probe_files, int probe_count,
|
||||
const CBMHashTable *indexed_files,
|
||||
cbm_lsp_surface_row_t **out_rows, int *out_count) {
|
||||
*out_rows = NULL;
|
||||
*out_count = 0;
|
||||
@@ -2376,6 +2404,7 @@ static int closure_probe_surfaces(cbm_pipeline_t *p, const char *project,
|
||||
cbm_pipeline_ctx_t probe_ctx = {
|
||||
.project_name = project,
|
||||
.repo_path = cbm_pipeline_repo_path(p),
|
||||
.indexed_files = indexed_files,
|
||||
.gbuf = probe_gbuf,
|
||||
.registry = NULL,
|
||||
.cancelled = cbm_pipeline_cancelled_ptr(p),
|
||||
@@ -3019,6 +3048,85 @@ static bool closure_metadata_current(bool metadata_current, const cbm_file_hash_
|
||||
return current && old_count == new_count;
|
||||
}
|
||||
|
||||
/* Does `list` (one repository path per line, as lsp_surface.included_files
|
||||
* stores it) name a file of `delta`? Every listed file must have been tracked
|
||||
* by the previous generation: a file it did not hash cannot be proven
|
||||
* unchanged, which *untracked reports. */
|
||||
static bool closure_list_names_delta(const char *list, const CBMHashTable *delta,
|
||||
const CBMHashTable *stored_by_path, bool *untracked) {
|
||||
bool hit = false;
|
||||
char name[CBM_SZ_4K];
|
||||
for (const char *at = list; at && *at;) {
|
||||
const char *end = strchr(at, '\n');
|
||||
size_t n = end ? (size_t)(end - at) : strlen(at);
|
||||
if (n > 0) {
|
||||
if (n >= sizeof(name)) {
|
||||
*untracked = true;
|
||||
return hit;
|
||||
}
|
||||
memcpy(name, at, n);
|
||||
name[n] = '\0';
|
||||
if (!cbm_ht_get(stored_by_path, name)) {
|
||||
*untracked = true;
|
||||
}
|
||||
if (cbm_ht_get(delta, name)) {
|
||||
hit = true;
|
||||
}
|
||||
}
|
||||
at = end ? end + 1 : at + n;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
/* The includers of a changed or deleted file (#2993). A C-family file's
|
||||
* preprocessed pass reads the repository files its #include lines name, so
|
||||
* its graph changes with their bytes even when its own bytes do not. Every
|
||||
* stored surface row lists the files its file's lookup read, transitively
|
||||
* (the headers a header includes are on the includer's own list), so one pass
|
||||
* over the rows finds every includer. Each joins the delta as a changed file
|
||||
* and goes through the same surface comparison as the others. `paths` holds
|
||||
* the changed files, then the deleted ones; the includers are inserted after
|
||||
* the changed files. Linear in the total length of the lists. Returns a
|
||||
* decline reason, or NULL. */
|
||||
static const char *closure_add_includers(const cbm_lsp_surface_row_t *rows, int row_count,
|
||||
const CBMHashTable *stored_by_path,
|
||||
const CBMHashTable *files_by_path, char **paths,
|
||||
int *n_changed, int n_deleted) {
|
||||
int changed = *n_changed;
|
||||
CBMHashTable *delta =
|
||||
cbm_ht_create((uint32_t)((size_t)(changed + n_deleted) * PAIR_LEN + CBM_SZ_64));
|
||||
char **found = (char **)cbm_alloc(CBM_MEM_CLASS_OTHER,
|
||||
(size_t)(row_count > 0 ? row_count : 1) * sizeof(char *));
|
||||
const char *why = !delta || !found ? "alloc" : NULL;
|
||||
for (int i = 0; !why && i < changed + n_deleted; i++) {
|
||||
cbm_ht_set(delta, paths[i], paths[i]);
|
||||
}
|
||||
int found_count = 0;
|
||||
for (int i = 0; !why && i < row_count; i++) {
|
||||
bool untracked = false;
|
||||
bool hit =
|
||||
closure_list_names_delta(rows[i].included_files, delta, stored_by_path, &untracked);
|
||||
if (untracked) {
|
||||
why = "include_untracked";
|
||||
} else if (hit && !cbm_ht_get(delta, rows[i].rel_path)) {
|
||||
if (!cbm_ht_get(files_by_path, rows[i].rel_path)) {
|
||||
why = "includer_not_discovered";
|
||||
} else {
|
||||
found[found_count++] = (char *)rows[i].rel_path;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!why && found_count > 0) {
|
||||
memmove(paths + changed + found_count, paths + changed, (size_t)n_deleted * sizeof(char *));
|
||||
memcpy(paths + changed, found, (size_t)found_count * sizeof(char *));
|
||||
*n_changed = changed + found_count;
|
||||
cbm_log_info("incremental.closure_includers", "includers", itoa_buf(found_count));
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_OTHER, found);
|
||||
cbm_ht_free(delta); /* keys borrowed */
|
||||
return why;
|
||||
}
|
||||
|
||||
/* Decide whether this manifest delta is closure-repairable, and if so build
|
||||
* the plan. Returns 1 with *plan filled, or 0 (decline → FULL) with the
|
||||
* reason logged. Every early exit declines; nothing here mutates state. */
|
||||
@@ -3202,6 +3310,12 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
for (int i = 0; i < plan->stored_count; i++) {
|
||||
cbm_ht_set(rows_by_path, plan->stored_rows[i].rel_path, &plan->stored_rows[i]);
|
||||
}
|
||||
decline = closure_add_includers(plan->stored_rows, plan->stored_count, stored_by_path,
|
||||
files_by_path, changed_paths, &n_changed, n_deleted);
|
||||
if (decline) {
|
||||
cbm_ht_free(rows_by_path);
|
||||
goto done;
|
||||
}
|
||||
|
||||
probe_files =
|
||||
(cbm_file_info_t *)calloc((size_t)(n_changed ? n_changed : 1), sizeof(cbm_file_info_t));
|
||||
@@ -3220,7 +3334,7 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
probe_files[i] = *info;
|
||||
}
|
||||
int probe_rc = n_changed > 0 ? closure_probe_surfaces(p, project, probe_files, n_changed,
|
||||
&probe_rows, &probe_count)
|
||||
files_by_path, &probe_rows, &probe_count)
|
||||
: 0;
|
||||
if (probe_rc != 0) {
|
||||
cbm_ht_free(rows_by_path);
|
||||
@@ -3235,9 +3349,13 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
* query. Python changes require a full rebuild; other surface changes and
|
||||
* deletions seed the dependent query. */
|
||||
int n_surface_changed = 0;
|
||||
/* dep_targets, then the body-edited files (body_targets) in the same block */
|
||||
const char **dep_targets =
|
||||
(const char **)calloc((size_t)(n_changed + n_deleted + n_changed), sizeof(char *));
|
||||
/* dep_targets, then the body-edited files (body_targets), then the stored
|
||||
* and fresh rows of every surface-changed or deleted file for the
|
||||
* declared-type identity gate (identity_old / identity_new; fresh NULL
|
||||
* for a deleted file), in the same block */
|
||||
int identity_cap = n_changed + n_deleted + 1;
|
||||
const char **dep_targets = (const char **)calloc(
|
||||
(size_t)(n_changed + n_deleted + n_changed + 2 * identity_cap), sizeof(char *));
|
||||
if (!dep_targets) {
|
||||
cbm_ht_free(rows_by_path);
|
||||
decline = "alloc";
|
||||
@@ -3245,6 +3363,9 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
}
|
||||
body_targets = dep_targets + n_changed + n_deleted;
|
||||
int dep_target_count = 0;
|
||||
const char **identity_old = body_targets + n_changed;
|
||||
const char **identity_new = identity_old + identity_cap;
|
||||
int identity_count = 0;
|
||||
/* The first file that declines the closure stops both loops; the one exit
|
||||
* below releases dep_targets and the row index for every reason. */
|
||||
const char *why = NULL;
|
||||
@@ -3281,6 +3402,8 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
} else {
|
||||
n_surface_changed++;
|
||||
dep_targets[dep_target_count++] = changed_paths[i];
|
||||
identity_old[identity_count] = stored_row->defs_json;
|
||||
identity_new[identity_count++] = fresh_row->defs_json;
|
||||
}
|
||||
}
|
||||
bool gone_scope_changed = false; /* a deleted file takes its declarations along */
|
||||
@@ -3294,8 +3417,19 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
if (gone && !doc_scope_repairable(gone->defs_json, NULL, removed_names)) {
|
||||
gone_scope_changed = true;
|
||||
}
|
||||
if (gone) {
|
||||
identity_old[identity_count] = gone->defs_json;
|
||||
identity_new[identity_count++] = NULL;
|
||||
}
|
||||
}
|
||||
cbm_ht_free(rows_by_path);
|
||||
/* Declared-type identities (type_scope.h) are not file content: a repair
|
||||
* keeps them only while the project's type definitions they depend on
|
||||
* stay as they were. */
|
||||
if (!why && identity_count > 0) {
|
||||
why = cbm_lsp_surface_identity_decline(identity_old, identity_new, identity_count,
|
||||
plan->stored_rows, plan->stored_count, NULL);
|
||||
}
|
||||
|
||||
/* A body edit keeps a file's names but moves its lines: a document that
|
||||
* bound a reference by lines (`file#L3-L9`, :lines:) would keep a stale
|
||||
@@ -3308,7 +3442,7 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
(body_target_count > 0 &&
|
||||
cbm_store_get_dependent_files(store, project, body_targets, body_target_count,
|
||||
&line_docs, &line_doc_count) != CBM_STORE_OK));
|
||||
free(dep_targets); /* body_targets with it */
|
||||
free(dep_targets); /* body_targets and the identity rows with it */
|
||||
body_targets = NULL;
|
||||
if (why) {
|
||||
decline = why;
|
||||
@@ -3403,6 +3537,9 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
|
||||
cbm_log_info("incremental.closure_plan_done", "closure", itoa_buf(plan->count),
|
||||
"doc_link_dependents", itoa_buf(n_row_dependents), "elapsed_ms",
|
||||
itoa_buf((int)elapsed_ms(t)));
|
||||
#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
|
||||
incr_test_note_plan(plan->count, n_surface_changed, dependent_count, NULL);
|
||||
#endif
|
||||
|
||||
done:
|
||||
cbm_path_alias_collection_free(plan_aliases);
|
||||
@@ -3420,6 +3557,9 @@ done:
|
||||
if (decline) {
|
||||
cbm_log_info("incremental.closure_decline", "reason", decline, "elapsed_ms",
|
||||
itoa_buf((int)elapsed_ms(t)));
|
||||
#if defined(CBM_INCREMENTAL_TEST_API) && CBM_INCREMENTAL_TEST_API
|
||||
incr_test_note_plan(-1, -1, -1, decline);
|
||||
#endif
|
||||
cbm_store_free_lsp_surfaces(plan->stored_rows, plan->stored_count);
|
||||
int fatal_rc = plan->fatal_rc;
|
||||
cbm_store_free_doc_links(plan->doc_rows, plan->doc_row_count);
|
||||
@@ -3566,6 +3706,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
|
||||
cbm_gbuf_t *gbuf = NULL;
|
||||
cbm_registry_t *registry = NULL;
|
||||
cbm_path_alias_collection_t *path_aliases = NULL;
|
||||
CBMHashTable *indexed_files = NULL;
|
||||
CBMHashTable *stale_surface_set = NULL;
|
||||
closure_resolve_t cr = {0};
|
||||
bool cr_arena_live = false;
|
||||
@@ -3778,6 +3919,11 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
|
||||
cbm_log_error("delta.err", "phase", "doc_link_scopes");
|
||||
goto out;
|
||||
}
|
||||
indexed_files = cbm_pipeline_indexed_files_new(files, file_count);
|
||||
if (!indexed_files) {
|
||||
cbm_log_error("delta.err", "phase", "indexed_files");
|
||||
goto out;
|
||||
}
|
||||
/* The purge already removed the closure and deleted files, so every File
|
||||
* row left in the stage is a file the passes will not see. A failed read
|
||||
* is a delta-route failure: the maps would silently diverge from a full
|
||||
@@ -3791,6 +3937,7 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
|
||||
cbm_pipeline_ctx_t ctx = {
|
||||
.project_name = project,
|
||||
.repo_path = cbm_pipeline_repo_path(p),
|
||||
.indexed_files = indexed_files,
|
||||
.gbuf = gbuf,
|
||||
.registry = registry,
|
||||
.cancelled = cbm_pipeline_cancelled_ptr(p),
|
||||
@@ -4133,6 +4280,7 @@ out:
|
||||
cbm_registry_free(registry);
|
||||
}
|
||||
cbm_path_alias_collection_free(path_aliases);
|
||||
cbm_ht_free(indexed_files); /* keys borrowed from files */
|
||||
if (gbuf) {
|
||||
cbm_gbuf_free(gbuf);
|
||||
}
|
||||
@@ -4546,10 +4694,12 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
|
||||
|
||||
cbm_path_alias_collection_t *path_aliases =
|
||||
cbm_load_path_aliases_excluded(cbm_pipeline_repo_path(p), excluded_dirs, excluded_count);
|
||||
CBMHashTable *indexed_files = cbm_pipeline_indexed_files_new(files, file_count);
|
||||
|
||||
cbm_pipeline_ctx_t ctx = {
|
||||
.project_name = project,
|
||||
.repo_path = cbm_pipeline_repo_path(p),
|
||||
.indexed_files = indexed_files,
|
||||
.gbuf = existing,
|
||||
.registry = registry,
|
||||
.cancelled = cbm_pipeline_cancelled_ptr(p),
|
||||
@@ -4637,6 +4787,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
|
||||
free(changed_files);
|
||||
cbm_registry_free(registry);
|
||||
cbm_path_alias_collection_free(path_aliases);
|
||||
cbm_ht_free(indexed_files); /* keys borrowed from files */
|
||||
incr_free_edge_capture(&edge_cap);
|
||||
cbm_store_free_coverage(old_cov, old_cov_count);
|
||||
free_mode_skipped(mode_skipped, mode_skipped_count);
|
||||
@@ -4736,6 +4887,7 @@ int cbm_pipeline_run_incremental(cbm_pipeline_t *p, const char *db_path, cbm_fil
|
||||
free(changed_files);
|
||||
cbm_registry_free(registry);
|
||||
cbm_path_alias_collection_free(path_aliases);
|
||||
cbm_ht_free(indexed_files); /* keys borrowed from files */
|
||||
|
||||
/* Re-link inbound cross-file edges that the purge orphaned. Runs after
|
||||
* re-resolution AND post-passes so the freshly re-created target nodes
|
||||
|
||||
@@ -458,6 +458,10 @@ typedef struct cbm_tf_release {
|
||||
typedef struct {
|
||||
const char *project_name; /* borrowed from pipeline */
|
||||
const char *repo_path; /* borrowed from pipeline */
|
||||
/* The rel_path of every file of the run's whole discovery (keys borrowed
|
||||
* from its file list), also when a pass is handed only some of them: the
|
||||
* files a C-family #include may resolve to (#2993). NULL: none resolves. */
|
||||
const CBMHashTable *indexed_files;
|
||||
/* An incremental run: the unchanged files whose earlier run declared
|
||||
* image builds (docker build ...), read again by the shell pass, as
|
||||
* those edges are recomputed whole. Borrowed; NULL in a full run. */
|
||||
@@ -577,6 +581,13 @@ typedef struct {
|
||||
int tf_release_cap;
|
||||
} cbm_pipeline_ctx_t;
|
||||
|
||||
/* The set for cbm_pipeline_ctx_t.indexed_files: every rel_path of `files`
|
||||
* (keys borrowed; free with cbm_ht_free). NULL on allocation failure. */
|
||||
CBMHashTable *cbm_pipeline_indexed_files_new(const cbm_file_info_t *files, int file_count);
|
||||
/* The #include scope of a pass's C-family extraction: the run's repository
|
||||
* root and its indexed files. */
|
||||
CBMIncludeScope cbm_pipeline_include_scope(const cbm_pipeline_ctx_t *ctx);
|
||||
|
||||
/* Origin-aware LSP returns only success/failure. Never retain partial output
|
||||
* when its configured owner proof cannot be applied to current source. */
|
||||
static inline void cbm_pipeline_test_owner_error(CBMFileResult *result) {
|
||||
@@ -2087,6 +2098,16 @@ void cbm_pipeline_incremental_test_after_stage_created_once(cbm_pipeline_test_ho
|
||||
void *userdata);
|
||||
cbm_incremental_route_t cbm_pipeline_incremental_test_last_route(void);
|
||||
void cbm_pipeline_incremental_test_reset_faults(void);
|
||||
/* The last closure plan: an accepted plan's re-parse set size, surface-changed
|
||||
* files and dependents (decline NULL), or a declined plan's reason (counters
|
||||
* -1). All -1 / NULL after a reset and when no plan ran. */
|
||||
typedef struct {
|
||||
int files;
|
||||
int surface_changed;
|
||||
int dependents;
|
||||
const char *decline;
|
||||
} cbm_incremental_closure_plan_t;
|
||||
cbm_incremental_closure_plan_t cbm_pipeline_incremental_test_last_closure_plan(void);
|
||||
|
||||
/* Shared persistence-hook plumbing. Tests use the incremental facade above so
|
||||
* one reset covers route, extraction, and publication faults. */
|
||||
|
||||
@@ -0,0 +1,821 @@
|
||||
/*
|
||||
* type_scope.c — declared types resolved once, in the scope that wrote them.
|
||||
* See type_scope.h for the contract.
|
||||
*
|
||||
* Cost: per file, one hash of its import map, one hash of its own definitions
|
||||
* (rows with lexical scopes) and one memo of the spellings it writes; per
|
||||
* definition, one scan of its type texts and one walk up its enclosing defs
|
||||
* that stops at the first one already walked. Every lookup is an exact hash
|
||||
* probe (no scan, no short-name candidate list), so the step is linear in the
|
||||
* bytes of declared type text and of the file's definition names.
|
||||
*/
|
||||
#include "pipeline/type_scope.h"
|
||||
|
||||
#include "foundation/constants.h"
|
||||
#include "graph_buffer/graph_buffer.h" /* the module check of a target */
|
||||
|
||||
#include <stdatomic.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* ── Language descriptions ────────────────────────────────────────── */
|
||||
|
||||
/* Go: every type-like declaration has a method set (a Go alias carries its
|
||||
* target through alias_target, which the registrar follows). */
|
||||
static const char *const go_labels[] = {"Struct", "Interface", "Type", "Class", "Enum", NULL};
|
||||
/* Python: what py_register_lsp_defs registers as a type. */
|
||||
static const char *const py_labels[] = {"Class", "Interface", "Protocol", "Type", NULL};
|
||||
|
||||
static const cbm_type_scope_lang_t type_scope_langs[] = {
|
||||
{.lang = CBM_LANG_GO,
|
||||
.labels = go_labels,
|
||||
.engine_qualifies_own_module = true,
|
||||
.imports_bind_modules = true,
|
||||
.return_types = true,
|
||||
.param_types = true,
|
||||
.field_types = true,
|
||||
.embedded_types = true},
|
||||
{.lang = CBM_LANG_PYTHON,
|
||||
.quoted_names = true,
|
||||
.labels = py_labels,
|
||||
.engine_qualifies_own_module = false,
|
||||
.lexical_scopes = true,
|
||||
.return_types = true,
|
||||
.param_types = true},
|
||||
};
|
||||
|
||||
const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang) {
|
||||
for (size_t i = 0; i < sizeof(type_scope_langs) / sizeof(type_scope_langs[0]); i++) {
|
||||
if (type_scope_langs[i].lang == lang) {
|
||||
return &type_scope_langs[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ── Work counter (test builds) ───────────────────────────────────── */
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
static _Atomic uint64_t g_type_scope_work;
|
||||
|
||||
uint64_t cbm_type_scope_test_work(void) {
|
||||
return atomic_load_explicit(&g_type_scope_work, memory_order_relaxed);
|
||||
}
|
||||
|
||||
#define TYPE_SCOPE_WORK(n) \
|
||||
atomic_fetch_add_explicit(&g_type_scope_work, (uint64_t)(n), memory_order_relaxed)
|
||||
#else
|
||||
#define TYPE_SCOPE_WORK(n) ((void)0)
|
||||
#endif
|
||||
|
||||
/* ── Per-file state ───────────────────────────────────────────────── */
|
||||
|
||||
/* Distinct, never-dereferenced values: "two imports bind this local to
|
||||
* different targets", a memoized miss, and the two nesting verdicts. */
|
||||
static char g_ambiguous_mark;
|
||||
static char g_miss_mark;
|
||||
static char g_nest_open_mark;
|
||||
static char g_nest_local_mark;
|
||||
static char g_bound_once_mark;
|
||||
static char g_bound_many_mark;
|
||||
static char g_overload_mark;
|
||||
static char g_overload_differ_mark;
|
||||
#define TYPE_SCOPE_BOUND_ONCE ((void *)&g_bound_once_mark)
|
||||
#define TYPE_SCOPE_BOUND_MANY ((void *)&g_bound_many_mark)
|
||||
#define TYPE_SCOPE_AMBIGUOUS ((void *)&g_ambiguous_mark)
|
||||
#define TYPE_SCOPE_MISS ((void *)&g_miss_mark)
|
||||
#define TYPE_SCOPE_NEST_OPEN ((void *)&g_nest_open_mark) /* module or class bodies only */
|
||||
#define TYPE_SCOPE_NEST_LOCAL ((void *)&g_nest_local_mark) /* inside a function */
|
||||
#define TYPE_SCOPE_OVERLOAD ((void *)&g_overload_mark) /* declared with @overload */
|
||||
#define TYPE_SCOPE_OVERLOAD_DIFFER ((void *)&g_overload_differ_mark)
|
||||
#define TYPE_SCOPE_ALIAS_MAX 256 /* a decorator name read through the imports */
|
||||
|
||||
struct cbm_type_scope_file {
|
||||
const cbm_type_scope_lang_t *lang;
|
||||
cbm_type_scope_t scope;
|
||||
size_t scope_len; /* the module's symbol scope (a package without __init__) */
|
||||
CBMHashTable *imports; /* local -> import QN, or TYPE_SCOPE_AMBIGUOUS */
|
||||
CBMHashTable *memo; /* spelling -> QN, or TYPE_SCOPE_MISS */
|
||||
CBMHashTable *seen; /* spelling -> serial of the last def that wrote it */
|
||||
/* lexical scopes only */
|
||||
CBMHashTable *defs; /* file def QN -> index + 1 into scope.file_defs */
|
||||
CBMHashTable *class_binds; /* "<class QN>.<name>" a class body binds (not a def) */
|
||||
CBMHashTable *overloaded; /* QN some def declares with @overload -> the return text
|
||||
* all its defs share, or TYPE_SCOPE_OVERLOAD_DIFFER */
|
||||
CBMHashTable *ovl_alias; /* local name a module-level `from typing import overload
|
||||
* as X` binds */
|
||||
CBMHashTable *tparams; /* every type parameter name the file declares */
|
||||
CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */
|
||||
CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */
|
||||
bool closed; /* the module's bindings cannot be listed: no identity */
|
||||
uintptr_t serial; /* the def being attached, from 1 */
|
||||
const char *enclosing_class; /* the def's immediately enclosing class, or NULL */
|
||||
CBMArena keys; /* memo keys and candidate strings */
|
||||
};
|
||||
|
||||
static bool type_scope_function_label(const char *label) {
|
||||
return label && (strcmp(label, "Function") == 0 || strcmp(label, "Method") == 0);
|
||||
}
|
||||
|
||||
/* Count the module-level bindings of every name from the ordered namespace
|
||||
* facts; a star import, a parse error or an incomplete record closes the
|
||||
* file. */
|
||||
static bool type_scope_index_module_facts(cbm_type_scope_file_t *f) {
|
||||
const CBMPyNamespaceFacts *facts = f->scope.module_facts;
|
||||
f->bindings = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(facts ? facts->count + 1 : 1));
|
||||
if (!f->bindings) {
|
||||
return false;
|
||||
}
|
||||
if (!facts || facts->status != CBM_PY_NS_COMPLETE) {
|
||||
f->closed = true;
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < facts->count && !f->closed; i++) {
|
||||
const CBMPyNamespaceFact *fact = &facts->items[i];
|
||||
TYPE_SCOPE_WORK(1);
|
||||
switch (fact->kind) {
|
||||
case CBM_PY_NS_IMPORT_STAR:
|
||||
f->closed = true; /* binds names nobody listed */
|
||||
break;
|
||||
case CBM_PY_NS_UNKNOWN:
|
||||
/* An effect or a compound statement: the import map and the
|
||||
* engine read past those as well. A parse error leaves the file's
|
||||
* bindings unknown. */
|
||||
f->closed = fact->reason == CBM_PY_NS_REASON_PARSE;
|
||||
break;
|
||||
case CBM_PY_NS_OWN_DEF:
|
||||
case CBM_PY_NS_IMPORT_MODULE:
|
||||
case CBM_PY_NS_IMPORT_NAME:
|
||||
case CBM_PY_NS_SHADOW:
|
||||
case CBM_PY_NS_DELETE:
|
||||
if (fact->local_name && fact->local_name[0]) {
|
||||
bool again = cbm_ht_get(f->bindings, fact->local_name) != NULL;
|
||||
/* keys borrow the facts, which outlive the file state */
|
||||
cbm_ht_set(f->bindings, fact->local_name,
|
||||
again ? TYPE_SCOPE_BOUND_MANY : TYPE_SCOPE_BOUND_ONCE);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break; /* __all__ facts bind no name */
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* True when the module binds this head more than once. */
|
||||
static bool type_scope_rebound(const cbm_type_scope_file_t *f, const char *head) {
|
||||
TYPE_SCOPE_WORK(1);
|
||||
return f->bindings && cbm_ht_get(f->bindings, head) == TYPE_SCOPE_BOUND_MANY;
|
||||
}
|
||||
|
||||
/* Each name a class body binds besides its definitions, keyed as a member of
|
||||
* the class ("<class QN>.<name>", the key type_scope_shadowed probes). */
|
||||
static void type_scope_index_class_bindings(cbm_type_scope_file_t *f, const CBMDefinition *d) {
|
||||
const char *bound = d->type_facts ? d->type_facts->class_bindings : NULL;
|
||||
for (const char *p = bound; p && *p && d->qualified_name;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
TYPE_SCOPE_WORK(len + 1);
|
||||
char *key =
|
||||
len ? cbm_arena_sprintf(&f->keys, "%s.%.*s", d->qualified_name, (int)len, p) : NULL;
|
||||
if (key && !cbm_ht_get(f->class_binds, key)) {
|
||||
cbm_ht_set(f->class_binds, key, key);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
}
|
||||
|
||||
/* A name some function or class body of the file declares `global` and binds
|
||||
* is rebound in the module by that body (when it runs, or at import for a
|
||||
* class body): like a name the module binds twice, it gets no identity. */
|
||||
static void type_scope_index_global_names(cbm_type_scope_file_t *f, const CBMDefinition *d) {
|
||||
const char *names = d->type_facts ? d->type_facts->global_names : NULL;
|
||||
for (const char *p = names; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
TYPE_SCOPE_WORK(len + 1);
|
||||
char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL;
|
||||
if (name) {
|
||||
cbm_ht_set(f->bindings, name, TYPE_SCOPE_BOUND_MANY);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
}
|
||||
|
||||
/* The local names the module's imports bind to typing's overload under another
|
||||
* name (`from typing import overload as ovl`, typing_extensions too). */
|
||||
static void type_scope_index_ovl_alias(cbm_type_scope_file_t *f) {
|
||||
const CBMPyNamespaceFacts *facts = f->scope.module_facts;
|
||||
for (int i = 0; facts && i < facts->count; i++) {
|
||||
const CBMPyNamespaceFact *x = &facts->items[i];
|
||||
TYPE_SCOPE_WORK(1);
|
||||
if (x->kind == CBM_PY_NS_IMPORT_NAME && x->relative_level == 0 && x->local_name &&
|
||||
x->module_name && x->member_name && strcmp(x->member_name, "overload") == 0 &&
|
||||
(strcmp(x->module_name, "typing") == 0 ||
|
||||
strcmp(x->module_name, "typing_extensions") == 0)) {
|
||||
cbm_ht_set(f->ovl_alias, x->local_name, (void *)x->local_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether a decorator's text is typing's @overload: its last dotted name is
|
||||
* `overload` (`@overload`, `@typing.overload`, `@t.overload`), or it is a
|
||||
* plain name the module imports as typing's overload (`@ovl`). */
|
||||
static bool type_scope_overload_decorator(const cbm_type_scope_file_t *f, const char *text) {
|
||||
while (text && (*text == '@' || *text == ' ' || *text == '\t')) {
|
||||
text++;
|
||||
}
|
||||
if (!text || !*text) {
|
||||
return false;
|
||||
}
|
||||
size_t len = strcspn(text, "( \t\r\n");
|
||||
const char *name = text;
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
if (text[i] == '.') {
|
||||
name = text + i + 1;
|
||||
}
|
||||
}
|
||||
if ((size_t)(text + len - name) == strlen("overload") &&
|
||||
memcmp(name, "overload", strlen("overload")) == 0) {
|
||||
return true;
|
||||
}
|
||||
char local[TYPE_SCOPE_ALIAS_MAX];
|
||||
if (name != text || len >= sizeof(local) || cbm_ht_count(f->ovl_alias) == 0) {
|
||||
return false;
|
||||
}
|
||||
memcpy(local, text, len);
|
||||
local[len] = '\0';
|
||||
return cbm_ht_get(f->ovl_alias, local) != NULL;
|
||||
}
|
||||
|
||||
/* A function with @overload declarations: callers see the overloads, which
|
||||
* pick the result from the arguments, so the implementation's annotations are
|
||||
* not its type at a call, nor is any one overload's -- unless all of its
|
||||
* definitions declare the same return type (whichever overload a call picks,
|
||||
* that is the type). Where they differ its QN takes no identity. */
|
||||
static void type_scope_index_overload(cbm_type_scope_file_t *f, const CBMDefinition *d) {
|
||||
for (int i = 0; d->decorators && d->decorators[i] && d->qualified_name; i++) {
|
||||
TYPE_SCOPE_WORK(1);
|
||||
if (type_scope_overload_decorator(f, d->decorators[i])) {
|
||||
cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Second pass: whether the definitions of each overloaded QN agree on the
|
||||
* return type text (none counts as a text of its own). */
|
||||
static void type_scope_compare_overloads(cbm_type_scope_file_t *f) {
|
||||
int n = cbm_ht_count(f->overloaded) ? f->scope.file_def_count : 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
const CBMDefinition *d = &f->scope.file_defs[i];
|
||||
void *seen = d->qualified_name ? cbm_ht_get(f->overloaded, d->qualified_name) : NULL;
|
||||
const char *ret = d->return_type ? d->return_type : "";
|
||||
TYPE_SCOPE_WORK(strlen(ret) + 1);
|
||||
if (seen == TYPE_SCOPE_OVERLOAD) {
|
||||
cbm_ht_set(f->overloaded, d->qualified_name, (void *)ret);
|
||||
} else if (seen && seen != TYPE_SCOPE_OVERLOAD_DIFFER && strcmp((const char *)seen, ret)) {
|
||||
cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD_DIFFER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash the file's own definitions, its type parameter names and the names
|
||||
* its class bodies bind. */
|
||||
static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) {
|
||||
int n = f->scope.file_def_count;
|
||||
f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1));
|
||||
f->class_binds = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
|
||||
f->overloaded = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
|
||||
f->ovl_alias = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
|
||||
f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
|
||||
f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1));
|
||||
if (!f->defs || !f->class_binds || !f->overloaded || !f->ovl_alias || !f->tparams ||
|
||||
!f->nesting || !type_scope_index_module_facts(f)) {
|
||||
return false;
|
||||
}
|
||||
type_scope_index_ovl_alias(f);
|
||||
for (int i = 0; i < n; i++) {
|
||||
const CBMDefinition *d = &f->scope.file_defs[i];
|
||||
if (d->qualified_name && !cbm_ht_get(f->defs, d->qualified_name)) {
|
||||
TYPE_SCOPE_WORK(1);
|
||||
cbm_ht_set(f->defs, d->qualified_name, (void *)(uintptr_t)(i + 1));
|
||||
}
|
||||
type_scope_index_class_bindings(f, d);
|
||||
type_scope_index_global_names(f, d);
|
||||
type_scope_index_overload(f, d);
|
||||
for (const char *p = d->type_facts ? d->type_facts->type_params : NULL; p && *p;) {
|
||||
const char *bar = strchr(p, '|');
|
||||
size_t len = bar ? (size_t)(bar - p) : strlen(p);
|
||||
char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL;
|
||||
TYPE_SCOPE_WORK(len + 1);
|
||||
if (name && !cbm_ht_get(f->tparams, name)) {
|
||||
cbm_ht_set(f->tparams, name, name);
|
||||
}
|
||||
p = bar ? bar + 1 : p + len;
|
||||
}
|
||||
}
|
||||
type_scope_compare_overloads(f);
|
||||
return true;
|
||||
}
|
||||
|
||||
cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang,
|
||||
const cbm_type_scope_t *scope) {
|
||||
if (!lang || !scope || !scope->reg || !scope->module_qn) {
|
||||
return NULL;
|
||||
}
|
||||
cbm_type_scope_file_t *f = cbm_calloc(CBM_MEM_CLASS_EXTRACT, sizeof(*f));
|
||||
if (!f) {
|
||||
return NULL;
|
||||
}
|
||||
f->lang = lang;
|
||||
f->scope = *scope;
|
||||
f->scope_len = cbm_fqn_symbol_scope_len(scope->module_qn);
|
||||
f->imports = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(scope->imp_count + 1));
|
||||
f->memo = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32);
|
||||
f->seen = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32);
|
||||
cbm_arena_init_lazy(&f->keys, CBM_SZ_4K);
|
||||
if (!f->imports || !f->memo || !f->seen ||
|
||||
(lang->lexical_scopes && !type_scope_index_file_defs(f))) {
|
||||
cbm_type_scope_file_end(f);
|
||||
return NULL;
|
||||
}
|
||||
for (int i = 0; i < scope->imp_count; i++) {
|
||||
const char *key = scope->imp_keys ? scope->imp_keys[i] : NULL;
|
||||
const char *val = scope->imp_vals ? scope->imp_vals[i] : NULL;
|
||||
if (!key || !val || !key[0]) {
|
||||
continue;
|
||||
}
|
||||
TYPE_SCOPE_WORK(1);
|
||||
void *prev = cbm_ht_get(f->imports, key);
|
||||
if (!prev) {
|
||||
cbm_ht_set(f->imports, key, (void *)val);
|
||||
} else if (prev != TYPE_SCOPE_AMBIGUOUS && strcmp((const char *)prev, val) != 0) {
|
||||
cbm_ht_set(f->imports, key, TYPE_SCOPE_AMBIGUOUS);
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
void cbm_type_scope_file_end(cbm_type_scope_file_t *file) {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
cbm_ht_free(file->imports); /* NULL-safe */
|
||||
cbm_ht_free(file->memo);
|
||||
cbm_ht_free(file->seen);
|
||||
cbm_ht_free(file->defs);
|
||||
cbm_ht_free(file->class_binds);
|
||||
cbm_ht_free(file->overloaded);
|
||||
cbm_ht_free(file->ovl_alias);
|
||||
cbm_ht_free(file->tparams);
|
||||
cbm_ht_free(file->nesting);
|
||||
cbm_ht_free(file->bindings);
|
||||
cbm_arena_destroy(&file->keys);
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, file);
|
||||
}
|
||||
|
||||
/* ── Resolution ───────────────────────────────────────────────────── */
|
||||
|
||||
/* `qn` when it names a project definition of an allowed label, else NULL. A
|
||||
* QN the graph holds as a module (a class and a module of one QN) is none:
|
||||
* the two share their members' QNs. */
|
||||
static const char *type_scope_target(const cbm_type_scope_file_t *f, const char *qn) {
|
||||
TYPE_SCOPE_WORK(1);
|
||||
const char *label = cbm_registry_label_of(f->scope.reg, qn);
|
||||
if (!label) {
|
||||
return NULL;
|
||||
}
|
||||
for (const char *const *l = f->lang->labels; *l; l++) {
|
||||
if (strcmp(*l, label) == 0) {
|
||||
const cbm_gbuf_node_t *node = f->lang->lexical_scopes && f->scope.graph
|
||||
? cbm_gbuf_find_by_qn(f->scope.graph, qn)
|
||||
: NULL;
|
||||
return node && node->label && strcmp(node->label, "Module") == 0 ? NULL : qn;
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The candidate QN for `dotted` through the import that binds its head, or
|
||||
* NULL. *bound reports whether an import binds the head at all (then the
|
||||
* file's own module does not decide the name). An import names a project
|
||||
* definition or nothing: a path that names no definition (a module outside
|
||||
* the project, a name a package re-exports) is no answer. */
|
||||
static const char *type_scope_via_import(cbm_type_scope_file_t *f, const char *dotted,
|
||||
size_t head_len, bool *bound, bool *ambiguous) {
|
||||
*bound = false;
|
||||
*ambiguous = false;
|
||||
const char *dot = dotted[head_len] == '.' ? dotted + head_len : NULL;
|
||||
if (!dot && f->lang->imports_bind_modules) {
|
||||
return NULL; /* a bare name never resolves through a package import */
|
||||
}
|
||||
char head[CBM_SZ_256];
|
||||
if (head_len == 0 || head_len >= sizeof(head)) {
|
||||
return NULL;
|
||||
}
|
||||
memcpy(head, dotted, head_len);
|
||||
head[head_len] = '\0';
|
||||
TYPE_SCOPE_WORK(1);
|
||||
void *v = cbm_ht_get(f->imports, head);
|
||||
if (!v) {
|
||||
return NULL;
|
||||
}
|
||||
*bound = true;
|
||||
if (v == TYPE_SCOPE_AMBIGUOUS) {
|
||||
*ambiguous = true;
|
||||
return NULL;
|
||||
}
|
||||
const char *val = (const char *)v;
|
||||
if (dot) {
|
||||
/* `pkg.T`: the import binds the module, the rest names inside it. */
|
||||
const char *qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, dot + 1);
|
||||
return qn ? type_scope_target(f, qn) : NULL;
|
||||
}
|
||||
/* A bare name: the import binds the type itself, or (a module-valued
|
||||
* binding, Python's `from m import T` whose edge names the module) the
|
||||
* type of that name inside it. Both existing and differing is no answer. */
|
||||
const char *direct = type_scope_target(f, val);
|
||||
const char *member_qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, head);
|
||||
const char *member = member_qn ? type_scope_target(f, member_qn) : NULL;
|
||||
if (direct && member && strcmp(direct, member) != 0) {
|
||||
*ambiguous = true;
|
||||
return NULL;
|
||||
}
|
||||
return direct ? direct : member;
|
||||
}
|
||||
|
||||
/* The memo / seen key of a spelling: the spelling itself, NUL-terminated in a
|
||||
* caller buffer (a name too long for it has no identity). */
|
||||
static bool type_scope_key(const char *spelling, size_t len, char *buf, size_t bufsz) {
|
||||
if (len == 0 || len >= bufsz) {
|
||||
return false;
|
||||
}
|
||||
memcpy(buf, spelling, len);
|
||||
buf[len] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
static size_t type_scope_head_len(const char *spelling, size_t len) {
|
||||
const char *dot = memchr(spelling, '.', len);
|
||||
return dot ? (size_t)(dot - spelling) : len;
|
||||
}
|
||||
|
||||
const char *cbm_type_scope_resolve(cbm_type_scope_file_t *f, const char *spelling, size_t len) {
|
||||
char probe[CBM_SZ_512];
|
||||
if (!f || !spelling || !type_scope_key(spelling, len, probe, sizeof(probe))) {
|
||||
return NULL;
|
||||
}
|
||||
TYPE_SCOPE_WORK(1);
|
||||
void *memo = cbm_ht_get(f->memo, probe);
|
||||
if (memo) {
|
||||
return memo == TYPE_SCOPE_MISS ? NULL : (const char *)memo;
|
||||
}
|
||||
char *key = cbm_arena_strndup(&f->keys, spelling, len);
|
||||
if (!key) {
|
||||
return NULL;
|
||||
}
|
||||
const char *result = NULL;
|
||||
const char *dotted = key; /* `T` or `pkg.T`, NUL-terminated */
|
||||
size_t head_len = type_scope_head_len(dotted, len);
|
||||
if (f->bindings) {
|
||||
/* A head the module binds more than once has no one answer. */
|
||||
char head[CBM_SZ_256];
|
||||
if (!type_scope_key(dotted, head_len, head, sizeof(head)) || type_scope_rebound(f, head)) {
|
||||
cbm_ht_set(f->memo, key, TYPE_SCOPE_MISS);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
bool bound = false;
|
||||
bool ambiguous = false;
|
||||
const char *via_import = type_scope_via_import(f, dotted, head_len, &bound, &ambiguous);
|
||||
/* A Python package's names live under the package, not its __init__. */
|
||||
const char *mod = f->scope.module_qn;
|
||||
int scope_len = (int)f->scope_len;
|
||||
const char *own_qn = cbm_arena_sprintf(&f->keys, "%.*s.%s", scope_len, mod, dotted);
|
||||
const char *own = own_qn ? type_scope_target(f, own_qn) : NULL;
|
||||
if (bound && !ambiguous) {
|
||||
/* The import decides, unless the own module binds the head as well
|
||||
* (any definition of that name: a class, a function, a TypeVar
|
||||
* variable): two bindings of one name, whose winner is source order. */
|
||||
const char *head_qn =
|
||||
cbm_arena_sprintf(&f->keys, "%.*s.%.*s", scope_len, mod, (int)head_len, dotted);
|
||||
TYPE_SCOPE_WORK(1);
|
||||
bool own_binds = head_qn && cbm_registry_exists(f->scope.reg, head_qn);
|
||||
bool same = via_import && own && strcmp(own, via_import) == 0;
|
||||
result = own_binds && !same ? NULL : via_import;
|
||||
} else if (!bound) {
|
||||
result = own;
|
||||
}
|
||||
cbm_ht_set(f->memo, key, result ? (void *)result : TYPE_SCOPE_MISS);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* ── The def's own enclosing scopes (lexical rows) ───────────────── */
|
||||
|
||||
/* Whether the definition `qn` lies inside a function. inside(q) is true when
|
||||
* q's parent is a function, false when the parent is the module, and
|
||||
* inside(parent) when the parent is a class of this file; a parent QN this
|
||||
* file does not define is no proof of a module or class body, so it counts as
|
||||
* inside (no identity). The walk stops at the first ancestor already judged,
|
||||
* and every class it passes is judged on the way, so each definition of the
|
||||
* file is walked through once. */
|
||||
static bool type_scope_function_local(cbm_type_scope_file_t *f, const char *qn) {
|
||||
const char **passed = NULL; /* classes walked through, not yet judged */
|
||||
int count = 0;
|
||||
int cap = 0;
|
||||
bool inside = true;
|
||||
const char *cur = qn;
|
||||
for (;;) {
|
||||
const char *dot = strrchr(cur, '.');
|
||||
size_t parent_len = dot ? (size_t)(dot - cur) : 0;
|
||||
if (parent_len <= f->scope_len) {
|
||||
inside = false; /* cur is a module-level definition */
|
||||
break;
|
||||
}
|
||||
char *parent = cbm_arena_strndup(&f->keys, cur, parent_len);
|
||||
TYPE_SCOPE_WORK(parent_len + 1);
|
||||
if (!parent) {
|
||||
break;
|
||||
}
|
||||
void *known = cbm_ht_get(f->nesting, parent);
|
||||
if (known) {
|
||||
inside = known == TYPE_SCOPE_NEST_LOCAL;
|
||||
break;
|
||||
}
|
||||
uintptr_t at = (uintptr_t)cbm_ht_get(f->defs, parent);
|
||||
if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) {
|
||||
break; /* inside a function, or under a parent this file lacks */
|
||||
}
|
||||
if (count == cap) {
|
||||
int grown_cap = cap ? cap * 2 : 8;
|
||||
const char **grown =
|
||||
(const char **)cbm_arena_alloc(&f->keys, (size_t)grown_cap * sizeof(*grown));
|
||||
if (!grown) {
|
||||
break;
|
||||
}
|
||||
if (count) {
|
||||
memcpy(grown, passed, (size_t)count * sizeof(*grown));
|
||||
}
|
||||
passed = grown;
|
||||
cap = grown_cap;
|
||||
}
|
||||
passed[count++] = parent; /* a class: inside(cur) == inside(parent) */
|
||||
cur = parent;
|
||||
}
|
||||
for (int i = 0; i < count; i++) {
|
||||
cbm_ht_set(f->nesting, passed[i], inside ? TYPE_SCOPE_NEST_LOCAL : TYPE_SCOPE_NEST_OPEN);
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/* The def's immediately enclosing class: its parent QN when that is a
|
||||
* non-function definition of this file, else NULL. */
|
||||
static const char *type_scope_enclosing_class(cbm_type_scope_file_t *f, const char *qn) {
|
||||
const char *dot = strrchr(qn, '.');
|
||||
size_t parent_len = dot ? (size_t)(dot - qn) : 0;
|
||||
if (parent_len <= f->scope_len) {
|
||||
return NULL;
|
||||
}
|
||||
char *parent = cbm_arena_strndup(&f->keys, qn, parent_len);
|
||||
TYPE_SCOPE_WORK(parent_len + 1);
|
||||
uintptr_t at = parent ? (uintptr_t)cbm_ht_get(f->defs, parent) : 0;
|
||||
if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) {
|
||||
return NULL;
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
|
||||
/* True when the def's own scopes bind the head of this spelling before the
|
||||
* module does: a type parameter the file declares, or a name the enclosing
|
||||
* class body declares (a nested definition) or binds (an assignment, an
|
||||
* import, a loop or with or except target...). */
|
||||
static bool type_scope_shadowed(cbm_type_scope_file_t *f, const char *name, size_t len) {
|
||||
size_t head_len = type_scope_head_len(name, len);
|
||||
char head[CBM_SZ_256];
|
||||
if (!type_scope_key(name, head_len, head, sizeof(head))) {
|
||||
return true;
|
||||
}
|
||||
TYPE_SCOPE_WORK(1);
|
||||
if (cbm_ht_get(f->tparams, head)) {
|
||||
return true;
|
||||
}
|
||||
if (!f->enclosing_class) {
|
||||
return false;
|
||||
}
|
||||
const char *member = cbm_arena_sprintf(&f->keys, "%s.%s", f->enclosing_class, head);
|
||||
TYPE_SCOPE_WORK(1);
|
||||
return !member || cbm_ht_get(f->defs, member) != NULL ||
|
||||
cbm_ht_get(f->class_binds, member) != NULL;
|
||||
}
|
||||
|
||||
/* ── Reduction of a type text to the names it writes ──────────────── */
|
||||
|
||||
static bool type_scope_ident_start(unsigned char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c >= 0x80;
|
||||
}
|
||||
|
||||
static bool type_scope_ident_char(unsigned char c) {
|
||||
return type_scope_ident_start(c) || (c >= '0' && c <= '9');
|
||||
}
|
||||
|
||||
typedef void (*type_scope_name_fn)(const char *name, size_t len, void *ud);
|
||||
|
||||
/* Call fn for every type name the text writes: a run of identifier
|
||||
* characters joined by `.`. A quoted run is a literal (skipped) unless
|
||||
* quoted_names; a name that is only a member access (one `.` before it) or a
|
||||
* label (one `:` after it: a property, a named parameter) is not a type
|
||||
* name. */
|
||||
static void type_scope_names(const cbm_type_scope_lang_t *lang, const char *text,
|
||||
type_scope_name_fn fn, void *ud) {
|
||||
size_t n = text ? strlen(text) : 0;
|
||||
TYPE_SCOPE_WORK(n);
|
||||
size_t i = 0;
|
||||
while (i < n) {
|
||||
unsigned char c = (unsigned char)text[i];
|
||||
if ((c == '"' || c == '\'' || c == '`') && !lang->quoted_names) {
|
||||
size_t close = i + 1;
|
||||
while (close < n && text[close] != (char)c) {
|
||||
close++;
|
||||
}
|
||||
i = close < n ? close + 1 : n;
|
||||
continue;
|
||||
}
|
||||
if (!type_scope_ident_start(c)) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
size_t start = i;
|
||||
while (i < n && type_scope_ident_char((unsigned char)text[i])) {
|
||||
i++;
|
||||
}
|
||||
for (;;) {
|
||||
if (i + 1 < n && text[i] == '.' && type_scope_ident_start((unsigned char)text[i + 1])) {
|
||||
i++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
while (i < n && type_scope_ident_char((unsigned char)text[i])) {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
bool member = start > 0 && text[start - 1] == '.' && (start < 2 || text[start - 2] != '.');
|
||||
size_t after = i;
|
||||
while (after < n && text[after] == ' ') {
|
||||
after++;
|
||||
}
|
||||
bool label = after < n && text[after] == ':' && (after + 1 >= n || text[after + 1] != ':');
|
||||
if (!member && !label) {
|
||||
fn(text + start, i - start, ud);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Attaching identities to a definition ─────────────────────────── */
|
||||
|
||||
typedef struct {
|
||||
cbm_type_scope_file_t *file;
|
||||
char *buf; /* "spelling=QN|..." being built (heap) */
|
||||
size_t len;
|
||||
size_t cap;
|
||||
bool failed;
|
||||
} type_scope_build_t;
|
||||
|
||||
/* True when the current def already wrote this spelling (one hash probe; the
|
||||
* seen table remembers, per spelling, the last def that wrote it). */
|
||||
static bool type_scope_seen(cbm_type_scope_file_t *f, const char *name, size_t len) {
|
||||
char probe[CBM_SZ_512];
|
||||
if (!type_scope_key(name, len, probe, sizeof(probe))) {
|
||||
return true; /* too long to key: never an identity */
|
||||
}
|
||||
TYPE_SCOPE_WORK(1);
|
||||
void *last = cbm_ht_get(f->seen, probe);
|
||||
if (last == (void *)f->serial) {
|
||||
return true;
|
||||
}
|
||||
const char *key = last ? cbm_ht_get_key(f->seen, probe) : cbm_arena_strdup(&f->keys, probe);
|
||||
if (key) {
|
||||
cbm_ht_set(f->seen, key, (void *)f->serial);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool type_scope_append(type_scope_build_t *b, const char *s, size_t n) {
|
||||
if (b->len + n + 1 > b->cap) {
|
||||
size_t cap = b->cap ? b->cap * 2 : 128;
|
||||
while (cap < b->len + n + 1) {
|
||||
cap *= 2;
|
||||
}
|
||||
char *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, b->buf, cap);
|
||||
if (!grown) {
|
||||
b->failed = true;
|
||||
return false;
|
||||
}
|
||||
b->buf = grown;
|
||||
b->cap = cap;
|
||||
}
|
||||
memcpy(b->buf + b->len, s, n);
|
||||
b->len += n;
|
||||
b->buf[b->len] = '\0';
|
||||
return true;
|
||||
}
|
||||
|
||||
static void type_scope_on_name(const char *name, size_t len, void *ud) {
|
||||
type_scope_build_t *b = (type_scope_build_t *)ud;
|
||||
if (b->failed || type_scope_seen(b->file, name, len)) {
|
||||
return;
|
||||
}
|
||||
if (b->file->lang->lexical_scopes && type_scope_shadowed(b->file, name, len)) {
|
||||
return;
|
||||
}
|
||||
const char *qn = cbm_type_scope_resolve(b->file, name, len);
|
||||
if (!qn) {
|
||||
return;
|
||||
}
|
||||
if (b->file->lang->engine_qualifies_own_module) {
|
||||
/* The engine already qualifies this spelling to exactly this QN. */
|
||||
const char *mod = b->file->scope.module_qn;
|
||||
size_t ml = strlen(mod);
|
||||
if (strncmp(qn, mod, ml) == 0 && qn[ml] == '.' && strlen(qn + ml + 1) == len &&
|
||||
memcmp(qn + ml + 1, name, len) == 0) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if ((b->len && !type_scope_append(b, "|", 1)) || !type_scope_append(b, name, len) ||
|
||||
!type_scope_append(b, "=", 1) || !type_scope_append(b, qn, strlen(qn))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* Each '|'-separated piece of `text`; with after_colon, only the part after
|
||||
* the first ':' of each piece (field_defs' "name:type"). */
|
||||
static void type_scope_scan_pieces(type_scope_build_t *b, const char *text, bool after_colon) {
|
||||
if (!text || !text[0]) {
|
||||
return;
|
||||
}
|
||||
size_t n = strlen(text);
|
||||
char *copy = cbm_arena_strndup(&b->file->keys, text, n);
|
||||
if (!copy) {
|
||||
return;
|
||||
}
|
||||
char *piece = copy;
|
||||
for (size_t i = 0; i <= n; i++) {
|
||||
if (copy[i] != '|' && copy[i] != '\0') {
|
||||
continue;
|
||||
}
|
||||
copy[i] = '\0';
|
||||
const char *t = piece;
|
||||
if (after_colon) {
|
||||
const char *colon = strchr(piece, ':');
|
||||
t = colon ? colon + 1 : NULL;
|
||||
}
|
||||
if (t && t[0]) {
|
||||
type_scope_names(b->file->lang, t, type_scope_on_name, b);
|
||||
}
|
||||
piece = copy + i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def) {
|
||||
if (!file || !arena || !def) {
|
||||
return;
|
||||
}
|
||||
const cbm_type_scope_lang_t *lang = file->lang;
|
||||
file->serial++;
|
||||
file->enclosing_class = NULL;
|
||||
if (lang->lexical_scopes) {
|
||||
/* A module whose bindings cannot be listed (a star import, an effect
|
||||
* binding unknown names), and a def inside a function (it sees locals
|
||||
* the step cannot list): neither gets one. */
|
||||
if (file->closed || !def->qualified_name ||
|
||||
type_scope_function_local(file, def->qualified_name) ||
|
||||
cbm_ht_get(file->overloaded, def->qualified_name) == TYPE_SCOPE_OVERLOAD_DIFFER) {
|
||||
return; /* (an overloaded function: type_scope_index_overload) */
|
||||
}
|
||||
file->enclosing_class = type_scope_enclosing_class(file, def->qualified_name);
|
||||
}
|
||||
type_scope_build_t b = {.file = file};
|
||||
if (lang->return_types) {
|
||||
type_scope_scan_pieces(&b, def->return_types, false);
|
||||
}
|
||||
if (lang->param_types && def->signature_param_types) {
|
||||
for (int i = 0; i < def->signature_param_count; i++) {
|
||||
const char *t = def->signature_param_types[i];
|
||||
if (t && strcmp(t, "?") != 0) {
|
||||
type_scope_names(lang, t, type_scope_on_name, &b);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lang->field_types) {
|
||||
type_scope_scan_pieces(&b, def->field_defs, true);
|
||||
}
|
||||
if (lang->embedded_types) {
|
||||
type_scope_scan_pieces(&b, def->embedded_types, false);
|
||||
}
|
||||
if (b.len > 0 && !b.failed) {
|
||||
def->type_scope = cbm_arena_strndup(arena, b.buf, b.len);
|
||||
}
|
||||
cbm_free(CBM_MEM_CLASS_EXTRACT, b.buf);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/*
|
||||
* type_scope.h — declared types resolved once, in the scope that wrote them.
|
||||
*
|
||||
* A definition's declared types (its return type, parameter types, field
|
||||
* types) travel to other files as source text inside CBMLSPDef. Each engine
|
||||
* used to qualify that text against the defining MODULE only, so a type the
|
||||
* defining file imported from a third file became `<defining module>.<Name>`,
|
||||
* a name nobody registered, and every call through it was lost.
|
||||
*
|
||||
* This step resolves every type name such a text mentions ONCE, in the scope
|
||||
* of the file that wrote it: the file's own module, then what its imports
|
||||
* bind. A name gets an identity only when that scope gives exactly one answer
|
||||
* and that answer is a project definition of a type label the consuming
|
||||
* engine registers. A name that is not found, is ambiguous, is shadowed by a
|
||||
* scope the step cannot see into, or is bound to anything outside the project
|
||||
* keeps no identity, and the engine keeps doing what it did before. There is
|
||||
* no project-wide name match here.
|
||||
*
|
||||
* The result is stored with the definition (CBMLSPDef.type_scope, persisted in
|
||||
* the file's LSP surface) as "spelling=QN|spelling=QN", the spelling exactly
|
||||
* as the type text writes it. Only identities the engine cannot derive itself
|
||||
* are stored: where the engine already qualifies a bare name to
|
||||
* `<module>.<spelling>`, a name the file's own module declares is left out.
|
||||
* The engines read an identity through cbm_type_scope_find (lsp/type_rep.h)
|
||||
* wherever they would otherwise qualify a type name against the module.
|
||||
*
|
||||
* An identity depends on two inputs: the writing file's own content (its type
|
||||
* texts, its imports, its module) and which project definitions are types.
|
||||
* The surface hash covers the first and leaves the identities themselves out;
|
||||
* the incremental planner declines a repair whenever the second changes
|
||||
* (pipeline_incremental.c, closure_identity_decline).
|
||||
*
|
||||
* What is language-specific is a description (cbm_type_scope_lang_t): which
|
||||
* definition labels an identity may name, how the language's imports and
|
||||
* scopes bind names, and which CBMLSPDef fields carry raw type text for that
|
||||
* language. A further language plugs in by adding its row.
|
||||
*/
|
||||
#ifndef CBM_PIPELINE_TYPE_SCOPE_H
|
||||
#define CBM_PIPELINE_TYPE_SCOPE_H
|
||||
|
||||
#include "cbm.h"
|
||||
#include "foundation/arena.h"
|
||||
#include "foundation/hash_table.h"
|
||||
#include "lsp/go_lsp.h" /* CBMLSPDef */
|
||||
#include "pipeline/pipeline.h"
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
|
||||
/* How one language writes type names, and what its engine consumes. */
|
||||
typedef struct {
|
||||
CBMLanguage lang;
|
||||
/* A name inside quotes is a type name (Python forward references); in
|
||||
* every other language a quoted run is a literal and is skipped. */
|
||||
bool quoted_names;
|
||||
/* Labels of the definitions an identity may name: the type kinds the
|
||||
* engine registers and can look members up on. NULL-terminated. */
|
||||
const char *const *labels;
|
||||
/* The engine qualifies a bare name against the defining module itself
|
||||
* (Go), so an own-module identity need not be stored. Python's cross
|
||||
* registrar keeps the bare spelling: it is stored there. */
|
||||
bool engine_qualifies_own_module;
|
||||
/* An import binds a module only (Go: a package), so only a qualified
|
||||
* `pkg.T` resolves through it and a bare name never does. Without it
|
||||
* (Python) `from m import T` binds the type itself. */
|
||||
bool imports_bind_modules;
|
||||
/* Python: an annotation is evaluated in the def's enclosing scopes before
|
||||
* the module. A def nested in a function sees that function's locals,
|
||||
* which the step cannot list, so it gets no identity; a name the
|
||||
* immediately enclosing class body declares or binds (any binding:
|
||||
* CBMDefTypeFacts.class_bindings) and a PEP 695 type parameter of the
|
||||
* file get none, and neither does a name the module binds more than once
|
||||
* (cbm_type_scope_t.module_facts), nor a type whose QN the graph holds as
|
||||
* a module (a class `Thing` in pkg/a/__init__.py beside pkg/a/Thing.py:
|
||||
* their members share QNs, so no member answer is that class's). */
|
||||
bool lexical_scopes;
|
||||
/* Which CBMLSPDef texts hold raw type spellings for this language. */
|
||||
bool return_types;
|
||||
bool param_types;
|
||||
bool field_types; /* "name:type|name:type" in field_defs */
|
||||
bool embedded_types; /* "|"-joined raw spellings in embedded_types */
|
||||
} cbm_type_scope_lang_t;
|
||||
|
||||
/* The description for `lang`, or NULL when no engine consumes identities. */
|
||||
const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang);
|
||||
|
||||
/* One file's scope: the project's names, the file's module, what the file's
|
||||
* imports bind (local name -> import QN, the LSP import map), and for a row
|
||||
* with lexical_scopes the file's own definitions. */
|
||||
typedef struct {
|
||||
const cbm_registry_t *reg;
|
||||
const char *module_qn;
|
||||
const char *const *imp_keys;
|
||||
const char *const *imp_vals;
|
||||
int imp_count;
|
||||
/* lexical_scopes only: the file's extraction definitions, in any order
|
||||
* (their QNs, labels and type facts); NULL with def_count 0 = none. */
|
||||
const CBMDefinition *file_defs;
|
||||
int file_def_count;
|
||||
/* lexical_scopes only: the module's ordered namespace facts. Without a
|
||||
* complete record, with a star import or with a parse error the file gets
|
||||
* no identity; a name the module binds twice (two imports, an import and
|
||||
* a definition, a later assignment) gets none. */
|
||||
const CBMPyNamespaceFacts *module_facts;
|
||||
/* lexical_scopes only: the graph the import map reads (its nodes'
|
||||
* labels), so a QN that is a module's gets no identity; NULL = not
|
||||
* checked. */
|
||||
const struct cbm_gbuf *graph;
|
||||
} cbm_type_scope_t;
|
||||
|
||||
/* Per-file working state: the import map by key, the file's own scopes, and
|
||||
* a memo of the spellings already resolved. Build once per file, free after
|
||||
* the file's defs. */
|
||||
typedef struct cbm_type_scope_file cbm_type_scope_file_t;
|
||||
|
||||
cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang,
|
||||
const cbm_type_scope_t *scope);
|
||||
void cbm_type_scope_file_end(cbm_type_scope_file_t *file);
|
||||
|
||||
/* The identity of one spelling (`T`, `pkg.T`) in the file's module and import
|
||||
* scope, or NULL (the def's own enclosing scopes are applied by the attach).
|
||||
* The returned QN is owned by the file state (valid until file_end). Never a
|
||||
* short-name guess. */
|
||||
const char *cbm_type_scope_resolve(cbm_type_scope_file_t *file, const char *spelling, size_t len);
|
||||
|
||||
/* Set def->type_scope from the def's type texts (per the description), or
|
||||
* leave it NULL when no name the def writes needs an identity. The string is
|
||||
* allocated in `arena`. */
|
||||
void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def);
|
||||
|
||||
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
|
||||
/* Work counter for the growth tests: one per byte of type text scanned, per
|
||||
* hash probe and per enclosing-scope step. Test builds only. */
|
||||
uint64_t cbm_type_scope_test_work(void);
|
||||
#endif
|
||||
|
||||
#endif /* CBM_PIPELINE_TYPE_SCOPE_H */
|
||||
+11
-6
@@ -428,6 +428,7 @@ static int init_schema(cbm_store_t *s) {
|
||||
" defs_json TEXT NOT NULL,"
|
||||
" ref_bloom BLOB,"
|
||||
" config_ctx TEXT NOT NULL DEFAULT '',"
|
||||
" included_files TEXT NOT NULL DEFAULT '',"
|
||||
" PRIMARY KEY (project, rel_path)"
|
||||
");"
|
||||
/* Best-effort indexing-coverage signal (#963). One row per file the
|
||||
@@ -6551,11 +6552,11 @@ int cbm_store_upsert_file_hash_batch(cbm_store_t *s, const cbm_file_hash_t *hash
|
||||
|
||||
static int upsert_lsp_surface_row(cbm_store_t *s, const cbm_lsp_surface_row_t *row) {
|
||||
const char *sql =
|
||||
"INSERT INTO lsp_surface (project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx)"
|
||||
" VALUES (?1, ?2, ?3, ?4, ?5, ?6)"
|
||||
"INSERT INTO lsp_surface (project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx,"
|
||||
" included_files) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"
|
||||
" ON CONFLICT(project, rel_path) DO UPDATE SET surface_sha = excluded.surface_sha,"
|
||||
" defs_json = excluded.defs_json, ref_bloom = excluded.ref_bloom,"
|
||||
" config_ctx = excluded.config_ctx";
|
||||
" config_ctx = excluded.config_ctx, included_files = excluded.included_files";
|
||||
sqlite3_stmt *stmt = NULL;
|
||||
if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
|
||||
store_set_error_sqlite(s, "lsp_surface upsert prepare");
|
||||
@@ -6571,6 +6572,7 @@ static int upsert_lsp_surface_row(cbm_store_t *s, const cbm_lsp_surface_row_t *r
|
||||
sqlite3_bind_null(stmt, ST_COL_5);
|
||||
}
|
||||
bind_text(stmt, ST_COL_6, row->config_ctx ? row->config_ctx : "");
|
||||
bind_text(stmt, ST_COL_7, row->included_files ? row->included_files : "");
|
||||
int rc = sqlite3_step(stmt);
|
||||
sqlite3_finalize(stmt);
|
||||
if (rc != SQLITE_DONE) {
|
||||
@@ -6606,8 +6608,8 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf
|
||||
int *count) {
|
||||
*out = NULL;
|
||||
*count = 0;
|
||||
const char *sql = "SELECT project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx"
|
||||
" FROM lsp_surface WHERE project = ?1 ORDER BY rel_path";
|
||||
const char *sql = "SELECT project, rel_path, surface_sha, defs_json, ref_bloom, config_ctx,"
|
||||
" included_files FROM lsp_surface WHERE project = ?1 ORDER BY rel_path";
|
||||
sqlite3_stmt *stmt = NULL;
|
||||
if (sqlite3_prepare_v2(s->db, sql, CBM_NOT_FOUND, &stmt, NULL) != SQLITE_OK) {
|
||||
store_set_error_sqlite(s, "lsp_surface get prepare");
|
||||
@@ -6644,11 +6646,13 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf
|
||||
const void *bloom = sqlite3_column_blob(stmt, ST_COL_4);
|
||||
int bloom_len = sqlite3_column_bytes(stmt, ST_COL_4);
|
||||
const char *cfg = (const char *)sqlite3_column_text(stmt, ST_COL_5);
|
||||
const char *inc = (const char *)sqlite3_column_text(stmt, ST_COL_6);
|
||||
r->project = strdup(proj ? proj : "");
|
||||
r->rel_path = strdup(rel ? rel : "");
|
||||
r->surface_sha = strdup(sha ? sha : "");
|
||||
r->defs_json = strdup(defs ? defs : "[]");
|
||||
r->config_ctx = strdup(cfg ? cfg : "");
|
||||
r->included_files = strdup(inc ? inc : "");
|
||||
if (bloom && bloom_len > 0) {
|
||||
void *copy = malloc((size_t)bloom_len);
|
||||
if (copy) {
|
||||
@@ -6658,7 +6662,7 @@ int cbm_store_get_lsp_surfaces(cbm_store_t *s, const char *project, cbm_lsp_surf
|
||||
}
|
||||
}
|
||||
if (!r->project || !r->rel_path || !r->surface_sha || !r->defs_json || !r->config_ctx ||
|
||||
(bloom && bloom_len > 0 && !r->ref_bloom)) {
|
||||
!r->included_files || (bloom && bloom_len > 0 && !r->ref_bloom)) {
|
||||
n++; /* count the partial row so the free below releases it */
|
||||
oom = true;
|
||||
break;
|
||||
@@ -6707,6 +6711,7 @@ void cbm_store_free_lsp_surfaces(cbm_lsp_surface_row_t *rows, int count) {
|
||||
free((void *)rows[i].defs_json);
|
||||
free((void *)rows[i].ref_bloom);
|
||||
free((void *)rows[i].config_ctx);
|
||||
free((void *)rows[i].included_files);
|
||||
}
|
||||
free(rows);
|
||||
}
|
||||
|
||||
+10
-2
@@ -39,8 +39,11 @@ typedef struct cbm_store_read_scope cbm_store_read_scope_t;
|
||||
* 6 #2360: File nodes record their declared package clause (`package`
|
||||
* property); an incremental run reads it back to build the namespace
|
||||
* map and the Scala top-level index for the files it does not
|
||||
* re-extract. */
|
||||
#define CBM_INDEX_FORMAT_VERSION 6
|
||||
* re-extract.
|
||||
* 7 #2993: lsp_surface rows record the repository files a C-family file's
|
||||
* #include lookup read (`included_files`); an incremental run
|
||||
* re-extracts the file when one of them changes. */
|
||||
#define CBM_INDEX_FORMAT_VERSION 7
|
||||
#define CBM_STORE_CANCELLED (-3)
|
||||
#define CBM_STORE_SCAN_LIMIT (-4)
|
||||
#define CBM_STORE_CALLBACK_ERR (-5)
|
||||
@@ -113,6 +116,11 @@ typedef struct {
|
||||
const void *ref_bloom; /* referenced-identifier bloom blob (may be NULL) */
|
||||
int ref_bloom_len;
|
||||
const char *config_ctx; /* governing-config context hash ("" = none) */
|
||||
/* The repository files the file's C-family #include lookup read
|
||||
* (CBMFileResult.included_files): sorted, one per line, "" = none. Not part
|
||||
* of the surface: an incremental run re-extracts the file when one of
|
||||
* them changes. */
|
||||
const char *included_files;
|
||||
} cbm_lsp_surface_row_t;
|
||||
|
||||
/* The definition variants that lie in a file (graph_buffer.c "Definition
|
||||
|
||||
@@ -42,8 +42,8 @@ static const sc_query_t sc_queries[] = {
|
||||
"(SELECT 1 FROM main.nodes n WHERE n.id=e.target_id));"},
|
||||
{"file_hashes", "SELECT rel_path,sha256,size FROM main.file_hashes WHERE project=?1 "
|
||||
"ORDER BY 1,2,3;"},
|
||||
{"lsp_surface", "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM "
|
||||
"main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5;"},
|
||||
{"lsp_surface", "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx,included_files "
|
||||
"FROM main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5,6;"},
|
||||
{"index_coverage", "SELECT rel_path,kind,detail FROM main.index_coverage WHERE project=?1 "
|
||||
"ORDER BY 1,2,3;"},
|
||||
{"index_coverage_meta",
|
||||
@@ -87,6 +87,22 @@ static void sc_frame(cbm_sha256_ctx *ctx, unsigned char tag, const void *bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/* Read-only legacy databases retain their existing content digest: a table
|
||||
* that gained a column is read with its earlier query when the column is
|
||||
* absent. NULL for tables without an earlier shape. */
|
||||
static const char *sc_legacy_query(const char *name) {
|
||||
if (strcmp(name, "index_coverage_meta") == 0) {
|
||||
return "SELECT index_mode,recording_status,ignored_files_stored,"
|
||||
"ignored_files_total,coverage_version,hash_records_complete FROM "
|
||||
"main.index_coverage_meta WHERE project=?1;";
|
||||
}
|
||||
if (strcmp(name, "lsp_surface") == 0) {
|
||||
return "SELECT rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM "
|
||||
"main.lsp_surface WHERE project=?1 ORDER BY 1,2,3,4,5;";
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static bool sc_table(sqlite3 *db, const sc_query_t *q, const char *project, cbm_sha256_ctx *ctx) {
|
||||
sqlite3_stmt *st = NULL;
|
||||
if (sqlite3_prepare_v2(db, q->sql, -1, &st, NULL) != SQLITE_OK) {
|
||||
@@ -105,13 +121,8 @@ static bool sc_table(sqlite3 *db, const sc_query_t *q, const char *project, cbm_
|
||||
sqlite3_step(schema) == SQLITE_DONE;
|
||||
return sqlite3_finalize(schema) == SQLITE_OK && absent;
|
||||
}
|
||||
/* Read-only legacy databases retain their existing content digest. */
|
||||
if (strcmp(q->name, "index_coverage_meta") != 0 ||
|
||||
sqlite3_prepare_v2(db,
|
||||
"SELECT index_mode,recording_status,ignored_files_stored,"
|
||||
"ignored_files_total,coverage_version,hash_records_complete FROM "
|
||||
"main.index_coverage_meta WHERE project=?1;",
|
||||
SC_SQL_TEXT_LENGTH, &st, NULL) != SQLITE_OK) {
|
||||
const char *legacy = sc_legacy_query(q->name);
|
||||
if (!legacy || sqlite3_prepare_v2(db, legacy, SC_SQL_TEXT_LENGTH, &st, NULL) != SQLITE_OK) {
|
||||
sqlite3_finalize(st);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ enum {
|
||||
GD_ALLOW_BLOB = 1 << GD_BLOB,
|
||||
GD_TABLE_COUNT = 10,
|
||||
GD_MAX_COLUMNS = 10,
|
||||
GD_LSP_SURFACE = 5,
|
||||
GD_COVERAGE_META = 7,
|
||||
GD_STORE_META = 8,
|
||||
GD_UNRESOLVED_CANDIDATES = 9,
|
||||
@@ -78,8 +79,9 @@ static const gd_column_t gd_project_summaries[] = {{"project", GD_T, 0, 1},
|
||||
{"created_at", GD_T, 0, 0},
|
||||
{"updated_at", GD_T, 0, 0}};
|
||||
static const gd_column_t gd_lsp_surface[] = {
|
||||
{"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0},
|
||||
{"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0}, {"config_ctx", GD_T, 0, 0}};
|
||||
{"project", GD_T, 0, 1}, {"rel_path", GD_T, 0, 2}, {"surface_sha", GD_T, 0, 0},
|
||||
{"defs_json", GD_T, 0, 0}, {"ref_bloom", GD_B | GD_N, 0, 0}, {"config_ctx", GD_T, 0, 0},
|
||||
{"included_files", GD_T, 0, 0}};
|
||||
static const gd_column_t gd_index_coverage[] = {{"project", GD_T, 0, 1},
|
||||
{"rel_path", GD_T, 0, 2},
|
||||
{"kind", GD_T, 0, 3},
|
||||
@@ -119,7 +121,7 @@ static const gd_table_t gd_tables[GD_TABLE_COUNT] = {
|
||||
"PRAGMA main.table_xinfo('project_summaries');",
|
||||
"SELECT project,summary,source_hash,created_at,updated_at FROM main.project_summaries "
|
||||
"ORDER BY CAST(project AS BLOB) ASC;"},
|
||||
{"lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface),
|
||||
{"lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface) - 1,
|
||||
"PRAGMA main.table_xinfo('lsp_surface');",
|
||||
"SELECT project,rel_path,surface_sha,defs_json,ref_bloom,config_ctx FROM main.lsp_surface "
|
||||
"ORDER BY CAST(project AS BLOB) ASC,CAST(rel_path AS BLOB) ASC;"},
|
||||
@@ -150,6 +152,14 @@ static const gd_table_t gd_coverage_meta_current = {
|
||||
"ignored_files_total,coverage_version,hash_records_complete,unresolved_calls_complete "
|
||||
"FROM main.index_coverage_meta ORDER BY CAST(project AS BLOB) ASC;"};
|
||||
|
||||
/* The same for lsp_surface: index format 7 records the files each C-family
|
||||
* file's #include lookup read (`included_files`). */
|
||||
static const gd_table_t gd_lsp_surface_current = {
|
||||
"lsp_surface", gd_lsp_surface, GD_COLUMNS(gd_lsp_surface),
|
||||
"PRAGMA main.table_xinfo('lsp_surface');",
|
||||
"SELECT project,rel_path,surface_sha,defs_json,ref_bloom,config_ctx,included_files "
|
||||
"FROM main.lsp_surface ORDER BY CAST(project AS BLOB) ASC,CAST(rel_path AS BLOB) ASC;"};
|
||||
|
||||
#undef GD_B
|
||||
#undef GD_N
|
||||
#undef GD_T
|
||||
@@ -168,11 +178,28 @@ typedef struct {
|
||||
bool have_uid;
|
||||
bool have_counter;
|
||||
bool have_unresolved_completeness;
|
||||
bool have_included_files;
|
||||
} gd_context_t;
|
||||
|
||||
static const gd_table_t *gd_table(const gd_context_t *g, int index) {
|
||||
return index == GD_COVERAGE_META && g->have_unresolved_completeness ? &gd_coverage_meta_current
|
||||
: &gd_tables[index];
|
||||
if (index == GD_COVERAGE_META && g->have_unresolved_completeness) {
|
||||
return &gd_coverage_meta_current;
|
||||
}
|
||||
if (index == GD_LSP_SURFACE && g->have_included_files) {
|
||||
return &gd_lsp_surface_current;
|
||||
}
|
||||
return &gd_tables[index];
|
||||
}
|
||||
|
||||
/* The newest schema a table may have, when it has a legacy one too. */
|
||||
static const gd_table_t *gd_current_table(const gd_table_t *table) {
|
||||
if (table == &gd_tables[GD_COVERAGE_META]) {
|
||||
return &gd_coverage_meta_current;
|
||||
}
|
||||
if (table == &gd_tables[GD_LSP_SURFACE]) {
|
||||
return &gd_lsp_surface_current;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
@@ -460,9 +487,8 @@ static bool gd_column_schema(gd_context_t *g, const gd_column_t *expected) {
|
||||
|
||||
static bool gd_columns(gd_context_t *g, const gd_table_t *table) {
|
||||
bool seen[GD_MAX_COLUMNS] = {false};
|
||||
bool coverage_meta = table == &gd_tables[GD_COVERAGE_META];
|
||||
int allowed_columns =
|
||||
coverage_meta ? gd_coverage_meta_current.column_count : table->column_count;
|
||||
const gd_table_t *current = gd_current_table(table);
|
||||
int allowed_columns = current ? current->column_count : table->column_count;
|
||||
if (!gd_prepare(g, table->column_query)) {
|
||||
return false;
|
||||
}
|
||||
@@ -498,9 +524,12 @@ static bool gd_columns(gd_context_t *g, const gd_table_t *table) {
|
||||
return gd_fail(g, CBM_STORE_GRAPH_DIGEST_SCHEMA);
|
||||
}
|
||||
}
|
||||
if (coverage_meta) {
|
||||
if (table == &gd_tables[GD_COVERAGE_META]) {
|
||||
g->have_unresolved_completeness = seen[table->column_count];
|
||||
}
|
||||
if (table == &gd_tables[GD_LSP_SURFACE]) {
|
||||
g->have_included_files = seen[table->column_count];
|
||||
}
|
||||
return gd_finalize(g);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* image_probe_main.c — entry point of the image probe (tests/test_image_probe.h),
|
||||
* the small executable that copied-image and install tests run instead of the
|
||||
* test runner. Its roles live in tests/image_probe_roles.c.
|
||||
*/
|
||||
#include "test_image_probe.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#if defined(__has_feature)
|
||||
#if __has_feature(memory_sanitizer)
|
||||
#define PROBE_MSAN_MIMALLOC_OUTPUT 1
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef PROBE_MSAN_MIMALLOC_OUTPUT
|
||||
#include <mimalloc.h>
|
||||
#include <sanitizer/msan_interface.h>
|
||||
|
||||
/* MSan lane only, exactly as the runner's tf_msan_mi_output (tests/test_main.c):
|
||||
* mimalloc is uninstrumented there, so text it formats on its own stack must
|
||||
* be marked initialized before it reaches an MSan interceptor. */
|
||||
static bool probe_msan_mi_output_live;
|
||||
|
||||
static void probe_msan_mi_output(const char *msg, void *arg) {
|
||||
(void)arg;
|
||||
if (!probe_msan_mi_output_live || !msg) {
|
||||
return;
|
||||
}
|
||||
__msan_unpoison_string(msg);
|
||||
if (!msg[0]) {
|
||||
return;
|
||||
}
|
||||
(void)fputs(msg, stderr);
|
||||
}
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
#ifdef PROBE_MSAN_MIMALLOC_OUTPUT
|
||||
mi_register_output(probe_msan_mi_output, NULL);
|
||||
probe_msan_mi_output_live = true;
|
||||
#endif
|
||||
/* An install verifies the candidate it staged by running it with
|
||||
* --version (src/cli/cli.c); the probe stands in for that binary. */
|
||||
if (argc == 2 && strcmp(argv[1], "--version") == 0) {
|
||||
(void)puts("codebase-memory-mcp test image probe");
|
||||
return 0;
|
||||
}
|
||||
int role_rc = tf_image_probe_dispatch(argc, argv);
|
||||
if (role_rc >= 0) {
|
||||
return role_rc;
|
||||
}
|
||||
(void)fprintf(stderr, "image probe: no role named by argv[1] (tests/test_image_probe.h)\n");
|
||||
return 2;
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
/*
|
||||
* image_probe_roles.c — the roles of the image probe (tests/test_image_probe.h).
|
||||
*
|
||||
* Linked into the probe (tests/image_probe_main.c) and into the test runner.
|
||||
* The runner dispatches only the image holder from here (daemon_runtime's
|
||||
* own-image cache test spawns the runner itself); its role table in
|
||||
* tests/test_main.c names every other literal too, so that the test-impact
|
||||
* engine still maps a change these roles reach to the tests that start them.
|
||||
* Every role is called directly from tf_image_probe_dispatch for the same
|
||||
* reason: a call edge, not a function-pointer table, links them.
|
||||
*
|
||||
* Exit codes: 0 success; 24/25 holder failures; 26 the daemon ANSWERED a HELLO
|
||||
* and refused it; 27 the HELLO session did not close; 28 the macOS mapping
|
||||
* failed; 29 the daemon answered an activation request and refused it; 30/31 a
|
||||
* HELLO/activation that got no answer inside the exchange budget (a slow peer
|
||||
* hash fails as itself, never as a refusal); 32 bad serve arguments; 33 the
|
||||
* served daemon did not start; 34 its teardown failed.
|
||||
*/
|
||||
#include "test_image_probe.h"
|
||||
#include "test_daemon_runtime_contract.h"
|
||||
|
||||
#include "daemon/daemon.h"
|
||||
#include "daemon/ipc.h"
|
||||
#include "daemon/runtime.h"
|
||||
#include "foundation/compat.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#ifdef __APPLE__
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
enum {
|
||||
/* The in-process daemon_runtime fixture's bounds (RUNTIME_TEST_TIMEOUT_MS,
|
||||
* RUNTIME_TEST_CLEANUP_TIMEOUT_MS, RUNTIME_TEST_CLEANUP_FREE_ATTEMPTS):
|
||||
* the served daemon behaves exactly like that fixture's. */
|
||||
PROBE_TIMEOUT_MS = 2000,
|
||||
PROBE_CLEANUP_TIMEOUT_MS = 60000,
|
||||
PROBE_CLEANUP_FREE_ATTEMPTS = 3,
|
||||
PROBE_PATH_CAP = 1024,
|
||||
};
|
||||
|
||||
static uint64_t probe_process_id(void) {
|
||||
#ifdef _WIN32
|
||||
return (uint64_t)GetCurrentProcessId();
|
||||
#else
|
||||
return (uint64_t)getpid();
|
||||
#endif
|
||||
}
|
||||
|
||||
static int probe_role_holder(int argc, char **argv) {
|
||||
#ifdef _WIN32
|
||||
if (argc != 3) {
|
||||
return -1;
|
||||
}
|
||||
HANDLE ready = OpenEventA(EVENT_MODIFY_STATE, FALSE, argv[2]);
|
||||
bool announced = ready && SetEvent(ready) != 0;
|
||||
if (ready) {
|
||||
(void)CloseHandle(ready);
|
||||
}
|
||||
if (!announced) {
|
||||
return 24;
|
||||
}
|
||||
Sleep(INFINITE);
|
||||
return 25;
|
||||
#else
|
||||
/* POSIX copied-image holder: block reading stdin until the parent closes
|
||||
* the release pipe, exactly like the cat(1) donor this replaced. A system
|
||||
* utility cannot serve as the copied image — a multi-call coreutils
|
||||
* binary (uutils cat) refuses to execute under the copied name. */
|
||||
(void)argv;
|
||||
if (argc != 2) {
|
||||
return -1;
|
||||
}
|
||||
char release[16];
|
||||
ssize_t count;
|
||||
do {
|
||||
count = read(STDIN_FILENO, release, sizeof(release));
|
||||
} while (count > 0 || (count < 0 && errno == EINTR));
|
||||
return count == 0 ? 0 : 25;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Real copied-image HELLO probe: the daemon authenticates and fingerprints an
|
||||
* ordinary, separately executed process image; no production-only hook. */
|
||||
static int probe_role_hello(int argc, char **argv) {
|
||||
if (argc != 6) {
|
||||
return -1;
|
||||
}
|
||||
cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]);
|
||||
cbm_daemon_build_identity_t identity = {
|
||||
.semantic_version = argv[4],
|
||||
.build_fingerprint = argv[5],
|
||||
};
|
||||
cbm_daemon_runtime_connect_result_t result;
|
||||
memset(&result, 0, sizeof(result));
|
||||
cbm_daemon_runtime_client_t *client =
|
||||
endpoint ? cbm_daemon_runtime_client_connect(endpoint, &identity,
|
||||
TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result)
|
||||
: NULL;
|
||||
bool accepted = client && result.status == CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED &&
|
||||
result.hello_status == CBM_DAEMON_HELLO_COMPATIBLE;
|
||||
bool closed =
|
||||
!client || cbm_daemon_runtime_client_close(client, TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS);
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
if (!accepted) {
|
||||
/* 26 only when the daemon ANSWERED and refused. No answer inside the
|
||||
* exchange budget (the daemon still hashing this copy, or I/O) is 30:
|
||||
* a slow peer-image hash must fail loudly as itself, never satisfy a
|
||||
* rejection assertion by timing out. */
|
||||
return result.status == CBM_DAEMON_RUNTIME_CONNECT_ERROR ? 30 : 26;
|
||||
}
|
||||
return closed ? 0 : 27;
|
||||
}
|
||||
|
||||
/* Real copied-image activation probe. The request identity is supplied by the
|
||||
* executing copy so the daemon must authenticate that peer image rather than
|
||||
* require the active generation's build fingerprint. */
|
||||
static int probe_role_activation(int argc, char **argv) {
|
||||
if (argc != 7) {
|
||||
return -1;
|
||||
}
|
||||
char *action_end = NULL;
|
||||
unsigned long action_value = strtoul(argv[6], &action_end, 10);
|
||||
bool action_valid = action_end != argv[6] && *action_end == '\0' &&
|
||||
action_value >= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL &&
|
||||
action_value <= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL;
|
||||
cbm_daemon_ipc_endpoint_t *endpoint =
|
||||
action_valid ? cbm_daemon_ipc_endpoint_new(argv[3], argv[2]) : NULL;
|
||||
cbm_daemon_build_identity_t identity = {
|
||||
.semantic_version = argv[4],
|
||||
.build_fingerprint = argv[5],
|
||||
};
|
||||
cbm_daemon_runtime_activation_result_t result;
|
||||
memset(&result, 0, sizeof(result));
|
||||
bool exchanged =
|
||||
endpoint && cbm_daemon_runtime_request_activation_shutdown(
|
||||
endpoint, &identity, (cbm_daemon_runtime_activation_action_t)action_value,
|
||||
TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result);
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
if (!exchanged) {
|
||||
return 31; /* no answer inside the exchange budget; see the HELLO probe */
|
||||
}
|
||||
return result.accepted ? 0 : 29;
|
||||
}
|
||||
|
||||
/* macOS adversarial HELLO probe: execute this mode from a foreign process
|
||||
* image while mapping the genuine daemon image RX. The daemon must
|
||||
* authenticate the main image, not merely find its own vnode in an arbitrary
|
||||
* executable map. */
|
||||
static int probe_role_mapped_hello(int argc, char **argv) {
|
||||
#ifdef __APPLE__
|
||||
if (argc != 7) {
|
||||
return -1;
|
||||
}
|
||||
int image_fd = open(argv[2], O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
void *mapping =
|
||||
image_fd >= 0 ? mmap(NULL, 1, PROT_READ | PROT_EXEC, MAP_PRIVATE, image_fd, 0) : MAP_FAILED;
|
||||
bool mapped = mapping != MAP_FAILED;
|
||||
if (image_fd >= 0 && close(image_fd) != 0) {
|
||||
mapped = false;
|
||||
}
|
||||
if (!mapped) {
|
||||
if (mapping != MAP_FAILED) {
|
||||
(void)munmap(mapping, 1);
|
||||
}
|
||||
return 28;
|
||||
}
|
||||
|
||||
char *hello_argv[] = {argv[0], "__cbm_runtime_hello_client", argv[3], argv[4], argv[5],
|
||||
argv[6]};
|
||||
int result = probe_role_hello(6, hello_argv);
|
||||
if (munmap(mapping, 1) != 0) {
|
||||
return 28;
|
||||
}
|
||||
return result >= 0 ? result : 28;
|
||||
#else
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
return -1;
|
||||
#endif
|
||||
}
|
||||
|
||||
static void probe_reply(const char *line) {
|
||||
(void)fputs(line, stdout);
|
||||
(void)fputc('\n', stdout);
|
||||
(void)fflush(stdout);
|
||||
}
|
||||
|
||||
/* The daemon of the copied-image tests, running from THIS image:
|
||||
* __cbm_runtime_serve <parent> <key> <version> <owner:0|1>
|
||||
* A runtime service starts only with its own image's fingerprint as identity,
|
||||
* so a daemon whose peers are copies of this probe must run here, not in the
|
||||
* runner. The configuration is the in-process daemon_runtime fixture's
|
||||
* (runtime_test_fixture_start, ABIs of runtime_test_identity), and with owner 1
|
||||
* a committed session of the active image is held in this process, like that
|
||||
* fixture's in-process owner client.
|
||||
*
|
||||
* One line answers each step on stdout; commands arrive on stdin, one byte:
|
||||
* start "ready <own fingerprint>" or "failed <stage>"
|
||||
* 'i' "1" when the held owner session was interrupted (its heartbeat
|
||||
* fails), else "0"
|
||||
* 'x' closes the owner session, then "1" when the service has exited by
|
||||
* itself within the fixture's bound, else "0"
|
||||
* EOF the runner's release: stop what still runs, free it, exit.
|
||||
* No step waits on a clock of its own: every bound is the runtime API's, and
|
||||
* the runner closing stdin ends the role. */
|
||||
static int probe_role_serve(int argc, char **argv) {
|
||||
if (argc != 6 || (strcmp(argv[5], "0") != 0 && strcmp(argv[5], "1") != 0)) {
|
||||
return 32;
|
||||
}
|
||||
#ifdef _WIN32
|
||||
/* Exact bytes both ways: no CRLF translation on the protocol pipes. */
|
||||
(void)_setmode(_fileno(stdin), _O_BINARY);
|
||||
(void)_setmode(_fileno(stdout), _O_BINARY);
|
||||
#endif
|
||||
bool with_owner = argv[5][0] == '1';
|
||||
char build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
char log_path[PROBE_PATH_CAP];
|
||||
int log_written = snprintf(log_path, sizeof(log_path), "%s/conflicts.ndjson", argv[2]);
|
||||
cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]);
|
||||
const char *failed = NULL;
|
||||
if (log_written <= 0 || log_written >= (int)sizeof(log_path)) {
|
||||
failed = "conflict-log-path";
|
||||
} else if (!endpoint) {
|
||||
failed = "endpoint";
|
||||
} else if (!cbm_daemon_runtime_process_build_fingerprint(probe_process_id(), build)) {
|
||||
failed = "own-image-fingerprint";
|
||||
}
|
||||
cbm_daemon_build_identity_t identity = {
|
||||
.semantic_version = argv[4],
|
||||
.build_fingerprint = build,
|
||||
.protocol_abi = 3,
|
||||
.store_abi = 11,
|
||||
.feature_abi = 7,
|
||||
};
|
||||
cbm_daemon_runtime_service_t *service = NULL;
|
||||
if (!failed) {
|
||||
cbm_daemon_runtime_service_config_t config = {
|
||||
.endpoint = endpoint,
|
||||
.identity = identity,
|
||||
.conflict_log_path = log_path,
|
||||
.conflict_log_cap_bytes = 64U * 1024U,
|
||||
.max_clients = 8,
|
||||
.lease_timeout_ms = 5000,
|
||||
.request_timeout_ms = PROBE_TIMEOUT_MS,
|
||||
.shutdown_timeout_ms = PROBE_TIMEOUT_MS,
|
||||
};
|
||||
service = cbm_daemon_runtime_service_start(&config);
|
||||
if (!service ||
|
||||
cbm_daemon_runtime_service_state(service) != CBM_DAEMON_RUNTIME_SERVICE_RUNNING) {
|
||||
failed = "service-start";
|
||||
}
|
||||
}
|
||||
cbm_daemon_runtime_client_t *owner = NULL;
|
||||
if (!failed && with_owner) {
|
||||
cbm_daemon_runtime_connect_result_t result;
|
||||
memset(&result, 0, sizeof(result));
|
||||
owner = cbm_daemon_runtime_client_connect(endpoint, &identity, PROBE_TIMEOUT_MS, &result);
|
||||
if (!owner || result.status != CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED) {
|
||||
failed = "owner-connect";
|
||||
}
|
||||
}
|
||||
char line[CBM_DAEMON_BUILD_FINGERPRINT_SIZE + 16];
|
||||
(void)snprintf(line, sizeof(line), "%s %s", failed ? "failed" : "ready",
|
||||
failed ? failed : build);
|
||||
probe_reply(line);
|
||||
|
||||
for (int command = failed ? EOF : getchar(); command != EOF; command = getchar()) {
|
||||
if (command == 'i') {
|
||||
bool interrupted =
|
||||
owner && !cbm_daemon_runtime_client_heartbeat(owner, PROBE_TIMEOUT_MS);
|
||||
probe_reply(interrupted ? "1" : "0");
|
||||
} else if (command == 'x') {
|
||||
if (owner) {
|
||||
(void)cbm_daemon_runtime_client_close(owner, PROBE_TIMEOUT_MS);
|
||||
owner = NULL;
|
||||
}
|
||||
probe_reply(cbm_daemon_runtime_service_wait_exited(service, PROBE_TIMEOUT_MS) ? "1"
|
||||
: "0");
|
||||
}
|
||||
}
|
||||
|
||||
if (owner) {
|
||||
(void)cbm_daemon_runtime_client_close(owner, PROBE_TIMEOUT_MS);
|
||||
}
|
||||
bool freed = service == NULL;
|
||||
if (service) {
|
||||
/* runtime_test_fixture_finish's teardown, unchanged. */
|
||||
bool stopped =
|
||||
cbm_daemon_runtime_service_state(service) == CBM_DAEMON_RUNTIME_SERVICE_EXITED ||
|
||||
cbm_daemon_runtime_service_stop(service, PROBE_CLEANUP_TIMEOUT_MS);
|
||||
for (int attempt = 0; stopped && !freed && attempt < PROBE_CLEANUP_FREE_ATTEMPTS;
|
||||
attempt++) {
|
||||
freed = cbm_daemon_runtime_service_free(service);
|
||||
if (!freed) {
|
||||
cbm_usleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
if (failed) {
|
||||
return 33;
|
||||
}
|
||||
return freed ? 0 : 34;
|
||||
}
|
||||
|
||||
int tf_image_probe_dispatch(int argc, char **argv) {
|
||||
if (argc < 2 || !argv || !argv[1]) {
|
||||
return -1;
|
||||
}
|
||||
const char *role = argv[1];
|
||||
if (strcmp(role, "__cbm_runtime_image_holder") == 0) {
|
||||
return probe_role_holder(argc, argv);
|
||||
}
|
||||
if (strcmp(role, "__cbm_runtime_serve") == 0) {
|
||||
return probe_role_serve(argc, argv);
|
||||
}
|
||||
if (strcmp(role, "__cbm_runtime_hello_client") == 0) {
|
||||
return probe_role_hello(argc, argv);
|
||||
}
|
||||
if (strcmp(role, "__cbm_runtime_activation_client") == 0) {
|
||||
return probe_role_activation(argc, argv);
|
||||
}
|
||||
if (strcmp(role, "__cbm_runtime_mapped_hello_client") == 0) {
|
||||
return probe_role_mapped_hello(argc, argv);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -16903,6 +16903,89 @@ TEST(clsp_issue1527_cross_file_memo_failures_propagate) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1546: the cross entry points get the file as it is on disk and must read a
|
||||
* `\` CR LF string splice the way the per-file extract does. Read raw, the CR
|
||||
* ends the escape, the LF ends the literal, and run() falls into the ERROR
|
||||
* region with its call. LF is the control; per-file, shared-registry and
|
||||
* batch entry each. */
|
||||
TEST(clsp_issue1546_cross_entry_points_read_crlf_string_splice) {
|
||||
static const char *const srcs[2] = {"struct S { int m() { return 1; } };\n"
|
||||
"void Middle()\n"
|
||||
"{\n"
|
||||
" const wchar_t* s = L\"line 0\\r\\n\\\n"
|
||||
"line 1\\r\\n\";\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"void run() { S s; s.m(); }\n",
|
||||
"struct S { int m() { return 1; } };\r\n"
|
||||
"void Middle()\r\n"
|
||||
"{\r\n"
|
||||
" const wchar_t* s = L\"line 0\\r\\n\\\r\n"
|
||||
"line 1\\r\\n\";\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void run() { S s; s.m(); }\r\n"};
|
||||
CBMLSPDef defs[] = {
|
||||
{.qualified_name = "test.S", .short_name = "S", .label = "Class", .lang = CBM_LANG_CPP},
|
||||
{.qualified_name = "test.S.m",
|
||||
.short_name = "m",
|
||||
.label = "Method",
|
||||
.receiver_type = "test.S",
|
||||
.return_types = "int",
|
||||
.lang = CBM_LANG_CPP},
|
||||
};
|
||||
bool resolved[2][3] = {{false}};
|
||||
for (int e = 0; e < 2; e++) {
|
||||
const char *src = srcs[e];
|
||||
int len = (int)strlen(src);
|
||||
for (int mode = 0; mode < 3; mode++) {
|
||||
CBMArena a;
|
||||
cbm_arena_init(&a);
|
||||
CBMTypeRegistry reg;
|
||||
cbm_registry_init(®, &a);
|
||||
reg.fallback = cbm_c_build_cross_registry(&a, defs, 2);
|
||||
CBMResolvedCallArray out = {0};
|
||||
CBMBatchCLSPFile file = {.source = src,
|
||||
.source_len = len,
|
||||
.module_qn = "test",
|
||||
.cpp_mode = true,
|
||||
.defs = defs,
|
||||
.def_count = 2};
|
||||
if (mode == 0) {
|
||||
(void)cbm_run_c_lsp_cross(&a, src, len, "test", true, defs, 2, NULL, NULL, 0, NULL,
|
||||
&out);
|
||||
} else if (mode == 1) {
|
||||
(void)cbm_run_c_lsp_cross_with_registry(&a, src, len, "test", true, ®, NULL,
|
||||
NULL, 0, NULL, &out);
|
||||
} else {
|
||||
(void)cbm_batch_c_lsp_cross(&a, &file, 1, &out);
|
||||
}
|
||||
for (int i = 0; i < out.count; i++) {
|
||||
const CBMResolvedCall *rc = &out.items[i];
|
||||
if (rc->caller_qn && strcmp(rc->caller_qn, "test.run") == 0 && rc->callee_qn &&
|
||||
strcmp(rc->callee_qn, "test.S.m") == 0) {
|
||||
resolved[e][mode] = true;
|
||||
}
|
||||
}
|
||||
cbm_arena_destroy(&a);
|
||||
}
|
||||
}
|
||||
for (int e = 0; e < 2; e++) {
|
||||
for (int mode = 0; mode < 3; mode++) {
|
||||
if (!resolved[e][mode]) {
|
||||
printf(" CRLF splice diagnostic: %s entry %d did not resolve run -> S.m\n",
|
||||
e ? "CRLF" : "LF", mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int e = 0; e < 2; e++) {
|
||||
for (int mode = 0; mode < 3; mode++) {
|
||||
ASSERT_TRUE(resolved[e][mode]);
|
||||
}
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* A chain's LENGTH is not nesting depth (#1527 follow-up). An operator chain
|
||||
* `a + a + ... + a` and a receiver chain `b.a().a()...` are evaluated link by
|
||||
* link, so neither consumes the evaluator's depth guard: the file keeps its
|
||||
@@ -17083,6 +17166,7 @@ SUITE(c_lsp) {
|
||||
RUN_TEST(clsp_issue1527_preprocessed_depth_failure_is_reported);
|
||||
RUN_TEST(registry_issue1527_index_preserves_registration_order);
|
||||
RUN_TEST(clsp_issue1527_cross_file_memo_failures_propagate);
|
||||
RUN_TEST(clsp_issue1546_cross_entry_points_read_crlf_string_splice);
|
||||
RUN_TEST(clsp_issue1527_long_binary_chain_is_not_nesting);
|
||||
RUN_TEST(clsp_issue1527_long_receiver_chain_is_not_nesting);
|
||||
RUN_TEST(clsp_c_reassigned_function_pointer_calls_join_exact_occurrences);
|
||||
|
||||
+62
-20
@@ -13,6 +13,7 @@
|
||||
#include "../src/foundation/compat_thread.h"
|
||||
#include "test_framework.h"
|
||||
#include "test_helpers.h"
|
||||
#include "test_image_probe.h"
|
||||
#include <cli/agent_profiles.h>
|
||||
#include <cli/activation_transaction.h>
|
||||
#include <cli/cli.h>
|
||||
@@ -917,6 +918,25 @@ static int cli_test_cmd_install(int argc, char **argv) {
|
||||
return cli_test_cmd_dispatch(cbm_cmd_install, argc, argv);
|
||||
}
|
||||
|
||||
/* An install whose running binary is the image probe (tests/test_image_probe.h),
|
||||
* not this runner. These tests need a real executable to stage, verify (it is
|
||||
* run with --version) and publish, never this one: each install of the ~800 MB
|
||||
* sanitized runner made up to five full SHA-256 passes and two fsync'd staged
|
||||
* copies of it, and one such hash costs 70-95 s on some hosted x86 CPUs. -1,
|
||||
* said on stderr, when the probe was not built. */
|
||||
static int cli_test_cmd_install_probe(int argc, char **argv) {
|
||||
static char probe[1024];
|
||||
if (!probe[0] && !th_image_probe_path(probe, sizeof(probe))) {
|
||||
(void)fprintf(stderr, "cli: no image probe beside this runner; it is built with the "
|
||||
"runner (Makefile.cbm, <runner>-image-probe)\n");
|
||||
return -1;
|
||||
}
|
||||
cbm_cli_set_self_path_override_for_test(probe);
|
||||
int rc = cli_test_cmd_install(argc, argv);
|
||||
cbm_cli_set_self_path_override_for_test(NULL);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int cli_test_cmd_uninstall(int argc, char **argv) {
|
||||
return cli_test_cmd_dispatch(cbm_cmd_uninstall, argc, argv);
|
||||
}
|
||||
@@ -1018,6 +1038,24 @@ static unsigned char *create_test_targz(const char *filename, const unsigned cha
|
||||
return gz;
|
||||
}
|
||||
|
||||
/* Two update tests package a native executable as the release, and on macOS
|
||||
* that executable is this test runner. An ASan runner that carries every
|
||||
* vendored grammar sits right at the updater's 500 MiB decompression limit;
|
||||
* the ObjectScript v1.11.0 parse tables took the CI runners past it, and the
|
||||
* archive was refused ("binary not found in archive") before the step under
|
||||
* test ran. The limit has its own test; these tests only need their archive
|
||||
* accepted, so the limit is sized to the fixture. Twice the inflated tar can
|
||||
* never refuse it: the decompression buffer only doubles from below the
|
||||
* inflated size. cbm_cli_set_decompress_max_for_test(0) restores the limit.
|
||||
* Both tests use the tar path, which is POSIX-only. */
|
||||
#ifndef _WIN32
|
||||
static void cli_update_fit_decompress_limit(long fixture_size) {
|
||||
/* create_test_targz adds a header block, block padding and two end blocks. */
|
||||
enum { TARGZ_OVERHEAD = 4 * 512 };
|
||||
cbm_cli_set_decompress_max_for_test(((size_t)fixture_size + TARGZ_OVERHEAD) * 2U);
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════
|
||||
* Mandatory daemon activation safety
|
||||
* ═══════════════════════════════════════════════════════════════════ */
|
||||
@@ -1430,7 +1468,7 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) {
|
||||
char dir_arg[640];
|
||||
snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", install_dir);
|
||||
char *install_argv[] = {"--force", "--skip-config", "--yes", dir_arg};
|
||||
int install_rc = child_ready ? cli_test_cmd_install(4, install_argv) : -1;
|
||||
int install_rc = child_ready ? cli_test_cmd_install_probe(4, install_argv) : -1;
|
||||
close(install_done_pipe[1]); /* the child's watch ends here at the latest */
|
||||
cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
@@ -1541,7 +1579,7 @@ TEST(cli_install_recovers_markerless_stale_rendezvous) {
|
||||
char dir_arg[640];
|
||||
snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", install_dir);
|
||||
char *install_argv[] = {"--force", "--skip-config", "--yes", dir_arg};
|
||||
int install_rc = orphan_created ? cli_test_cmd_install(4, install_argv) : -1;
|
||||
int install_rc = orphan_created ? cli_test_cmd_install_probe(4, install_argv) : -1;
|
||||
cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
|
||||
@@ -1951,7 +1989,7 @@ static int cli_scope_install(cli_scope_fixture_t *fixture, const char *home, con
|
||||
snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);
|
||||
char *install_argv[] = {skip_binary ? "--skip-binary" : "--force", "--skip-config", "--yes",
|
||||
dir_arg};
|
||||
int rc = cli_test_cmd_install(4, install_argv);
|
||||
int rc = cli_test_cmd_install_probe(4, install_argv);
|
||||
cbm_cli_set_activation_runtime_parent_for_test(g_cli_suite_runtime_parent);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
return rc;
|
||||
@@ -2375,7 +2413,7 @@ TEST(cli_install_force_quiesces_active_cohort_before_replacing_binary) {
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
char *argv[] = {"--force"};
|
||||
int rc = cli_test_cmd_install(1, argv);
|
||||
int rc = cli_test_cmd_install_probe(1, argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
|
||||
const char *installed = read_test_file(bin_target);
|
||||
@@ -2427,11 +2465,11 @@ TEST(cli_install_dir_and_skip_config_stage_first_install_safely) {
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
char *argv[] = {"--force", "--skip-config", "--yes", "--dir", install_dir};
|
||||
int rc = cli_test_cmd_install(5, argv);
|
||||
int rc = cli_test_cmd_install_probe(5, argv);
|
||||
char equals_arg[640];
|
||||
snprintf(equals_arg, sizeof(equals_arg), "--dir=%s", install_dir);
|
||||
char *dry_argv[] = {"--force", "--skip-config", "--dry-run", equals_arg};
|
||||
int dry_rc = cli_test_cmd_install(4, dry_argv);
|
||||
int dry_rc = cli_test_cmd_install_probe(4, dry_argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
|
||||
@@ -2835,12 +2873,12 @@ TEST(cli_no_hooks_removes_codex_pretool_hook) {
|
||||
size_t owned = 0U;
|
||||
size_t foreign = 0U;
|
||||
char *default_args[] = {"--skip-binary", "--clients=codex", "--yes"};
|
||||
int default_rc = cli_test_cmd_install(3, default_args);
|
||||
int default_rc = cli_test_cmd_install_probe(3, default_args);
|
||||
test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign);
|
||||
bool default_json = default_rc == 0 && owned == 1U && foreign == 1U;
|
||||
|
||||
char *no_hooks_args[] = {"--no-hooks", "--skip-binary", "--clients=codex", "--yes"};
|
||||
int no_hooks_rc = cli_test_cmd_install(4, no_hooks_args);
|
||||
int no_hooks_rc = cli_test_cmd_install_probe(4, no_hooks_args);
|
||||
test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign);
|
||||
char *json_state = read_test_file_alloc(hooks_path);
|
||||
char *toml_state = read_test_file_alloc(config_path);
|
||||
@@ -2851,26 +2889,26 @@ TEST(cli_no_hooks_removes_codex_pretool_hook) {
|
||||
free(json_state);
|
||||
free(toml_state);
|
||||
|
||||
int bare_rc = cli_test_cmd_install(3, default_args);
|
||||
int bare_rc = cli_test_cmd_install_probe(3, default_args);
|
||||
test_codex_pretool_hook_counts(hooks_path, foreign_command, &owned, &foreign);
|
||||
bool bare_disabled = bare_rc == 0 && owned == 0U && foreign == 1U;
|
||||
|
||||
/* Without hooks.json the config.toml managed block carries the hooks. */
|
||||
(void)remove(hooks_path);
|
||||
char *hooks_args[] = {"--hooks", "--skip-binary", "--clients=codex", "--yes"};
|
||||
int toml_enable_rc = cli_test_cmd_install(4, hooks_args);
|
||||
int toml_enable_rc = cli_test_cmd_install_probe(4, hooks_args);
|
||||
toml_state = read_test_file_alloc(config_path);
|
||||
bool toml_enabled = toml_enable_rc == 0 && toml_state &&
|
||||
test_count_substring(toml_state, "[[hooks.PreToolUse]]") == 1U;
|
||||
free(toml_state);
|
||||
int toml_disable_rc = cli_test_cmd_install(4, no_hooks_args);
|
||||
int toml_disable_rc = cli_test_cmd_install_probe(4, no_hooks_args);
|
||||
toml_state = read_test_file_alloc(config_path);
|
||||
bool toml_disabled = toml_disable_rc == 0 && toml_state &&
|
||||
!strstr(toml_state, "hooks.PreToolUse") &&
|
||||
!strstr(toml_state, "hook-augment") &&
|
||||
strstr(toml_state, "[mcp_servers.codebase-memory-mcp]");
|
||||
free(toml_state);
|
||||
int restore_rc = cli_test_cmd_install(4, hooks_args);
|
||||
int restore_rc = cli_test_cmd_install_probe(4, hooks_args);
|
||||
toml_state = read_test_file_alloc(config_path);
|
||||
bool restored = restore_rc == 0 && toml_state &&
|
||||
test_count_substring(toml_state, "[[hooks.PreToolUse]]") == 1U;
|
||||
@@ -2951,12 +2989,12 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) {
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
|
||||
char *default_args[] = {"--skip-binary", "--clients=augment", "--yes"};
|
||||
int default_rc = cli_test_cmd_install(3, default_args);
|
||||
int default_rc = cli_test_cmd_install_probe(3, default_args);
|
||||
bool default_scripts =
|
||||
default_rc == 0 && cbm_file_exists(session_path) && cbm_file_exists(coverage_path);
|
||||
|
||||
char *no_hooks_args[] = {"--no-hooks", "--skip-binary", "--clients=augment", "--yes"};
|
||||
int no_hooks_rc = cli_test_cmd_install(4, no_hooks_args);
|
||||
int no_hooks_rc = cli_test_cmd_install_probe(4, no_hooks_args);
|
||||
bool scripts_removed =
|
||||
no_hooks_rc == 0 && !cbm_file_exists(session_path) && !cbm_file_exists(coverage_path);
|
||||
char *settings = read_test_file_alloc(settings_path);
|
||||
@@ -2966,12 +3004,12 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) {
|
||||
!strstr(settings, "codebase-memory-coverage");
|
||||
free(settings);
|
||||
|
||||
int bare_rc = cli_test_cmd_install(3, default_args);
|
||||
int bare_rc = cli_test_cmd_install_probe(3, default_args);
|
||||
bool bare_disabled =
|
||||
bare_rc == 0 && !cbm_file_exists(session_path) && !cbm_file_exists(coverage_path);
|
||||
|
||||
char *hooks_args[] = {"--hooks", "--skip-binary", "--clients=augment", "--yes"};
|
||||
int hooks_rc = cli_test_cmd_install(4, hooks_args);
|
||||
int hooks_rc = cli_test_cmd_install_probe(4, hooks_args);
|
||||
settings = read_test_file_alloc(settings_path);
|
||||
bool restored = hooks_rc == 0 && cbm_file_exists(session_path) &&
|
||||
cbm_file_exists(coverage_path) && settings &&
|
||||
@@ -2987,7 +3025,7 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) {
|
||||
owned_session ? owned_session : "");
|
||||
free(owned_session);
|
||||
write_test_file(session_path, user_session);
|
||||
int user_rc = cli_test_cmd_install(4, no_hooks_args);
|
||||
int user_rc = cli_test_cmd_install_probe(4, no_hooks_args);
|
||||
char *kept_session = read_test_file_alloc(session_path);
|
||||
bool user_script_kept = user_rc == 0 && kept_session &&
|
||||
strcmp(kept_session, user_session) == 0 &&
|
||||
@@ -2997,7 +3035,7 @@ TEST(cli_no_hooks_removes_augment_owned_scripts) {
|
||||
/* End on --hooks, as the Codex case does: the opt-out is process state,
|
||||
* and later tests install without the command line. */
|
||||
(void)remove(session_path);
|
||||
int final_rc = cli_test_cmd_install(4, hooks_args);
|
||||
int final_rc = cli_test_cmd_install_probe(4, hooks_args);
|
||||
bool final_restored =
|
||||
final_rc == 0 && cbm_file_exists(session_path) && cbm_file_exists(coverage_path);
|
||||
|
||||
@@ -3057,7 +3095,7 @@ TEST(cli_install_reset_deletion_waits_for_final_activation_guard) {
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
char *argv[] = {"--force", "--reset-indexes", "--yes"};
|
||||
int rc = cli_test_cmd_install(3, argv);
|
||||
int rc = cli_test_cmd_install_probe(3, argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
|
||||
@@ -3375,7 +3413,7 @@ TEST(cli_install_config_failure_keeps_published_binary) {
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
char *argv[] = {"--force", "--yes"};
|
||||
int rc = cli_test_cmd_install(2, argv);
|
||||
int rc = cli_test_cmd_install_probe(2, argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
cbm_set_auto_answer_for_test(0);
|
||||
|
||||
@@ -3618,6 +3656,7 @@ TEST(cli_update_agent_configs_finish_before_guard_release) {
|
||||
};
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
cli_update_fit_decompress_limit(native_size);
|
||||
char *argv[] = {"--force"};
|
||||
int rc = cli_test_cmd_update(1, argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
@@ -3643,6 +3682,7 @@ TEST(cli_update_agent_configs_finish_before_guard_release) {
|
||||
cbm_cli_set_activation_ops_for_test(&failure_ops);
|
||||
int config_failure_rc = cli_test_cmd_update(1, argv);
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
cbm_cli_set_decompress_max_for_test(0);
|
||||
struct stat updated_status;
|
||||
bool replacement_kept = stat(bin_target, &updated_status) == 0 &&
|
||||
updated_status.st_size != (off_t)(sizeof(old_binary) - 1U);
|
||||
@@ -3760,6 +3800,7 @@ TEST(cli_update_names_the_failing_staging_step_and_os_error) {
|
||||
};
|
||||
cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);
|
||||
cbm_cli_set_activation_ops_for_test(&ops);
|
||||
cli_update_fit_decompress_limit(native_size);
|
||||
FILE *capture = tmpfile();
|
||||
int saved_stdout = capture ? dup(STDOUT_FILENO) : -1;
|
||||
int saved_stderr = capture ? dup(STDERR_FILENO) : -1;
|
||||
@@ -3785,6 +3826,7 @@ TEST(cli_update_names_the_failing_staging_step_and_os_error) {
|
||||
close(saved_stderr);
|
||||
}
|
||||
cbm_cli_set_activation_ops_for_test(NULL);
|
||||
cbm_cli_set_decompress_max_for_test(0);
|
||||
char output[16384] = {0};
|
||||
if (capture) {
|
||||
rewind(capture);
|
||||
|
||||
+442
-84
@@ -8,6 +8,7 @@
|
||||
#include "test_framework.h"
|
||||
#include "test_helpers.h"
|
||||
#include "test_daemon_runtime_contract.h"
|
||||
#include "test_image_probe.h"
|
||||
|
||||
#include "daemon/application.h"
|
||||
#include "daemon/host.h"
|
||||
@@ -37,6 +38,7 @@
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include "foundation/subprocess.h" /* cbm_build_win_cmdline */
|
||||
#include "foundation/win_utf8.h"
|
||||
#include <stddef.h>
|
||||
#include <windows.h>
|
||||
@@ -505,6 +507,37 @@ static bool runtime_test_copy_self_image(const char *destination) {
|
||||
#endif
|
||||
}
|
||||
|
||||
/* The image probe beside this runner (tests/test_image_probe.h): the small
|
||||
* executable the copied-image tests copy, hash and run instead of this runner.
|
||||
* NULL, said once on stderr, when it was not built. */
|
||||
static const char *runtime_test_probe_image(void) {
|
||||
static char path[RUNTIME_TEST_PATH_CAP];
|
||||
if (!path[0] && !th_image_probe_path(path, sizeof(path))) {
|
||||
fprintf(stderr, "daemon_runtime: no image probe beside this runner; it is built "
|
||||
"with the runner (Makefile.cbm, <runner>-image-probe)\n");
|
||||
return NULL;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
static bool runtime_test_copy_probe_image(const char *destination) {
|
||||
const char *probe = runtime_test_probe_image();
|
||||
#ifdef _WIN32
|
||||
wchar_t *source_wide = probe && destination ? cbm_path_to_wide(probe) : NULL;
|
||||
wchar_t *destination_wide = source_wide ? cbm_path_to_wide(destination) : NULL;
|
||||
bool copied = destination_wide && CopyFileW(source_wide, destination_wide, TRUE) != 0;
|
||||
free(destination_wide);
|
||||
free(source_wide);
|
||||
return copied;
|
||||
#elif defined(__APPLE__) || defined(__linux__)
|
||||
return probe && destination && runtime_test_copy_executable(probe, destination);
|
||||
#else
|
||||
(void)probe;
|
||||
(void)destination;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
static bool runtime_test_paths_refer_to_same_file(const char *left, const char *right) {
|
||||
enum { CANONICAL_CAP = 4096 };
|
||||
char left_canonical[CANONICAL_CAP];
|
||||
@@ -1287,10 +1320,10 @@ typedef struct {
|
||||
* fixture's convenience start also joins a service-owned participant guard. */
|
||||
static runtime_test_coordination_t *runtime_test_fixture_coordination = NULL;
|
||||
|
||||
static bool runtime_test_fixture_start_configured(
|
||||
runtime_test_fixture_t *fixture, const char *tag, const cbm_daemon_build_identity_t *identity,
|
||||
uint32_t max_clients, uint64_t lease_timeout_ms,
|
||||
const cbm_daemon_runtime_application_callbacks_t *application) {
|
||||
/* The private parent, rendezvous key, endpoint and log paths of a fixture,
|
||||
* before any daemon serves it: shared by the in-process service below and the
|
||||
* image probe's daemon (runtime_test_probe_daemon_start). */
|
||||
static bool runtime_test_fixture_prepare(runtime_test_fixture_t *fixture, const char *tag) {
|
||||
memset(fixture, 0, sizeof(*fixture));
|
||||
if (!th_secure_runtime_parent_new(fixture->parent, sizeof(fixture->parent), tag)) {
|
||||
return runtime_test_fixture_start_failed(tag, "temporary-directory",
|
||||
@@ -1325,7 +1358,16 @@ static bool runtime_test_fixture_start_configured(
|
||||
if (lock_written <= 0 || lock_written >= (int)sizeof(fixture->lock_log_path)) {
|
||||
return runtime_test_fixture_start_failed(tag, "lock-log-path", lock_written);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool runtime_test_fixture_start_configured(
|
||||
runtime_test_fixture_t *fixture, const char *tag, const cbm_daemon_build_identity_t *identity,
|
||||
uint32_t max_clients, uint64_t lease_timeout_ms,
|
||||
const cbm_daemon_runtime_application_callbacks_t *application) {
|
||||
if (!runtime_test_fixture_prepare(fixture, tag)) {
|
||||
return false;
|
||||
}
|
||||
cbm_daemon_runtime_service_config_t config = {
|
||||
.endpoint = fixture->endpoint,
|
||||
.identity = *identity,
|
||||
@@ -1549,6 +1591,306 @@ static void runtime_test_fixture_finish(runtime_test_fixture_t *fixture) {
|
||||
memset(fixture, 0, sizeof(*fixture));
|
||||
}
|
||||
|
||||
/* ── The image probe's daemon ────────────────────────────────────────────
|
||||
* The copied-image tests need a daemon whose peers are separately executed
|
||||
* copies of the daemon's own image. A runtime service starts only with its own
|
||||
* image's fingerprint as identity, so that daemon runs in the small image
|
||||
* probe (__cbm_runtime_serve, tests/image_probe_roles.c), not in this runner:
|
||||
* it fingerprints every peer copy before answering, and a copy of this
|
||||
* ~800 MB sanitized runner took 70-95 s per hash on some hosted x86 CPUs, past
|
||||
* the clients' exchange budget. Paths, key, endpoint and cleanup are the
|
||||
* in-process fixture's (its .service stays NULL); the daemon is driven over
|
||||
* its stdin and stdout, and nothing here waits on a clock: every read ends on
|
||||
* a reply or on EOF when the probe is gone. */
|
||||
typedef struct {
|
||||
runtime_test_fixture_t fixture;
|
||||
char build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE]; /* its identity: the probe's fingerprint */
|
||||
bool spawned;
|
||||
#ifdef _WIN32
|
||||
HANDLE process;
|
||||
HANDLE commands; /* the probe's stdin */
|
||||
HANDLE replies; /* the probe's stdout */
|
||||
#else
|
||||
pid_t process;
|
||||
int commands;
|
||||
int replies;
|
||||
#endif
|
||||
} runtime_test_probe_daemon_t;
|
||||
|
||||
#ifdef _WIN32
|
||||
/* Start argv with exactly the two pipe ends (and a duplicate of this runner's
|
||||
* stderr, when there is one) inherited, as tf_rss_tree_start_descendant does. */
|
||||
static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon,
|
||||
const char *const *argv) {
|
||||
SECURITY_ATTRIBUTES inheritable;
|
||||
memset(&inheritable, 0, sizeof(inheritable));
|
||||
inheritable.nLength = sizeof(inheritable);
|
||||
inheritable.bInheritHandle = TRUE;
|
||||
HANDLE child_input = NULL;
|
||||
HANDLE commands = NULL;
|
||||
HANDLE replies = NULL;
|
||||
HANDLE child_output = NULL;
|
||||
HANDLE child_error = NULL;
|
||||
bool piped = CreatePipe(&child_input, &commands, &inheritable, 0) &&
|
||||
CreatePipe(&replies, &child_output, &inheritable, 0) &&
|
||||
SetHandleInformation(commands, HANDLE_FLAG_INHERIT, 0) &&
|
||||
SetHandleInformation(replies, HANDLE_FLAG_INHERIT, 0);
|
||||
HANDLE error = GetStdHandle(STD_ERROR_HANDLE);
|
||||
if (piped && error && error != INVALID_HANDLE_VALUE &&
|
||||
!DuplicateHandle(GetCurrentProcess(), error, GetCurrentProcess(), &child_error, 0, TRUE,
|
||||
DUPLICATE_SAME_ACCESS)) {
|
||||
child_error = NULL; /* the probe then runs without a stderr */
|
||||
}
|
||||
char command_line[RUNTIME_TEST_PATH_CAP * 4];
|
||||
bool built = piped && cbm_build_win_cmdline(command_line, sizeof(command_line), argv);
|
||||
wchar_t *application = built ? cbm_path_to_wide(argv[0]) : NULL;
|
||||
wchar_t *command = application ? cbm_utf8_to_wide(command_line) : NULL;
|
||||
HANDLE inherit[3] = {child_input, child_output, child_error};
|
||||
DWORD inherit_count = child_error ? 3U : 2U;
|
||||
SIZE_T attrs_size = 0;
|
||||
(void)InitializeProcThreadAttributeList(NULL, 1, 0, &attrs_size);
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST attrs =
|
||||
command ? (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attrs_size) : NULL;
|
||||
bool attrs_init = attrs && InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size);
|
||||
bool attrs_ready =
|
||||
attrs_init && UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
|
||||
inherit, inherit_count * sizeof(HANDLE), NULL,
|
||||
NULL);
|
||||
STARTUPINFOEXW startup;
|
||||
memset(&startup, 0, sizeof(startup));
|
||||
startup.StartupInfo.cb = sizeof(startup);
|
||||
startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
|
||||
startup.StartupInfo.hStdInput = child_input;
|
||||
startup.StartupInfo.hStdOutput = child_output;
|
||||
startup.StartupInfo.hStdError = child_error;
|
||||
startup.lpAttributeList = attrs;
|
||||
PROCESS_INFORMATION process;
|
||||
memset(&process, 0, sizeof(process));
|
||||
bool started = attrs_ready &&
|
||||
CreateProcessW(application, command, NULL, NULL, TRUE,
|
||||
EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, NULL, NULL,
|
||||
&startup.StartupInfo, &process) != 0;
|
||||
if (attrs_init) {
|
||||
DeleteProcThreadAttributeList(attrs);
|
||||
}
|
||||
free(attrs);
|
||||
free(command);
|
||||
free(application);
|
||||
HANDLE child_ends[3] = {child_input, child_output, child_error};
|
||||
for (size_t i = 0; i < 3U; i++) {
|
||||
if (child_ends[i]) {
|
||||
(void)CloseHandle(child_ends[i]);
|
||||
}
|
||||
}
|
||||
if (!started) {
|
||||
if (commands) {
|
||||
(void)CloseHandle(commands);
|
||||
}
|
||||
if (replies) {
|
||||
(void)CloseHandle(replies);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
(void)CloseHandle(process.hThread);
|
||||
daemon->process = process.hProcess;
|
||||
daemon->commands = commands;
|
||||
daemon->replies = replies;
|
||||
return true;
|
||||
}
|
||||
#elif defined(__APPLE__) || defined(__linux__)
|
||||
/* posix_spawn, not fork, for the reason runtime_test_spawn_blocked_executable
|
||||
* gives. This runner's pipe ends are close-on-exec, so no later child holds
|
||||
* the daemon's stdin open past its release. */
|
||||
static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon,
|
||||
const char *const *argv) {
|
||||
int commands[2] = {-1, -1};
|
||||
int replies[2] = {-1, -1};
|
||||
if (pipe(commands) != 0) {
|
||||
return false;
|
||||
}
|
||||
if (pipe(replies) != 0) {
|
||||
(void)close(commands[0]);
|
||||
(void)close(commands[1]);
|
||||
return false;
|
||||
}
|
||||
bool private_ends = fcntl(commands[1], F_SETFD, FD_CLOEXEC) == 0 &&
|
||||
fcntl(replies[0], F_SETFD, FD_CLOEXEC) == 0;
|
||||
posix_spawn_file_actions_t actions;
|
||||
bool actions_ready = private_ends && posix_spawn_file_actions_init(&actions) == 0;
|
||||
bool actions_set = actions_ready &&
|
||||
posix_spawn_file_actions_adddup2(&actions, commands[0], STDIN_FILENO) == 0 &&
|
||||
posix_spawn_file_actions_adddup2(&actions, replies[1], STDOUT_FILENO) == 0 &&
|
||||
posix_spawn_file_actions_addclose(&actions, commands[0]) == 0 &&
|
||||
posix_spawn_file_actions_addclose(&actions, replies[1]) == 0;
|
||||
pid_t child = -1;
|
||||
bool started = actions_set && posix_spawn(&child, argv[0], &actions, NULL,
|
||||
(char *const *)argv, environ) == 0;
|
||||
if (actions_ready) {
|
||||
(void)posix_spawn_file_actions_destroy(&actions);
|
||||
}
|
||||
(void)close(commands[0]);
|
||||
(void)close(replies[1]);
|
||||
if (!started) {
|
||||
(void)close(commands[1]);
|
||||
(void)close(replies[0]);
|
||||
return false;
|
||||
}
|
||||
daemon->process = child;
|
||||
daemon->commands = commands[1];
|
||||
daemon->replies = replies[0];
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
static bool runtime_test_probe_daemon_spawn(runtime_test_probe_daemon_t *daemon,
|
||||
const char *const *argv) {
|
||||
(void)daemon;
|
||||
(void)argv;
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* One reply line, without its line end. false on EOF (the probe is gone), a
|
||||
* read error, or a line longer than cap. */
|
||||
static bool runtime_test_probe_daemon_read_line(runtime_test_probe_daemon_t *daemon, char *line,
|
||||
size_t cap) {
|
||||
size_t used = 0;
|
||||
bool fits = cap > 0;
|
||||
for (;;) {
|
||||
char ch = 0;
|
||||
#ifdef _WIN32
|
||||
DWORD got = 0;
|
||||
if (!ReadFile(daemon->replies, &ch, 1, &got, NULL) || got != 1) {
|
||||
return false;
|
||||
}
|
||||
#else
|
||||
ssize_t got = read(daemon->replies, &ch, 1);
|
||||
if (got < 0 && errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
if (got != 1) {
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
if (ch == '\n') {
|
||||
if (fits) {
|
||||
line[used] = '\0';
|
||||
}
|
||||
return fits;
|
||||
}
|
||||
if (ch != '\r' && fits && used + 1 < cap) {
|
||||
line[used++] = ch;
|
||||
} else if (ch != '\r') {
|
||||
fits = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool runtime_test_probe_daemon_send(runtime_test_probe_daemon_t *daemon, char command) {
|
||||
#ifdef _WIN32
|
||||
DWORD written = 0;
|
||||
return WriteFile(daemon->commands, &command, 1, &written, NULL) != 0 && written == 1;
|
||||
#else
|
||||
/* A probe that is already gone must fail the test, not kill the runner
|
||||
* with SIGPIPE: ignore it for this one write, as test_subprocess does. */
|
||||
struct sigaction ignore;
|
||||
struct sigaction previous;
|
||||
memset(&ignore, 0, sizeof(ignore));
|
||||
ignore.sa_handler = SIG_IGN;
|
||||
sigemptyset(&ignore.sa_mask);
|
||||
if (sigaction(SIGPIPE, &ignore, &previous) != 0) {
|
||||
return false;
|
||||
}
|
||||
ssize_t written;
|
||||
do {
|
||||
written = write(daemon->commands, &command, 1);
|
||||
} while (written < 0 && errno == EINTR);
|
||||
bool restored = sigaction(SIGPIPE, &previous, NULL) == 0;
|
||||
return written == 1 && restored;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Start the probe's daemon in a fresh fixture: true once it reported "ready"
|
||||
* with its fingerprint, which then is daemon->build. with_owner also holds a
|
||||
* committed session of the active image inside the probe. */
|
||||
static bool runtime_test_probe_daemon_start(runtime_test_probe_daemon_t *daemon, const char *tag,
|
||||
const char *version, bool with_owner) {
|
||||
memset(daemon, 0, sizeof(*daemon));
|
||||
const char *probe = runtime_test_probe_image();
|
||||
if (!probe) {
|
||||
return runtime_test_fixture_start_failed(tag, "image-probe", 0);
|
||||
}
|
||||
if (!runtime_test_fixture_prepare(&daemon->fixture, tag)) {
|
||||
return false;
|
||||
}
|
||||
const char *argv[] = {probe,
|
||||
"__cbm_runtime_serve",
|
||||
daemon->fixture.parent,
|
||||
daemon->fixture.key,
|
||||
version,
|
||||
with_owner ? "1" : "0",
|
||||
NULL};
|
||||
daemon->spawned = runtime_test_probe_daemon_spawn(daemon, argv);
|
||||
if (!daemon->spawned) {
|
||||
return runtime_test_fixture_start_failed(tag, "image-probe-spawn",
|
||||
runtime_test_last_os_error());
|
||||
}
|
||||
char line[CBM_DAEMON_BUILD_FINGERPRINT_SIZE + 16] = {0};
|
||||
bool answered = runtime_test_probe_daemon_read_line(daemon, line, sizeof(line));
|
||||
bool ready = answered && strncmp(line, "ready ", 6) == 0 && runtime_test_is_fingerprint(line + 6);
|
||||
if (!ready) {
|
||||
printf(" image probe daemon did not start: tag=%s reply=%s\n", tag,
|
||||
answered ? line : "(none: the probe exited)");
|
||||
return false;
|
||||
}
|
||||
memcpy(daemon->build, line + 6, CBM_DAEMON_BUILD_FINGERPRINT_SIZE);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Ask the daemon one question ('i' owner interrupted, 'x' exited by itself):
|
||||
* true when it answered, the answer in *answer. */
|
||||
static bool runtime_test_probe_daemon_ask(runtime_test_probe_daemon_t *daemon, char command,
|
||||
bool *answer) {
|
||||
char line[8] = {0};
|
||||
bool answered = daemon->spawned && runtime_test_probe_daemon_send(daemon, command) &&
|
||||
runtime_test_probe_daemon_read_line(daemon, line, sizeof(line)) &&
|
||||
(strcmp(line, "0") == 0 || strcmp(line, "1") == 0);
|
||||
*answer = answered && line[0] == '1';
|
||||
return answered;
|
||||
}
|
||||
|
||||
/* Release the daemon (EOF on its stdin), reap it and remove the fixture's
|
||||
* paths. Returns its exit code, or -1 when it never ran or did not exit
|
||||
* normally. Safe on a daemon whose start failed, and on a memset one. */
|
||||
static int runtime_test_probe_daemon_finish(runtime_test_probe_daemon_t *daemon) {
|
||||
int exit_code = -1;
|
||||
if (daemon->spawned) {
|
||||
#ifdef _WIN32
|
||||
(void)CloseHandle(daemon->commands);
|
||||
bool waited = runtime_test_windows_wait_image_probe(daemon->process);
|
||||
DWORD code = 0;
|
||||
if (waited && GetExitCodeProcess(daemon->process, &code) != 0 && code <= INT_MAX) {
|
||||
exit_code = (int)code;
|
||||
}
|
||||
(void)CloseHandle(daemon->process);
|
||||
(void)CloseHandle(daemon->replies);
|
||||
#elif defined(__APPLE__) || defined(__linux__)
|
||||
(void)close(daemon->commands);
|
||||
int status = 0;
|
||||
pid_t waited;
|
||||
do {
|
||||
waited = waitpid(daemon->process, &status, 0);
|
||||
} while (waited < 0 && errno == EINTR);
|
||||
if (waited == daemon->process && WIFEXITED(status)) {
|
||||
exit_code = WEXITSTATUS(status);
|
||||
}
|
||||
(void)close(daemon->replies);
|
||||
#endif
|
||||
daemon->spawned = false;
|
||||
}
|
||||
runtime_test_fixture_finish(&daemon->fixture);
|
||||
return exit_code;
|
||||
}
|
||||
|
||||
static bool runtime_test_read_log(const char *path, char out[RUNTIME_TEST_LOG_CAP]) {
|
||||
FILE *file = cbm_fopen(path, "rb");
|
||||
if (!file) {
|
||||
@@ -2323,8 +2665,6 @@ TEST(daemon_runtime_activation_ack_snapshots_then_interrupts_all_clients) {
|
||||
|
||||
#if defined(_WIN32) || defined(__APPLE__) || defined(__linux__)
|
||||
TEST(daemon_runtime_activation_accepts_authenticated_different_build) {
|
||||
cbm_daemon_build_identity_t active_identity =
|
||||
runtime_test_identity("2.4.0", runtime_test_self_build());
|
||||
char directory[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
char foreign_image[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
int directory_written =
|
||||
@@ -2334,8 +2674,12 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) {
|
||||
int image_written = directory_created ? snprintf(foreign_image, sizeof(foreign_image),
|
||||
"%s/foreign-activation", directory)
|
||||
: -1;
|
||||
/* The active daemon and the foreign requester are both the image probe
|
||||
* (runtime_test_probe_daemon_t): the daemon hashes the requester's image
|
||||
* to authenticate its claimed build, over a few MB instead of a copy of
|
||||
* this runner. */
|
||||
bool copied = image_written > 0 && image_written < (int)sizeof(foreign_image) &&
|
||||
runtime_test_copy_self_image(foreign_image);
|
||||
runtime_test_copy_probe_image(foreign_image);
|
||||
#ifdef __APPLE__
|
||||
/* Appending an overlay invalidates Mach-O strict validation. A distinct
|
||||
* signing identifier changes the executable bytes while keeping the copy
|
||||
@@ -2349,38 +2693,28 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) {
|
||||
char foreign_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
bool fingerprinted =
|
||||
runnable && cbm_daemon_build_fingerprint_file(foreign_image, foreign_build);
|
||||
bool differs = fingerprinted && strcmp(foreign_build, active_identity.build_fingerprint) != 0;
|
||||
cbm_daemon_build_identity_t foreign_identity = runtime_test_identity("9.9.9", foreign_build);
|
||||
|
||||
/* Finalize the foreign executable before the runtime starts any worker
|
||||
* threads. In particular, macOS code signing is an external process; the
|
||||
* test must not fork that helper from the live multithreaded daemon. The
|
||||
* immutable signed copy remains the actual peer image authenticated by
|
||||
* the activation request below. */
|
||||
runtime_test_fixture_t fixture;
|
||||
memset(&fixture, 0, sizeof(fixture));
|
||||
bool started =
|
||||
differs && runtime_test_fixture_start(&fixture, "activation-foreign", &active_identity);
|
||||
cbm_daemon_runtime_connect_result_t owner_result = {0};
|
||||
cbm_daemon_runtime_client_t *owner = NULL;
|
||||
if (started) {
|
||||
owner = cbm_daemon_runtime_client_connect(fixture.endpoint, &active_identity,
|
||||
RUNTIME_TEST_TIMEOUT_MS, &owner_result);
|
||||
}
|
||||
/* The foreign executable is final before the daemon starts; macOS code
|
||||
* signing above is an external process. The immutable signed copy remains
|
||||
* the actual peer image authenticated by the activation request below.
|
||||
* The daemon holds one committed owner session of its own image. */
|
||||
runtime_test_probe_daemon_t daemon;
|
||||
memset(&daemon, 0, sizeof(daemon));
|
||||
bool started = fingerprinted &&
|
||||
runtime_test_probe_daemon_start(&daemon, "activation-foreign", "2.4.0", true);
|
||||
bool differs = started && strcmp(foreign_build, daemon.build) != 0;
|
||||
int foreign_exit = -1;
|
||||
bool foreign_ran =
|
||||
owner && differs &&
|
||||
runtime_test_run_activation_image(foreign_image, &fixture, &foreign_identity,
|
||||
differs &&
|
||||
runtime_test_run_activation_image(foreign_image, &daemon.fixture, &foreign_identity,
|
||||
CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL, &foreign_exit);
|
||||
bool owner_interrupted = owner && foreign_ran &&
|
||||
!cbm_daemon_runtime_client_heartbeat(owner, RUNTIME_TEST_TIMEOUT_MS);
|
||||
if (owner) {
|
||||
(void)cbm_daemon_runtime_client_close(owner, RUNTIME_TEST_TIMEOUT_MS);
|
||||
owner = NULL;
|
||||
}
|
||||
bool exited =
|
||||
started && cbm_daemon_runtime_service_wait_exited(fixture.service, RUNTIME_TEST_TIMEOUT_MS);
|
||||
runtime_test_fixture_finish(&fixture);
|
||||
bool owner_interrupted = false;
|
||||
bool interrupted_asked =
|
||||
foreign_ran && runtime_test_probe_daemon_ask(&daemon, 'i', &owner_interrupted);
|
||||
bool exited = false;
|
||||
bool exited_asked = started && runtime_test_probe_daemon_ask(&daemon, 'x', &exited);
|
||||
int daemon_exit = runtime_test_probe_daemon_finish(&daemon);
|
||||
if (image_written > 0 && image_written < (int)sizeof(foreign_image)) {
|
||||
(void)cbm_unlink(foreign_image);
|
||||
}
|
||||
@@ -2388,18 +2722,20 @@ TEST(daemon_runtime_activation_accepts_authenticated_different_build) {
|
||||
(void)cbm_rmdir(directory);
|
||||
}
|
||||
|
||||
ASSERT_TRUE(started);
|
||||
ASSERT_EQ(owner_result.status, CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED);
|
||||
ASSERT_TRUE(directory_created);
|
||||
ASSERT_TRUE(copied);
|
||||
ASSERT_TRUE(changed);
|
||||
ASSERT_TRUE(runnable);
|
||||
ASSERT_TRUE(fingerprinted);
|
||||
ASSERT_TRUE(started);
|
||||
ASSERT_TRUE(differs);
|
||||
ASSERT_TRUE(foreign_ran);
|
||||
ASSERT_EQ(foreign_exit, 0);
|
||||
ASSERT_TRUE(interrupted_asked);
|
||||
ASSERT_TRUE(owner_interrupted);
|
||||
ASSERT_TRUE(exited_asked);
|
||||
ASSERT_TRUE(exited);
|
||||
ASSERT_EQ(daemon_exit, 0);
|
||||
PASS();
|
||||
}
|
||||
#endif
|
||||
@@ -4875,15 +5211,20 @@ TEST(daemon_runtime_process_fingerprint_supports_extended_length_image) {
|
||||
}
|
||||
bool directory_created = path_built && cbm_mkdir_p(directory, 0700);
|
||||
int image_written = directory_created ? snprintf(image_path, sizeof(image_path),
|
||||
"%s/test-runner-long-image.exe", directory)
|
||||
"%s/image-probe-long-image.exe", directory)
|
||||
: -1;
|
||||
wchar_t *ordinary_wide = image_written > 0 && image_written < (int)sizeof(image_path)
|
||||
? cbm_utf8_to_wide(image_path)
|
||||
: NULL;
|
||||
bool exceeds_legacy_limit = ordinary_wide && wcslen(ordinary_wide) >= MAX_PATH;
|
||||
free(ordinary_wide);
|
||||
bool copied = exceeds_legacy_limit && runtime_test_windows_copy_self(image_path);
|
||||
const char *expected = runtime_test_self_build();
|
||||
/* A copy of the image probe, not of this runner: the fingerprint below
|
||||
* hashes the whole held image (runtime_test_probe_daemon_t says why). */
|
||||
bool copied = exceeds_legacy_limit && runtime_test_copy_probe_image(image_path);
|
||||
char expected_build[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
const char *probe = runtime_test_probe_image();
|
||||
const char *expected =
|
||||
probe && cbm_daemon_build_fingerprint_file(probe, expected_build) ? expected_build : NULL;
|
||||
|
||||
int event_written =
|
||||
snprintf(event_name, sizeof(event_name), "Local\\cbm-runtime-long-image-%lu-%llu",
|
||||
@@ -4964,10 +5305,7 @@ TEST(daemon_runtime_process_fingerprint_supports_extended_length_image) {
|
||||
* Re-signing the changed copy keeps the probe runnable on arm64 while ensuring
|
||||
* that only the deliberately injected mapping has the active identity. */
|
||||
TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) {
|
||||
cbm_daemon_build_identity_t identity =
|
||||
runtime_test_identity("2.4.0", runtime_test_self_build());
|
||||
char directory[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
char active_image[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
char foreign_image[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
char foreign_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
int directory_written =
|
||||
@@ -4977,7 +5315,11 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) {
|
||||
int foreign_written = directory_created ? snprintf(foreign_image, sizeof(foreign_image),
|
||||
"%s/foreign-client", directory)
|
||||
: -1;
|
||||
bool active_resolved = runtime_test_self_image_path(active_image);
|
||||
/* The daemon runs from the image probe (runtime_test_probe_daemon_t), so
|
||||
* the active image the foreign client maps is the probe, and the foreign
|
||||
* main image the daemon must hash is a re-signed copy of the probe. */
|
||||
const char *active_image = runtime_test_probe_image();
|
||||
bool active_resolved = active_image != NULL;
|
||||
bool foreign_copied = active_resolved && foreign_written > 0 &&
|
||||
foreign_written < (int)sizeof(foreign_image) &&
|
||||
runtime_test_copy_executable(active_image, foreign_image);
|
||||
@@ -4987,22 +5329,20 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) {
|
||||
bool foreign_signed = foreign_changed && runtime_test_mac_ad_hoc_sign(foreign_image);
|
||||
bool foreign_fingerprinted =
|
||||
foreign_signed && cbm_daemon_build_fingerprint_file(foreign_image, foreign_fingerprint);
|
||||
bool fingerprint_differs =
|
||||
foreign_fingerprinted && strcmp(foreign_fingerprint, identity.build_fingerprint) != 0;
|
||||
|
||||
runtime_test_fixture_t fixture;
|
||||
memset(&fixture, 0, sizeof(fixture));
|
||||
bool fixture_attempted = directory_created && active_resolved && fingerprint_differs;
|
||||
bool started =
|
||||
fixture_attempted && runtime_test_fixture_start(&fixture, "mapped-foreign", &identity);
|
||||
runtime_test_probe_daemon_t daemon;
|
||||
memset(&daemon, 0, sizeof(daemon));
|
||||
bool started = directory_created && foreign_fingerprinted &&
|
||||
runtime_test_probe_daemon_start(&daemon, "mapped-foreign", "2.4.0", false);
|
||||
cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", daemon.build);
|
||||
bool fingerprint_differs =
|
||||
started && strcmp(foreign_fingerprint, identity.build_fingerprint) != 0;
|
||||
int foreign_exit = -1;
|
||||
bool foreign_ran =
|
||||
started && runtime_test_run_mapped_hello_image(foreign_image, active_image, &fixture,
|
||||
&identity, &foreign_exit);
|
||||
|
||||
if (fixture_attempted) {
|
||||
runtime_test_fixture_finish(&fixture);
|
||||
}
|
||||
fingerprint_differs && runtime_test_run_mapped_hello_image(
|
||||
foreign_image, active_image, &daemon.fixture, &identity,
|
||||
&foreign_exit);
|
||||
int daemon_exit = runtime_test_probe_daemon_finish(&daemon);
|
||||
if (foreign_written > 0 && foreign_written < (int)sizeof(foreign_image)) {
|
||||
(void)cbm_unlink(foreign_image);
|
||||
}
|
||||
@@ -5016,33 +5356,41 @@ TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active) {
|
||||
ASSERT_TRUE(foreign_changed);
|
||||
ASSERT_TRUE(foreign_signed);
|
||||
ASSERT_TRUE(foreign_fingerprinted);
|
||||
ASSERT_TRUE(fingerprint_differs);
|
||||
ASSERT_TRUE(started);
|
||||
ASSERT_TRUE(fingerprint_differs);
|
||||
ASSERT_TRUE(foreign_ran);
|
||||
/* 26 = the daemon answered with a rejection. A probe that got no answer
|
||||
* inside the exchange budget exits 30 and must not pass here. */
|
||||
ASSERT_EQ(foreign_exit, 26);
|
||||
ASSERT_EQ(daemon_exit, 0);
|
||||
PASS();
|
||||
}
|
||||
#endif
|
||||
|
||||
/* The daemon admits a peer running a DIFFERENT file only after hashing that
|
||||
* file: identical bytes are admitted, changed bytes refused. The daemon runs
|
||||
* from the image probe and its peers are copies of the probe
|
||||
* (runtime_test_probe_daemon_t), so the hash it pays before answering is over
|
||||
* a few MB, not over a copy of this runner. */
|
||||
TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed) {
|
||||
cbm_daemon_build_identity_t identity =
|
||||
runtime_test_identity("2.4.0", runtime_test_self_build());
|
||||
runtime_test_fixture_t identical_fixture;
|
||||
runtime_test_probe_daemon_t identical_daemon;
|
||||
bool identical_started =
|
||||
runtime_test_fixture_start(&identical_fixture, "copied-identical", &identity);
|
||||
runtime_test_probe_daemon_start(&identical_daemon, "copied-identical", "2.4.0", false);
|
||||
cbm_daemon_build_identity_t identity = runtime_test_identity("2.4.0", identical_daemon.build);
|
||||
char identical_path[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
int identical_path_written = identical_started
|
||||
#ifdef _WIN32
|
||||
? snprintf(identical_path, sizeof(identical_path),
|
||||
"%s/client-copy.exe", identical_fixture.parent)
|
||||
"%s/client-copy.exe",
|
||||
identical_daemon.fixture.parent)
|
||||
#else
|
||||
? snprintf(identical_path, sizeof(identical_path),
|
||||
"%s/client-copy", identical_fixture.parent)
|
||||
"%s/client-copy", identical_daemon.fixture.parent)
|
||||
#endif
|
||||
: -1;
|
||||
bool identical_copied = identical_path_written > 0 &&
|
||||
identical_path_written < (int)sizeof(identical_path) &&
|
||||
runtime_test_copy_self_image(identical_path);
|
||||
runtime_test_copy_probe_image(identical_path);
|
||||
char identical_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
bool identical_bytes =
|
||||
identical_copied &&
|
||||
@@ -5050,35 +5398,39 @@ TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed)
|
||||
strcmp(identical_fingerprint, identity.build_fingerprint) == 0;
|
||||
int identical_exit = -1;
|
||||
bool identical_ran =
|
||||
identical_bytes && runtime_test_run_hello_image(identical_path, &identical_fixture,
|
||||
identical_bytes && runtime_test_run_hello_image(identical_path, &identical_daemon.fixture,
|
||||
&identity, &identical_exit);
|
||||
bool identical_exited =
|
||||
identical_ran && identical_exit == 0 &&
|
||||
cbm_daemon_runtime_service_wait_exited(identical_fixture.service, RUNTIME_TEST_TIMEOUT_MS);
|
||||
bool identical_exited = false;
|
||||
bool identical_asked = identical_ran && identical_exit == 0 &&
|
||||
runtime_test_probe_daemon_ask(&identical_daemon, 'x', &identical_exited);
|
||||
(void)cbm_unlink(identical_path);
|
||||
runtime_test_fixture_finish(&identical_fixture);
|
||||
int identical_daemon_exit = runtime_test_probe_daemon_finish(&identical_daemon);
|
||||
|
||||
#ifdef __linux__
|
||||
runtime_test_fixture_t changed_fixture;
|
||||
runtime_test_probe_daemon_t changed_daemon;
|
||||
bool changed_started =
|
||||
runtime_test_fixture_start(&changed_fixture, "copied-changed", &identity);
|
||||
runtime_test_probe_daemon_start(&changed_daemon, "copied-changed", "2.4.0", false);
|
||||
cbm_daemon_build_identity_t changed_identity =
|
||||
runtime_test_identity("2.4.0", changed_daemon.build);
|
||||
char changed_path[RUNTIME_TEST_PATH_CAP] = {0};
|
||||
int changed_path_written = changed_started ? snprintf(changed_path, sizeof(changed_path),
|
||||
"%s/client-copy", changed_fixture.parent)
|
||||
: -1;
|
||||
int changed_path_written =
|
||||
changed_started ? snprintf(changed_path, sizeof(changed_path), "%s/client-copy",
|
||||
changed_daemon.fixture.parent)
|
||||
: -1;
|
||||
bool changed_copied = changed_path_written > 0 &&
|
||||
changed_path_written < (int)sizeof(changed_path) &&
|
||||
runtime_test_copy_self_image(changed_path) &&
|
||||
runtime_test_copy_probe_image(changed_path) &&
|
||||
runtime_test_append_image_marker(changed_path);
|
||||
char changed_fingerprint[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};
|
||||
bool changed_bytes = changed_copied &&
|
||||
cbm_daemon_build_fingerprint_file(changed_path, changed_fingerprint) &&
|
||||
strcmp(changed_fingerprint, identity.build_fingerprint) != 0;
|
||||
strcmp(changed_fingerprint, changed_identity.build_fingerprint) != 0;
|
||||
int changed_exit = -1;
|
||||
bool changed_ran = changed_bytes && runtime_test_run_hello_image(changed_path, &changed_fixture,
|
||||
&identity, &changed_exit);
|
||||
bool changed_ran =
|
||||
changed_bytes && runtime_test_run_hello_image(changed_path, &changed_daemon.fixture,
|
||||
&changed_identity, &changed_exit);
|
||||
(void)cbm_unlink(changed_path);
|
||||
runtime_test_fixture_finish(&changed_fixture);
|
||||
int changed_daemon_exit = runtime_test_probe_daemon_finish(&changed_daemon);
|
||||
#endif
|
||||
|
||||
ASSERT_TRUE(identical_started);
|
||||
@@ -5086,13 +5438,18 @@ TEST(daemon_runtime_copied_image_fallback_accepts_identical_and_rejects_changed)
|
||||
ASSERT_TRUE(identical_bytes);
|
||||
ASSERT_TRUE(identical_ran);
|
||||
ASSERT_EQ(identical_exit, 0);
|
||||
ASSERT_TRUE(identical_asked);
|
||||
ASSERT_TRUE(identical_exited);
|
||||
ASSERT_EQ(identical_daemon_exit, 0);
|
||||
#ifdef __linux__
|
||||
ASSERT_TRUE(changed_started);
|
||||
ASSERT_TRUE(changed_copied);
|
||||
ASSERT_TRUE(changed_bytes);
|
||||
ASSERT_TRUE(changed_ran);
|
||||
/* 26 = the daemon answered with a rejection; no answer inside the
|
||||
* exchange budget exits 30 and fails here instead of passing. */
|
||||
ASSERT_EQ(changed_exit, 26);
|
||||
ASSERT_EQ(changed_daemon_exit, 0);
|
||||
#endif
|
||||
PASS();
|
||||
}
|
||||
@@ -5118,7 +5475,7 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) {
|
||||
setup = setup && image_written > 0 && image_written < (int)sizeof(image_path) &&
|
||||
replacement_written > 0 && replacement_written < (int)sizeof(replacement_path) &&
|
||||
event_written > 0 && event_written < (int)sizeof(event_name) &&
|
||||
runtime_test_windows_copy_self(image_path);
|
||||
runtime_test_copy_probe_image(image_path);
|
||||
|
||||
FILE *replacement_file = setup ? cbm_fopen(replacement_path, "wb") : NULL;
|
||||
bool replacement_written_ok =
|
||||
@@ -5188,12 +5545,13 @@ TEST(daemon_runtime_process_fingerprint_never_hashes_replacement_path) {
|
||||
int replacement_written =
|
||||
setup ? snprintf(replacement_path, sizeof(replacement_path), "%s/replacement", directory)
|
||||
: -1;
|
||||
/* The copied image is this runner in holder mode, not a system utility:
|
||||
* a multi-call coreutils /bin/cat (uutils) prints "unknown program" and
|
||||
* exits when executed under the copied name. */
|
||||
/* The copied image is the image probe in holder mode, not a system
|
||||
* utility: a multi-call coreutils /bin/cat (uutils) prints "unknown
|
||||
* program" and exits when executed under the copied name. Not this runner
|
||||
* either: the fingerprint below hashes the whole held image. */
|
||||
setup = setup && image_written > 0 && image_written < (int)sizeof(image_path) &&
|
||||
replacement_written > 0 && replacement_written < (int)sizeof(replacement_path) &&
|
||||
runtime_test_copy_self_image(image_path);
|
||||
runtime_test_copy_probe_image(image_path);
|
||||
|
||||
FILE *replacement_file = setup ? cbm_fopen(replacement_path, "wb") : NULL;
|
||||
bool replacement_written_ok =
|
||||
|
||||
@@ -412,6 +412,140 @@ TEST(extract_cpp_real_in_body_error_still_flagged_issue1071) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1546: the grammars built on tree-sitter-c read a backslash line splice
|
||||
* inside a string literal as `\` plus one character. With CRLF line endings
|
||||
* that character was the CR, the LF then ended the literal, and every
|
||||
* function after it was lost to one ERROR region. */
|
||||
static const CBMDefinition *splice_def(CBMFileResult *r, const char *name) {
|
||||
for (int i = 0; i < r->defs.count; i++) {
|
||||
if (r->defs.items[i].name && strcmp(r->defs.items[i].name, name) == 0) {
|
||||
return &r->defs.items[i];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The reporter's file, byte for byte. */
|
||||
TEST(extract_cpp_crlf_string_splice_keeps_later_functions_issue1546) {
|
||||
CBMFileResult *r = extract("void Head()\r\n"
|
||||
"{\r\n"
|
||||
" int h = 0;\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void Middle()\r\n"
|
||||
"{\r\n"
|
||||
" const wchar_t* s = L\"line 0\\r\\n\\\r\n"
|
||||
"line 1\\r\\n\";\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void TrailerOne()\r\n"
|
||||
"{\r\n"
|
||||
" int a = 1;\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void TrailerTwo()\r\n"
|
||||
"{\r\n"
|
||||
" int b = 2;\r\n"
|
||||
"}\r\n",
|
||||
CBM_LANG_CPP, "t", "repro.cpp");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->has_error);
|
||||
ASSERT_FALSE(r->parse_incomplete);
|
||||
const CBMDefinition *middle = splice_def(r, "Middle");
|
||||
const CBMDefinition *one = splice_def(r, "TrailerOne");
|
||||
const CBMDefinition *two = splice_def(r, "TrailerTwo");
|
||||
ASSERT_NOT_NULL(middle);
|
||||
ASSERT_NOT_NULL(one);
|
||||
ASSERT_NOT_NULL(two);
|
||||
ASSERT_EQ((int)middle->start_line, 6);
|
||||
ASSERT_EQ((int)middle->end_line, 10);
|
||||
ASSERT_EQ((int)one->start_line, 12);
|
||||
ASSERT_EQ((int)two->start_line, 17);
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Every grammar built on tree-sitter-c has the same escape rule. */
|
||||
TEST(extract_c_family_crlf_string_splice_parses_clean_issue1546) {
|
||||
static const CBMLanguage langs[] = {CBM_LANG_C, CBM_LANG_CPP, CBM_LANG_CUDA,
|
||||
CBM_LANG_OBJC, CBM_LANG_GLSL, CBM_LANG_HLSL,
|
||||
CBM_LANG_ISPC, CBM_LANG_SLANG};
|
||||
const char *src = "void Head()\r\n"
|
||||
"{\r\n"
|
||||
" int h = 0;\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void Middle()\r\n"
|
||||
"{\r\n"
|
||||
" const char *s = \"line 0\\\r\n"
|
||||
"line 1\";\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"void TrailerOne()\r\n"
|
||||
"{\r\n"
|
||||
" int a = 1;\r\n"
|
||||
"}\r\n";
|
||||
for (size_t i = 0; i < sizeof(langs) / sizeof(langs[0]); i++) {
|
||||
CBMFileResult *r = extract(src, langs[i], "t", "splice.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->parse_incomplete);
|
||||
const CBMDefinition *middle = splice_def(r, "Middle");
|
||||
const CBMDefinition *tail = splice_def(r, "TrailerOne");
|
||||
ASSERT_NOT_NULL(middle);
|
||||
ASSERT_NOT_NULL(tail);
|
||||
ASSERT_EQ((int)middle->end_line, 10);
|
||||
ASSERT_EQ((int)tail->start_line, 12);
|
||||
cbm_free_result(r);
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Splices in a macro and a line comment, which the grammar already read with
|
||||
* CRLF, still do; the preprocessed second pass sees the rewritten bytes too. */
|
||||
TEST(extract_c_crlf_splices_in_macro_comment_and_string_issue1546) {
|
||||
CBMFileResult *r = extract("#define LOG2(a, b) \\\r\n"
|
||||
" do { log_it(a); \\\r\n"
|
||||
" log_it(b); } while (0)\r\n"
|
||||
"\r\n"
|
||||
"// a comment that ends with a splice \\\r\n"
|
||||
" and goes on here\r\n"
|
||||
"\r\n"
|
||||
"static const char *usage = \"usage: tool\\n\\\r\n"
|
||||
" -h help\\n\";\r\n"
|
||||
"\r\n"
|
||||
"int helper(int x)\r\n"
|
||||
"{\r\n"
|
||||
" return x + 1;\r\n"
|
||||
"}\r\n"
|
||||
"\r\n"
|
||||
"int main(void)\r\n"
|
||||
"{\r\n"
|
||||
" LOG2(\"a\", \"b\");\r\n"
|
||||
" return helper(2);\r\n"
|
||||
"}\r\n",
|
||||
CBM_LANG_C, "t", "mix.c");
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_FALSE(r->parse_incomplete);
|
||||
ASSERT(has_def(r, "Macro", "LOG2"));
|
||||
const CBMDefinition *usage = splice_def(r, "usage");
|
||||
const CBMDefinition *helper = splice_def(r, "helper");
|
||||
ASSERT_NOT_NULL(usage);
|
||||
ASSERT_NOT_NULL(helper);
|
||||
ASSERT_EQ((int)usage->end_line, 9);
|
||||
ASSERT_EQ((int)helper->start_line, 11);
|
||||
ASSERT_EQ((int)helper->end_line, 14);
|
||||
for (int i = 0; i < r->calls.count; i++) {
|
||||
const CBMCall *c = &r->calls.items[i];
|
||||
if (c->callee_name && strcmp(c->callee_name, "helper") == 0) {
|
||||
ASSERT_NOT_NULL(c->enclosing_func_qn);
|
||||
ASSERT_NOT_NULL(strstr(c->enclosing_func_qn, "main"));
|
||||
}
|
||||
}
|
||||
ASSERT(has_call(r, "log_it"));
|
||||
cbm_free_result(r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1735: the #1071 check's cost. cbm_subtract_macro_invocation_regions asked
|
||||
* "is this region a macro call?" before "is it inside a function?", and the
|
||||
* first question walked the source from byte 0 for every region: regions x
|
||||
@@ -16326,6 +16460,9 @@ SUITE(extraction) {
|
||||
RUN_TEST(extract_cpp_macros_issue375);
|
||||
RUN_TEST(extract_cpp_functionlike_macro_type_arg_no_false_parse_partial_issue1071);
|
||||
RUN_TEST(extract_cpp_real_in_body_error_still_flagged_issue1071);
|
||||
RUN_TEST(extract_cpp_crlf_string_splice_keeps_later_functions_issue1546);
|
||||
RUN_TEST(extract_c_family_crlf_string_splice_parses_clean_issue1546);
|
||||
RUN_TEST(extract_c_crlf_splices_in_macro_comment_and_string_issue1546);
|
||||
RUN_TEST(macro_check_reads_no_source_for_regions_outside_functions_issue1735);
|
||||
RUN_TEST(macro_check_locates_lines_with_one_table_issue1735);
|
||||
RUN_TEST(extract_gdscript_issue186);
|
||||
|
||||
+5
-1
@@ -1168,11 +1168,15 @@ TEST(golsp_crossfile_interface_field_chain) {
|
||||
"type Context struct {\n\techo *echo.Echo\n}\n\n"
|
||||
"func (c *Context) process() {\n\tc.echo.Binder.Bind(\"hello\")\n}\n";
|
||||
|
||||
/* The walked file's struct carries its fields as the pipeline folds them
|
||||
* (pxc_fold_struct_fields): every route reads a struct's fields from its
|
||||
* definition. */
|
||||
CBMLSPDef defs[] = {
|
||||
{.qualified_name = "test.main.Context",
|
||||
.short_name = "Context",
|
||||
.label = "Type",
|
||||
.def_module_qn = "test.main"},
|
||||
.def_module_qn = "test.main",
|
||||
.field_defs = "echo:*echo.Echo"},
|
||||
{.qualified_name = "test.main.Context.process",
|
||||
.short_name = "process",
|
||||
.label = "Method",
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
#ifndef TEST_IMAGE_PROBE_H
|
||||
#define TEST_IMAGE_PROBE_H
|
||||
|
||||
/*
|
||||
* The image probe: a small executable built beside every test runner
|
||||
* (Makefile.cbm, <runner>-image-probe, e.g. build/c/test-runner-image-probe)
|
||||
* from tests/image_probe_main.c, tests/image_probe_roles.c, the daemon runtime
|
||||
* and foundation (~5 MB with sanitizers, against ~800 MB for the runner).
|
||||
*
|
||||
* Tests that need a real, separately executed process image use it instead of
|
||||
* a copy of the runner: daemon_runtime's copied-image probes run their daemon
|
||||
* and clients from it, and the cli install tests publish it as the installed
|
||||
* binary. Each of those used to SHA-256 the whole sanitized runner, several
|
||||
* times per test, and one such hash costs 70-95 s on some hosted x86 CPUs: a
|
||||
* daemon still hashing a peer copy missed the client's exchange budget, and the
|
||||
* cli suite ran past its wall-clock ceiling, decided by which CPU a job drew.
|
||||
* The production verification code is unchanged; only the image is smaller.
|
||||
*
|
||||
* Roles (argv[1]), dispatched by tf_image_probe_dispatch:
|
||||
* __cbm_runtime_serve <parent> <key> <version> <owner:0|1>
|
||||
* __cbm_runtime_hello_client <parent> <key> <version> <build>
|
||||
* __cbm_runtime_activation_client <parent> <key> <version> <build> <action>
|
||||
* __cbm_runtime_mapped_hello_client <mapped-image> <parent> <key> <version> <build>
|
||||
* __cbm_runtime_image_holder [<ready-event>]
|
||||
* The probe's main also answers --version (install verification runs it).
|
||||
*/
|
||||
|
||||
#include "foundation/compat_fs.h" /* cbm_fopen: the probe path may be non-ASCII */
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include "foundation/win_utf8.h"
|
||||
#include <stdlib.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#ifdef __APPLE__
|
||||
#include <libproc.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* Runs the role argv[1] names: its exit code, or -1 when argv names none. */
|
||||
int tf_image_probe_dispatch(int argc, char **argv);
|
||||
|
||||
/* The probe built beside the running runner: the runner's own image path
|
||||
* without ".exe", then "-image-probe" (".exe" again on Windows). False when
|
||||
* the path cannot be formed or names no file: a missing probe is a build
|
||||
* defect the calling test reports, never a skip. */
|
||||
static inline bool th_image_probe_path(char *out, size_t cap) {
|
||||
if (!out || cap == 0) {
|
||||
return false;
|
||||
}
|
||||
out[0] = '\0';
|
||||
char self[4096] = {0};
|
||||
#ifdef _WIN32
|
||||
char *module = cbm_module_path_utf8();
|
||||
size_t module_length = module ? strlen(module) : 0;
|
||||
bool resolved = module_length > 0 && module_length < sizeof(self);
|
||||
if (resolved) {
|
||||
memcpy(self, module, module_length + 1);
|
||||
}
|
||||
free(module);
|
||||
size_t length = resolved ? strlen(self) : 0;
|
||||
if (length > 4 && _stricmp(self + length - 4, ".exe") == 0) {
|
||||
self[length - 4] = '\0';
|
||||
}
|
||||
const char *suffix = "-image-probe.exe";
|
||||
#elif defined(__APPLE__)
|
||||
int length = proc_pidpath(getpid(), self, (uint32_t)sizeof(self));
|
||||
bool resolved = length > 0 && length < (int)sizeof(self);
|
||||
if (resolved) {
|
||||
self[length] = '\0';
|
||||
}
|
||||
const char *suffix = "-image-probe";
|
||||
#elif defined(__linux__)
|
||||
ssize_t length = readlink("/proc/self/exe", self, sizeof(self) - 1);
|
||||
bool resolved = length > 0 && length < (ssize_t)sizeof(self) - 1;
|
||||
if (resolved) {
|
||||
self[length] = '\0';
|
||||
}
|
||||
const char *suffix = "-image-probe";
|
||||
#else
|
||||
bool resolved = false;
|
||||
const char *suffix = "";
|
||||
#endif
|
||||
int written = resolved ? snprintf(out, cap, "%s%s", self, suffix) : -1;
|
||||
if (written <= 0 || (size_t)written >= cap) {
|
||||
out[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
FILE *probe = cbm_fopen(out, "rb");
|
||||
if (!probe) {
|
||||
out[0] = '\0';
|
||||
return false;
|
||||
}
|
||||
(void)fclose(probe);
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif /* TEST_IMAGE_PROBE_H */
|
||||
@@ -568,6 +568,89 @@ TEST(index_format_v5_scala_packages_rebuild) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* Format 6 recorded no included files on its lsp_surface rows (#2993). An
|
||||
* incremental refresh re-extracts the includers of a changed header from that
|
||||
* record, so a format-6 index refreshed in place would keep an includer's
|
||||
* edges stale after an edit to its header alone. */
|
||||
static const RFile k_include_files[] = {
|
||||
{"lib/m.h", "#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n"},
|
||||
{"lib/a.c",
|
||||
"#define A_LOCAL 1\n#include \"m.h\"\n\nvoid caller(int v) {\n DO_WORK(v);\n}\n"},
|
||||
{"lib/t.c", "void real_target(int x) { (void)x; }\nvoid other_target(int x) { (void)x; }\n"},
|
||||
};
|
||||
|
||||
/* CALLS edges from the function `caller` to the Function `target`. */
|
||||
static int include_caller_calls(cbm_store_t *s, const char *target) {
|
||||
char sql[512];
|
||||
snprintf(sql, sizeof(sql),
|
||||
"SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
|
||||
"t.id=e.target_id WHERE e.type='CALLS' AND s.name='caller' AND t.name='%s' AND "
|
||||
"t.label='Function'",
|
||||
target);
|
||||
sqlite3_stmt *st = NULL;
|
||||
if (sqlite3_prepare_v2(cbm_store_get_db(s), sql, -1, &st, NULL) != SQLITE_OK) {
|
||||
return -1;
|
||||
}
|
||||
int count = sqlite3_step(st) == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1;
|
||||
sqlite3_finalize(st);
|
||||
return count;
|
||||
}
|
||||
|
||||
static int include_rows_recorded(cbm_store_t *s) {
|
||||
sqlite3_stmt *st = NULL;
|
||||
if (sqlite3_prepare_v2(cbm_store_get_db(s),
|
||||
"SELECT COUNT(*) FROM lsp_surface WHERE included_files <> ''", -1, &st,
|
||||
NULL) != SQLITE_OK) {
|
||||
return -1;
|
||||
}
|
||||
int count = sqlite3_step(st) == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1;
|
||||
sqlite3_finalize(st);
|
||||
return count;
|
||||
}
|
||||
|
||||
TEST(index_format_v6_included_files_rebuild) {
|
||||
RProj lp;
|
||||
cbm_store_t *q0 = rh_index_files(&lp, k_include_files, 3);
|
||||
ASSERT_NOT_NULL(q0);
|
||||
ASSERT_EQ(include_caller_calls(q0, "real_target"), 1);
|
||||
ASSERT_EQ(include_rows_recorded(q0), 1);
|
||||
cbm_store_close(q0);
|
||||
|
||||
/* The old shape: no row records the files its lookup read. */
|
||||
cbm_store_t *w = cbm_store_open_path(lp.dbpath);
|
||||
ASSERT_NOT_NULL(w);
|
||||
ASSERT_EQ(sqlite3_exec(cbm_store_get_db(w), "UPDATE lsp_surface SET included_files = ''", NULL,
|
||||
NULL, NULL),
|
||||
SQLITE_OK);
|
||||
ASSERT_EQ(cbm_store_set_format_version(w, 6), CBM_STORE_OK);
|
||||
cbm_store_close(w);
|
||||
|
||||
/* Only the header changes. */
|
||||
char path[700];
|
||||
snprintf(path, sizeof(path), "%s/lib/m.h", lp.tmpdir);
|
||||
FILE *fp = fopen(path, "wb");
|
||||
ASSERT_NOT_NULL(fp);
|
||||
fputs("#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n", fp);
|
||||
fclose(fp);
|
||||
|
||||
char *resp = index_capture(&lp);
|
||||
ASSERT_NOT_NULL(resp);
|
||||
free(resp);
|
||||
cbm_store_t *r = cbm_store_open_path(lp.dbpath);
|
||||
ASSERT_NOT_NULL(r);
|
||||
ASSERT_EQ(include_caller_calls(r, "other_target"), 1);
|
||||
ASSERT_EQ(include_caller_calls(r, "real_target"), 0);
|
||||
if (!strstr(g_log_buf, "format_change_reindex")) {
|
||||
FAIL("a format-6 index was not routed through the full-reindex path");
|
||||
}
|
||||
ASSERT_EQ(include_rows_recorded(r), 1);
|
||||
int format = -1;
|
||||
ASSERT_EQ(cbm_store_get_format_version(r, &format), CBM_STORE_OK);
|
||||
ASSERT_EQ(format, CBM_INDEX_FORMAT_VERSION);
|
||||
rh_cleanup(&lp, r);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(index_format) {
|
||||
RUN_TEST(index_format_siblings_distinct_and_searchable);
|
||||
RUN_TEST(index_format_legacy_index_rebuilds_and_repairs);
|
||||
@@ -575,4 +658,5 @@ SUITE(index_format) {
|
||||
RUN_TEST(index_format_swift_collisions_and_stale_calls_rebuild);
|
||||
RUN_TEST(index_format_v2_images_rebuild_without_invented_host);
|
||||
RUN_TEST(index_format_v5_scala_packages_rebuild);
|
||||
RUN_TEST(index_format_v6_included_files_rebuild);
|
||||
}
|
||||
|
||||
+17
-132
@@ -11,7 +11,7 @@ int tf_deselected_count = 0;
|
||||
|
||||
#include "test_framework.h"
|
||||
#include "test_helpers.h"
|
||||
#include "test_daemon_runtime_contract.h"
|
||||
#include "test_image_probe.h"
|
||||
#include "foundation/compat.h" /* cbm_setenv — #845 supervisor kill switch */
|
||||
#include "foundation/compat_fs.h" /* cbm_fopen — worker response file */
|
||||
#include "foundation/constants.h" /* CBM_SZ_4K — forced stderr buffer */
|
||||
@@ -48,10 +48,6 @@ int tf_deselected_count = 0;
|
||||
#include <limits.h> /* INT_MAX: a handed-down descriptor */
|
||||
#include <sys/wait.h> /* waitpid: the process-tree probe root */
|
||||
#include <unistd.h>
|
||||
#ifdef __APPLE__
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#endif
|
||||
#ifdef CBM_TEST_COVERAGE
|
||||
#include <dlfcn.h> /* the libc functions behind the profile-keeping ones */
|
||||
#include <fcntl.h> /* the marker of a forked child */
|
||||
@@ -657,129 +653,12 @@ static int tf_maybe_run_version_cohort_crash_holder(int argc, char **argv) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static int tf_maybe_run_runtime_image_holder(int argc, char **argv) {
|
||||
#ifdef _WIN32
|
||||
if (argc != 3 || strcmp(argv[1], "__cbm_runtime_image_holder") != 0) {
|
||||
return -1;
|
||||
}
|
||||
HANDLE ready = OpenEventA(EVENT_MODIFY_STATE, FALSE, argv[2]);
|
||||
bool announced = ready && SetEvent(ready) != 0;
|
||||
if (ready) {
|
||||
(void)CloseHandle(ready);
|
||||
}
|
||||
if (!announced) {
|
||||
return 24;
|
||||
}
|
||||
Sleep(INFINITE);
|
||||
return 25;
|
||||
#else
|
||||
/* POSIX copied-image holder: block reading stdin until the parent closes
|
||||
* the release pipe, exactly like the cat(1) donor this replaced. A system
|
||||
* utility cannot serve as the copied image — a multi-call coreutils
|
||||
* binary (uutils cat) refuses to execute under the copied name. */
|
||||
if (argc != 2 || strcmp(argv[1], "__cbm_runtime_image_holder") != 0) {
|
||||
return -1;
|
||||
}
|
||||
char release[16];
|
||||
ssize_t count;
|
||||
do {
|
||||
count = read(STDIN_FILENO, release, sizeof(release));
|
||||
} while (count > 0 || (count < 0 && errno == EINTR));
|
||||
return count == 0 ? 0 : 25;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Real copied-image HELLO probe used by daemon_runtime. Keeping this in the
|
||||
* test runner avoids any production-only test hook: the daemon authenticates
|
||||
* and fingerprints an ordinary, separately executed process image. */
|
||||
static int tf_maybe_run_runtime_hello_client(int argc, char **argv) {
|
||||
if (argc != 6 || strcmp(argv[1], "__cbm_runtime_hello_client") != 0) {
|
||||
return -1;
|
||||
}
|
||||
cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_ipc_endpoint_new(argv[3], argv[2]);
|
||||
cbm_daemon_build_identity_t identity = {
|
||||
.semantic_version = argv[4],
|
||||
.build_fingerprint = argv[5],
|
||||
};
|
||||
cbm_daemon_runtime_connect_result_t result;
|
||||
memset(&result, 0, sizeof(result));
|
||||
cbm_daemon_runtime_client_t *client =
|
||||
endpoint ? cbm_daemon_runtime_client_connect(endpoint, &identity,
|
||||
TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result)
|
||||
: NULL;
|
||||
bool accepted = client && result.status == CBM_DAEMON_RUNTIME_CONNECT_ACCEPTED &&
|
||||
result.hello_status == CBM_DAEMON_HELLO_COMPATIBLE;
|
||||
bool closed =
|
||||
!client || cbm_daemon_runtime_client_close(client, TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS);
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
if (!accepted) {
|
||||
return 26;
|
||||
}
|
||||
return closed ? 0 : 27;
|
||||
}
|
||||
|
||||
/* Real copied-image activation probe. The request identity is supplied by the
|
||||
* executing copy so the daemon must authenticate that peer image rather than
|
||||
* require the active generation's build fingerprint. */
|
||||
static int tf_maybe_run_runtime_activation_client(int argc, char **argv) {
|
||||
if (argc != 7 || strcmp(argv[1], "__cbm_runtime_activation_client") != 0) {
|
||||
return -1;
|
||||
}
|
||||
char *action_end = NULL;
|
||||
unsigned long action_value = strtoul(argv[6], &action_end, 10);
|
||||
bool action_valid = action_end != argv[6] && *action_end == '\0' &&
|
||||
action_value >= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL &&
|
||||
action_value <= (unsigned long)CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL;
|
||||
cbm_daemon_ipc_endpoint_t *endpoint =
|
||||
action_valid ? cbm_daemon_ipc_endpoint_new(argv[3], argv[2]) : NULL;
|
||||
cbm_daemon_build_identity_t identity = {
|
||||
.semantic_version = argv[4],
|
||||
.build_fingerprint = argv[5],
|
||||
};
|
||||
cbm_daemon_runtime_activation_result_t result;
|
||||
memset(&result, 0, sizeof(result));
|
||||
bool exchanged =
|
||||
endpoint && cbm_daemon_runtime_request_activation_shutdown(
|
||||
endpoint, &identity, (cbm_daemon_runtime_activation_action_t)action_value,
|
||||
TF_RUNTIME_IMAGE_EXCHANGE_TIMEOUT_MS, &result);
|
||||
cbm_daemon_ipc_endpoint_free(endpoint);
|
||||
return exchanged && result.accepted ? 0 : 29;
|
||||
}
|
||||
|
||||
/* macOS adversarial HELLO probe: execute this mode from a foreign process
|
||||
* image while mapping the genuine runner RX. The daemon must authenticate the
|
||||
* main image, not merely find its own vnode in an arbitrary executable map. */
|
||||
static int tf_maybe_run_runtime_mapped_hello_client(int argc, char **argv) {
|
||||
#ifdef __APPLE__
|
||||
if (argc != 7 || strcmp(argv[1], "__cbm_runtime_mapped_hello_client") != 0) {
|
||||
return -1;
|
||||
}
|
||||
int image_fd = open(argv[2], O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
|
||||
void *mapping =
|
||||
image_fd >= 0 ? mmap(NULL, 1, PROT_READ | PROT_EXEC, MAP_PRIVATE, image_fd, 0) : MAP_FAILED;
|
||||
bool mapped = mapping != MAP_FAILED;
|
||||
if (image_fd >= 0 && close(image_fd) != 0) {
|
||||
mapped = false;
|
||||
}
|
||||
if (!mapped) {
|
||||
if (mapping != MAP_FAILED) {
|
||||
(void)munmap(mapping, 1);
|
||||
}
|
||||
return 28;
|
||||
}
|
||||
|
||||
char *hello_argv[] = {argv[0], "__cbm_runtime_hello_client", argv[3], argv[4], argv[5],
|
||||
argv[6]};
|
||||
int result = tf_maybe_run_runtime_hello_client(6, hello_argv);
|
||||
if (munmap(mapping, 1) != 0) {
|
||||
return 28;
|
||||
}
|
||||
return result >= 0 ? result : 28;
|
||||
#else
|
||||
(void)argc;
|
||||
(void)argv;
|
||||
return -1;
|
||||
#endif
|
||||
/* The image probe's roles (tests/image_probe_roles.c, tests/test_image_probe.h).
|
||||
* The runner itself dispatches only the image holder through here; tf_roles
|
||||
* names the probe's other literals under TF_PHASE_PROBE so the test-impact
|
||||
* engine still maps a change those roles reach to the tests that start them. */
|
||||
static int tf_role_image_probe(int argc, char **argv) {
|
||||
return tf_image_probe_dispatch(argc, argv);
|
||||
}
|
||||
|
||||
static int tf_maybe_run_mcp_idxfailclosed_probe(int argc, char **argv) {
|
||||
@@ -1860,6 +1739,7 @@ extern void suite_activation_transaction(void);
|
||||
extern void suite_system_info(void);
|
||||
extern void suite_worker_pool(void);
|
||||
extern void suite_parallel(void);
|
||||
extern void suite_type_scope(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);
|
||||
@@ -2289,6 +2169,7 @@ typedef enum {
|
||||
TF_PHASE_SEAMED, /* after the spill and build-fingerprint pins */
|
||||
TF_PHASE_WORKER, /* after the fingerprint capture; the literal anywhere in argv */
|
||||
TF_PHASE_SPAWNER, /* never dispatched: one more literal a spawner names */
|
||||
TF_PHASE_PROBE, /* never dispatched here: the image probe runs the role */
|
||||
} tf_phase_t;
|
||||
|
||||
typedef struct {
|
||||
@@ -2314,10 +2195,11 @@ static const tf_role_t tf_roles[] = {
|
||||
TF_ROLE(TF_PHASE_INSTALL, "--build-config", tf_role_build_config),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "--userns-secure-probe", tf_role_userns_secure_probe),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_mcp_idxfailclosed_probe", tf_maybe_run_mcp_idxfailclosed_probe),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_image_holder", tf_maybe_run_runtime_image_holder),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_hello_client", tf_maybe_run_runtime_hello_client),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_activation_client", tf_maybe_run_runtime_activation_client),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_mapped_hello_client", tf_maybe_run_runtime_mapped_hello_client),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_runtime_image_holder", tf_role_image_probe),
|
||||
TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_serve", tf_role_image_probe),
|
||||
TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_hello_client", tf_role_image_probe),
|
||||
TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_activation_client", tf_role_image_probe),
|
||||
TF_ROLE(TF_PHASE_PROBE, "__cbm_runtime_mapped_hello_client", tf_role_image_probe),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_version_cohort_crash_holder", tf_maybe_run_version_cohort_crash_holder),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_daemon_ipc_lock_probe", tf_maybe_run_daemon_ipc_lock_probe),
|
||||
TF_ROLE(TF_PHASE_SEAMED, "__cbm_deleted_self_probe", tf_maybe_run_deleted_self_probe),
|
||||
@@ -2748,6 +2630,9 @@ int main(int argc, char **argv) {
|
||||
/* Parallel pipeline */
|
||||
RUN_SELECTED_SUITE(parallel);
|
||||
|
||||
/* Declared types resolved in the scope that wrote them */
|
||||
RUN_SELECTED_SUITE(type_scope);
|
||||
|
||||
/* Promoted lexical-resolution regression contracts. */
|
||||
RUN_SELECTED_SUITE(repro_lexical_binding_precision);
|
||||
|
||||
|
||||
+118
-2
@@ -307,6 +307,8 @@ static bool g_harness_spill = false;
|
||||
static int64_t g_harness_parked = -1;
|
||||
/* Opt-in: hand cbm_parallel_resolve the production Tier-2 C# registry. */
|
||||
static bool g_harness_cs_registry = false;
|
||||
/* Opt-in: the same for the Tier-2 C/C++ registry. */
|
||||
static bool g_harness_c_registry = false;
|
||||
|
||||
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,
|
||||
@@ -385,10 +387,14 @@ static cbm_gbuf_t *run_parallel_with_extract_opts_and_mutator(
|
||||
if (g_harness_cs_registry && all_defs) {
|
||||
harness_registries.cs = cbm_cs_build_cross_registry(&cross_arena, all_defs, def_count);
|
||||
}
|
||||
if (g_harness_c_registry && all_defs) {
|
||||
harness_registries.c = cbm_c_build_cross_registry(&cross_arena, all_defs, def_count);
|
||||
}
|
||||
cbm_parallel_resolve(&ctx, files, file_count, result_cache, &shared_ids, worker_count, all_defs,
|
||||
def_count, def_modules, module_def_index,
|
||||
g_harness_cs_registry ? &harness_registries
|
||||
: NULL /* tests use per-file path */);
|
||||
g_harness_cs_registry || g_harness_c_registry
|
||||
? &harness_registries
|
||||
: NULL /* tests use per-file path */);
|
||||
cbm_gbuf_set_next_id(gbuf, atomic_load(&shared_ids));
|
||||
|
||||
cbm_pxc_free_module_def_index(module_def_index);
|
||||
@@ -4879,6 +4885,115 @@ TEST(parallel_cross_file_reread_preserves_unretained_edges) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #1546: the per-file extract parses a C-family file with each `\` CR LF line
|
||||
* splice rewritten as space `\` LF. The cross-file C/C++ LSP pass reads the
|
||||
* file again (the parallel driver from its retained copy, the sequential one
|
||||
* from disk) and must read it the same way. o->run() after the string splice
|
||||
* is a call only that pass resolves: the struct is declared in another file.
|
||||
* LF is the control; with CRLF the cross pass used to see the rest of main.cpp
|
||||
* as one ERROR region and lose the edge in both drivers. */
|
||||
static const char *const crlf_splice_files[][2] = {
|
||||
{"other.h", "#ifndef OTHER_H\n"
|
||||
"#define OTHER_H\n"
|
||||
"struct ops { int (*run)(int); };\n"
|
||||
"struct ops *get_ops(void);\n"
|
||||
"#endif\n"},
|
||||
{"other.cpp", "#include \"other.h\"\n"
|
||||
"static int run_impl(int x) { return x; }\n"
|
||||
"static struct ops the_ops = { run_impl };\n"
|
||||
"struct ops *get_ops(void)\n"
|
||||
"{\n"
|
||||
" return &the_ops;\n"
|
||||
"}\n"},
|
||||
{"main.cpp", "#include \"other.h\"\n"
|
||||
"void Middle(void)\n"
|
||||
"{\n"
|
||||
" const wchar_t* s = L\"line 0\\r\\n\\\n"
|
||||
"line 1\\r\\n\";\n"
|
||||
"}\n"
|
||||
"\n"
|
||||
"int after_one(void)\n"
|
||||
"{\n"
|
||||
" struct ops *o = get_ops();\n"
|
||||
" return o->run(3);\n"
|
||||
"}\n"},
|
||||
};
|
||||
|
||||
static int write_with_line_endings(const char *path, const char *lf_text, bool crlf) {
|
||||
char *text = malloc(strlen(lf_text) * 2 + 1);
|
||||
if (!text) {
|
||||
return -1;
|
||||
}
|
||||
size_t n = 0;
|
||||
for (const char *p = lf_text; *p; p++) {
|
||||
if (crlf && *p == '\n') {
|
||||
text[n++] = '\r';
|
||||
}
|
||||
text[n++] = *p;
|
||||
}
|
||||
text[n] = '\0';
|
||||
int rc = th_write_file(path, text);
|
||||
free(text);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static bool crlf_splice_has_lsp_edge(const cbm_gbuf_t *gbuf) {
|
||||
const cbm_gbuf_edge_t *edge =
|
||||
gbuf ? find_call_edge_to_target_fragment(gbuf, "main.after_one", "ops.run") : NULL;
|
||||
return edge && edge->properties_json &&
|
||||
strstr(edge->properties_json, "\"strategy\":\"lsp") != NULL;
|
||||
}
|
||||
|
||||
TEST(cross_file_cpp_lsp_after_crlf_string_splice_issue1546) {
|
||||
enum { CRLF_SPLICE_FILES = 3 };
|
||||
bool seq_edge[2] = {false};
|
||||
bool par_edge[2] = {false};
|
||||
for (int crlf = 0; crlf < 2; crlf++) {
|
||||
char tmpdir[256];
|
||||
snprintf(tmpdir, sizeof(tmpdir), "/tmp/cbm_par_crlf_XXXXXX");
|
||||
if (!cbm_mkdtemp(tmpdir)) {
|
||||
FAIL("mkdtemp failed");
|
||||
}
|
||||
char paths[CRLF_SPLICE_FILES][512];
|
||||
cbm_file_info_t files[CRLF_SPLICE_FILES] = {0};
|
||||
bool written = true;
|
||||
for (int i = 0; i < CRLF_SPLICE_FILES; i++) {
|
||||
snprintf(paths[i], sizeof(paths[i]), "%s/%s", tmpdir, crlf_splice_files[i][0]);
|
||||
written = written &&
|
||||
write_with_line_endings(paths[i], crlf_splice_files[i][1], crlf != 0) == 0;
|
||||
files[i].path = paths[i];
|
||||
files[i].rel_path = (char *)crlf_splice_files[i][0];
|
||||
files[i].language = CBM_LANG_CPP;
|
||||
}
|
||||
if (!written) {
|
||||
th_rmtree(tmpdir);
|
||||
FAIL("failed to write the CRLF splice fixture");
|
||||
}
|
||||
/* Both drivers resolve C/C++ against the shared Tier-2 registry, as
|
||||
* production does; tests/test_c_lsp.c covers the per-file entry. */
|
||||
cbm_gbuf_t *seq =
|
||||
run_sequential_with_lsp_cross("cbm_crlf", tmpdir, files, CRLF_SPLICE_FILES);
|
||||
g_harness_c_registry = true;
|
||||
cbm_gbuf_t *par = run_parallel("cbm_crlf", tmpdir, files, CRLF_SPLICE_FILES, 2);
|
||||
g_harness_c_registry = false;
|
||||
seq_edge[crlf] = crlf_splice_has_lsp_edge(seq);
|
||||
par_edge[crlf] = crlf_splice_has_lsp_edge(par);
|
||||
if (!seq_edge[crlf] || !par_edge[crlf]) {
|
||||
printf(" CRLF splice diagnostic (%s): sequential=%s parallel=%s\n",
|
||||
crlf ? "CRLF" : "LF", seq_edge[crlf] ? "present" : "absent",
|
||||
par_edge[crlf] ? "present" : "absent");
|
||||
}
|
||||
cbm_gbuf_free(seq);
|
||||
cbm_gbuf_free(par);
|
||||
th_rmtree(tmpdir);
|
||||
}
|
||||
ASSERT_TRUE(seq_edge[0]);
|
||||
ASSERT_TRUE(par_edge[0]);
|
||||
ASSERT_TRUE(seq_edge[1]);
|
||||
ASSERT_TRUE(par_edge[1]);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* issue #294: gRPC service-name extraction must (a) preserve the canonical
|
||||
* proto service name (FooServiceClient → FooService, not Foo) and (b) only
|
||||
* match real stub/client types — ordinary receiver vars must NOT produce
|
||||
@@ -6138,6 +6253,7 @@ SUITE(parallel) {
|
||||
RUN_TEST(parallel_python_lsp_override_cross_file_emits_lsp_strategy_edges);
|
||||
RUN_TEST(parallel_go_cross_package_field_chain_resolves);
|
||||
RUN_TEST(parallel_cross_file_reread_preserves_unretained_edges);
|
||||
RUN_TEST(cross_file_cpp_lsp_after_crlf_string_splice_issue1546);
|
||||
RUN_TEST(parallel_java_kotlin_lsp_override_cross_file_emits_lsp_strategy_edges);
|
||||
RUN_TEST(parallel_rust_external_target_contract);
|
||||
RUN_TEST(parallel_java_external_target_contract);
|
||||
|
||||
+498
-14
@@ -2416,6 +2416,97 @@ TEST(pipeline_incremental_keeps_ansible_includes_of_an_edited_file) {
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* IMPORTS edges the Ansible pass drew (via ansible); -1 on a query error. */
|
||||
static int ansible_import_edges(cbm_store_t *s, const char *project) {
|
||||
sqlite3_stmt *st = NULL;
|
||||
int n = -1;
|
||||
if (sqlite3_prepare_v2(cbm_store_get_db(s),
|
||||
"SELECT COUNT(*) FROM edges WHERE project=?1 AND type='IMPORTS' AND "
|
||||
"json_extract(properties,'$.via')='ansible'",
|
||||
-1, &st, NULL) == SQLITE_OK &&
|
||||
sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT) == SQLITE_OK &&
|
||||
sqlite3_step(st) == SQLITE_ROW) {
|
||||
n = sqlite3_column_int(st, 0);
|
||||
}
|
||||
sqlite3_finalize(st);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* A playbook extracts no imports of its own: its role and include edges come
|
||||
* from the Ansible pass, so the semantic pass builds its import map from those
|
||||
* IMPORTS edges (the slow path). Those keys were libc copies released through
|
||||
* the memory core, and on macOS, where the core's allocator is not the libc
|
||||
* one, the index worker crashed in the semantic pass on every repository of 50
|
||||
* files or fewer holding a role or an include (any repository at one worker).
|
||||
* Here the memory core's own count binds, whatever the allocator and wherever
|
||||
* the string landed: a block the core takes back without having handed it out
|
||||
* leaves its class below where it started. A first index of the same tree
|
||||
* warms what the process builds once and keeps (the semantic pass's
|
||||
* pretrained token table is one), so the readings are taken around a second,
|
||||
* identical full index and an incremental re-index of the edited playbook
|
||||
* (the incremental route runs the same pass for changed files): the verdict
|
||||
* does not depend on what ran before in the process. */
|
||||
TEST(pipeline_semantic_import_map_keys_come_from_the_memory_core) {
|
||||
if (setup_test_repo() != 0) {
|
||||
FAIL("failed to create temp dir");
|
||||
}
|
||||
write_temp_file(g_tmpdir, "site.yml",
|
||||
"- hosts: localhost\n roles:\n - web\n tasks:\n"
|
||||
" - include_tasks: tasks/setup.yml\n");
|
||||
write_temp_file(g_tmpdir, "roles/web/tasks/main.yml",
|
||||
"- name: Say hi\n debug:\n msg: hi\n");
|
||||
write_temp_file(g_tmpdir, "tasks/setup.yml", "- name: Setup\n debug:\n msg: setup\n");
|
||||
char warm_path[512];
|
||||
snprintf(warm_path, sizeof(warm_path), "%s/semantic_keys_warm.db", g_tmpdir);
|
||||
int warm_rc = -1;
|
||||
cbm_pipeline_t *warm = cbm_pipeline_new(g_tmpdir, warm_path, CBM_MODE_FULL);
|
||||
if (warm) {
|
||||
warm_rc = cbm_pipeline_run(warm);
|
||||
cbm_pipeline_free(warm);
|
||||
}
|
||||
char db_path[512];
|
||||
snprintf(db_path, sizeof(db_path), "%s/semantic_keys.db", g_tmpdir);
|
||||
|
||||
cbm_mem_class_flush_thread();
|
||||
size_t blocks_before = cbm_mem_class_live_blocks(CBM_MEM_CLASS_SEMANTIC);
|
||||
size_t bytes_before = cbm_mem_class_live_bytes(CBM_MEM_CLASS_SEMANTIC);
|
||||
int full_rc = -1;
|
||||
int incr_rc = -1;
|
||||
int imports = -1;
|
||||
cbm_pipeline_t *p1 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
|
||||
if (p1) {
|
||||
full_rc = cbm_pipeline_run(p1);
|
||||
cbm_store_t *s = cbm_store_open_path(db_path);
|
||||
if (s) {
|
||||
imports = ansible_import_edges(s, cbm_pipeline_project_name(p1));
|
||||
cbm_store_close(s);
|
||||
}
|
||||
cbm_pipeline_free(p1);
|
||||
}
|
||||
write_temp_file(g_tmpdir, "site.yml",
|
||||
"- hosts: localhost\n roles:\n - web\n tasks:\n"
|
||||
" - include_tasks: tasks/setup.yml\n - debug:\n msg: edited\n");
|
||||
cbm_pipeline_t *p2 = cbm_pipeline_new(g_tmpdir, db_path, CBM_MODE_FULL);
|
||||
if (p2) {
|
||||
incr_rc = cbm_pipeline_run(p2);
|
||||
cbm_pipeline_free(p2);
|
||||
}
|
||||
cbm_mem_class_flush_thread();
|
||||
size_t blocks_after = cbm_mem_class_live_blocks(CBM_MEM_CLASS_SEMANTIC);
|
||||
size_t bytes_after = cbm_mem_class_live_bytes(CBM_MEM_CLASS_SEMANTIC);
|
||||
teardown_test_repo();
|
||||
|
||||
ASSERT_EQ(warm_rc, 0);
|
||||
ASSERT_EQ(full_rc, 0);
|
||||
ASSERT_EQ(incr_rc, 0);
|
||||
/* The playbook's role and include are the IMPORTS edges the slow path reads. */
|
||||
ASSERT_TRUE(imports >= 2);
|
||||
/* Every SEMANTIC block taken back was handed out: the class is where it began. */
|
||||
ASSERT_TRUE(blocks_after == blocks_before);
|
||||
ASSERT_TRUE(bytes_after == bytes_before);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* The CALLS edges an Ansible notify draws (via notify); -1 on a query error. */
|
||||
static int ansible_notify_calls(cbm_store_t *s, const char *project) {
|
||||
sqlite3_stmt *st = NULL;
|
||||
@@ -32548,7 +32639,7 @@ TEST(pipeline_python_namespace_change_admission) {
|
||||
}
|
||||
int body = -9, signature = -9, alias = -9, order = -9;
|
||||
int empty = -9, literal = -9, unknown = -9, deletion = -9, transition = -9;
|
||||
const char *non_python = "{\"v\":4,\"lang\":0,\"lsp\":[],\"reg\":[],\"py\":null}";
|
||||
const char *non_python = "{\"v\":5,\"lang\":0,\"lsp\":[],\"reg\":[],\"py\":null}";
|
||||
if (complete) {
|
||||
body = cbm_lsp_surface_python_change(json[0], json[1]);
|
||||
signature = cbm_lsp_surface_python_change(json[0], json[2]);
|
||||
@@ -32679,24 +32770,24 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) {
|
||||
* it re-extracts in full. */
|
||||
const char *bad[] = {
|
||||
"{\"v\":1,\"lsp\":[]}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[]}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":4,\"lang\":1.0,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":4,\"v\":4,\"lang\":0,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[]}",
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":5,\"lang\":1.0,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":5,\"v\":5,\"lang\":0,\"lsp\":[],\"py\":null}",
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":3,\"failure\":2,\"events\":[]}}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\\u0000suffix\",\"status\":2,"
|
||||
"\"failure\":0,\"events\":[]}}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":["
|
||||
"{\"k\":999,\"d\":0,\"s\":0,\"r\":0,\"f\":0,\"l\":0,"
|
||||
"\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}",
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":["
|
||||
"{\"k\":8,\"d\":0,\"s\":1,\"r\":0,\"f\":0,\"l\":4294967296,"
|
||||
"\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}",
|
||||
@@ -32716,7 +32807,7 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) {
|
||||
cbm_arena_destroy(&arena);
|
||||
}
|
||||
const char *unknown =
|
||||
"{\"v\":4,\"lang\":1,\"lsp\":[],\"reg\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"{\"v\":5,\"lang\":1,\"lsp\":[],\"reg\":[],\"py\":{\"v\":2,\"lang\":1,"
|
||||
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":["
|
||||
"{\"k\":7,\"d\":0,\"s\":0,\"r\":7,\"f\":0,\"l\":0,"
|
||||
"\"n\":null,\"m\":null,\"i\":null,\"a\":[]}]}}";
|
||||
@@ -32744,7 +32835,7 @@ TEST(pipeline_lsp_surface_large_object_array_decode) {
|
||||
const size_t capacity = (size_t)count * 192 + 64;
|
||||
char *json = malloc(capacity);
|
||||
ASSERT_NOT_NULL(json);
|
||||
size_t used = (size_t)snprintf(json, capacity, "{\"v\":4,\"lang\":0,\"py\":null,\"lsp\":[");
|
||||
size_t used = (size_t)snprintf(json, capacity, "{\"v\":5,\"lang\":0,\"py\":null,\"lsp\":[");
|
||||
for (int i = 0; i < count; i++) {
|
||||
int n = snprintf(json + used, capacity - used,
|
||||
"%s{\"qn\":\"pkg.f%d\",\"sn\":\"f%d\",\"lb\":\"Function\","
|
||||
@@ -32837,7 +32928,7 @@ TEST(pipeline_lsp_surface_persisted_and_body_edit_invariant) {
|
||||
/* The row is the versioned codec envelope (codec version 4) with
|
||||
* the def present. */
|
||||
snprintf(json_probe, sizeof(json_probe), "%.20s", row_a->defs_json);
|
||||
ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":4") != NULL);
|
||||
ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":5") != NULL);
|
||||
ASSERT_TRUE(strstr(row_a->defs_json, "surface_probe") != NULL);
|
||||
} else if (round == 1) {
|
||||
ASSERT_STR_EQ(row_a->surface_sha, sha_baseline);
|
||||
@@ -35421,7 +35512,399 @@ TEST(pipeline_inc_c_family_fragments) {
|
||||
th_rmtree(tmp);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* ── C/C++ #include lookup against the indexed repository root (#2993) ── */
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <direct.h>
|
||||
#define inc_root_chdir _chdir
|
||||
#define inc_root_getcwd _getcwd
|
||||
#else
|
||||
#define inc_root_chdir chdir
|
||||
#define inc_root_getcwd getcwd
|
||||
#endif
|
||||
|
||||
/* Index `root` into `db` with the process working directory set to `cwd`, and
|
||||
* restore the working directory afterwards. */
|
||||
static int inc_root_index_from(const char *root, const char *db, const char *cwd) {
|
||||
char saved[CBM_SZ_4K];
|
||||
if (!inc_root_getcwd(saved, sizeof(saved)) || inc_root_chdir(cwd) != 0) {
|
||||
return -1;
|
||||
}
|
||||
int rc = -1;
|
||||
cbm_pipeline_t *p = cbm_pipeline_new(root, db, CBM_MODE_FULL);
|
||||
if (p) {
|
||||
(void)cbm_pipeline_set_project_name(p, "incroot");
|
||||
cbm_pipeline_set_persistence(p, false);
|
||||
rc = cbm_pipeline_run(p);
|
||||
cbm_pipeline_free(p);
|
||||
}
|
||||
if (inc_root_chdir(saved) != 0) {
|
||||
rc = -1;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* One FNV-1a digest over every node and edge row of the graph, in sorted
|
||||
* order: two graphs with the same digest and row count are the same graph. */
|
||||
static uint64_t inc_root_graph_digest(const char *db_path, int *rows) {
|
||||
static const char *const queries[] = {
|
||||
"SELECT label||'|'||qualified_name||'|'||file_path||'|'||start_line||'|'||end_line||'|'||"
|
||||
"properties FROM nodes ORDER BY 1",
|
||||
"SELECT e.type||'|'||s.qualified_name||'|'||t.qualified_name||'|'||e.properties FROM edges "
|
||||
"e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id ORDER BY 1",
|
||||
};
|
||||
uint64_t h = 1469598103934665603ULL;
|
||||
*rows = 0;
|
||||
sqlite3 *db = NULL;
|
||||
if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) == SQLITE_OK) {
|
||||
for (size_t q = 0; q < sizeof(queries) / sizeof(queries[0]); q++) {
|
||||
sqlite3_stmt *stmt = NULL;
|
||||
if (sqlite3_prepare_v2(db, queries[q], -1, &stmt, NULL) == SQLITE_OK) {
|
||||
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
||||
const unsigned char *row = sqlite3_column_text(stmt, 0);
|
||||
for (const unsigned char *c = row ? row : (const unsigned char *)""; *c; c++) {
|
||||
h = (h ^ *c) * 1099511628211ULL;
|
||||
}
|
||||
h = (h ^ 0xffU) * 1099511628211ULL;
|
||||
(*rows)++;
|
||||
}
|
||||
}
|
||||
sqlite3_finalize(stmt);
|
||||
}
|
||||
}
|
||||
sqlite3_close(db);
|
||||
return h;
|
||||
}
|
||||
|
||||
/* CALLS edges from the function named `from` to the Function named `to`. */
|
||||
static int inc_root_calls(const char *db, const char *from, const char *to) {
|
||||
char sql[512];
|
||||
snprintf(sql, sizeof(sql),
|
||||
"SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
|
||||
"t.id=e.target_id WHERE e.type='CALLS' AND s.name='%s' AND t.name='%s' AND "
|
||||
"t.label='Function'",
|
||||
from, to);
|
||||
return k8s_inc_count(db, sql);
|
||||
}
|
||||
|
||||
/* #2993: the graph depended on the directory the indexer was started from:
|
||||
* a quoted #include was looked up relative to the process working directory.
|
||||
* The lookup now resolves against the indexed repository root. The same
|
||||
* fixture, indexed from an empty directory, from a directory holding a
|
||||
* different lib/m.h, and from the repository root, gives one graph, in which
|
||||
* the macro of the repository's own lib/m.h expands to a call that resolves
|
||||
* to its in-tree target. */
|
||||
TEST(pipeline_c_include_lookup_uses_repo_root) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "%s/cbm_incroot_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
char root[512];
|
||||
char empty[512];
|
||||
char other[512];
|
||||
snprintf(root, sizeof(root), "%s/repo", tmp);
|
||||
snprintf(empty, sizeof(empty), "%s/empty", tmp);
|
||||
snprintf(other, sizeof(other), "%s/other", tmp);
|
||||
write_temp_file(root, "lib/a.c",
|
||||
"#define A_C_LOCAL 1\n"
|
||||
"#include \"m.h\"\n"
|
||||
"\n"
|
||||
"void caller(int v) {\n"
|
||||
" DO_WORK(v);\n"
|
||||
"}\n");
|
||||
write_temp_file(root, "lib/m.h",
|
||||
"#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n");
|
||||
write_temp_file(root, "lib/t.c",
|
||||
"void real_target(int x) { (void)x; }\n"
|
||||
"void other_target(int x) { (void)x; }\n");
|
||||
write_temp_file(other, "lib/m.h",
|
||||
"#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n");
|
||||
ASSERT(cbm_mkdir_p(empty, 0755));
|
||||
|
||||
const char *cwds[] = {empty, other, root};
|
||||
enum { RUNS = sizeof(cwds) / sizeof(cwds[0]) };
|
||||
int rc[RUNS];
|
||||
int rows[RUNS];
|
||||
int real[RUNS];
|
||||
int stray[RUNS];
|
||||
uint64_t digest[RUNS];
|
||||
for (int i = 0; i < RUNS; i++) {
|
||||
char db[512];
|
||||
snprintf(db, sizeof(db), "%s/graph%d.db", tmp, i);
|
||||
rc[i] = inc_root_index_from(root, db, cwds[i]);
|
||||
digest[i] = inc_root_graph_digest(db, &rows[i]);
|
||||
real[i] = inc_root_calls(db, "caller", "real_target");
|
||||
stray[i] = inc_root_calls(db, "caller", "other_target");
|
||||
}
|
||||
th_rmtree(tmp);
|
||||
for (int i = 0; i < RUNS; i++) {
|
||||
ASSERT_EQ(rc[i], 0);
|
||||
ASSERT_GT(rows[i], 0);
|
||||
ASSERT_EQ(real[i], 1);
|
||||
ASSERT_EQ(stray[i], 0);
|
||||
ASSERT_EQ(rows[i], rows[0]);
|
||||
ASSERT(digest[i] == digest[0]);
|
||||
}
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2993: simplecpp discards a file's whole expansion when it stops at #error.
|
||||
* An #error reached inside an included header must not cost the file its
|
||||
* expansion: the file keeps its expansion without includes, so the call its
|
||||
* own macro expands to survives. Indexed from the repository root, where the
|
||||
* header is found whichever way the lookup is made. */
|
||||
TEST(pipeline_c_include_error_keeps_expansion_without_includes) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "%s/cbm_incerr_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
char root[512];
|
||||
snprintf(root, sizeof(root), "%s/repo", tmp);
|
||||
write_temp_file(root, "cfg.h",
|
||||
"#ifndef CFG_H\n"
|
||||
"#define CFG_H\n"
|
||||
"#ifndef CFG_CONFIGURED\n"
|
||||
"#error \"configure first\"\n"
|
||||
"#endif\n"
|
||||
"#endif\n");
|
||||
write_temp_file(root, "z.c",
|
||||
"#include \"cfg.h\"\n"
|
||||
"#define RUN_STEP(x) step_target(x)\n"
|
||||
"\n"
|
||||
"int z_entry(int v) {\n"
|
||||
" RUN_STEP(v);\n"
|
||||
" return v;\n"
|
||||
"}\n");
|
||||
write_temp_file(root, "steps.c", "void step_target(int x) { (void)x; }\n");
|
||||
char db[512];
|
||||
snprintf(db, sizeof(db), "%s/graph.db", tmp);
|
||||
int rc = inc_root_index_from(root, db, root);
|
||||
int step_calls = inc_root_calls(db, "z_entry", "step_target");
|
||||
th_rmtree(tmp);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(step_calls, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2993: an included header's body is the header's own -- indexed as its own
|
||||
* file, with its own lines. The includer's expansion holds only the
|
||||
* includer's tokens (the header's macros still shape them), so a call or a
|
||||
* write inside a header's inline function is never one of the includer's
|
||||
* edges, and no edge of the includer carries a line past the includer's last
|
||||
* line. Indexed from the repository root, where the header is found whichever
|
||||
* way the lookup is made. */
|
||||
TEST(pipeline_c_header_body_stays_with_the_header) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "%s/cbm_inchdr_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
char root[512];
|
||||
snprintf(root, sizeof(root), "%s/repo", tmp);
|
||||
char header[2048];
|
||||
int used = snprintf(header, sizeof(header), "#ifndef OPS_H\n#define OPS_H\n");
|
||||
for (int i = 0; i < 24; i++) {
|
||||
used += snprintf(header + used, sizeof(header) - (size_t)used, "/* line %d */\n", i);
|
||||
}
|
||||
snprintf(header + used, sizeof(header) - (size_t)used,
|
||||
"extern int header_counter;\n"
|
||||
"static inline int ops_inline(int v) {\n"
|
||||
" header_counter = v;\n"
|
||||
" return header_only_callee(v);\n"
|
||||
"}\n"
|
||||
"#endif\n");
|
||||
write_temp_file(root, "ops.h", header);
|
||||
/* user.c is 6 lines long. */
|
||||
write_temp_file(root, "user.c",
|
||||
"#include \"ops.h\"\n"
|
||||
"#define USER_FLAG 1\n"
|
||||
"\n"
|
||||
"int user_fn(int v) {\n"
|
||||
" return main_only_callee(v);\n"
|
||||
"}\n");
|
||||
write_temp_file(root, "callees.c",
|
||||
"int header_counter;\n"
|
||||
"int header_only_callee(int v) { return v; }\n"
|
||||
"int main_only_callee(int v) { return v; }\n");
|
||||
char db[512];
|
||||
snprintf(db, sizeof(db), "%s/graph.db", tmp);
|
||||
int rc = inc_root_index_from(root, db, root);
|
||||
int from_user = k8s_inc_count(
|
||||
db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
|
||||
"t.id=e.target_id WHERE e.type IN ('CALLS','USAGE','WRITES') AND "
|
||||
"s.file_path='user.c' AND t.name IN ('header_only_callee','header_counter')");
|
||||
int past_end = k8s_inc_count(
|
||||
db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id WHERE e.type IN "
|
||||
"('CALLS','USAGE') AND s.file_path='user.c' AND "
|
||||
"CAST(json_extract(e.properties,'$.line') AS INTEGER) > 6");
|
||||
int own_call = k8s_inc_count(
|
||||
db, "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
|
||||
"t.id=e.target_id WHERE e.type='CALLS' AND s.file_path='ops.h' AND "
|
||||
"t.name='header_only_callee'");
|
||||
int user_call = inc_root_calls(db, "user_fn", "main_only_callee");
|
||||
th_rmtree(tmp);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(from_user, 0);
|
||||
ASSERT_EQ(past_end, 0);
|
||||
ASSERT_GT(own_call, 0);
|
||||
ASSERT_EQ(user_call, 1);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2993: only a name that denotes a file of the indexed tree resolves. Each
|
||||
* of the three includes of lib/a.c names a header that is not part of the
|
||||
* indexed tree (the third is reached through a symbolic link, which discovery
|
||||
* does not index either), so none of the three macros expands, wherever the
|
||||
* indexer runs; here it runs from the repository root. */
|
||||
TEST(pipeline_c_include_lookup_stays_in_repo_root) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "%s/cbm_incside_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
char root[512];
|
||||
snprintf(root, sizeof(root), "%s/repo", tmp);
|
||||
write_temp_file(tmp, "m_side.h", "#define SIDE_M(x) m_target(x)\n");
|
||||
write_temp_file(tmp, "n_side.h", "#define SIDE_N(x) n_target(x)\n");
|
||||
write_temp_file(tmp, "l_side.h", "#define SIDE_L(x) l_target(x)\n");
|
||||
char source[2048];
|
||||
snprintf(source, sizeof(source),
|
||||
"#define A_LOCAL 1\n"
|
||||
"#include \"../../m_side.h\"\n"
|
||||
"#include \"%s/n_side.h\"\n"
|
||||
"#include \"l_side.h\"\n"
|
||||
"\n"
|
||||
"void caller(int v) {\n"
|
||||
" SIDE_M(v);\n"
|
||||
" SIDE_N(v);\n"
|
||||
" SIDE_L(v);\n"
|
||||
"}\n",
|
||||
tmp);
|
||||
write_temp_file(root, "lib/a.c", source);
|
||||
write_temp_file(root, "lib/t.c",
|
||||
"void m_target(int x) { (void)x; }\n"
|
||||
"void n_target(int x) { (void)x; }\n"
|
||||
"void l_target(int x) { (void)x; }\n");
|
||||
#ifndef _WIN32
|
||||
char link_target[512];
|
||||
char link_path[512];
|
||||
snprintf(link_target, sizeof(link_target), "%s/l_side.h", tmp);
|
||||
snprintf(link_path, sizeof(link_path), "%s/lib/l_side.h", root);
|
||||
ASSERT_EQ(symlink(link_target, link_path), 0);
|
||||
#endif
|
||||
char db[512];
|
||||
snprintf(db, sizeof(db), "%s/graph.db", tmp);
|
||||
int rc = inc_root_index_from(root, db, root);
|
||||
static const char *const targets[] = {"m_target", "n_target", "l_target"};
|
||||
int wrong = 0;
|
||||
for (size_t i = 0; i < sizeof(targets) / sizeof(targets[0]); i++) {
|
||||
int n = inc_root_calls(db, "caller", targets[i]);
|
||||
if (n != 0) {
|
||||
printf(" caller -> %s: %d\n", targets[i], n);
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
th_rmtree(tmp);
|
||||
ASSERT_EQ(rc, 0);
|
||||
ASSERT_EQ(wrong, 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
/* #2993: a C file's graph depends on the in-tree headers its includes read,
|
||||
* so an edit to a header alone changes its includers' graphs. lib/a.c
|
||||
* includes lib/m.h directly, lib/b.c through lib/mid.h; only lib/m.h's macro
|
||||
* changes. The incremental refresh (closure repair) must re-extract both
|
||||
* includers and give the graph a fresh full index gives. 60 filler files take
|
||||
* the fixture past MIN_FILES_FOR_PARALLEL, so the fresh full index resolves
|
||||
* calls on the same parallel path as the repair: the sequential path writes
|
||||
* the same CALLS properties in another key order. */
|
||||
TEST(pipeline_c_header_edit_refreshes_includers_incrementally) {
|
||||
char tmp[256];
|
||||
snprintf(tmp, sizeof(tmp), "%s/cbm_incedit_XXXXXX", cbm_tmpdir());
|
||||
ASSERT_NOT_NULL(cbm_mkdtemp(tmp));
|
||||
char root[512];
|
||||
snprintf(root, sizeof(root), "%s/repo", tmp);
|
||||
write_temp_file(root, "lib/m.h",
|
||||
"#ifndef M_H\n#define M_H\n#define DO_WORK(x) real_target(x)\n#endif\n");
|
||||
write_temp_file(root, "lib/mid.h", "#ifndef MID_H\n#define MID_H\n#include \"m.h\"\n#endif\n");
|
||||
write_temp_file(root, "lib/a.c",
|
||||
"#define A_LOCAL 1\n"
|
||||
"#include \"m.h\"\n"
|
||||
"\n"
|
||||
"void caller_a(int v) {\n"
|
||||
" DO_WORK(v);\n"
|
||||
"}\n");
|
||||
write_temp_file(root, "lib/b.c",
|
||||
"#define B_LOCAL 1\n"
|
||||
"#include \"mid.h\"\n"
|
||||
"\n"
|
||||
"void caller_b(int v) {\n"
|
||||
" DO_WORK(v);\n"
|
||||
"}\n");
|
||||
write_temp_file(root, "lib/t.c",
|
||||
"void real_target(int x) { (void)x; }\n"
|
||||
"void other_target(int x) { (void)x; }\n");
|
||||
write_temp_file(root, "lib/u.c", "int unrelated(void) { return 1; }\n");
|
||||
for (int i = 0; i < 60; i++) {
|
||||
char name[64];
|
||||
char body[96];
|
||||
snprintf(name, sizeof(name), "fill/fill_%02d.c", i);
|
||||
snprintf(body, sizeof(body), "int fill_%02d(void) { return %d; }\n", i, i);
|
||||
write_temp_file(root, name, body);
|
||||
}
|
||||
char db[512];
|
||||
char fresh_db[512];
|
||||
snprintf(db, sizeof(db), "%s/graph.db", tmp);
|
||||
snprintf(fresh_db, sizeof(fresh_db), "%s/fresh.db", tmp);
|
||||
int rc_full = inc_root_index_from(root, db, root);
|
||||
int before_a = inc_root_calls(db, "caller_a", "real_target");
|
||||
|
||||
write_temp_file(root, "lib/m.h",
|
||||
"#ifndef M_H\n#define M_H\n#define DO_WORK(x) other_target(x)\n#endif\n");
|
||||
cbm_pipeline_incremental_test_reset_faults();
|
||||
int rc_incr = inc_root_index_from(root, db, root);
|
||||
cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
|
||||
int rc_fresh = inc_root_index_from(root, fresh_db, root);
|
||||
|
||||
int incr_rows = 0;
|
||||
int fresh_rows = 0;
|
||||
uint64_t incr_digest = inc_root_graph_digest(db, &incr_rows);
|
||||
uint64_t fresh_digest = inc_root_graph_digest(fresh_db, &fresh_rows);
|
||||
unsigned char incr_content[32] = {0};
|
||||
unsigned char fresh_content[32] = {1};
|
||||
cbm_store_t *incr_store = cbm_store_open_path(db);
|
||||
cbm_store_t *fresh_store = cbm_store_open_path(fresh_db);
|
||||
bool contents_read =
|
||||
incr_store && fresh_store &&
|
||||
cbm_store_graph_content_digest(incr_store, "incroot", incr_content) == CBM_STORE_OK &&
|
||||
cbm_store_graph_content_digest(fresh_store, "incroot", fresh_content) == CBM_STORE_OK;
|
||||
cbm_store_close(incr_store);
|
||||
cbm_store_close(fresh_store);
|
||||
static const char *const callers[] = {"caller_a", "caller_b"};
|
||||
int wrong = 0;
|
||||
for (size_t i = 0; i < sizeof(callers) / sizeof(callers[0]); i++) {
|
||||
int now = inc_root_calls(db, callers[i], "other_target");
|
||||
int stale = inc_root_calls(db, callers[i], "real_target");
|
||||
if (now != 1 || stale != 0) {
|
||||
printf(" %s: other_target %d, real_target %d\n", callers[i], now, stale);
|
||||
wrong++;
|
||||
}
|
||||
}
|
||||
th_rmtree(tmp);
|
||||
ASSERT_EQ(rc_full, 0);
|
||||
ASSERT_EQ(before_a, 1);
|
||||
ASSERT_EQ(rc_incr, 0);
|
||||
ASSERT_EQ(route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
|
||||
ASSERT_EQ(rc_fresh, 0);
|
||||
ASSERT_EQ(wrong, 0);
|
||||
ASSERT_EQ(incr_rows, fresh_rows);
|
||||
ASSERT(incr_digest == fresh_digest);
|
||||
ASSERT(contents_read);
|
||||
ASSERT(memcmp(incr_content, fresh_content, sizeof(incr_content)) == 0);
|
||||
PASS();
|
||||
}
|
||||
|
||||
SUITE(pipeline) {
|
||||
RUN_TEST(pipeline_c_header_edit_refreshes_includers_incrementally);
|
||||
RUN_TEST(pipeline_c_include_lookup_uses_repo_root);
|
||||
RUN_TEST(pipeline_c_include_error_keeps_expansion_without_includes);
|
||||
RUN_TEST(pipeline_c_header_body_stays_with_the_header);
|
||||
RUN_TEST(pipeline_c_include_lookup_stays_in_repo_root);
|
||||
RUN_TEST(pipeline_inc_c_family_fragments);
|
||||
RUN_TEST(pipeline_python_module_callers_sequential);
|
||||
RUN_TEST(pipeline_python_module_callers_parallel);
|
||||
@@ -35535,6 +36018,7 @@ SUITE(pipeline) {
|
||||
RUN_TEST(pipeline_incremental_preserves_cross_file_calls);
|
||||
RUN_TEST(pipeline_incremental_drops_terraform_reads_of_a_moved_module);
|
||||
RUN_TEST(pipeline_incremental_keeps_ansible_includes_of_an_edited_file);
|
||||
RUN_TEST(pipeline_semantic_import_map_keys_come_from_the_memory_core);
|
||||
RUN_TEST(pipeline_incremental_keeps_ansible_notifies_across_files);
|
||||
RUN_TEST(pipeline_incremental_keeps_ansible_deploys_across_files);
|
||||
RUN_TEST(pipeline_field_named_like_method_keeps_its_reads_and_writes);
|
||||
|
||||
@@ -537,12 +537,12 @@ static pc_spill_witness_t pc_collect_spill_witness(pc_fixture_t *f) {
|
||||
decl = cbm_test_declarations_parse(pc_config0, strlen(pc_config0), false);
|
||||
if (!decl) goto done;
|
||||
cache[0] = cbm_extract_file_ex_with_tests(plain, (int)strlen(plain), CBM_LANG_C,
|
||||
PC_PROJECT, "contributor.c", 0, NULL, NULL, NULL, NULL, decl);
|
||||
PC_PROJECT, "contributor.c", 0, NULL, NULL, NULL, NULL, decl, NULL);
|
||||
if (!cache[0] || cache[0]->test_declarations_status != CBM_TEST_EXTRACT_OK || cache[0]->defs.count < 1)
|
||||
goto done;
|
||||
cbm_result_compact(cache[0]);
|
||||
cache[1] = cbm_extract_file_ex_with_tests(owner, (int)strlen(owner), CBM_LANG_C,
|
||||
PC_PROJECT, "parked.c", 0, NULL, NULL, NULL, NULL, decl);
|
||||
PC_PROJECT, "parked.c", 0, NULL, NULL, NULL, NULL, decl, NULL);
|
||||
if (!pc_result_case(cache[1], "CHECK_parked", PC_PROJECT ".parked.CHECK_parked")) goto done;
|
||||
cbm_result_compact(cache[1]);
|
||||
ctx.test_declarations = decl;
|
||||
|
||||
@@ -33,7 +33,7 @@ static cbm_test_declarations_t *tc_config(const char *records, const char *prese
|
||||
static CBMFileResult *tc_extract(const char *source, CBMLanguage language, const char *path,
|
||||
const cbm_test_declarations_t *config) {
|
||||
return cbm_extract_file_ex_with_tests(source, (int)strlen(source), language,
|
||||
"convproj", path, 0, NULL, NULL, NULL, NULL, config);
|
||||
"convproj", path, 0, NULL, NULL, NULL, NULL, config, NULL);
|
||||
}
|
||||
|
||||
static CBMFileResult *tc_legacy(const char *source, CBMLanguage language, const char *path) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user