diff --git a/Makefile.cbm b/Makefile.cbm index 66cccffe2..8e19fcac0 100644 --- a/Makefile.cbm +++ b/Makefile.cbm @@ -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 \ @@ -870,7 +871,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 diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h index 310206153..ffaaf6652 100644 --- a/internal/cbm/cbm.h +++ b/internal/cbm/cbm.h @@ -328,8 +328,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 @@ -1387,6 +1423,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). diff --git a/internal/cbm/extract_defs.c b/internal/cbm/extract_defs.c index 585f93db4..843fcfbae 100644 --- a/internal/cbm/extract_defs.c +++ b/internal/cbm/extract_defs.c @@ -16,6 +16,7 @@ #include "semantic/ast_profile.h" #include "tree_sitter/api.h" // TSNode, ts_node_* #include // INT_MAX +#include // test-seam work counters #include // uint32_t, SIZE_MAX #include // snprintf (ObjectScript storage/trigger sidecars) #include // malloc/free (child-collection scratch) @@ -6939,6 +6940,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 ` runs. The rule's definition carries the first target; * every further one gets a definition of its own over the same rule span -- @@ -7250,6 +7788,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 @@ -8542,6 +9086,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); @@ -8973,6 +9598,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); @@ -9497,6 +10139,12 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node, 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 @@ -11014,6 +11662,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; @@ -11042,13 +11737,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; + } } } } diff --git a/internal/cbm/lsp/go_lsp.c b/internal/cbm/lsp/go_lsp.c index 6e4aa81a1..dede34b93 100644 --- a/internal/cbm/lsp/go_lsp.c +++ b/internal/cbm/lsp/go_lsp.c @@ -33,6 +33,8 @@ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, const char *field_name, int depth); static void extract_type_params_from_ast(CBMArena *arena, CBMTypeRegistry *reg, TSNode root, const char *source, const char *module_qn); +static const char *go_embedded_spelling(const char **next, size_t *len); +static const char *go_embedded_field_name(CBMArena *a, const char *s, size_t len); // --- Initialization --- @@ -125,6 +127,90 @@ static const CBMType *resolve_builtin_type(GoLSPContext *ctx, const char *name) // --- go_parse_type_node: AST type node -> CBMType --- +/* ── Type names a function declares itself ──────────────────────────── + * + * A function's type parameters (and its receiver's) and the types it declares + * in its body are not the package's types of those names: `func F[T any](x T)` + * and `func F() { type T struct{...}; var t T }` in a package with its own T. + * The walker types such a name as unknown (it abstains) instead of the + * package-level type. Each one is bound in the walker's own lexical scope + * under a key no identifier can spell ("#T"), so it holds exactly where Go's + * does: a type parameter for the function, a local type from its declaration + * to the end of its block or closure. */ +#define GO_SHADOW_KEY_MAX 256 + +static bool go_shadow_key(const char *name, char *key) { + size_t n = name ? strlen(name) : 0; + if (n == 0 || n + 2 > GO_SHADOW_KEY_MAX) { + return false; + } + key[0] = '#'; + memcpy(key + 1, name, n + 1); + return true; +} + +static bool go_type_shadowed(const GoLSPContext *ctx, const char *name) { + char key[GO_SHADOW_KEY_MAX]; + return go_shadow_key(name, key) && cbm_scope_contains(ctx->current_scope, key); +} + +static void go_shadow_add(GoLSPContext *ctx, TSNode name_node) { + char *name = ts_node_is_null(name_node) ? NULL : lsp_node_text(ctx, name_node); + char key[GO_SHADOW_KEY_MAX]; + if (!name || strcmp(name, "_") == 0 || !go_shadow_key(name, key)) { + return; + } + cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, key), cbm_type_unknown()); +} + +/* `[K comparable, V any]`: every name of every type_parameter_declaration. */ +static void go_shadow_type_params(GoLSPContext *ctx, TSNode list) { + 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) { + go_shadow_add(ctx, ts_node_child(decl, k)); + } + } + } +} + +/* A generic receiver `(s *Set[K, V])` declares K and V: the type identifiers + * inside the receiver type's type arguments. */ +static void go_shadow_receiver_params(GoLSPContext *ctx, TSNode node, bool in_args, int depth) { + if (ts_node_is_null(node) || depth > CBM_LSP_MAX_LOOKUP_DEPTH) { + return; + } + const char *kind = ts_node_type(node); + if (in_args && strcmp(kind, "type_identifier") == 0) { + go_shadow_add(ctx, node); + 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_shadow_receiver_params(ctx, ts_node_named_child(node, i), args, depth + 1); + } +} + +/* `type T struct{...}` / `type T = U` inside the function being walked. */ +static void go_shadow_declared_types(GoLSPContext *ctx, TSNode decl) { + uint32_t n = ts_node_named_child_count(decl); + for (uint32_t i = 0; i < n; i++) { + TSNode spec = ts_node_named_child(decl, i); + const char *sk = ts_node_type(spec); + if (strcmp(sk, "type_spec") == 0 || strcmp(sk, "type_alias") == 0) { + go_shadow_add(ctx, ts_node_child_by_field_name(spec, "name", 4)); + } + } +} + const CBMType *go_parse_type_node(GoLSPContext *ctx, TSNode node) { if (ts_node_is_null(node)) return cbm_type_unknown(); @@ -136,6 +222,8 @@ const CBMType *go_parse_type_node(GoLSPContext *ctx, TSNode node) { char *name = lsp_node_text(ctx, node); if (!name) return cbm_type_unknown(); + if (go_type_shadowed(ctx, name)) + return cbm_type_unknown(); /* the function's own T, not the package's */ const CBMType *builtin = resolve_builtin_type(ctx, name); if (builtin) return builtin; @@ -346,6 +434,74 @@ static void go_unify_type(const CBMType *param_type, const CBMType *arg_type, // --- go_eval_expr_type: recursive expression type evaluator --- +/* Walk a closure's body in a child scope (inheriting every outer binding) + * with its declared parameters bound: `func(reg *httpmock.Registry) { + * reg.Register(...) }` types `reg` wherever the literal stands (an + * argument, an assignment, a composite literal's field value). */ +static void go_walk_func_literal(GoLSPContext *ctx, TSNode node) { + TSNode body = ts_node_child_by_field_name(node, "body", 4); + if (ts_node_is_null(body)) { + return; + } + CBMScope *saved = ctx->current_scope; + ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); + TSNode params = ts_node_child_by_field_name(node, "parameters", 10); + if (!ts_node_is_null(params)) { + uint32_t nc = ts_node_child_count(params); + for (uint32_t i = 0; i < nc; i++) { + TSNode param = ts_node_child(params, i); + if (ts_node_is_null(param) || !ts_node_is_named(param) || + strcmp(ts_node_type(param), "parameter_declaration") != 0) { + continue; + } + TSNode type_node = ts_node_child_by_field_name(param, "type", 4); + const CBMType *pt = go_parse_type_node(ctx, type_node); + uint32_t pnc = ts_node_child_count(param); + for (uint32_t j = 0; j < pnc; j++) { + TSNode ch = ts_node_child(param, j); + if (!ts_node_is_null(ch) && ts_node_is_named(ch) && + strcmp(ts_node_type(ch), "identifier") == 0) { + char *pname = lsp_node_text(ctx, ch); + if (pname && strcmp(pname, "_") != 0) { + cbm_scope_bind(ctx->current_scope, pname, pt); + } + } + } + } + } + resolve_calls_in_node(ctx, body); + ctx->current_scope = saved; +} + +/* The type a package-level symbol has as an expression: a value's declared + * type (CBM_FUNC_FLAG_VALUE: the signature's single result), a function's + * own signature. NULL when unknown. */ +static const CBMType *go_symbol_type(const CBMRegisteredFunc *f) { + if (!f || !f->signature) { + return NULL; + } + if ((f->flags & CBM_FUNC_FLAG_VALUE) == 0) { + return f->signature; + } + const CBMType **rets = + f->signature->kind == CBM_TYPE_FUNC ? f->signature->data.func.return_types : NULL; + return rets && rets[0] ? rets[0] : NULL; +} + +/* A package-level symbol a call can target: a function, never a value. */ +static const CBMRegisteredFunc *go_lookup_callable(const CBMTypeRegistry *reg, + const char *package_qn, const char *name) { + const CBMRegisteredFunc *f = cbm_registry_lookup_symbol(reg, package_qn, name); + return f && (f->flags & CBM_FUNC_FLAG_VALUE) ? NULL : f; +} + +/* The same rule for a lookup by full QN (the fast resolve path). */ +static const CBMRegisteredFunc *go_lookup_func_callable(const CBMTypeRegistry *reg, + const char *qn) { + const CBMRegisteredFunc *f = cbm_registry_lookup_func(reg, qn); + return f && (f->flags & CBM_FUNC_FLAG_VALUE) ? NULL : f; +} + const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (ts_node_is_null(node)) return cbm_type_unknown(); @@ -362,12 +518,15 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { const CBMType *t = cbm_scope_lookup(ctx->current_scope, name); if (cbm_scope_contains(ctx->current_scope, name)) return t ? t : cbm_type_unknown(); + // A type the function declares itself (a conversion `T(x)`) + if (go_type_shadowed(ctx, name)) + return cbm_type_unknown(); - // Check if it's a package-level function - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); - if (f && f->signature) - return f->signature; + // A package-level function or value (of any file of the package) + const CBMType *st = + go_symbol_type(cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name)); + if (st) + return st; // Check if it's a builtin type (for type conversions like string(x), int(x)) const CBMType *bt = resolve_builtin_type(ctx, name); @@ -400,11 +559,11 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { if (pkg_name) { const char *pkg_qn = resolve_import(ctx, pkg_name); if (pkg_qn) { - // Look up pkg.Symbol as a function or type - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name); - if (f && f->signature) - return f->signature; + // Look up pkg.Symbol as a function, a value or a type + const CBMType *st = go_symbol_type( + cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name)); + if (st) + return st; // Check if it's a type char *type_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", pkg_qn, field_name); const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); @@ -805,42 +964,7 @@ const CBMType *go_eval_expr_type(GoLSPContext *ctx, TSNode node) { // --- Func literal (closure) --- if (strcmp(kind, "func_literal") == 0) { // Process the closure body to resolve calls with captured scope - TSNode body = ts_node_child_by_field_name(node, "body", 4); - if (!ts_node_is_null(body)) { - // Push child scope (inherits all outer bindings via parent chain) - CBMScope *saved = ctx->current_scope; - ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); - - // Bind closure parameters - TSNode params = ts_node_child_by_field_name(node, "parameters", 10); - if (!ts_node_is_null(params)) { - uint32_t nc = ts_node_child_count(params); - for (uint32_t i = 0; i < nc; i++) { - TSNode param = ts_node_child(params, i); - if (ts_node_is_null(param) || !ts_node_is_named(param)) - continue; - if (strcmp(ts_node_type(param), "parameter_declaration") != 0) - continue; - TSNode type_node = ts_node_child_by_field_name(param, "type", 4); - const CBMType *pt = go_parse_type_node(ctx, type_node); - uint32_t pnc = ts_node_child_count(param); - for (uint32_t j = 0; j < pnc; j++) { - TSNode ch = ts_node_child(param, j); - if (!ts_node_is_null(ch) && ts_node_is_named(ch) && - strcmp(ts_node_type(ch), "identifier") == 0) { - char *pname = lsp_node_text(ctx, ch); - if (pname && strcmp(pname, "_") != 0) - cbm_scope_bind(ctx->current_scope, pname, pt); - } - } - } - } - - // Walk closure body to resolve calls - resolve_calls_in_node(ctx, body); - - ctx->current_scope = saved; - } + go_walk_func_literal(ctx, node); // Build full FUNC type with param/return types from AST const CBMType *pt_arr[16]; @@ -935,13 +1059,13 @@ const CBMType *go_eval_builtin_call(GoLSPContext *ctx, const char *name, TSNode // --- Import-alias re-qualification ------------------------------------ // -// parse_field_defs_into_type qualifies struct field type texts as -// ".". When the author wrote the text through an import -// alias ("Svc:svc.Svc" in module test.main), that yields a QN -// ("test.main.svc.Svc") that exists nowhere in the project-wide registry — -// the real QN is ".Svc" and only the calling file's import map -// can say so. On an exact-QN miss this rewrites the alias segment through -// the file's imports; returns NULL when no alias segment is involved. +// parse_field_defs qualifies a struct field type text the defining file's +// scope did not resolve (no identity in the def's type_scope) as +// ".". Written through an import alias ("Svc:svc.Svc" in +// module test.main), that yields a QN ("test.main.svc.Svc") that exists +// nowhere in the project-wide registry. On an exact-QN miss this rewrites the +// alias segment through the calling file's imports; returns NULL when no alias +// segment is involved. static const char *go_requalify_via_imports(GoLSPContext *ctx, const char *type_qn) { if (!ctx || !type_qn || !type_qn[0] || ctx->import_count <= 0) @@ -972,28 +1096,33 @@ static const char *go_requalify_via_imports(GoLSPContext *ctx, const char *type_ return NULL; } +/* Go's selector rule: `x.f` names the field or method f at the shallowest + * depth of x's embedding tree that has one, and more than one at that depth + * (two embedded types with a method of that name, a field and a method) is + * no selection at all. An alias is its target, at the same depth. The walk is + * breadth-first and visits each type once; max_depth is the depth the + * depth-first walks it replaces went to. The one member, or none. */ +typedef struct { + const CBMRegisteredFunc *method; + const CBMType *field; + const char *field_owner; /* the type declaring the field */ + int found; /* distinct members at the shallowest depth with any */ +} go_member_t; + +enum { GO_FIELD_LOOKUP_DEPTH = 5 }; /* the depth go_lookup_field always went to */ + +static go_member_t go_select_member(GoLSPContext *ctx, const char *type_qn, const char *name, + int max_depth); + +/* A field's type: the type's own field, else the one member the selector + * rule picks (go_select_member) when that is a field. */ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, const char *field_name, int depth) { - if (!type_qn || !field_name || depth > 5) + (void)depth; + if (!type_qn || !field_name) return NULL; - const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); - if (!rt && depth == 0) { - /* Import-alias re-qualification: field texts from cross-package defs - * may embed an alias segment only this file's import map resolves. */ - const char *alt_qn = go_requalify_via_imports(ctx, type_qn); - if (alt_qn) - rt = cbm_registry_lookup_type(ctx->registry, alt_qn); - } - if (!rt) - return NULL; - - // Follow alias chain - if (rt->alias_of) - return go_lookup_field(ctx, rt->alias_of, field_name, depth + 1); - - // Direct field lookup - if (rt->field_names) { + if (rt && !rt->alias_of && rt->field_names) { for (int i = 0; rt->field_names[i]; i++) { if (strcmp(rt->field_names[i], field_name) == 0 && rt->field_types && rt->field_types[i]) { @@ -1001,74 +1130,138 @@ static const CBMType *go_lookup_field(GoLSPContext *ctx, const char *type_qn, } } } - - // Promoted fields from embedded types - if (rt->embedded_types) { - for (int i = 0; rt->embedded_types[i]; i++) { - const CBMType *f = go_lookup_field(ctx, rt->embedded_types[i], field_name, depth + 1); - if (f) - return f; - } - } - - return NULL; + go_member_t m = go_select_member(ctx, type_qn, field_name, GO_FIELD_LOOKUP_DEPTH); + return m.field && !cbm_type_is_unknown(m.field) ? m.field : NULL; } // --- go_lookup_field_or_method: method sets + embedding --- -static const CBMRegisteredFunc *go_lookup_field_or_method_depth(GoLSPContext *ctx, - const char *type_qn, - const char *member_name, - int depth) { - if (!type_qn || !member_name) - return NULL; - if (depth > CBM_LSP_MAX_LOOKUP_DEPTH) - return NULL; +static void go_member_note(go_member_t *m, const CBMRegisteredFunc *method, const CBMType *field, + const char *owner) { + if (!method && !field) { + return; /* nothing of that name here */ + } + if (method) { + if (m->method == method || + (m->method && m->method->qualified_name && method->qualified_name && + strcmp(m->method->qualified_name, method->qualified_name) == 0)) { + return; + } + if (!m->method) { + m->method = method; + } + m->found++; + return; + } + if (m->field_owner && owner && strcmp(m->field_owner, owner) == 0) { + return; + } + if (!m->field) { + m->field = field; + m->field_owner = owner; + } + m->found++; +} - // Direct method lookup - const CBMRegisteredFunc *f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name); - if (f) - return f; - - /* Import-alias re-qualification fallback: NAMED receivers built from - * cross-package field type texts can carry a ".svc.Svc" QN; - * retry the method set on the import-resolved QN (see - * go_requalify_via_imports). */ - if (depth == 0) { - const char *alt_qn = go_requalify_via_imports(ctx, type_qn); - if (alt_qn) { - f = go_lookup_field_or_method_depth(ctx, alt_qn, member_name, depth + 1); - if (f) - return f; +static const CBMType *go_own_field(const CBMRegisteredType *rt, const char *name) { + for (int i = 0; rt->field_names && rt->field_names[i]; i++) { + if (strcmp(rt->field_names[i], name) == 0) { + return rt->field_types && rt->field_types[i] ? rt->field_types[i] : cbm_type_unknown(); } } + return NULL; +} - const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); - if (rt) { - // Follow type alias chain - if (rt->alias_of) { - f = go_lookup_field_or_method_depth(ctx, rt->alias_of, member_name, depth + 1); - if (f) - return f; +/* Append `qn` to a level unless the walk has seen it. */ +static void go_member_push(CBMArena *a, CBMHashTable *seen, const char ***level, int *count, + int *cap, const char *qn) { + if (!qn || !seen || cbm_ht_get(seen, qn)) { + return; + } + cbm_ht_set(seen, qn, (void *)qn); + if (*count == *cap) { + int grown_cap = *cap ? *cap * 2 : 8; + const char **grown = (const char **)cbm_arena_alloc(a, (size_t)grown_cap * sizeof(char *)); + if (!grown) { + return; } + if (*count) { + memcpy(grown, *level, (size_t)*count * sizeof(char *)); + } + *level = grown; + *cap = grown_cap; + } + (*level)[(*count)++] = qn; +} - // Check embedded types (promoted methods) - if (rt->embedded_types) { - for (int i = 0; rt->embedded_types[i]; i++) { - f = go_lookup_field_or_method_depth(ctx, rt->embedded_types[i], member_name, - depth + 1); - if (f) - return f; +static go_member_t go_select_member(GoLSPContext *ctx, const char *type_qn, const char *name, + int max_depth) { + go_member_t m = {0}; + CBMHashTable *seen = cbm_ht_create(16); + if (!type_qn || !name || !seen) { + cbm_ht_free(seen); + return m; + } + const char **level = NULL; + int count = 0; + int cap = 0; + go_member_push(ctx->arena, seen, &level, &count, &cap, type_qn); + /* Import-alias re-qualification: NAMED receivers built from cross-package + * field type texts can carry a ".svc.Svc" QN only this file's + * import map resolves (go_requalify_via_imports); it names the same type. */ + go_member_push(ctx->arena, seen, &level, &count, &cap, go_requalify_via_imports(ctx, type_qn)); + for (int depth = 0; count > 0 && depth <= max_depth && m.found == 0; depth++) { + const char **next = NULL; + int next_count = 0; + int next_cap = 0; + for (int i = 0; i < count; i++) { + const char *t = level[i]; + while (t) { + go_member_note(&m, cbm_registry_lookup_method(ctx->registry, t, name), NULL, NULL); + const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, t); + if (!rt) { + break; + } + const CBMType *field = go_own_field(rt, name); + if (field) { + go_member_note(&m, NULL, field, t); + } + for (int e = 0; rt->embedded_types && rt->embedded_types[e]; e++) { + go_member_push(ctx->arena, seen, &next, &next_count, &next_cap, + rt->embedded_types[e]); + } + /* the alias target is this type, at this depth */ + const char *target = rt->alias_of; + t = target && !cbm_ht_get(seen, target) ? target : NULL; + if (t) { + cbm_ht_set(seen, t, (void *)t); + } } } + level = next; + count = next_count; } - - return NULL; + cbm_ht_free(seen); + if (m.found != 1) { + m.method = NULL; + m.field = NULL; + } + return m; } const CBMRegisteredFunc *go_lookup_field_or_method(GoLSPContext *ctx, const char *type_qn, const char *member_name) { - return go_lookup_field_or_method_depth(ctx, type_qn, member_name, 0); + if (!type_qn || !member_name) + return NULL; + // Direct method lookup (a type has no field of a method's name) + const CBMRegisteredFunc *f = cbm_registry_lookup_method(ctx->registry, type_qn, member_name); + if (f) + return f; + // Its own field of that name: a field, never a promoted method + const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, type_qn); + if (rt && !rt->alias_of && go_own_field(rt, member_name)) + return NULL; + return go_select_member(ctx, type_qn, member_name, CBM_LSP_MAX_LOOKUP_DEPTH).method; } /* Resolve only source forms that prove one callable identity. This is @@ -1093,8 +1286,7 @@ static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node) { if (cbm_scope_contains(ctx->current_scope, name)) { return cbm_scope_lookup_callable(ctx->current_scope, name); } - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); + const CBMRegisteredFunc *f = go_lookup_callable(ctx->registry, ctx->package_qn, name); return f ? f->qualified_name : NULL; } @@ -1111,8 +1303,7 @@ static const char *go_exact_callable_target(GoLSPContext *ctx, TSNode node) { char *local = lsp_node_text(ctx, operand); const char *package_qn = local ? resolve_import(ctx, local) : NULL; if (package_qn) { - const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, package_qn, member); + const CBMRegisteredFunc *f = go_lookup_callable(ctx->registry, package_qn, member); return f ? f->qualified_name : NULL; } } @@ -1529,6 +1720,17 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { return; const char *kind = ts_node_type(node); + /* A closure the walk reaches is walked with its parameters bound, not + * as plain children in the enclosing scope. */ + if (strcmp(kind, "func_literal") == 0) { + go_walk_func_literal(ctx, node); + return; + } + /* A type declared in the function shadows the package's from here on. */ + if (ctx->in_function && strcmp(kind, "type_declaration") == 0) { + go_shadow_declared_types(ctx, node); + } + // Process statements to build scope go_process_statement(ctx, node); @@ -1559,7 +1761,7 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { const char *pkg_qn = resolve_import(ctx, pkg_name); if (pkg_qn && field_name) { const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, pkg_qn, field_name); + go_lookup_callable(ctx->registry, pkg_qn, field_name); if (f) { emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, node); @@ -1755,7 +1957,7 @@ static void resolve_calls_in_node_inner(GoLSPContext *ctx, TSNode node) { } // Package-local function const CBMRegisteredFunc *f = - cbm_registry_lookup_symbol(ctx->registry, ctx->package_qn, name); + go_lookup_callable(ctx->registry, ctx->package_qn, name); if (f) { emit_resolved_call(ctx, f->qualified_name, "lsp_direct", 0.95f, node); } else { @@ -2018,6 +2220,17 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { CBMScope *saved_scope = ctx->current_scope; ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope); + // The function's type parameters (and its receiver's) shadow the + // package's types of those names, in its signature and its body (bound in + // the function scope just pushed). + bool saved_in_function = ctx->in_function; + ctx->in_function = true; + go_shadow_type_params(ctx, ts_node_child_by_field_name(func_node, "type_parameters", 15)); + if (strcmp(ts_node_type(func_node), "method_declaration") == 0) { + go_shadow_receiver_params(ctx, ts_node_child_by_field_name(func_node, "receiver", 8), false, + 0); + } + // Bind parameters into scope (including variadic) TSNode params = ts_node_child_by_field_name(func_node, "parameters", 10); if (!ts_node_is_null(params)) { @@ -2129,6 +2342,7 @@ static void process_function(GoLSPContext *ctx, TSNode func_node) { // Restore scope ctx->current_scope = saved_scope; + ctx->in_function = saved_in_function; } // --- Process entire file --- @@ -2171,18 +2385,23 @@ void go_lsp_process_file(GoLSPContext *ctx, TSNode root) { // --- Helper: parse Go return type text into CBMType --- -const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const char *module_qn) { +/* scope_ix: the defining def's resolved type identities (CBMLSPDef.type_scope, + * indexed), NULL when it has none. A named type the scope knows is that + * identity; any other named type keeps the module qualification. */ +static const CBMType *go_parse_type_text_scoped(CBMArena *a, const char *text, + const char *module_qn, + const cbm_type_scope_index_t *scope_ix) { if (!text || !text[0]) return cbm_type_unknown(); // Pointer: *Foo if (text[0] == '*') { - return cbm_type_pointer(a, cbm_parse_return_type_text(a, text + 1, module_qn)); + return cbm_type_pointer(a, go_parse_type_text_scoped(a, text + 1, module_qn, scope_ix)); } // Slice: []Foo if (text[0] == '[' && text[1] == ']') { - return cbm_type_slice(a, cbm_parse_return_type_text(a, text + 2, module_qn)); + return cbm_type_slice(a, go_parse_type_text_scoped(a, text + 2, module_qn, scope_ix)); } // Builtin types @@ -2195,19 +2414,30 @@ const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const c return cbm_type_builtin(a, text); } + // Named type the defining file's scope resolved (`pkg.T` through its import). + const char *scoped = cbm_type_scope_find(scope_ix, text, strlen(text)); + if (scoped) { + return cbm_type_named(a, scoped); + } + // Named type: assume local to module return cbm_type_named(a, cbm_arena_sprintf(a, "%s.%s", module_qn, text)); } +const CBMType *cbm_parse_return_type_text(CBMArena *a, const char *text, const char *module_qn) { + return go_parse_type_text_scoped(a, text, module_qn, NULL); +} + typedef struct { const char *module_qn; + const cbm_type_scope_index_t *scope_ix; /* the def's resolved type identities, or NULL */ } CBMGoLSPSignatureParserContext; static const CBMType *cbm_go_lsp_parse_signature_param_text(CBMArena *arena, const char *text, void *parser_ctx) { const CBMGoLSPSignatureParserContext *ctx = (const CBMGoLSPSignatureParserContext *)parser_ctx; const char *module_qn = ctx && ctx->module_qn ? ctx->module_qn : ""; - return cbm_parse_return_type_text(arena, text, module_qn); + return go_parse_type_text_scoped(arena, text, module_qn, ctx ? ctx->scope_ix : NULL); } // --- Shared Go stdlib registry --- @@ -2578,12 +2808,20 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, if (ts_node_is_null(field_list)) continue; - // Scan field_declarations for embeds and named fields - const char *embeds[16]; + // Scan field_declarations for embeds and named fields: all of + // them (no count decides what the registry holds). An embedded + // type is also a field named by its unqualified type name. + uint32_t fl_cap = ts_node_child_count(field_list) * 2 + 1; + const char **embeds = + (const char **)cbm_arena_alloc(arena, fl_cap * sizeof(const char *)); int embed_count = 0; - const char *fld_names[64]; - const CBMType *fld_types[64]; + const char **fld_names = + (const char **)cbm_arena_alloc(arena, fl_cap * sizeof(const char *)); + const CBMType **fld_types = + (const CBMType **)cbm_arena_alloc(arena, fl_cap * sizeof(const CBMType *)); int fld_count = 0; + if (!embeds || !fld_names || !fld_types) + continue; // Create a temporary LSP context for parsing field types GoLSPContext tmp_ctx; @@ -2607,18 +2845,24 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, if (ts_node_is_null(fname) && !ts_node_is_null(ftype)) { // Embedded field: has type but no name - if (embed_count < 15) { - char *embed_text = cbm_node_text(arena, ftype, source); - if (embed_text && embed_text[0]) { - const char *et = embed_text; - while (*et == '*') - et++; - embeds[embed_count++] = - cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + char *embed_text = cbm_node_text(arena, ftype, source); + if (embed_text && embed_text[0]) { + const char *et = embed_text; + while (*et == '*') + et++; + const char *eqn = cbm_arena_sprintf(arena, "%s.%s", module_qn, et); + embeds[embed_count++] = eqn; + size_t elen = 0; + const char *enext = embed_text; + const char *es = go_embedded_spelling(&enext, &elen); + const char *ename = es ? go_embedded_field_name(arena, es, elen) : NULL; + if (ename && eqn) { + fld_names[fld_count] = ename; + fld_types[fld_count] = cbm_type_named(arena, eqn); + fld_count++; } } - } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype) && - fld_count < 63) { + } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype)) { // Named field: name + type char *fn = cbm_node_text(arena, fname, source); if (fn && fn[0]) { @@ -2682,8 +2926,10 @@ void cbm_run_go_lsp(CBMArena *arena, CBMFileResult *result, const char *source, // --- Cross-file LSP: parse source, build registry from defs, run LSP --- -// Helper: split "|"-separated string into array of CBMType*. -static const CBMType **split_pipe_types(CBMArena *a, const char *text, const char *module_qn) { +// Helper: split "|"-separated string into array of CBMType*. scope_ix: the +// defining def's resolved type identities (go_parse_type_text_scoped). +static const CBMType **split_pipe_types(CBMArena *a, const char *text, const char *module_qn, + const cbm_type_scope_index_t *scope_ix) { if (!text || !text[0]) return NULL; @@ -2708,7 +2954,7 @@ static const CBMType **split_pipe_types(CBMArena *a, const char *text, const cha char save = *p; *p = '\0'; if (start[0]) { - arr[idx++] = cbm_parse_return_type_text(a, start, module_qn); + arr[idx++] = go_parse_type_text_scoped(a, start, module_qn, scope_ix); } if (save == '\0') break; @@ -2719,6 +2965,256 @@ static const CBMType **split_pipe_types(CBMArena *a, const char *text, const cha return idx > 0 ? arr : NULL; } +/* The mark of a QN in the value table below (go_value_qn_counts) whose + * definitions give different answers; any other value is the QN's first + * definition. */ +static char g_go_qn_shared_mark; + +static bool go_type_qn_shared(const CBMHashTable *shared, const char *qn) { + return shared && qn && cbm_ht_get(shared, qn) == &g_go_qn_shared_mark; +} + +static bool go_same_text(const char *a, const char *b) { + return (!a || !a[0]) ? (!b || !b[0]) : (b && strcmp(a, b) == 0); +} + +/* The QN a package-level value registers under: ., or NULL + * for a def that is no typed value. */ +static const char *go_value_qn(CBMArena *a, const CBMLSPDef *d, const char *def_mod) { + if (!d->label || strcmp(d->label, "Variable") != 0 || !d->short_name || !d->return_types || + !d->return_types[0] || strchr(d->return_types, '|') || !def_mod || !def_mod[0]) { + return NULL; + } + return cbm_arena_sprintf(a, "%s.%s", def_mod, d->short_name); +} + +/* Every Go def QN and every value QN, marked shared when two defs that give + * different answers have it. A directory holds both `package foo` and + * `package foo_test`, and their package-level names live under one directory + * QN: a value whose QN another definition also has (a value of another type + * or identity, a function, a type of the other package) is registered for + * neither, so no answer depends on file order. Two values of one QN that + * spell the same type with the same identities (build variants of one + * declaration) give one answer and stay. NULL on allocation failure (then no + * value is registered). */ +static CBMHashTable *go_value_qn_counts(CBMArena *a, const CBMLSPDef *defs, int def_count, + const char *fallback_mod) { + CBMHashTable *seen = cbm_ht_create((uint32_t)(def_count / 4 + 64)); + for (int i = 0; seen && i < def_count; i++) { + const CBMLSPDef *d = &defs[i]; + if (!d->qualified_name || d->lang != CBM_LANG_GO) { + continue; + } + const char *def_mod = d->def_module_qn ? d->def_module_qn : fallback_mod; + const char *value_qn = go_value_qn(a, d, def_mod); + const char *keys[2] = {d->qualified_name, + value_qn && strcmp(value_qn, d->qualified_name) != 0 ? value_qn + : NULL}; + for (int k = 0; k < 2; k++) { + if (!keys[k]) { + continue; + } + void *prev = cbm_ht_get(seen, keys[k]); + if (!prev) { + cbm_ht_set(seen, keys[k], (void *)d); /* the first definition */ + continue; + } + const CBMLSPDef *first = (const CBMLSPDef *)prev; + bool same_value = + prev != &g_go_qn_shared_mark && value_qn && + go_value_qn(a, first, first->def_module_qn ? first->def_module_qn : fallback_mod) && + go_same_text(first->return_types, d->return_types) && + go_same_text(first->type_scope, d->type_scope); + if (!same_value) { + cbm_ht_set(seen, keys[k], &g_go_qn_shared_mark); + } + } + } + return seen; +} + +/* ── Language hook: promotion of embedded-struct members ───────────── + * + * Go promotes the methods and fields of an embedded type to the struct that + * embeds it. A member lookup on the struct falls through to its embedded + * types (go_lookup_promoted), which needs their QNs; a struct from another + * file brings them as their source spelling ("logging.LogHolder", "*Base"). + * The QN of a spelling is its identity in the declaring file's scope + * (type_scope.h), or for a bare name the declaring package's own type; a + * spelling neither gives is dropped. This is the one Go-specific step on top + * of the shared layer. */ +/* One embedded spelling of a '|'-joined list, without its `*` and its type + * arguments (a generic instance names its type): sets *len, returns its + * start, or NULL at the end of the list. *next moves past it. */ +static const char *go_embedded_spelling(const char **next, size_t *len) { + const char *p = *next; + if (!p || !*p) { + return NULL; + } + const char *bar = strchr(p, '|'); + size_t n = bar ? (size_t)(bar - p) : strlen(p); + *next = bar ? bar + 1 : p + n; + while (n > 0 && *p == '*') { + p++; + n--; + } + const char *bracket = memchr(p, '[', n); + *len = bracket ? (size_t)(bracket - p) : n; + return p; +} + +/* The QN of one embedded spelling: its identity in the declaring file's + * scope, or for a bare name the declaring package's own type; NULL when + * neither gives one. */ +static const char *go_embedded_qn(CBMArena *a, const char *s, size_t len, const char *def_mod, + const cbm_type_scope_index_t *scope_ix) { + const char *qn = len ? cbm_type_scope_find(scope_ix, s, len) : NULL; + if (!qn && len && !memchr(s, '.', len) && def_mod && def_mod[0]) { + qn = cbm_arena_sprintf(a, "%s.%.*s", def_mod, (int)len, s); + } + return qn; +} + +/* The field name an embedded spelling declares: Go's unqualified type name + * (`pkg.T` -> `T`). NULL when it has none. */ +static const char *go_embedded_field_name(CBMArena *a, const char *s, size_t len) { + const char *name = s; + for (size_t i = 0; i < len; i++) { + if (s[i] == '.') { + name = s + i + 1; + } + } + size_t n = len - (size_t)(name - s); + return n ? cbm_arena_strndup(a, name, n) : NULL; +} + +static const char **go_embedded_qns(CBMArena *a, const char *embedded, const char *def_mod, + const cbm_type_scope_index_t *scope_ix) { + if (!embedded || !embedded[0]) { + return NULL; + } + int count = 1; + for (const char *p = embedded; *p; p++) { + count += *p == '|'; + } + const char **out = (const char **)cbm_arena_alloc(a, (size_t)(count + 1) * sizeof(*out)); + if (!out) { + return NULL; + } + int n = 0; + size_t len = 0; + for (const char *next = embedded, *s; (s = go_embedded_spelling(&next, &len)) != NULL;) { + const char *qn = go_embedded_qn(a, s, len, def_mod, scope_ix); + if (qn) { + out[n++] = qn; + } + } + out[n] = NULL; + return n > 0 ? out : NULL; +} + +/* Append fields to rt (a name rt already declares keeps its entry). One hash + * set of the names, so the cost is linear in the fields. */ +static void go_append_fields(CBMArena *a, CBMRegisteredType *rt, const char *const *names, + const CBMType *const *types, int n) { + if (n <= 0) { + return; + } + int had = 0; + while (rt->field_names && rt->field_names[had]) { + had++; + } + const char **out_names = + (const char **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(char *)); + const CBMType **out_types = + (const CBMType **)cbm_arena_alloc(a, (size_t)(had + n + 1) * sizeof(CBMType *)); + CBMHashTable *present = cbm_ht_create((uint32_t)(had + n + 8)); + if (!out_names || !out_types || !present) { + cbm_ht_free(present); + return; + } + int count = 0; + for (int i = 0; i < had; i++) { + out_names[count] = rt->field_names[i]; + out_types[count++] = rt->field_types ? rt->field_types[i] : NULL; + cbm_ht_set(present, rt->field_names[i], (void *)1); + } + for (int i = 0; i < n; i++) { + if (!names[i] || cbm_ht_get(present, names[i])) { + continue; + } + cbm_ht_set(present, names[i], (void *)1); + out_names[count] = names[i]; + out_types[count++] = types[i] ? types[i] : cbm_type_unknown(); + } + cbm_ht_free(present); + out_names[count] = NULL; + out_types[count] = NULL; + rt->field_names = out_names; + rt->field_types = out_types; +} + +/* Go's selector rule names an embedded field by its unqualified type name, at + * the embedding type's depth: `s.Config` is the embedded Config even where an + * embedded type has a field Config one level down, and a method of that name + * one level down is shadowed by it. Each embedded spelling of `embedded` + * becomes a field of rt: typed as the embedded type when `typed` and its QN is + * known, else of unknown type (it shadows, and answers nothing). */ +static void go_add_embedded_fields(CBMArena *a, CBMRegisteredType *rt, const char *embedded, + const char *def_mod, const cbm_type_scope_index_t *scope_ix, + bool typed) { + if (!embedded || !embedded[0] || rt->is_interface) { + return; + } + int count = 1; + for (const char *p = embedded; *p; p++) { + count += *p == '|'; + } + const char **names = (const char **)cbm_arena_alloc(a, (size_t)count * sizeof(char *)); + const CBMType **types = (const CBMType **)cbm_arena_alloc(a, (size_t)count * sizeof(CBMType *)); + if (!names || !types) { + return; + } + int n = 0; + size_t len = 0; + for (const char *next = embedded, *s; (s = go_embedded_spelling(&next, &len)) != NULL;) { + const char *name = go_embedded_field_name(a, s, len); + if (!name) { + continue; + } + const char *qn = typed ? go_embedded_qn(a, s, len, def_mod, scope_ix) : NULL; + names[n] = name; + types[n++] = qn ? cbm_type_named(a, qn) : cbm_type_unknown(); + } + go_append_fields(a, rt, names, types, n); +} + +/* A package-level value (a Go `var`/`const` Variable def whose declaration or + * initializer spells its type): registered under . with + * CBM_FUNC_FLAG_VALUE and that type as the signature's single result, so + * `pkg.V.Method()` and a bare `V.Method()` of another file are typed. A + * value is never a call target (go_lookup_callable, go_lookup_func_callable), + * and a QN another definition shares registers no value (go_value_qn_counts). */ +static void go_register_value(CBMTypeRegistry *reg, CBMArena *a, const CBMLSPDef *d, + const char *def_mod, const cbm_type_scope_index_t *scope_ix, + const CBMHashTable *value_qns) { + const char *qn = go_value_qn(a, d, def_mod); + if (!qn || !value_qns || go_type_qn_shared(value_qns, qn)) { + return; + } + const CBMType **ret = split_pipe_types(a, d->return_types, def_mod, scope_ix); + if (!ret || !ret[0] || cbm_type_is_unknown(ret[0])) { + return; + } + CBMRegisteredFunc rf; + memset(&rf, 0, sizeof(rf)); + rf.qualified_name = qn; + rf.short_name = d->short_name; + rf.signature = cbm_type_func(a, NULL, NULL, ret); + rf.flags = CBM_FUNC_FLAG_VALUE; + cbm_registry_add_func(reg, rf); +} + // Helper: split "|"-separated string into array of const char*. static const char **split_pipe_strings(CBMArena *a, const char *text) { if (!text || !text[0]) @@ -2780,16 +3276,15 @@ static const char *go_alias_target_qn(CBMArena *arena, const char *target, /* Parse "name:type|name:type" into NULL-terminated name/type arrays. False when * nothing parsed (or on allocation failure): the type keeps no field info. */ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char *def_module_qn, - const char ***names_out, const CBMType ***types_out) { + const cbm_type_scope_index_t *scope_ix, const char ***names_out, + const CBMType ***types_out) { - // Count fields + // Count fields: all of them (no count decides which fields a struct has) int count = 1; for (const char *p = field_defs; *p; p++) { if (*p == '|') count++; } - if (count > 63) - count = 63; const char **names = (const char **)cbm_arena_alloc(arena, (count + 1) * sizeof(const char *)); const CBMType **types = @@ -2815,7 +3310,7 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char if (colon && idx < count) { *colon = '\0'; names[idx] = cbm_arena_strdup(arena, start); - types[idx] = cbm_parse_return_type_text(arena, colon + 1, def_module_qn); + types[idx] = go_parse_type_text_scoped(arena, colon + 1, def_module_qn, scope_ix); idx++; } if (save == '\0') @@ -2830,23 +3325,268 @@ static bool parse_field_defs(CBMArena *arena, const char *field_defs, const char return idx > 0; } -static void parse_field_defs_into_type(CBMArena *arena, CBMTypeRegistry *reg, const char *type_qn, - const char *field_defs, const char *def_module_qn) { - if (!field_defs || !field_defs[0] || !type_qn) - return; - const char **names = NULL; - const CBMType **types = NULL; - if (parse_field_defs(arena, field_defs, def_module_qn, &names, &types)) { - // Find the registered type and update field info - for (int ti = 0; ti < reg->type_count; ti++) { - if (reg->types[ti].qualified_name && - strcmp(reg->types[ti].qualified_name, type_qn) == 0) { - reg->types[ti].field_names = names; - reg->types[ti].field_types = types; - break; +/* Go module QNs are directories, so a package and its external test package + * (`foo` and `foo_test`), or build-tagged variants, can declare two types of + * one QN. A type lookup answers with one entry of a name, which one depends on + * file order, so what is keyed by such a QN is registered only where every + * definition of the QN gives the same answer: + * - a field when every definition declares it with the same type text whose + * name means the same type (its identity, or the package's own type); + * - the embedded types when every definition embeds the same types. + * Build variants of one struct keep what they share; `foo` and `foo_test` + * declaring different structs of one name keep only what agrees. A name any + * definition declares as a field (named or embedded) is still a field of the + * QN at its depth, of unknown type where they do not agree, so no deeper + * member of that name is selected (go_type_qn_shadow). */ +typedef struct { + const CBMLSPDef *first; + int count; /* definitions of the QN */ + const char *first_embeds; /* the first definition's embedded QNs, '|'-joined */ + bool embeds_differ; + bool fields_done; + const char *fields; /* count > 1: the fields every definition agrees on, or NULL */ + const CBMLSPDef **all; /* count > 1: every definition of the QN */ + int all_cap; + bool shadow_done; + const char **shadow_names; /* every field name some definition declares */ + int shadow_count; +} go_type_qn_t; + +/* What a field type text means in one definition: the part the parser looks + * up after `*` and `[]`, resolved through the def's identities, or NULL for + * the package's own name (the same in every definition of one directory). */ +static const char *go_field_type_identity(const cbm_type_scope_index_t *ix, const char *text) { + while (text && (*text == '*' || (text[0] == '[' && text[1] == ']'))) { + text += *text == '*' ? 1 : 2; + } + return text ? cbm_type_scope_find(ix, text, strlen(text)) : NULL; +} + +static const char *go_join_embeds(CBMArena *a, const CBMLSPDef *d) { + const char *mod = d->def_module_qn ? d->def_module_qn : ""; + const char **qns = + go_embedded_qns(a, d->embedded_types, mod, cbm_type_scope_index(a, d->type_scope)); + size_t total = 1; + for (int i = 0; qns && qns[i]; i++) { + total += strlen(qns[i]) + 1; + } + char *out = (char *)cbm_arena_alloc(a, total); + if (!out) { + return ""; + } + size_t at = 0; + for (int i = 0; qns && qns[i]; i++) { + if (i) { + out[at++] = '|'; + } + size_t n = strlen(qns[i]); + memcpy(out + at, qns[i], n); + at += n; + } + out[at] = '\0'; + return out; +} + +/* Keep the fields of `agreed` ("name:type|...") that `d` declares alike. */ +static const char *go_agreed_fields(CBMArena *a, const char *agreed, const CBMLSPDef *agreed_def, + const CBMLSPDef *d) { + if (!agreed || !agreed[0] || !d->field_defs || !d->field_defs[0]) { + return NULL; + } + const cbm_type_scope_index_t *agreed_ix = cbm_type_scope_index(a, agreed_def->type_scope); + const cbm_type_scope_index_t *d_ix = cbm_type_scope_index(a, d->type_scope); + CBMHashTable *mine = cbm_ht_create(16); + char *copy = cbm_arena_strdup(a, d->field_defs); + for (char *p = copy; mine && p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *colon = strchr(p, ':'); + if (colon) { + *colon = '\0'; + cbm_ht_set(mine, p, colon + 1); /* name -> type text */ + } + p = bar ? bar + 1 : NULL; + } + /* The kept fields are a subset of `agreed`: one buffer of its size. */ + char *out = (char *)cbm_arena_alloc(a, strlen(agreed) + 1); + size_t at = 0; + char *keep = cbm_arena_strdup(a, agreed); + for (char *p = keep; mine && out && p && *p;) { + char *bar = strchr(p, '|'); + if (bar) { + *bar = '\0'; + } + char *colon = strchr(p, ':'); + const char *theirs = + colon ? (const char *)cbm_ht_get(mine, cbm_arena_strndup(a, p, (size_t)(colon - p))) + : NULL; + if (theirs && strcmp(theirs, colon + 1) == 0 && + go_same_text(go_field_type_identity(agreed_ix, colon + 1), + go_field_type_identity(d_ix, theirs))) { + size_t n = strlen(p); + if (at) { + out[at++] = '|'; } + memcpy(out + at, p, n); + at += n; + } + p = bar ? bar + 1 : NULL; + } + cbm_ht_free(mine); + if (!out || at == 0) { + return NULL; + } + out[at] = '\0'; + return out; +} + +/* QN -> go_type_qn_t for every Go type definition (keys borrowed from defs; + * free with cbm_ht_free, entries live in `a`), or NULL on allocation failure + * (then a QN of two definitions keeps nothing). */ +static CBMHashTable *go_type_qn_table(CBMArena *a, const CBMLSPDef *defs, int def_count) { + CBMHashTable *table = cbm_ht_create((uint32_t)(def_count / 4 + 64)); + for (int i = 0; table && i < def_count; i++) { + const CBMLSPDef *d = &defs[i]; + if (!d->qualified_name || !d->label || d->lang != CBM_LANG_GO || + !cbm_label_is_type_like(d->label)) { + continue; + } + go_type_qn_t *e = (go_type_qn_t *)cbm_ht_get(table, d->qualified_name); + if (!e) { + e = (go_type_qn_t *)cbm_arena_alloc(a, sizeof(*e)); + if (!e) { + cbm_ht_free(table); + return NULL; + } + memset(e, 0, sizeof(*e)); + e->first = d; + cbm_ht_set(table, d->qualified_name, e); + } + e->count++; + if (e->count == 2) { + e->first_embeds = go_join_embeds(a, e->first); + e->fields = e->first->field_defs; + } + if (e->count >= 2) { + e->embeds_differ = + e->embeds_differ || !go_same_text(e->first_embeds, go_join_embeds(a, d)); + e->fields = go_agreed_fields(a, e->fields, e->first, d); + if (e->count > e->all_cap) { + int cap = e->all_cap ? e->all_cap * 2 : 4; + const CBMLSPDef **grown = + (const CBMLSPDef **)cbm_arena_alloc(a, (size_t)cap * sizeof(*grown)); + if (!grown) { + cbm_ht_free(table); + return NULL; + } + if (e->all_cap) { + memcpy(grown, e->all, (size_t)(e->count - 1) * sizeof(*grown)); + } else { + grown[0] = e->first; + } + e->all = grown; + e->all_cap = cap; + } + e->all[e->count - 1] = d; } } + return table; +} + +/* The field names some definition of a QN of several declares (named fields + * and embedded types), each once; computed on the first call. */ +static int go_pipe_pieces(const char *s) { + int n = s && *s ? 1 : 0; + for (; s && *s; s++) { + n += *s == '|'; + } + return n; +} + +static void go_shadow_note(go_type_qn_t *e, CBMHashTable *seen, const char *name) { + if (name && !cbm_ht_get(seen, name)) { + cbm_ht_set(seen, name, (void *)name); + e->shadow_names[e->shadow_count++] = name; + } +} + +static void go_type_qn_shadow(CBMArena *a, go_type_qn_t *e) { + if (e->shadow_done) { + return; + } + e->shadow_done = true; + int bound = 0; + for (int i = 0; i < e->count; i++) { + bound += go_pipe_pieces(e->all[i]->field_defs) + go_pipe_pieces(e->all[i]->embedded_types); + } + CBMHashTable *seen = bound ? cbm_ht_create((uint32_t)(bound + 8)) : NULL; + e->shadow_names = + seen ? (const char **)cbm_arena_alloc(a, (size_t)(bound + 1) * sizeof(char *)) : NULL; + if (!e->shadow_names) { + cbm_ht_free(seen); + return; + } + /* In definition order, then declaration order: a fixed order. */ + for (int i = 0; i < e->count; i++) { + const CBMLSPDef *d = e->all[i]; + for (const char *p = d->field_defs; p && *p;) { + const char *colon = strchr(p, ':'); + const char *bar = strchr(p, '|'); + if (colon && (!bar || colon < bar) && colon > p) { + go_shadow_note(e, seen, cbm_arena_strndup(a, p, (size_t)(colon - p))); + } + p = bar ? bar + 1 : NULL; + } + size_t len = 0; + for (const char *next = d->embedded_types, *s; + (s = go_embedded_spelling(&next, &len)) != NULL;) { + go_shadow_note(e, seen, go_embedded_field_name(a, s, len)); + } + } + e->shadow_names[e->shadow_count] = NULL; + cbm_ht_free(seen); +} + +/* A type QN of several definitions: every field name some definition + * declares that rt does not register with a type becomes a field of unknown + * type (it shadows deeper members and answers nothing). */ +static void go_add_shadow_fields(CBMArena *a, CBMRegisteredType *rt, const CBMHashTable *table, + const CBMLSPDef *d) { + go_type_qn_t *e = table ? (go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + if (!e || e->count < 2 || rt->is_interface) { + return; + } + go_type_qn_shadow(a, e); + if (e->shadow_count == 0) { + return; + } + const CBMType **types = + (const CBMType **)cbm_arena_alloc(a, (size_t)e->shadow_count * sizeof(CBMType *)); + if (!types) { + return; + } + for (int i = 0; i < e->shadow_count; i++) { + types[i] = cbm_type_unknown(); + } + go_append_fields(a, rt, e->shadow_names, types, e->shadow_count); +} + +/* The fields to register for `d`: its own when it is its QN's only definition, + * else those every definition of the QN agrees on (NULL: none). Without a + * table (allocation failure) every def keeps its own, as before the table. */ +static const char *go_type_qn_fields(const CBMHashTable *table, const CBMLSPDef *d) { + const go_type_qn_t *e = + table ? (const go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + return !e || e->count < 2 ? d->field_defs : e->fields; +} + +/* Whether `d`'s embedded types are the same in every definition of its QN. */ +static bool go_type_qn_embeds(const CBMHashTable *table, const CBMLSPDef *d) { + const go_type_qn_t *e = + table ? (const go_type_qn_t *)cbm_ht_get(table, d->qualified_name) : NULL; + return !e || e->count < 2 || !e->embeds_differ; } // --- Phase 1c: Extract type parameters from generic function declarations --- @@ -3358,12 +4098,16 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, // caller's arena which outlives this call, so cbm_arena_strdup is // wasted work. On kubernetes (~110k defs × 11k files × 5 strdups // ~= 6B mallocs) this alone saves ~90s of resolve wall time. + CBMHashTable *type_qns = go_type_qn_table(arena, defs, def_count); + CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, module_qn); for (int i = 0; i < def_count; i++) { CBMLSPDef *d = &defs[i]; if (!d->qualified_name || !d->short_name || !d->label) continue; const char *def_mod = d->def_module_qn ? d->def_module_qn : module_qn; + /* The def's declared-type identities, indexed once for its texts. */ + const cbm_type_scope_index_t *scope_ix = cbm_type_scope_index(arena, d->type_scope); // Every type-like container (Type/Class/Struct/Interface/Enum/Trait). // Struct included so Go structs (now labelled "Struct") register as types. @@ -3373,7 +4117,11 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, rt.qualified_name = d->qualified_name; // borrowed rt.short_name = d->short_name; // borrowed rt.is_interface = d->is_interface || strcmp(d->label, "Interface") == 0; - rt.embedded_types = split_pipe_strings(arena, d->embedded_types); + /* Embedded types other definitions of the QN differ in promote + * nothing (go_type_qn_table). */ + rt.embedded_types = go_type_qn_embeds(type_qns, d) + ? go_embedded_qns(arena, d->embedded_types, def_mod, scope_ix) + : NULL; // Set method_names for interfaces from "|"-separated string if (rt.is_interface && d->method_names_str && d->method_names_str[0]) { @@ -3381,12 +4129,22 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, } rt.alias_of = go_alias_target_qn(arena, d->alias_target, def_mod); - cbm_registry_add_type(®, rt); - - // Populate struct field types from field_defs - if (d->field_defs && d->field_defs[0]) { - parse_field_defs_into_type(arena, ®, rt.qualified_name, d->field_defs, def_mod); + // Struct field types from field_defs, on this def's own entry: a + // type lookup answers with the last entry of a name, so fields on + // an earlier receiver placeholder were never seen. A QN of several + // definitions keeps the fields they agree on (go_type_qn_table). + const char *fields = go_type_qn_fields(type_qns, d); + if (fields && fields[0]) { + (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, + &rt.field_types); } + /* Embedded types are fields too (Go's selector rule), and a QN of + * several definitions shadows every field name one declares. */ + go_add_embedded_fields(arena, &rt, d->embedded_types, def_mod, scope_ix, + go_type_qn_embeds(type_qns, d)); + go_add_shadow_fields(arena, &rt, type_qns, d); + + cbm_registry_add_type(®, rt); } // Function/Method @@ -3397,8 +4155,8 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, rf.short_name = d->short_name; // borrowed // Build FUNC type from return_types text - const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod); - CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod}; + const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod, scope_ix); + CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod, scope_ix}; const CBMType **param_types = cbm_type_materialize_signature_params( arena, d->signature_param_types, d->signature_param_count, cbm_go_lsp_parse_signature_param_text, ¶m_parser_ctx); @@ -3420,23 +4178,15 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, cbm_registry_add_func(®, rf); } + go_register_value(®, arena, d, def_mod, scope_ix, value_qns); } + cbm_ht_free(type_qns); /* NULL-safe */ + cbm_ht_free(value_qns); - // 3. Phase 1b: Scan AST for struct definitions to populate embedded_types + // 3. Phase 1b: the walked file's type aliases. Its structs' fields and + // embedded types come from their definitions, as on the shared registry: + // every field and every embedded type, the same answer on every route. { - /* One context parses every struct's field types, so its import rows are - * chained once (resolve_import), not once per struct. */ - GoLSPContext tmp_ctx; - memset(&tmp_ctx, 0, sizeof(tmp_ctx)); - tmp_ctx.arena = arena; - tmp_ctx.source = source; - tmp_ctx.source_len = source_len; - tmp_ctx.registry = ® - tmp_ctx.package_qn = module_qn; - tmp_ctx.import_local_names = import_names; - tmp_ctx.import_package_qns = import_qns; - tmp_ctx.import_count = import_count; - // Collect top-level children once (O(n)); ts_node_child(root,i) is O(i) → O(n²). uint32_t rkn = 0; TSNode *rkids = cbm_lsp_collect_children(arena, root, &rkn); @@ -3484,96 +4234,6 @@ void cbm_run_go_lsp_cross(CBMArena *arena, const char *source, int source_len, } continue; } - - if (strcmp(spec_kind2, "type_spec") != 0) - continue; - - TSNode name_node = ts_node_child_by_field_name(spec, "name", 4); - TSNode type_node = ts_node_child_by_field_name(spec, "type", 4); - if (ts_node_is_null(name_node) || ts_node_is_null(type_node)) - continue; - if (strcmp(ts_node_type(type_node), "struct_type") != 0) - continue; - - char *type_name = cbm_node_text(arena, name_node, source); - if (!type_name || !type_name[0]) - continue; - const char *type_qn = cbm_arena_sprintf(arena, "%s.%s", module_qn, type_name); - - TSNode field_list = ts_node_child_by_field_name(type_node, "body", 4); - if (ts_node_is_null(field_list)) { - if (ts_node_named_child_count(type_node) > 0) - field_list = ts_node_named_child(type_node, 0); - } - if (ts_node_is_null(field_list)) - continue; - - const char *embeds[16]; - int embed_count = 0; - const char *fld_names[64]; - const CBMType *fld_types[64]; - int fld_count = 0; - - uint32_t fl_nc = ts_node_child_count(field_list); - for (uint32_t k = 0; k < fl_nc; k++) { - TSNode field = ts_node_child(field_list, k); - if (ts_node_is_null(field) || !ts_node_is_named(field)) - continue; - if (strcmp(ts_node_type(field), "field_declaration") != 0) - continue; - TSNode fname = ts_node_child_by_field_name(field, "name", 4); - TSNode ftype = ts_node_child_by_field_name(field, "type", 4); - if (ts_node_is_null(fname) && !ts_node_is_null(ftype)) { - if (embed_count < 15) { - char *embed_text = cbm_node_text(arena, ftype, source); - if (embed_text && embed_text[0]) { - const char *et = embed_text; - while (*et == '*') - et++; - embeds[embed_count++] = - cbm_arena_sprintf(arena, "%s.%s", module_qn, et); - } - } - } else if (!ts_node_is_null(fname) && !ts_node_is_null(ftype) && - fld_count < 63) { - char *fn = cbm_node_text(arena, fname, source); - if (fn && fn[0]) { - fld_names[fld_count] = fn; - fld_types[fld_count] = go_parse_type_node(&tmp_ctx, ftype); - fld_count++; - } - } - } - - for (int ti = 0; ti < reg.type_count; ti++) { - if (!reg.types[ti].qualified_name || - strcmp(reg.types[ti].qualified_name, type_qn) != 0) - continue; - - if (embed_count > 0) { - const char **arr = (const char **)cbm_arena_alloc( - arena, (embed_count + 1) * sizeof(const char *)); - for (int ei = 0; ei < embed_count; ei++) - arr[ei] = embeds[ei]; - arr[embed_count] = NULL; - reg.types[ti].embedded_types = arr; - } - if (fld_count > 0) { - const char **names = (const char **)cbm_arena_alloc( - arena, (fld_count + 1) * sizeof(const char *)); - const CBMType **types = (const CBMType **)cbm_arena_alloc( - arena, (fld_count + 1) * sizeof(const CBMType *)); - for (int fi = 0; fi < fld_count; fi++) { - names[fi] = fld_names[fi]; - types[fi] = fld_types[fi]; - } - names[fld_count] = NULL; - types[fld_count] = NULL; - reg.types[ti].field_names = names; - reg.types[ti].field_types = types; - } - break; - } } } } @@ -3638,11 +4298,13 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * not finalized until the end, so its own lookup scans every type, and the * receiver check below plus the field-definition lookup made the build * O(types x (methods + structs)) -- 4.4 s single-threaded on the Go corpus, - * the scaling lane's parse_field_defs_into_type x2.9 (waste sanitizer, - * 2026-09-17). First-match semantics are kept exactly: a receiver's - * placeholder type added before its struct still receives the fields. - * NULL on allocation failure: the linear paths below run as before. */ + * the scaling lane's field-definition lookup x2.9 (waste sanitizer, + * 2026-09-17). A receiver's placeholder type added before its struct + * receives the struct's fields as well as the struct's own entry. + * NULL on allocation failure: the receiver check scans the registry. */ CBMHashTable *first_type = cbm_ht_create((uint32_t)(def_count / 4 + 1024)); + CBMHashTable *type_qns = go_type_qn_table(arena, defs, def_count); + CBMHashTable *value_qns = go_value_qn_counts(arena, defs, def_count, ""); int noted_types = 0; #define GO_NOTE_NEW_TYPES() \ do { \ @@ -3666,6 +4328,8 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i * (set by cbm_pxc_collect_all_defs). There is no caller module to * fall back to — this registry is project-wide, not per-file. */ const char *def_mod = d->def_module_qn ? d->def_module_qn : ""; + /* The def's declared-type identities, indexed once for its texts. */ + const cbm_type_scope_index_t *scope_ix = cbm_type_scope_index(arena, d->type_scope); // Every type-like container (Type/Class/Struct/Interface/Enum/Trait). // Struct included so Go structs (now labelled "Struct") register as types. @@ -3675,26 +4339,36 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i rt.qualified_name = d->qualified_name; /* borrowed */ rt.short_name = d->short_name; rt.is_interface = d->is_interface || strcmp(d->label, "Interface") == 0; - rt.embedded_types = split_pipe_strings(arena, d->embedded_types); + /* Embedded types other definitions of the QN differ in promote + * nothing (go_type_qn_table). */ + rt.embedded_types = go_type_qn_embeds(type_qns, d) + ? go_embedded_qns(arena, d->embedded_types, def_mod, scope_ix) + : NULL; if (rt.is_interface && d->method_names_str && d->method_names_str[0]) { rt.method_names = split_pipe_strings(arena, d->method_names_str); } rt.alias_of = go_alias_target_qn(arena, d->alias_target, def_mod); + /* Fields on this def's own entry, which a lookup after finalize + * answers with (the last entry of a name). The first entry -- a + * receiver placeholder when a method came earlier -- keeps them + * too, for the first-registered readers. A QN of several + * definitions keeps the fields they agree on (go_type_qn_table). */ + const char *fields = go_type_qn_fields(type_qns, d); + if (fields && fields[0]) { + (void)parse_field_defs(arena, fields, def_mod, scope_ix, &rt.field_names, + &rt.field_types); + } + /* Embedded types are fields too (Go's selector rule), and a QN of + * several definitions shadows every field name one declares. */ + go_add_embedded_fields(arena, &rt, d->embedded_types, def_mod, scope_ix, + go_type_qn_embeds(type_qns, d)); + go_add_shadow_fields(arena, &rt, type_qns, d); cbm_registry_add_type(reg, rt); GO_NOTE_NEW_TYPES(); - if (d->field_defs && d->field_defs[0]) { - if (first_type) { - const char **names = NULL; - const CBMType **types = NULL; - uintptr_t at = (uintptr_t)cbm_ht_get(first_type, rt.qualified_name); - if (parse_field_defs(arena, d->field_defs, def_mod, &names, &types) && at) { - reg->types[at - 1].field_names = names; - reg->types[at - 1].field_types = types; - } - } else { - parse_field_defs_into_type(arena, reg, rt.qualified_name, d->field_defs, - def_mod); - } + uintptr_t at = first_type ? (uintptr_t)cbm_ht_get(first_type, rt.qualified_name) : 0; + if (rt.field_names && at && (int)at - 1 != reg->type_count - 1) { + reg->types[at - 1].field_names = rt.field_names; + reg->types[at - 1].field_types = rt.field_types; } } @@ -3703,8 +4377,8 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i memset(&rf, 0, sizeof(rf)); rf.qualified_name = d->qualified_name; /* borrowed */ rf.short_name = d->short_name; - const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod); - CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod}; + const CBMType **ret_types = split_pipe_types(arena, d->return_types, def_mod, scope_ix); + CBMGoLSPSignatureParserContext param_parser_ctx = {def_mod, scope_ix}; const CBMType **param_types = cbm_type_materialize_signature_params( arena, d->signature_param_types, d->signature_param_count, cbm_go_lsp_parse_signature_param_text, ¶m_parser_ctx); @@ -3725,9 +4399,12 @@ CBMTypeRegistry *cbm_go_build_cross_registry(CBMArena *arena, CBMLSPDef *defs, i } cbm_registry_add_func(reg, rf); } + go_register_value(reg, arena, d, def_mod, scope_ix, value_qns); } #undef GO_NOTE_NEW_TYPES cbm_ht_free(first_type); + cbm_ht_free(type_qns); /* NULL-safe */ + cbm_ht_free(value_qns); cbm_registry_finalize(reg); reg->read_only = true; /* seal: shared Tier-2 registry is read-only during resolve */ @@ -3828,7 +4505,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * * but the global registry has. (method_not_found with NAMED * receiver, or any other case where callee_qn looks like a * full QN). Direct lookup. */ - const CBMRegisteredFunc *f = cbm_registry_lookup_func(reg, uc->callee_qn); + const CBMRegisteredFunc *f = go_lookup_func_callable(reg, uc->callee_qn); /* Case 2: callee_qn is "local_pkg_alias.suffix" — the alias * needs translating through the file's import map to get the @@ -3848,7 +4525,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * char fq[1024]; int n = snprintf(fq, sizeof(fq), "%s.%s", import_qns[j], suffix); if (n > 0 && n < (int)sizeof(fq)) { - f = cbm_registry_lookup_func(reg, fq); + f = go_lookup_func_callable(reg, fq); } break; } @@ -3862,7 +4539,7 @@ int cbm_go_fast_resolve_qualified_calls(CBMFileResult *result, CBMTypeRegistry * * an exact package-local lookup rather than a project-wide short-name * guess. */ if (!f && !strchr(uc->callee_qn, '.') && result->module_qn) { - f = cbm_registry_lookup_symbol(reg, result->module_qn, uc->callee_qn); + f = go_lookup_callable(reg, result->module_qn, uc->callee_qn); } if (!f) diff --git a/internal/cbm/lsp/go_lsp.h b/internal/cbm/lsp/go_lsp.h index 6724f186a..ec7b04ea1 100644 --- a/internal/cbm/lsp/go_lsp.h +++ b/internal/cbm/lsp/go_lsp.h @@ -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. diff --git a/internal/cbm/lsp/py_lsp.c b/internal/cbm/lsp/py_lsp.c index 8e745c23f..5f348cb72 100644 --- a/internal/cbm/lsp/py_lsp.c +++ b/internal/cbm/lsp/py_lsp.c @@ -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]) { diff --git a/internal/cbm/lsp/type_registry.h b/internal/cbm/lsp/type_registry.h index c979833d0..68caae8ae 100644 --- a/internal/cbm/lsp/type_registry.h +++ b/internal/cbm/lsp/type_registry.h @@ -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. diff --git a/internal/cbm/lsp/type_rep.c b/internal/cbm/lsp/type_rep.c index afc5b0d52..a7694fb46 100644 --- a/internal/cbm/lsp/type_rep.c +++ b/internal/cbm/lsp/type_rep.c @@ -1,4 +1,5 @@ #include "type_rep.h" +#include #include #include @@ -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; +} diff --git a/internal/cbm/lsp/type_rep.h b/internal/cbm/lsp/type_rep.h index a32e7812a..c5e2b2f31 100644 --- a/internal/cbm/lsp/type_rep.h +++ b/internal/cbm/lsp/type_rep.h @@ -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 diff --git a/internal/cbm/result_compact.c b/internal/cbm/result_compact.c index b8b70da46..64aa44dac 100644 --- a/internal/cbm/result_compact.c +++ b/internal/cbm/result_compact.c @@ -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) { diff --git a/src/pipeline/lsp_surface.c b/src/pipeline/lsp_surface.c index 20b16e5e3..5d1bd5599 100644 --- a/src/pipeline/lsp_surface.c +++ b/src/pipeline/lsp_surface.c @@ -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; } @@ -535,17 +791,34 @@ 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; + } cbm_pipeline_result_release(fr, loaded); if (!json) { 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); @@ -749,6 +1022,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. */ diff --git a/src/pipeline/lsp_surface.h b/src/pipeline/lsp_surface.h index 1a73b3427..937e1430b 100644 --- a/src/pipeline/lsp_surface.h +++ b/src/pipeline/lsp_surface.h @@ -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. */ diff --git a/src/pipeline/pass_lsp_cross.c b/src/pipeline/pass_lsp_cross.c index eae590326..9299fe4eb 100644 --- a/src/pipeline/pass_lsp_cross.c +++ b/src/pipeline/pass_lsp_cross.c @@ -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) { diff --git a/src/pipeline/pass_lsp_cross.h b/src/pipeline/pass_lsp_cross.h index 51964bc41..9459ea903 100644 --- a/src/pipeline/pass_lsp_cross.h +++ b/src/pipeline/pass_lsp_cross.h @@ -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 diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.c index bae038f5d..48b69aa19 100644 --- a/src/pipeline/pipeline.c +++ b/src/pipeline/pipeline.c @@ -2609,6 +2609,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]; diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c index 40a425ea6..92b7cc804 100644 --- a/src/pipeline/pipeline_incremental.c +++ b/src/pipeline/pipeline_incremental.c @@ -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 @@ -3235,9 +3262,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 +3276,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 +3315,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 +3330,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 +3355,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 +3450,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 +3470,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); diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h index 475f233a2..029b1b8b4 100644 --- a/src/pipeline/pipeline_internal.h +++ b/src/pipeline/pipeline_internal.h @@ -2081,6 +2081,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. */ diff --git a/src/pipeline/type_scope.c b/src/pipeline/type_scope.c new file mode 100644 index 000000000..ed840cb69 --- /dev/null +++ b/src/pipeline/type_scope.c @@ -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 +#include +#include +#include +#include + +/* ── 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; /* "." 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 (".", 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); +} diff --git a/src/pipeline/type_scope.h b/src/pipeline/type_scope.h new file mode 100644 index 000000000..cf547850f --- /dev/null +++ b/src/pipeline/type_scope.h @@ -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 `.`, + * 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 + * `.`, 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 +#include + +/* 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 */ diff --git a/tests/test_go_lsp.c b/tests/test_go_lsp.c index 1f0d58087..49a948384 100644 --- a/tests/test_go_lsp.c +++ b/tests/test_go_lsp.c @@ -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", diff --git a/tests/test_main.c b/tests/test_main.c index 189ad8e93..e93c5f95a 100644 --- a/tests/test_main.c +++ b/tests/test_main.c @@ -1860,6 +1860,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); @@ -2748,6 +2749,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); diff --git a/tests/test_pipeline.c b/tests/test_pipeline.c index f6adc208f..a6a422eff 100644 --- a/tests/test_pipeline.c +++ b/tests/test_pipeline.c @@ -32639,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]); @@ -32770,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\":[]}]}}", @@ -32807,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\":[]}]}}"; @@ -32835,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\"," @@ -32928,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); diff --git a/tests/test_type_scope.c b/tests/test_type_scope.c new file mode 100644 index 000000000..ad7f7fc6a --- /dev/null +++ b/tests/test_type_scope.c @@ -0,0 +1,2462 @@ +/* + * test_type_scope.c — declared types resolved once, in the scope that wrote + * them (src/pipeline/type_scope.h). + * + * Unit tests pin the shared step's answers against a hand-built registry: an + * identity is stored only when the declaring file's scope gives exactly one + * answer and that answer is a project type. Growth tests count the work of + * every loop the step adds at two sizes. Pipeline tests index small fixtures + * per engine (a caller, a file declaring a function or field whose type it + * imports, the file defining that type, and a same-named decoy) with one + * worker and with four, above the parallel threshold; the shapes the review + * of the first cut found false edges in get no edge; and every incremental + * route gives the full index's graph. + */ +#include "test_framework.h" +#include "test_helpers.h" + +#include "foundation/compat.h" +#include "foundation/compat_fs.h" +#include "foundation/arena.h" +#include "lsp/type_rep.h" +#include "pipeline/lsp_surface.h" +#include "pipeline/pass_lsp_cross.h" +#include "pipeline/pipeline.h" +#include "pipeline/pipeline_internal.h" /* incremental route seam */ +#include "pipeline/type_scope.h" +#include "sqlite3.h" +#include "store/store.h" + +#include +#include +#include + +/* ── Unit: the shared step ─────────────────────────────────────────── */ + +typedef struct { + cbm_registry_t *reg; + CBMArena arena; +} ts_unit_t; + +static void ts_unit_begin(ts_unit_t *u) { + u->reg = cbm_registry_new(); + cbm_arena_init(&u->arena); + cbm_registry_add(u->reg, "Store", "p.a.Store", "Class", false); + cbm_registry_add(u->reg, "Store", "p.b.Store", "Class", false); + cbm_registry_add(u->reg, "Result", "p.c.Result", "Variable", false); + cbm_registry_add(u->reg, "make", "p.c.make", "Function", false); + cbm_registry_add(u->reg, "Local", "p.app.Local", "Class", false); +} + +static void ts_unit_end(ts_unit_t *u) { + cbm_registry_free(u->reg); + cbm_arena_destroy(&u->arena); +} + +/* A Python module's namespace facts: each name bound once by an import. */ +typedef struct { + CBMPyNamespaceFact items[16]; + CBMPyNamespaceFacts facts; +} ts_facts_t; + +static const CBMPyNamespaceFacts *ts_facts(ts_facts_t *f, const char *const *bound, int n) { + memset(f, 0, sizeof(*f)); + for (int i = 0; i < n && i < 16; i++) { + f->items[i] = (CBMPyNamespaceFact){.kind = CBM_PY_NS_IMPORT_NAME, .local_name = bound[i]}; + } + f->facts = (CBMPyNamespaceFacts){.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = f->items, + .count = n < 16 ? n : 16, + .cap = 16}; + return &f->facts; +} + +typedef struct { + CBMLanguage lang; + const char *def_qn; /* default p.app.f */ + const char *ret; + const char *const *keys; + const char *const *vals; + int n; + const CBMDefinition *file_defs; + int file_def_count; + const CBMPyNamespaceFacts *facts; /* Python; NULL = one complete empty record */ +} ts_attach_t; + +/* The type_scope one def gets in module p.app. */ +static const char *ts_unit_attach_with(ts_unit_t *u, const ts_attach_t *in) { + ts_facts_t empty; + cbm_type_scope_t scope = {.reg = u->reg, + .module_qn = "p.app", + .imp_keys = in->keys, + .imp_vals = in->vals, + .imp_count = in->n, + .file_defs = in->file_defs, + .file_def_count = in->file_def_count, + .module_facts = in->facts ? in->facts : ts_facts(&empty, NULL, 0)}; + cbm_type_scope_file_t *f = cbm_type_scope_file_begin(cbm_type_scope_lang(in->lang), &scope); + if (!f) { + return ""; + } + CBMLSPDef def = {0}; + def.qualified_name = in->def_qn ? in->def_qn : "p.app.f"; + def.short_name = "f"; + def.label = "Function"; + def.return_types = in->ret; + def.lang = in->lang; + cbm_type_scope_attach(f, &u->arena, &def); + cbm_type_scope_file_end(f); + return def.type_scope; +} + +static const char *ts_unit_attach(ts_unit_t *u, CBMLanguage lang, const char *ret, + const char *const *keys, const char *const *vals, int n) { + ts_attach_t in = {.lang = lang, .ret = ret, .keys = keys, .vals = vals, .n = n}; + return ts_unit_attach_with(u, &in); +} + +TEST(type_scope_import_binding_is_the_identity) { + ts_unit_t u; + ts_unit_begin(&u); + /* `from p.a import Store`-shaped (a module-valued binding) and a direct + * one; the same-named Store of the other module is never chosen. */ + const char *keys[] = {"Store"}; + const char *mod_vals[] = {"p.a"}; + const char *direct_vals[] = {"p.b.Store"}; + ts_facts_t facts; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Optional[Store]", + .keys = keys, + .vals = mod_vals, + .n = 1, + .facts = ts_facts(&facts, keys, 1)}; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Store=p.a.Store"); + in.vals = direct_vals; + in.ret = "list[Store]"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Store=p.b.Store"); + /* The own module declares Store as well: two bindings of one name. */ + cbm_registry_add(u.reg, "Store", "p.app.Store", "Class", false); + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +TEST(type_scope_dotted_spelling_through_its_head) { + ts_unit_t u; + ts_unit_begin(&u); + const char *keys[] = {"a"}; + const char *vals[] = {"p.a"}; + /* Go `*a.Store`, `[]a.Store`, a map value: one identity for `a.Store`. */ + const char *got = + ts_unit_attach(&u, CBM_LANG_GO, "*a.Store|[]a.Store|map[string]a.Store", keys, vals, 1); + ASSERT_STR_EQ(got, "a.Store=p.a.Store"); + /* A name the head's module does not declare: nothing. */ + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "*a.Missing", keys, vals, 1)); + ts_unit_end(&u); + PASS(); +} + +TEST(type_scope_stores_nothing_without_one_answer) { + ts_unit_t u; + ts_unit_begin(&u); + ts_facts_t facts; + /* Two imports bind Store to different targets: ambiguous. */ + const char *keys2[] = {"Store", "Store"}; + const char *vals2[] = {"p.a.Store", "p.b.Store"}; + const char *one[] = {"Store"}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Store", + .keys = keys2, + .vals = vals2, + .n = 2, + .facts = ts_facts(&facts, one, 1)}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* Not found anywhere in scope. */ + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_PYTHON, "Nowhere", NULL, NULL, 0)); + /* Bound, but to something no members are looked up on: a variable and a + * function. */ + const char *rk[] = {"Result", "make"}; + const char *rv[] = {"p.c.Result", "p.c.make"}; + ts_attach_t bound = {.lang = CBM_LANG_PYTHON, + .ret = "Result[make]", + .keys = rk, + .vals = rv, + .n = 2, + .facts = ts_facts(&facts, rk, 2)}; + ASSERT_NULL(ts_unit_attach_with(&u, &bound)); + ts_unit_end(&u); + PASS(); +} + +/* Finding 6: an import that names no project definition (the standard + * library, a third-party package) is no identity, and the engine keeps its + * own handling of the spelling (`Self`). */ +TEST(type_scope_names_outside_the_project_get_none) { + ts_unit_t u; + ts_unit_begin(&u); + ts_facts_t facts; + const char *keys[] = {"Self", "logging", "pathlib"}; + /* What the import map makes of them: project-prefixed paths no node has. */ + const char *vals[] = {"p.typing.Self", "p.logging", "p.pathlib"}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .ret = "Self", + .keys = keys, + .vals = vals, + .n = 3, + .facts = ts_facts(&facts, keys, 3)}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "logging.Logger"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "pathlib.Path"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +/* Go imports bind packages: a bare name never resolves through one, so a + * type parameter (never dotted) named like an import cannot take a type of + * that package; and an own-module name is left to the engine. */ +TEST(type_scope_go_bare_names_and_own_module) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "T", "p.tpkg.T", "Struct", false); + const char *keys[] = {"T"}; + const char *vals[] = {"p.tpkg"}; + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "T", keys, vals, 1)); + ASSERT_STR_EQ(ts_unit_attach(&u, CBM_LANG_GO, "*T.T", keys, vals, 1), "T.T=p.tpkg.T"); + ASSERT_NULL(ts_unit_attach(&u, CBM_LANG_GO, "*Local", NULL, NULL, 0)); + ts_unit_end(&u); + PASS(); +} + +/* Python's cross registrar keeps bare spellings, so an own-module identity + * is stored (a forward reference in quotes too). */ +TEST(type_scope_python_own_module) { + ts_unit_t u; + ts_unit_begin(&u); + ASSERT_STR_EQ(ts_unit_attach(&u, CBM_LANG_PYTHON, "Optional[\"Local\"]", NULL, NULL, 0), + "Local=p.app.Local"); + ts_unit_end(&u); + PASS(); +} + +/* Finding 3: a method's annotation is looked up in its class body first. A + * name the enclosing class declares (a nested class, a class attribute) gets + * no identity, and a def inside a function none at all. */ +TEST(type_scope_python_enclosing_scopes) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "Config", "p.app.Config", "Class", false); + cbm_registry_add(u.reg, "Config", "p.app.Model.Config", "Class", false); + cbm_registry_add(u.reg, "Alias", "p.app.Alias", "Class", false); + const CBMDefinition defs[] = { + {.qualified_name = "p.app.Config", .label = "Class"}, + {.qualified_name = "p.app.Alias", .label = "Class"}, + {.qualified_name = "p.app.Model", .label = "Class"}, + {.qualified_name = "p.app.Model.Config", .label = "Class"}, + {.qualified_name = "p.app.Model.Alias", .label = "Variable"}, + {.qualified_name = "p.app.Model.cfg", .label = "Method"}, + {.qualified_name = "p.app.Model.alias", .label = "Method"}, + {.qualified_name = "p.app.Model.Config.owner", .label = "Method"}, + {.qualified_name = "p.app.outer", .label = "Function"}, + {.qualified_name = "p.app.outer.inner", .label = "Function"}, + {.qualified_name = "p.app.top", .label = "Function"}, + }; + int n = (int)(sizeof(defs) / sizeof(defs[0])); + ts_attach_t in = { + .lang = CBM_LANG_PYTHON, .file_defs = defs, .file_def_count = n, .ret = "Config"}; + in.def_qn = "p.app.Model.cfg"; /* Model.Config */ + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.Model.alias"; + in.ret = "Alias"; /* the class attribute Model.Alias */ + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.outer.inner"; /* inside a function: its locals */ + in.ret = "Config"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* The module scope answers where nothing encloses the name. */ + in.def_qn = "p.app.top"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Config=p.app.Config"); + in.def_qn = "p.app.Model.Config.owner"; /* its class declares no `Alias` */ + in.ret = "Alias"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Alias=p.app.Alias"); + ts_unit_end(&u); + PASS(); +} + +/* Round 3, N2: a name the class body binds without defining it (`Config = + * Other`, an import, a loop, with or except target) is the class attribute in + * its methods' annotations, so it gets no identity; a name the body does not + * bind keeps the module's. */ +TEST(type_scope_python_class_body_bindings) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "Config", "p.app.Config", "Class", false); + cbm_registry_add(u.reg, "Keep", "p.app.Keep", "Class", false); + static const CBMDefTypeFacts model_binds = {.class_bindings = "x|Config|Other"}; + const CBMDefinition defs[] = { + {.qualified_name = "p.app.Config", .label = "Class"}, + {.qualified_name = "p.app.Keep", .label = "Class"}, + {.qualified_name = "p.app.Model", .label = "Class", .type_facts = &model_binds}, + {.qualified_name = "p.app.Model.cfg", .label = "Method"}, + {.qualified_name = "p.app.top", .label = "Function"}, + }; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .file_defs = defs, + .file_def_count = (int)(sizeof(defs) / sizeof(defs[0])), + .def_qn = "p.app.Model.cfg", + .ret = "Optional[Config]"}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.ret = "Keep"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Keep=p.app.Keep"); + in.def_qn = "p.app.top"; /* outside the class: the module's Config */ + in.ret = "Config"; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Config=p.app.Config"); + ts_unit_end(&u); + PASS(); +} + +/* Type parameters: a PEP 695 parameter of the file (`def f[T]`, + * `class C[T]`) and a TypeVar the module assigns over an import never take a + * real type's identity. */ +TEST(type_scope_python_type_parameters) { + ts_unit_t u; + ts_unit_begin(&u); + cbm_registry_add(u.reg, "T", "p.app.T", "Class", false); + cbm_registry_add(u.reg, "Item", "p.a.Item", "Class", false); + static const CBMDefTypeFacts wrap_params = {.type_params = "T"}; + static const CBMDefTypeFacts box_params = {.type_params = "K|T"}; + const CBMDefinition defs[] = { + {.qualified_name = "p.app.T", .label = "Class"}, + {.qualified_name = "p.app.wrap", .label = "Function", .type_facts = &wrap_params}, + {.qualified_name = "p.app.Box", .label = "Class", .type_facts = &box_params}, + {.qualified_name = "p.app.Box.get", .label = "Method"}, + }; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, + .file_defs = defs, + .file_def_count = 4, + .def_qn = "p.app.wrap", + .ret = "T"}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + in.def_qn = "p.app.Box.get"; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* `from p.a import Item` then `Item = TypeVar("Item")`: bound twice. */ + CBMPyNamespaceFact twice[] = { + {.kind = CBM_PY_NS_IMPORT_NAME, .local_name = "Item"}, + {.kind = CBM_PY_NS_SHADOW, .local_name = "Item", .reason = CBM_PY_NS_REASON_VALUE}}; + CBMPyNamespaceFacts facts = {.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = twice, + .count = 2, + .cap = 2}; + const char *keys[] = {"Item"}; + const char *vals[] = {"p.a.Item"}; + ts_attach_t tv = {.lang = CBM_LANG_PYTHON, + .ret = "Item", + .keys = keys, + .vals = vals, + .n = 1, + .facts = &facts}; + ASSERT_NULL(ts_unit_attach_with(&u, &tv)); + facts.count = 1; /* the import alone decides */ + ASSERT_STR_EQ(ts_unit_attach_with(&u, &tv), "Item=p.a.Item"); + ts_unit_end(&u); + PASS(); +} + +/* A module whose bindings cannot be listed gets no identity: a star import, + * a parse error, an incomplete record. */ +TEST(type_scope_python_unlisted_bindings_get_none) { + ts_unit_t u; + ts_unit_begin(&u); + CBMPyNamespaceFact star[] = {{.kind = CBM_PY_NS_IMPORT_STAR, .module_name = "p.c"}}; + CBMPyNamespaceFacts facts = {.version = CBM_PY_NAMESPACE_FACTS_VERSION, + .language = CBM_LANG_PYTHON, + .status = CBM_PY_NS_COMPLETE, + .items = star, + .count = 1, + .cap = 1}; + ts_attach_t in = {.lang = CBM_LANG_PYTHON, .ret = "Local", .facts = &facts}; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + CBMPyNamespaceFact parse[] = {{.kind = CBM_PY_NS_UNKNOWN, .reason = CBM_PY_NS_REASON_PARSE}}; + facts.items = parse; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + /* An effect (a call) does not hide bindings from the step. */ + parse[0].reason = CBM_PY_NS_REASON_EFFECT; + ASSERT_STR_EQ(ts_unit_attach_with(&u, &in), "Local=p.app.Local"); + facts.status = CBM_PY_NS_INCOMPLETE; + ASSERT_NULL(ts_unit_attach_with(&u, &in)); + ts_unit_end(&u); + PASS(); +} + +/* ── Growth: counted work at two sizes ─────────────────────────────── */ + +static bool ts_linear(uint64_t small, uint64_t large) { + /* Twice the input: close to twice the work (names grow by a digit). */ + return small > 0 && large * 10 >= small * 18 && large * 10 <= small * 23; +} + +/* `defs` defs in one file, each writing its own `a.T` (no memo hit), or + * one def writing `defs` distinct names. */ +static uint64_t ts_step_work(int defs, bool one_def) { + ts_unit_t u; + ts_unit_begin(&u); + char qn[64]; + for (int i = 0; i < defs; i++) { + snprintf(qn, sizeof(qn), "p.a.T%d", i); + cbm_registry_add(u.reg, qn + 4, qn, "Struct", false); + } + const char *keys[] = {"a"}; + const char *vals[] = {"p.a"}; + cbm_type_scope_t scope = { + .reg = u.reg, .module_qn = "p.app", .imp_keys = keys, .imp_vals = vals, .imp_count = 1}; + cbm_type_scope_file_t *f = cbm_type_scope_file_begin(cbm_type_scope_lang(CBM_LANG_GO), &scope); + char *all = (char *)calloc((size_t)defs, 16); + size_t at = 0; + uint64_t before = cbm_type_scope_test_work(); + for (int i = 0; i < defs; i++) { + char text[32]; + snprintf(text, sizeof(text), "*a.T%d", i); + if (one_def) { + at += (size_t)snprintf(all + at, 16, "%s%s", at ? "|" : "", text); + continue; + } + CBMLSPDef def = {.qualified_name = "p.app.f", .short_name = "f", .label = "Function"}; + def.return_types = text; + def.lang = CBM_LANG_GO; + cbm_type_scope_attach(f, &u.arena, &def); + } + if (one_def) { + CBMLSPDef def = {.qualified_name = "p.app.f", .short_name = "f", .label = "Function"}; + def.return_types = all; + def.lang = CBM_LANG_GO; + cbm_type_scope_attach(f, &u.arena, &def); + } + uint64_t work = cbm_type_scope_test_work() - before; + free(all); + cbm_type_scope_file_end(f); + ts_unit_end(&u); + return work; +} + +TEST(type_scope_step_work_grows_linearly) { + uint64_t defs_small = ts_step_work(1000, false); + uint64_t defs_large = ts_step_work(2000, false); + uint64_t names_small = ts_step_work(1000, true); + uint64_t names_large = ts_step_work(2000, true); + printf(" step work: defs 1000=%llu 2000=%llu, names in one def 1000=%llu 2000=%llu\n", + (unsigned long long)defs_small, (unsigned long long)defs_large, + (unsigned long long)names_small, (unsigned long long)names_large); + ASSERT_TRUE(ts_linear(defs_small, defs_large)); + ASSERT_TRUE(ts_linear(names_small, names_large)); + PASS(); +} + +/* The engines' lookup: one def with k identities, k lookups. */ +static uint64_t ts_lookup_work(int k) { + CBMArena a; + cbm_arena_init(&a); + size_t cap = (size_t)k * 40 + 1; + char *scope = (char *)calloc(cap, 1); + size_t at = 0; + for (int i = 0; i < k; i++) { + at += (size_t)snprintf(scope + at, cap - at, "%sa.T%d=p.a.T%d", at ? "|" : "", i, i); + } + uint64_t before = cbm_type_scope_index_test_work(); + const cbm_type_scope_index_t *ix = cbm_type_scope_index(&a, scope); + int found = 0; + for (int i = 0; i < k; i++) { + char name[32]; + int n = snprintf(name, sizeof(name), "a.T%d", i); + found += cbm_type_scope_find(ix, name, (size_t)n) != NULL; + } + uint64_t work = cbm_type_scope_index_test_work() - before; + free(scope); + cbm_arena_destroy(&a); + return found == k ? work : 0; +} + +TEST(type_scope_lookup_work_grows_linearly) { + uint64_t small = ts_lookup_work(1000); + uint64_t large = ts_lookup_work(2000); + printf(" lookup work: 1000 identities=%llu 2000=%llu\n", (unsigned long long)small, + (unsigned long long)large); + ASSERT_TRUE(ts_linear(small, large)); + PASS(); +} + +/* The per-file selection's worklist. A chain (module i's def names module + * i-1's type) and a fan (n modules' defs all name one module of n defs): the + * fan walked that module once per identity before. */ +static uint64_t ts_reach_work(int n, bool fan) { + CBMArena a; + cbm_arena_init(&a); + int count = fan ? 2 * n : n; + CBMLSPDef *defs = (CBMLSPDef *)calloc((size_t)count, sizeof(CBMLSPDef)); + for (int i = 0; i < count; i++) { + CBMLSPDef *d = &defs[i]; + bool hub = fan && i >= n; /* the fan's target module, n defs */ + int mod = hub ? n : i; + d->def_module_qn = cbm_arena_sprintf(&a, "p.m%d", mod); + d->qualified_name = cbm_arena_sprintf(&a, "p.m%d.T%d", mod, i); + d->short_name = "T"; + d->label = hub || !fan ? "Struct" : "Function"; + d->lang = CBM_LANG_GO; + if (!hub && (fan || i > 0)) { + int target = fan ? n : i - 1; + int target_def = fan ? n : i - 1; + d->type_scope = cbm_arena_sprintf(&a, "x.T=p.m%d.T%d", target, target_def); + } + } + CBMModuleDefIndex *idx = cbm_pxc_build_module_def_index(defs, count); + char own[32]; + snprintf(own, sizeof(own), "p.m%d", fan ? 0 : n - 1); + /* The fan's caller imports every holder module. */ + const char **imps = (const char **)calloc((size_t)n, sizeof(char *)); + for (int i = 0; i < n; i++) { + imps[i] = cbm_arena_sprintf(&a, "p.m%d", i); + } + uint64_t before = cbm_pxc_test_reach_work(); + int out = 0; + bool ok = false; + CBMLSPDef *sel = cbm_pxc_filter_defs_for_file(idx, defs, CBM_LANG_GO, NULL, own, + fan ? imps : NULL, fan ? n : 0, &out, &ok); + uint64_t work = cbm_pxc_test_reach_work() - before; + free(sel); + free(imps); + cbm_pxc_free_module_def_index(idx); + free(defs); + cbm_arena_destroy(&a); + return ok && out == count ? work : 0; +} + +TEST(type_scope_reach_work_grows_linearly) { + uint64_t chain_small = ts_reach_work(1000, false); + uint64_t chain_large = ts_reach_work(2000, false); + uint64_t fan_small = ts_reach_work(1000, true); + uint64_t fan_large = ts_reach_work(2000, true); + printf(" reach work: chain 1000=%llu 2000=%llu, fan 1000=%llu 2000=%llu\n", + (unsigned long long)chain_small, (unsigned long long)chain_large, + (unsigned long long)fan_small, (unsigned long long)fan_large); + ASSERT_TRUE(ts_linear(chain_small, chain_large)); + ASSERT_TRUE(ts_linear(fan_small, fan_large)); + PASS(); +} + +/* The planner's identity gate over n stored rows, each holding one identity, + * after a change of the type one of them names. */ +static uint64_t ts_decline_work(int n, const char **reason) { + cbm_lsp_surface_row_t *rows = (cbm_lsp_surface_row_t *)calloc((size_t)n, sizeof(*rows)); + for (int i = 0; i < n; i++) { + char *json = (char *)malloc(256); + snprintf(json, 256, + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.f%d.New\",\"sn\":\"New\",\"lb\":" + "\"Function\",\"lg\":%d,\"ty\":\"store.T%d=p.store.T%d\"}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, i, (int)CBM_LANG_GO, i, i); + rows[i].defs_json = json; + } + char before_row[256]; + snprintf(before_row, sizeof(before_row), + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\"," + "\"lg\":%d,\"al\":\"Impl\"}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO); + char after_row[256]; + snprintf(after_row, sizeof(after_row), + "{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\"," + "\"lg\":%d,\"al\":null}],\"reg\":[],\"py\":null}", + (int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO); + const char *old_rows[] = {before_row}; + const char *new_rows[] = {after_row}; + uint64_t work = 0; + *reason = cbm_lsp_surface_identity_decline(old_rows, new_rows, 1, rows, n, &work); + for (int i = 0; i < n; i++) { + free((void *)rows[i].defs_json); + } + free(rows); + return work; +} + +TEST(type_scope_identity_gate_work_grows_linearly) { + const char *small_reason = NULL; + const char *large_reason = NULL; + uint64_t small = ts_decline_work(1000, &small_reason); + uint64_t large = ts_decline_work(2000, &large_reason); + printf(" identity gate work: 1000 rows=%llu 2000=%llu (%s)\n", (unsigned long long)small, + (unsigned long long)large, large_reason ? large_reason : "kept"); + ASSERT_STR_EQ(small_reason, "identity_target_changed"); + ASSERT_STR_EQ(large_reason, "identity_target_changed"); + ASSERT_TRUE(ts_linear(small, large)); + PASS(); +} + +/* ── Pipeline fixtures ─────────────────────────────────────────────── */ + +/* CALLS edges from a node named `src` to the node whose QN ends in + * `tgt_qn_tail` whose properties contain `fragment` (NULL = any). */ +static int ts_calls_to(cbm_store_t *s, const char *project, const char *src, + const char *tgt_qn_tail, const char *fragment) { + cbm_edge_t *edges = NULL; + int count = 0; + if (cbm_store_find_edges_by_type(s, project, "CALLS", &edges, &count) != CBM_STORE_OK) { + return -1; + } + int matches = 0; + size_t tail = strlen(tgt_qn_tail); + for (int i = 0; i < count; i++) { + cbm_node_t a = {0}; + cbm_node_t b = {0}; + bool ok = cbm_store_find_node_by_id(s, edges[i].source_id, &a) == CBM_STORE_OK && + cbm_store_find_node_by_id(s, edges[i].target_id, &b) == CBM_STORE_OK; + size_t qn_len = ok && b.qualified_name ? strlen(b.qualified_name) : 0; + if (ok && a.name && strcmp(a.name, src) == 0 && qn_len >= tail && + strcmp(b.qualified_name + qn_len - tail, tgt_qn_tail) == 0 && + (qn_len == tail || b.qualified_name[qn_len - tail - 1] == '.') && + (!fragment || (edges[i].properties_json && strstr(edges[i].properties_json, fragment)))) { + matches++; + } + cbm_node_free_fields(&a); + cbm_node_free_fields(&b); + } + if (edges) { + cbm_store_free_edges(edges, count); + } + return matches; +} + +#define TS_LSP "\"strategy\":\"lsp_" + +typedef struct { + const char *rel; + const char *content; +} ts_file_t; + +static void ts_write(const char *tmp, const ts_file_t *files) { + for (int i = 0; files && files[i].rel; i++) { + th_write_file(TH_PATH(tmp, files[i].rel), files[i].content); + } +} + +/* Filler files that put a fixture above the parallel threshold. */ +static void ts_pad(const char *tmp, CBMLanguage lang, int count) { + for (int i = 0; i < count; i++) { + char rel[64]; + char body[128]; + if (lang == CBM_LANG_GO) { + snprintf(rel, sizeof(rel), "fill/f%d.go", i); + snprintf(body, sizeof(body), "package fill\n\nfunc F%d() int { return %d }\n", i, i); + } else { + snprintf(rel, sizeof(rel), "fill/f%d.py", i); + snprintf(body, sizeof(body), "def f%d():\n return %d\n", i, i); + } + th_write_file(TH_PATH(tmp, rel), body); + } +} + +enum { TS_PAD_FILES = 52 }; /* above the parallel threshold (50 files) */ + +/* Full index of `tmp` with CBM_WORKERS=workers into tmp/. */ +static cbm_store_t *ts_index_workers(const char *tmp, const char *db_name, int workers, + char *project, size_t project_size) { + char *saved = NULL; + const char *old = getenv("CBM_WORKERS"); + saved = old ? strdup(old) : NULL; + char w[16]; + snprintf(w, sizeof(w), "%d", workers); + cbm_setenv("CBM_WORKERS", w, 1); + char db_path[512]; + snprintf(db_path, sizeof(db_path), "%s/%s", tmp, db_name); + cbm_pipeline_t *p = cbm_pipeline_new(tmp, db_path, CBM_MODE_FULL); + int rc = p ? cbm_pipeline_run(p) : -1; + if (p) { + snprintf(project, project_size, "%s", cbm_pipeline_project_name(p)); + } + cbm_pipeline_free(p); + if (saved) { + cbm_setenv("CBM_WORKERS", saved, 1); + free(saved); + } else { + cbm_unsetenv("CBM_WORKERS"); + } + return rc == 0 ? cbm_store_open_path(db_path) : NULL; +} + +/* One fixture indexed with one worker and with four (both above the parallel + * threshold); `check` returns 0 when the graph is right. */ +typedef int (*ts_check_fn)(cbm_store_t *s, const char *project, const char *label); + +static int ts_twins(const char *name, const ts_file_t *files, CBMLanguage pad_lang, + ts_check_fn check) { + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_%s_XXXXXX", name); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + ts_write(tmp, files); + ts_pad(tmp, pad_lang, TS_PAD_FILES); + int bad = 0; + for (int run = 0; run < 2 && !bad; run++) { + int workers = run == 0 ? 1 : 4; + char project[256] = {0}; + cbm_store_t *s = ts_index_workers(tmp, run == 0 ? "seq.db" : "par.db", workers, project, + sizeof(project)); + if (!s) { + bad = 1; + break; + } + bad = check(s, project, run == 0 ? "1 worker" : "4 workers"); + cbm_store_close(s); + } + th_rmtree(tmp); + ASSERT_EQ(bad, 0); + PASS(); +} + +/* Go: app calls fixture.New() (returns *store.Store) and reads + * fixture.NewHolder().S (a field of type *store.Store); fixture.go imports + * store. decoy/ declares a same-named Store with the same method. */ +static const ts_file_t go_scope_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"decoy/store.go", "package decoy\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store { return &store.Store{} }\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n\n" + "func Field() string {\n\th := fixture.NewHolder()\n\treturn h.S.Get(\"y\")\n}\n"}, + {NULL, NULL}}; + +static int go_scope_check(cbm_store_t *s, const char *project, const char *label) { + int ret_hit = ts_calls_to(s, project, "Run", "store.Store.Get", TS_LSP); + int ret_decoy = ts_calls_to(s, project, "Run", "decoy.Store.Get", NULL); + int field_hit = ts_calls_to(s, project, "Field", "store.Store.Get", TS_LSP); + int field_decoy = ts_calls_to(s, project, "Field", "decoy.Store.Get", NULL); + printf(" go (%s): return=%d decoy=%d field=%d decoy=%d\n", label, ret_hit, ret_decoy, + field_hit, field_decoy); + return !(ret_hit == 1 && ret_decoy == 0 && field_hit == 1 && field_decoy == 0); +} + +TEST(type_scope_go_return_and_field_types) { + return ts_twins("go", go_scope_files, CBM_LANG_GO, go_scope_check); +} + +/* Go: a type parameter named like an import (`import T "…/tpkg"`, then + * `func Wrap[T any](x T) T`) is the parameter inside Wrap, not tpkg's T. */ +static const ts_file_t go_tparam_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"tpkg/t.go", "package tpkg\n\ntype T struct{ n int }\n\nfunc (t T) M() string { return \"t\" }\n"}, + {"other/x.go", "package other\n\ntype X struct{ n int }\n\nfunc (x X) M() string { return \"x\" }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport T \"example.com/demo/tpkg\"\n\n" + "var Keep T.T\n\nfunc Wrap[T any](x T) T { return x }\n"}, + {"app/app.go", "package app\n\nimport (\n\t\"example.com/demo/fixture\"\n" + "\t\"example.com/demo/other\"\n)\n\n" + "func Run() string { return fixture.Wrap(other.X{}).M() }\n"}, + {NULL, NULL}}; + +static int go_tparam_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "Run", "tpkg.T.M", NULL); + printf(" go type parameter (%s): edge to tpkg.T.M=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_go_type_parameter_is_no_import) { + return ts_twins("gotp", go_tparam_files, CBM_LANG_GO, go_tparam_check); +} + +/* Python: app.py calls fixture.make() (-> Store, imported by fixture.py from + * pkg.store) and fixture.local() (-> Local, fixture.py's own class). decoy.py + * declares a same-named Store with the same method. */ +static const ts_file_t py_scope_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/store.py", "class Store:\n def get(self, k):\n return k\n"}, + {"pkg/decoy.py", "class Store:\n def get(self, k):\n return k\n"}, + {"pkg/fixture.py", "from pkg.store import Store\n\n\n" + "class Local:\n def ping(self):\n return 1\n\n\n" + "def make() -> Store:\n return Store()\n\n\n" + "def local() -> Local:\n return Local()\n"}, + {"pkg/app.py", "from pkg.fixture import make, local\n\n\n" + "def run():\n s = make()\n return s.get(\"x\")\n\n\n" + "def own():\n v = local()\n return v.ping()\n"}, + {NULL, NULL}}; + +static int py_scope_check(cbm_store_t *s, const char *project, const char *label) { + int ret_hit = ts_calls_to(s, project, "run", "pkg.store.Store.get", TS_LSP); + int ret_decoy = ts_calls_to(s, project, "run", "pkg.decoy.Store.get", NULL); + int own_hit = ts_calls_to(s, project, "own", "pkg.fixture.Local.ping", TS_LSP); + printf(" python (%s): return=%d decoy=%d own=%d\n", label, ret_hit, ret_decoy, own_hit); + return !(ret_hit == 1 && ret_decoy == 0 && own_hit == 1); +} + +TEST(type_scope_python_return_types) { + return ts_twins("py", py_scope_files, CBM_LANG_PYTHON, py_scope_check); +} + +/* Finding 3: `def cfg(self) -> Config` in a class with a nested `Config` + * names Model.Config, never the module-level Config. */ +static const ts_file_t py_nested_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/mod.py", "class Config:\n def load(self):\n return 1\n\n\n" + "class Model:\n" + " class Config:\n def load(self):\n return 2\n\n" + " def cfg(self) -> Config:\n return Model.Config()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run():\n m = Model()\n return m.cfg().load()\n"}, + {NULL, NULL}}; + +static int py_nested_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" python nested class (%s): edge to module-level Config.load=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_python_nested_class_is_not_the_module_class) { + return ts_twins("pynest", py_nested_files, CBM_LANG_PYTHON, py_nested_check); +} + +/* Round 3, N2 (the review's py-classattr): a class body that binds a name + * without defining it -- `Config = OtherConfig`, an import, an annotated + * assignment, a for, with or except target, a walrus -- makes that name the + * class attribute in its methods' annotations (Python: get_type_hints gives + * OtherConfig, Other, None, 1...). None of them may become the module-level + * class of that name; a name the body does not bind (Keep) still does. */ +static const ts_file_t py_classbind_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/other.py", "class OtherConfig:\n def load(self):\n return 'other'\n\n\n" + "class Other:\n def load(self):\n return 'other'\n"}, + {"pkg/mod.py", + "import contextlib\nfrom pkg.other import Other, OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class A:\n def load(self):\n return 'A'\n\n\n" + "class B:\n def load(self):\n return 'B'\n\n\n" + "class C:\n def load(self):\n return 'C'\n\n\n" + "class D:\n def load(self):\n return 'D'\n\n\n" + "class F:\n def load(self):\n return 'F'\n\n\n" + "class Keep:\n def load(self):\n return 'keep'\n\n\n" + "class Model:\n" + " Config = OtherConfig\n" + " Keep: type\n" /* an annotation alone binds nothing: Keep stays the module's */ + " from pkg.other import Other as A\n" + " B: type = Other\n" + " for C in (1,):\n pass\n" + " with contextlib.nullcontext() as D:\n pass\n" + " (F := 1)\n\n" + " def cfg(self) -> Config:\n return OtherConfig()\n\n" + " def ma(self) -> A:\n return Other()\n\n" + " def mb(self) -> B:\n return Other()\n\n" + " def mc(self) -> C:\n return None\n\n" + " def md(self) -> D:\n return None\n\n" + " def mf(self) -> F:\n return None\n\n" + " def keep(self) -> Keep:\n return Keep()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run():\n return Model().cfg().load()\n\n\n" + "def run_a():\n return Model().ma().load()\n\n\n" + "def run_b():\n return Model().mb().load()\n\n\n" + "def run_c():\n return Model().mc().load()\n\n\n" + "def run_d():\n return Model().md().load()\n\n\n" + "def run_f():\n return Model().mf().load()\n\n\n" + "def run_keep():\n return Model().keep().load()\n"}, + {NULL, NULL}}; + +static int py_classbind_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL) + + ts_calls_to(s, project, "run_a", "pkg.mod.A.load", NULL) + + ts_calls_to(s, project, "run_b", "pkg.mod.B.load", NULL) + + ts_calls_to(s, project, "run_c", "pkg.mod.C.load", NULL) + + ts_calls_to(s, project, "run_d", "pkg.mod.D.load", NULL) + + ts_calls_to(s, project, "run_f", "pkg.mod.F.load", NULL); + int keep = ts_calls_to(s, project, "run_keep", "pkg.mod.Keep.load", NULL); + printf(" python class-body bindings (%s): module-class edges=%d, keep=%d\n", label, wrong, + keep); + return !(wrong == 0 && keep == 1); +} + +TEST(type_scope_python_class_body_bindings_shadow_the_module) { + return ts_twins("pybind", py_classbind_files, CBM_LANG_PYTHON, py_classbind_check); +} + +/* Round 3 (a class and a module of one QN): pkg/a/__init__.py defines class + * Thing beside the module pkg/a/Thing.py; both share the QN pkg.a.Thing and + * their members `run` share pkg.a.Thing.run, so no member edge through an + * identity Thing=pkg.a.Thing is that class's (the graph keeps the module's + * nodes). Python: `from pkg.a import Thing` is the class while nothing imports + * the submodule, and the submodule once something does. The partner: a class + * of the same __init__ with no module of its QN (Other) is reached through + * the same kind of identity. */ +static const ts_file_t py_classmod_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a/__init__.py", "class Thing:\n def run(self):\n return 'class'\n\n\n" + "class Other:\n def run(self):\n return 'other'\n"}, + {"pkg/a/Thing.py", "def run():\n return 'module'\n"}, + {"pkg/b.py", "from pkg.a import Other, Thing\n\n\ndef make() -> Thing:\n return Thing()\n\n\n" + "def make_other() -> Other:\n return Other()\n"}, + {"pkg/c.py", "from pkg.b import make, make_other\n\n\ndef go():\n return make().run()\n\n\n" + "def go_other():\n return make_other().run()\n"}, + {NULL, NULL}}; + +static int py_classmod_check(cbm_store_t *s, const char *project, const char *label) { + int member = ts_calls_to(s, project, "go", "pkg.a.Thing.run", NULL); + int other = ts_calls_to(s, project, "go_other", "pkg.a.Other.run", NULL); + printf(" python class and module of one QN (%s): go -> Thing.run=%d, go_other -> Other.run=%d\n", + label, member, other); + return !(member == 0 && other == 1); +} + +TEST(type_scope_python_class_and_module_of_one_qn) { + return ts_twins("pyclassmod", py_classmod_files, CBM_LANG_PYTHON, py_classmod_check); +} + +/* `global R` in a class body (run at import) or a function body that binds R + * rebinds the module's R, so `def make_r() -> R` after it names whatever that + * body bound (python3: pkg.b.R for the class body; for the function, whether + * it ran). No identity is taken from the import. A module that only imports R + * keeps it (run_a), and so does one whose function declares `global R` and + * only reads it (run_p). */ +static const ts_file_t py_global_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a.py", "class R:\n def save(self):\n return 'a'\n"}, + {"pkg/b.py", "class R:\n def save(self):\n return 'b'\n"}, + {"pkg/mod.py", "from pkg.a import R\n\n\nclass Rebind:\n global R\n from pkg.b import R\n\n\n" + "def make_r() -> R:\n return R()\n"}, + {"pkg/mod2.py", "from pkg.a import R\n\n\ndef setup():\n global R\n from pkg.b import R\n\n\n" + "def make_s() -> R:\n return R()\n"}, + {"pkg/mod3.py", "from pkg.a import R\n\n\ndef make_a() -> R:\n return R()\n"}, + {"pkg/mod4.py", "from pkg.a import R\n\n\ndef peek():\n global R\n return R.__name__\n\n\n" + "def make_p() -> R:\n return R()\n"}, + {"pkg/use.py", "from pkg.mod import make_r\nfrom pkg.mod2 import make_s\nfrom pkg.mod3 import make_a\n" + "from pkg.mod4 import make_p\n\n\n" + "def run_r():\n return make_r().save()\n\n\n" + "def run_s():\n return make_s().save()\n\n\n" + "def run_a():\n return make_a().save()\n\n\n" + "def run_p():\n return make_p().save()\n"}, + {NULL, NULL}}; + +static int py_global_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run_r", "pkg.a.R.save", NULL) + + ts_calls_to(s, project, "run_s", "pkg.a.R.save", NULL); + int kept = ts_calls_to(s, project, "run_a", "pkg.a.R.save", NULL); + int read = ts_calls_to(s, project, "run_p", "pkg.a.R.save", NULL); + printf(" python global rebinding (%s): rebound edges=%d, plain import=%d, global read=%d\n", + label, wrong, kept, read); + return !(wrong == 0 && kept == 1 && read == 1); +} + +TEST(type_scope_python_global_rebinding_takes_no_identity) { + return ts_twins("pyglobal", py_global_files, CBM_LANG_PYTHON, py_global_check); +} + +/* `except ValueError as E` unbinds E when the clause + * ends, and `D = Other; del D` leaves D unbound: methods defined after them + * name the module's E and D (python3 agrees). A `del` after a method that saw + * the binding (`D2 = Other`, `def md2(self) -> D2`, `del D2`) keeps the + * abstention: evaluated at definition time (Python before 3.14) the annotation + * is Other, evaluated lazily (3.14 on) the module's D2 -- no one answer. */ +static const ts_file_t py_unbind_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/mod.py", "class Other:\n def load(self):\n return 'other'\n\n\n" + "class D:\n def load(self):\n return 'D'\n\n\n" + "class E:\n def load(self):\n return 'E'\n\n\n" + "class D2:\n def load(self):\n return 'D2'\n\n\n" + "class Model:\n" + " try:\n raise ValueError()\n except ValueError as E:\n pass\n" + " D = Other\n del D\n D2 = Other\n\n" + " def md2(self) -> D2:\n return D2()\n\n" + " del D2\n\n" + " def me(self) -> E:\n return E()\n\n" + " def md(self) -> D:\n return D()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\n" + "def run_e():\n return Model().me().load()\n\n\n" + "def run_d():\n return Model().md().load()\n\n\n" + "def run_d2():\n return Model().md2().load()\n"}, + {NULL, NULL}}; + +static int py_unbind_check(cbm_store_t *s, const char *project, const char *label) { + int e = ts_calls_to(s, project, "run_e", "pkg.mod.E.load", NULL); + int d = ts_calls_to(s, project, "run_d", "pkg.mod.D.load", NULL); + int d2 = ts_calls_to(s, project, "run_d2", "pkg.mod.D2.load", NULL) + + ts_calls_to(s, project, "run_d2", "pkg.mod.Other.load", NULL); + printf(" python class-body unbinding (%s): E=%d D=%d, D2 (bound at definition)=%d\n", label, e, + d, d2); + return !(e == 1 && d == 1 && d2 == 0); +} + +TEST(type_scope_python_unbound_class_names_are_the_module_names) { + return ts_twins("pyunbind", py_unbind_files, CBM_LANG_PYTHON, py_unbind_check); +} + +/* A method declared with @overload (the shape of scrapy's Response.replace). + * Callers see the overloads, which pick the result from the arguments + * (`replace(cls=Text)` is a Text, python3 runs Text.css); the + * implementation's `-> Response` is no call's type, so no identity is taken + * from any of its signatures. A plain method keeps its own (run_plain), and so + * does an overloaded one whose definitions all return Response (run_opts, the + * shape of sqlalchemy's Connection.execution_options). */ +static const ts_file_t py_overload_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/resp.py", "from __future__ import annotations\n\nfrom typing import Self, TypeVar, overload\n\n" + "T = TypeVar(\"T\", bound=\"Response\")\n\n\n" + "class Response:\n def css(self):\n return 'base'\n\n" + " @overload\n def replace(self, cls: type[T]) -> T: ...\n\n" + " @overload\n def replace(self, cls: None = None) -> Self: ...\n\n" + " def replace(self, cls=None) -> Response:\n" + " return (cls or type(self))()\n\n" + " @overload\n def opts(self, *, a: int) -> Response: ...\n\n" + " @overload\n def opts(self, **kw: int) -> Response: ...\n\n" + " def opts(self, **kw) -> Response:\n return Response()\n\n" + " def plain(self) -> Response:\n return Response()\n\n\n" + "class Text(Response):\n def css(self):\n return 'text'\n"}, + {"pkg/make.py", "from pkg.resp import Response\n\n\ndef make() -> Response:\n return Response()\n"}, + {"pkg/use.py", "from pkg.make import make\nfrom pkg.resp import Text\n\n\n" + "def run():\n return make().replace(cls=Text).css()\n\n\n" + "def run_plain():\n return make().plain().css()\n\n\n" + "def run_opts():\n return make().opts(a=1).css()\n"}, + {NULL, NULL}}; + +static int py_overload_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run", "pkg.resp.Response.css", NULL); + int plain = ts_calls_to(s, project, "run_plain", "pkg.resp.Response.css", NULL); + int agreed = ts_calls_to(s, project, "run_opts", "pkg.resp.Response.css", NULL); + printf(" python overloaded method (%s): run -> Response.css=%d, run_plain=%d, run_opts=%d\n", + label, wrong, plain, agreed); + return !(wrong == 0 && plain == 1 && agreed == 1); +} + +TEST(type_scope_python_overloaded_method_takes_no_identity) { + return ts_twins("pyoverload", py_overload_files, CBM_LANG_PYTHON, py_overload_check); +} + +/* The same through an import under another name (`from typing import + * overload as ovl`, `@ovl`): the name is read through the module's imports + * (python3: `replace(cls=AliasText)` runs AliasText.css). A method of the + * same class under a plain decorator keeps its identity (run_kept, python3 + * Alias.css). */ +static const ts_file_t py_overload_alias_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/resp.py", "from __future__ import annotations\n\nfrom typing import Self, TypeVar\n" + "from typing import overload as ovl\n\n" + "T = TypeVar(\"T\", bound=\"Alias\")\n\n\n" + "def keep(fn):\n return fn\n\n\n" + "class Alias:\n def css(self):\n return 'alias'\n\n" + " @ovl\n def replace(self, cls: type[T]) -> T: ...\n\n" + " @ovl\n def replace(self, cls: None = None) -> Self: ...\n\n" + " def replace(self, cls=None) -> Alias:\n" + " return (cls or type(self))()\n\n" + " @keep\n def kept(self) -> Alias:\n return Alias()\n\n\n" + "class AliasText(Alias):\n def css(self):\n return 'text'\n"}, + {"pkg/make.py", "from pkg.resp import Alias\n\n\ndef make() -> Alias:\n return Alias()\n"}, + {"pkg/use.py", "from pkg.make import make\nfrom pkg.resp import AliasText\n\n\n" + "def run_alias():\n return make().replace(cls=AliasText).css()\n\n\n" + "def run_kept():\n return make().kept().css()\n"}, + {NULL, NULL}}; + +static int py_overload_alias_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "run_alias", "pkg.resp.Alias.css", NULL); + int kept = ts_calls_to(s, project, "run_kept", "pkg.resp.Alias.css", NULL); + printf(" python overload under another name (%s): run_alias -> Alias.css=%d, run_kept=%d\n", + label, wrong, kept); + return !(wrong == 0 && kept == 1); +} + +TEST(type_scope_python_overload_imported_under_another_name) { + return ts_twins("pyovlalias", py_overload_alias_files, CBM_LANG_PYTHON, + py_overload_alias_check); +} + +/* A struct's embedded-type text is built once, with one buffer: the + * extractor's work for n embedded types is linear in n. */ +static uint64_t ts_go_embedded_work(int n) { + size_t cap = (size_t)n * 24 + 256; + char *src = (char *)calloc(cap, 1); + if (!src) { + return 0; + } + size_t at = (size_t)snprintf(src, cap, + "package p\n\nimport \"example.com/demo/parts\"\n\ntype S struct {\n"); + for (int i = 0; i < n; i++) { + at += (size_t)snprintf(src + at, cap - at, "\tparts.E%d\n", i); + } + at += (size_t)snprintf(src + at, cap - at, "}\n"); + uint64_t before = cbm_extract_test_go_embedded_work(); + CBMFileResult *r = + cbm_extract_file(src, (int)at, CBM_LANG_GO, "proj", "p/s.go", 0, NULL, NULL); + uint64_t work = cbm_extract_test_go_embedded_work() - before; + /* the whole list is there: n spellings, the last one included */ + char last[32]; + snprintf(last, sizeof(last), "parts.E%d", n - 1); + bool whole = false; + for (int i = 0; r && i < r->defs.count; i++) { + const CBMDefTypeFacts *f = r->defs.items[i].type_facts; + whole = whole || (f && f->go_embedded && strstr(f->go_embedded, last)); + } + cbm_free_result(r); + free(src); + return whole ? work : 0; +} + +TEST(type_scope_go_embedded_text_work_grows_linearly) { + uint64_t small = ts_go_embedded_work(2000); + uint64_t mid = ts_go_embedded_work(4000); + uint64_t large = ts_go_embedded_work(8000); + printf(" go embedded text work: 2000 embeds=%llu 4000=%llu 8000=%llu\n", + (unsigned long long)small, (unsigned long long)mid, (unsigned long long)large); + ASSERT_TRUE(ts_linear(small, mid)); + ASSERT_TRUE(ts_linear(mid, large)); + PASS(); +} + +/* Finding 6: `-> Self` chains across files keep main's edges; `Self` comes + * from typing, which the project does not define. A decoy declares the same + * method names. */ +static const ts_file_t py_self_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/builder.py", "from typing import Self\n\n\n" + "class Builder:\n" + " def a(self) -> Self:\n return self\n\n" + " def b(self) -> Self:\n return self\n\n" + " def done(self) -> int:\n return 1\n"}, + {"pkg/app.py", "from pkg.builder import Builder\n\n\n" + "def run():\n x = Builder()\n return x.a().b().done()\n"}, + {"pkg/decoy.py", "class Other:\n" + " def a(self):\n return self\n\n" + " def b(self):\n return self\n\n" + " def done(self):\n return 2\n"}, + {NULL, NULL}}; + +static int py_self_check(cbm_store_t *s, const char *project, const char *label) { + int a = ts_calls_to(s, project, "run", "pkg.builder.Builder.a", NULL); + int b = ts_calls_to(s, project, "run", "pkg.builder.Builder.b", NULL); + int done = ts_calls_to(s, project, "run", "pkg.builder.Builder.done", NULL); + int decoy = ts_calls_to(s, project, "run", "pkg.decoy.Other.done", NULL) + + ts_calls_to(s, project, "run", "pkg.decoy.Other.b", NULL); + printf(" python Self chain (%s): a=%d b=%d done=%d decoy=%d\n", label, a, b, done, decoy); + return !(a == 1 && b == 1 && done == 1 && decoy == 0); +} + +TEST(type_scope_python_self_chain_keeps_its_edges) { + return ts_twins("pyself", py_self_files, CBM_LANG_PYTHON, py_self_check); +} + +/* Type parameters: `def wrap[Item](x: Item) -> Item` in a file that also + * imports a class Item; the caller passes an Other. */ +static const ts_file_t py_tparam_files[] = { + {"pkg/__init__.py", ""}, + {"pkg/item.py", "class Item:\n def save(self):\n return 1\n"}, + {"pkg/other.py", "class Other:\n def save(self):\n return 2\n"}, + {"pkg/box.py", "from pkg.item import Item\n\n\n" + "def touch(i: Item) -> None:\n i.save()\n\n\n" + "def wrap[Item](x: Item) -> Item:\n return x\n"}, + {"pkg/app.py", "from pkg.box import wrap\nfrom pkg.other import Other\n\n\n" + "def go():\n o = wrap(Other())\n return o.save()\n"}, + {NULL, NULL}}; + +static int py_tparam_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "go", "pkg.item.Item.save", NULL); + printf(" python type parameter (%s): edge to pkg.item.Item.save=%d\n", label, wrong); + return wrong != 0; +} + +TEST(type_scope_python_type_parameter_is_no_import) { + return ts_twins("pytp", py_tparam_files, CBM_LANG_PYTHON, py_tparam_check); +} + +/* ── Go registrars: fields ────────────────────────────────────────── */ + +/* Resolve `source` (module test.main or `module_qn`) against `defs` with the + * per-file registrar or the shared one; the number of resolved calls to + * `callee`. */ +static int ts_go_registry_hits(bool shared, const char *source, const char *module_qn, + CBMLSPDef *defs, int def_count, const char **imp_names, + const char **imp_qns, int imp_count, const char *callee) { + CBMArena arena; + cbm_arena_init(&arena); + CBMResolvedCallArray out = {0}; + if (shared) { + CBMTypeRegistry *reg = cbm_go_build_cross_registry(&arena, defs, def_count); + if (reg) { + cbm_run_go_lsp_cross_with_registry(&arena, source, (int)strlen(source), module_qn, + NULL, reg, imp_names, imp_qns, imp_count, NULL, + &out); + } + } else { + cbm_run_go_lsp_cross(&arena, source, (int)strlen(source), module_qn, NULL, defs, + def_count, imp_names, imp_qns, imp_count, NULL, &out); + } + int hits = 0; + for (int i = 0; i < out.count; i++) { + if (out.items[i].callee_qn && strcmp(out.items[i].callee_qn, callee) == 0) { + hits++; + } + } + cbm_arena_destroy(&arena); + return hits; +} + +/* A method of Configuration registered before the struct makes a receiver + * placeholder first; after finalize a type lookup answers with the last + * entry of that name, so the struct's fields must sit on its own entry. They + * sat on the placeholder, and every field chain through such a struct died + * (helm's `cfg.Releases.Get`). The field type also comes through an identity + * (`store.Storage`). */ +static int go_registry_field_case(bool shared) { + const char *source = "package main\n\n" + "import \"p/cfg\"\n\n" + "func run(c *cfg.Configuration) string {\n" + "\treturn c.Releases.Get(\"x\")\n}\n"; + CBMLSPDef defs[] = { + {.qualified_name = "test.main.run", + .short_name = "run", + .label = "Function", + .def_module_qn = "test.main", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.cfg.Configuration.hook", + .short_name = "hook", + .label = "Method", + .def_module_qn = "p.cfg", + .receiver_type = "p.cfg.Configuration", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.cfg.Configuration", + .short_name = "Configuration", + .label = "Struct", + .def_module_qn = "p.cfg", + .field_defs = "Releases:*store.Storage", + .type_scope = "store.Storage=p.store.Storage", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.store.Storage", + .short_name = "Storage", + .label = "Struct", + .def_module_qn = "p.store", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.store.Storage.Get", + .short_name = "Get", + .label = "Method", + .def_module_qn = "p.store", + .receiver_type = "p.store.Storage", + .return_types = "string", + .lang = CBM_LANG_GO}, + }; + const char *imp_names[] = {"cfg"}; + const char *imp_qns[] = {"p.cfg"}; + int hits = ts_go_registry_hits(shared, source, "test.main", defs, 5, imp_names, imp_qns, 1, + "p.store.Storage.Get"); + printf(" go registry (%s): run -> Storage.Get resolved %d\n", shared ? "shared" : "per-file", + hits); + ASSERT_EQ(hits, 1); + PASS(); +} + +TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file) { + return go_registry_field_case(false); +} + +TEST(type_scope_go_fields_survive_an_earlier_receiver_shared) { + return go_registry_field_case(true); +} + +/* `package svc` and `package svc_test` in one directory both declare a + * struct S (one QN): which S a lookup answers with depends on file order, so + * neither's fields are registered, and the answer is the same in both + * orders. */ +static int go_shared_qn_case(bool shared) { + const char *source = "package svc_test\n\n" + "func run(s *S) string { return s.X.Get() }\n"; + CBMLSPDef real_s = {.qualified_name = "p.svc.S", + .short_name = "S", + .label = "Struct", + .def_module_qn = "p.svc", + .field_defs = "X:*real.Store", + .type_scope = "real.Store=p.real.Store", + .lang = CBM_LANG_GO}; + CBMLSPDef fake_s = real_s; + fake_s.field_defs = "X:*fake.Store"; + fake_s.type_scope = "fake.Store=p.fake.Store"; + CBMLSPDef rest[] = { + {.qualified_name = "p.real.Store", .short_name = "Store", .label = "Struct", + .def_module_qn = "p.real", .lang = CBM_LANG_GO}, + {.qualified_name = "p.real.Store.Get", .short_name = "Get", .label = "Method", + .def_module_qn = "p.real", .receiver_type = "p.real.Store", .return_types = "string", + .lang = CBM_LANG_GO}, + {.qualified_name = "p.fake.Store", .short_name = "Store", .label = "Struct", + .def_module_qn = "p.fake", .lang = CBM_LANG_GO}, + {.qualified_name = "p.fake.Store.Get", .short_name = "Get", .label = "Method", + .def_module_qn = "p.fake", .receiver_type = "p.fake.Store", .return_types = "string", + .lang = CBM_LANG_GO}, + }; + int hits[2][2]; + for (int order = 0; order < 2; order++) { + CBMLSPDef defs[6]; + defs[0] = order ? fake_s : real_s; + defs[1] = order ? real_s : fake_s; + memcpy(defs + 2, rest, sizeof(rest)); + hits[order][0] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.real.Store.Get"); + hits[order][1] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.fake.Store.Get"); + } + printf(" go shared QN (%s): order A real=%d fake=%d, order B real=%d fake=%d\n", + shared ? "shared" : "per-file", hits[0][0], hits[0][1], hits[1][0], hits[1][1]); + ASSERT_EQ(hits[0][0] + hits[0][1] + hits[1][0] + hits[1][1], 0); + /* Build variants of one struct (prometheus' labels.Builder): the same + * fields with the same identities give one answer in every order, so + * the fields stay. */ + CBMLSPDef variants[6] = {real_s, real_s}; + memcpy(variants + 2, rest, sizeof(rest)); + int same = ts_go_registry_hits(shared, source, "p.svc", variants, 6, NULL, NULL, 0, + "p.real.Store.Get"); + /* Variants that differ elsewhere (prometheus' labels.Builder: one adds + * fields) keep the field they declare alike, in both orders. */ + CBMLSPDef wider = real_s; + wider.field_defs = "X:*real.Store|Extra:int"; + int partial[2]; + for (int order = 0; order < 2; order++) { + CBMLSPDef defs[6] = {order ? wider : real_s, order ? real_s : wider}; + memcpy(defs + 2, rest, sizeof(rest)); + partial[order] = ts_go_registry_hits(shared, source, "p.svc", defs, 6, NULL, NULL, 0, + "p.real.Store.Get"); + } + /* The same text naming another type in each (`store` is real in one, + * fake in the other): no agreement. */ + CBMLSPDef via_real = real_s; + via_real.field_defs = "X:*store.Store"; + via_real.type_scope = "store.Store=p.real.Store"; + CBMLSPDef via_fake = via_real; + via_fake.type_scope = "store.Store=p.fake.Store"; + CBMLSPDef split[6] = {via_real, via_fake}; + memcpy(split + 2, rest, sizeof(rest)); + int split_hits = ts_go_registry_hits(shared, source, "p.svc", split, 6, NULL, NULL, 0, + "p.real.Store.Get") + + ts_go_registry_hits(shared, source, "p.svc", split, 6, NULL, NULL, 0, + "p.fake.Store.Get"); + printf(" go shared QN (%s): same fields real=%d, agreed field %d/%d, same text other " + "identity %d\n", + shared ? "shared" : "per-file", same, partial[0], partial[1], split_hits); + ASSERT_EQ(same, 1); + ASSERT_EQ(partial[0], 1); + ASSERT_EQ(partial[1], 1); + ASSERT_EQ(split_hits, 0); + PASS(); +} + +TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file) { + return go_shared_qn_case(false); +} + +TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared) { + return go_shared_qn_case(true); +} + +/* ── Go: closure parameters ───────────────────────────────────────── */ + +/* A closure parameter is typed wherever the literal stands, here as a + * composite literal's field value (a test table), not only where the literal + * is evaluated. decoy/ declares the same Store with the same method. */ +static const ts_file_t go_closure_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"decoy/store.go", "package decoy\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/store\"\n\n" + "type stub struct {\n\trun func(s *store.Store) string\n}\n\n" + "func Closure() string {\n" + "\ttt := []stub{{run: func(s *store.Store) string { return s.Get(\"x\") }}}\n" + "\treturn tt[0].run(nil)\n}\n"}, + {NULL, NULL}}; + +static int go_closure_check(cbm_store_t *s, const char *project, const char *label) { + int closure = ts_calls_to(s, project, "Closure", "store.Store.Get", TS_LSP); + int decoy = ts_calls_to(s, project, "Closure", "decoy.Store.Get", NULL); + printf(" go closure (%s): closure=%d decoy=%d\n", label, closure, decoy); + return !(closure == 1 && decoy == 0); +} + +TEST(type_scope_go_closure_parameters_in_composite_literals) { + return ts_twins("goclos", go_closure_files, CBM_LANG_GO, go_closure_check); +} + +/* ── Go: package-level values ─────────────────────────────────────── */ + +/* How many Variable nodes named `name` carry a `return_type` property: a + * value's type crosses files through the LSP defs only, never as a graph + * property (Variable nodes carry none on any other language). */ +static int ts_variable_return_type_props(cbm_store_t *s, const char *project, const char *name) { + cbm_node_t *nodes = NULL; + int count = 0; + if (cbm_store_find_nodes_by_name(s, project, name, &nodes, &count) != CBM_STORE_OK) { + return -1; + } + int hits = 0; + for (int i = 0; i < count; i++) { + if (nodes[i].label && strcmp(nodes[i].label, "Variable") == 0 && nodes[i].properties_json && + strstr(nodes[i].properties_json, "\"return_type\"")) { + hits++; + } + } + cbm_store_free_nodes(nodes, count); + return hits; +} + +/* Package-level values of another package typed by their declaration or + * initializer (`&T{}`, `T{}`, `new(T)`, a typed const and the const block's + * implicit repetition). decoy/ declares the same names. */ +#define TS_GO_VALUES_STORE \ + "type Store struct{ n int }\n\nfunc (s *Store) Get(k string) string { return k }\n\n" \ + "type Kind string\n\nfunc (k Kind) String() string { return string(k) }\n" +static const ts_file_t go_values_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\n" TS_GO_VALUES_STORE}, + {"decoy/store.go", "package decoy\n\n" TS_GO_VALUES_STORE}, + {"conf/conf.go", "package conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n\nvar Plain = store.Store{}\n\n" + "var Fresh = new(store.Store)\n\nconst Primary store.Kind = \"primary\"\n\n" + "const (\n\tFirst store.Kind = \"a\"\n\tSecond\n)\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string { return conf.Default.Get(\"a\") }\n\n" + "func Value() string { return conf.Plain.Get(\"b\") }\n\n" + "func Fresh() string { return conf.Fresh.Get(\"c\") }\n\n" + "func Typed() string { return conf.Primary.String() }\n\n" + "func Repeated() string { return conf.Second.String() }\n"}, + {NULL, NULL}}; + +static int go_values_check(cbm_store_t *s, const char *project, const char *label) { + int pointer = ts_calls_to(s, project, "Pointer", "store.Store.Get", TS_LSP); + int value = ts_calls_to(s, project, "Value", "store.Store.Get", TS_LSP); + int fresh = ts_calls_to(s, project, "Fresh", "store.Store.Get", TS_LSP); + int typed = ts_calls_to(s, project, "Typed", "store.Kind.String", TS_LSP); + int repeated = ts_calls_to(s, project, "Repeated", "store.Kind.String", TS_LSP); + int decoy = ts_calls_to(s, project, "Pointer", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Value", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Fresh", "decoy.Store.Get", NULL) + + ts_calls_to(s, project, "Typed", "decoy.Kind.String", NULL) + + ts_calls_to(s, project, "Repeated", "decoy.Kind.String", NULL); + /* A value is no callee: no CALLS edge reaches a Variable node. */ + int to_value = ts_calls_to(s, project, "Pointer", "conf.Default", NULL) + + ts_calls_to(s, project, "Value", "conf.Plain", NULL); + int props = ts_variable_return_type_props(s, project, "Default") + + ts_variable_return_type_props(s, project, "Primary"); + printf(" go values (%s): pointer=%d value=%d new=%d typed=%d repeated=%d decoy=%d " + "to_value=%d return_type_props=%d\n", + label, pointer, value, fresh, typed, repeated, decoy, to_value, props); + return !(pointer == 1 && value == 1 && fresh == 1 && typed == 1 && repeated == 1 && + decoy == 0 && to_value == 0 && props == 0); +} + +TEST(type_scope_go_package_values) { + return ts_twins("govals", go_values_files, CBM_LANG_GO, go_values_check); +} + +/* Finding 4: `package svc` and `package svc_test` in one directory declare + * a value of one name (svc.go: real, a_test.go: fake); b_test.go uses the + * fake one, use.go the real one. Their values share a directory QN, so + * neither is typed, in either file order; and a function value called + * through `conf.Hook()` keeps main's edge (the value is no call target of + * the LSP). */ +static int go_test_package_case(bool tests_last) { + const char *a_test = tests_last ? "svc/za_test.go" : "svc/a_test.go"; + const char *b_test = tests_last ? "svc/zb_test.go" : "svc/b_test.go"; + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"conf/conf.go", "package conf\n\nfunc impl() string { return \"x\" }\n\n" + "var Hook func() string = impl\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Run() string { return conf.Hook() }\n"}, + {"real/real.go", + "package real\n\ntype Store struct{ n int }\n\nfunc (s *Store) Get() string { return \"r\" }\n"}, + {"fake/fake.go", + "package fake\n\ntype Store struct{ n int }\n\nfunc (s *Store) Get() string { return \"f\" }\n"}, + {"svc/svc.go", "package svc\n\nimport \"example.com/demo/real\"\n\n" + "var defaultStore = &real.Store{}\n\n" + "func Keep() *real.Store { return defaultStore }\n"}, + {"svc/use.go", "package svc\n\nfunc Use() string { return defaultStore.Get() }\n"}, + {a_test, "package svc_test\n\nimport \"example.com/demo/fake\"\n\n" + "var defaultStore = &fake.Store{}\n"}, + {b_test, "package svc_test\n\nfunc helper() string { return defaultStore.Get() }\n"}, + {NULL, NULL}}; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_gotest_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + FAIL("tmpdir"); + } + ts_write(tmp, files); + ts_pad(tmp, CBM_LANG_GO, TS_PAD_FILES); + int bad = 0; + for (int run = 0; run < 2; run++) { + char project[256] = {0}; + cbm_store_t *s = ts_index_workers(tmp, run ? "par.db" : "seq.db", run ? 4 : 1, project, + sizeof(project)); + if (!s) { + bad++; + continue; + } + int helper_real = ts_calls_to(s, project, "helper", "real.Store.Get", NULL); + int helper_fake = ts_calls_to(s, project, "helper", "fake.Store.Get", NULL); + int use_fake = ts_calls_to(s, project, "Use", "fake.Store.Get", NULL); + int use_real = ts_calls_to(s, project, "Use", "real.Store.Get", NULL); + int hook = ts_calls_to(s, project, "Run", "conf.Hook", NULL); + int hook_main = ts_calls_to(s, project, "Run", "conf.Hook", "\"strategy\":\"import_map\""); + printf(" go test package (%s, tests %s): helper real=%d fake=%d, Use real=%d fake=%d, " + "Run->conf.Hook=%d (import_map %d)\n", + run ? "4 workers" : "1 worker", tests_last ? "last" : "first", helper_real, + helper_fake, use_real, use_fake, hook, hook_main); + bad += helper_real + helper_fake + use_fake + use_real != 0 || hook != 1 || hook_main != 1; + cbm_store_close(s); + } + th_rmtree(tmp); + ASSERT_EQ(bad, 0); + PASS(); +} + +TEST(type_scope_go_test_package_values_share_no_name) { + ASSERT_EQ(go_test_package_case(false), 0); + ASSERT_EQ(go_test_package_case(true), 0); + PASS(); +} + +/* Build variants of one value (`//go:build linux` and `!linux` files that + * both declare `var Default = &store.Store{}`) give one answer, so the value + * stays typed. */ +static const ts_file_t go_variant_value_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"conf/conf_linux.go", "//go:build linux\n\npackage conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n"}, + {"conf/conf_other.go", "//go:build !linux\n\npackage conf\n\nimport \"example.com/demo/store\"\n\n" + "var Default = &store.Store{}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string { return conf.Default.Get(\"a\") }\n"}, + {NULL, NULL}}; + +static int go_variant_value_check(cbm_store_t *s, const char *project, const char *label) { + int hit = ts_calls_to(s, project, "Pointer", "store.Store.Get", TS_LSP); + printf(" go variant values (%s): pointer=%d\n", label, hit); + return hit != 1; +} + +TEST(type_scope_go_build_variant_values_stay_typed) { + return ts_twins("govar", go_variant_value_files, CBM_LANG_GO, go_variant_value_check); +} + +/* ── Go: embedded-member promotion ────────────────────────────────── */ + +/* A struct of another file embeds `base.Base` (an imported package's type) + * and `*Local` (its own package's); the promoted methods are found through + * the declaring file's scope. decoy/ declares the same Base with the same + * method. */ +static const ts_file_t go_embed_files[] = { + {"go.mod", "module example.com/emb\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Base struct{ n int }\n\n" + "func (b *Base) Hello() string { return \"x\" }\n"}, + {"decoy/base.go", "package decoy\n\ntype Base struct{ n int }\n\n" + "func (b *Base) Hello() string { return \"y\" }\n"}, + {"outer/outer.go", "package outer\n\nimport \"example.com/emb/base\"\n\n" + "type Outer struct {\n\tbase.Base\n\tname string\n}\n\n" + "type Local struct{ k int }\n\nfunc (l *Local) Bye() string { return \"z\" }\n\n" + "type Both struct {\n\t*Local\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/emb/outer\"\n\n" + "func Run(o *outer.Outer) string { return o.Hello() }\n\n" + "func Run2(b *outer.Both) string { return b.Bye() }\n"}, + {NULL, NULL}}; + +static int go_embed_check(cbm_store_t *s, const char *project, const char *label) { + int imported = ts_calls_to(s, project, "Run", "base.Base.Hello", TS_LSP); + int decoy = ts_calls_to(s, project, "Run", "decoy.Base.Hello", NULL); + int own = ts_calls_to(s, project, "Run2", "outer.Local.Bye", TS_LSP); + printf(" go embedded (%s): imported=%d decoy=%d own=%d\n", label, imported, decoy, own); + return !(imported == 1 && decoy == 0 && own == 1); +} + +TEST(type_scope_go_embedded_members_promote) { + return ts_twins("goemb", go_embed_files, CBM_LANG_GO, go_embed_check); +} + +/* Finding 5: Go selects the member at the shallowest depth, and a tie there + * is no selection. Across files (the review's go-embed: Outer embeds base.A, + * which embeds Inner with Hello, and base.B with Hello: B.Hello at depth 1 + * wins over Inner.Hello at depth 2), in one file the same, a tie of two + * embedded types at one depth, and an outer field of the member's name. */ +static const ts_file_t go_depth_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Inner struct{ n int }\n\n" + "func (i *Inner) Hello() string { return \"inner\" }\n\n" + "type A struct{ Inner }\n\n" + "type B struct{ k int }\n\n" + "func (b *B) Hello() string { return \"b\" }\n\n" + "type C struct{ k int }\n\n" + "func (c *C) Hello() string { return \"c\" }\n"}, + {"outer/outer.go", "package outer\n\nimport \"example.com/demo/base\"\n\n" + "type Outer struct {\n\tbase.A\n\tbase.B\n}\n\n" + "type Tie struct {\n\tbase.B\n\tbase.C\n}\n\n" + "type Shadow struct {\n\tHello func() string\n\tbase.B\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/outer\"\n\n" + "func Run(o *outer.Outer) string { return o.Hello() }\n\n" + "func Tied(t *outer.Tie) string { return t.Hello() }\n\n" + "func Field(s *outer.Shadow) string { return s.Hello() }\n"}, + {"local/local.go", "package local\n\ntype Inner struct{ n int }\n\n" + "func (i *Inner) Hello() string { return \"inner\" }\n\n" + "type A struct{ Inner }\n\n" + "type B struct{ k int }\n\n" + "func (b *B) Hello() string { return \"b\" }\n\n" + "type Outer struct {\n\tA\n\tB\n}\n\n" + "func Here(o *Outer) string { return o.Hello() }\n"}, + {NULL, NULL}}; + +static int go_depth_check(cbm_store_t *s, const char *project, const char *label) { + int shallow = ts_calls_to(s, project, "Run", "base.B.Hello", NULL); + int deep = ts_calls_to(s, project, "Run", "base.Inner.Hello", NULL); + int tied = ts_calls_to(s, project, "Tied", "base.B.Hello", NULL) + + ts_calls_to(s, project, "Tied", "base.C.Hello", NULL); + int shadowed = ts_calls_to(s, project, "Field", "base.B.Hello", NULL); + int here_shallow = ts_calls_to(s, project, "Here", "local.B.Hello", NULL); + int here_deep = ts_calls_to(s, project, "Here", "local.Inner.Hello", NULL); + printf(" go promotion depth (%s): Run B=%d Inner=%d, tie=%d, field=%d, one file B=%d " + "Inner=%d\n", + label, shallow, deep, tied, shadowed, here_shallow, here_deep); + return !(deep == 0 && shallow <= 1 && tied == 0 && shadowed == 0 && here_deep == 0 && + here_shallow <= 1); +} + +TEST(type_scope_go_promotion_takes_the_shallowest_depth) { + return ts_twins("godepth", go_depth_files, CBM_LANG_GO, go_depth_check); +} + +/* Round 3, N1: the unqualified type name of an embedded field is a field of + * its depth (Go spec). srv.Server{ Config; base.Handler } with Handler's own + * field `Config *base.Config`: s.Config is srv.Config at depth 0, in another + * package and in one of srv's files (main's right edge there stays); an + * embedded func type `Logger` shadows base.W's method Logger one level down; + * the same in one file; an embedded type the project does not have + * (sync.Mutex) still shadows a deeper `Mutex`; and build variants of one + * struct, one of which declares a field `Item` the other does not, select no + * `Item` at all: `v.Item` is base.Item on a linux build and Deep's Item2 + * elsewhere (`go run` on darwin: item2), so no one edge is right. Each "no + * edge" case has a positive partner: a promoted method of Outer (Ping), the + * explicit path to the deeper Mutex (Lock2), a field both variants declare + * alike (UseSame); Here's edge is the embedded Cfg's. `go run` agrees. */ +static const ts_file_t go_embfield_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"base/base.go", "package base\n\ntype Config struct{ n int }\n\n" + "func (c *Config) Validate() string { return \"base\" }\n\n" + "type Handler struct {\n\tConfig *Config\n}\n\n" + "type W struct{ n int }\n\nfunc (w W) Logger(s string) string { return s }\n\n" + "func (w W) Ping() string { return \"p\" }\n\n" + "type M struct{ n int }\n\nfunc (m *M) Lock() {}\n\n" + "type Locker struct {\n\tMutex *M\n}\n\n" + "type Item struct{ n int }\n\nfunc (i *Item) Do() string { return \"item\" }\n\n" + "type Item2 struct{ n int }\n\nfunc (i *Item2) Do() string { return \"item2\" }\n\n" + "type Deep struct {\n\tItem *Item2\n}\n"}, + {"srv/config.go", "package srv\n\ntype Config struct{ port int }\n\n" + "func (c Config) Validate() string { return \"srv\" }\n"}, + {"srv/server.go", "package srv\n\nimport (\n\t\"sync\"\n\n\t\"example.com/demo/base\"\n)\n\n" + "type Server struct {\n\tConfig\n\tbase.Handler\n}\n\n" + "type Logger func(string) string\n\n" + "type Outer struct {\n\tLogger\n\tbase.W\n}\n\n" + "type U struct {\n\tsync.Mutex\n\tbase.Locker\n}\n"}, + {"srv/local.go", "package srv\n\nfunc Local(s *Server) string { return s.Config.Validate() }\n"}, + {"srv/v_linux.go", "//go:build linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" + "type V struct {\n\tItem *base.Item\n\tSame *base.Item\n\tbase.Deep\n}\n"}, + {"srv/v_other.go", "//go:build !linux\n\npackage srv\n\nimport \"example.com/demo/base\"\n\n" + "type V struct {\n\tSame *base.Item\n\tbase.Deep\n}\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/srv\"\n\n" + "func Run(s *srv.Server) string { return s.Config.Validate() }\n\n" + "func Log(o srv.Outer) string { return o.Logger(\"x\") }\n\n" + "func Lock(u *srv.U) { u.Mutex.Lock() }\n\n" + "func Use(v *srv.V) string { return v.Item.Do() }\n\n" + "func Ping(o srv.Outer) string { return o.Ping() }\n\n" + "func Lock2(u *srv.U) { u.Locker.Mutex.Lock() }\n\n" + "func UseSame(v *srv.V) string { return v.Same.Do() }\n"}, + {"one/one.go", "package one\n\ntype Cfg struct{ n int }\n\nfunc (c Cfg) Check() string { return \"cfg\" }\n\n" + "type Other struct{ n int }\n\nfunc (o Other) Check() string { return \"other\" }\n\n" + "type H struct {\n\tCfg Other\n}\n\n" + "type S struct {\n\tCfg\n\tH\n}\n\n" + "func Here(s *S) string { return s.Cfg.Check() }\n"}, + {NULL, NULL}}; + +static int go_embfield_check(cbm_store_t *s, const char *project, const char *label) { + int run_right = ts_calls_to(s, project, "Run", "srv.Config.Validate", NULL); + int local_right = ts_calls_to(s, project, "Local", "srv.Config.Validate", NULL); + int here_right = ts_calls_to(s, project, "Here", "one.Cfg.Check", NULL); + int ping = ts_calls_to(s, project, "Ping", "base.W.Ping", NULL); + int lock2 = ts_calls_to(s, project, "Lock2", "base.M.Lock", NULL); + int same = ts_calls_to(s, project, "UseSame", "base.Item.Do", NULL); + int wrong = ts_calls_to(s, project, "Run", "base.Config.Validate", NULL) + + ts_calls_to(s, project, "Local", "base.Config.Validate", NULL) + + ts_calls_to(s, project, "Log", "base.W.Logger", NULL) + + ts_calls_to(s, project, "Lock", "base.M.Lock", NULL) + + ts_calls_to(s, project, "Here", "one.Other.Check", NULL); + /* the answer of a build: Item on linux, Item2 elsewhere */ + int by_build = ts_calls_to(s, project, "Use", "base.Item2.Do", NULL) + + ts_calls_to(s, project, "Use", "base.Item.Do", NULL); + printf(" go embedded field names (%s): Run=%d Local=%d Here=%d Ping=%d Lock2=%d UseSame=%d, " + "wrong=%d, by build=%d\n", + label, run_right, local_right, here_right, ping, lock2, same, wrong, by_build); + return !(run_right == 1 && local_right == 1 && here_right == 1 && ping == 1 && lock2 == 1 && + same == 1 && wrong == 0 && by_build == 0); +} + +TEST(type_scope_go_embedded_field_names_are_fields) { + return ts_twins("goembfield", go_embfield_files, CBM_LANG_GO, go_embfield_check); +} + +/* Round 3, N3: a type the function declares itself -- a local `type T` and a + * type parameter, of a function, of a generic receiver, of a generic type -- + * is never the package's T, whose embedded p1.E would promote Hello: not in + * the walker (Local, Generic, Direct: main's own false `Direct -> m.T.Own` + * goes too) and not through another package's signatures (Call through a + * generic result, Boxed through a generic method's result). Pkg uses the + * package's T and keeps its promoted edge. `go run` agrees on each. */ +static const ts_file_t go_shadowtype_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p2\" }\n\n" + "func (E) Own() string { return \"p2own\" }\n"}, + {"m/t.go", "package m\n\nimport \"example.com/demo/p1\"\n\ntype T struct{ p1.E }\n\n" + "func (T) Own() string { return \"m\" }\n"}, + {"m/use.go", "package m\n\nimport \"example.com/demo/p2\"\n\n" + "func Local() string {\n\ttype T struct{ p2.E }\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func Generic[T interface{ Hello() string }](x T) string { return x.Hello() }\n\n" + "func Direct[T interface{ Own() string }](x T) string { return x.Own() }\n\n" + "func Pkg() string {\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func First[T any](xs []T) T { return xs[0] }\n\n" + "type Box[T any] struct{ V T }\n\n" + "func (b Box[T]) Get() T { return b.V }\n"}, + {"app/app.go", "package app\n\nimport (\n\t\"example.com/demo/m\"\n\t\"example.com/demo/p2\"\n)\n\n" + "func Call() string { return m.First([]p2.E{{}}).Hello() }\n\n" + "func Boxed() string { return m.Box[p2.E]{}.Get().Hello() }\n\n" + "func Field(b m.Box[p2.E]) string { return b.V.Hello() }\n"}, + {NULL, NULL}}; + +static int go_shadowtype_check(cbm_store_t *s, const char *project, const char *label) { + int wrong = ts_calls_to(s, project, "Local", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Generic", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Direct", "m.T.Own", NULL) + + ts_calls_to(s, project, "Call", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Boxed", "p1.E.Hello", NULL) + + ts_calls_to(s, project, "Field", "p1.E.Hello", NULL); + int pkg = ts_calls_to(s, project, "Pkg", "p1.E.Hello", NULL); + /* the signatures are read: the calls themselves resolve */ + int direct = ts_calls_to(s, project, "Call", "m.First", NULL) + + ts_calls_to(s, project, "Boxed", "m.Box.Get", NULL); + printf(" go function-declared types (%s): wrong=%d, package T Pkg=%d, First/Get=%d\n", label, + wrong, pkg, direct); + return !(wrong == 0 && pkg == 1 && direct == 2); +} + +TEST(type_scope_go_function_declared_types_are_not_the_package_types) { + return ts_twins("goshadow", go_shadowtype_files, CBM_LANG_GO, go_shadowtype_check); +} + +/* A local type declared in an inner block or in a + * closure shadows the package's type only there (Go's block scope): after the + * `if` block and outside the closure, `T` is the package's again, whose + * embedded p1.E promotes Hello (`go run`: Block p1, Clo p2p1). Inside the + * closure the local T (embedding p2.E) gets no package edge. */ +static const ts_file_t go_blocktype_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{}\n\nfunc (E) Hello() string { return \"p2\" }\n"}, + {"m/t.go", "package m\n\nimport \"example.com/demo/p1\"\n\ntype T struct{ p1.E }\n"}, + {"m/use.go", "package m\n\nimport \"example.com/demo/p2\"\n\n" + "func Block(c bool) string {\n\tif c {\n\t\ttype T struct{ p2.E }\n\t\tvar t T\n" + "\t\t_ = t\n\t}\n\tvar t T\n\treturn t.Hello()\n}\n\n" + "func Clo() string {\n\tf := func() string {\n\t\ttype T struct{ p2.E }\n" + "\t\tvar t T\n\t\treturn t.Hello()\n\t}\n\tvar t T\n\treturn f() + t.Hello()\n}\n"}, + {NULL, NULL}}; + +static int go_blocktype_check(cbm_store_t *s, const char *project, const char *label) { + int block = ts_calls_to(s, project, "Block", "p1.E.Hello", NULL); + int clo = ts_calls_to(s, project, "Clo", "p1.E.Hello", NULL); + printf(" go block-local types (%s): Block p1=%d, Clo p1=%d\n", label, block, clo); + return !(block == 1 && clo == 1); +} + +TEST(type_scope_go_local_types_shadow_only_their_block) { + return ts_twins("goblock", go_blocktype_files, CBM_LANG_GO, go_blocktype_check); +} + +/* Round 3, the 63-field limit beside N4: a struct of 66 named fields whose + * last two are typed. Every route registers every field now. */ +static const ts_file_t go_wide_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"kind/kind.go", "package kind\n\ntype K struct{}\n\nfunc (K) Name() string { return \"k\" }\n\n" + "type L struct{}\n\nfunc (L) Name() string { return \"l\" }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/wide\"\n\n" + "func Run(w *wide.Wide) string { return w.Last.Name() }\n"}, + {NULL, NULL}}; + +static int go_wide_check(cbm_store_t *s, const char *project, const char *label) { + int run = ts_calls_to(s, project, "Run", "kind.L.Name", NULL); + int use = ts_calls_to(s, project, "Use", "kind.K.Name", NULL) + + ts_calls_to(s, project, "Use", "kind.L.Name", NULL); + printf(" go wide struct (%s): Run=%d Use=%d\n", label, run, use); + return !(run == 1 && use == 2); +} + +static char g_go_wide_source[4096]; +static char g_go_wide_edited[4096]; + +static const char *go_wide_source(char *buf, size_t cap, bool edited) { + size_t at = (size_t)snprintf(buf, cap, + "package wide\n\nimport \"example.com/demo/kind\"\n\ntype Wide struct {\n"); + for (int i = 0; i < 64; i++) { + at += (size_t)snprintf(buf + at, cap - at, "\tF%d int\n", i); + } + snprintf(buf + at, cap - at, + "\tLate kind.K\n\tLast kind.L\n}\n\nfunc Use(w *Wide) string {\n\t%s\n}\n", + edited ? "s := w.Late.Name() + w.Last.Name()\n\treturn s" + : "return w.Late.Name() + w.Last.Name()"); + return buf; +} + +static void go_wide_fixture(ts_file_t *files) { + int n = (int)(sizeof(go_wide_files) / sizeof(go_wide_files[0])) - 1; + memcpy(files, go_wide_files, (size_t)n * sizeof(ts_file_t)); + files[n] = (ts_file_t){"wide/wide.go", + go_wide_source(g_go_wide_source, sizeof(g_go_wide_source), false)}; + files[n + 1] = (ts_file_t){NULL, NULL}; +} + +TEST(type_scope_go_struct_fields_have_no_limit) { + ts_file_t files[8]; + go_wide_fixture(files); + return ts_twins("gowide", files, CBM_LANG_GO, go_wide_check); +} + +/* ── Full index versus every incremental route ───────────────────── */ + +static void ts_listing_append(sqlite3 *db, const char *sql, const char *project, char **buf, + size_t *len) { + sqlite3_stmt *st = NULL; + if (sqlite3_prepare_v2(db, sql, -1, &st, NULL) != SQLITE_OK) { + return; + } + sqlite3_bind_text(st, 1, project, -1, SQLITE_TRANSIENT); + while (sqlite3_step(st) == SQLITE_ROW) { + const char *row = (const char *)sqlite3_column_text(st, 0); + size_t n = row ? strlen(row) : 0; + char *grown = (char *)realloc(*buf, *len + n + 2); + if (!grown) { + break; + } + *buf = grown; + memcpy(*buf + *len, row ? row : "", n); + *len += n; + (*buf)[(*len)++] = '\n'; + (*buf)[*len] = '\0'; + } + sqlite3_finalize(st); +} + +/* Every node (label, QN) and edge (type, source QN, target QN, properties) + * of the project, sorted: equal listings are equal graphs. A call's `args` + * are left out: on main already the closure route renders them differently + * from a full index (quote style, key order), whatever the resolver did. */ +static char *ts_listing(const char *db_path, const char *project) { + sqlite3 *db = NULL; + if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + sqlite3_close(db); + return NULL; + } + char *buf = (char *)calloc(1, 1); + size_t len = 0; + ts_listing_append(db, + "SELECT label||'|'||qualified_name FROM nodes WHERE project=?1 ORDER BY 1", + project, &buf, &len); + ts_listing_append(db, + "SELECT e.type||'|'||s.qualified_name||'|'||t.qualified_name||'|'||" + "CASE WHEN json_valid(e.properties) THEN json_remove(e.properties, '$.args') " + "ELSE coalesce(e.properties, '') END FROM edges e " + "JOIN nodes s ON s.id=e.source_id " + "JOIN nodes t ON t.id=e.target_id WHERE e.project=?1 ORDER BY 1", + project, &buf, &len); + sqlite3_close(db); + return buf; +} + +/* Print the lines one listing has and the other lacks (a failing case). */ +static void ts_listing_diff(const char *a, const char *b, const char *tag) { + for (const char *line = a; line && *line;) { + const char *nl = strchr(line, '\n'); + size_t n = nl ? (size_t)(nl - line) : strlen(line); + bool found = false; + for (const char *p = b; p && *p && !found;) { + const char *pnl = strchr(p, '\n'); + size_t pn = pnl ? (size_t)(pnl - p) : strlen(p); + found = pn == n && memcmp(p, line, n) == 0; + p = pnl ? pnl + 1 : p + pn; + } + if (!found) { + printf(" only %s: %.*s\n", tag, (int)n, line); + } + line = nl ? nl + 1 : line + n; + } +} + +typedef struct { + cbm_incremental_route_t route; + cbm_incremental_closure_plan_t plan; + bool same_graph; + int before_bad; /* the `before` check on the first index (0 = right) */ + int after_bad; /* the `after` check on the repaired graph (0 = right) */ +} ts_incr_result_t; + +/* Run `check` on one database of the harness: 0 when it holds (or there is + * no check), else nonzero (also when the index named no project). */ +static int ts_db_check(const char *db, const char *project, ts_check_fn check, const char *label) { + if (!check || !project[0]) { + return check ? 1 : 0; + } + cbm_store_t *s = cbm_store_open_path(db); + int bad = s ? check(s, project, label) : 1; + if (s) { + cbm_store_close(s); + } + return bad; +} + +/* Index `files` (plus `pad` Go or Python fillers), apply `edits`, index again + * incrementally into the same database, then index the edited tree afresh; + * the two graphs must be equal whatever route the incremental run took. + * `before` (optional) checks the first index, `after` the repaired graph. */ +static ts_incr_result_t ts_incremental_checked(const ts_file_t *files, CBMLanguage pad_lang, + int pad, const ts_file_t *edits, const char *tag, + ts_check_fn before, ts_check_fn after) { + ts_incr_result_t r = {.route = CBM_INCREMENTAL_ROUTE_NONE}; + char tmp[256]; + snprintf(tmp, sizeof(tmp), "/tmp/cbm_tscope_incr_XXXXXX"); + if (!cbm_mkdtemp(tmp)) { + return r; + } + ts_write(tmp, files); + ts_pad(tmp, pad_lang, pad); + char db[512]; + snprintf(db, sizeof(db), "%s/incr.db", tmp); + cbm_pipeline_t *base = cbm_pipeline_new(tmp, db, CBM_MODE_FULL); + char project[256] = {0}; + if (base && cbm_pipeline_run(base) == 0) { + snprintf(project, sizeof(project), "%s", cbm_pipeline_project_name(base)); + } + cbm_pipeline_free(base); + r.before_bad = ts_db_check(db, project, before, "before the edit"); + + ts_write(tmp, edits); + cbm_pipeline_incremental_test_reset_faults(); + cbm_pipeline_t *incr = cbm_pipeline_new(tmp, db, CBM_MODE_FULL); + int rc = incr ? cbm_pipeline_run(incr) : -1; + r.route = cbm_pipeline_incremental_test_last_route(); + r.plan = cbm_pipeline_incremental_test_last_closure_plan(); + cbm_pipeline_free(incr); + r.after_bad = rc == 0 ? ts_db_check(db, project, after, "repaired") : 1; + + char full_db[512]; + snprintf(full_db, sizeof(full_db), "%s/full.db", tmp); + cbm_pipeline_t *full = cbm_pipeline_new(tmp, full_db, CBM_MODE_FULL); + int full_rc = full ? cbm_pipeline_run(full) : -1; + cbm_pipeline_free(full); + + char *repaired = rc == 0 && project[0] ? ts_listing(db, project) : NULL; + char *fresh = full_rc == 0 && project[0] ? ts_listing(full_db, project) : NULL; + r.same_graph = repaired && fresh && strcmp(repaired, fresh) == 0; + printf(" incremental %s: route=%d plan files=%d surface_changed=%d dependents=%d " + "decline=%s same_graph=%d\n", + tag, (int)r.route, r.plan.files, r.plan.surface_changed, r.plan.dependents, + r.plan.decline ? r.plan.decline : "-", (int)r.same_graph); + if (!r.same_graph && repaired && fresh) { + ts_listing_diff(repaired, fresh, "incremental"); + ts_listing_diff(fresh, repaired, "full"); + } + free(repaired); + free(fresh); + th_rmtree(tmp); + return r; +} + +static ts_incr_result_t ts_incremental(const ts_file_t *files, CBMLanguage pad_lang, int pad, + const ts_file_t *edits, const char *tag) { + return ts_incremental_checked(files, pad_lang, pad, edits, tag, NULL, NULL); +} + +/* Only the caller is re-parsed (a closure of one file: the per-file Go + * registrar): fixture.go's identities come back from its stored row. */ +TEST(type_scope_incremental_caller_edit_per_file_go) { + const ts_file_t edit[] = { + {"app/app.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\tv := s.Get(\"x\")\n\treturn v\n}\n\n" + "func Field() string {\n\th := fixture.NewHolder()\n\treturn h.S.Get(\"y\")\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(go_scope_files, CBM_LANG_GO, 0, edit, "go caller edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* The same through package-level values: the per-file Go registrar types + * `conf.Default` from conf.go's stored row. */ +TEST(type_scope_incremental_caller_edit_per_file_go_values) { + const ts_file_t edit[] = { + {"app/app.go", "package app\n\nimport \"example.com/demo/conf\"\n\n" + "func Pointer() string {\n\tv := conf.Default.Get(\"a\")\n\treturn v\n}\n\n" + "func Value() string { return conf.Plain.Get(\"b\") }\n\n" + "func Fresh() string { return conf.Fresh.Get(\"c\") }\n\n" + "func Typed() string { return conf.Primary.String() }\n\n" + "func Repeated() string { return conf.Second.String() }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = + ts_incremental(go_values_files, CBM_LANG_GO, 0, edit, "go values caller edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 9: a body edit of the file that holds the identities, with twelve + * dependents in a 40-file tree (the review's go-incr), stays a one-file + * repair as on main: the probe and the stored row hash the same bytes. */ +static const ts_file_t go_incr_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\n" + "func (s *Store) Get(k string) string { return k }\n"}, + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store { return &store.Store{} }\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {"app0/app.go", "package app0\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app1/app.go", "package app1\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app2/app.go", "package app2\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app3/app.go", "package app3\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app4/app.go", "package app4\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app5/app.go", "package app5\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app6/app.go", "package app6\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app7/app.go", "package app7\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app8/app.go", "package app8\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app9/app.go", "package app9\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app10/app.go", "package app10\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {"app11/app.go", "package app11\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string {\n\ts := fixture.New()\n\treturn s.Get(\"x\")\n}\n"}, + {NULL, NULL}}; + +TEST(type_scope_incremental_body_edit_stays_one_file) { + const ts_file_t edit[] = { + {"fixture/fixture.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n\n" + "func New() *store.Store {\n\ts := &store.Store{}\n\treturn s\n}\n\n" + "func NewHolder() Holder { return Holder{} }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(go_incr_files, CBM_LANG_GO, 25, edit, "go body edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_EQ(r.plan.surface_changed, 0); + ASSERT_EQ(r.plan.dependents, 0); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 7, Go: the type an identity names changes in its declaring file + * while every name stays (an alias that becomes a defined type, a type that + * becomes a variable), and a caller two imports away resolved through it. + * The methods live in other files of the package, so the caller is no + * dependent of the edited file. The doc-link scope records an exported + * type's kind and alias target, so main already declines these; the graph + * must still be the full index's. */ +static const ts_file_t go_alias_files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "type T = Impl\n"}, + {"store/b2.go", "package store\n\nfunc (i Impl) M() string { return \"impl\" }\n"}, + {"store/b3.go", "package store\n\nfunc (i Impl2) M() string { return \"impl2\" }\n"}, + {"decoy/d.go", "package decoy\n\ntype T struct{ n int }\n\nfunc (t T) M() string { return \"d\" }\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "func Make() store.T { return store.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().M() }\n"}, + {NULL, NULL}}; + +/* The change the doc-link scope does not see (it records an exported type's + * name, kind, alias target and field names, never a field's type): the + * struct an identity names gets another field type. The caller resolved + * `fixture.Get().S.Get()` through fixture.go's identity `model.Holder` and + * Holder's field; it has no edge into model/b.go. */ +TEST(type_scope_incremental_named_type_field_change_matches_full) { + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/store.go", "package store\n\ntype Store struct{ n int }\n\ntype Other struct{ n int }\n"}, + {"store/m1.go", "package store\n\nfunc (s *Store) Get() string { return \"s\" }\n"}, + {"store/m2.go", "package store\n\nfunc (o *Other) Get() string { return \"o\" }\n"}, + {"model/b.go", "package model\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Store\n}\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/model\"\n\n" + "func Get() model.Holder { return model.Holder{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Get().S.Get() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"model/b.go", "package model\n\nimport \"example.com/demo/store\"\n\n" + "type Holder struct {\n\tS *store.Other\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go named type field change"); + ASSERT_TRUE(r.same_graph); + ASSERT_STR_EQ(r.plan.decline, "identity_target_changed"); + PASS(); +} + +TEST(type_scope_incremental_type_shape_changes_match_full) { + const ts_file_t to_defined[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "type T Impl\n"}, + {NULL, NULL}}; + ts_incr_result_t r = + ts_incremental(go_alias_files, CBM_LANG_GO, 0, to_defined, "go alias->defined type"); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_FORCED_FULL); + const ts_file_t to_var[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype Impl2 struct{ n int }\n\n" + "var T = Impl{}\n"}, + {NULL, NULL}}; + r = ts_incremental(go_alias_files, CBM_LANG_GO, 0, to_var, "go type->var"); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_FORCED_FULL); + PASS(); +} + +/* The shape only the identity gate catches: the struct an identity names + * embeds another package's type of the same name (`p1.E` -> `p2.E`, both + * imported already). The doc-link scope sees the same type, kind and field + * names; the caller reached the promoted method through fixture.go's + * identity and has no edge into model/b.go, so a repair would keep its stale + * edge to p1.E.Hello. */ +TEST(type_scope_incremental_named_type_embed_change_matches_full) { + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"p1/e.go", "package p1\n\ntype E struct{ n int }\n\nfunc (e *E) Hello() string { return \"1\" }\n"}, + {"p2/e.go", "package p2\n\ntype E struct{ n int }\n\nfunc (e *E) Hello() string { return \"2\" }\n"}, + {"model/b.go", "package model\n\nimport (\n\t\"example.com/demo/p1\"\n\t\"example.com/demo/p2\"\n)\n\n" + "var _ p2.E\n\ntype T struct {\n\tp1.E\n}\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/model\"\n\n" + "func Make() *model.T { return &model.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().Hello() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"model/b.go", "package model\n\nimport (\n\t\"example.com/demo/p1\"\n\t\"example.com/demo/p2\"\n)\n\n" + "var _ p1.E\n\ntype T struct {\n\tp2.E\n}\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go named type embed change"); + ASSERT_TRUE(r.same_graph); + ASSERT_STR_EQ(r.plan.decline, "identity_target_changed"); + PASS(); +} + +/* Round 3, N4 (the review's go-emb16): a body edit of the file declaring a + * struct of 17 embedded types is a one-file repair, and the repaired graph is + * the full index's: the per-file route takes the struct's embedded types from + * its definition, as the full index does, all of them (it kept 15). */ +static char g_go_emb_parts[4096]; +static char g_go_emb_big[2048]; +static char g_go_emb_big_edited[2048]; + +static void go_emb_sources(void) { + size_t at = (size_t)snprintf(g_go_emb_parts, sizeof(g_go_emb_parts), "package big\n\n"); + size_t fa = 0; + char fields[512]; + for (int i = 0; i < 17; i++) { + at += (size_t)snprintf(g_go_emb_parts + at, sizeof(g_go_emb_parts) - at, + "type E%d struct{}\n\nfunc (E%d) M%d() string { return \"%d\" }\n\n", i, + i, i, i); + fa += (size_t)snprintf(fields + fa, sizeof(fields) - fa, "\tE%d\n", i); + } + snprintf(g_go_emb_big, sizeof(g_go_emb_big), + "package big\n\ntype Big struct {\n%s}\n\n" + "func Use(b *Big) string {\n\treturn b.M16() + b.M14()\n}\n", + fields); + snprintf(g_go_emb_big_edited, sizeof(g_go_emb_big_edited), + "package big\n\ntype Big struct {\n%s}\n\n" + "func Use(b *Big) string {\n\ts := b.M16() + b.M14()\n\treturn s\n}\n", + fields); +} + +/* The repaired graph has the edge through the 17th embedded type. */ +static int go_emb16_after(cbm_store_t *s, const char *project, const char *label) { + int m16 = ts_calls_to(s, project, "Use", "big.E16.M16", NULL); + int m14 = ts_calls_to(s, project, "Use", "big.E14.M14", NULL); + printf(" go 17 embedded types (%s): Use -> E16.M16=%d E14.M14=%d\n", label, m16, m14); + return !(m16 == 1 && m14 == 1); +} + +TEST(type_scope_incremental_many_embedded_types_match_full) { + go_emb_sources(); + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"big/parts.go", g_go_emb_parts}, + {"big/big.go", g_go_emb_big}, + {"big/use2.go", "package big\n\nfunc Use2(b *Big) string { return b.M16() }\n"}, + {"decoy/d.go", "package decoy\n\ntype D struct{}\n\nfunc (D) M16() string { return \"d\" }\n\n" + "func (D) M14() string { return \"d\" }\n"}, + {"app/app.go", "package app\n\nimport \"example.com/demo/big\"\n\n" + "func Run(b *big.Big) string { return b.M16() }\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = {{"big/big.go", g_go_emb_big_edited}, {NULL, NULL}}; + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_GO, 40, edit, "go 17 embedded types", + NULL, go_emb16_after); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.after_bad, 0); + PASS(); +} + +/* The same for a struct of 66 fields (the 63-field limit beside N4): the + * repaired graph is the full index's and has the calls through fields 65 + * and 66 (both routes cut at 63 before). */ +static int go_wide_after(cbm_store_t *s, const char *project, const char *label) { + int use = ts_calls_to(s, project, "Use", "kind.K.Name", NULL) + + ts_calls_to(s, project, "Use", "kind.L.Name", NULL); + printf(" go 66 fields (%s): Use through fields 65 and 66=%d\n", label, use); + return use != 2; +} + +TEST(type_scope_incremental_many_fields_match_full) { + ts_file_t files[8]; + go_wide_fixture(files); + const ts_file_t edit[] = { + {"wide/wide.go", go_wide_source(g_go_wide_edited, sizeof(g_go_wide_edited), true)}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_GO, 40, edit, "go 66 fields", NULL, + go_wide_after); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.after_bad, 0); + PASS(); +} + +/* The gate is narrow: a signature change of another definition in the + * declaring file stays a repair. */ +TEST(type_scope_incremental_other_def_edit_stays_a_repair) { + const ts_file_t edit[] = { + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype T = Impl\n\n" + "func Helper(n int) int { return n }\n"}, + {NULL, NULL}}; + const ts_file_t files[] = { + {"go.mod", "module example.com/demo\n\ngo 1.21\n"}, + {"store/b.go", "package store\n\ntype Impl struct{ n int }\n\ntype T = Impl\n\n" + "func Helper() int { return 1 }\n"}, + {"store/b2.go", "package store\n\nfunc (i Impl) M() string { return \"impl\" }\n"}, + {"fixture/a.go", "package fixture\n\nimport \"example.com/demo/store\"\n\n" + "func Make() store.T { return store.T{} }\n"}, + {"app/c.go", "package app\n\nimport \"example.com/demo/fixture\"\n\n" + "func Run() string { return fixture.Make().M() }\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_GO, 0, edit, "go other def edit"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Python: a caller's body edit re-resolves that file alone with the per-file + * Python registrar, reading fixture.py's identities from its stored row; a + * body edit of fixture.py itself stays a one-file repair too. */ +TEST(type_scope_incremental_python_body_edits) { + const ts_file_t caller[] = { + {"pkg/app.py", "from pkg.fixture import make, local\n\n\n" + "def run():\n s = make()\n v = s.get(\"x\")\n return v\n\n\n" + "def own():\n v = local()\n return v.ping()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(py_scope_files, CBM_LANG_PYTHON, 0, caller, "py caller"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_TRUE(r.same_graph); + const ts_file_t declaring[] = { + {"pkg/fixture.py", "from pkg.store import Store\n\n\n" + "class Local:\n def ping(self):\n return 1\n\n\n" + "def make() -> Store:\n s = Store()\n return s\n\n\n" + "def local() -> Local:\n return Local()\n"}, + {NULL, NULL}}; + r = ts_incremental(py_scope_files, CBM_LANG_PYTHON, 0, declaring, "py declaring body"); + ASSERT_EQ(r.route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR); + ASSERT_EQ(r.plan.files, 1); + ASSERT_EQ(r.plan.surface_changed, 0); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Finding 7, Python: the declaring module's name changes from an alias to a + * class (and a class to a function), a caller two imports away. */ +TEST(type_scope_incremental_python_declaring_change_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/b.py", "class Impl:\n def m(self):\n return 1\n\n\nT = Impl\n"}, + {"pkg/a.py", "from pkg.b import T\n\n\ndef make() -> T:\n return T()\n"}, + {"pkg/c.py", "from pkg.a import make\n\n\ndef run():\n return make().m()\n"}, + {NULL, NULL}}; + const ts_file_t to_class[] = { + {"pkg/b.py", "class Impl:\n def m(self):\n return 1\n\n\n" + "class T:\n def m(self):\n return 2\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental(files, CBM_LANG_PYTHON, 0, to_class, "py alias->class"); + ASSERT_TRUE(r.same_graph); + const ts_file_t start_class[] = { + {"pkg/__init__.py", ""}, + {"pkg/b.py", "class T:\n def m(self):\n return 1\n"}, + {"pkg/a.py", "from pkg.b import T\n\n\ndef make() -> T:\n return T()\n"}, + {"pkg/c.py", "from pkg.a import make\n\n\ndef run():\n return make().m()\n"}, + {NULL, NULL}}; + const ts_file_t to_function[] = { + {"pkg/b.py", "def T():\n return 1\n\n\ndef m():\n return 2\n"}, {NULL, NULL}}; + r = ts_incremental(start_class, CBM_LANG_PYTHON, 0, to_function, "py class->function"); + ASSERT_TRUE(r.same_graph); + PASS(); +} + +/* Round 3, N2 on the incremental routes: a class-body edit that binds the + * name a method annotation uses (`marker = OtherConfig` becomes `Config = + * OtherConfig`: same lines, same bytes otherwise) changes the class's + * identities. The class's bindings are part of its stored row, so the run is + * not a one-file repair that keeps the caller's stale `run -> + * pkg.mod.Config.load`: before the edit the edge is there (Config is the + * module's), after it the repaired graph has none (python3: OtherConfig). */ +static int py_classedit_before(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" py class-body edit (%s): run -> Config.load=%d\n", label, edge); + return edge != 1; +} + +static int py_classedit_after(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.mod.Config.load", NULL); + printf(" py class-body edit (%s): run -> Config.load=%d\n", label, edge); + return edge != 0; +} + +TEST(type_scope_incremental_python_class_body_binding_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/other.py", "class OtherConfig:\n def load(self):\n return 'other'\n"}, + {"pkg/mod.py", "from pkg.other import OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class Model:\n marker = OtherConfig\n\n" + " def cfg(self) -> Config:\n return Config()\n"}, + {"pkg/use.py", "from pkg.mod import Model\n\n\ndef run():\n return Model().cfg().load()\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"pkg/mod.py", "from pkg.other import OtherConfig\n\n\n" + "class Config:\n def load(self):\n return 'module'\n\n\n" + "class Model:\n Config = OtherConfig\n\n" + " def cfg(self) -> Config:\n return Config()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_PYTHON, 0, edit, + "py class-body binding", py_classedit_before, + py_classedit_after); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.before_bad, 0); + ASSERT_EQ(r.after_bad, 0); + PASS(); +} + +/* A function body edit (same lines) that declares the module's R `global` + * and binds it: the module's annotation `-> R` loses its identity. The + * function's global names are part of its stored row, so the run is not a + * one-file repair that keeps the caller's stale `run -> pkg.a.R.save`. */ +static int py_globaledit_before(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.a.R.save", NULL); + printf(" py global edit (%s): run -> pkg.a.R.save=%d\n", label, edge); + return edge != 1; +} + +static int py_globaledit_after(cbm_store_t *s, const char *project, const char *label) { + int edge = ts_calls_to(s, project, "run", "pkg.a.R.save", NULL); + printf(" py global edit (%s): run -> pkg.a.R.save=%d\n", label, edge); + return edge != 0; +} + +TEST(type_scope_incremental_python_global_binding_matches_full) { + const ts_file_t files[] = { + {"pkg/__init__.py", ""}, + {"pkg/a.py", "class R:\n def save(self):\n return 'a'\n"}, + {"pkg/b.py", "class R:\n def save(self):\n return 'b'\n"}, + {"pkg/mod.py", "from pkg.a import R\n\n\ndef setup():\n r = None\n from pkg.b import R\n\n\n" + "def make() -> R:\n return R()\n"}, + {"pkg/use.py", "from pkg.mod import make\n\n\ndef run():\n return make().save()\n"}, + {NULL, NULL}}; + const ts_file_t edit[] = { + {"pkg/mod.py", "from pkg.a import R\n\n\ndef setup():\n global R\n from pkg.b import R\n\n\n" + "def make() -> R:\n return R()\n"}, + {NULL, NULL}}; + ts_incr_result_t r = ts_incremental_checked(files, CBM_LANG_PYTHON, 0, edit, "py global binding", + py_globaledit_before, py_globaledit_after); + ASSERT_TRUE(r.same_graph); + ASSERT_EQ(r.before_bad, 0); + ASSERT_EQ(r.after_bad, 0); + PASS(); +} + +SUITE(type_scope) { + RUN_TEST(type_scope_import_binding_is_the_identity); + RUN_TEST(type_scope_dotted_spelling_through_its_head); + RUN_TEST(type_scope_stores_nothing_without_one_answer); + RUN_TEST(type_scope_names_outside_the_project_get_none); + RUN_TEST(type_scope_go_bare_names_and_own_module); + RUN_TEST(type_scope_python_own_module); + RUN_TEST(type_scope_python_enclosing_scopes); + RUN_TEST(type_scope_python_class_body_bindings); + RUN_TEST(type_scope_python_type_parameters); + RUN_TEST(type_scope_python_unlisted_bindings_get_none); + RUN_TEST(type_scope_step_work_grows_linearly); + RUN_TEST(type_scope_lookup_work_grows_linearly); + RUN_TEST(type_scope_reach_work_grows_linearly); + RUN_TEST(type_scope_identity_gate_work_grows_linearly); + RUN_TEST(type_scope_go_return_and_field_types); + RUN_TEST(type_scope_go_type_parameter_is_no_import); + RUN_TEST(type_scope_python_return_types); + RUN_TEST(type_scope_python_nested_class_is_not_the_module_class); + RUN_TEST(type_scope_python_class_body_bindings_shadow_the_module); + RUN_TEST(type_scope_python_class_and_module_of_one_qn); + RUN_TEST(type_scope_python_global_rebinding_takes_no_identity); + RUN_TEST(type_scope_python_unbound_class_names_are_the_module_names); + RUN_TEST(type_scope_python_overloaded_method_takes_no_identity); + RUN_TEST(type_scope_python_overload_imported_under_another_name); + RUN_TEST(type_scope_python_self_chain_keeps_its_edges); + RUN_TEST(type_scope_python_type_parameter_is_no_import); + RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_per_file); + RUN_TEST(type_scope_go_fields_survive_an_earlier_receiver_shared); + RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_per_file); + RUN_TEST(type_scope_go_shared_type_qn_keeps_no_fields_shared); + RUN_TEST(type_scope_go_closure_parameters_in_composite_literals); + RUN_TEST(type_scope_go_package_values); + RUN_TEST(type_scope_go_test_package_values_share_no_name); + RUN_TEST(type_scope_go_build_variant_values_stay_typed); + RUN_TEST(type_scope_go_embedded_members_promote); + RUN_TEST(type_scope_go_promotion_takes_the_shallowest_depth); + RUN_TEST(type_scope_go_embedded_field_names_are_fields); + RUN_TEST(type_scope_go_function_declared_types_are_not_the_package_types); + RUN_TEST(type_scope_go_local_types_shadow_only_their_block); + RUN_TEST(type_scope_go_embedded_text_work_grows_linearly); + RUN_TEST(type_scope_go_struct_fields_have_no_limit); + RUN_TEST(type_scope_incremental_caller_edit_per_file_go); + RUN_TEST(type_scope_incremental_caller_edit_per_file_go_values); + RUN_TEST(type_scope_incremental_body_edit_stays_one_file); + RUN_TEST(type_scope_incremental_named_type_field_change_matches_full); + RUN_TEST(type_scope_incremental_named_type_embed_change_matches_full); + RUN_TEST(type_scope_incremental_many_embedded_types_match_full); + RUN_TEST(type_scope_incremental_many_fields_match_full); + RUN_TEST(type_scope_incremental_python_class_body_binding_matches_full); + RUN_TEST(type_scope_incremental_python_global_binding_matches_full); + RUN_TEST(type_scope_incremental_type_shape_changes_match_full); + RUN_TEST(type_scope_incremental_other_def_edit_stays_a_repair); + RUN_TEST(type_scope_incremental_python_body_edits); + RUN_TEST(type_scope_incremental_python_declaring_change_matches_full); +}