Merge pull request #3034 from DeusData/feat/declared-type-scope-go-python-2

feat(lsp): resolve declared types in the scope that wrote them (Go, Python)
This commit is contained in:
Martin Vogel
2026-11-18 23:05:14 +01:00
committed by GitHub
23 changed files with 6148 additions and 375 deletions
+2 -1
View File
@@ -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
+39
View File
@@ -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).
+713
View File
@@ -16,6 +16,7 @@
#include "semantic/ast_profile.h"
#include "tree_sitter/api.h" // TSNode, ts_node_*
#include <limits.h> // INT_MAX
#include <stdatomic.h> // test-seam work counters
#include <stdint.h> // uint32_t, SIZE_MAX
#include <stdio.h> // snprintf (ObjectScript storage/trigger sidecars)
#include <stdlib.h> // malloc/free (child-collection scratch)
@@ -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 <target>` 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;
}
}
}
}
+980 -303
View File
File diff suppressed because it is too large Load Diff
+8
View File
@@ -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.
+28 -3
View File
@@ -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]) {
+4
View File
@@ -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.
+126
View File
@@ -1,4 +1,5 @@
#include "type_rep.h"
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
@@ -963,3 +964,128 @@ const CBMType *cbm_type_substitute(CBMArena *a, const CBMType *t, const char **t
return t;
}
}
/* ── Declared-type identities of one definition ─────────────────── */
/* One identity: offsets into the index's copy of the scope, where '=' and '|'
* are cut to NULs (12 bytes; len 0 = an empty slot). */
typedef struct {
uint32_t name;
uint32_t len;
uint32_t qn;
} cbm_type_scope_entry_t;
/* Up to TYPE_SCOPE_LIST_MAX identities (most definitions have one to three)
* are a plain list a lookup scans, a bounded cost; more are an open-addressing
* table of a power-of-two size. Same answers either way. */
enum { TYPE_SCOPE_LIST_MAX = 4 };
struct cbm_type_scope_index {
const char *text; /* the copy the entries point into */
cbm_type_scope_entry_t *slots; /* the list (mask 0) or the table */
uint32_t mask; /* table size - 1, or 0 for a list */
uint32_t count; /* list entries */
};
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
static _Atomic uint64_t g_type_scope_index_work;
uint64_t cbm_type_scope_index_test_work(void) {
return atomic_load_explicit(&g_type_scope_index_work, memory_order_relaxed);
}
#define TYPE_SCOPE_INDEX_WORK(n) \
atomic_fetch_add_explicit(&g_type_scope_index_work, (uint64_t)(n), memory_order_relaxed)
#else
#define TYPE_SCOPE_INDEX_WORK(n) ((void)0)
#endif
static uint32_t type_scope_hash(const char *s, size_t len) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < len; i++) {
h = (h ^ (unsigned char)s[i]) * 16777619u;
}
return h;
}
const cbm_type_scope_index_t *cbm_type_scope_index(CBMArena *a, const char *scope) {
if (!a || !scope || !scope[0]) {
return NULL;
}
size_t n = strlen(scope);
TYPE_SCOPE_INDEX_WORK(n);
if (n >= UINT32_MAX) {
return NULL;
}
uint32_t entries = 1;
for (size_t i = 0; i < n; i++) {
entries += scope[i] == '|';
}
bool list = entries <= TYPE_SCOPE_LIST_MAX;
uint32_t size = list ? entries : 4;
while (!list && size < entries * 2) {
size *= 2;
}
char *copy = cbm_arena_strndup(a, scope, n);
cbm_type_scope_index_t *ix = (cbm_type_scope_index_t *)cbm_arena_alloc(a, sizeof(*ix));
cbm_type_scope_entry_t *slots =
(cbm_type_scope_entry_t *)cbm_arena_alloc(a, (size_t)size * sizeof(*slots));
if (!copy || !ix || !slots) {
return NULL;
}
memset(slots, 0, (size_t)size * sizeof(*slots));
*ix = (cbm_type_scope_index_t){.text = copy, .slots = slots, .mask = list ? 0 : size - 1};
for (char *p = copy; p && *p;) {
char *bar = strchr(p, '|');
if (bar) {
*bar = '\0';
}
char *eq = strchr(p, '=');
if (eq && eq > p && eq[1]) {
*eq = '\0';
uint32_t len = (uint32_t)(eq - p);
cbm_type_scope_entry_t e = {
.name = (uint32_t)(p - copy), .len = len, .qn = (uint32_t)(eq + 1 - copy)};
uint32_t at = list ? 0 : type_scope_hash(p, len) & ix->mask;
uint32_t end = list ? ix->count : UINT32_MAX;
/* the first entry of a spelling stands */
while (at < end && slots[at].len &&
!(slots[at].len == len && memcmp(copy + slots[at].name, p, len) == 0)) {
TYPE_SCOPE_INDEX_WORK(1);
at = list ? at + 1 : (at + 1) & ix->mask;
}
if (list && at == ix->count) {
slots[ix->count++] = e;
} else if (!list && !slots[at].len) {
slots[at] = e;
}
}
p = bar ? bar + 1 : NULL;
}
return ix;
}
const char *cbm_type_scope_find(const cbm_type_scope_index_t *ix, const char *name,
size_t name_len) {
if (!ix || !name || name_len == 0) {
return NULL;
}
TYPE_SCOPE_INDEX_WORK(name_len);
const cbm_type_scope_entry_t *slots = ix->slots;
if (ix->mask == 0) {
for (uint32_t i = 0; i < ix->count; i++) {
TYPE_SCOPE_INDEX_WORK(1);
if (slots[i].len == name_len && memcmp(ix->text + slots[i].name, name, name_len) == 0) {
return ix->text + slots[i].qn;
}
}
return NULL;
}
uint32_t at = type_scope_hash(name, name_len) & ix->mask;
while (slots[at].len) {
TYPE_SCOPE_INDEX_WORK(1);
if (slots[at].len == name_len && memcmp(ix->text + slots[at].name, name, name_len) == 0) {
return ix->text + slots[at].qn;
}
at = (at + 1) & ix->mask;
}
return NULL;
}
+21
View File
@@ -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
+10
View File
@@ -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) {
+288 -14
View File
@@ -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. */
+26 -2
View File
@@ -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. */
+378 -32
View File
@@ -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) {
+6
View File
@@ -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
+8
View File
@@ -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];
+58 -5
View File
@@ -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);
+10
View File
@@ -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. */
+821
View File
@@ -0,0 +1,821 @@
/*
* type_scope.c — declared types resolved once, in the scope that wrote them.
* See type_scope.h for the contract.
*
* Cost: per file, one hash of its import map, one hash of its own definitions
* (rows with lexical scopes) and one memo of the spellings it writes; per
* definition, one scan of its type texts and one walk up its enclosing defs
* that stops at the first one already walked. Every lookup is an exact hash
* probe (no scan, no short-name candidate list), so the step is linear in the
* bytes of declared type text and of the file's definition names.
*/
#include "pipeline/type_scope.h"
#include "foundation/constants.h"
#include "graph_buffer/graph_buffer.h" /* the module check of a target */
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ── Language descriptions ────────────────────────────────────────── */
/* Go: every type-like declaration has a method set (a Go alias carries its
* target through alias_target, which the registrar follows). */
static const char *const go_labels[] = {"Struct", "Interface", "Type", "Class", "Enum", NULL};
/* Python: what py_register_lsp_defs registers as a type. */
static const char *const py_labels[] = {"Class", "Interface", "Protocol", "Type", NULL};
static const cbm_type_scope_lang_t type_scope_langs[] = {
{.lang = CBM_LANG_GO,
.labels = go_labels,
.engine_qualifies_own_module = true,
.imports_bind_modules = true,
.return_types = true,
.param_types = true,
.field_types = true,
.embedded_types = true},
{.lang = CBM_LANG_PYTHON,
.quoted_names = true,
.labels = py_labels,
.engine_qualifies_own_module = false,
.lexical_scopes = true,
.return_types = true,
.param_types = true},
};
const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang) {
for (size_t i = 0; i < sizeof(type_scope_langs) / sizeof(type_scope_langs[0]); i++) {
if (type_scope_langs[i].lang == lang) {
return &type_scope_langs[i];
}
}
return NULL;
}
/* ── Work counter (test builds) ───────────────────────────────────── */
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
static _Atomic uint64_t g_type_scope_work;
uint64_t cbm_type_scope_test_work(void) {
return atomic_load_explicit(&g_type_scope_work, memory_order_relaxed);
}
#define TYPE_SCOPE_WORK(n) \
atomic_fetch_add_explicit(&g_type_scope_work, (uint64_t)(n), memory_order_relaxed)
#else
#define TYPE_SCOPE_WORK(n) ((void)0)
#endif
/* ── Per-file state ───────────────────────────────────────────────── */
/* Distinct, never-dereferenced values: "two imports bind this local to
* different targets", a memoized miss, and the two nesting verdicts. */
static char g_ambiguous_mark;
static char g_miss_mark;
static char g_nest_open_mark;
static char g_nest_local_mark;
static char g_bound_once_mark;
static char g_bound_many_mark;
static char g_overload_mark;
static char g_overload_differ_mark;
#define TYPE_SCOPE_BOUND_ONCE ((void *)&g_bound_once_mark)
#define TYPE_SCOPE_BOUND_MANY ((void *)&g_bound_many_mark)
#define TYPE_SCOPE_AMBIGUOUS ((void *)&g_ambiguous_mark)
#define TYPE_SCOPE_MISS ((void *)&g_miss_mark)
#define TYPE_SCOPE_NEST_OPEN ((void *)&g_nest_open_mark) /* module or class bodies only */
#define TYPE_SCOPE_NEST_LOCAL ((void *)&g_nest_local_mark) /* inside a function */
#define TYPE_SCOPE_OVERLOAD ((void *)&g_overload_mark) /* declared with @overload */
#define TYPE_SCOPE_OVERLOAD_DIFFER ((void *)&g_overload_differ_mark)
#define TYPE_SCOPE_ALIAS_MAX 256 /* a decorator name read through the imports */
struct cbm_type_scope_file {
const cbm_type_scope_lang_t *lang;
cbm_type_scope_t scope;
size_t scope_len; /* the module's symbol scope (a package without __init__) */
CBMHashTable *imports; /* local -> import QN, or TYPE_SCOPE_AMBIGUOUS */
CBMHashTable *memo; /* spelling -> QN, or TYPE_SCOPE_MISS */
CBMHashTable *seen; /* spelling -> serial of the last def that wrote it */
/* lexical scopes only */
CBMHashTable *defs; /* file def QN -> index + 1 into scope.file_defs */
CBMHashTable *class_binds; /* "<class QN>.<name>" a class body binds (not a def) */
CBMHashTable *overloaded; /* QN some def declares with @overload -> the return text
* all its defs share, or TYPE_SCOPE_OVERLOAD_DIFFER */
CBMHashTable *ovl_alias; /* local name a module-level `from typing import overload
* as X` binds */
CBMHashTable *tparams; /* every type parameter name the file declares */
CBMHashTable *nesting; /* def QN -> TYPE_SCOPE_NEST_OPEN / _LOCAL (memo) */
CBMHashTable *bindings; /* module-level name -> count of binding facts (1, 2+) */
bool closed; /* the module's bindings cannot be listed: no identity */
uintptr_t serial; /* the def being attached, from 1 */
const char *enclosing_class; /* the def's immediately enclosing class, or NULL */
CBMArena keys; /* memo keys and candidate strings */
};
static bool type_scope_function_label(const char *label) {
return label && (strcmp(label, "Function") == 0 || strcmp(label, "Method") == 0);
}
/* Count the module-level bindings of every name from the ordered namespace
* facts; a star import, a parse error or an incomplete record closes the
* file. */
static bool type_scope_index_module_facts(cbm_type_scope_file_t *f) {
const CBMPyNamespaceFacts *facts = f->scope.module_facts;
f->bindings = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(facts ? facts->count + 1 : 1));
if (!f->bindings) {
return false;
}
if (!facts || facts->status != CBM_PY_NS_COMPLETE) {
f->closed = true;
return true;
}
for (int i = 0; i < facts->count && !f->closed; i++) {
const CBMPyNamespaceFact *fact = &facts->items[i];
TYPE_SCOPE_WORK(1);
switch (fact->kind) {
case CBM_PY_NS_IMPORT_STAR:
f->closed = true; /* binds names nobody listed */
break;
case CBM_PY_NS_UNKNOWN:
/* An effect or a compound statement: the import map and the
* engine read past those as well. A parse error leaves the file's
* bindings unknown. */
f->closed = fact->reason == CBM_PY_NS_REASON_PARSE;
break;
case CBM_PY_NS_OWN_DEF:
case CBM_PY_NS_IMPORT_MODULE:
case CBM_PY_NS_IMPORT_NAME:
case CBM_PY_NS_SHADOW:
case CBM_PY_NS_DELETE:
if (fact->local_name && fact->local_name[0]) {
bool again = cbm_ht_get(f->bindings, fact->local_name) != NULL;
/* keys borrow the facts, which outlive the file state */
cbm_ht_set(f->bindings, fact->local_name,
again ? TYPE_SCOPE_BOUND_MANY : TYPE_SCOPE_BOUND_ONCE);
}
break;
default:
break; /* __all__ facts bind no name */
}
}
return true;
}
/* True when the module binds this head more than once. */
static bool type_scope_rebound(const cbm_type_scope_file_t *f, const char *head) {
TYPE_SCOPE_WORK(1);
return f->bindings && cbm_ht_get(f->bindings, head) == TYPE_SCOPE_BOUND_MANY;
}
/* Each name a class body binds besides its definitions, keyed as a member of
* the class ("<class QN>.<name>", the key type_scope_shadowed probes). */
static void type_scope_index_class_bindings(cbm_type_scope_file_t *f, const CBMDefinition *d) {
const char *bound = d->type_facts ? d->type_facts->class_bindings : NULL;
for (const char *p = bound; p && *p && d->qualified_name;) {
const char *bar = strchr(p, '|');
size_t len = bar ? (size_t)(bar - p) : strlen(p);
TYPE_SCOPE_WORK(len + 1);
char *key =
len ? cbm_arena_sprintf(&f->keys, "%s.%.*s", d->qualified_name, (int)len, p) : NULL;
if (key && !cbm_ht_get(f->class_binds, key)) {
cbm_ht_set(f->class_binds, key, key);
}
p = bar ? bar + 1 : p + len;
}
}
/* A name some function or class body of the file declares `global` and binds
* is rebound in the module by that body (when it runs, or at import for a
* class body): like a name the module binds twice, it gets no identity. */
static void type_scope_index_global_names(cbm_type_scope_file_t *f, const CBMDefinition *d) {
const char *names = d->type_facts ? d->type_facts->global_names : NULL;
for (const char *p = names; p && *p;) {
const char *bar = strchr(p, '|');
size_t len = bar ? (size_t)(bar - p) : strlen(p);
TYPE_SCOPE_WORK(len + 1);
char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL;
if (name) {
cbm_ht_set(f->bindings, name, TYPE_SCOPE_BOUND_MANY);
}
p = bar ? bar + 1 : p + len;
}
}
/* The local names the module's imports bind to typing's overload under another
* name (`from typing import overload as ovl`, typing_extensions too). */
static void type_scope_index_ovl_alias(cbm_type_scope_file_t *f) {
const CBMPyNamespaceFacts *facts = f->scope.module_facts;
for (int i = 0; facts && i < facts->count; i++) {
const CBMPyNamespaceFact *x = &facts->items[i];
TYPE_SCOPE_WORK(1);
if (x->kind == CBM_PY_NS_IMPORT_NAME && x->relative_level == 0 && x->local_name &&
x->module_name && x->member_name && strcmp(x->member_name, "overload") == 0 &&
(strcmp(x->module_name, "typing") == 0 ||
strcmp(x->module_name, "typing_extensions") == 0)) {
cbm_ht_set(f->ovl_alias, x->local_name, (void *)x->local_name);
}
}
}
/* Whether a decorator's text is typing's @overload: its last dotted name is
* `overload` (`@overload`, `@typing.overload`, `@t.overload`), or it is a
* plain name the module imports as typing's overload (`@ovl`). */
static bool type_scope_overload_decorator(const cbm_type_scope_file_t *f, const char *text) {
while (text && (*text == '@' || *text == ' ' || *text == '\t')) {
text++;
}
if (!text || !*text) {
return false;
}
size_t len = strcspn(text, "( \t\r\n");
const char *name = text;
for (size_t i = 0; i < len; i++) {
if (text[i] == '.') {
name = text + i + 1;
}
}
if ((size_t)(text + len - name) == strlen("overload") &&
memcmp(name, "overload", strlen("overload")) == 0) {
return true;
}
char local[TYPE_SCOPE_ALIAS_MAX];
if (name != text || len >= sizeof(local) || cbm_ht_count(f->ovl_alias) == 0) {
return false;
}
memcpy(local, text, len);
local[len] = '\0';
return cbm_ht_get(f->ovl_alias, local) != NULL;
}
/* A function with @overload declarations: callers see the overloads, which
* pick the result from the arguments, so the implementation's annotations are
* not its type at a call, nor is any one overload's -- unless all of its
* definitions declare the same return type (whichever overload a call picks,
* that is the type). Where they differ its QN takes no identity. */
static void type_scope_index_overload(cbm_type_scope_file_t *f, const CBMDefinition *d) {
for (int i = 0; d->decorators && d->decorators[i] && d->qualified_name; i++) {
TYPE_SCOPE_WORK(1);
if (type_scope_overload_decorator(f, d->decorators[i])) {
cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD);
return;
}
}
}
/* Second pass: whether the definitions of each overloaded QN agree on the
* return type text (none counts as a text of its own). */
static void type_scope_compare_overloads(cbm_type_scope_file_t *f) {
int n = cbm_ht_count(f->overloaded) ? f->scope.file_def_count : 0;
for (int i = 0; i < n; i++) {
const CBMDefinition *d = &f->scope.file_defs[i];
void *seen = d->qualified_name ? cbm_ht_get(f->overloaded, d->qualified_name) : NULL;
const char *ret = d->return_type ? d->return_type : "";
TYPE_SCOPE_WORK(strlen(ret) + 1);
if (seen == TYPE_SCOPE_OVERLOAD) {
cbm_ht_set(f->overloaded, d->qualified_name, (void *)ret);
} else if (seen && seen != TYPE_SCOPE_OVERLOAD_DIFFER && strcmp((const char *)seen, ret)) {
cbm_ht_set(f->overloaded, d->qualified_name, TYPE_SCOPE_OVERLOAD_DIFFER);
}
}
}
/* Hash the file's own definitions, its type parameter names and the names
* its class bodies bind. */
static bool type_scope_index_file_defs(cbm_type_scope_file_t *f) {
int n = f->scope.file_def_count;
f->defs = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1));
f->class_binds = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
f->overloaded = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
f->ovl_alias = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
f->tparams = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 8);
f->nesting = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(n + 1));
if (!f->defs || !f->class_binds || !f->overloaded || !f->ovl_alias || !f->tparams ||
!f->nesting || !type_scope_index_module_facts(f)) {
return false;
}
type_scope_index_ovl_alias(f);
for (int i = 0; i < n; i++) {
const CBMDefinition *d = &f->scope.file_defs[i];
if (d->qualified_name && !cbm_ht_get(f->defs, d->qualified_name)) {
TYPE_SCOPE_WORK(1);
cbm_ht_set(f->defs, d->qualified_name, (void *)(uintptr_t)(i + 1));
}
type_scope_index_class_bindings(f, d);
type_scope_index_global_names(f, d);
type_scope_index_overload(f, d);
for (const char *p = d->type_facts ? d->type_facts->type_params : NULL; p && *p;) {
const char *bar = strchr(p, '|');
size_t len = bar ? (size_t)(bar - p) : strlen(p);
char *name = len ? cbm_arena_strndup(&f->keys, p, len) : NULL;
TYPE_SCOPE_WORK(len + 1);
if (name && !cbm_ht_get(f->tparams, name)) {
cbm_ht_set(f->tparams, name, name);
}
p = bar ? bar + 1 : p + len;
}
}
type_scope_compare_overloads(f);
return true;
}
cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang,
const cbm_type_scope_t *scope) {
if (!lang || !scope || !scope->reg || !scope->module_qn) {
return NULL;
}
cbm_type_scope_file_t *f = cbm_calloc(CBM_MEM_CLASS_EXTRACT, sizeof(*f));
if (!f) {
return NULL;
}
f->lang = lang;
f->scope = *scope;
f->scope_len = cbm_fqn_symbol_scope_len(scope->module_qn);
f->imports = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, (uint32_t)(scope->imp_count + 1));
f->memo = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32);
f->seen = cbm_ht_create_in(CBM_MEM_CLASS_EXTRACT, 32);
cbm_arena_init_lazy(&f->keys, CBM_SZ_4K);
if (!f->imports || !f->memo || !f->seen ||
(lang->lexical_scopes && !type_scope_index_file_defs(f))) {
cbm_type_scope_file_end(f);
return NULL;
}
for (int i = 0; i < scope->imp_count; i++) {
const char *key = scope->imp_keys ? scope->imp_keys[i] : NULL;
const char *val = scope->imp_vals ? scope->imp_vals[i] : NULL;
if (!key || !val || !key[0]) {
continue;
}
TYPE_SCOPE_WORK(1);
void *prev = cbm_ht_get(f->imports, key);
if (!prev) {
cbm_ht_set(f->imports, key, (void *)val);
} else if (prev != TYPE_SCOPE_AMBIGUOUS && strcmp((const char *)prev, val) != 0) {
cbm_ht_set(f->imports, key, TYPE_SCOPE_AMBIGUOUS);
}
}
return f;
}
void cbm_type_scope_file_end(cbm_type_scope_file_t *file) {
if (!file) {
return;
}
cbm_ht_free(file->imports); /* NULL-safe */
cbm_ht_free(file->memo);
cbm_ht_free(file->seen);
cbm_ht_free(file->defs);
cbm_ht_free(file->class_binds);
cbm_ht_free(file->overloaded);
cbm_ht_free(file->ovl_alias);
cbm_ht_free(file->tparams);
cbm_ht_free(file->nesting);
cbm_ht_free(file->bindings);
cbm_arena_destroy(&file->keys);
cbm_free(CBM_MEM_CLASS_EXTRACT, file);
}
/* ── Resolution ───────────────────────────────────────────────────── */
/* `qn` when it names a project definition of an allowed label, else NULL. A
* QN the graph holds as a module (a class and a module of one QN) is none:
* the two share their members' QNs. */
static const char *type_scope_target(const cbm_type_scope_file_t *f, const char *qn) {
TYPE_SCOPE_WORK(1);
const char *label = cbm_registry_label_of(f->scope.reg, qn);
if (!label) {
return NULL;
}
for (const char *const *l = f->lang->labels; *l; l++) {
if (strcmp(*l, label) == 0) {
const cbm_gbuf_node_t *node = f->lang->lexical_scopes && f->scope.graph
? cbm_gbuf_find_by_qn(f->scope.graph, qn)
: NULL;
return node && node->label && strcmp(node->label, "Module") == 0 ? NULL : qn;
}
}
return NULL;
}
/* The candidate QN for `dotted` through the import that binds its head, or
* NULL. *bound reports whether an import binds the head at all (then the
* file's own module does not decide the name). An import names a project
* definition or nothing: a path that names no definition (a module outside
* the project, a name a package re-exports) is no answer. */
static const char *type_scope_via_import(cbm_type_scope_file_t *f, const char *dotted,
size_t head_len, bool *bound, bool *ambiguous) {
*bound = false;
*ambiguous = false;
const char *dot = dotted[head_len] == '.' ? dotted + head_len : NULL;
if (!dot && f->lang->imports_bind_modules) {
return NULL; /* a bare name never resolves through a package import */
}
char head[CBM_SZ_256];
if (head_len == 0 || head_len >= sizeof(head)) {
return NULL;
}
memcpy(head, dotted, head_len);
head[head_len] = '\0';
TYPE_SCOPE_WORK(1);
void *v = cbm_ht_get(f->imports, head);
if (!v) {
return NULL;
}
*bound = true;
if (v == TYPE_SCOPE_AMBIGUOUS) {
*ambiguous = true;
return NULL;
}
const char *val = (const char *)v;
if (dot) {
/* `pkg.T`: the import binds the module, the rest names inside it. */
const char *qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, dot + 1);
return qn ? type_scope_target(f, qn) : NULL;
}
/* A bare name: the import binds the type itself, or (a module-valued
* binding, Python's `from m import T` whose edge names the module) the
* type of that name inside it. Both existing and differing is no answer. */
const char *direct = type_scope_target(f, val);
const char *member_qn = cbm_arena_sprintf(&f->keys, "%s.%s", val, head);
const char *member = member_qn ? type_scope_target(f, member_qn) : NULL;
if (direct && member && strcmp(direct, member) != 0) {
*ambiguous = true;
return NULL;
}
return direct ? direct : member;
}
/* The memo / seen key of a spelling: the spelling itself, NUL-terminated in a
* caller buffer (a name too long for it has no identity). */
static bool type_scope_key(const char *spelling, size_t len, char *buf, size_t bufsz) {
if (len == 0 || len >= bufsz) {
return false;
}
memcpy(buf, spelling, len);
buf[len] = '\0';
return true;
}
static size_t type_scope_head_len(const char *spelling, size_t len) {
const char *dot = memchr(spelling, '.', len);
return dot ? (size_t)(dot - spelling) : len;
}
const char *cbm_type_scope_resolve(cbm_type_scope_file_t *f, const char *spelling, size_t len) {
char probe[CBM_SZ_512];
if (!f || !spelling || !type_scope_key(spelling, len, probe, sizeof(probe))) {
return NULL;
}
TYPE_SCOPE_WORK(1);
void *memo = cbm_ht_get(f->memo, probe);
if (memo) {
return memo == TYPE_SCOPE_MISS ? NULL : (const char *)memo;
}
char *key = cbm_arena_strndup(&f->keys, spelling, len);
if (!key) {
return NULL;
}
const char *result = NULL;
const char *dotted = key; /* `T` or `pkg.T`, NUL-terminated */
size_t head_len = type_scope_head_len(dotted, len);
if (f->bindings) {
/* A head the module binds more than once has no one answer. */
char head[CBM_SZ_256];
if (!type_scope_key(dotted, head_len, head, sizeof(head)) || type_scope_rebound(f, head)) {
cbm_ht_set(f->memo, key, TYPE_SCOPE_MISS);
return NULL;
}
}
bool bound = false;
bool ambiguous = false;
const char *via_import = type_scope_via_import(f, dotted, head_len, &bound, &ambiguous);
/* A Python package's names live under the package, not its __init__. */
const char *mod = f->scope.module_qn;
int scope_len = (int)f->scope_len;
const char *own_qn = cbm_arena_sprintf(&f->keys, "%.*s.%s", scope_len, mod, dotted);
const char *own = own_qn ? type_scope_target(f, own_qn) : NULL;
if (bound && !ambiguous) {
/* The import decides, unless the own module binds the head as well
* (any definition of that name: a class, a function, a TypeVar
* variable): two bindings of one name, whose winner is source order. */
const char *head_qn =
cbm_arena_sprintf(&f->keys, "%.*s.%.*s", scope_len, mod, (int)head_len, dotted);
TYPE_SCOPE_WORK(1);
bool own_binds = head_qn && cbm_registry_exists(f->scope.reg, head_qn);
bool same = via_import && own && strcmp(own, via_import) == 0;
result = own_binds && !same ? NULL : via_import;
} else if (!bound) {
result = own;
}
cbm_ht_set(f->memo, key, result ? (void *)result : TYPE_SCOPE_MISS);
return result;
}
/* ── The def's own enclosing scopes (lexical rows) ───────────────── */
/* Whether the definition `qn` lies inside a function. inside(q) is true when
* q's parent is a function, false when the parent is the module, and
* inside(parent) when the parent is a class of this file; a parent QN this
* file does not define is no proof of a module or class body, so it counts as
* inside (no identity). The walk stops at the first ancestor already judged,
* and every class it passes is judged on the way, so each definition of the
* file is walked through once. */
static bool type_scope_function_local(cbm_type_scope_file_t *f, const char *qn) {
const char **passed = NULL; /* classes walked through, not yet judged */
int count = 0;
int cap = 0;
bool inside = true;
const char *cur = qn;
for (;;) {
const char *dot = strrchr(cur, '.');
size_t parent_len = dot ? (size_t)(dot - cur) : 0;
if (parent_len <= f->scope_len) {
inside = false; /* cur is a module-level definition */
break;
}
char *parent = cbm_arena_strndup(&f->keys, cur, parent_len);
TYPE_SCOPE_WORK(parent_len + 1);
if (!parent) {
break;
}
void *known = cbm_ht_get(f->nesting, parent);
if (known) {
inside = known == TYPE_SCOPE_NEST_LOCAL;
break;
}
uintptr_t at = (uintptr_t)cbm_ht_get(f->defs, parent);
if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) {
break; /* inside a function, or under a parent this file lacks */
}
if (count == cap) {
int grown_cap = cap ? cap * 2 : 8;
const char **grown =
(const char **)cbm_arena_alloc(&f->keys, (size_t)grown_cap * sizeof(*grown));
if (!grown) {
break;
}
if (count) {
memcpy(grown, passed, (size_t)count * sizeof(*grown));
}
passed = grown;
cap = grown_cap;
}
passed[count++] = parent; /* a class: inside(cur) == inside(parent) */
cur = parent;
}
for (int i = 0; i < count; i++) {
cbm_ht_set(f->nesting, passed[i], inside ? TYPE_SCOPE_NEST_LOCAL : TYPE_SCOPE_NEST_OPEN);
}
return inside;
}
/* The def's immediately enclosing class: its parent QN when that is a
* non-function definition of this file, else NULL. */
static const char *type_scope_enclosing_class(cbm_type_scope_file_t *f, const char *qn) {
const char *dot = strrchr(qn, '.');
size_t parent_len = dot ? (size_t)(dot - qn) : 0;
if (parent_len <= f->scope_len) {
return NULL;
}
char *parent = cbm_arena_strndup(&f->keys, qn, parent_len);
TYPE_SCOPE_WORK(parent_len + 1);
uintptr_t at = parent ? (uintptr_t)cbm_ht_get(f->defs, parent) : 0;
if (!at || type_scope_function_label(f->scope.file_defs[at - 1].label)) {
return NULL;
}
return parent;
}
/* True when the def's own scopes bind the head of this spelling before the
* module does: a type parameter the file declares, or a name the enclosing
* class body declares (a nested definition) or binds (an assignment, an
* import, a loop or with or except target...). */
static bool type_scope_shadowed(cbm_type_scope_file_t *f, const char *name, size_t len) {
size_t head_len = type_scope_head_len(name, len);
char head[CBM_SZ_256];
if (!type_scope_key(name, head_len, head, sizeof(head))) {
return true;
}
TYPE_SCOPE_WORK(1);
if (cbm_ht_get(f->tparams, head)) {
return true;
}
if (!f->enclosing_class) {
return false;
}
const char *member = cbm_arena_sprintf(&f->keys, "%s.%s", f->enclosing_class, head);
TYPE_SCOPE_WORK(1);
return !member || cbm_ht_get(f->defs, member) != NULL ||
cbm_ht_get(f->class_binds, member) != NULL;
}
/* ── Reduction of a type text to the names it writes ──────────────── */
static bool type_scope_ident_start(unsigned char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c >= 0x80;
}
static bool type_scope_ident_char(unsigned char c) {
return type_scope_ident_start(c) || (c >= '0' && c <= '9');
}
typedef void (*type_scope_name_fn)(const char *name, size_t len, void *ud);
/* Call fn for every type name the text writes: a run of identifier
* characters joined by `.`. A quoted run is a literal (skipped) unless
* quoted_names; a name that is only a member access (one `.` before it) or a
* label (one `:` after it: a property, a named parameter) is not a type
* name. */
static void type_scope_names(const cbm_type_scope_lang_t *lang, const char *text,
type_scope_name_fn fn, void *ud) {
size_t n = text ? strlen(text) : 0;
TYPE_SCOPE_WORK(n);
size_t i = 0;
while (i < n) {
unsigned char c = (unsigned char)text[i];
if ((c == '"' || c == '\'' || c == '`') && !lang->quoted_names) {
size_t close = i + 1;
while (close < n && text[close] != (char)c) {
close++;
}
i = close < n ? close + 1 : n;
continue;
}
if (!type_scope_ident_start(c)) {
i++;
continue;
}
size_t start = i;
while (i < n && type_scope_ident_char((unsigned char)text[i])) {
i++;
}
for (;;) {
if (i + 1 < n && text[i] == '.' && type_scope_ident_start((unsigned char)text[i + 1])) {
i++;
} else {
break;
}
while (i < n && type_scope_ident_char((unsigned char)text[i])) {
i++;
}
}
bool member = start > 0 && text[start - 1] == '.' && (start < 2 || text[start - 2] != '.');
size_t after = i;
while (after < n && text[after] == ' ') {
after++;
}
bool label = after < n && text[after] == ':' && (after + 1 >= n || text[after + 1] != ':');
if (!member && !label) {
fn(text + start, i - start, ud);
}
}
}
/* ── Attaching identities to a definition ─────────────────────────── */
typedef struct {
cbm_type_scope_file_t *file;
char *buf; /* "spelling=QN|..." being built (heap) */
size_t len;
size_t cap;
bool failed;
} type_scope_build_t;
/* True when the current def already wrote this spelling (one hash probe; the
* seen table remembers, per spelling, the last def that wrote it). */
static bool type_scope_seen(cbm_type_scope_file_t *f, const char *name, size_t len) {
char probe[CBM_SZ_512];
if (!type_scope_key(name, len, probe, sizeof(probe))) {
return true; /* too long to key: never an identity */
}
TYPE_SCOPE_WORK(1);
void *last = cbm_ht_get(f->seen, probe);
if (last == (void *)f->serial) {
return true;
}
const char *key = last ? cbm_ht_get_key(f->seen, probe) : cbm_arena_strdup(&f->keys, probe);
if (key) {
cbm_ht_set(f->seen, key, (void *)f->serial);
}
return false;
}
static bool type_scope_append(type_scope_build_t *b, const char *s, size_t n) {
if (b->len + n + 1 > b->cap) {
size_t cap = b->cap ? b->cap * 2 : 128;
while (cap < b->len + n + 1) {
cap *= 2;
}
char *grown = cbm_realloc(CBM_MEM_CLASS_EXTRACT, b->buf, cap);
if (!grown) {
b->failed = true;
return false;
}
b->buf = grown;
b->cap = cap;
}
memcpy(b->buf + b->len, s, n);
b->len += n;
b->buf[b->len] = '\0';
return true;
}
static void type_scope_on_name(const char *name, size_t len, void *ud) {
type_scope_build_t *b = (type_scope_build_t *)ud;
if (b->failed || type_scope_seen(b->file, name, len)) {
return;
}
if (b->file->lang->lexical_scopes && type_scope_shadowed(b->file, name, len)) {
return;
}
const char *qn = cbm_type_scope_resolve(b->file, name, len);
if (!qn) {
return;
}
if (b->file->lang->engine_qualifies_own_module) {
/* The engine already qualifies this spelling to exactly this QN. */
const char *mod = b->file->scope.module_qn;
size_t ml = strlen(mod);
if (strncmp(qn, mod, ml) == 0 && qn[ml] == '.' && strlen(qn + ml + 1) == len &&
memcmp(qn + ml + 1, name, len) == 0) {
return;
}
}
if ((b->len && !type_scope_append(b, "|", 1)) || !type_scope_append(b, name, len) ||
!type_scope_append(b, "=", 1) || !type_scope_append(b, qn, strlen(qn))) {
return;
}
}
/* Each '|'-separated piece of `text`; with after_colon, only the part after
* the first ':' of each piece (field_defs' "name:type"). */
static void type_scope_scan_pieces(type_scope_build_t *b, const char *text, bool after_colon) {
if (!text || !text[0]) {
return;
}
size_t n = strlen(text);
char *copy = cbm_arena_strndup(&b->file->keys, text, n);
if (!copy) {
return;
}
char *piece = copy;
for (size_t i = 0; i <= n; i++) {
if (copy[i] != '|' && copy[i] != '\0') {
continue;
}
copy[i] = '\0';
const char *t = piece;
if (after_colon) {
const char *colon = strchr(piece, ':');
t = colon ? colon + 1 : NULL;
}
if (t && t[0]) {
type_scope_names(b->file->lang, t, type_scope_on_name, b);
}
piece = copy + i + 1;
}
}
void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def) {
if (!file || !arena || !def) {
return;
}
const cbm_type_scope_lang_t *lang = file->lang;
file->serial++;
file->enclosing_class = NULL;
if (lang->lexical_scopes) {
/* A module whose bindings cannot be listed (a star import, an effect
* binding unknown names), and a def inside a function (it sees locals
* the step cannot list): neither gets one. */
if (file->closed || !def->qualified_name ||
type_scope_function_local(file, def->qualified_name) ||
cbm_ht_get(file->overloaded, def->qualified_name) == TYPE_SCOPE_OVERLOAD_DIFFER) {
return; /* (an overloaded function: type_scope_index_overload) */
}
file->enclosing_class = type_scope_enclosing_class(file, def->qualified_name);
}
type_scope_build_t b = {.file = file};
if (lang->return_types) {
type_scope_scan_pieces(&b, def->return_types, false);
}
if (lang->param_types && def->signature_param_types) {
for (int i = 0; i < def->signature_param_count; i++) {
const char *t = def->signature_param_types[i];
if (t && strcmp(t, "?") != 0) {
type_scope_names(lang, t, type_scope_on_name, &b);
}
}
}
if (lang->field_types) {
type_scope_scan_pieces(&b, def->field_defs, true);
}
if (lang->embedded_types) {
type_scope_scan_pieces(&b, def->embedded_types, false);
}
if (b.len > 0 && !b.failed) {
def->type_scope = cbm_arena_strndup(arena, b.buf, b.len);
}
cbm_free(CBM_MEM_CLASS_EXTRACT, b.buf);
}
+137
View File
@@ -0,0 +1,137 @@
/*
* type_scope.h — declared types resolved once, in the scope that wrote them.
*
* A definition's declared types (its return type, parameter types, field
* types) travel to other files as source text inside CBMLSPDef. Each engine
* used to qualify that text against the defining MODULE only, so a type the
* defining file imported from a third file became `<defining module>.<Name>`,
* a name nobody registered, and every call through it was lost.
*
* This step resolves every type name such a text mentions ONCE, in the scope
* of the file that wrote it: the file's own module, then what its imports
* bind. A name gets an identity only when that scope gives exactly one answer
* and that answer is a project definition of a type label the consuming
* engine registers. A name that is not found, is ambiguous, is shadowed by a
* scope the step cannot see into, or is bound to anything outside the project
* keeps no identity, and the engine keeps doing what it did before. There is
* no project-wide name match here.
*
* The result is stored with the definition (CBMLSPDef.type_scope, persisted in
* the file's LSP surface) as "spelling=QN|spelling=QN", the spelling exactly
* as the type text writes it. Only identities the engine cannot derive itself
* are stored: where the engine already qualifies a bare name to
* `<module>.<spelling>`, a name the file's own module declares is left out.
* The engines read an identity through cbm_type_scope_find (lsp/type_rep.h)
* wherever they would otherwise qualify a type name against the module.
*
* An identity depends on two inputs: the writing file's own content (its type
* texts, its imports, its module) and which project definitions are types.
* The surface hash covers the first and leaves the identities themselves out;
* the incremental planner declines a repair whenever the second changes
* (pipeline_incremental.c, closure_identity_decline).
*
* What is language-specific is a description (cbm_type_scope_lang_t): which
* definition labels an identity may name, how the language's imports and
* scopes bind names, and which CBMLSPDef fields carry raw type text for that
* language. A further language plugs in by adding its row.
*/
#ifndef CBM_PIPELINE_TYPE_SCOPE_H
#define CBM_PIPELINE_TYPE_SCOPE_H
#include "cbm.h"
#include "foundation/arena.h"
#include "foundation/hash_table.h"
#include "lsp/go_lsp.h" /* CBMLSPDef */
#include "pipeline/pipeline.h"
#include <stdbool.h>
#include <stddef.h>
/* How one language writes type names, and what its engine consumes. */
typedef struct {
CBMLanguage lang;
/* A name inside quotes is a type name (Python forward references); in
* every other language a quoted run is a literal and is skipped. */
bool quoted_names;
/* Labels of the definitions an identity may name: the type kinds the
* engine registers and can look members up on. NULL-terminated. */
const char *const *labels;
/* The engine qualifies a bare name against the defining module itself
* (Go), so an own-module identity need not be stored. Python's cross
* registrar keeps the bare spelling: it is stored there. */
bool engine_qualifies_own_module;
/* An import binds a module only (Go: a package), so only a qualified
* `pkg.T` resolves through it and a bare name never does. Without it
* (Python) `from m import T` binds the type itself. */
bool imports_bind_modules;
/* Python: an annotation is evaluated in the def's enclosing scopes before
* the module. A def nested in a function sees that function's locals,
* which the step cannot list, so it gets no identity; a name the
* immediately enclosing class body declares or binds (any binding:
* CBMDefTypeFacts.class_bindings) and a PEP 695 type parameter of the
* file get none, and neither does a name the module binds more than once
* (cbm_type_scope_t.module_facts), nor a type whose QN the graph holds as
* a module (a class `Thing` in pkg/a/__init__.py beside pkg/a/Thing.py:
* their members share QNs, so no member answer is that class's). */
bool lexical_scopes;
/* Which CBMLSPDef texts hold raw type spellings for this language. */
bool return_types;
bool param_types;
bool field_types; /* "name:type|name:type" in field_defs */
bool embedded_types; /* "|"-joined raw spellings in embedded_types */
} cbm_type_scope_lang_t;
/* The description for `lang`, or NULL when no engine consumes identities. */
const cbm_type_scope_lang_t *cbm_type_scope_lang(CBMLanguage lang);
/* One file's scope: the project's names, the file's module, what the file's
* imports bind (local name -> import QN, the LSP import map), and for a row
* with lexical_scopes the file's own definitions. */
typedef struct {
const cbm_registry_t *reg;
const char *module_qn;
const char *const *imp_keys;
const char *const *imp_vals;
int imp_count;
/* lexical_scopes only: the file's extraction definitions, in any order
* (their QNs, labels and type facts); NULL with def_count 0 = none. */
const CBMDefinition *file_defs;
int file_def_count;
/* lexical_scopes only: the module's ordered namespace facts. Without a
* complete record, with a star import or with a parse error the file gets
* no identity; a name the module binds twice (two imports, an import and
* a definition, a later assignment) gets none. */
const CBMPyNamespaceFacts *module_facts;
/* lexical_scopes only: the graph the import map reads (its nodes'
* labels), so a QN that is a module's gets no identity; NULL = not
* checked. */
const struct cbm_gbuf *graph;
} cbm_type_scope_t;
/* Per-file working state: the import map by key, the file's own scopes, and
* a memo of the spellings already resolved. Build once per file, free after
* the file's defs. */
typedef struct cbm_type_scope_file cbm_type_scope_file_t;
cbm_type_scope_file_t *cbm_type_scope_file_begin(const cbm_type_scope_lang_t *lang,
const cbm_type_scope_t *scope);
void cbm_type_scope_file_end(cbm_type_scope_file_t *file);
/* The identity of one spelling (`T`, `pkg.T`) in the file's module and import
* scope, or NULL (the def's own enclosing scopes are applied by the attach).
* The returned QN is owned by the file state (valid until file_end). Never a
* short-name guess. */
const char *cbm_type_scope_resolve(cbm_type_scope_file_t *file, const char *spelling, size_t len);
/* Set def->type_scope from the def's type texts (per the description), or
* leave it NULL when no name the def writes needs an identity. The string is
* allocated in `arena`. */
void cbm_type_scope_attach(cbm_type_scope_file_t *file, CBMArena *arena, CBMLSPDef *def);
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
/* Work counter for the growth tests: one per byte of type text scanned, per
* hash probe and per enclosing-scope step. Test builds only. */
uint64_t cbm_type_scope_test_work(void);
#endif
#endif /* CBM_PIPELINE_TYPE_SCOPE_H */
+5 -1
View File
@@ -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",
+4
View File
@@ -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);
+14 -14
View File
@@ -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);
File diff suppressed because it is too large Load Diff