Merge origin/main into fix/scala-companion-objects

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
This commit is contained in:
Martin Vogel
2026-11-27 03:44:34 +01:00
46 changed files with 13304 additions and 662 deletions
+4 -3
View File
@@ -579,7 +579,8 @@ PIPELINE_SRCS = \
src/pipeline/pass_ensemble_routing.c \
src/pipeline/pass_pkgmap.c \
src/pipeline/site_bind.c \
src/pipeline/include_path.c
src/pipeline/include_path.c \
src/pipeline/scope_closure.c
# SimHash / MinHash module
SIMHASH_SRCS = src/simhash/minhash.c
@@ -875,7 +876,7 @@ TEST_DISCOVER_SRCS = \
TEST_GRAPH_BUFFER_SRCS = tests/test_graph_buffer.c
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c tests/test_site_bind.c tests/test_scope_facts.c tests/test_include_path.c
TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_doc_mentions_perl.c tests/test_doc_mentions_ts.c tests/test_doc_mentions_php.c tests/test_doc_mentions_c.c tests/test_diagrams.c tests/test_openapi.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_type_scope.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c tests/test_site_bind.c tests/test_scope_facts.c tests/test_include_path.c tests/test_scope_closure.c
TEST_WATCHER_SRCS = tests/test_watcher.c tests/test_svn_state.c
@@ -889,7 +890,7 @@ TEST_GO_LSP_SRCS = tests/test_go_lsp.c
TEST_C_LSP_SRCS = tests/test_c_lsp.c
TEST_PHP_LSP_SRCS = tests/test_php_lsp.c
TEST_PHP_LSP_SRCS = tests/test_php_lsp.c tests/test_member_walk.c tests/test_php_member_walk.c
TEST_CS_LSP_SRCS = tests/test_cs_lsp.c
+39 -7
View File
@@ -336,7 +336,7 @@ 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
/* Go, Python and PHP 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:
@@ -344,9 +344,10 @@ typedef struct {
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. */
/* Facts of one Go, Python or PHP definition that no graph property carries;
* only the cross-file step reads them (src/pipeline/type_scope.h, the Go,
* Python and PHP cross registrars, the member lookup lsp/member_walk.h).
* 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
@@ -372,6 +373,18 @@ typedef struct CBMDefTypeFacts {
* 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;
/* PHP class, interface, trait or enum (the member lookup): one kind letter
* per base_classes entry ('e' extends, 'i' implements), plus a trailing
* '+' when bases past the extractor's cap were not recorded; NULL = the
* kinds are unknown. */
const char *base_kinds;
/* PHP: the traits the body uses, as written (they stay out of
* base_classes, which makes INHERITS edges), one kind letter each ('t'),
* and the rules those uses apply to their members (`insteadof` / `as`,
* encoded by extract_defs.c extract_php_member_bases). */
const char **mixins;
const char *mixin_kinds;
const char *member_rules;
} CBMDefTypeFacts;
/* extra_props key of a generated member, one the compiler writes and the
@@ -800,6 +813,10 @@ enum {
CBM_SCOPE_REEXPORT = 1u << 4, /* INCLUDE: its names reach this file's includers */
/* inside a parse error: may or may not hold where a later name is used */
CBM_SCOPE_CONDITIONAL = 1u << 5,
/* QREF: on the way out, the first component names a symbol that is no
* type (Protobuf: a method of the enclosing service, a service of the
* file): protoc resolves the reference to it and rejects the file */
CBM_SCOPE_NOT_A_TYPE = 1u << 6,
};
typedef struct {
@@ -807,7 +824,10 @@ typedef struct {
/* DEF: the full name where the row has packages or nesting (Protobuf:
* package, enclosing messages, name: "a.b.Outer.Inner"). INCLUDE: the
* importing file's package ("" when none), which its references are
* relative to. NULL elsewhere. */
* relative to. QREF: the innermost scope around the reference, its first
* scope to search (Protobuf: the enclosing message's full name, or the
* file's package outside any message); NULL when it is unknown. NULL
* elsewhere. */
const char *qual;
uint32_t pos; /* byte offset after which the event is in effect */
int32_t index; /* into defs (DEF) or imports (INCLUDE); QREF: start byte; else -1 */
@@ -902,7 +922,13 @@ typedef struct {
* kind / group / name / ns; `path` is
* the patch file (as written, relative to the kustomization), NULL for an
* inline patch. kind and name both NULL: the patch file's documents name
* them. def_index -1: the kustomization itself is the source. */
* them. def_index -1: the kustomization itself is the source.
* CBM_K8S_FACT_FILE: a kustomization reads the file `path` (as written,
* relative to the kustomization) at `line`, named by `via`: an entry of a
* configMapGenerator's or secretGenerator's `files` (the path after
* `key=`), `envs` or `env`, or of `configurations`. The file is input to
* the build, not a member of it. def_index -1: the kustomization itself
* is the source. */
typedef enum {
CBM_K8S_FACT_REF = 0,
CBM_K8S_FACT_CRD,
@@ -911,7 +937,8 @@ typedef enum {
CBM_K8S_FACT_SOURCE,
CBM_K8S_FACT_IMAGE,
CBM_K8S_FACT_ENV,
CBM_K8S_FACT_PATCH
CBM_K8S_FACT_PATCH,
CBM_K8S_FACT_FILE
} CBMK8sFactKind;
typedef struct {
CBMK8sFactKind fact;
@@ -1306,6 +1333,11 @@ typedef struct {
/* The preprocessed second view only: the raw view's test definitions and
* the line map (cbm_test_span_owner_qn). NULL in every raw view. */
const CBMTestSpanMap *pp_test_spans;
/* PHP: the file's namespace changes and class `use` aliases in byte order,
* and how far a class's trait names have been qualified with them
* (extract_defs.c php_names_at); NULL until a class uses a trait;
* allocated in `scratch`. */
void *php_names;
} CBMExtractCtx;
/* Internal configured-definition seams. No declarations pointer enters a result. */
+526
View File
@@ -4561,6 +4561,516 @@ static const char **extract_php_bases(CBMArena *a, TSNode node, const char *sour
return result;
}
/* PHP, for the member lookup (lsp/member_walk.h): the kind of each
* base_classes entry, in the order extract_php_bases records them ('e' for
* `extends`, 'i' for `implements`; a trailing '+' when bases past its cap were
* not recorded), and the traits the body uses with the adaptation clauses of
* those uses. Traits stay out of base_classes: that list makes INHERITS edges.
* Rules, ';'-separated: "x T m U" (T::m insteadof U, one per excluded U) and
* "a T m alias" ("a - m alias" when the trait is not named); an `as` that only
* changes visibility renames nothing. */
/* The namespace and class `use` aliases in force where a PHP class is
* written, so a trait name can be qualified there, by PHP's own compile-time
* rule, before it reaches another file's resolver. */
typedef struct {
const char *ns; /* "App\\Models"; NULL in the global namespace */
const char **alias; /* local names */
const char **target; /* their full names, `\`-separated, no leading `\` */
int count;
int cap;
} php_names_t;
static bool php_names_add(CBMArena *a, php_names_t *n, const char *alias, const char *target) {
if (!alias || !alias[0] || !target || !target[0]) {
return true;
}
if (n->count == n->cap) {
int cap = n->cap ? n->cap * 2 : 8;
const char **al = (const char **)cbm_arena_alloc(a, (size_t)cap * sizeof(*al));
const char **tg = (const char **)cbm_arena_alloc(a, (size_t)cap * sizeof(*tg));
if (!al || !tg) {
return false;
}
if (n->count) {
memcpy(al, n->alias, (size_t)n->count * sizeof(*al));
memcpy(tg, n->target, (size_t)n->count * sizeof(*tg));
}
n->alias = al;
n->target = tg;
n->cap = cap;
}
n->alias[n->count] = alias;
n->target[n->count] = target[0] == '\\' ? target + 1 : target;
n->count++;
return true;
}
/* Whether `word` (lower case) starts at p, as a whole word, in any case. */
static bool php_word_at(const char *p, const char *end, const char *word) {
size_t n = strlen(word);
if ((size_t)(end - p) < n) {
return false;
}
for (size_t i = 0; i < n; i++) {
if (tolower((unsigned char)p[i]) != word[i]) {
return false;
}
}
return p + n == end || !(isalnum((unsigned char)p[n]) || p[n] == '_');
}
/* `use function ...` / `use const ...` (a declaration, or one clause of a
* group): not a class name. Read from the text: the keyword's node shape
* differs between grammar versions. */
static bool php_use_is_class(TSNode node, const char *source) {
const char *p = source + ts_node_start_byte(node);
const char *end = source + ts_node_end_byte(node);
if (php_word_at(p, end, "use")) {
p += 3;
}
while (p < end && isspace((unsigned char)*p)) {
p++;
}
return !php_word_at(p, end, "function") && !php_word_at(p, end, "const");
}
static void php_names_clause(CBMArena *a, TSNode clause, const char *source, const char *prefix,
php_names_t *n) {
char *name = NULL;
char *alias = NULL;
uint32_t cc = ts_node_named_child_count(clause);
for (uint32_t i = 0; i < cc; i++) {
TSNode c = ts_node_named_child(clause, i);
const char *k = ts_node_type(c);
if (strcmp(k, "qualified_name") == 0 || strcmp(k, "name") == 0) {
if (!name) {
name = cbm_node_text(a, c, source);
} else if (!alias) {
alias = cbm_node_text(a, c, source);
}
} else if (strcmp(k, "namespace_aliasing_clause") == 0) {
TSNode an = cbm_find_child_by_kind(c, "name");
if (!ts_node_is_null(an)) {
alias = cbm_node_text(a, an, source);
}
}
}
if (!name || !name[0]) {
return;
}
const char *full = prefix && prefix[0] ? cbm_arena_sprintf(a, "%s\\%s", prefix, name) : name;
if (!alias) {
const char *last = strrchr(full, '\\');
alias = (char *)(last ? last + 1 : full);
}
(void)php_names_add(a, n, alias, full);
}
static void php_names_use(CBMArena *a, TSNode decl, const char *source, php_names_t *n) {
if (!php_use_is_class(decl, source)) {
return;
}
const char *prefix = NULL;
uint32_t nc = ts_node_named_child_count(decl);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(decl, i);
const char *k = ts_node_type(c);
if (strcmp(k, "namespace_use_clause") == 0) {
php_names_clause(a, c, source, NULL, n);
} else if (strcmp(k, "namespace_name") == 0 || strcmp(k, "qualified_name") == 0 ||
strcmp(k, "name") == 0) {
prefix = cbm_node_text(a, c, source); /* use App\{A, B as C}; */
} else if (strcmp(k, "namespace_use_group") == 0) {
uint32_t gc = ts_node_named_child_count(c);
for (uint32_t j = 0; j < gc; j++) {
TSNode g = ts_node_named_child(c, j);
const char *gk = ts_node_type(g);
if ((strcmp(gk, "namespace_use_clause") == 0 ||
strcmp(gk, "namespace_use_group_clause") == 0) &&
php_use_is_class(g, source)) {
php_names_clause(a, g, source, prefix, n);
}
}
}
}
}
static const char *php_namespace_name(CBMArena *a, TSNode ns_def, const char *source) {
TSNode nn = cbm_find_child_by_kind(ns_def, "namespace_name");
return ts_node_is_null(nn) ? NULL : cbm_node_text(a, nn, source);
}
/* The file's namespace changes and class aliases in byte order (one cursor
* pass per file), and the names in force up to the last class asked: classes
* come in source order, so each one only applies the events before it. */
enum { PHP_EV_NS = 1, PHP_EV_USE = 2 };
typedef struct {
uint32_t at;
uint8_t kind;
const char *a; /* NS: the namespace (NULL: global); USE: the alias */
const char *b; /* USE: the target */
} php_name_ev_t;
typedef struct {
php_name_ev_t *ev;
int count;
int cap;
int next;
uint32_t last_at;
php_names_t cur;
} php_names_state_t;
static bool php_ev_add(CBMArena *a, php_names_state_t *st, uint32_t at, uint8_t kind, const char *x,
const char *y) {
if (st->count == st->cap) {
int cap = st->cap ? st->cap * 2 : 16;
php_name_ev_t *ev = (php_name_ev_t *)cbm_arena_alloc(a, (size_t)cap * sizeof(*ev));
if (!ev) {
return false;
}
if (st->count) {
memcpy(ev, st->ev, (size_t)st->count * sizeof(*ev));
}
st->ev = ev;
st->cap = cap;
}
php_name_ev_t *e = &st->ev[st->count++];
e->at = at;
e->kind = kind;
e->a = x;
e->b = y;
return true;
}
static void php_ev_uses(CBMArena *a, php_names_state_t *st, TSNode decl, const char *source) {
php_names_t one;
memset(&one, 0, sizeof(one));
php_names_use(a, decl, source, &one);
for (int i = 0; i < one.count; i++) {
(void)php_ev_add(a, st, ts_node_start_byte(decl), PHP_EV_USE, one.alias[i], one.target[i]);
}
}
static php_names_state_t *php_names_build(CBMArena *a, TSNode root, const char *source) {
php_names_state_t *st = (php_names_state_t *)cbm_arena_alloc(a, sizeof(*st));
if (!st) {
return NULL;
}
memset(st, 0, sizeof(*st));
TSTreeCursor cur = ts_tree_cursor_new(root);
if (ts_tree_cursor_goto_first_child(&cur)) {
do {
TSNode c = ts_tree_cursor_current_node(&cur);
if (!ts_node_is_named(c)) {
continue;
}
const char *k = ts_node_type(c);
if (strcmp(k, "namespace_use_declaration") == 0) {
php_ev_uses(a, st, c, source);
continue;
}
if (strcmp(k, "namespace_definition") != 0) {
continue;
}
/* `namespace X;` starts anew; `namespace X { ... }` holds its own
* uses, and after it the global namespace has none. */
(void)php_ev_add(a, st, ts_node_start_byte(c), PHP_EV_NS,
php_namespace_name(a, c, source), NULL);
TSNode body = cbm_find_child_by_kind(c, "compound_statement");
if (ts_node_is_null(body)) {
continue;
}
TSTreeCursor in = ts_tree_cursor_new(body);
if (ts_tree_cursor_goto_first_child(&in)) {
do {
TSNode u = ts_tree_cursor_current_node(&in);
if (ts_node_is_named(u) &&
strcmp(ts_node_type(u), "namespace_use_declaration") == 0) {
php_ev_uses(a, st, u, source);
}
} while (ts_tree_cursor_goto_next_sibling(&in));
}
ts_tree_cursor_delete(&in);
(void)php_ev_add(a, st, ts_node_end_byte(c), PHP_EV_NS, NULL, NULL);
} while (ts_tree_cursor_goto_next_sibling(&cur));
}
ts_tree_cursor_delete(&cur);
return st;
}
/* The names in force where `cls` is written. */
static void php_names_at(CBMExtractCtx *ctx, TSNode cls, php_names_t *out) {
memset(out, 0, sizeof(*out));
CBMArena *a = ctx->scratch ? ctx->scratch : ctx->arena;
php_names_state_t *st = (php_names_state_t *)ctx->php_names;
if (!st) {
st = php_names_build(a, ts_tree_root_node(cls.tree), ctx->source);
ctx->php_names = st;
if (!st) {
return;
}
}
uint32_t at = ts_node_start_byte(cls);
if (at < st->last_at) {
st->next = 0; /* asked out of source order: from the start again */
st->cur.ns = NULL;
st->cur.count = 0;
}
while (st->next < st->count && st->ev[st->next].at < at) {
const php_name_ev_t *e = &st->ev[st->next++];
if (e->kind == PHP_EV_NS) {
st->cur.ns = e->a;
st->cur.count = 0;
} else {
(void)php_names_add(a, &st->cur, e->a, e->b);
}
}
st->last_at = at;
*out = st->cur;
}
static bool php_seg_eq(const char *a, const char *b, size_t len) {
for (size_t i = 0; i < len; i++) {
if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i])) {
return false;
}
}
return a[len] == '\0';
}
/* The fully qualified name (leading `\`) a class-name spelling denotes
* where it is written: as is when qualified; its first segment replaced by
* the target of the class `use` that aliases it; else under the namespace. */
static const char *php_fq_class(CBMArena *a, const php_names_t *n, const char *spelled) {
if (!spelled || !spelled[0] || strcmp(spelled, "-") == 0) {
return spelled;
}
if (spelled[0] == '\\') {
return spelled;
}
const char *bs = strchr(spelled, '\\');
size_t seg = bs ? (size_t)(bs - spelled) : strlen(spelled);
if (bs && seg == 9 && php_word_at(spelled, bs, "namespace")) {
/* `namespace\Sub\X`: relative to the current namespace, never an alias. */
return n->ns && n->ns[0] ? cbm_arena_sprintf(a, "\\%s%s", n->ns, bs)
: cbm_arena_sprintf(a, "%s", bs);
}
for (int i = n->count - 1; i >= 0; i--) {
if (php_seg_eq(n->alias[i], spelled, seg)) {
return cbm_arena_sprintf(a, "\\%s%s", n->target[i], bs ? bs : "");
}
}
return n->ns && n->ns[0] ? cbm_arena_sprintf(a, "\\%s\\%s", n->ns, spelled)
: cbm_arena_sprintf(a, "\\%s", spelled);
}
static void php_rule_append(CBMArena *a, char **rules, const char *kind, const char *trait,
const char *method, const char *other) {
if (!method || !method[0] || !other || !other[0]) {
return;
}
const char *t = trait && trait[0] ? trait : "-";
*rules = *rules ? cbm_arena_sprintf(a, "%s;%s %s %s %s", *rules, kind, t, method, other)
: cbm_arena_sprintf(a, "%s %s %s %s", kind, t, method, other);
}
/* A node spelling a class or trait name: `T`, `A\T`, `\A\T`, or
* `namespace\T` (relative_name). */
static bool php_class_name_node(const char *k) {
return strcmp(k, "name") == 0 || strcmp(k, "qualified_name") == 0 ||
strcmp(k, "relative_name") == 0;
}
/* `T::m` of a class_constant_access_expression: its two name parts. */
static void php_scoped_member(CBMArena *a, TSNode n, const char *source, char **trait,
char **method) {
uint32_t nc = ts_node_named_child_count(n);
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_named_child(n, i);
const char *k = ts_node_type(c);
if (!php_class_name_node(k)) {
continue;
}
if (!*trait) {
*trait = cbm_node_text(a, c, source);
} else if (!*method) {
*method = cbm_node_text(a, c, source);
}
}
}
static void php_use_list_rules(CBMArena *a, TSNode list, const char *source, char **rules,
const php_names_t *names) {
uint32_t nc = ts_node_named_child_count(list);
for (uint32_t i = 0; i < nc; i++) {
TSNode cl = ts_node_named_child(list, i);
const char *ck = ts_node_type(cl);
bool instead = strcmp(ck, "use_instead_of_clause") == 0;
if (!instead && strcmp(ck, "use_as_clause") != 0) {
continue;
}
char *trait = NULL;
char *method = NULL;
char *alias = NULL;
uint32_t cc = ts_node_named_child_count(cl);
for (uint32_t j = 0; j < cc; j++) {
TSNode p = ts_node_named_child(cl, j);
const char *pk = ts_node_type(p);
if (strcmp(pk, "class_constant_access_expression") == 0) {
php_scoped_member(a, p, source, &trait, &method);
if (trait) {
trait = (char *)php_fq_class(a, names, trait);
}
} else if (php_class_name_node(pk)) {
char *t = cbm_node_text(a, p, source);
if (instead) {
/* one excluded trait */
php_rule_append(a, rules, "x", trait, method, php_fq_class(a, names, t));
} else if (!method) {
method = t;
} else if (!alias) {
alias = t;
}
}
}
if (!instead) {
php_rule_append(a, rules, "a", trait, method, alias);
}
}
}
static CBMDefTypeFacts *def_type_facts(CBMArena *a, CBMDefinition *def);
static void extract_php_member_bases(CBMExtractCtx *ctx, CBMArena *a, TSNode node,
CBMDefinition *def) {
const char *source = ctx->source;
/* The namespace and class aliases in force where the type is written:
* its own namespace (a file may hold several; the file-level
* namespace_name keeps only the first), and its trait names' meaning. */
php_names_t names;
php_names_at(ctx, node, &names);
def->decl_namespace = cbm_arena_strdup(a, names.ns ? names.ns : "");
char kinds[MAX_BASES + 2];
int nk = 0;
bool truncated = false;
uint32_t nc = ts_node_child_count(node);
for (uint32_t i = 0; i < nc; i++) {
TSNode child = ts_node_child(node, i);
const char *ck = ts_node_type(child);
bool ext = strcmp(ck, "base_clause") == 0;
if (!ext && strcmp(ck, "class_interface_clause") != 0) {
continue;
}
/* The same entries push_base_text keeps: non-empty after the generic
* arguments and the namespace are cut. */
uint32_t cc = ts_node_named_child_count(child);
for (uint32_t j = 0; j < cc; j++) {
char *t = cbm_node_text(a, ts_node_named_child(child, j), source);
if (!t) {
continue;
}
char *angle = strchr(t, '<');
if (angle) {
*angle = '\0';
}
char *last_bs = strrchr(t, '\\');
if (!(last_bs ? last_bs[1] : t[0])) {
continue;
}
if (nk >= MAX_BASES_MINUS_1) {
truncated = true;
continue;
}
kinds[nk++] = ext ? 'e' : 'i';
}
}
if (truncated) {
kinds[nk++] = '+';
}
kinds[nk] = '\0';
int bases = 0;
while (def->base_classes && def->base_classes[bases]) {
bases++;
}
/* Kinds only when they describe exactly the recorded bases. */
if (nk - (truncated ? 1 : 0) == bases && nk > 0) {
CBMDefTypeFacts *f = def_type_facts(a, def);
if (f) {
f->base_kinds = cbm_arena_strdup(a, kinds);
}
}
TSNode body = ts_node_child_by_field_name(node, TS_FIELD("body"));
if (ts_node_is_null(body)) {
body = cbm_find_child_by_kind(node, "declaration_list");
}
if (ts_node_is_null(body)) {
body = cbm_find_child_by_kind(node, "enum_declaration_list");
}
if (ts_node_is_null(body)) {
return;
}
int count = 0;
int cap = 0;
const char **mixins = NULL;
char *rules = NULL;
uint32_t bc = ts_node_named_child_count(body);
for (uint32_t i = 0; i < bc; i++) {
TSNode use = ts_node_named_child(body, i);
if (strcmp(ts_node_type(use), "use_declaration") != 0) {
continue;
}
/* A trait is named as the class's file names it (`names`). */
uint32_t uc = ts_node_named_child_count(use);
for (uint32_t j = 0; j < uc; j++) {
TSNode c = ts_node_named_child(use, j);
const char *k = ts_node_type(c);
if (strcmp(k, "use_list") == 0) {
php_use_list_rules(a, c, source, &rules, &names);
continue;
}
if (!php_class_name_node(k)) {
continue;
}
char *t = cbm_node_text(a, c, source);
if (!t || !t[0]) {
continue;
}
if (count + 1 >= cap) {
int ncap = cap ? cap * 2 : 4;
const char **grown =
(const char **)cbm_arena_alloc(a, (size_t)ncap * sizeof(*grown));
if (!grown) {
return;
}
if (count > 0) {
memcpy(grown, mixins, (size_t)count * sizeof(*grown));
}
mixins = grown;
cap = ncap;
}
mixins[count++] = php_fq_class(a, &names, t);
}
}
CBMDefTypeFacts *f = count > 0 || rules ? def_type_facts(a, def) : NULL;
if (!f) {
return;
}
if (count > 0) {
mixins[count] = NULL;
char *mk = (char *)cbm_arena_alloc(a, (size_t)count + 1);
if (!mk) {
return;
}
memset(mk, 't', (size_t)count);
mk[count] = '\0';
f->mixins = mixins;
f->mixin_kinds = mk;
}
f->member_rules = rules;
}
/* Kotlin: supertypes live in `delegation_specifier` children. Each holds
* either a bare `user_type` (interface) or a `constructor_invocation` whose
* `user_type` is the superclass. Descend to the `type_identifier`. */
@@ -9932,6 +10442,9 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s
}
}
def.base_classes = extract_base_classes(a, node, ctx->source, ctx->language);
if (ctx->language == CBM_LANG_PHP) {
extract_php_member_bases(ctx, a, node, &def);
}
if (ctx->language == CBM_LANG_RUBY) {
def.mixin_refs = ruby_class_mixin_refs(a, node, ctx->source);
}
@@ -10442,6 +10955,12 @@ static void push_method_def(CBMExtractCtx *ctx, TSNode child, TSNode class_node,
strcmp(ts_node_type(child), "function_signature_item") == 0) {
def.is_abstract = true;
}
/* PHP: a method without a body (`abstract function`, an interface's) is a
* declaration; the member lookup lets a trait's be satisfied further on. */
if (ctx->language == CBM_LANG_PHP && strcmp(ts_node_type(child), "method_declaration") == 0 &&
ts_node_is_null(ts_node_child_by_field_name(child, TS_FIELD("body")))) {
def.is_abstract = true;
}
if (ctx->language == CBM_LANG_RUBY) {
def.is_singleton = ruby_def_is_singleton(child);
}
@@ -10901,6 +11420,13 @@ static void extract_rust_impl(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
a, params, ctx->source, ctx->language, true, &def.signature_param_count);
}
// Return type, as extract_func_def reads it for a free `fn`.
TSNode rt = ts_node_child_by_field_name(child, TS_FIELD("return_type"));
if (!ts_node_is_null(rt)) {
def.return_type = cbm_node_text(a, rt, ctx->source);
def.return_types = extract_return_types(a, rt, ctx->source, ctx->language);
}
if (spec->branching_node_types && spec->branching_node_types[0]) {
set_def_complexity(&def, child, spec);
}
+85
View File
@@ -515,6 +515,79 @@ static void emit_kustomize_charts(CBMExtractCtx *ctx, TSNode seq) {
}
}
static const char KUST_CONFIGMAP_GEN[] = "configMapGenerator";
static const char KUST_SECRET_GEN[] = "secretGenerator";
static const char KUST_CONFIGURATIONS[] = "configurations";
// A FILE fact: the kustomization reads `path`, named by `via` (one of the
// static names above) at the row of `at`.
static void emit_kustomize_file(CBMExtractCtx *ctx, const char *path, const char *via, TSNode at) {
if (!path || !path[0]) {
return;
}
CBMK8sFact f = {.fact = CBM_K8S_FACT_FILE,
.def_index = -1,
.via = via,
.path = path,
.line = (int)ts_node_start_point(at).row + TS_LINE_OFFSET};
cbm_k8sfact_push(&ctx->result->k8s_facts, ctx->arena, f);
}
// One FILE fact per scalar item of sequence `seq`. `keyed`: an item may be
// `key=path` (a generator's `files`), and the path is what follows the `=`.
static void emit_kustomize_file_items(CBMExtractCtx *ctx, TSNode seq, const char *via, bool keyed) {
k8s_kids_t items = k8s_kids(seq);
TSNode item;
while (k8s_kid(&items, false, &item)) {
if (strcmp(ts_node_type(item), "block_sequence_item") != 0) {
continue;
}
k8s_kids_t vals = k8s_kids(item);
TSNode val;
while (k8s_kid(&vals, false, &val)) {
const char *text = get_scalar_text(ctx->arena, val, ctx->source);
const char *eq = text && keyed ? strchr(text, '=') : NULL;
emit_kustomize_file(ctx, eq ? eq + SKIP_ONE : text, via, val);
}
}
}
// The generators of a `configMapGenerator` / `secretGenerator` list: the
// files each reads -- `files`, `envs`, and the single `env` of older
// kustomize. Literals name no file.
static void emit_kustomize_generators(CBMExtractCtx *ctx, TSNode seq, const char *via) {
CBMArena *a = ctx->arena;
k8s_kids_t items = k8s_kids(seq);
TSNode item;
while (k8s_kid(&items, false, &item)) {
TSNode map = strcmp(ts_node_type(item), "block_sequence_item") == 0
? kust_item_mapping(item)
: (TSNode){0};
if (ts_node_is_null(map)) {
continue;
}
k8s_kids_t pairs = k8s_kids(map);
TSNode pair;
while (k8s_kid(&pairs, false, &pair)) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
continue;
}
const char *key = get_scalar_text(a, ts_node_named_child(pair, 0), ctx->source);
TSNode v = unwrap_pair_value(pair);
if (!key || ts_node_is_null(v)) {
continue;
}
bool files = strcmp(key, "files") == 0;
if ((files || strcmp(key, "envs") == 0) &&
strcmp(ts_node_type(v), "block_sequence") == 0) {
emit_kustomize_file_items(ctx, v, via, files);
} else if (strcmp(key, "env") == 0) {
emit_kustomize_file(ctx, get_scalar_text(a, v, ctx->source), via, v);
}
}
}
}
// Process a single block_mapping_pair for kustomize list keys.
static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
@@ -536,6 +609,18 @@ static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
emit_kustomize_charts(ctx, val_node);
return;
}
if (strcmp(key_text, KUST_CONFIGMAP_GEN) == 0) {
emit_kustomize_generators(ctx, val_node, KUST_CONFIGMAP_GEN);
return;
}
if (strcmp(key_text, KUST_SECRET_GEN) == 0) {
emit_kustomize_generators(ctx, val_node, KUST_SECRET_GEN);
return;
}
if (strcmp(key_text, KUST_CONFIGURATIONS) == 0) {
emit_kustomize_file_items(ctx, val_node, KUST_CONFIGURATIONS, false);
return;
}
if (!is_kustomize_list_key(key_text)) {
return;
}
+115 -3
View File
@@ -28,6 +28,7 @@
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -36,6 +37,7 @@ typedef enum {
SC_ROLE_TYPE, /* defines a type (Protobuf message, enum) */
SC_ROLE_INCLUDE, /* an include statement, when an import starts here */
SC_ROLE_QREF, /* a qualified type reference: its text, qualifier included */
SC_ROLE_SERVICE, /* a service: its methods are symbols an rpc's types meet first */
} sc_role_t;
typedef struct {
@@ -51,17 +53,22 @@ typedef struct {
const char *package_kind; /* the statement naming the file's package; NULL: none */
const char *nest_kind; /* a type kind whose nested types it names; NULL: none */
bool public_reexports; /* `import public` re-exports what it imports */
/* a symbol scope that is no type (Protobuf: a service, its methods), the
* kinds of their name children ("<kind>_name"); NULL: none */
const char *service_kind;
const char *method_kind;
} sc_lang_t;
static const sc_rule_t SC_PROTO_RULES[] = {
{"message", SC_ROLE_TYPE, "Class"}, {"enum", SC_ROLE_TYPE, "Class"},
{"import", SC_ROLE_INCLUDE, NULL}, {"message_or_enum_type", SC_ROLE_QREF, NULL},
{NULL, SC_ROLE_NONE, NULL},
{"service", SC_ROLE_SERVICE, NULL}, {NULL, SC_ROLE_NONE, NULL},
};
static const char *const SC_PROTO_NAMES[] = {"message_name", "enum_name", NULL};
static const sc_lang_t SC_LANGS[] = {
{CBM_LANG_PROTOBUF, SC_PROTO_RULES, SC_PROTO_NAMES, "package", "message", true},
{CBM_LANG_PROTOBUF, SC_PROTO_RULES, SC_PROTO_NAMES, "package", "message", true, "service",
"rpc"},
};
static _Atomic uint64_t g_scope_nodes_visited = 0;
@@ -136,6 +143,14 @@ typedef struct {
uint32_t *cond_depth;
uint32_t ncond;
uint32_t cap_cond;
/* symbols that are no type: the file's services, and the methods of the
* service holding bytes [svc_start, svc_end); each sorted by name */
const char **svcs;
uint32_t nsvcs;
const char **methods;
uint32_t nmethods;
uint32_t svc_start;
uint32_t svc_end;
} sc_walk_t;
/* The definition of `label` named `name` that starts on `line`; -1 when there
@@ -278,6 +293,84 @@ static void sc_include(sc_walk_t *w, TSNode n) {
}
}
static int sc_str_cmp(const void *a, const void *b) {
return strcmp(*(const char *const *)a, *(const char *const *)b);
}
/* The names of `n`'s children of kind `kind` (each through its "<kind>_name"
* child), sorted, into an arena array; false when memory ran out. */
static bool sc_names_of(sc_walk_t *w, TSNode n, const char *kind, const char ***out,
uint32_t *count) {
char name_kind[CBM_SZ_64];
*out = NULL;
*count = 0;
if (snprintf(name_kind, sizeof(name_kind), "%s_name", kind) >= (int)sizeof(name_kind)) {
return true;
}
uint32_t c = ts_node_named_child_count(n);
const char **v = c ? cbm_arena_alloc(w->ctx->arena, c * sizeof(*v)) : NULL;
if (c && !v) {
return false;
}
for (uint32_t i = 0; i < c; i++) {
TSNode ch = ts_node_named_child(n, i);
if (strcmp(ts_node_type(ch), kind) != 0) {
continue;
}
uint32_t cc = ts_node_named_child_count(ch);
for (uint32_t j = 0; j < cc; j++) {
TSNode nm = ts_node_named_child(ch, j);
if (strcmp(ts_node_type(nm), name_kind) == 0) {
const char *t = sc_text(w, nm);
if (t) {
v[(*count)++] = t;
}
break;
}
}
}
if (*count > SKIP_ONE) {
qsort(v, *count, sizeof(*v), sc_str_cmp);
}
*out = v;
return true;
}
/* Entering a service: its methods, which an rpc's types meet first. */
static bool sc_service(sc_walk_t *w, TSNode n) {
w->svc_start = ts_node_start_byte(n);
w->svc_end = ts_node_end_byte(n);
return sc_names_of(w, n, w->lang->method_kind, &w->methods, &w->nmethods);
}
static bool sc_sorted_has(sc_walk_t *w, const char *const *v, uint32_t n, const char *key) {
w->steps++; /* one search */
return n > 0 && bsearch(&key, v, n, sizeof(*v), sc_str_cmp) != NULL;
}
/* Whether, on the way out from the reference at byte `at`, its first
* component names a symbol that is no type before any type: in an rpc a
* method of its service (protoc searches the service first and resolves any
* symbol there), or a service of the file; elsewhere a service only when the
* reference is qualified (an unqualified field type skips what is no type). */
static bool sc_meets_no_type(sc_walk_t *w, const char *text, uint32_t at) {
if (!w->lang->service_kind || text[0] == '.') {
return false; /* from the root: no scope is searched */
}
size_t fl = strcspn(text, ".");
char first[CBM_SZ_256];
if (fl >= sizeof(first)) {
return true; /* not read: never proven */
}
memcpy(first, text, fl);
first[fl] = '\0';
bool in_rpc = at >= w->svc_start && at < w->svc_end;
if (in_rpc && sc_sorted_has(w, w->methods, w->nmethods, first)) {
return true;
}
return (in_rpc || text[fl] == '.') && sc_sorted_has(w, w->svcs, w->nsvcs, first);
}
/* A qualified type reference as written, blanks and comments between its
* parts dropped: "google.protobuf.Empty", ".a.B", "Empty". */
static void sc_qref(sc_walk_t *w, TSNode n) {
@@ -300,8 +393,15 @@ static void sc_qref(sc_walk_t *w, TSNode n) {
k += ce - cb;
}
text[k] = '\0';
/* the innermost scope around it: the enclosing message (NULL when its
* full name is unknown), else the file's package */
const char *scope = w->lang->package_kind ? w->pkg : NULL;
if (w->nnest > 0) {
scope = w->nest_full[w->nnest - SKIP_ONE];
}
if (k > 0) {
sc_emit(w, CBM_SCOPE_QREF, text, NULL, (int32_t)b, e, 0);
uint8_t flags = sc_meets_no_type(w, text, b) ? (uint8_t)CBM_SCOPE_NOT_A_TYPE : 0;
sc_emit(w, CBM_SCOPE_QREF, text, scope, (int32_t)b, e, flags);
}
}
@@ -326,6 +426,9 @@ static bool sc_visit(sc_walk_t *w, TSNode n, bool *failed) {
case SC_ROLE_QREF:
sc_qref(w, n);
return false;
case SC_ROLE_SERVICE:
*failed = !sc_service(w, n);
return true;
case SC_ROLE_NONE:
default:
return true;
@@ -432,6 +535,9 @@ void cbm_extract_scope(CBMExtractCtx *ctx) {
if (lang->package_kind) {
w.pkg = sc_package(&w, ctx->root);
}
if (lang->service_kind && !sc_names_of(&w, ctx->root, lang->service_kind, &w.svcs, &w.nsvcs)) {
return;
}
const CBMDefArray *defs = &ctx->result->defs;
if (defs->count > 0) {
w.defs = cbm_arena_alloc(ctx->arena, (size_t)defs->count * sizeof(*w.defs));
@@ -457,6 +563,12 @@ void cbm_extract_scope(CBMExtractCtx *ctx) {
qsort(w.imps, (size_t)w.nimps, sizeof(*w.imps), sc_ref_cmp);
}
uint64_t visited = sc_walk_tree(&w, ctx->root);
if (ts_node_has_error(ctx->root)) {
/* a tree with an error the walk may not meet as an ERROR node (a
* MISSING token the parser inserted): the compiler rejects the file,
* so nothing in it is proven */
sc_emit(&w, CBM_SCOPE_OPAQUE, NULL, NULL, -1, ts_node_end_byte(ctx->root), 0);
}
atomic_fetch_add_explicit(&g_scope_nodes_visited, visited + w.steps, memory_order_relaxed);
CBMScopeEventArray *ev = &ctx->result->scope;
if (ev->count > SKIP_ONE) {
+9
View File
@@ -124,6 +124,15 @@ typedef struct {
* "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;
/* Member lookup (member_walk.h): one kind letter per embedded_types entry
* ('e' extends, 'i' implements, 't' trait use), plus a trailing '+' when
* the extractor left bases unrecorded; NULL = the entries' kinds are
* unknown. PHP today (embedded_types then lists the bases, then the
* traits). */
const char *supertype_kinds;
/* The rules the type's mixin uses apply to their members, as
* CBMDefTypeFacts.member_rules (PHP `insteadof` / `as`). NULL = none. */
const char *member_rules;
} CBMLSPDef;
// Parse source, build registry from defs + stdlib, run LSP.
File diff suppressed because it is too large Load Diff
+342
View File
@@ -0,0 +1,342 @@
/*
* member_walk.h — one member lookup over a type's ancestry, shared by every
* object-oriented engine.
*
* Lifted from the parked Ruby branch (feat/ruby-cross-file-lookup, commit
* 96547561c) and corrected for the other engines. Every engine answers "type
* T, member m" by searching the members of a sequence of types in an order
* the language defines: PHP's own members, then its traits, then the parent;
* Python's C3 linearisation; Go's embedding depths. The ORDER is the
* language's (a lineariser turns CBMRegisteredType.supertypes into steps);
* the SEARCH over it is this file's, the same for every language.
*
* Three answers, and only three:
*
* CBM_MW_FOUND a step declares the member: the hit says which, where
* (own, superclass, mixin, interface declaration, ...) and
* whether every step before it was completely known;
* CBM_MW_ABSENT the walk reached an explicit STOP step: the ancestry is
* completely known and declares no such member. A
* lineariser writes STOP only after a fully known ancestry,
* and no SOFT place was passed on the way;
* CBM_MW_ABSTAIN anything else: a hard UNSEEN step, a type that cannot be
* described, two definitions where one is needed, a cycle,
* the END of the steps, or a STOP reached after a SOFT place.
* A builder that forgets a STOP or an UNSEEN gets "unknown",
* never "not found" (the Ruby branch's failure: "unknown"
* read as "not found" removed right edges). ABSTAIN is the
* zero value for that reason.
*
* Possible against proven (CBMMemberHit.prefix_complete). A FOUND hit with a
* complete prefix is PROVEN: every step before it was completely known. A hit
* with an incomplete prefix is POSSIBLE: the walk passed a SOFT place (a
* supertype the registry does not hold, or one not resolved), or an OUTSIDE
* step whose position nobody knows, and found the member behind it; what it
* passed may declare the member first. An engine decides what it does with a
* possible answer; the walk never decides. Behind a SOFT place the walk never
* answers ABSENT.
*
* Steps (an order is an array of them, first searched first):
*
* OWN the members (type_id, side) itself declares;
* UNSEEN something nobody can see may answer here. A hard one (the
* default: the type's own members are not known, e.g. computed)
* ends the walk: unknown. A SOFT one (CBM_MW_SOFT) stands for a type
* the registry does not hold (outside the project, not resolved):
* it is passed; what the walk finds behind it is FOUND with
* prefix_complete false (possible), and the walk can no longer end
* ABSENT. The walk's own order for a type the registry does not hold
* is [OWN, SOFT UNSEEN, STOP] (its own members, if any, are proven);
* STOP nothing beyond this point: absent (phase 1 ends, see LATER);
* NEXT the last step only: the order goes on as (type_id, side)'s order.
* Single inheritance links to the parent's order instead of copying
* it, so a chain of n types costs n steps in total;
* GROUP the next `count` steps (OWN, SUB or UNSEEN each) are one place whose
* members' relative order nobody knows. With CBM_MW_GROUP_EXCLUSIVE
* (PHP traits, Go embedding at one depth: a valid program has at most
* one provider of a name) one distinct definition answers even when
* another member is unknown, and a SOFT member leaves its prefix as
* it was; without it every member must be known, and a hit beside a
* SOFT member is only possible. Members are siblings: each is
* walked from the state before the group. Two distinct definitions
* abstain. None goes on after the group;
* SUB the first answer of (type_id, side)'s whole order (a trait using
* traits, a mixin with its own ancestry);
* LATER (type_id, side)'s order is searched only after the chain ended at
* a STOP without a hit (interface declarations, abstract members):
* phase 2, breadth first, each type once, first hit wins; a cycle
* among the entries searched answers ABSTAIN, never ABSENT. A LATER
* step with type_id NULL is an unknown place in phase 2 (hard or
* SOFT, as UNSEEN);
* OPEN the type dispatches undeclared names (CBM_MEMBERS_OPEN): a STOP
* reached after it answers ABSTAIN instead of ABSENT.
*
* A mixin's abstract member (CBM_FUNC_FLAG_ABSTRACTMETHOD at a MIXIN place:
* a PHP trait's `abstract function m()`) is a requirement, not an
* implementation. It defers to later places only while every place that
* could satisfy it before them is known: met with nothing unknown beside it
* (same group) or before it, the walk goes on, and an implementation found
* further on answers (proven); the requirement answers itself at the chain's
* STOP (proven only when nothing SOFT lies anywhere on the way). Met beside
* or after a SOFT place, or when a SOFT place lies between it and the next
* implementation, the requirement itself is the answer, possible, and the
* chain does not go on. In a group it never conflicts with an implementation;
* beside a hard unknown member it is unknown.
*
* Depth and memory. Nothing in the walk uses C stack depth that grows with
* the input: a mixin's whole order and the rest of a chain past a NEXT link
* are nodes answered on an explicit stack of frames (heap), each answered
* once per walker and kept (with whether it passed a SOFT place), so n
* lookups over one ancestry cost the ancestry once. A group of at least
* eight members finds the members that declare a name through an index of
* its leaf members (a member that is its type's own members only); renames
* are found by name. Every step read, order built and index entry counts one
* unit of work (CBMMemberWalker.work, CBM_LSP_WORK). Nothing caps an order's
* length or depth. Cycles (a class extending itself through others, a trait
* using itself, interfaces extending each other) abstain.
*
* Threading. A walker serves one thread and keeps its answers for one
* registry, member kind and overload mode (another one clears them); the
* registry must not change while the walker lives (PHP: per file). Orders
* built lazily belong to that thread too. Sealed orders
* (cbm_member_orders_build_all) are read-only and may be shared by walkers on
* many threads. `prepare` is only ever called with a type the orders'
* registry itself holds, never one found through its fallback: a shared
* fallback registry's types are settled before it is sealed and are only read.
*
* Known limits for the next engines (no code yet; the slice that needs each):
* - Phase 2 is breadth first and its first hit wins. Java's and C#'s
* "most specific default method" (an interface overriding its parent's
* default; two unrelated defaults conflict) is not expressible: the Java /
* C# engine slices.
* - A SUB is its type's whole order, phase 2 included: a mixin with LATER
* steps answers its interface declarations before the outer chain's
* parents are searched. The Ruby and Scala (trait with interfaces) slices.
* - Go embedding needs groups of OWN members per depth (a SUB member's
* deeper hit conflicts with a shallower sibling's and the group abstains:
* recall lost, no false edge) unless the lineariser flattens the depths:
* the Go slice.
* - cbm_member_orders_build_all covers the head registry's types and
* receivers only, not a fallback's: the first engine with chained shared
* registries (TypeScript, Python Tier 2).
* - The sealed path and CBMTypeRegistry.member_orders have no production
* user yet; their thread safety is tested in unit tests only: the first
* engine that shares orders across threads.
* - Arity and argument-type selection of overloads is the engine's, after
* COLLECT: the Java / Kotlin / C# slices add selectors with their reader.
* - path_local counts a depth-0 hit inside a mixin's whole answer as the
* mixin's own member (an empty path below it). That is exact for PHP,
* whose traits have no parent and no interface steps. Where a mixin has
* ancestors of its own, such a hit can be an ancestor's member, and the
* exact test is the hit's owner against the mixin itself: the Ruby and
* Scala slices (modules and traits with supertypes).
* - Sequential SUB steps that are not grouped (Ruby includes) cost one pass
* of the order per SUB step not yet answered (quadratic in the number of
* such steps of one order, once per name): the Ruby slice.
* - Phase 2 is kept per (chain node, name) and composed along the chain
* (n lookups from n classes of an n-deep chain each implementing an
* interface search each node's interfaces once). The collecting modes
* and `super` lookups still search the whole deferred list per lookup,
* quadratic in that shape: the Java / Kotlin / C# slices (COLLECT) and
* the first engine with `super` lookups.
*/
#ifndef CBM_LSP_MEMBER_WALK_H
#define CBM_LSP_MEMBER_WALK_H
#include "type_registry.h"
#include <stdbool.h>
#include <stdint.h>
/* The sides a language may look members up on (Ruby: instance and class). */
enum { CBM_MW_SIDES = 2 };
typedef enum {
CBM_MW_OWN = 0,
CBM_MW_UNSEEN,
CBM_MW_STOP,
CBM_MW_NEXT,
CBM_MW_GROUP,
CBM_MW_SUB,
CBM_MW_LATER,
CBM_MW_OPEN,
} CBMMemberStepKind;
/* Where a hit lies, seen from the type the lookup started on. */
typedef enum {
CBM_MW_PLACE_OWN = 0, /* the start type's own members */
CBM_MW_PLACE_SUPER, /* a superclass's own members */
CBM_MW_PLACE_INTERFACE_DEFAULT, /* an interface's member, reached in phase 2 */
CBM_MW_PLACE_MIXIN, /* a trait / module / embedded type */
CBM_MW_PLACE_PREPEND_IN_BODY, /* Ruby: a module prepended in the class body */
CBM_MW_PLACE_OUTSIDE, /* a mixin applied outside the type's body */
} CBMMemberPlace;
enum {
CBM_MW_GROUP_EXCLUSIVE = 1u << 0, /* GROUP: valid programs have at most one provider */
CBM_MW_SOFT = 1u << 1, /* UNSEEN, LATER NULL, a group's UNSEEN member: a type the
registry does not hold, passed (behind it: possible) */
};
typedef struct {
const char *type_id; /* OWN, SUB, LATER, NEXT: the type */
const char *via; /* GROUP: the type whose order holds the group (renames, place) */
int count; /* GROUP: the number of member steps that follow */
int side; /* OWN, SUB, LATER, NEXT */
uint8_t kind; /* CBMMemberStepKind */
uint8_t place; /* CBMMemberPlace of a hit at an OWN or SUB step */
uint8_t flags; /* GROUP: CBM_MW_GROUP_* */
} CBMMemberStep;
typedef enum {
CBM_MW_ABSTAIN = 0, /* unknown: no answer, the caller's other rules stay */
CBM_MW_FOUND,
CBM_MW_ABSENT, /* only at an explicit STOP */
} CBMMemberWalkResult;
typedef enum {
CBM_MW_MEMBER_METHOD = 1,
CBM_MW_MEMBER_FIELD = 2,
CBM_MW_MEMBER_ANY = 3, /* a method, else a field */
} CBMMemberKind;
typedef enum {
CBM_MW_HIDE_BY_NAME = 0, /* the first place declaring the name answers (PHP, Python, Ruby) */
CBM_MW_COLLECT, /* every declaration of the name in the order (Java, Kotlin) */
CBM_MW_HIDE_BY_SIGNATURE, /* every declaration, a derived one hiding an equal signature (C#) */
} CBMOverloadMode;
/* A lineariser: the steps of (t, side)'s order, appended to `out`. Returns
* false when the type cannot be described (the lookup then abstains). The
* steps' strings must outlive the orders (registry or arena strings). */
struct CBMMemberOrders;
struct CBMMemberSteps;
typedef bool (*CBMLineariser)(struct CBMMemberOrders *o, const CBMRegisteredType *t, int side,
struct CBMMemberSteps *out);
/* Optional, per-file registries only: settle a type's supertypes (resolve
* spellings, set states and member flags) the first time its order is
* built. Never called on sealed orders, and only with a type the orders'
* registry itself holds (never one found through its fallback). */
typedef void (*CBMMemberPrepare)(void *ctx, CBMRegisteredType *t);
typedef struct CBMMemberSteps {
CBMMemberStep *items;
int count;
int cap;
bool oom; /* a push could not grow the list: the order is incomplete */
} CBMMemberSteps;
void cbm_member_steps_push(CBMMemberSteps *s, CBMMemberStepKind kind, const char *type_id, int side,
CBMMemberPlace place);
/* A GROUP header; the caller pushes `count` member steps right after it. */
void cbm_member_steps_group(CBMMemberSteps *s, const char *via, int count, uint8_t flags);
/* A SOFT unknown place: an UNSEEN step, or (kind LATER) an unknown place in
* phase 2. */
void cbm_member_steps_soft(CBMMemberSteps *s, CBMMemberStepKind kind, int side,
CBMMemberPlace place);
void cbm_member_steps_free(CBMMemberSteps *s);
/* The orders of one registry, built once per (type, side) and cached. */
typedef struct CBMMemberOrders {
const CBMTypeRegistry *reg;
CBMLineariser lin;
CBMMemberPrepare prepare; /* may be NULL */
void *prepare_ctx;
CBMArena *arena; /* the cached steps live here */
void *by_type; /* CBMHashTable: type QN -> cached orders of its sides */
bool sealed; /* shared read-only: a missing order is never built */
uint64_t built; /* orders built (counted work) */
uint64_t steps; /* steps stored in all orders (memory accounting) */
CBMMemberSteps scratch;
} CBMMemberOrders;
/* Orders over `reg` built by `lin`, cached in `arena`. */
void cbm_member_orders_init(CBMMemberOrders *o, const CBMTypeRegistry *reg, CBMLineariser lin,
CBMArena *arena);
void cbm_member_orders_free(CBMMemberOrders *o);
/* Build every registered type's orders, and every method receiver's, for
* `sides` sides, then refuse lazy builds (a shared registry: build before the
* registry's seal). */
void cbm_member_orders_build_all(CBMMemberOrders *o, int sides);
/* The order of (type_qn, side), built on first use unless sealed. A type the
* registry does not hold gets [OWN type, SOFT UNSEEN, STOP]: its own members
* can still answer (proven), anything behind them is only possible; sealed,
* a name built neither as a type nor as a receiver gets [SOFT UNSEEN, STOP].
* Returns false when no order exists. */
bool cbm_member_orders_get(CBMMemberOrders *o, const char *type_qn, int side,
const CBMMemberStep **steps, int *count);
/* One lookup. */
typedef struct {
const CBMTypeRegistry *reg; /* the registry whose members are probed */
int lang; /* CBMLanguage, informative */
const char *type_qn; /* the start type (its registered QN) */
int side;
const char *name;
uint8_t member_kind; /* CBMMemberKind; 0 = METHOD */
const char *after; /* `super`: start after this type's OWN step */
int after_side;
uint8_t overloads; /* CBMOverloadMode */
} CBMMemberQuery;
typedef struct {
const CBMRegisteredFunc *func; /* a method hit */
const CBMType *field_type; /* a field hit */
const char *owner_qn; /* the type that declares the member */
const char *via_qn; /* MIXIN: the type whose group brought the owner in
(the outermost one); else the owner */
const char *member_name; /* the declared name (an alias's target name) */
uint8_t place; /* CBMMemberPlace */
bool prefix_complete; /* true = proven: no step before the hit was OUTSIDE or
a SOFT place; false = possible, never a proof */
uint8_t mixin_depth; /* sub-orders the hit lies in: 0 own / superclass /
interface, 1 a direct mixin, 2+ a mixin's mixin
(capped at 255) */
bool renamed; /* found under an alias (a rename of a group's holder) */
bool path_local; /* MIXIN: every type on the `use` path, from via_qn down
to the one whose group holds the owner, satisfies the
walker's `local` predicate (the owner itself is not
asked); false without a predicate */
} CBMMemberHit;
/* Which types the engine counts as its own for path_local (PHP: declared in
* the file being resolved). Set before the first lookup and fixed for the
* walker's life: the answers it keeps carry the flag. */
typedef bool (*CBMMemberLocal)(void *ctx, const char *type_qn);
typedef struct {
uint64_t work; /* steps read, orders built, index entries made: the counted growth unit */
CBMMemberLocal local; /* optional, see CBMMemberLocal */
void *local_ctx;
CBMMemberOrders *orders;
void *state; /* answers kept across lookups, the frame stack, indexes (member_walk.c) */
/* COLLECT / HIDE_BY_SIGNATURE: every hit of the last lookup. */
CBMMemberHit *hits;
int hit_count;
int hit_cap;
} CBMMemberWalker;
void cbm_member_walker_init(CBMMemberWalker *w, CBMMemberOrders *orders);
void cbm_member_walker_free(CBMMemberWalker *w);
/* Look the member up. *out receives the hit on FOUND (the first one for the
* collecting modes, whose full list is w->hits[0, w->hit_count)). */
CBMMemberWalkResult cbm_member_lookup(CBMMemberWalker *w, const CBMMemberQuery *q,
CBMMemberHit *out);
/* ── Linearisers ─────────────────────────────────────────────────────
*
* cbm_lin_own_traits_parent (PHP): own members; the traits as one exclusive
* GROUP of sub-orders (renames of the using type applied); the interfaces
* (IMPLEMENTS, and an interface's EXTENDS) as LATER steps; then the parent
* (the one EXTENDS of a class) by NEXT. A supertype that is not KNOWN becomes
* a SOFT unknown place where it stands (a group member, an unknown LATER, an
* UNSEEN followed by STOP in place of the parent; so do two parents): what
* lies behind it answers only as a possible hit, and nothing is ever absent.
* OPEN after the own step for CBM_MEMBERS_OPEN; a hard UNSEEN after it for
* COMPUTED and REOPENED_EXTERNAL; DECLS_DISAGREE makes the order [OWN, UNSEEN].
* A class with no parent ends with STOP. */
bool cbm_lin_own_traits_parent(CBMMemberOrders *o, const CBMRegisteredType *t, int side,
CBMMemberSteps *out);
#endif /* CBM_LSP_MEMBER_WALK_H */
+904 -517
View File
File diff suppressed because it is too large Load Diff
+23 -8
View File
@@ -73,10 +73,16 @@ typedef struct {
* Zero via memset. */
int walk_depth;
/* Receiver -> registered-method index used while traits are flattened
* (php_lsp.c, php_trait_index_t). Owned by the class-field pass, NULL
* outside it. Zero via memset. */
struct php_trait_index *trait_index;
/* The shared member lookup (member_walk.h) over this file's registry:
* orders, walker and their scratch (php_lsp.c php_members_begin). NULL
* until the registry is complete; zero via memset. */
struct php_members *members;
/* The registry's types by the name PHP gives them (namespace and short
* name, lower case, '.'-separated) -> QN, from the namespace of the file
* that declares each; a name two types share maps to "" (ambiguous).
* Trait uses resolve here only (php_settle_trait). NULL until built. */
struct CBMHashTable *type_fqns;
/* Debug mode (CBM_LSP_DEBUG env). */
bool debug;
@@ -95,9 +101,15 @@ void php_lsp_add_use(PHPLSPContext *ctx, const char *local_name, const char *tar
void php_lsp_process_file(PHPLSPContext *ctx, TSNode root);
/* Refine an already-populated registry from local class ASTs: declared and
* PHPDoc returns, trait flattening, and typed fields. */
* PHPDoc returns, the supertypes and trait rules of the file's own classes,
* and typed fields. */
void cbm_php_refine_lsp_registry(PHPLSPContext *ctx, CBMTypeRegistry *reg, TSNode root);
/* Attach the shared member lookup to ctx over its (complete) registry, and
* release it. Lookups before begin find only a receiver's own members. */
void php_members_begin(PHPLSPContext *ctx, CBMTypeRegistry *reg);
void php_members_end(PHPLSPContext *ctx);
/* Evaluate a PHP expression's type. May return NULL / CBM_TYPE_UNKNOWN. */
const CBMType *php_eval_expr_type(PHPLSPContext *ctx, TSNode node);
@@ -107,9 +119,12 @@ const CBMType *php_parse_type_node(PHPLSPContext *ctx, TSNode node);
/* Resolve a class name (bare or qualified) using current namespace + use map. */
const char *php_resolve_class_name(PHPLSPContext *ctx, const char *name);
/* Look up a method on a class, walking parent chain (registry-based). */
const CBMRegisteredFunc *php_lookup_method(PHPLSPContext *ctx, const char *class_qn,
const char *method_name);
/* The method PHP calls for `method_name` on class_qn, found by the shared
* member lookup (own members, traits, parent chain, interfaces); NULL when
* the lookup finds none or does not know. A trait's method is reported as a
* member of the class that uses the trait. */
const CBMRegisteredFunc *php_find_method(PHPLSPContext *ctx, const char *class_qn,
const char *method_name);
/* Entry point: build registry from file defs + stdlib + composer (if present),
* then run resolution. Called from cbm_extract_file(). */
+85
View File
@@ -78,8 +78,88 @@ typedef struct {
// so this is the only way to bind a short name through `using` directives and
// enclosing namespaces (#2120). NULL for nested types and unknown namespaces.
const char *namespace_qn;
// --- Member lookup (member_walk.h), every object-oriented engine ---
// The type's ancestry as data: one entry per supertype, in source order.
// The language's lineariser turns it into the lookup order. NULL/0 = no
// ancestry recorded (the order then ends unknown, never "not found").
const struct CBMSupertype *supertypes;
int supertype_count;
// CBM_MEMBERS_*: where the type's members are not all listed.
uint32_t member_flags;
// Renames the type applies to its mixins' members (PHP `insteadof` / `as`).
const struct CBMMemberRename *renames;
int rename_count;
} CBMRegisteredType;
/* One entry of a type's ancestry (16 bytes). type_qn is the registered type's
* qualified name when state is KNOWN, else the spelling as written. */
typedef enum {
CBM_SUPER_EXTENDS = 1, /* superclass (Java, PHP, Python bases, an interface's parents) */
CBM_SUPER_IMPLEMENTS, /* an interface a class implements */
CBM_SUPER_INCLUDE, /* Ruby include */
CBM_SUPER_PREPEND, /* Ruby prepend */
CBM_SUPER_EXTEND, /* Ruby extend (class side) */
CBM_SUPER_EMBED, /* Go struct embedding */
CBM_SUPER_TRAIT, /* PHP trait use, Rust trait impl, Scala mixin */
CBM_SUPER_DELEGATE, /* Kotlin `by` delegation */
} CBMSupertypeKind;
typedef enum {
CBM_SUPER_KNOWN = 0, /* a registered type: its order is known */
CBM_SUPER_EXTERNAL, /* outside the project (vendor, JDK, node_modules) */
CBM_SUPER_UNRESOLVED, /* the spelling names no registered type */
CBM_SUPER_DISPUTED, /* the sources name different types */
} CBMSupertypeState;
typedef enum {
CBM_SUPER_IN_BODY = 0, /* written in the type's own declaration */
CBM_SUPER_OUTSIDE, /* written elsewhere (Ruby `K.include M` in another file) */
CBM_SUPER_UNRECORDED, /* applied by code the extractor does not read */
} CBMSupertypeWhere;
typedef struct CBMSupertype {
const char *type_qn;
uint8_t kind; /* CBMSupertypeKind */
uint8_t state; /* CBMSupertypeState */
uint8_t where; /* CBMSupertypeWhere */
uint8_t side; /* the side of the type it adds to (Ruby: instance or class) */
} CBMSupertype;
/* CBMRegisteredType.member_flags. Each makes some lookups answer "unknown". */
enum {
/* Names nobody declares are dispatched at run time (PHP __call /
* __callStatic, Ruby method_missing, Python __getattr__, Perl AUTOLOAD, a
* PHP enum's built-in cases/from/tryFrom): a lookup that finds nothing
* declared anywhere in the order is unknown, never absent. */
CBM_MEMBERS_OPEN = 1u << 0,
/* Members are defined by code nobody evaluates (Ruby define_method):
* unknown right after the type's own members. */
CBM_MEMBERS_COMPUTED = 1u << 1,
/* The project reopens a type from outside it (a Ruby core class): its
* listed members are only the project's. */
CBM_MEMBERS_REOPENED_EXTERNAL = 1u << 2,
/* Two declarations of the type disagree on its ancestry. */
CBM_MEMBERS_DECLS_DISAGREE = 1u << 3,
};
/* A rename a type applies to the members its mixins bring in. */
typedef enum {
/* `name` is another name for from_type's member from_name (PHP
* `T::m as a`); from_type NULL = whichever mixin declares from_name. */
CBM_RENAME_ALIAS = 1,
/* from_type's member `name` does not reach this type (PHP
* `S::m insteadof T` excludes T's m). */
CBM_RENAME_EXCLUDE,
} CBMMemberRenameKind;
typedef struct CBMMemberRename {
const char *name;
const char *from_type; /* a registered type QN (or NULL, see ALIAS) */
const char *from_name; /* ALIAS only */
uint8_t kind; /* CBMMemberRenameKind */
} CBMMemberRename;
// Hash-table bucket entry. Chains collisions via next-index list for overload sets.
typedef struct {
uint64_t hash; // FNV-1a of key
@@ -213,6 +293,11 @@ typedef struct CBMTypeRegistry {
const char **export_keys;
const char **export_targets;
int export_count;
/* Member-lookup orders per type (member_walk.h CBMMemberOrders), or NULL.
* A shared registry's builder fills and seals them before the seal of
* the registry; a per-file registry's owner attaches its own. */
struct CBMMemberOrders *member_orders;
} CBMTypeRegistry;
// Initialize a registry.
+1
View File
@@ -5,6 +5,7 @@
#include "lsp/type_rep.c"
#include "lsp/scope.c"
#include "lsp/type_registry.c"
#include "lsp/member_walk.c"
#include "lsp/go_lsp.c"
#include "lsp/generated/go_stdlib_data.c"
#include "lsp/c_lsp.c"
+4
View File
@@ -292,6 +292,10 @@ static void cr_walk_def(cr_ctx_t *c, CBMDefinition *d) {
cr_str(c, &facts->go_embedded);
cr_str(c, &facts->class_bindings);
cr_str(c, &facts->global_names);
cr_str(c, &facts->base_kinds);
cr_list(c, &facts->mixins);
cr_str(c, &facts->mixin_kinds);
cr_str(c, &facts->member_rules);
}
}
+5 -1
View File
@@ -8,6 +8,10 @@ const fs = require('fs');
const { spawnSync } = require('child_process');
const isWindows = process.platform === 'win32';
// How long the cached binary may take to answer --version: the same bound as
// CANDIDATE_TIMEOUT_MS in install.js (test/candidate-bound.test.js keeps the two
// equal; the launcher stays self-contained and does not load the installer).
const CANDIDATE_TIMEOUT_MS = 300_000;
// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,
// so the cached file is the executed file — there is no launcher pair to keep
// in sync and no adjacent payload to validate.
@@ -22,7 +26,7 @@ const cacheReady = () => {
// A cached Windows binary that cannot report its own version is not usable.
const probe = spawnSync(binPath, ['--version'], {
stdio: 'ignore',
timeout: 15_000,
timeout: CANDIDATE_TIMEOUT_MS,
windowsHide: true,
});
return !probe.error && probe.status === 0;
+6 -1
View File
@@ -17,7 +17,11 @@ const VERSION = require('./package.json').version;
const BIN_DIR = path.join(__dirname, 'bin');
const MAX_REDIRECTS = 5;
const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;
const CANDIDATE_TIMEOUT_MS = 15_000;
// How long a downloaded or cached binary may take to answer --version. A slow
// host (antivirus scan, emulation, first page-in) can need far more than a few
// seconds, but a candidate that never answers must not hang the start forever.
// Keep in sync with the Go wrapper (candidateVerifyBound) and the PyPI wrapper.
const CANDIDATE_TIMEOUT_MS = 300_000;
// Entry-count guard for the zip namespace check. Keep in sync with the Go
// wrapper (pkg/go/cmd/codebase-memory-mcp/main.go) and the PyPI wrapper.
const MAX_ARCHIVE_MEMBERS = 64;
@@ -840,6 +844,7 @@ if (require.main === module || module.parent == null) {
}
module.exports = {
CANDIDATE_TIMEOUT_MS,
UNIX_ARCHIVE_NAMES,
WINDOWS_ARCHIVE_NAMES,
WINDOWS_BINARY_NAME,
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const { CANDIDATE_TIMEOUT_MS } = require('../install.js');
// A slow host can need far more than 15 s to run a fresh binary's --version
// (#2877), while a candidate that never answers must still release the start.
// The Go wrapper (candidateVerifyBound) and the PyPI wrapper use the same bound.
test('candidate verification waits minutes, not seconds', () => {
assert.ok(CANDIDATE_TIMEOUT_MS >= 120_000, `bound is ${CANDIDATE_TIMEOUT_MS} ms`);
});
test('the launcher probes a cached binary with the same bound', () => {
const bin = fs.readFileSync(path.join(__dirname, '..', 'bin.js'), 'utf8');
const declared = bin.match(/const CANDIDATE_TIMEOUT_MS = ([\d_]+);/);
assert.ok(declared, 'bin.js declares its own CANDIDATE_TIMEOUT_MS');
assert.strictEqual(Number(declared[1].replace(/_/g, '')), CANDIDATE_TIMEOUT_MS);
assert.match(bin, /timeout: CANDIDATE_TIMEOUT_MS/);
assert.doesNotMatch(bin, /timeout:\s*\d/);
});
+4 -1
View File
@@ -46,7 +46,10 @@ _LOOPBACK_HTTP_URL = re.compile(
_LOOPBACK_HOSTNAMES = frozenset({"localhost", "127.0.0.1", "::1"})
_MAX_REDIRECTS = 5
_NETWORK_TIMEOUT_SECONDS = 120
_CANDIDATE_TIMEOUT_SECONDS = 15
# How long a downloaded binary may take to answer --version: generous for a
# slow host, finite so a candidate that never answers cannot hang the start.
# Keep in sync with the Go wrapper (candidateVerifyBound) and the npm wrapper.
_CANDIDATE_TIMEOUT_SECONDS = 300
# Entry-count guard for the archive namespace check. Keep in sync with the
# Go wrapper (pkg/go/cmd/codebase-memory-mcp/main.go) and the npm wrapper.
_MAX_ARCHIVE_MEMBERS = 64
+13
View File
@@ -113,6 +113,19 @@ class BinarySelectionTests(unittest.TestCase):
self.assertNotIn("install.sh", output)
class CandidateVerifyBoundTests(unittest.TestCase):
def test_candidate_verification_waits_minutes(self):
# A slow host can need far more than 15 s to run a fresh binary's
# --version (#2877); a candidate that never answers must still release
# the start. Same bound as the Go wrapper and the npm wrapper.
self.assertGreaterEqual(_cli._CANDIDATE_TIMEOUT_SECONDS, 120)
def test_verify_candidate_passes_the_bound(self):
with mock.patch.object(_cli.subprocess, "run") as run:
_cli._verify_candidate(Path("candidate"))
self.assertEqual(run.call_args.kwargs["timeout"], _cli._CANDIDATE_TIMEOUT_SECONDS)
class ProcessLivenessTests(unittest.TestCase):
def test_windows_probe_never_calls_os_kill(self):
with mock.patch.object(_cli.os, "name", "nt"), mock.patch.object(
+11 -2
View File
@@ -48,8 +48,13 @@
* 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 };
* itself (closure_identity_decline, pipeline_incremental.c).
* 6: defs carry their supertypes' kinds in "sk" and their mixin rules in "mr"
* (the shared member lookup, PHP); a version-5 surface has neither and must be
* re-extracted. Both are inputs of the def itself, compared like its other
* fields. In version 6, "ns" of a PHP type is the type's own namespace (a file
* may hold several), not the file's first one. */
enum { SURFACE_CODEC_VERSION = 6 };
/* Labels the incremental name registry serves that pxc_map_label does NOT
* carry into the CBMLSPDef set. Their (name, qn, label) triple must still
@@ -847,6 +852,8 @@ static char *surface_file_to_json(const CBMFileResult *result, CBMLanguage langu
yyjson_mut_obj_add_bool(doc, o, "ab", d->is_abstract);
add_str_array_or_null(doc, o, "dec", d->decorators, -1);
add_str_or_null(doc, o, "al", d->alias_target);
add_str_or_null(doc, o, "sk", d->supertype_kinds);
add_str_or_null(doc, o, "mr", d->member_rules);
yyjson_mut_obj_add_bool(doc, o, "sg", d->is_singleton);
add_str_or_null(doc, o, "mx", d->mixin_refs);
/* Stored for the routes that resolve against this row without
@@ -1267,6 +1274,8 @@ int cbm_lsp_surface_defs_from_json(CBMArena *arena, const char *defs_json, CBMLS
d->is_singleton = yyjson_get_bool(yyjson_obj_get(o, "sg"));
d->mixin_refs = arena_str_or_null(arena, yyjson_obj_get(o, "mx"));
d->type_scope = arena_str_or_null(arena, yyjson_obj_get(o, "ty"));
d->supertype_kinds = arena_str_or_null(arena, yyjson_obj_get(o, "sk"));
d->member_rules = arena_str_or_null(arena, yyjson_obj_get(o, "mr"));
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. */
+8 -1
View File
@@ -1593,9 +1593,12 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
int resolved = 0;
int unresolved = 0;
int errors = 0;
/* the shared layer's memo for this pass (site_bind.h) */
cbm_site_memo_t *site_memo = NULL;
for (int i = 0; i < file_count; i++) {
if (cbm_pipeline_check_cancel(ctx)) {
cbm_pipeline_site_memo_free(site_memo);
return CBM_NOT_FOUND;
}
@@ -1604,6 +1607,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
CBMFileResult *result = calls_get_or_extract(ctx, i, &files[i], &result_owned);
if (!result) {
if (atomic_load(&ctx->test_declarations_failed)) {
cbm_pipeline_site_memo_free(site_memo);
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
errors++;
@@ -1614,6 +1618,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
if (result_owned) {
cbm_free_result(result);
}
cbm_pipeline_site_memo_free(site_memo);
return CBM_PIPELINE_ABORT_PRESERVE_DB;
}
@@ -1656,7 +1661,8 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
cbm_external_import_index_t ext_imports = {0};
cbm_spawn_file_begin(result->imports.items, result->imports.count);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, files[i].language, result);
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, files[i].language, result,
&site_memo, evidence);
for (int c = 0; c < result->calls.count; c++) {
CBMCall *call = &result->calls.items[c];
if (!call->callee_name) {
@@ -1688,6 +1694,7 @@ int cbm_pipeline_pass_calls(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *file
}
}
cbm_pipeline_site_memo_free(site_memo);
cbm_log_info("pass.done", "pass", "calls", "total", itoa_log(total_calls), "resolved",
itoa_log(resolved), "unresolved", itoa_log(unresolved), "errors",
itoa_log(errors));
+155 -2
View File
@@ -14,6 +14,9 @@
* unknown one. In the text, `${{ github.workspace }}` is
* $GITHUB_WORKSPACE, `${{ github.action_path }}` $GITHUB_ACTION_PATH, any
* other `${{ }}` an unknown variable (its line breaks kept).
* A local `uses:` ("./...", a path from the repository root) is handed on
* as well: a step's names an action directory, a job's a reusable
* workflow file; one with `${{` in it is none.
* - Prow: a file with a top-level presubmits / postsubmits / periodics key
* (in-repo job config). A job container's command + args is exec'd, no
* shell: the words are literal, a kubelet `$(VAR)` unknown; `bash -c TEXT`
@@ -53,6 +56,8 @@ typedef struct {
const char *src;
const char *rel;
cbm_ci_cmd_fn fn;
cbm_ci_use_fn use_fn; /* local `uses:`; NULL: not wanted */
void *use_ud; /* use_fn's own userdata */
cbm_build_site_fn site_fn; /* a build-site walk's callback */
cbm_compose_service_fn service_fn; /* a compose walk's callback */
void *ud;
@@ -451,10 +456,29 @@ static const char *ci_run_default(const ci_t *c, TSNode m, const char *key) {
return ci_get_str(c, ci_get(c, ci_get(c, m, "defaults"), "run"), key);
}
static const char *ci_repo_path(CBMArena *a, const char *base, const char *rel);
/* The `uses:` of step or job `owner` when it names something of this
* repository: "./dir", "./.github/workflows/x.yml". One with an expression in
* it, or leaving the repository, is none. */
static void ci_local_use(const ci_t *c, TSNode owner, bool job) {
int row = 0;
const char *uses = c->use_fn ? ci_scalar(c, ci_get(c, owner, "uses"), &row) : NULL;
if (!uses || uses[0] != '.' || uses[SKIP_ONE] != '/' || strstr(uses, CI_EXPR_OPEN)) {
return;
}
const char *path = ci_repo_path(c->a, "", uses);
if (path) {
cbm_ci_use_t use = {.path = path, .job = job, .line = row + SKIP_ONE};
c->use_fn(&use, c->use_ud);
}
}
static void ci_gha_steps(const ci_t *c, TSNode steps, const char *job, const ci_scope_t *sc) {
int n = 0;
TSNode *items = ci_items(c, steps, &n);
for (int i = 0; i < n; i++) {
ci_local_use(c, items[i], false);
int row = 0;
const char *run = ci_scalar(c, ci_get(c, items[i], "run"), &row);
if (!run) {
@@ -500,6 +524,7 @@ static void ci_workflow(const ci_t *c, TSNode root) {
ci_pair_t *jobs = ci_pairs(c, ci_get(c, root, "jobs"), &n);
for (int i = 0; i < n; i++) {
TSNode j = jobs[i].value;
ci_local_use(c, j, true);
const char *wd = ci_run_default(c, j, "working-directory");
const char *sh = ci_run_default(c, j, "shell");
ci_scope_t sc = {.env = ci_env_add(c, &wenv, ci_get(c, j, "env")),
@@ -1129,10 +1154,131 @@ static const char *ci_compose_build_args(const ci_t *c, TSNode build, const ci_e
return json ? cbm_arena_sprintf(c->a, "%s}", json) : NULL;
}
/* ── Files a compose service reads (PHASE 4 P4.7) ─────────────────────
* The repository paths a service names, relative to the compose file's
* directory (its project directory):
* - volumes: a bind mount's host side -- the short form `./host:/ctr[:mode]`
* whose host side begins with `.` (compose reads one without it as a
* volume's name), and the long form {type: bind, source: host}, where
* the type says it is a path;
* - env_file: a path, a list of paths, a list of {path: ...};
* - configs / secrets: the top-level entry a service's list names (a name,
* or {source: name}), by that entry's `file:`.
* Variables are interpolated from the project's .env. A variable without a
* value, an absolute or home path and a path out of the repository are none.
* Whether a path is a file the index holds is the caller's to decide. */
typedef struct {
cbm_compose_file_t *v;
int n;
int cap;
} ci_files_t;
/* `p` (interpolated already; NULL: none) as a repository path into `l`. */
static void ci_files_add(const ci_t *c, ci_files_t *l, const char *dir, const char *p,
const char *via, int row, bool dot_only) {
if (!p || !p[0] || p[0] == '~' || (dot_only && p[0] != '.') || l->n >= l->cap) {
return;
}
const char *path = ci_repo_path(c->a, dir, p);
if (path && path[0]) {
l->v[l->n++] = (cbm_compose_file_t){.path = path, .via = via, .line = row + SKIP_ONE};
}
}
static bool ci_is_mapping(TSNode n) {
return ci_type(n, "block_mapping") || ci_type(n, "flow_mapping");
}
/* name -> `file:` text (as written) of the entries of the top-level `key`
* mapping that have one; NULL: none. The caller frees the table. */
static CBMHashTable *ci_compose_named_files(const ci_t *c, TSNode root, const char *key) {
int n = 0;
ci_pair_t *defs = ci_pairs(c, ci_get(c, root, key), &n);
CBMHashTable *by_name = n > 0 ? cbm_ht_create((uint32_t)n) : NULL;
for (int i = 0; by_name && i < n; i++) {
const char *file = ci_get_str(c, defs[i].value, "file");
if (file && !cbm_ht_get(by_name, defs[i].key)) {
cbm_ht_set(by_name, defs[i].key, (void *)file);
}
}
return by_name;
}
/* The files service `svc` names; `named`: the top-level configs and secrets
* by name (ci_compose_named_files; either may be NULL). */
static int ci_compose_files(const ci_t *c, TSNode svc, const char *dir, const ci_env_t *env,
CBMHashTable *const named[PAIR_LEN], const cbm_compose_file_t **out) {
static const char *const KEY[PAIR_LEN] = {"configs", "secrets"};
static const char *const VIA[PAIR_LEN] = {"config", "secret"};
int nv = 0;
int ne = 0;
int nn[PAIR_LEN] = {0};
TSNode *vols = ci_items(c, ci_get(c, svc, "volumes"), &nv);
TSNode env_file = ci_get(c, svc, "env_file");
TSNode *envs = ci_items(c, env_file, &ne);
TSNode *refs[PAIR_LEN] = {NULL, NULL};
for (int k = 0; k < PAIR_LEN; k++) {
refs[k] = named[k] ? ci_items(c, ci_get(c, svc, KEY[k]), &nn[k]) : NULL;
}
ci_files_t l = {.cap = nv + ne + nn[0] + nn[SKIP_ONE] + SKIP_ONE};
l.v = cbm_arena_alloc(c->a, (size_t)l.cap * sizeof(*l.v));
*out = l.v;
if (!l.v) {
return 0;
}
for (int i = 0; i < nv; i++) {
int row = 0;
if (ci_is_mapping(vols[i])) {
const char *type = ci_get_str(c, vols[i], "type");
const char *source = type && strcmp(type, "bind") == 0
? ci_scalar(c, ci_get(c, vols[i], "source"), &row)
: NULL;
ci_files_add(c, &l, dir, source ? ci_interp(c->a, source, env) : NULL, "volume", row,
false);
continue;
}
/* interpolate first: a default (`${D:-./conf}`) holds a colon of its own */
const char *raw = ci_scalar(c, vols[i], &row);
const char *s = raw ? ci_interp(c->a, raw, env) : NULL;
const char *colon = s ? strchr(s, ':') : NULL;
if (colon) { /* without one: an anonymous volume's container path */
ci_files_add(c, &l, dir, cbm_arena_strndup(c->a, s, (size_t)(colon - s)), "volume", row,
true);
}
}
if (!envs) { /* a single path */
int row = 0;
const char *raw = ci_scalar(c, env_file, &row);
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, "env_file", row, false);
}
for (int i = 0; i < ne; i++) {
int row = 0;
const char *raw = ci_is_mapping(envs[i]) ? ci_scalar(c, ci_get(c, envs[i], "path"), &row)
: ci_scalar(c, envs[i], &row);
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, "env_file", row, false);
}
for (int k = 0; k < PAIR_LEN; k++) {
for (int i = 0; i < nn[k]; i++) {
int row = 0;
const char *name = ci_is_mapping(refs[k][i])
? ci_scalar(c, ci_get(c, refs[k][i], "source"), &row)
: ci_scalar(c, refs[k][i], &row);
const char *raw = name ? cbm_ht_get(named[k], name) : NULL;
ci_files_add(c, &l, dir, raw ? ci_interp(c->a, raw, env) : NULL, VIA[k], row, false);
}
}
return l.n;
}
static void ci_compose(const ci_t *c, TSNode root, const char *dir, const ci_env_t *env) {
static const ci_env_t no_env = {0};
int ns = 0;
ci_pair_t *svcs = ci_pairs(c, ci_get(c, root, "services"), &ns);
CBMHashTable *named[PAIR_LEN] = {NULL, NULL};
if (c->service_fn) {
named[0] = ci_compose_named_files(c, root, "configs");
named[SKIP_ONE] = ci_compose_named_files(c, root, "secrets");
}
for (int i = 0; i < ns; i++) {
TSNode svc = ci_content(svcs[i].value);
if (!ci_type(svc, "block_mapping") && !ci_type(svc, "flow_mapping")) {
@@ -1166,9 +1312,15 @@ static void ci_compose(const ci_t *c, TSNode root, const char *dir, const ci_env
.end_line = (int)ts_node_end_point(svc).row + SKIP_ONE};
s.ndeps = ci_compose_deps(c, svc, &s.deps);
s.nenv = ci_compose_env(c, svc, env, &s.env, &s.env_lines, &s.env_hosts);
s.nfiles = ci_compose_files(c, svc, dir, env, named, &s.files);
c->service_fn(&s, c->ud);
}
}
for (int k = 0; k < PAIR_LEN; k++) {
if (named[k]) {
cbm_ht_free(named[k]);
}
}
}
bool cbm_build_path(const char *rel) {
@@ -1265,7 +1417,7 @@ bool cbm_ci_path(const char *rel) {
}
void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len, cbm_ci_cmd_fn fn,
void *ud) {
void *ud, cbm_ci_use_fn use_fn, void *use_ud) {
if (!ci_yaml_ext(rel)) {
return;
}
@@ -1278,7 +1430,8 @@ void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len,
tree = ts_parser_parse_string(parser, NULL, src, (uint32_t)len);
}
if (tree) {
ci_t c = {.a = a, .src = src, .rel = rel, .fn = fn, .ud = ud};
ci_t c = {
.a = a, .src = src, .rel = rel, .fn = fn, .ud = ud, .use_fn = use_fn, .use_ud = use_ud};
TSNode stream = ts_tree_root_node(tree);
for (uint32_t i = 0; i < ts_node_named_child_count(stream); i++) {
TSNode doc = ts_node_named_child(stream, i);
+26
View File
@@ -21,6 +21,7 @@ enum { PD_SWIFT_PROPS_MARGIN = 80 };
#include <stdint.h>
#include <ctype.h>
#include "pipeline/pipeline_internal.h"
#include "pipeline/site_bind.h"
#include "graph_buffer/graph_buffer.h"
#include "foundation/log.h"
#include "foundation/mem_core.h" /* cbm_alloc/cbm_free: the grown properties buffer */
@@ -1235,6 +1236,24 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
cbm_pipeline_diagram_arrows(ctx, result);
cbm_pipeline_create_env_configures_for_file(ctx, result, files[i].rel_path);
}
/* The shared layer's scope (site_bind.h): every file is extracted and
* its IMPORTS made; built once, before any resolver. The route that
* runs the resolvers frees it. Mirrors pipeline.c's parallel route. */
if (!ctx->site_scope) {
struct timespec st;
cbm_clock_gettime(CLOCK_MONOTONIC, &st);
ctx->site_scope = cbm_pipeline_site_scope_build(ctx, files, file_count, local_cache,
NULL, 0, NULL, 0);
if (ctx->site_scope) {
struct timespec now;
cbm_clock_gettime(CLOCK_MONOTONIC, &now);
long ms = (long)((now.tv_sec - st.tv_sec) * CBM_MSEC_PER_SEC +
(now.tv_nsec - st.tv_nsec) / CBM_NSEC_PER_MSEC);
char ms_buf[CBM_SZ_32];
snprintf(ms_buf, sizeof(ms_buf), "%ld", ms);
cbm_log_info("pass.timing", "pass", "site_scope", "elapsed_ms", ms_buf);
}
}
/* Publish instead of free — see the twin in pass_parallel.c (#1355).
* Only the Scala index is pass-local. */
cbm_pipeline_import_maps_free(NULL, scala_index);
@@ -1248,6 +1267,13 @@ int cbm_pipeline_pass_definitions(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t
}
cbm_free(CBM_MEM_CLASS_EXTRACT, local_cache);
}
} else if (!ctx->site_scope) {
/* No result cache (its allocation failed): no scope of the shared
* layer either, so every site keeps main's answer, as for a language
* without a row (never a wrong answer; the parallel route, which always
* has its cache, answers). Logged so a run that degraded shows it. */
cbm_log_warn("site_bind.scope_skipped", "reason", "no_result_cache", "effect",
"main_decides_every_site");
}
cbm_registry_build_swift_owners(ctx->registry, ctx->gbuf, ctx->repo_path, ctx->excluded_dirs,
+191 -10
View File
@@ -38,6 +38,22 @@
* global EnvVar a program's readers share is not joined: the same name is
* read by other programs (measured: 23 % of such joins in scope). Values are
* never read into the graph.
*
* PHASE 4 P4.6: the repository files a Dockerfile copies. Each context source
* of a COPY / ADD written as a plain path -- no --from, no URL, no glob, no
* variable -- that is an indexed file under exactly one of the two contexts a
* build of this Dockerfile can have (its directory, the repository root) is a
* file the Dockerfile REFERENCES_FILE {via: copy | add, line}: File to File,
* once per file, at the first instruction naming it. Which context a build
* reads is in the build command, not in the Dockerfile, so a source that is a
* file under both is no edge; a directory is no edge (it names no one file).
*
* PHASE 4 P4.7: the repository files a compose service names -- a bind
* mount's host side, an env_file, a listed config's or secret's file
* (pass_ci.c reads them). Compose states these paths relative to the compose
* file's directory, so each that is an indexed file is a file the service
* REFERENCES_FILE {via: volume | env_file | config | secret, line}: service
* to File, once per file, at the first line naming it.
* Run at the end of the K8s pass.
*/
#include "foundation/constants.h"
@@ -65,12 +81,15 @@
enum { DK_MAX_STAGES = 64, DK_MAX_WORDS = 256, DK_MAX_DEPTH = 8 };
typedef struct dk_copy {
const char *from; /* --from= value; NULL: none, or unknown */
bool has_from; /* --from given */
const char **srcs; /* NULL entries: unknown */
const char *from; /* --from= value; NULL: none, or unknown */
bool has_from; /* --from given */
const char **srcs; /* NULL entries: unknown */
const uint8_t *var; /* per source: written with a variable (`$`) */
int nsrc;
const char *dst; /* as written; NULL: unknown */
const char *workdir;
int line;
bool add; /* ADD, not COPY */
struct dk_copy *next; /* the stage's previous COPY */
} dk_copy_t;
@@ -920,8 +939,9 @@ static char *dk_logical_line(dk_t *d, size_t at) {
return out;
}
/* A COPY / ADD in JSON form: its strings, expanded. */
static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
/* A COPY / ADD in JSON form: its strings, expanded; var[i]: string i was
* written with a variable. */
static int dk_copy_json(dk_t *d, const char *p, const char **out, uint8_t *var, int max) {
yyjson_doc *doc = yyjson_read(p, strlen(p), YYJSON_READ_STOP_WHEN_DONE);
yyjson_val *arr = doc ? yyjson_doc_get_root(doc) : NULL;
int n = 0;
@@ -930,6 +950,7 @@ static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
if (yyjson_is_arr(arr)) {
for (yyjson_arr_iter_init(arr, &it); n < max && (v = yyjson_arr_iter_next(&it));) {
const char *s = yyjson_get_str(v);
var[n] = s && strchr(s, '$') != NULL;
out[n++] = s ? dk_expand(d, d->local, cbm_arena_strdup(d->a, s), NULL) : NULL;
}
}
@@ -947,13 +968,15 @@ static int dk_copy_json(dk_t *d, const char *p, const char **out, int max) {
static void dk_copy(dk_t *d, TSNode ins) {
static const char FROM[] = "--from=";
const char *words[DK_MAX_WORDS];
uint8_t var[DK_MAX_WORDS];
int nw = 0;
dk_copy_t *c = cbm_arena_alloc(d->a, sizeof(*c));
char *p = dk_logical_line(d, ts_node_start_byte(ins));
if (!c || !p) {
return;
}
*c = (dk_copy_t){.workdir = d->workdir};
*c = (dk_copy_t){
.workdir = d->workdir, .line = dk_line(ins), .add = dk_type(ins, "add_instruction")};
p += strcspn(p, " \t"); /* the keyword */
for (;;) {
p += strspn(p, " \t");
@@ -974,10 +997,11 @@ static void dk_copy(dk_t *d, TSNode ins) {
}
p += l;
}
bool json = *p == '[' && (nw = dk_copy_json(d, p, words, DK_MAX_WORDS)) > 0;
bool json = *p == '[' && (nw = dk_copy_json(d, p, words, var, DK_MAX_WORDS)) > 0;
while (!json && *p && nw < DK_MAX_WORDS) {
size_t l = strcspn(p, " \t");
const char *w = cbm_arena_strndup(d->a, p, l);
var[nw] = w && strchr(w, '$') != NULL;
words[nw++] = w && strncmp(w, "<<", PAIR_LEN) != 0 ? dk_expand(d, d->local, w, NULL) : NULL;
p += l;
p += strspn(p, " \t");
@@ -986,10 +1010,13 @@ static void dk_copy(dk_t *d, TSNode ins) {
return;
}
c->srcs = cbm_arena_alloc(d->a, (size_t)(nw - SKIP_ONE) * sizeof(*c->srcs));
if (!c->srcs) {
uint8_t *cvar = cbm_arena_alloc(d->a, (size_t)(nw - SKIP_ONE));
if (!c->srcs || !cvar) {
return;
}
memcpy((void *)c->srcs, words, (size_t)(nw - SKIP_ONE) * sizeof(*c->srcs));
memcpy(cvar, var, (size_t)(nw - SKIP_ONE));
c->var = cvar;
c->nsrc = nw - SKIP_ONE;
c->dst = words[nw - SKIP_ONE];
c->next = d->st[d->stage].copies;
@@ -1735,6 +1762,104 @@ static void dk_image_set(dk_t *d) {
}
}
typedef struct {
int line;
bool add;
const cbm_gbuf_node_t *file;
} dk_fileref_t;
static int dk_fileref_cmp(const void *x, const void *y) {
const dk_fileref_t *a = x;
const dk_fileref_t *b = y;
if (a->line != b->line) {
return a->line < b->line ? -1 : SKIP_ONE;
}
return strcmp(a->file->file_path, b->file->file_path);
}
/* True when context source `src`, the file `hit` under one context candidate,
* is a directory under the other: the build command decides which of the two
* the instruction copies. */
static bool dk_dir_under_other_context(dk_t *d, const char *src, const char *hit) {
const char *ctxs[PAIR_LEN] = {d->dir, ""};
int nctx = d->dir[0] ? PAIR_LEN : SKIP_ONE;
while (*src == '/') {
src++;
}
for (int i = 0; d->ix->dirs && i < nctx; i++) {
const char *p = dk_norm(d, dk_join(d, ctxs[i], src));
if (p && strcmp(p, hit) != 0 && cbm_ht_get(d->ix->dirs, p)) {
return true;
}
}
return false;
}
/* P4.6: REFERENCES_FILE from the Dockerfile's File to each repository file a
* COPY / ADD of any stage names as a plain context source: no --from, no URL,
* no glob, no variable, and a file under exactly one of the two contexts
* (dk_repo) that is no directory under the other. Once per file, at the
* first instruction naming it. */
static void dk_copy_refs(dk_t *d) {
const cbm_gbuf_node_t *self = d->ix->files ? cbm_ht_get(d->ix->files, d->file) : NULL;
if (!self || d->stage < 0) {
return;
}
int cap = 0;
for (int s = 0; s <= d->stage && s < DK_MAX_STAGES; s++) {
for (const dk_copy_t *c = d->st[s].copies; c; c = c->next) {
cap += c->has_from ? 0 : c->nsrc;
}
}
dk_fileref_t *refs = cap ? cbm_arena_alloc(d->a, (size_t)cap * sizeof(*refs)) : NULL;
int n = 0;
for (int s = 0; refs && s <= d->stage && s < DK_MAX_STAGES; s++) {
for (const dk_copy_t *c = d->st[s].copies; c; c = c->next) {
for (int k = 0; !c->has_from && k < c->nsrc; k++) {
const char *src = c->srcs[k];
if (!src || c->var[k] || strstr(src, "://") || dk_glob(src)) {
continue;
}
/* Docker refuses a source that climbs out of its context,
* whichever context that is. */
const char *rel = dk_norm(d, src + strspn(src, "/"));
if (!rel || (rel[0] == '.' && rel[SKIP_ONE] == '.' &&
(rel[PAIR_LEN] == '/' || rel[PAIR_LEN] == '\0'))) {
continue;
}
const char *p = dk_repo(d, src, NULL, DK_WANT_FILE);
if (p && dk_dir_under_other_context(d, src, p)) {
continue;
}
const cbm_gbuf_node_t *file = p ? cbm_ht_get(d->ix->files, p) : NULL;
if (file && file != self) {
refs[n++] = (dk_fileref_t){c->line, c->add, file};
}
}
}
}
if (n == 0) {
return;
}
qsort(refs, (size_t)n, sizeof(*refs), dk_fileref_cmp);
CBMHashTable *seen = cbm_ht_create(0);
for (int i = 0; seen && i < n; i++) {
const char *path = refs[i].file->file_path;
if (cbm_ht_get(seen, path)) {
continue;
}
cbm_ht_set(seen, path, (void *)path);
const char *props = cbm_arena_sprintf(d->a, "{\"via\":\"%s\",\"line\":%d}",
refs[i].add ? "add" : "copy", refs[i].line);
if (props) {
cbm_gbuf_insert_edge(d->ctx->gbuf, self->id, refs[i].file->id, "REFERENCES_FILE",
props);
d->edges++;
}
}
cbm_ht_free(seen);
}
static void dk_file(dk_t *d, TSNode root) {
for (uint32_t i = 0; i < ts_node_named_child_count(root); i++) {
TSNode ins = ts_node_named_child(root, i);
@@ -1761,6 +1886,7 @@ static void dk_file(dk_t *d, TSNode root) {
dk_spawn(d);
dk_envs(d);
dk_image_set(d);
dk_copy_refs(d);
}
/* A build's view of the Dockerfile: only what decides its image references
@@ -1908,7 +2034,8 @@ typedef struct {
const char *file;
const char *base; /* the compose file's module QN */
int64_t file_node;
int pass; /* 0: make the service nodes, 1: their edges */
CBMHashTable *files; /* the repository's File nodes by path; NULL: none */
int pass; /* 0: make the service nodes, 1: their edges */
int edges;
} dk_compose_t;
@@ -1983,6 +2110,46 @@ static void dk_compose_image(dk_compose_t *c, const cbm_compose_service_t *s, in
}
}
static int dk_compose_file_cmp(const void *x, const void *y) {
const cbm_compose_file_t *a = x;
const cbm_compose_file_t *b = y;
if (a->line != b->line) {
return a->line < b->line ? -1 : SKIP_ONE;
}
int c = strcmp(a->path, b->path);
return c ? c : strcmp(a->via, b->via);
}
/* P4.7: REFERENCES_FILE {via: volume | env_file | config | secret, line} from
* service `self` to each indexed file it names (a bind mount's host side, an
* env_file, a listed config's or secret's file), once per file at the first
* line naming it. A directory, a file the index does not hold and the compose
* file itself are none: the paths are stated relative to the compose file's
* directory, so nothing is guessed. */
static void dk_compose_files(dk_compose_t *c, const cbm_compose_service_t *s, int64_t self) {
if (!c->files || s->nfiles <= 0) {
return;
}
cbm_compose_file_t *v = cbm_arena_alloc(c->a, (size_t)s->nfiles * sizeof(*v));
CBMHashTable *seen = v ? cbm_ht_create((uint32_t)s->nfiles) : NULL;
if (!seen) {
return;
}
memcpy(v, s->files, (size_t)s->nfiles * sizeof(*v));
qsort(v, (size_t)s->nfiles, sizeof(*v), dk_compose_file_cmp);
for (int i = 0; i < s->nfiles; i++) {
const cbm_gbuf_node_t *f = cbm_ht_get(c->files, v[i].path);
if (!f || f->id == c->file_node || cbm_ht_get(seen, v[i].path)) {
continue;
}
cbm_ht_set(seen, v[i].path, (void *)f);
dk_compose_edge(
c, self, f->id, "REFERENCES_FILE",
cbm_arena_sprintf(c->a, "{\"via\":\"%s\",\"line\":%d}", v[i].via, v[i].line));
}
cbm_ht_free(seen);
}
static void dk_compose_service(const cbm_compose_service_t *s, void *ud) {
dk_compose_t *c = ud;
const char *qn = dk_compose_qn(c, s->name);
@@ -2029,6 +2196,7 @@ static void dk_compose_service(const cbm_compose_service_t *s, void *ud) {
"{\"via\":\"build\",\"tool\":\"compose\"}");
}
}
dk_compose_files(c, s, self->id);
}
/* The .env of the directory of `rel` under the repository, NULL when none. */
@@ -2054,6 +2222,7 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
return 0;
}
dk_builds_t b = {.ctx = ctx, .a = a};
CBMHashTable *by_path = NULL; /* built at the first build configuration */
for (int i = 0; i < n; i++) {
const char *rel = files[i]->file_path;
if (!rel || !cbm_build_path(rel)) {
@@ -2066,6 +2235,14 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
if (!src) {
continue;
}
if (!by_path) {
by_path = cbm_ht_create((uint32_t)n);
for (int k = 0; by_path && k < n; k++) {
if (files[k]->file_path) {
cbm_ht_set(by_path, files[k]->file_path, (void *)files[k]);
}
}
}
char *dotenv = dk_read_dotenv(ctx, rel);
b.file = rel;
cbm_build_sites(a, rel, src, len, dotenv, dk_build_site, &b);
@@ -2073,7 +2250,8 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
.a = a,
.file = rel,
.base = cbm_fqn_compute(a, ctx->project_name, rel, NULL),
.file_node = files[i]->id};
.file_node = files[i]->id,
.files = by_path};
for (cs.pass = 0; cs.base && cs.pass < PAIR_LEN; cs.pass++) {
cbm_compose_services(a, rel, src, len, dotenv, dk_compose_service, &cs);
}
@@ -2083,6 +2261,9 @@ static int dk_link_builds(cbm_pipeline_ctx_t *ctx, CBMArena *a) {
}
cbm_free(CBM_MEM_CLASS_OTHER, src);
}
if (by_path) {
cbm_ht_free(by_path);
}
return b.edges;
}
+114 -5
View File
@@ -1322,6 +1322,15 @@ typedef struct {
int line;
} k8s_kchart_t;
/* A file a kustomization reads (extract_k8s.c FILE fact): input to its
* build, no member of it. */
typedef struct {
char *kust; /* the kustomization file */
char *path; /* the file, from the repository root */
const char *via; /* static: configMapGenerator, secretGenerator, configurations */
int line;
} k8s_kfile_t;
typedef struct {
k8s_ref_t *refs;
int ref_n;
@@ -1350,6 +1359,9 @@ typedef struct {
k8s_kchart_t *kcharts;
int kchart_n;
int kchart_cap;
k8s_kfile_t *kfiles;
int kfile_n;
int kfile_cap;
} k8s_facts_t;
static void k8s_facts_free(k8s_facts_t *f) {
@@ -1407,6 +1419,11 @@ static void k8s_facts_free(k8s_facts_t *f) {
cbm_free(CBM_MEM_CLASS_OTHER, c->values);
}
cbm_free(CBM_MEM_CLASS_OTHER, f->kcharts);
for (int i = 0; i < f->kfile_n; i++) {
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles[i].kust);
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles[i].path);
}
cbm_free(CBM_MEM_CLASS_OTHER, f->kfiles);
cbm_free(CBM_MEM_CLASS_OTHER, f->envs);
cbm_free(CBM_MEM_CLASS_OTHER, f->hrs);
cbm_free(CBM_MEM_CLASS_OTHER, f->srcs);
@@ -5368,21 +5385,59 @@ static void k8s_kchart_keep(k8s_facts_t *f, const char *kust, const CBMK8sFact *
.line = x->line};
}
/* Keep a kustomization's facts: its patches (PATCH) and the charts it
* inflates (DEPLOY via "kustomize"), each file as a repository path -- a
* patch file outside the repository (or a URL) names no file of it, a values
* file there is left out. */
/* The static name of a FILE fact's `via`; NULL: not one of ours. */
static const char *k8s_kfile_via(const char *via) {
static const char *const names[] = {"configMapGenerator", "secretGenerator", "configurations"};
for (size_t i = 0; via && i < sizeof(names) / sizeof(names[0]); i++) {
if (strcmp(via, names[i]) == 0) {
return names[i];
}
}
return NULL;
}
/* A file kustomization `kust` reads, at repository path `path`. */
static void k8s_kfile_keep(k8s_facts_t *f, const char *kust, const CBMK8sFact *x,
const char *path) {
const char *via = k8s_kfile_via(x->via);
if (!via || !k8s_grow((void **)&f->kfiles, &f->kfile_cap, f->kfile_n, sizeof(*f->kfiles))) {
return;
}
char *kust_copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, kust);
char *path_copy = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, path);
if (!kust_copy || !path_copy) {
cbm_free(CBM_MEM_CLASS_OTHER, kust_copy);
cbm_free(CBM_MEM_CLASS_OTHER, path_copy);
return;
}
f->kfiles[f->kfile_n++] =
(k8s_kfile_t){.kust = kust_copy, .path = path_copy, .via = via, .line = x->line};
}
/* Keep a kustomization's facts: its patches (PATCH), the charts it inflates
* (DEPLOY via "kustomize") and the files it reads (FILE), each file as a
* repository path -- a patch file outside the repository (or a URL) names no
* file of it, a values file or a read file there is left out. */
static void k8s_kustomize_keep(k8s_facts_t *f, const char *kust, const CBMFileResult *res) {
char dir[CBM_SZ_1K];
k8s_dirname(kust, dir, sizeof(dir));
for (int i = 0; res && i < res->k8s_facts.count; i++) {
const CBMK8sFact *x = &res->k8s_facts.items[i];
bool chart = x->fact == CBM_K8S_FACT_DEPLOY && x->via && strcmp(x->via, "kustomize") == 0;
if (x->fact != CBM_K8S_FACT_PATCH && !chart) {
bool file = x->fact == CBM_K8S_FACT_FILE;
if (x->fact != CBM_K8S_FACT_PATCH && !chart && !file) {
continue;
}
char path[CBM_SZ_1K];
bool in_repo = x->path && k8s_repo_path(dir, x->path, path, sizeof(path));
if (file) {
/* An absolute path names a file of the machine, not of the
* repository: k8s_repo_path would read it from the directory. */
if (in_repo && x->path[0] != '/') {
k8s_kfile_keep(f, kust, x, path);
}
continue;
}
if (chart) {
k8s_kchart_keep(f, kust, x, in_repo ? path : NULL);
continue;
@@ -5645,6 +5700,59 @@ static void k8s_patch_builds(const k8s_kusts_t *ks, const k8s_ints_t *inc, int k
}
}
static int k8s_cmp_kfile(const void *a, const void *b) {
const k8s_kfile_t *x = a;
const k8s_kfile_t *y = b;
int c = strcmp(x->kust, y->kust);
if (c == 0) {
c = (x->line > y->line) - (x->line < y->line);
}
return c ? c : strcmp(x->path, y->path);
}
/* The files kustomizations read -> REFERENCES_FILE {via: configMapGenerator |
* secretGenerator | configurations, line}, the kustomization's File to the
* file's File: once per kustomization and file, at the first line naming it.
* A file the index does not hold (a generated kubeconfig, a secret kept out
* of the repository) is none. Never an IMPORTS: that would make the file a
* member of the build (k8s_kusts_wire). */
static void k8s_link_kfiles(cbm_pipeline_ctx_t *ctx, k8s_facts_t *f) {
if (f->kfile_n == 0) {
return;
}
k8s_qsort(f->kfiles, (size_t)f->kfile_n, sizeof(*f->kfiles), k8s_cmp_kfile);
CBMArena keys;
cbm_arena_init_lazy(&keys, CBM_SZ_4K);
CBMHashTable *seen = cbm_ht_create((uint32_t)f->kfile_n);
int edges = 0;
for (int i = 0; seen && i < f->kfile_n; i++) {
const k8s_kfile_t *x = &f->kfiles[i];
const cbm_gbuf_node_t *tgt = cbm_pipeline_file_node(ctx->gbuf, ctx->project_name, x->path);
int64_t src = k8s_file_of(ctx, x->kust);
/* a File's QN folds `/` and `.` alike: the path itself must be the file's */
if (src <= 0 || !tgt || !tgt->file_path || strcmp(tgt->file_path, x->path) != 0 ||
tgt->id == src) {
continue;
}
const char *key = cbm_arena_sprintf(&keys, "%s\x01%s", x->kust, x->path);
if (!key || cbm_ht_get(seen, key)) {
continue;
}
cbm_ht_set(seen, key, (void *)key);
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"%s\",\"line\":%d}", x->via, x->line);
cbm_gbuf_insert_edge(ctx->gbuf, src, tgt->id, "REFERENCES_FILE", props);
edges++;
}
if (seen) {
cbm_ht_free(seen);
}
cbm_arena_destroy(&keys);
if (edges > 0) {
cbm_log_info("pass.k8s.kustomize_files", "edges", itoa_k8s(edges));
}
}
/* Kustomize patches -> OVERRIDE {via: patch, kustomization, patch, line},
* child -> base: each patch against the build of the kustomization stating
* it, a component's against the build of each kustomization including it
@@ -6111,6 +6219,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
k8s_helm_collect(ctx, &facts, &helm);
k8s_link_envs(ctx, &facts);
k8s_link_patches(ctx, &kusts, &facts);
k8s_link_kfiles(ctx, &facts);
k8s_link_renames(ctx, &kusts);
k8s_facts_free(&facts);
k8s_records_free(&recs);
+53
View File
@@ -751,6 +751,11 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
dst->namespace_name =
src->decl_namespace ? cbm_arena_strdup(arena, src->decl_namespace) : NULL;
}
/* PHP types too, where the extractor recorded it (a file may hold several
* namespaces): the member lookup finds a trait by namespace and name. */
if (lang == CBM_LANG_PHP && src->decl_namespace && cbm_label_is_type_like(src->label)) {
dst->namespace_name = cbm_arena_strdup(arena, src->decl_namespace);
}
dst->is_interface = (strcmp(label, "Interface") == 0 || strcmp(label, "Protocol") == 0);
/* The return-type string. The Go registrar splits it on '|' (go_lsp.c
* split_pipe_types), so a Go result LIST arrives split into its element
@@ -776,6 +781,7 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
/* 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. */
bool raw_bases = !(bs && bs->reg && pxc_lang_resolves_base_qns(lang));
dst->embedded_types =
(bs && bs->reg && pxc_lang_resolves_base_qns(lang))
? pxc_join_base_qns(arena, src->base_classes, bs, module_qn, src->qualified_name)
@@ -788,6 +794,48 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
? cbm_arena_sprintf(arena, "%s|%s", dst->embedded_types, facts->go_embedded)
: cbm_arena_strdup(arena, facts->go_embedded);
}
/* Member lookup (member_walk.h): the kind of each supertype, with the
* mixins (PHP trait uses) listed after the bases, and the rules of those
* uses. Kinds that do not describe exactly the listed entries are left
* out: the registrar then knows the ancestry only as unknown. */
if (lang != CBM_LANG_GO && raw_bases && facts && (facts->base_kinds || facts->mixins)) {
int nb = 0;
while (src->base_classes && src->base_classes[nb]) {
nb++;
}
int nm = 0;
while (facts->mixins && facts->mixins[nm]) {
nm++;
}
size_t bk = facts->base_kinds ? strlen(facts->base_kinds) : 0;
bool more = bk > 0 && facts->base_kinds[bk - 1] == '+';
bool kinds_ok = (int)bk - (more ? 1 : 0) == nb &&
(nm == 0 || (facts->mixin_kinds && (int)strlen(facts->mixin_kinds) == nm));
const char **all =
kinds_ok ? (const char **)cbm_arena_alloc(arena, (size_t)(nb + nm + 1) * sizeof(*all))
: NULL;
char *kinds = kinds_ok ? (char *)cbm_arena_alloc(arena, (size_t)(nb + nm + 2)) : NULL;
if (all && kinds) {
for (int i = 0; i < nb; i++) {
all[i] = src->base_classes[i];
kinds[i] = facts->base_kinds[i];
}
for (int i = 0; i < nm; i++) {
all[nb + i] = facts->mixins[i];
kinds[nb + i] = facts->mixin_kinds[i];
}
all[nb + nm] = NULL;
int nk = nb + nm;
if (more) {
kinds[nk++] = '+';
}
kinds[nk] = '\0';
dst->embedded_types = pxc_join_pipe(arena, all);
dst->supertype_kinds = kinds;
}
dst->member_rules =
facts->member_rules ? cbm_arena_strdup(arena, facts->member_rules) : NULL;
}
dst->signature_param_types = NULL;
dst->signature_param_count = 0;
if (src->signature_param_types && src->signature_param_count > 0) {
@@ -838,6 +886,11 @@ static int pxc_build_lsp_def(CBMArena *arena, const CBMDefinition *src, const ch
dst->trait_qn = src->impl_trait ? cbm_arena_strdup(arena, src->impl_trait) : NULL;
dst->is_abstract = src->is_abstract;
}
if (lang == CBM_LANG_PHP) {
/* A method without a body: a trait's is a requirement to the member
* lookup (member_walk.h). */
dst->is_abstract = src->is_abstract;
}
if (lang == CBM_LANG_RUBY) {
dst->is_singleton = src->is_singleton;
dst->mixin_refs = src->mixin_refs ? cbm_arena_strdup(arena, src->mixin_refs) : NULL;
+22 -6
View File
@@ -2112,7 +2112,10 @@ typedef struct __attribute__((aligned(CBM_CACHE_LINE))) {
* log line so divergence between pipelines becomes observable. */
int lsp_overrides;
CBMFileResult *loaded; /* spill-loaded result this worker is using */
char _pad[CBM_CACHE_LINE - 2 * sizeof(void *) - ((PP_RING + 1) * sizeof(int))];
/* the shared layer's memo of this worker (site_bind.h), made on its
* first lookup, freed after the workers join */
cbm_site_memo_t *site_memo;
char _pad[CBM_CACHE_LINE - 3 * sizeof(void *) - ((PP_RING + 1) * sizeof(int))];
} resolve_worker_state_t;
typedef struct {
@@ -3830,7 +3833,8 @@ static void resolve_file_calls(resolve_ctx_t *rc, resolve_worker_state_t *ws, CB
bool field_index_ready = false;
cbm_spawn_file_begin(result->imports.items, result->imports.count);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result, &ws->site_memo,
evidence);
for (int c = 0; c < result->calls.count; c++) {
const CBMCall *call = &result->calls.items[c];
CBMCallEvidence fallback = {0};
@@ -4304,7 +4308,8 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
bool field_index_ready =
cbm_pipeline_lsp_field_index_build(&result->resolved_calls, &field_index);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, rc->pctx, rc->main_gbuf, rel, lang, result, &ws->site_memo,
NULL);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
@@ -4462,11 +4467,20 @@ static void resolve_file_usages(resolve_ctx_t *rc, resolve_worker_state_t *ws,
* also agree: the same repo indexed in parallel and sequentially has to
* produce byte-identical edge properties. */
char uprops[CBM_SZ_512];
char esc_ref[CBM_SZ_256]; /* sliced source text: escape quotes/newlines */
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
if (scoped.verdict == CBM_SITE_PROVEN) {
/* a proven answer of the shared layer names its strategy
* (site_bind.h). MUST match pass_usages.c. */
cbm_pipeline_site_usage_props(uprops, sizeof(uprops), usage, CBM_SITE_PROVEN);
} else {
char esc_ref[CBM_SZ_256]; /* sliced source text: escape quotes/newlines */
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
}
const char *edge_type = precise_call_reference ? "CALL_REFERENCE" : "USAGE";
cbm_gbuf_insert_edge(ws->local_edge_buf, src->id, tgt->id, edge_type, uprops);
if (scoped.verdict == CBM_SITE_POSSIBLE) {
cbm_pipeline_site_bind_usage_drawn(&site, usage, tgt);
}
ws->usages_resolved++;
}
cbm_pipeline_site_bind_end(&site, ws->local_edge_buf);
@@ -5360,6 +5374,8 @@ int cbm_parallel_resolve(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int total_semantic = 0;
int total_lsp_overrides = 0;
for (int i = 0; i < worker_count; i++) {
cbm_pipeline_site_memo_free(workers[i].site_memo);
workers[i].site_memo = NULL;
if (workers[i].local_edge_buf) {
cbm_gbuf_merge(ctx->gbuf, workers[i].local_edge_buf);
total_calls += workers[i].calls_resolved;
+337 -17
View File
@@ -69,6 +69,9 @@
/* Candidate paths a target lookup scanned (complexity guard counter). */
_Atomic uint64_t g_sh_candidates = 0;
/* Targets, prerequisites and target-prerequisite pairs the Make dependency
* drawing looked at (complexity guard counter). */
_Atomic uint64_t g_sh_make_pairs = 0;
enum {
SH_GROW_MIN = 16,
@@ -384,12 +387,32 @@ typedef struct {
const char *default_of; /* pass-arena, build: JSON array of the ${X:-d} defaults naming `ext` */
} sh_hit_t;
/* A prerequisite a makefile rule states as one plain word. */
typedef struct {
const char *name; /* pass-arena */
int line;
bool order_only; /* after the rule's `|` */
} sh_mkpre_t;
/* A makefile rule with plain prerequisites (sh_make_deps). */
typedef struct {
const char *file; /* pass-arena: the makefile */
const char **targets; /* pass-arena: the rule's targets, as written */
int ntargets;
sh_mkpre_t *pres; /* pass-arena */
int npres;
uint32_t pos; /* the rule's source byte: the order make reads them in */
} sh_mkrule_t;
typedef struct {
sh_hit_t *items;
int count;
int cap;
CBMArena arena;
CBMHashTable *declarers; /* files running a container build: path -> path */
sh_mkrule_t *mkrules;
int nmkrules;
int cap_mkrules;
} sh_hits_t;
typedef struct {
@@ -3037,6 +3060,9 @@ struct mk {
int cap_lines;
mk_include_fn on_include; /* NULL: includes are not followed */
void *ud;
sh_hits_t *deps; /* NULL: the rules' prerequisites are not recorded */
const char *rel; /* with `deps`: the makefile */
int in_error; /* depth of the regions the grammar could not parse */
};
static const char MK_UNKNOWN[] = "${__cbm_unknown}";
@@ -3292,6 +3318,91 @@ static int mk_cmp_line(const void *a, const void *b) {
return (x > y) - (x < y);
}
/* A prerequisite make reads as written: one word that is no pattern (%), no
* glob and holds no variable. */
static bool mk_plain_word(TSNode w, const char *src) {
if (strcmp(ts_node_type(w), "word") != 0) {
return false;
}
uint32_t b = ts_node_start_byte(w);
uint32_t e = ts_node_end_byte(w);
for (uint32_t i = b; i < e; i++) {
if (src[i] == '\0' || strchr("%*?[$=", src[i])) {
return false;
}
}
return e > b;
}
static bool mk_is_prerequisites(TSNode n) {
return ts_node_is_named(n) && strcmp(ts_node_type(n), "prerequisites") == 0;
}
/* The plain prerequisites a rule states, with its targets: what sh_make_deps
* matches against the makefile's rule nodes. Read from the rule's
* `prerequisites` only, so a static pattern rule (`a.o: %.o: %.c`) yields
* none. A target-specific variable the grammar took for a rule
* (`t: override X = v`) shows as an ERROR in the rule line: none either. */
static void mk_rule_deps(mk_t *m, TSNode rule) {
sh_hits_t *h = m->deps;
TSNode targets = rule;
uint32_t nc = ts_node_child_count(rule);
uint32_t nt = 0;
int np = 0;
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_child(rule, i);
if (strcmp(ts_node_type(c), "ERROR") == 0 ||
(mk_is_prerequisites(c) && ts_node_has_error(c))) {
return;
}
if (nt == 0 && strcmp(ts_node_type(c), "targets") == 0) {
targets = c;
nt = ts_node_named_child_count(c);
}
for (uint32_t k = 0; mk_is_prerequisites(c) && k < ts_node_named_child_count(c); k++) {
np += mk_plain_word(ts_node_named_child(c, k), m->src);
}
}
if (nt == 0 || np == 0 ||
!sh_grow((void **)&h->mkrules, &h->cap_mkrules, h->nmkrules, sizeof(*h->mkrules))) {
return;
}
sh_mkrule_t r = {.file = cbm_arena_strdup(&h->arena, m->rel),
.targets = cbm_arena_alloc(&h->arena, nt * sizeof(*r.targets)),
.pres = cbm_arena_alloc(&h->arena, (size_t)np * sizeof(*r.pres)),
.pos = ts_node_start_byte(rule)};
if (!r.file || !r.targets || !r.pres) {
return;
}
for (uint32_t i = 0; i < nt; i++) {
TSNode t = ts_node_named_child(targets, i);
uint32_t tb = ts_node_start_byte(t);
const char *name = cbm_arena_strndup(&h->arena, m->src + tb, ts_node_end_byte(t) - tb);
if (name && name[0]) {
r.targets[r.ntargets++] = name;
}
}
for (uint32_t i = 0; i < nc; i++) {
TSNode c = ts_node_child(rule, i);
bool order_only = sh_eq(ts_node_field_name_for_child(rule, i), "order_only");
for (uint32_t k = 0; mk_is_prerequisites(c) && k < ts_node_named_child_count(c); k++) {
TSNode w = ts_node_named_child(c, k);
uint32_t wb = ts_node_start_byte(w);
const char *name =
mk_plain_word(w, m->src)
? cbm_arena_strndup(&h->arena, m->src + wb, ts_node_end_byte(w) - wb)
: NULL;
if (name && r.npres < np) {
r.pres[r.npres++] =
(sh_mkpre_t){name, (int)ts_node_start_point(w).row + SKIP_ONE, order_only};
}
}
}
if (r.ntargets > 0 && r.npres > 0) {
h->mkrules[h->nmkrules++] = r;
}
}
static void mk_collect(mk_t *m, TSNode n, bool cond);
static void mk_collect_error(mk_t *m, TSNode err, bool cond);
@@ -3302,6 +3413,9 @@ static void mk_collect_one(mk_t *m, TSNode c, bool cond) {
} else if (strcmp(t, "recipe_line") == 0) {
mk_split_lines(m, c);
} else if (strcmp(t, "rule") == 0 || strcmp(t, "recipe") == 0) {
if (m->deps && m->in_error == 0 && strcmp(t, "rule") == 0) {
mk_rule_deps(m, c);
}
mk_collect(m, c, cond);
} else if (strcmp(t, "ERROR") == 0) {
mk_collect_error(m, c, cond);
@@ -3367,6 +3481,7 @@ static void mk_collect_error(mk_t *m, TSNode err, bool cond) {
uint32_t scan = ts_node_start_byte(err);
uint32_t end = ts_node_end_byte(err);
int depth = 0;
m->in_error++;
for (uint32_t i = 0; i < ts_node_named_child_count(err); i++) {
TSNode c = ts_node_named_child(err, i);
uint32_t cb = ts_node_start_byte(c);
@@ -3379,8 +3494,16 @@ static void mk_collect_error(mk_t *m, TSNode err, bool cond) {
depth = depth < 0 ? 0 : depth;
scan = le + SKIP_ONE;
}
/* The grammar resumed before a rule that stands at the start of its
* line: its prerequisites are read as written. Anything else in the
* region (an indented rule, one nested in another node) is not. */
if (m->deps && m->in_error == SKIP_ONE && strcmp(ts_node_type(c), "rule") == 0 &&
ts_node_start_point(c).column == 0) {
mk_rule_deps(m, c);
}
mk_collect_one(m, c, cond || depth > 0);
}
m->in_error--;
}
static void sh_makefile(sh_pass_t *p, const char *rel, const char *src, size_t len) {
@@ -3398,7 +3521,9 @@ static void sh_makefile(sh_pass_t *p, const char *rel, const char *src, size_t l
.src = src,
.vars = cbm_ht_create(0),
.makefile = strcmp(base, "Makefile") == 0 || strcmp(base, "GNUmakefile") == 0 ||
strcmp(base, "makefile") == 0};
strcmp(base, "makefile") == 0,
.deps = p->hits,
.rel = rel};
if (m.vars) {
mk_collect(&m, ts_tree_root_node(tree), false);
}
@@ -3537,6 +3662,168 @@ static const char *mk_rule_key(CBMArena *a, const char *file, const char *name)
return cbm_arena_sprintf(a, "%s\x1f%s", file, name);
}
/* Into `rules` (file \x1f name -> node): the rule nodes of the files in
* `want`, the first rule of a name in a file. */
static void mk_rule_nodes(cbm_pipeline_ctx_t *ctx, CBMArena *a, CBMHashTable *want,
CBMHashTable *rules) {
const cbm_gbuf_node_t **nodes = NULL;
int count = 0;
if (cbm_ht_count(want) == 0 ||
cbm_gbuf_find_by_label(ctx->gbuf, "Function", &nodes, &count) != 0) {
return;
}
for (int i = 0; i < count; i++) {
const char *fp = nodes[i]->file_path;
if (!fp || !nodes[i]->name || !cbm_ht_get(want, fp)) {
continue;
}
const char *key = mk_rule_key(a, fp, nodes[i]->name);
const cbm_gbuf_node_t *old = key ? cbm_ht_get(rules, key) : NULL;
if (key && (!old || nodes[i]->start_line < old->start_line)) {
cbm_ht_set(rules, key, (void *)nodes[i]);
}
}
}
static int mk_cmp_rule(const void *a, const void *b) {
const sh_mkrule_t *x = a;
const sh_mkrule_t *y = b;
int c = strcmp(x->file, y->file);
return c ? c : (x->pos > y->pos) - (x->pos < y->pos);
}
/* One prerequisite edge to draw (sh_make_deps). */
typedef struct {
int64_t src;
int64_t dep;
int line;
bool order_only;
} sh_mkedge_t;
/* True the first time rule `rule` names node `id` in role `role` (a target,
* a normal prerequisite, an order-only one); a repeat on the same rule line
* is skipped, so the line costs its words plus its distinct pairs, not the
* product of its repeats. Sets *failed when the key cannot be kept. */
static bool mk_first_in_rule(CBMArena *a, CBMHashTable *once, bool *failed, int rule, char role,
int64_t id) {
const char *key = cbm_arena_sprintf(a, "%d%c%lld", rule, role, (long long)id);
if (!key) {
*failed = true;
return false;
}
if (cbm_ht_get(once, key)) {
return false;
}
cbm_ht_set(once, key, (void *)key);
return true;
}
/* A rule's prerequisite that names a rule of the same makefile: DEPENDS_ON
* {via: prerequisite, line} from each of the rule's targets to that rule's
* node -- once per pair, at the first line stating it, as make merges the
* prerequisites of a target's rules; an order-only one (after `|`) says so.
* A pair listed both ways is a normal prerequisite to make, at the first
* line listing it as one. The prerequisite is a plain word (mk_rule_deps):
* one with a variable, a pattern or a glob, one naming a file or a rule of
* another makefile, and a target naming itself draw nothing. */
static void sh_make_deps(cbm_pipeline_ctx_t *ctx, sh_hits_t *h) {
CBMArena a;
cbm_arena_init(&a);
CBMHashTable *want = cbm_ht_create(0);
CBMHashTable *rules = cbm_ht_create(0);
CBMHashTable *seen = cbm_ht_create(0); /* "<source id>><target id>" -> index in edges + 1 */
CBMHashTable *once = cbm_ht_create(0); /* a rule's own repeats (mk_first_in_rule) */
sh_mkedge_t *edges = NULL;
int nedges = 0;
int cap_edges = 0;
/* What cannot be kept draws nothing: half the statements of a pair could
* leave it order-only, or at a later line, than the makefile says. */
bool failed = !want || !rules || !seen || !once;
for (int i = 0; !failed && i < h->nmkrules; i++) {
cbm_ht_set(want, h->mkrules[i].file, (void *)h->mkrules[i].file);
}
if (!failed) {
mk_rule_nodes(ctx, &a, want, rules);
qsort(h->mkrules, (size_t)h->nmkrules, sizeof(*h->mkrules), mk_cmp_rule);
}
for (int i = 0; !failed && i < h->nmkrules; i++) {
const sh_mkrule_t *r = &h->mkrules[i];
if (r->ntargets <= 0 || r->npres <= 0) {
continue;
}
const cbm_gbuf_node_t **srcs = cbm_arena_alloc(&a, (size_t)r->ntargets * sizeof(*srcs));
int nsrc = 0;
failed = !srcs;
for (int t = 0; !failed && t < r->ntargets; t++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
const char *key = mk_rule_key(&a, r->file, r->targets[t]);
const cbm_gbuf_node_t *src = key ? cbm_ht_get(rules, key) : NULL;
failed = !key;
if (src && mk_first_in_rule(&a, once, &failed, i, 't', src->id)) {
srcs[nsrc++] = src;
}
}
for (int k = 0; !failed && nsrc > 0 && k < r->npres; k++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
const char *key = mk_rule_key(&a, r->file, r->pres[k].name);
const cbm_gbuf_node_t *dep = key ? cbm_ht_get(rules, key) : NULL;
failed = !key;
if (!dep || !mk_first_in_rule(&a, once, &failed, i, r->pres[k].order_only ? 'o' : 'p',
dep->id)) {
continue;
}
for (int t = 0; !failed && t < nsrc; t++) {
atomic_fetch_add_explicit(&g_sh_make_pairs, SKIP_ONE, memory_order_relaxed);
if (srcs[t] == dep) {
continue;
}
const char *pair =
cbm_arena_sprintf(&a, "%lld>%lld", (long long)srcs[t]->id, (long long)dep->id);
if (!pair) {
failed = true;
break;
}
intptr_t at = (intptr_t)cbm_ht_get(seen, pair);
if (at > 0) {
sh_mkedge_t *e = &edges[at - SKIP_ONE];
if (e->order_only && !r->pres[k].order_only) {
e->order_only = false;
e->line = r->pres[k].line;
}
continue;
}
if (!sh_grow((void **)&edges, &cap_edges, nedges, sizeof(*edges))) {
failed = true;
break;
}
edges[nedges++] =
(sh_mkedge_t){srcs[t]->id, dep->id, r->pres[k].line, r->pres[k].order_only};
cbm_ht_set(seen, pair, (void *)(intptr_t)nedges);
}
}
}
for (int i = 0; !failed && i < nedges; i++) {
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"prerequisite\",\"line\":%d%s}", edges[i].line,
edges[i].order_only ? ",\"order_only\":true" : "");
cbm_gbuf_insert_edge(ctx->gbuf, edges[i].src, edges[i].dep, "DEPENDS_ON", props);
}
cbm_free(CBM_MEM_CLASS_OTHER, edges);
if (want) {
cbm_ht_free(want);
}
if (rules) {
cbm_ht_free(rules);
}
if (seen) {
cbm_ht_free(seen);
}
if (once) {
cbm_ht_free(once);
}
cbm_arena_destroy(&a);
}
/* Each make hit's target: the rule node of that name in the makefile, else
* in the files it includes, in reading order (the first rule of a file).
* Read here, when linking, so an unchanged makefile is read too. */
@@ -3570,21 +3857,8 @@ static void sh_make_resolve(sh_pass_t *p, cbm_pipeline_ctx_t *ctx, sh_hits_t *h)
}
cbm_ht_set(closures, x->path, cl);
}
const cbm_gbuf_node_t **nodes = NULL;
int count = 0;
if (rules && want && cbm_ht_count(want) > 0 &&
cbm_gbuf_find_by_label(ctx->gbuf, "Function", &nodes, &count) == 0) {
for (int i = 0; i < count; i++) {
const char *fp = nodes[i]->file_path;
if (!fp || !nodes[i]->name || !cbm_ht_get(want, fp)) {
continue;
}
const char *key = mk_rule_key(&a, fp, nodes[i]->name);
const cbm_gbuf_node_t *old = key ? cbm_ht_get(rules, key) : NULL;
if (key && (!old || nodes[i]->start_line < old->start_line)) {
cbm_ht_set(rules, key, (void *)nodes[i]);
}
}
if (rules && want) {
mk_rule_nodes(ctx, &a, want, rules);
}
for (int i = 0; rules && closures && i < h->count; i++) {
sh_hit_t *x = &h->items[i];
@@ -4020,11 +4294,53 @@ static void sh_ci_cmd(const cbm_ci_cmd_t *cmd, void *ud) {
sh_state_free(&s);
}
typedef struct {
sh_pass_t *p;
const char *rel;
CBMArena *a;
CBMHashTable *seen; /* target paths drawn */
} sh_ci_use_t;
/* A local `uses:` of a workflow or composite action: REFERENCES_FILE {via:
* uses, line} from its File to the file it names -- a job's reusable
* workflow, a step's action by its action.yml or action.yaml (the one the
* directory holds; with both, or neither, there is no edge) -- once per
* file, at the first use. */
static void sh_ci_use(const cbm_ci_use_t *use, void *ud) {
static const char *const NAMES[PAIR_LEN] = {"action.yml", "action.yaml"};
sh_ci_use_t *x = ud;
const sh_index_t *ix = x->p->ix;
const char *target = use->job ? use->path : NULL;
for (int k = 0; !use->job && k < PAIR_LEN; k++) {
const char *cand =
cbm_arena_sprintf(x->a, "%s%s%s", use->path, use->path[0] ? "/" : "", NAMES[k]);
if (cand && cbm_ht_get(ix->file_ids, cand)) {
if (target) {
return; /* both spellings: which one GitHub reads is not ours to say */
}
target = cand;
}
}
int64_t src = (int64_t)(intptr_t)cbm_ht_get(ix->file_ids, x->rel);
int64_t tgt = target ? (int64_t)(intptr_t)cbm_ht_get(ix->file_ids, target) : 0;
if (src <= 0 || tgt <= 0 || src == tgt || !x->seen || cbm_ht_get(x->seen, target)) {
return;
}
cbm_ht_set(x->seen, target, (void *)target);
char props[CBM_SZ_64];
snprintf(props, sizeof(props), "{\"via\":\"uses\",\"line\":%d}", use->line);
cbm_gbuf_insert_edge(ix->ctx->gbuf, src, tgt, "REFERENCES_FILE", props);
}
static void sh_ci_file(sh_pass_t *p, const char *rel, const char *src, size_t len) {
CBMArena a;
cbm_arena_init(&a);
sh_ci_t x = {.p = p, .rel = rel, .a = &a};
cbm_ci_commands(&a, rel, src, len, sh_ci_cmd, &x);
sh_ci_use_t u = {.p = p, .rel = rel, .a = &a, .seen = cbm_ht_create(0)};
cbm_ci_commands(&a, rel, src, len, sh_ci_cmd, &x, sh_ci_use, &u);
if (u.seen) {
cbm_ht_free(u.seen);
}
cbm_arena_destroy(&a);
}
@@ -4151,6 +4467,10 @@ void cbm_pipeline_pass_shell(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
if (hits.count > 0 && p.ix_ok && p.parser) {
sh_make_resolve(&p, ctx, &hits);
}
if (hits.nmkrules > 0) {
sh_make_deps(ctx, &hits);
}
cbm_free(CBM_MEM_CLASS_OTHER, hits.mkrules);
int edges = hits.count > 0 ? sh_link(ctx, &hits) : 0;
if (hits.declarers) {
sh_mark_declarers(ctx, hits.declarers);
+101 -5
View File
@@ -954,7 +954,18 @@ static TSNode tf_root_body(TSNode root) {
* when that declares none of its names, of the nearest ancestor directory's
* module that does (applied by a -var-file the repository does not state:
* the edge says `inferred`): each assignment to a declared variable
* OVERRIDEs {via: tfvars, line} its `variable` block. */
* OVERRIDEs {via: tfvars, line} its `variable` block.
*
* A file function whose path begins at the module's own directory --
* file("${path.module}/x"), templatefile(...), filebase64(...) and the hash
* functions (filemd5, filesha1, filesha256, filesha512, filebase64sha256,
* filebase64sha512) -- reads a repository file: REFERENCES_FILE {via: <the
* function>, line} from the top-level block holding the call to that file's
* File node, once per block and file at the first call. The rest of the path
* must be literal. A path written without ${path.module} is relative to the
* directory Terraform is run in, which the module does not state: no edge;
* neither for path.root / path.cwd, another interpolation, or a file the
* index does not hold. */
typedef struct {
char *file; /* the referencing file */
@@ -974,6 +985,15 @@ typedef struct {
int line;
} tf_call_t;
/* A repository file a file function reads. */
typedef struct {
char *file; /* the calling file */
char *src; /* the holding top-level block's definition name */
char *path; /* the file it names, from the repository root */
const char *fn; /* static: the function */
int line;
} tf_fref_t;
typedef struct {
cbm_pipeline_ctx_t *ctx;
CBMArena *arena;
@@ -985,6 +1005,9 @@ typedef struct {
tf_call_t *mcalls;
int call_n;
int call_cap;
tf_fref_t *frefs;
int fref_n;
int fref_cap;
const char *dir; /* the module's directory */
const char *src; /* the file's text */
const char *file; /* its repository path (arena) */
@@ -1126,7 +1149,45 @@ static void tf_traversal(tf_mod_t *m, const char *src_block, TSNode v) {
}
}
/* Every traversal under `n` (iterative: deep expressions). */
static bool tf_text_is(const char *src, TSNode n, const char *word);
/* A call of a file function inside block `src_block`: the file its first
* argument names when that begins at ${path.module} (tf_string's anchor) and
* is literal otherwise. */
static void tf_file_call(tf_mod_t *m, const char *src_block, TSNode call) {
static const char *const FNS[] = {
"file", "templatefile", "filebase64", "filemd5", "filesha1",
"filesha256", "filesha512", "filebase64sha256", "filebase64sha512", NULL};
TSNode fn = ts_node_named_child(call, 0);
TSNode args = {0};
for (uint32_t i = 0; i < ts_node_named_child_count(call); i++) {
if (tf_type(ts_node_named_child(call, i), "function_arguments")) {
args = ts_node_named_child(call, i);
}
}
const char *name = NULL;
for (int k = 0; !ts_node_is_null(fn) && FNS[k] && !name; k++) {
name = tf_text_is(m->src, fn, FNS[k]) ? FNS[k] : NULL;
}
if (!name || ts_node_is_null(args) || ts_node_named_child_count(args) == 0) {
return;
}
char v[CBM_SZ_1K];
char path[CBM_SZ_1K];
if (!tf_string(m->src, m->dir, ts_node_named_child(args, 0), v, sizeof(v)) || v[0] != '\x01' ||
!tf_repo_path(m->dir, v, path, sizeof(path)) || !path[0] ||
!tf_grow((void **)&m->frefs, &m->fref_cap, m->fref_n, sizeof(*m->frefs))) {
return;
}
char *p = cbm_arena_strdup(m->arena, path);
if (p) {
m->frefs[m->fref_n++] = (tf_fref_t){(char *)m->file, (char *)src_block, p, name,
(int)ts_node_start_point(call).row + SKIP_ONE};
}
}
/* Every traversal and every file-function call under `n` (iterative: deep
* expressions). */
static void tf_walk_refs(tf_mod_t *m, const char *src_block, TSNode n) {
TSTreeCursor cur = ts_tree_cursor_new(n);
bool more = true;
@@ -1134,6 +1195,8 @@ static void tf_walk_refs(tf_mod_t *m, const char *src_block, TSNode n) {
TSNode c = ts_tree_cursor_current_node(&cur);
if (tf_type(c, "variable_expr")) {
tf_traversal(m, src_block, c);
} else if (tf_type(c, "function_call")) {
tf_file_call(m, src_block, c);
}
if (ts_tree_cursor_goto_first_child(&cur)) {
continue;
@@ -1280,8 +1343,11 @@ static int tf_ref_edge(tf_mod_t *m, int64_t src, int64_t tgt, const char *type,
/* Resolve the module's references against its declarations, module.X.Y
* against the outputs of X's source directory (`mods`: directory -> its
* module), and its local module calls to their directories' Folders. */
static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders) {
* module), its local module calls to their directories' Folders, and its
* file-function calls to the files they name (`files`: path -> File node;
* NULL: none). */
static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders,
CBMHashTable *files) {
int edges = 0;
for (int i = 0; i < m->ref_n; i++) {
const tf_ref_t *r = &m->refs[i];
@@ -1328,6 +1394,29 @@ static int tf_mod_link(tf_mod_t *m, CBMHashTable *mods, CBMHashTable *folders) {
cbm_gbuf_insert_edge(m->ctx->gbuf, src, folder->id, "IMPORTS", props);
edges++;
}
/* file functions: once per block and file, at the first call (the calls
* stand in source order, the module's files in path order) */
CBMHashTable *seen = files && m->fref_n > 0 ? cbm_ht_create((uint32_t)m->fref_n) : NULL;
for (int i = 0; seen && i < m->fref_n; i++) {
const tf_fref_t *r = &m->frefs[i];
const cbm_gbuf_node_t *f = cbm_ht_get(files, r->path);
int64_t src = f ? tf_def_node(m, r->file, r->src) : 0;
const char *key =
src > 0 && src != f->id
? cbm_arena_sprintf(m->arena, "%lld>%lld", (long long)src, (long long)f->id)
: NULL;
if (!key || cbm_ht_get(seen, key)) {
continue;
}
cbm_ht_set(seen, key, (void *)key);
char props[CBM_SZ_128];
snprintf(props, sizeof(props), "{\"via\":\"%s\",\"line\":%d}", r->fn, r->line);
cbm_gbuf_insert_edge(m->ctx->gbuf, src, f->id, "REFERENCES_FILE", props);
edges++;
}
if (seen) {
cbm_ht_free(seen);
}
return edges;
}
@@ -1340,6 +1429,7 @@ static void tf_mod_free(tf_mod_t *m) {
}
cbm_free(CBM_MEM_CLASS_OTHER, m->refs);
cbm_free(CBM_MEM_CLASS_OTHER, m->mcalls);
cbm_free(CBM_MEM_CLASS_OTHER, m->frefs);
cbm_free(CBM_MEM_CLASS_OTHER, m);
}
@@ -1481,6 +1571,7 @@ static int tf_link_repo(cbm_pipeline_ctx_t *ctx, TSParser *parser, const char *c
tf_mod_t **list = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)pn * sizeof(*list));
int nm = 0;
int calls = 0;
int frefs = 0;
for (int i = 0; mods && list && i < pn;) {
int j = i;
while (j < pn && tf_same_dir(paths[i], paths[j])) {
@@ -1491,13 +1582,18 @@ static int tf_link_repo(cbm_pipeline_ctx_t *ctx, TSParser *parser, const char *c
list[nm++] = m;
cbm_ht_set(mods, m->dir, m);
calls += m->call_n;
frefs += m->fref_n;
}
i = j;
}
CBMHashTable *folders = calls > 0 ? tf_label_index(ctx, "Folder") : NULL;
CBMHashTable *fileix = frefs > 0 ? tf_label_index(ctx, "File") : NULL;
int edges = 0;
for (int k = 0; k < nm; k++) {
edges += tf_mod_link(list[k], mods, folders);
edges += tf_mod_link(list[k], mods, folders, fileix);
}
if (fileix) {
cbm_ht_free(fileix);
}
for (int k = 0; mods && k < vn; k++) {
edges += tf_link_tfvars(&arena, parser, mods, ctx->repo_path, vpaths[k]);
+29 -7
View File
@@ -151,7 +151,8 @@ static const cbm_gbuf_node_t *find_enclosing_node(cbm_pipeline_ctx_t *ctx, const
/* Resolve USAGE edges for one file's extracted usages. */
static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result,
const char *rel, const char *module_qn, const char **imp_keys,
const char **imp_vals, int imp_count, CBMLanguage lang) {
const char **imp_vals, int imp_count, CBMLanguage lang,
cbm_site_memo_t **site_memo) {
int resolved = 0;
cbm_pipeline_lsp_reference_index_t reference_index = {0};
bool reference_index_ready =
@@ -163,7 +164,7 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
cbm_php_vendor_names_t php_vendor;
cbm_pipeline_php_vendor_names_build(ctx->gbuf, ctx->project_name, rel, result, &php_vendor);
cbm_site_file_t site;
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, lang, result);
cbm_pipeline_site_bind_begin(&site, ctx, ctx->gbuf, rel, lang, result, site_memo, NULL);
for (int u = 0; u < result->usages.count; u++) {
CBMUsage *usage = &result->usages.items[u];
if (!usage->ref_name) {
@@ -321,13 +322,22 @@ static int resolve_usage_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *res
}
/* ref_name is sliced source text and can contain quotes/newlines —
* escape it or the edge properties JSON is malformed. */
char esc_ref[CBM_SZ_256];
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
* escape it or the edge properties JSON is malformed. A proven answer
* of the shared layer names its strategy (site_bind.h). MUST match
* pass_parallel.c. */
char uprops[CBM_SZ_512];
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
if (scoped.verdict == CBM_SITE_PROVEN) {
cbm_pipeline_site_usage_props(uprops, sizeof(uprops), usage, CBM_SITE_PROVEN);
} else {
char esc_ref[CBM_SZ_256];
cbm_json_escape(esc_ref, sizeof(esc_ref), usage->ref_name);
snprintf(uprops, sizeof(uprops), "{\"callee\":\"%s\"}", esc_ref);
}
const char *edge_type = precise_call_reference ? "CALL_REFERENCE" : "USAGE";
cbm_gbuf_insert_edge(ctx->gbuf, src->id, tgt->id, edge_type, uprops);
if (scoped.verdict == CBM_SITE_POSSIBLE) {
cbm_pipeline_site_bind_usage_drawn(&site, usage, tgt);
}
resolved++;
}
cbm_pipeline_site_bind_end(&site, ctx->gbuf);
@@ -458,8 +468,20 @@ static int resolve_rw_edges(cbm_pipeline_ctx_t *ctx, const CBMFileResult *result
return resolved;
}
static int pass_usages_files(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files, int file_count,
cbm_site_memo_t **site_memo);
int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
int file_count) {
/* the shared layer's memo for this pass (site_bind.h) */
cbm_site_memo_t *site_memo = NULL;
int rc = pass_usages_files(ctx, files, file_count, &site_memo);
cbm_pipeline_site_memo_free(site_memo);
return rc;
}
static int pass_usages_files(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files, int file_count,
cbm_site_memo_t **site_memo) {
cbm_log_info("pass.start", "pass", "usages", "files", itoa_log(file_count));
int usage_resolved = 0;
@@ -533,7 +555,7 @@ int cbm_pipeline_pass_usages(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *fil
pu_module_is_dir(files[i].language));
usage_resolved += resolve_usage_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language);
imp_count, files[i].language, site_memo);
throw_resolved += resolve_throw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals,
imp_count, files[i].language);
rw_resolved += resolve_rw_edges(ctx, result, rel, module_qn, imp_keys, imp_vals, imp_count,
+26 -6
View File
@@ -25,6 +25,7 @@ enum { CBM_DIR_PERMS = 0755, PL_RING = 4, PL_RING_MASK = 3, PL_SEQ_PASSES = 7 };
#include "pipeline/lsp_resolve.h"
#include "pipeline/pass_lsp_cross.h"
#include "pipeline/pass_ensemble_routing.h"
#include "pipeline/site_bind.h"
#include "pipeline/worker_pool.h"
#include "graph_buffer/graph_buffer.h"
#include "git/git_context.h"
@@ -2632,12 +2633,15 @@ static void log_result_census(const char *tag, CBMFileResult **cache, int file_c
census_len(def->decl_namespace) + census_len(def->variant_key) +
census_len(def->alias_target) + census_len(def->mixin_refs);
if (def->type_facts) {
str_def_misc += sizeof(*def->type_facts) +
census_len(def->type_facts->type_params) +
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);
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) +
census_len(def->type_facts->base_kinds) + census_list(def->type_facts->mixins) +
census_len(def->type_facts->mixin_kinds) +
census_len(def->type_facts->member_rules);
}
}
for (int c = 0; c < r->calls.count; c++) {
@@ -2938,6 +2942,10 @@ static int run_sequential_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
rc = CBM_NOT_FOUND;
}
}
/* The definitions pass built the shared layer's scope; the resolvers
* are done with it. */
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
/* Consume infra bindings (YAML/HCL topic/queue/scheduler → endpoint) so
* INFRA_MAPS edges also form on the sequential path, not just the parallel
* one. process_one_infra_binding self-creates the topic Route node when no
@@ -3057,6 +3065,16 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
if (registry_next_id > atomic_load(&shared_ids)) {
atomic_store(&shared_ids, registry_next_id);
}
/* The shared layer's scope (site_bind.h): every file is extracted and
* its IMPORTS made; built once, sealed before the resolve workers start,
* freed after them. Mirrors pass_definitions.c on the sequential route. */
cbm_clock_gettime(CLOCK_MONOTONIC, t);
ctx->site_scope =
cbm_pipeline_site_scope_build(ctx, files, file_count, cache, NULL, 0, NULL, 0);
if (ctx->site_scope) {
cbm_log_info("pass.timing", "pass", "site_scope", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
}
/* Cross-file LSP precondition: build a project-wide CBMLSPDef[]
* once. The fused resolve_worker invokes cbm_pxc_run_one(_ts) per
* file using these defs + the file's IMPORTS map, so cross-file
@@ -3166,6 +3184,8 @@ static int run_parallel_pipeline(cbm_pipeline_t *p, cbm_pipeline_ctx_t *ctx,
rc = cbm_parallel_resolve(ctx, files, file_count, cache, &shared_ids, worker_count, all_defs,
def_count, def_modules, module_def_index, &cross_registries);
cbm_doclinks_end(ctx);
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
cbm_log_info("pass.timing", "pass", "parallel_resolve", "elapsed_ms",
itoa_buf((int)elapsed_ms(*t)));
pipeline_phase_mark("parallel_resolve");
+282
View File
@@ -24,6 +24,8 @@ enum { INCR_RING_BUF = 4, INCR_RING_MASK = 3, INCR_TS_BUF = 24 };
#include "pipeline/pipeline_internal.h"
#include "helpers.h" /* cbm_fqn_module */
#include "pipeline/doc_links.h"
#include "pipeline/scope_closure.h"
#include "pipeline/site_bind.h"
#include "store/store.h"
#include "graph_buffer/graph_buffer.h"
#include "discover/discover.h"
@@ -1553,6 +1555,12 @@ typedef struct {
* the arenas live exactly as long as cr.arena itself. */
CBMArena *rehydrate_arenas;
int rehydrate_arena_count;
/* The shared layer's scope reads every discovered file: the re-parsed
* ones fresh, the others from their stored facts (borrowed). */
const cbm_file_info_t *all_files;
int all_count;
const cbm_lsp_surface_row_t *stored_rows;
int stored_count;
} closure_resolve_t;
typedef struct {
@@ -2015,6 +2023,19 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
atomic_store(&shared_ids, registry_next_id);
}
/* The shared layer's scope (site_bind.h), sealed before the resolve
* workers start: the re-parsed files fresh, every other discovered
* file of a row language from its stored facts (closure repair). */
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
ctx->site_scope = cbm_pipeline_site_scope_build(
ctx, changed_files, ci, cache, closure ? closure->all_files : NULL,
closure ? closure->all_count : 0, closure ? closure->stored_rows : NULL,
closure ? closure->stored_count : 0);
if (ctx->site_scope) {
cbm_log_info("pass.timing", "pass", "incr_site_scope", "elapsed_ms",
itoa_buf((int)elapsed_ms(t)));
}
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
CBMLSPDef *all_defs = NULL;
int all_def_count = 0;
@@ -2143,6 +2164,8 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
cbm_doclinks_end(ctx);
cross_resolve_cleanup:
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
if (module_def_index) {
cbm_pxc_free_module_def_index(module_def_index);
}
@@ -2213,6 +2236,9 @@ static int run_extract_resolve(cbm_pipeline_ctx_t *ctx, cbm_file_info_t *changed
if (rc == 0) {
(void)cbm_pipeline_pass_doc_links(ctx, changed_files, ci);
}
/* the definitions pass built the shared layer's scope */
cbm_pipeline_site_scope_free(ctx->site_scope);
ctx->site_scope = NULL;
if (owns_cache) {
free_incremental_result_cache(cache, ci);
ctx->result_cache = prior_cache;
@@ -2697,6 +2723,141 @@ static bool closure_release_values(cbm_store_t *store, const char *project, cons
return hit;
}
/* Is p[0, n) a key of `table`? */
static bool closure_docker_has(CBMHashTable *table, const char *p, size_t n) {
char key[CBM_SZ_4K];
if (n == 0 || n >= sizeof(key)) {
return false;
}
memcpy(key, p, n);
key[n] = '\0';
return cbm_ht_get(table, key) != NULL;
}
/* A Dockerfile below the repository root reads a COPY / ADD source under its
* own directory or under the root, the one of the two that holds the file; a
* source both hold is no edge (pass_docker.c dk_repo: REFERENCES_FILE, and
* the path mapping behind SPAWNS). Deleting one file of such a pair leaves the
* other as the single candidate: an edge the full index draws from a
* Dockerfile that did not change, and a repair of the deleted file alone does
* not read that Dockerfile again. So a deleted file whose partner path is
* still indexed declines. Every Dockerfile's directory counts, whether or not
* the Dockerfile names the file: it is not parsed here.
*
* The two directions, each one lookup per directory level of a path:
* - deleted <dir>/<source>, <source> still a file at the root: the deleted
* path's own prefixes are tried as Dockerfile directories;
* - deleted <source>, <dir>/<source> still a file: every indexed file under
* a Dockerfile directory enters `under` by its path below that directory,
* and the deleted path is looked up there.
* A source that is a file under one context and a directory under the other
* is no edge either (dk_dir_under_other_context), and the directory goes
* with its last file. So the same holds one level up: a deleted file whose
* directory, below a Dockerfile directory, is a file at the root, or whose
* directory is <source> of a file <dir>/<source>, declines too -- also when
* the directory still holds other files, which costs a full run and no edge.
* Work is the path depths of the indexed and the deleted files (the deleted
* ones squared, a path being short), and only when a file was deleted and a
* Dockerfile lies below the root. Returns the reason, or NULL. */
static const char *closure_docker_context_decline(const cbm_file_info_t *files, int file_count,
CBMHashTable *files_by_path, char **deleted,
int n_deleted) {
CBMHashTable *dirs = NULL; /* directories holding a Dockerfile (keys in `keys`) */
CBMArena keys;
cbm_arena_init_lazy(&keys, CBM_SZ_4K);
const char *decline = NULL;
for (int f = 0; n_deleted > 0 && f < file_count && !decline; f++) {
const char *rel = files[f].rel_path;
const char *slash = files[f].language == CBM_LANG_DOCKERFILE ? strrchr(rel, '/') : NULL;
if (!slash) {
continue;
}
dirs = dirs ? dirs : cbm_ht_create(0);
char *dir = dirs ? cbm_arena_strndup(&keys, rel, (size_t)(slash - rel)) : NULL;
if (!dir) {
decline = "alloc";
} else {
cbm_ht_set(dirs, dir, dir);
}
}
/* <source> of each indexed <dir>/<source> */
CBMHashTable *under = dirs && !decline ? cbm_ht_create(0) : NULL;
if (dirs && !decline && !under) {
decline = "alloc";
}
for (int f = 0; under && f < file_count; f++) {
const char *rel = files[f].rel_path;
for (const char *s = strchr(rel, '/'); s; s = strchr(s + SKIP_ONE, '/')) {
if (s[SKIP_ONE] && closure_docker_has(dirs, rel, (size_t)(s - rel))) {
cbm_ht_set(under, s + SKIP_ONE, (void *)rel);
}
}
}
for (int i = 0; under && i < n_deleted && !decline; i++) {
const char *gone = deleted[i];
if (cbm_ht_get(under, gone)) {
decline = "docker_context_pair_deleted"; /* <dir>/<gone> is still a file */
}
for (const char *s = strchr(gone, '/'); s && !decline; s = strchr(s + SKIP_ONE, '/')) {
/* a directory of the deleted file that is <source> of a file
* <dir>/<source>: under the root it may be no directory now */
if (closure_docker_has(under, gone, (size_t)(s - gone))) {
decline = "docker_context_pair_deleted";
}
if (decline || !closure_docker_has(dirs, gone, (size_t)(s - gone))) {
continue;
}
const char *src = s + SKIP_ONE;
if (cbm_ht_get(files_by_path, src)) {
decline = "docker_context_pair_deleted"; /* <source> is still a file at the root */
}
/* a directory below <dir> that is a file at the root */
for (const char *t = strchr(src, '/'); t && !decline; t = strchr(t + SKIP_ONE, '/')) {
if (closure_docker_has(files_by_path, src, (size_t)(t - src))) {
decline = "docker_context_pair_deleted";
}
}
}
}
if (under) {
cbm_ht_free(under);
}
if (dirs) {
cbm_ht_free(dirs);
}
cbm_arena_destroy(&keys);
return decline;
}
/* A workflow names a local action by its directory, and its edge goes to the
* one action file that directory holds (pass_shell.c sh_ci_use); with both
* spellings, action.yml and action.yaml, there is none. Deleting one of the
* two makes the other the action: an edge the full index draws from a
* workflow that did not change, and the repair reads no workflow again. So
* a deleted action file whose other spelling is still indexed declines.
* One lookup per deleted file. Returns the reason, or NULL. */
static const char *closure_local_action_decline(CBMHashTable *files_by_path, char **deleted,
int n_deleted) {
static const char *const names[PAIR_LEN] = {"action.yml", "action.yaml"};
for (int i = 0; i < n_deleted; i++) {
const char *p = deleted[i];
const char *slash = p ? strrchr(p, '/') : NULL;
const char *base = slash ? slash + SKIP_ONE : p;
for (int k = 0; base && k < PAIR_LEN; k++) {
if (strcmp(base, names[k]) != 0) {
continue;
}
char other[CBM_SZ_4K];
int n = snprintf(other, sizeof(other), "%.*s%s", (int)(base - p), p,
names[PAIR_LEN - SKIP_ONE - k]);
if (n > 0 && (size_t)n < sizeof(other) && cbm_ht_get(files_by_path, other)) {
return "local_action_pair_deleted";
}
}
}
return NULL;
}
/* Kubernetes inputs reach past their own file (pass_k8s.c): a kustomization
* decides which manifests deploy together and in which namespace, a
* Chart.yaml links other charts, and a manifest's Services select workloads
@@ -3147,6 +3308,107 @@ static const char *closure_add_includers(const cbm_lsp_surface_row_t *rows, int
/* Decide whether this manifest delta is closure-repairable, and if so build
* the plan. Returns 1 with *plan filled, or 0 (decline → FULL) with the
* reason logged. Every early exit declines; nothing here mutates state. */
/* The file names (last path component) a row's stored facts re-export
* (`import public`), into `names`; 0, -1 when the row has no facts ("is"),
* -2 when they cannot be read. */
static int closure_scope_row(CBMArena *a, const cbm_lsp_surface_row_t *row, CBMHashTable *names) {
cbm_lsp_scope_facts_t facts;
int rc = cbm_lsp_surface_scope_from_json(a, row ? row->defs_json : NULL, &facts);
if (rc == 0) {
return CBM_NOT_FOUND;
}
if (rc != SKIP_ONE) {
return -PAIR_LEN;
}
for (int i = 0; i < facts.event_count; i++) {
const CBMScopeEvent *e = &facts.events[i];
if (names && e->kind == CBM_SCOPE_INCLUDE && (e->flags & CBM_SCOPE_REEXPORT) &&
e->index >= 0 && e->index < facts.module_count) {
const char *slash = strrchr(facts.modules[e->index], '/');
cbm_ht_set(names, slash ? slash + SKIP_ONE : facts.modules[e->index], (void *)1);
}
}
return 0;
}
/* Whether a file may be what some re-export names (by its last path
* component: never fewer than the path rule would resolve). */
static bool closure_scope_reexported(CBMHashTable *names, const char *rel) {
const char *slash = strrchr(rel, '/');
return cbm_ht_get(names, slash ? slash + SKIP_ONE : rel) != NULL;
}
/* The shared layer's scope (site_bind.h) on a repair reads every file of a
* row language the repair leaves alone from its stored facts: a row without
* them (an older binary wrote it) or with unreadable ones declines. A file's
* changed facts reach the files with an edge into it (its includers re-resolve
* as dependents); when it is re-exported (`import public`) they also reach
* the re-exporter's includers, which have no edge into it: a surface change
* (or deletion) of a file some re-export may name declines too. NULL: the
* repair may go on. */
static const char *closure_scope_decline(const cbm_lsp_surface_row_t *stored, int stored_count,
CBMHashTable *rows_by_path,
const cbm_lsp_surface_row_t *fresh, int fresh_count,
CBMHashTable *files_by_path, char **changed, int n_changed,
int n_deleted) {
CBMArena a;
cbm_arena_init(&a);
const char *why = NULL;
CBMHashTable *reexported = cbm_ht_create(CBM_SZ_16);
if (!reexported) {
cbm_arena_destroy(&a);
return "alloc";
}
for (int i = 0; i < stored_count && !why; i++) {
const cbm_file_info_t *info = cbm_ht_get(files_by_path, stored[i].rel_path);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
int rc = closure_scope_row(&a, &stored[i], reexported);
why = rc == CBM_NOT_FOUND ? "scope_facts_missing" : rc < 0 ? "scope_facts_malformed" : NULL;
}
for (int i = 0; i < fresh_count && !why; i++) {
const cbm_file_info_t *info = cbm_ht_get(files_by_path, fresh[i].rel_path);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
int rc = closure_scope_row(&a, &fresh[i], reexported);
why = rc < 0 ? "scope_facts_malformed" : NULL;
}
bool changed_scope = false;
bool any = cbm_ht_count(reexported) > 0;
for (int i = 0; i < n_changed + n_deleted && !why && any && !changed_scope; i++) {
if (!closure_scope_reexported(reexported, changed[i])) {
continue;
}
const cbm_lsp_surface_row_t *old_row = cbm_ht_get(rows_by_path, changed[i]);
if (i >= n_changed) {
/* a deleted file whose row holds facts is of a row language */
changed_scope = old_row && closure_scope_row(&a, old_row, NULL) != CBM_NOT_FOUND;
continue;
}
const cbm_file_info_t *info = cbm_ht_get(files_by_path, changed[i]);
if (!info || !cbm_closure_lang(info->language)) {
continue;
}
const cbm_lsp_surface_row_t *new_row = NULL;
for (int j = 0; j < fresh_count; j++) {
if (strcmp(fresh[j].rel_path, changed[i]) == 0) {
new_row = &fresh[j];
break;
}
}
changed_scope = old_row && (!new_row || !old_row->surface_sha || !new_row->surface_sha ||
strcmp(old_row->surface_sha, new_row->surface_sha) != 0);
}
if (!why && changed_scope) {
why = "scope_reexport_changed";
}
cbm_ht_free(reexported); /* keys borrowed from the arena */
cbm_arena_destroy(&a);
return why;
}
static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *project,
cbm_file_info_t *files, int file_count, const cbm_file_hash_t *stored,
int stored_count, const cbm_file_hash_t *fresh, int fresh_count,
@@ -3271,6 +3533,15 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
if (decline) {
goto done;
}
decline = closure_docker_context_decline(files, file_count, files_by_path,
changed_paths + n_changed, n_deleted);
if (decline) {
goto done;
}
decline = closure_local_action_decline(files_by_path, changed_paths + n_changed, n_deleted);
if (decline) {
goto done;
}
decline = closure_terraform_decline(changed_paths, n_changed + n_deleted);
if (decline) {
goto done;
@@ -3361,6 +3632,13 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p
decline = "probe_failed";
goto done;
}
decline =
closure_scope_decline(plan->stored_rows, plan->stored_count, rows_by_path, probe_rows,
probe_count, files_by_path, changed_paths, n_changed, n_deleted);
if (decline) {
cbm_ht_free(rows_by_path);
goto done;
}
/* Validate Python namespace metadata before any hash cutoff or dependent
* query. Python changes require a full rebuild; other surface changes and
@@ -3828,6 +4106,10 @@ static int run_closure_delta(cbm_pipeline_t *p, const char *db_path, const char
}
cbm_arena_init(&cr.arena);
cr_arena_live = true;
cr.all_files = files;
cr.all_count = file_count;
cr.stored_rows = plan->stored_rows;
cr.stored_count = plan->stored_count;
cbm_clock_gettime(CLOCK_MONOTONIC, &t);
{
/* Eligible rows first (skip everything being re-parsed or deleted),
+39 -3
View File
@@ -586,6 +586,11 @@ typedef struct {
* files with the context, read-only afterwards, freed with it. NULL: no
* import is read by the path rule (main's strategies decide). */
struct cbm_include_universe *include_universe;
/* The shared cross-file layer's scope (site_bind.h): built after IMPORTS
* on one thread, read only by the resolvers, freed by the route that
* built it. NULL: no file of a row language (every site NO_ANSWER). */
struct cbm_site_scope *site_scope;
} cbm_pipeline_ctx_t;
/* The set for cbm_pipeline_ctx_t.indexed_files: every rel_path of `files`
@@ -1439,11 +1444,24 @@ typedef void (*cbm_ci_cmd_fn)(const cbm_ci_cmd_t *cmd, void *ud);
* (.github/workflows/<name>.yml|yaml) or a composite action (action.yml|yaml). */
bool cbm_ci_path(const char *rel);
/* A local `uses:` of a GitHub workflow or composite action (pass_ci.c): a
* path from the repository root ("./..."), which is how GitHub reads it
* wherever the file lies. A step's names an action's directory (`path`; ""
* is the root), a job's names a reusable workflow file. `line` is 1-based. */
typedef struct {
const char *path;
bool job;
int line;
} cbm_ci_use_t;
typedef void (*cbm_ci_use_fn)(const cbm_ci_use_t *use, void *ud);
/* Hand each command line the CI configuration `rel` (YAML text src) runs to
* fn: GitHub Actions run: steps for a workflow or composite action, else
* Prow job containers. Strings live in arena `a`. */
* Prow job containers. In the same walk, each local `uses:` of a workflow or
* composite action goes to use_fn (NULL: not wanted) with use_ud, in
* document order. Strings live in arena `a`. */
void cbm_ci_commands(CBMArena *a, const char *rel, const char *src, size_t len, cbm_ci_cmd_fn fn,
void *ud);
void *ud, cbm_ci_use_fn use_fn, void *use_ud);
/* An image a build configuration builds from a Dockerfile (pass_ci.c). */
typedef struct {
@@ -1455,6 +1473,18 @@ typedef struct {
} cbm_build_site_t;
typedef void (*cbm_build_site_fn)(const cbm_build_site_t *site, void *ud);
/* A repository file a compose service names (pass_ci.c): a path relative to
* the compose file's directory, normalised -- a bind mount's host side
* ("volume"), an env_file entry ("env_file"), the file of a config or secret
* the service lists ("config" / "secret") -- with the 1-based line where the
* service names it. The path may be a directory, or a file the index does
* not hold. */
typedef struct {
const char *path;
const char *via;
int line;
} cbm_compose_file_t;
/* A compose service (pass_ci.c): its image (a reference, variables
* expanded; NULL: none or unknown), the Dockerfile its build names
* (repository path; NULL: no build, or unknown), the service names its
@@ -1465,7 +1495,7 @@ typedef void (*cbm_build_site_fn)(const cbm_build_site_t *site, void *ud);
* image_default_of: the variables whose inline default (${X:-d}) named the
* image; image_override_of: those whose default the project's .env replaced
* (JSON arrays, NULL: none), and default_image the image those defaults
* name. */
* name. files: the repository paths it names (cbm_compose_file_t). */
typedef struct {
const char *name;
const char *image;
@@ -1479,6 +1509,8 @@ typedef struct {
const int *env_lines;
const char **env_hosts;
int nenv;
const cbm_compose_file_t *files;
int nfiles;
int line;
int end_line;
} cbm_compose_service_t;
@@ -1681,6 +1713,10 @@ extern _Atomic uint64_t g_importance_store_rows;
extern _Atomic uint64_t g_k8s_candidates;
extern _Atomic uint64_t g_op_candidates;
extern _Atomic uint64_t g_sh_candidates;
/* Targets, prerequisites and target-prerequisite pairs the Make dependency
* drawing looked at (pass_shell.c sh_make_deps): linear in a rule line's
* words plus its distinct pairs, however often a name is repeated. */
extern _Atomic uint64_t g_sh_make_pairs;
/* ── Incremental pipeline (pipeline_incremental.c) ───────────────── */
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
#ifndef CBM_SCOPE_CLOSURE_H
#define CBM_SCOPE_CLOSURE_H
/*
* scope_closure.h — which definitions named N a file sees, unordered mode:
* the closure and the lookup of the shared cross-file layer.
*
* A file sees its own definitions, those of its package mates where the row
* says a package is visible, and what each file it includes exports. A file
* exports its own definitions and what its re-exporting includes export
* (Protobuf `import public`); a plain include is not passed on. The closure is
* never listed per file: re-exporting includes are collapsed into strongly
* connected components, and a lookup of N searches backwards from the
* components of N's defining files along re-export edges, once per name
* (memoised per name and component).
*
* The lookup answers, in its own terms (possible against proven):
* PROVEN exactly one visible definition, the closure complete, the
* name not bound locally, the definition not conditional;
* POSSIBLE exactly one visible definition otherwise (a source on the way
* is unresolved or outside the repository, opaque, a prelude);
* NO_ANSWER none visible with an incomplete closure, or two or more;
* PROVEN_ABSENT none visible, the closure complete (counted only).
* `why` says what kept an answer from being proven; drawing is the caller's.
*
* Threads: built and sealed on one thread; afterwards the closure is read
* only. A lookup writes nothing but the memo it is handed, so each thread
* brings its own (cbm_closure_memo_t). The memo only saves work: an answer is
* the same with a fresh memo, a used one or none.
*/
#include "cbm.h"
#include <stdbool.h>
#include <stdint.h>
/* One language's scope row. */
typedef struct {
CBMLanguage lang;
bool package_visible; /* a file sees its package mates' definitions without an include */
bool prelude_external; /* names may come from an implicit external prelude */
bool ambiguity_is_error; /* two visible definitions do not compile: one visible past an
* unresolved or external source is still the one */
bool qualified_refs; /* a reference as written is read against full names from the
* scopes around it (Protobuf; see cbm_closure_ref_t) */
} cbm_closure_lang_t;
/* The row of a language, or NULL. */
const cbm_closure_lang_t *cbm_closure_lang(CBMLanguage lang);
typedef enum {
CBM_CLOSURE_NO_ANSWER = 0,
CBM_CLOSURE_PROVEN,
CBM_CLOSURE_POSSIBLE,
CBM_CLOSURE_PROVEN_ABSENT,
} cbm_closure_verdict_t;
/* Why an answer is not proven (several may hold). */
enum {
CBM_CLOSURE_WHY_UNRESOLVED = 1u << 0, /* an include on the way names no repository file */
CBM_CLOSURE_WHY_OPAQUE = 1u << 1, /* a file on the way has a part the facts cannot read */
CBM_CLOSURE_WHY_PRELUDE = 1u << 2, /* the row's names may come from a prelude */
CBM_CLOSURE_WHY_LOCAL = 1u << 3, /* the reference is bound by a parameter or local */
CBM_CLOSURE_WHY_CONDITIONAL = 1u << 4, /* the one definition may not be in effect */
CBM_CLOSURE_WHY_AMBIGUOUS = 1u << 5, /* two or more definitions are visible */
CBM_CLOSURE_WHY_NO_NODE = 1u << 6, /* the one definition has no graph node */
/* the one definition is in a message of the referring file (or the
* file's package is unknown) and the reference carries no scope: the
* enclosing message decides (protoc's scope walk) */
CBM_CLOSURE_WHY_SCOPE = 1u << 7,
};
/* How the answer's definition is visible. */
enum { CBM_CLOSURE_VIA_OWN = 1, CBM_CLOSURE_VIA_INCLUDE = 2, CBM_CLOSURE_VIA_PACKAGE = 3 };
/* The lookup key of one site. */
typedef struct {
const char *name; /* the last identifier */
/* the reference as written, qualifier included ("common.Status",
* ".a.b.Outer.Inner"), or NULL for the bare name. A row with qualified
* references reads it against definitions' full names: a leading dot is
* the root; otherwise the full name is a scope around the referring site
* followed by it, the innermost scope in which its first component names
* a symbol deciding. A definition whose full name is unknown matches by
* its name alone. */
const char *written;
/* the innermost scope around the site, the first one searched
* ("a.b.Outer": the enclosing message; "a.b": the package; "": the
* root), or NULL when it is unknown: then the scopes are the referring
* file's package and each package around it, and any message of the
* file holding a definition of the first component may decide first
* (an answer is then at most possible) */
const char *scope;
uint32_t pos; /* the site's byte (ordered rows; unused in unordered mode) */
uint8_t ns; /* namespace (unused in unordered mode) */
uint8_t flags; /* CBM_CLOSURE_REF_* */
} cbm_closure_ref_t;
enum { CBM_CLOSURE_REF_LOCAL = 1u << 0 /* bound by a parameter or a local */ };
typedef struct {
cbm_closure_verdict_t verdict;
const char *qn; /* the definition's qualified name (PROVEN, POSSIBLE), else NULL */
const char *full; /* ... and its full name, NULL when unknown */
int file; /* its file, else -1 */
int visible; /* definitions named N visible from the file (2 means two or more) */
bool complete; /* every source on the way is a repository file the facts read whole */
uint32_t why; /* CBM_CLOSURE_WHY_* */
uint8_t via; /* CBM_CLOSURE_VIA_* of the answer */
} cbm_closure_answer_t;
typedef struct cbm_closure cbm_closure_t;
cbm_closure_t *cbm_closure_new(void);
void cbm_closure_free(cbm_closure_t *s);
/* A file of a language with a row; returns its index, -1 on failure (also
* for a path added twice). `package` "" when it has none, NULL when unknown
* (references from the file then read every scope as possibly around them). */
int cbm_closure_add_file(cbm_closure_t *s, const char *rel, const cbm_closure_lang_t *row,
const char *package);
/* A definition of `file`: its name, full name (or NULL: unknown), graph
* qualified name (NULL: the graph has no node for it) and whether it is
* conditional. Strings are copied. */
bool cbm_closure_add_def(cbm_closure_t *s, int file, const char *name, const char *full,
const char *qn, bool conditional);
/* An include of `file`: the included file, or -1 when it names no repository
* file; re-exporting or plain. */
bool cbm_closure_add_include(cbm_closure_t *s, int file, int target, bool reexport);
/* A part of `file` the facts cannot read (an OPAQUE event). */
bool cbm_closure_add_opaque(cbm_closure_t *s, int file);
/* After the last file: components, completeness and the by-name index.
* Returns 0, or -1 on allocation failure. No file is added after it. */
int cbm_closure_seal(cbm_closure_t *s);
/* The index of the file at `rel`, or -1. */
int cbm_closure_file(const cbm_closure_t *s, const char *rel);
/* Files and definitions added (memory reports). */
int cbm_closure_file_count(const cbm_closure_t *s);
int cbm_closure_def_count(const cbm_closure_t *s);
/* One thread's memo of what components export per name. */
typedef struct cbm_closure_memo cbm_closure_memo_t;
cbm_closure_memo_t *cbm_closure_memo_new(void);
void cbm_closure_memo_free(cbm_closure_memo_t *m);
/* What `ref` names from `file`. `memo` may be NULL (nothing is kept). */
cbm_closure_answer_t cbm_closure_lookup(const cbm_closure_t *s, cbm_closure_memo_t *memo, int file,
const cbm_closure_ref_t *ref);
/* Counted work (growth tests): of building and sealing the closure, and of
* the lookups a memo served (reach steps, lookup steps). */
uint64_t cbm_closure_work(const cbm_closure_t *s);
uint64_t cbm_closure_memo_work(const cbm_closure_memo_t *m);
#endif /* CBM_SCOPE_CLOSURE_H */
+734 -18
View File
@@ -3,28 +3,463 @@
* sites. See site_bind.h for where the resolvers ask and how they apply an
* answer.
*
* No language has a row yet, so begin marks no file active, every site gets
* NO_ANSWER and the end step draws nothing: the hook costs a few calls per
* file and one call per site.
* The run's scope is the visibility closure (scope_closure.h) of every file
* of a row language, from its scope facts (extract_scope.c): DEF events are
* the definitions, INCLUDE events the includes, resolved to repository files
* by the path rule (include_path.h), OPAQUE events parts the facts cannot
* read. A usage is looked up by the type reference it ends (a QREF event).
*/
#include "pipeline/site_bind.h"
#include "cbm.h"
#include "foundation/compat_fs.h"
#include "foundation/constants.h"
#include "foundation/hash_table.h"
#include "foundation/log.h"
#include "foundation/mem_core.h"
#include "foundation/platform.h"
#include "foundation/str_util.h"
#include "graph_buffer/graph_buffer.h"
#include "pipeline/include_path.h"
#include "pipeline/lsp_surface.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "pipeline/scope_closure.h"
#include <stdatomic.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* Strategies and confidences of the layer's edges. */
#define SB_PROVEN_STRATEGY "include_scope"
#define SB_POSSIBLE_STRATEGY "include_scope_may"
#define SB_PROVEN_CONF 0.95
#define SB_POSSIBLE_CONF 0.85
enum { SB_PATH_BUF = 1024, SB_PROPS_BUF = 2048 };
struct cbm_site_scope {
cbm_closure_t *closure;
int files;
int stored_files;
int unreadable_files;
int includes;
int includes_resolved;
/* run totals (count only), summed by every resolver thread */
_Atomic uint64_t proven;
_Atomic uint64_t possible;
_Atomic uint64_t drawn;
_Atomic uint64_t same;
_Atomic uint64_t disagree;
_Atomic uint64_t present;
_Atomic uint64_t unsettled;
_Atomic uint64_t absent;
/* CBM_SITE_BIND_DUMP=<path> (test-seam builds only): one line per
* answered site and per settled possible answer, appended (measurement) */
FILE *dump;
/* building only: resolved include path -> the first import spelling
* that named it (in spell_arena); freed before the closure is sealed */
CBMHashTable *spellings;
CBMArena spell_arena;
};
static const char *sb_verdict_name(cbm_closure_verdict_t v) {
switch (v) {
case CBM_CLOSURE_PROVEN:
return "proven";
case CBM_CLOSURE_POSSIBLE:
return "possible";
case CBM_CLOSURE_PROVEN_ABSENT:
return "absent";
default:
return "no_answer";
}
}
struct cbm_site_memo {
cbm_closure_memo_t *closure_memo;
};
void cbm_pipeline_site_memo_free(cbm_site_memo_t *m) {
if (m) {
cbm_closure_memo_free(m->closure_memo);
cbm_free(CBM_MEM_CLASS_OTHER, m);
}
}
/* A POSSIBLE answer, settled when the file is done. */
struct sb_pending {
int64_t source_id;
const cbm_gbuf_node_t *target;
int index; /* the usage or call in sf->result */
bool is_call;
bool main_drew; /* usage: main's chain drew a USAGE edge at the site */
const cbm_gbuf_node_t *main_target; /* ... to this node */
};
/* ── Building the run's scope ───────────────────────────────────────── */
/* One file's facts: fresh (a result) or stored (a surface row's "is"). */
typedef struct {
const char *rel;
CBMLanguage lang;
const cbm_closure_lang_t *row;
const CBMFileResult *result; /* fresh */
cbm_lsp_scope_facts_t facts; /* stored */
bool stored;
bool readable;
int index; /* in the closure */
} sb_file_t;
/* The package a file's facts name: every INCLUDE event carries it; NULL
* (unknown) for a file without one. */
/* The file's package: the one its INCLUDE events carry; a file without one
* (no import) gives it through its definitions: the full name of the one with
* the fewest components is the package followed by its name (a top-level
* definition; a nested one has more). NULL: unknown (no import, no
* definition). `buf` holds a derived package. */
static const char *sb_package(const CBMScopeEvent *ev, int n, char *buf, size_t cap) {
int best = -1;
size_t best_dots = SIZE_MAX;
for (int i = 0; i < n; i++) {
if (ev[i].kind == CBM_SCOPE_INCLUDE && ev[i].qual) {
return ev[i].qual; /* a stored row's INCLUDE carries none: read the definitions */
}
if (ev[i].kind == CBM_SCOPE_DEF && ev[i].qual && ev[i].name) {
size_t dots = 0;
for (const char *c = ev[i].qual; *c; c++) {
dots += *c == '.';
}
if (dots < best_dots) {
best_dots = dots;
best = i;
}
}
}
if (best < 0) {
return NULL;
}
const char *qual = ev[best].qual;
size_t ql = strlen(qual);
size_t nl = strlen(ev[best].name);
if (ql == nl) {
return strcmp(qual, ev[best].name) == 0 ? "" : NULL;
}
if (ql <= nl + SKIP_ONE || qual[ql - nl - SKIP_ONE] != '.' ||
strcmp(qual + ql - nl, ev[best].name) != 0 || ql - nl - SKIP_ONE >= cap) {
return NULL;
}
memcpy(buf, qual, ql - nl - SKIP_ONE);
buf[ql - nl - SKIP_ONE] = '\0';
return buf;
}
static void sb_add_events(const cbm_pipeline_ctx_t *ctx, cbm_site_scope_t *sc, const sb_file_t *f) {
const CBMScopeEvent *ev = f->stored ? f->facts.events : f->result->scope.items;
int n = f->stored ? f->facts.event_count : f->result->scope.count;
for (int i = 0; i < n; i++) {
const CBMScopeEvent *e = &ev[i];
bool conditional = (e->flags & CBM_SCOPE_CONDITIONAL) != 0;
switch (e->kind) {
case CBM_SCOPE_DEF: {
const CBMDefinition *d = NULL;
if (f->stored && e->index >= 0 && e->index < f->facts.def_count) {
d = &f->facts.defs[e->index];
} else if (!f->stored && e->index >= 0 && e->index < f->result->defs.count) {
d = &f->result->defs.items[e->index];
}
(void)cbm_closure_add_def(sc->closure, f->index, e->name, e->qual,
d ? d->qualified_name : NULL, conditional);
if (sc->dump) {
fprintf(sc->dump, "D\t%s\t%s\t%s\t%s\n", f->rel, e->name ? e->name : "",
e->qual ? e->qual : "", d && d->qualified_name ? d->qualified_name : "");
}
break;
}
case CBM_SCOPE_ASSIGN:
/* a name defined here with no node of the graph */
(void)cbm_closure_add_def(sc->closure, f->index, e->name, NULL, NULL, conditional);
break;
case CBM_SCOPE_INCLUDE: {
CBMImport imp;
memset(&imp, 0, sizeof(imp));
if (f->stored && e->index >= 0 && e->index < f->facts.module_count) {
imp.module_path = f->facts.modules[e->index];
} else if (!f->stored && e->index >= 0 && e->index < f->result->imports.count) {
imp = f->result->imports.items[e->index];
}
char path[SB_PATH_BUF];
int target = CBM_NOT_FOUND;
if (imp.module_path &&
cbm_include_path_resolve(ctx->include_universe, ctx->gbuf, ctx->project_name,
f->rel, f->lang, &imp, path,
sizeof(path)) == CBM_INCLUDE_PATH_FILE) {
target = cbm_closure_file(sc->closure, path);
}
if (target >= 0 && sc->spellings) {
const char *first = cbm_ht_get(sc->spellings, path);
if (!first) {
const char *k = cbm_arena_strdup(&sc->spell_arena, path);
const char *v = cbm_arena_strdup(&sc->spell_arena, imp.module_path);
if (k && v) {
cbm_ht_set(sc->spellings, k, (void *)v);
}
} else if (strcmp(first, imp.module_path) != 0) {
/* one file named by two import spellings: protoc reads two
* virtual files that define the same names ("already
* defined"), so nothing through it is proven */
(void)cbm_closure_add_opaque(sc->closure, target);
}
}
sc->includes++;
sc->includes_resolved += target >= 0;
(void)cbm_closure_add_include(sc->closure, f->index, target,
(e->flags & CBM_SCOPE_REEXPORT) != 0);
break;
}
case CBM_SCOPE_OPAQUE:
(void)cbm_closure_add_opaque(sc->closure, f->index);
break;
default:
break;
}
}
}
cbm_site_scope_t *cbm_pipeline_site_scope_build(const cbm_pipeline_ctx_t *ctx,
const cbm_file_info_t *fresh, int fresh_count,
CBMFileResult **cache, const cbm_file_info_t *all,
int all_count, const cbm_lsp_surface_row_t *stored,
int stored_count) {
if (!ctx || !ctx->include_universe) {
return NULL;
}
/* Row files: the fresh ones, then the other discovered ones (stored). */
int nrow = 0;
for (int i = 0; i < fresh_count; i++) {
nrow += cbm_closure_lang(fresh[i].language) != NULL;
}
for (int i = 0; all && i < all_count; i++) {
nrow += cbm_closure_lang(all[i].language) != NULL;
}
if (nrow == 0) {
return NULL; /* no file of a row language: no cost at all */
}
cbm_site_scope_t *sc = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*sc));
sb_file_t *files = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)nrow * sizeof(*files));
bool *loaded = cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)nrow * sizeof(*loaded));
CBMHashTable *fresh_rel = cbm_ht_create(CBM_SZ_64);
CBMHashTable *rows_by_rel = stored_count > 0 ? cbm_ht_create(CBM_SZ_256) : NULL;
CBMArena facts_arena;
cbm_arena_init(&facts_arena);
bool ok = sc && files && loaded && fresh_rel && (stored_count == 0 || rows_by_rel);
if (ok) {
memset(sc, 0, sizeof(*sc));
memset(files, 0, (size_t)nrow * sizeof(*files));
memset(loaded, 0, (size_t)nrow * sizeof(*loaded));
sc->closure = cbm_closure_new();
ok = sc->closure != NULL;
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
/* measurement only, in test-seam builds: the product never reads the
* variable nor opens a file (sc->dump stays NULL) */
char dump_path[SB_PATH_BUF];
if (ok && cbm_safe_getenv("CBM_SITE_BIND_DUMP", dump_path, sizeof(dump_path), NULL)) {
sc->dump = cbm_fopen(dump_path, "a");
}
#endif
} else if (sc) {
memset(sc, 0, sizeof(*sc));
}
int n = 0;
for (int i = 0; ok && i < fresh_count; i++) {
const cbm_closure_lang_t *row = cbm_closure_lang(fresh[i].language);
if (!row) {
continue;
}
sb_file_t *f = &files[n];
f->rel = fresh[i].rel_path;
f->lang = fresh[i].language;
f->row = row;
f->result = cache ? cbm_pipeline_result_acquire(ctx, cache, i, NULL, &loaded[n]) : NULL;
f->readable = f->result != NULL;
cbm_ht_set(fresh_rel, f->rel, f);
n++;
}
for (int i = 0; ok && i < stored_count; i++) {
if (stored[i].rel_path) {
cbm_ht_set(rows_by_rel, stored[i].rel_path, (void *)&stored[i]);
}
}
for (int i = 0; ok && all && i < all_count; i++) {
const cbm_closure_lang_t *row = cbm_closure_lang(all[i].language);
if (!row || cbm_ht_get(fresh_rel, all[i].rel_path)) {
continue;
}
sb_file_t *f = &files[n++];
f->rel = all[i].rel_path;
f->lang = all[i].language;
f->row = row;
f->stored = true;
const cbm_lsp_surface_row_t *r = rows_by_rel ? cbm_ht_get(rows_by_rel, f->rel) : NULL;
f->readable =
r && cbm_lsp_surface_scope_from_json(&facts_arena, r->defs_json, &f->facts) == SKIP_ONE;
}
/* Files first, so an include can name any of them. */
for (int i = 0; ok && i < n; i++) {
sb_file_t *f = &files[i];
const char *package = NULL;
char pkgbuf[SB_PATH_BUF];
if (f->readable) {
package = f->stored ? sb_package(f->facts.events, f->facts.event_count, pkgbuf,
sizeof(pkgbuf))
: sb_package(f->result->scope.items, f->result->scope.count, pkgbuf,
sizeof(pkgbuf));
}
f->index = cbm_closure_add_file(sc->closure, f->rel, f->row, package);
if (f->index < 0) {
f->readable = false; /* a path seen twice: the first one stands */
continue;
}
sc->files++;
sc->stored_files += f->stored;
if (!f->readable) {
sc->unreadable_files++;
(void)cbm_closure_add_opaque(sc->closure, f->index);
}
}
if (ok) {
cbm_arena_init(&sc->spell_arena);
sc->spellings = cbm_ht_create(CBM_SZ_256);
}
for (int i = 0; ok && i < n; i++) {
if (files[i].readable) {
sb_add_events(ctx, sc, &files[i]);
}
}
if (sc && sc->spellings) {
cbm_ht_free(sc->spellings);
sc->spellings = NULL;
cbm_arena_destroy(&sc->spell_arena);
}
ok = ok && cbm_closure_seal(sc->closure) == 0;
for (int i = 0; files && i < n; i++) {
if (!files[i].stored && files[i].result) {
cbm_pipeline_result_release((CBMFileResult *)files[i].result, loaded[i]);
}
}
cbm_arena_destroy(&facts_arena); /* the closure copied what it keeps */
cbm_free(CBM_MEM_CLASS_OTHER, files);
cbm_free(CBM_MEM_CLASS_OTHER, loaded);
if (fresh_rel) {
cbm_ht_free(fresh_rel);
}
if (rows_by_rel) {
cbm_ht_free(rows_by_rel);
}
if (!ok) {
cbm_pipeline_site_scope_free(sc);
return NULL;
}
char b[4][CBM_SZ_16];
snprintf(b[0], sizeof(b[0]), "%d", sc->files);
snprintf(b[1], sizeof(b[1]), "%d", cbm_closure_def_count(sc->closure));
snprintf(b[2], sizeof(b[2]), "%d", sc->includes);
snprintf(b[3], sizeof(b[3]), "%d", sc->includes_resolved);
cbm_log_info("site_bind.scope", "files", b[0], "defs", b[1], "includes", b[2], "resolved",
b[3]);
return sc;
}
void cbm_pipeline_site_scope_free(cbm_site_scope_t *sc) {
if (!sc) {
return;
}
if (sc->closure) {
char b[8][CBM_SZ_32];
const _Atomic uint64_t *v[8] = {&sc->proven, &sc->possible, &sc->drawn, &sc->same,
&sc->disagree, &sc->present, &sc->unsettled, &sc->absent};
for (int i = 0; i < 8; i++) {
snprintf(b[i], sizeof(b[i]), "%llu", (unsigned long long)atomic_load(v[i]));
}
/* drawn and present together: whether a possible answer's edge was drawn
* by the layer or already there depends on which worker's buffer holds
* main's edge (route-dependent); that it exists does not */
snprintf(b[2], sizeof(b[2]), "%llu",
(unsigned long long)(atomic_load(v[2]) + atomic_load(v[5])));
cbm_log_info("site_bind.run", "proven", b[0], "possible", b[1], "possible_drawn", b[2],
"possible_same", b[3], "possible_disagree", b[4], "possible_unsettled", b[6],
"proven_absent", b[7]);
}
if (sc->dump) {
fclose(sc->dump);
}
cbm_closure_free(sc->closure);
cbm_free(CBM_MEM_CLASS_OTHER, sc);
}
/* ── The test seam ───────────────────────────────────────────────────── */
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
enum { SB_MARKS = 16 };
static struct {
char name[CBM_SZ_128];
char target[CBM_SZ_512];
cbm_site_verdict_t verdict;
} g_marks[SB_MARKS];
static int g_nmarks;
void cbm_pipeline_site_bind_test_mark(const char *name, const char *target_qn,
cbm_site_verdict_t verdict) {
if (!name) {
g_nmarks = 0;
return;
}
if (g_nmarks < SB_MARKS) {
snprintf(g_marks[g_nmarks].name, sizeof(g_marks[g_nmarks].name), "%s", name);
snprintf(g_marks[g_nmarks].target, sizeof(g_marks[g_nmarks].target), "%s",
target_qn ? target_qn : "");
g_marks[g_nmarks].verdict = verdict;
g_nmarks++;
}
}
/* The mark of a site's name, or -1. */
static int sb_marked(const char *name) {
for (int i = 0; name && i < g_nmarks; i++) {
if (strcmp(name, g_marks[i].name) == 0) {
return i;
}
}
return CBM_NOT_FOUND;
}
#endif
/* ── Sites ───────────────────────────────────────────────────────────── */
void cbm_pipeline_site_bind_begin(cbm_site_file_t *sf, const cbm_pipeline_ctx_t *ctx,
const cbm_gbuf_t *graph, const char *rel, CBMLanguage lang,
const CBMFileResult *result) {
const CBMFileResult *result, cbm_site_memo_t **memo,
const CBMCallEvidence *evidence) {
if (!sf) {
return;
}
*sf = (cbm_site_file_t){
.ctx = ctx, .graph = graph, .result = result, .rel = rel, .lang = lang, .active = false};
memset(sf, 0, sizeof(*sf));
sf->ctx = ctx;
sf->graph = graph;
sf->result = result;
sf->rel = rel;
sf->lang = lang;
sf->memo = memo;
sf->evidence = evidence;
sf->file = CBM_NOT_FOUND;
const cbm_site_scope_t *sc = ctx ? ctx->site_scope : NULL;
if (sc && result && graph && rel && cbm_closure_lang(lang)) {
sf->file = cbm_closure_file(sc->closure, rel);
sf->active = sf->file >= 0;
}
}
/* The answer at every site of a file no row covers. */
@@ -33,26 +468,307 @@ static cbm_site_answer_t sb_no_answer(void) {
return none;
}
static cbm_site_answer_t sb_proven(const cbm_gbuf_node_t *target) {
cbm_site_answer_t a = {.verdict = CBM_SITE_PROVEN, .target = target};
a.res.qualified_name = target->qualified_name;
a.res.strategy = SB_PROVEN_STRATEGY;
a.res.confidence = SB_PROVEN_CONF;
a.res.candidate_count = SKIP_ONE;
return a;
}
/* Keep a POSSIBLE answer for the end step; false when out of memory (the
* site then has no answer). */
static bool sb_pend(cbm_site_file_t *sf, const cbm_gbuf_node_t *source,
const cbm_gbuf_node_t *target, int index, bool is_call) {
if (sf->npending >= sf->cap_pending) {
int ncap = sf->cap_pending ? sf->cap_pending * PAIR_LEN : CBM_SZ_16;
sb_pending_t *np = cbm_alloc(CBM_MEM_CLASS_RESOLVE, (size_t)ncap * sizeof(*np));
if (!np) {
return false;
}
if (sf->npending) {
memcpy(np, sf->pending, (size_t)sf->npending * sizeof(*np));
}
cbm_free(CBM_MEM_CLASS_RESOLVE, sf->pending);
sf->pending = np;
sf->cap_pending = ncap;
}
sf->pending[sf->npending++] = (sb_pending_t){.source_id = source->id,
.target = target,
.index = index,
.is_call = is_call,
.main_drew = false,
.main_target = NULL};
return true;
}
/* Turn a target node and a verdict into the site's answer. */
static cbm_site_answer_t sb_answer(cbm_site_file_t *sf, cbm_site_verdict_t v,
const cbm_gbuf_node_t *source, const cbm_gbuf_node_t *target,
int index, bool is_call) {
if (!target) {
return sb_no_answer();
}
if (v == CBM_SITE_PROVEN) {
sf->proven++;
return sb_proven(target);
}
if (v == CBM_SITE_POSSIBLE && sb_pend(sf, source, target, index, is_call)) {
sf->possible++;
cbm_site_answer_t a = {.verdict = CBM_SITE_POSSIBLE, .target = target};
return a;
}
return sb_no_answer();
}
cbm_site_answer_t cbm_pipeline_site_bind_call(cbm_site_file_t *sf, const CBMCall *call,
const cbm_gbuf_node_t *source) {
/* No row exists, so no file is active. */
(void)sf;
(void)call;
(void)source;
if (!sf || !call || !source || !sf->result) {
return sb_no_answer();
}
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
int mark = sb_marked(call->callee_name);
if (mark >= 0 && sf->graph) {
return sb_answer(sf, g_marks[mark].verdict, source,
cbm_gbuf_find_by_qn(sf->graph, g_marks[mark].target),
(int)(call - sf->result->calls.items), true);
}
#endif
/* No row answers calls yet (Protobuf has none). */
return sb_no_answer();
}
/* The type reference (a QREF event) that the site [start, end) is the last
* name of, or NULL. Events are sorted by position (a QREF's is its end byte,
* its index the start byte). */
static const CBMScopeEvent *sb_qref_ending(const CBMFileResult *r, uint32_t start, uint32_t end) {
const CBMScopeEvent *ev = r->scope.items;
int lo = 0;
int hi = r->scope.count;
while (lo < hi) {
int mid = lo + (hi - lo) / PAIR_LEN;
if (ev[mid].pos < end) {
lo = mid + SKIP_ONE;
} else {
hi = mid;
}
}
for (int i = lo; i < r->scope.count && ev[i].pos == end; i++) {
if (ev[i].kind == CBM_SCOPE_QREF && ev[i].name && ev[i].index >= 0 &&
(uint32_t)ev[i].index <= start) {
return &ev[i];
}
}
return NULL;
}
/* The thread's closure memo, made on its first lookup. */
static cbm_closure_memo_t *sb_memo(cbm_site_file_t *sf) {
if (!sf->memo) {
return NULL;
}
if (!*sf->memo) {
cbm_site_memo_t *m = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*m));
if (!m) {
return NULL;
}
m->closure_memo = cbm_closure_memo_new();
if (!m->closure_memo) {
cbm_free(CBM_MEM_CLASS_OTHER, m);
return NULL;
}
*sf->memo = m;
}
return (*sf->memo)->closure_memo;
}
cbm_site_answer_t cbm_pipeline_site_bind_usage(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *source) {
/* No row exists, so no file is active. */
(void)sf;
(void)usage;
(void)source;
return sb_no_answer();
if (!sf || !usage || !source || !sf->result || !usage->ref_name) {
return sb_no_answer();
}
int index = (int)(usage - sf->result->usages.items);
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
int mark = sb_marked(usage->ref_name);
if (mark >= 0 && sf->graph) {
return sb_answer(sf, g_marks[mark].verdict, source,
cbm_gbuf_find_by_qn(sf->graph, g_marks[mark].target), index, false);
}
#endif
if (!sf->active || usage->site_end_byte <= usage->site_start_byte) {
return sb_no_answer();
}
const CBMScopeEvent *qref =
sb_qref_ending(sf->result, usage->site_start_byte, usage->site_end_byte);
if (!qref) {
return sb_no_answer(); /* not the last name of a type reference */
}
if (qref->flags & CBM_SCOPE_NOT_A_TYPE) {
return sb_no_answer(); /* protoc resolves it to a method or a service */
}
const char *written = qref->name;
const char *dot = strrchr(written, '.');
if (strcmp(dot ? dot + SKIP_ONE : written, usage->ref_name) != 0) {
return sb_no_answer();
}
cbm_closure_ref_t ref = {
.name = usage->ref_name, .written = dot ? written : NULL, .scope = qref->qual};
const cbm_site_scope_t *sc = sf->ctx->site_scope;
cbm_closure_answer_t a = cbm_closure_lookup(sc->closure, sb_memo(sf), sf->file, &ref);
if (sc->dump) {
fprintf(sc->dump, "A\t%s\t%u\t%u\t%s\t%s\t%s\t%s\t%s\t%u\t%d\n", sf->rel,
usage->site_start_byte, usage->site_end_byte, usage->ref_name, written,
sb_verdict_name(a.verdict), a.qn ? a.qn : "", a.full ? a.full : "", a.why,
a.visible);
}
switch (a.verdict) {
case CBM_CLOSURE_PROVEN:
case CBM_CLOSURE_POSSIBLE: {
const cbm_gbuf_node_t *target = cbm_gbuf_find_by_qn(sf->graph, a.qn);
return sb_answer(sf, a.verdict == CBM_CLOSURE_PROVEN ? CBM_SITE_PROVEN : CBM_SITE_POSSIBLE,
source, target, index, false);
}
case CBM_CLOSURE_PROVEN_ABSENT:
sf->absent++;
return sb_no_answer();
default:
return sb_no_answer();
}
}
void cbm_pipeline_site_bind_usage_drawn(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *target) {
if (!sf || sf->npending == 0 || !usage || !sf->result) {
return;
}
sb_pending_t *last = &sf->pending[sf->npending - SKIP_ONE];
if (!last->is_call && last->index == (int)(usage - sf->result->usages.items)) {
last->main_drew = true;
last->main_target = target;
}
}
void cbm_pipeline_site_usage_props(char *buf, size_t cap, const CBMUsage *usage,
cbm_site_verdict_t verdict) {
char esc[CBM_SZ_256];
cbm_json_escape(esc, sizeof(esc), usage && usage->ref_name ? usage->ref_name : "");
bool proven = verdict == CBM_SITE_PROVEN;
snprintf(buf, cap, "{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\"}", esc,
proven ? SB_PROVEN_CONF : SB_POSSIBLE_CONF,
proven ? SB_PROVEN_STRATEGY : SB_POSSIBLE_STRATEGY);
}
/* ── The end step ────────────────────────────────────────────────────── */
static bool sb_has_edge(const cbm_gbuf_t *gb, int64_t source, int64_t target, const char *type) {
const cbm_gbuf_edge_t **out = NULL;
int count = 0;
if (!gb || cbm_gbuf_find_edges_by_source_type(gb, source, type, &out, &count) != 0) {
return false;
}
for (int i = 0; i < count; i++) {
if (out[i]->target_id == target) {
return true;
}
}
return false;
}
/* Draw a possible edge (the site's main drew nothing of its type). */
static bool sb_draw(cbm_site_file_t *sf, cbm_gbuf_t *edges, const sb_pending_t *p) {
char props[SB_PROPS_BUF];
if (!p->is_call) {
cbm_pipeline_site_usage_props(props, sizeof(props), &sf->result->usages.items[p->index],
CBM_SITE_POSSIBLE);
return cbm_gbuf_insert_edge(edges, p->source_id, p->target->id, "USAGE", props) > 0;
}
const CBMCall *call = &sf->result->calls.items[p->index];
char esc[CBM_SZ_256];
cbm_json_escape(esc, sizeof(esc), call->callee_name ? call->callee_name : "");
int n = snprintf(props, sizeof(props),
"{\"callee\":\"%s\",\"confidence\":%.2f,\"strategy\":\"%s\",\"candidates\":%d",
esc, SB_POSSIBLE_CONF, SB_POSSIBLE_STRATEGY, SKIP_ONE);
cbm_pipeline_close_call_props(props, n, call, true);
return cbm_gbuf_insert_edge(edges, p->source_id, p->target->id, "CALLS", props) > 0;
}
void cbm_pipeline_site_bind_end(cbm_site_file_t *sf, cbm_gbuf_t *edges) {
/* No POSSIBLE answer was given, so nothing is left to draw. */
(void)sf;
(void)edges;
if (!sf) {
return;
}
cbm_site_scope_t *sc = sf->ctx ? sf->ctx->site_scope : NULL;
int drawn = 0;
int same = 0;
int disagree = 0;
int present = 0;
int unsettled = 0;
for (int i = 0; edges && i < sf->npending; i++) {
const sb_pending_t *p = &sf->pending[i];
const char *type = p->is_call ? "CALLS" : "USAGE";
bool drew = false;
const cbm_gbuf_node_t *main_target = NULL;
if (p->is_call) {
if (!sf->evidence) {
unsettled++; /* what main emitted at the site is unknown: nothing drawn */
continue;
}
const CBMCallEvidence *ev = &sf->evidence[p->index];
drew = ev->calls_emitted;
main_target =
ev->candidate_qn ? cbm_gbuf_find_by_qn(sf->graph, ev->candidate_qn) : NULL;
} else {
drew = p->main_drew;
main_target = p->main_target;
}
bool exists =
sb_has_edge(edges, p->source_id, p->target->id, type) ||
(sf->graph != edges && sb_has_edge(sf->graph, p->source_id, p->target->id, type));
const char *outcome = "drawn";
if (drew) {
if (main_target == p->target || (!main_target && exists)) {
same++;
outcome = "same";
} else {
disagree++; /* main's edge stays alone */
outcome = "disagree";
}
} else if (p->target->id == p->source_id || exists) {
present++; /* the edge is there already (another site): nothing added */
outcome = "present";
} else if (sb_draw(sf, edges, p)) {
drawn++;
} else {
outcome = "failed";
}
if (sc && sc->dump) {
uint32_t at = p->is_call ? 0 : sf->result->usages.items[p->index].site_start_byte;
fprintf(sc->dump, "S\t%s\t%u\t%s\t%s\t%s\n", sf->rel ? sf->rel : "", at, outcome,
p->target->qualified_name,
main_target && main_target->qualified_name ? main_target->qualified_name : "");
}
}
if (sc && (sf->proven || sf->possible || sf->absent)) {
atomic_fetch_add(&sc->proven, (uint64_t)sf->proven);
atomic_fetch_add(&sc->possible, (uint64_t)sf->possible);
atomic_fetch_add(&sc->drawn, (uint64_t)drawn);
atomic_fetch_add(&sc->same, (uint64_t)same);
atomic_fetch_add(&sc->disagree, (uint64_t)disagree);
atomic_fetch_add(&sc->present, (uint64_t)present);
atomic_fetch_add(&sc->unsettled, (uint64_t)unsettled);
atomic_fetch_add(&sc->absent, (uint64_t)sf->absent);
char b[8][CBM_SZ_16];
const int v[8] = {sf->proven, sf->possible, drawn, same,
disagree, present, unsettled, sf->absent};
for (int i = 0; i < 8; i++) {
snprintf(b[i], sizeof(b[i]), "%d", v[i]);
}
cbm_log_info("site_bind.file", "rel", sf->rel ? sf->rel : "", "proven", b[0], "possible",
b[1], "drawn", b[2], "same", b[3], "disagree", b[4], "present", b[5],
"unsettled", b[6], "absent", b[7]);
}
cbm_free(CBM_MEM_CLASS_RESOLVE, sf->pending);
sf->pending = NULL;
sf->npending = 0;
sf->cap_pending = 0;
}
+78 -18
View File
@@ -14,23 +14,27 @@
* classification; a usage site that no engine row was found
* for, after the C member join and before the PHP vendor check
* and main's name chain.
* PROVEN replaces main's name chain at the site. A call keeps every
* later step of main (service and route classification, spawn,
* field policy, guards) on the answer; a usage takes the target.
* POSSIBLE main's chain decides the site as before. The layer may draw
* its own edge for it when the file is done
* (cbm_pipeline_site_bind_end), and only where main drew no
* edge of that type between the same two nodes.
* NO_ANSWER main's chain, unchanged.
* PROVEN replaces main's name chain at the site (strategy
* `include_scope`, confidence 0.95). A call keeps every later
* step of main (service and route classification, spawn, field
* policy, guards) on the answer; a usage takes the target.
* POSSIBLE main's chain decides the site as before. When the file is done
* (cbm_pipeline_site_bind_end) the layer draws its own edge
* (`include_scope_may`, confidence 0.85) only where main drew no
* edge of that type at the site; where main drew the same target
* nothing is added; where main drew another target main's edge
* stays alone and the disagreement is counted.
* NO_ANSWER main's chain, unchanged. A proven absence is counted only.
*
* Rules and their rows live in site_bind.c; a resolver is never edited for
* a new rule. No language has a row yet: every file is inactive, every site
* gets NO_ANSWER and the end step draws nothing, so the graph is main's on
* both routes.
* Rows: the scope rows of scope_closure.h (Protobuf). A usage is answered
* only at the last name of a type reference the scope facts recorded (a
* QREF event ending where the usage ends), read as written. Calls of a row
* language are not answered yet (Protobuf has none).
*
* Threads: one cbm_site_file_t per file being resolved, on the stack of the
* worker resolving it. Whatever run-wide input a row reads is built and
* sealed before any resolver starts.
* The run's scope (cbm_site_scope_t) is built once after IMPORTS, on one
* thread, before any resolver starts, and is read only afterwards. Each
* resolver thread brings its own memo (cbm_site_memo_t, created on its first
* lookup); no answer depends on what a memo holds.
*/
#include "cbm.h"
@@ -39,6 +43,7 @@
#include "pipeline/pipeline_internal.h"
#include <stdbool.h>
#include <stddef.h>
typedef enum {
CBM_SITE_NO_ANSWER = 0, /* main's chain decides, unchanged */
@@ -55,6 +60,15 @@ typedef struct {
const cbm_gbuf_node_t *target;
} cbm_site_answer_t;
/* The run's scope: NULL when no discovered file has a row. */
typedef struct cbm_site_scope cbm_site_scope_t;
/* One resolver thread's memo (opaque); NULL until its first lookup. */
typedef struct cbm_site_memo cbm_site_memo_t;
void cbm_pipeline_site_memo_free(cbm_site_memo_t *m);
typedef struct sb_pending sb_pending_t;
/* One file's state, on the resolver's stack between begin and end. */
typedef struct {
const cbm_pipeline_ctx_t *ctx;
@@ -62,13 +76,40 @@ typedef struct {
const CBMFileResult *result;
const char *rel;
CBMLanguage lang;
bool active; /* false: no row covers this file, every site is NO_ANSWER */
bool active; /* false: no row covers this file, every site is NO_ANSWER */
int file; /* the file in the run's scope (active only) */
cbm_site_memo_t **memo; /* the thread's memo slot */
const CBMCallEvidence *evidence; /* per call: what main emitted (calls), or NULL */
sb_pending_t *pending; /* POSSIBLE answers left to the end step */
int npending;
int cap_pending;
int proven;
int possible;
int absent;
} cbm_site_file_t;
/* Start one file: before its first site is asked. */
/* Build the run's scope from every discovered file of a row language: its
* fresh result (cache[i] for fresh[i], read through the spill-aware
* accessor) or, for a file of `all` without one, its stored facts (the
* surface row's "is" key; incremental closure repair). A row-language file
* with neither takes part as unreadable (nothing proven through it). On one
* thread, after IMPORTS and before any resolver. NULL: no row-language file
* (or out of memory): every site gets NO_ANSWER. */
cbm_site_scope_t *cbm_pipeline_site_scope_build(const cbm_pipeline_ctx_t *ctx,
const cbm_file_info_t *fresh, int fresh_count,
CBMFileResult **cache, const cbm_file_info_t *all,
int all_count, const cbm_lsp_surface_row_t *stored,
int stored_count);
/* Log the run's counts and free. */
void cbm_pipeline_site_scope_free(cbm_site_scope_t *sc);
/* Start one file: before its first site is asked. `memo`: the calling
* thread's slot; `evidence`: the file's per-call evidence (calls pass), or
* NULL. */
void cbm_pipeline_site_bind_begin(cbm_site_file_t *sf, const cbm_pipeline_ctx_t *ctx,
const cbm_gbuf_t *graph, const char *rel, CBMLanguage lang,
const CBMFileResult *result);
const CBMFileResult *result, cbm_site_memo_t **memo,
const CBMCallEvidence *evidence);
/* The answer for one call of sf->result (an element of result->calls),
* made in the function or file node `source`. */
@@ -80,9 +121,28 @@ cbm_site_answer_t cbm_pipeline_site_bind_call(cbm_site_file_t *sf, const CBMCall
cbm_site_answer_t cbm_pipeline_site_bind_usage(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *source);
/* Main's chain drew a USAGE edge to `target` at a usage the layer answered
* POSSIBLE (both usage resolvers call it right after drawing). */
void cbm_pipeline_site_bind_usage_drawn(cbm_site_file_t *sf, const CBMUsage *usage,
const cbm_gbuf_node_t *target);
/* The properties of a USAGE edge the layer draws: the usage's name, the
* answer's confidence and strategy. */
void cbm_pipeline_site_usage_props(char *buf, size_t cap, const CBMUsage *usage,
cbm_site_verdict_t verdict);
/* End one file: after its last site, with the buffer its edges went to
* (the run's graph on the sequential route, the worker's edge buffer on the
* parallel one). Draws what POSSIBLE answers leave to this step. */
void cbm_pipeline_site_bind_end(cbm_site_file_t *sf, cbm_gbuf_t *edges);
#if defined(CBM_ENABLE_TEST_SEAMS) && CBM_ENABLE_TEST_SEAMS
/* Add a mark: every call and usage named `name` that the layer is asked
* about, in a file of any language, answers `verdict` with the node
* `target_qn` (PROVEN or POSSIBLE). Up to sixteen marks; a NULL name clears
* them. Set only while no index runs. */
void cbm_pipeline_site_bind_test_mark(const char *name, const char *target_qn,
cbm_site_verdict_t verdict);
#endif
#endif /* CBM_SITE_BIND_H */
+12 -2
View File
@@ -941,10 +941,20 @@ TEST(repro_lsp_ordered_signatures_php_trait_self_refinement) {
php_lsp_init(&ctx, &arena, source, (int)strlen(source), &registry, module_qn, &out);
cbm_php_refine_lsp_registry(&ctx, &registry, root);
/* The trait's method as the class that uses it reports it (the member
* lookup, php_find_method): the copy PHP makes, its `self` the class. */
php_members_begin(&ctx, &registry);
const CBMRegisteredFunc *tap = php_find_method(&ctx, consumer_qn, "tap");
CBMTypeRegistry seen;
cbm_registry_init(&seen, &arena);
if (tap) {
cbm_registry_add_func(&seen, *tap);
}
php_members_end(&ctx);
const char *expected[] = {"int", "Thing", "int"};
int failures = check_signature(&registry, "cbm.ordered.php.trait.Consumer.tap",
int failures = check_signature(&seen, "cbm.ordered.php.trait.Consumer.tap",
"php-trait-self-refinement", expected, 3);
failures += check_single_return(&registry, "cbm.ordered.php.trait.Consumer.tap",
failures += check_single_return(&seen, "cbm.ordered.php.trait.Consumer.tap",
"php-trait-self-refinement", "Consumer");
ts_tree_delete(tree);
+26
View File
@@ -1803,6 +1803,31 @@ static const char *def_return_type(CBMFileResult *r, const char *name) {
return NULL;
}
/* Methods in an `impl` block publish their declared return type like a free
* `fn` does; a method without `->` has none. */
TEST(rust_impl_method_return_type) {
CBMFileResult *r = extract("struct Matcher;\n"
"pub fn free() -> u8 { 0 }\n"
"impl Matcher {\n"
" pub fn build(&self, p: &str) -> Result<Matcher, Error> { todo!() }\n"
" fn name(&self) -> &'static str { \"m\" }\n"
" fn reset(&mut self) {}\n"
"}\n"
"impl Clone for Matcher {\n"
" fn clone(&self) -> Self { Matcher }\n"
"}\n",
CBM_LANG_RUST, "t", "matcher.rs");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
ASSERT_STR_EQ(def_return_type(r, "free"), "u8");
ASSERT_STR_EQ(def_return_type(r, "build"), "Result<Matcher, Error>");
ASSERT_STR_EQ(def_return_type(r, "name"), "&'static str");
ASSERT_STR_EQ(def_return_type(r, "clone"), "Self");
ASSERT_NULL(def_return_type(r, "reset"));
cbm_free_result(r);
PASS();
}
/* A member's name is the identifier at the bottom of its declarator, and its
* type is everything around that identifier, in the canonical spelling of the
* function return types below. Taking the first declarator's first child as
@@ -16653,6 +16678,7 @@ SUITE(extraction) {
/* Systems */
RUN_TEST(rust_function);
RUN_TEST(rust_struct);
RUN_TEST(rust_impl_method_return_type);
RUN_TEST(go_function);
RUN_TEST(go_struct);
RUN_TEST(go_interface);
+757
View File
@@ -37,6 +37,8 @@
#include <foundation/log.h>
#include <sqlite3.h>
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
@@ -1878,6 +1880,261 @@ static char *gpf_spawns(const GpfFile *files, int nfiles) {
free(got_); \
} while (0)
/* Every REFERENCES_FILE edge a Dockerfile draws for a COPY / ADD source, as
* "source file -> target file (via:line)", sorted, one per line. */
static char *gpf_copy_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' "
"AND json_extract(e.properties,'$.via') IN ('copy','add') ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
#define GPF_ASSERT_COPY_REFS(files, n, want) \
do { \
char *got_ = gpf_copy_refs(files, n); \
if (!got_ || strcmp(got_, want) != 0) { \
fprintf(stderr, "COPY refs got:\n%s\nwant:\n%s\n", got_ ? got_ : "(null)", want); \
free(got_); \
FAIL("REFERENCES_FILE edge set"); \
} \
free(got_); \
} while (0)
/* A Dockerfile at the repository root has one context. Each plain source of
* a COPY / ADD that is an indexed file is a file the Dockerfile references,
* once, at the first instruction naming it. No edge for a directory, a
* source of another stage or image (--from), a URL, a glob, a source a
* variable supplies (an ARG default can be overridden by the build), a
* source no indexed file is, or the Dockerfile itself. */
TEST(probe_dockerfile_copy_sources_are_file_references) {
static const GpfFile files[] = {
{"Dockerfile", "ARG CONF=conf/app.yaml\n"
"FROM python:3.12 AS build\n"
"WORKDIR /app\n"
"COPY requirements.txt setup.py ./\n"
"COPY src/ ./src/\n"
"COPY . .\n"
"ADD conf/app.yaml /etc/app.yaml\n"
"ADD https://example.com/tool.tgz /tmp/\n"
"COPY ${CONF} /etc/again.yaml\n"
"COPY *.py /all/\n"
"COPY missing.py /missing.py\n"
"COPY Dockerfile /Dockerfile\n"
"FROM python:3.12-slim\n"
"COPY --from=build /app/setup.py /setup.py\n"
"COPY [\"setup.py\", \"run.sh\", \"/opt/\"]\n"},
{"requirements.txt", "flask==3.0.0\n"},
{"setup.py", "from setuptools import setup\n\nsetup(name=\"app\")\n"},
{"run.sh", "#!/bin/sh\nexec python -m app\n"},
{"conf/app.yaml", "name: app\n"},
{"src/app.py", "def main():\n return 0\n"}};
GPF_ASSERT_COPY_REFS(files, 6,
"Dockerfile -> conf/app.yaml (add:7)\n"
"Dockerfile -> requirements.txt (copy:4)\n"
"Dockerfile -> run.sh (copy:15)\n"
"Dockerfile -> setup.py (copy:4)");
PASS();
}
/* A Dockerfile below the root can be built with its own directory or with
* the repository root as context; the build command decides, and it is not
* in the Dockerfile. A source that is a file under exactly one of the two is
* that file. A source that is a file under both is no edge, and neither is
* one that is a file under one and a directory under the other: with the
* other context the instruction copies the directory. */
TEST(probe_dockerfile_copy_source_under_two_contexts_is_no_reference) {
static const GpfFile files[] = {
{"svc/Dockerfile", "FROM alpine:3.20\n"
"COPY entry.sh /entry.sh\n"
"COPY shared/tool.sh /tool.sh\n"
"COPY both.sh /both.sh\n"
"COPY ../outside.sh /outside.sh\n"
"COPY config.yaml /etc/config.yaml\n"},
{"svc/entry.sh", "#!/bin/sh\necho entry\n"},
{"shared/tool.sh", "#!/bin/sh\necho tool\n"},
{"both.sh", "#!/bin/sh\necho root\n"},
{"svc/both.sh", "#!/bin/sh\necho svc\n"},
{"outside.sh", "#!/bin/sh\necho outside\n"},
{"config.yaml", "mode: root\n"},
{"svc/config.yaml/part.yaml", "mode: part\n"}};
GPF_ASSERT_COPY_REFS(files, 8,
"svc/Dockerfile -> shared/tool.sh (copy:3)\n"
"svc/Dockerfile -> svc/entry.sh (copy:2)");
PASS();
}
/* Every REFERENCES_FILE edge a compose service draws, as
* "<service> -> <target file> (via:line)", sorted, one per line. */
static char *gpf_compose_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.name || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND s.label='Resource' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
#define GPF_ASSERT_COMPOSE_REFS(files, n, want) \
do { \
char *got_ = gpf_compose_refs(files, n); \
if (!got_ || strcmp(got_, want) != 0) { \
fprintf(stderr, "compose refs got:\n%s\nwant:\n%s\n", got_ ? got_ : "(null)", want); \
free(got_); \
FAIL("REFERENCES_FILE edge set"); \
} \
free(got_); \
} while (0)
/* A compose service names repository files relative to the compose file's
* directory: a bind mount's host side (short and long form), an env_file, the
* file of a config or secret it lists. Each indexed file is a file the
* service references, once, at the first line naming it. No edge for a
* directory, a named or anonymous volume, an absolute or home path, a
* short-form host side without a leading dot (compose reads it as a volume's
* name), a path out of the repository, a variable without a value, a file the
* index does not hold, or a config without a file. */
TEST(probe_compose_service_files_are_file_references) {
static const GpfFile files[] = {
{"compose.yaml", "services:\n"
" web:\n"
" image: nginx:1.27\n"
" volumes:\n"
" - ./conf/nginx.conf:/etc/nginx/nginx.conf:ro\n"
" - ./src:/app\n"
" - data:/var/lib/data\n"
" - /etc/localtime:/etc/localtime:ro\n"
" - ~/.aws:/root/.aws\n"
" - ../outside.conf:/outside.conf\n"
" - ${CONF_DIR:-./conf}/extra.conf:/etc/extra.conf\n"
" - ${UNSET_DIR}/x.conf:/x.conf\n"
" - conf/nodot.conf:/etc/nodot.conf\n"
" - /anonymous\n"
" - type: bind\n"
" source: ./conf/long.conf\n"
" target: /etc/long.conf\n"
" - type: volume\n"
" source: data\n"
" target: /data\n"
" - ./conf/missing.conf:/etc/missing.conf\n"
" env_file:\n"
" - ./conf/web.env\n"
" - path: ./conf/more.env\n"
" required: false\n"
" configs:\n"
" - app_config\n"
" - source: other_config\n"
" target: /etc/other.yaml\n"
" - external_config\n"
" secrets:\n"
" - db_settings\n"
" worker:\n"
" image: alpine:3.20\n"
" volumes:\n"
" - ./conf/nginx.conf:/a\n"
" - ./conf/nginx.conf:/b\n"
" env_file: ./conf/web.env\n"
"configs:\n"
" app_config:\n"
" file: ./conf/app.yaml\n"
" other_config:\n"
" file: conf/other.yaml\n"
" external_config:\n"
" external: true\n"
"secrets:\n"
" db_settings:\n"
" file: ./conf/db.ini\n"
"volumes:\n"
" data: {}\n"},
{"conf/nginx.conf", "worker_processes 1;\n"},
{"conf/extra.conf", "gzip on;\n"},
{"conf/long.conf", "sendfile on;\n"},
{"conf/nodot.conf", "tcp_nopush on;\n"},
{"conf/web.env", "MODE=web\n"},
{"conf/more.env", "EXTRA=1\n"},
{"conf/app.yaml", "name: app\n"},
{"conf/other.yaml", "name: other\n"},
{"conf/db.ini", "[db]\nname = app\n"},
{"src/app.py", "def main():\n return 0\n"}};
GPF_ASSERT_COMPOSE_REFS(files, 11,
"Service/web -> conf/app.yaml (config:27)\n"
"Service/web -> conf/db.ini (secret:32)\n"
"Service/web -> conf/extra.conf (volume:11)\n"
"Service/web -> conf/long.conf (volume:16)\n"
"Service/web -> conf/more.env (env_file:24)\n"
"Service/web -> conf/nginx.conf (volume:5)\n"
"Service/web -> conf/other.yaml (config:28)\n"
"Service/web -> conf/web.env (env_file:23)\n"
"Service/worker -> conf/nginx.conf (volume:36)\n"
"Service/worker -> conf/web.env (env_file:38)");
PASS();
}
/* The paths are relative to the compose file's directory, not to the
* repository root: a same-named file at the root is not the one, a path may
* climb to a sibling directory, and one that leaves the repository or names
* the compose file itself is no edge. A long-form bind mount says it is a
* path, so its source needs no leading dot. */
TEST(probe_compose_service_files_resolve_from_the_compose_directory) {
static const GpfFile files[] = {
{"deploy/compose.yaml", "services:\n"
" api:\n"
" image: api:1\n"
" volumes:\n"
" - ./app.conf:/etc/app.conf\n"
" - ../shared/base.conf:/etc/base.conf\n"
" - ../../out.conf:/etc/out.conf\n"
" - ./compose.yaml:/self.yaml\n"
" - type: bind\n"
" source: more.conf\n"
" target: /etc/more.conf\n"},
{"deploy/app.conf", "name deploy;\n"},
{"deploy/more.conf", "name more;\n"},
{"app.conf", "name root;\n"},
{"more.conf", "name root-more;\n"},
{"shared/base.conf", "name base;\n"},
{"out.conf", "name out;\n"}};
GPF_ASSERT_COMPOSE_REFS(files, 7,
"Service/api -> deploy/app.conf (volume:5)\n"
"Service/api -> deploy/more.conf (volume:10)\n"
"Service/api -> shared/base.conf (volume:6)");
PASS();
}
/* Every SPAWNS and DEPLOYS edge as "source -> target (TYPE api|via[
* ci[/job]])", sorted, one per line: top-level code as "@<file>"; a script
* as "script:<path>", a Process as "proc:<name>", a Chart as "chart:<name>",
@@ -2841,6 +3098,205 @@ TEST(probe_kustomize_helm_charts_deploy_their_chart) {
PASS();
}
/* The REFERENCES_FILE edges a kustomization draws for the files it reads, as
* "<kustomization> -> <target file> (via:line)", sorted, one per line; then a
* line "imports <files>": the targets of the IMPORTS edges leaving
* kustomization files. */
static char *gpf_kustomize_files(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce((SELECT group_concat(x, char(10)) FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND json_extract(e.properties,'$.via') "
"IN ('configMapGenerator','secretGenerator','configurations') ORDER BY x)), '') "
"|| char(10) || 'imports ' || coalesce((SELECT group_concat(x, ',') FROM (SELECT "
"DISTINCT t.file_path AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='IMPORTS' AND s.file_path LIKE '%kustomization.yaml' "
"ORDER BY x)), '')";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW && sqlite3_column_text(st, 0)) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A kustomization reads files that are input to its build without being a
* member of it: a generator's `files` (a path, or `key=path`) and `envs`, and
* its `configurations`. Each indexed file is a file the kustomization
* references, once, at the first line naming it -- and never an import: an
* import makes a file's objects part of the build. A file the index does not
* hold (one that is missing, and config/settings.json, which is on disk but
* a name discovery skips), a path out of the repository, an absolute path
* (it names a file of the machine, not of the repository, also when the
* repository holds a file at that path below its root or below the
* kustomization) and a generator's literals are none. */
TEST(probe_kustomize_generator_files_are_file_references) {
static const GpfFile files[] = {
{"deploy/kustomization.yaml", "apiVersion: kustomize.config.k8s.io/v1beta1\n"
"kind: Kustomization\n"
"resources:\n"
" - deployment.yaml\n"
"configMapGenerator:\n"
" - name: app-config\n"
" files:\n"
" - app.properties\n"
" - settings=config/settings.json\n"
" - limits=config/limits.json\n"
" - missing.properties\n"
" - abs=/abs.properties\n"
" envs:\n"
" - app.env\n"
" - name: literal-only\n"
" literals:\n"
" - A=1\n"
"secretGenerator:\n"
" - name: tokens\n"
" files:\n"
" - ../../outside.yaml\n"
" - ../shared/token.yaml\n"
"configurations:\n"
" - kustomizeconfig.yaml\n"
" - app.properties\n"
" - /abs.properties\n"},
{"deploy/deployment.yaml", "apiVersion: apps/v1\n"
"kind: Deployment\n"
"metadata:\n"
" name: app\n"
"spec:\n"
" replicas: 1\n"},
{"deploy/app.properties", "mode=prod\n"},
{"deploy/config/settings.json", "{\"mode\": \"prod\"}\n"},
{"deploy/config/limits.json", "{\"max\": 3}\n"},
{"deploy/app.env", "MODE=prod\n"},
{"deploy/kustomizeconfig.yaml", "nameReference: []\n"},
{"deploy/abs.properties", "mode=abs\n"},
{"abs.properties", "mode=root\n"},
{"shared/token.yaml", "token: placeholder\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_kustomize_files(files, n);
static const char want[] =
"deploy/kustomization.yaml -> deploy/app.env (configMapGenerator:14)\n"
"deploy/kustomization.yaml -> deploy/app.properties (configMapGenerator:8)\n"
"deploy/kustomization.yaml -> deploy/config/limits.json (configMapGenerator:10)\n"
"deploy/kustomization.yaml -> deploy/kustomizeconfig.yaml (configurations:24)\n"
"deploy/kustomization.yaml -> shared/token.yaml (secretGenerator:22)\n"
"imports deploy/deployment.yaml";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "kustomize files got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("kustomize file refs");
}
free(got);
PASS();
}
/* Every REFERENCES_FILE edge a local `uses:` draws, as
* "<file> -> <target file> (uses:line)", sorted, one per line. */
static char *gpf_local_uses(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' "
"AND json_extract(e.properties,'$.via')='uses' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A local `uses:` ("./...") is a path from the repository root, wherever the
* workflow or action lies. A step's names an action by its directory: the
* edge goes to that directory's action.yml or action.yaml, the one it holds.
* A job's names a reusable workflow file. Each file once, at the first use.
* No edge for an action of another repository, a path with an expression, a
* directory with no action file, or one holding both spellings. */
TEST(probe_github_actions_local_uses_reference_their_files) {
static const GpfFile files[] = {
{".github/workflows/ci.yml", "name: ci\n"
"on: [push]\n"
"jobs:\n"
" build:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - uses: actions/checkout@v4\n"
" - uses: ./.github/actions/setup\n"
" - uses: ./\n"
" - uses: ./.github/actions/${{ matrix.kind }}\n"
" - uses: ./.github/actions/missing\n"
" - uses: ./.github/actions/both\n"
" - name: again\n"
" uses: ./.github/actions/setup\n"
" - run: echo done\n"
" call:\n"
" uses: ./.github/workflows/reusable.yml\n"
" far:\n"
" uses: org/repo/.github/workflows/x.yml@main\n"},
{".github/workflows/reusable.yml", "on:\n"
" workflow_call: {}\n"
"jobs:\n"
" a:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - run: echo a\n"},
{".github/actions/setup/action.yml", "name: setup\n"
"runs:\n"
" using: composite\n"
" steps:\n"
" - uses: ./.github/actions/inner\n"
" - run: echo setup\n"
" shell: bash\n"},
{".github/actions/inner/action.yaml", "name: inner\n"
"runs:\n"
" using: composite\n"
" steps:\n"
" - run: echo inner\n"
" shell: bash\n"},
{".github/actions/both/action.yml", "name: both\nruns:\n using: composite\n steps: []\n"},
{".github/actions/both/action.yaml", "name: both\nruns:\n using: composite\n steps: []\n"},
{"action.yaml", "name: root\nruns:\n using: composite\n steps: []\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_local_uses(files, n);
static const char want[] =
".github/actions/setup/action.yml -> .github/actions/inner/action.yaml (uses:5)\n"
".github/workflows/ci.yml -> .github/actions/setup/action.yml (uses:8)\n"
".github/workflows/ci.yml -> .github/workflows/reusable.yml (uses:17)\n"
".github/workflows/ci.yml -> action.yaml (uses:9)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "local uses got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("local uses");
}
free(got);
PASS();
}
/* Every Terraform reference edge as
* "<file> <block> -> <file> <block> <type> <ref>:<line>", then a line
* "other tf edges <n>": USAGE / CALLS edges leaving a .tf file that the
@@ -2930,6 +3386,78 @@ TEST(probe_terraform_refs_resolve_in_their_module) {
PASS();
}
/* Every REFERENCES_FILE edge a Terraform block draws for a file function, as
* "<file> <block> -> <target file> (fn:line)", sorted, one per line. */
static char *gpf_tf_file_refs(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ' ' || s.name || ' -> ' || t.file_path || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') "
"|| ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='REFERENCES_FILE' AND s.file_path LIKE '%.tf' "
"ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A file function whose path begins at ${path.module} reads a file of the
* repository: the block holding the call references that file, once, at its
* first call. A path without ${path.module} is relative to the directory
* Terraform runs in and draws nothing; neither does path.root, a path with
* another interpolation, a variable, a directory read by fileset, or a file
* the index does not hold. */
TEST(probe_terraform_file_functions_reference_their_files) {
static const GpfFile files[] = {
{"infra/main.tf", "variable \"name\" {}\n"
"locals {\n"
" policy = file(\"${path.module}/policies/read.json\")\n"
" again = file(\"${path.module}/policies/read.json\")\n"
" plain = file(\"policies/read.json\")\n"
" rooted = file(\"${path.root}/policies/read.json\")\n"
" named = file(\"${path.module}/policies/${var.name}.json\")\n"
" byvar = file(var.name)\n"
" set = fileset(\"${path.module}/policies\", \"*.json\")\n"
" gone = file(\"${path.module}/policies/missing.json\")\n"
"}\n"
"resource \"aws_instance\" \"web\" {\n"
" user_data = templatefile(\"${path.module}/templates/init.sh\", {\n"
" name = var.name\n"
" })\n"
" hash = filemd5(\"${path.module}/../shared/common.yaml\")\n"
"}\n"},
{"infra/policies/read.json", "{\"Version\": \"2012-10-17\"}\n"},
{"infra/templates/init.sh", "#!/bin/sh\necho ${name}\n"},
{"shared/common.yaml", "name: common\n"},
{"policies/read.json", "{\"Version\": \"2012-10-17\"}\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_tf_file_refs(files, n);
static const char want[] =
"infra/main.tf locals -> infra/policies/read.json (file:3)\n"
"infra/main.tf resource.aws_instance.web -> infra/templates/init.sh (templatefile:13)\n"
"infra/main.tf resource.aws_instance.web -> shared/common.yaml (filemd5:16)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "terraform file refs got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("terraform file refs");
}
free(got);
PASS();
}
/* A Terraform / OpenTofu module file (.tf, .tofu) extracts its blocks but no
* generic calls or usages -- its references are the module resolver's -- while
* any other HCL file (Packer, Nomad, Terragrunt .hcl) keeps them. */
@@ -4220,6 +4748,225 @@ TEST(probe_make_rules_have_a_node_per_target) {
PASS();
}
/* Every DEPENDS_ON edge a Make prerequisite draws, as
* "<file>:<target> -> <file>:<rule> (prerequisite:<line>[ order-only])",
* sorted, one per line. */
static char *gpf_make_prerequisites(const GpfFile *files, int nfiles) {
GpfProj lp;
cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
char *out = NULL;
if (store) {
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT coalesce(group_concat(x, char(10)), '') FROM (SELECT "
"s.file_path || ':' || s.name || ' -> ' || t.file_path || ':' || t.name || ' (' || "
"json_extract(e.properties,'$.via') || ':' || json_extract(e.properties,'$.line') || "
"CASE WHEN json_extract(e.properties,'$.order_only') IS NULL THEN '' ELSE "
"' order-only' END || ')' AS x "
"FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON t.id=e.target_id "
"WHERE e.project=?1 AND e.type='DEPENDS_ON' AND s.label='Function' ORDER BY x)";
if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
if (sqlite3_step(st) == SQLITE_ROW) {
out = strdup((const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
}
gpf_cleanup(&lp, store);
return out;
}
/* A prerequisite that names a rule of the same makefile is a dependency of
* each of the rule's targets on that rule: once per pair, at the first line
* stating it (make merges the prerequisites of a target's rules), an
* order-only one marked -- unless another rule of the target lists it as a
* normal one: make then treats it as normal, and the edge carries that
* line. A rule under a conditional, a pattern rule and a
* rule whose target is a variable have their prerequisites like any other.
* No edge for a prerequisite with a variable, a pattern or a glob, one that
* names a file or a rule of another makefile (an included one too), a target
* naming itself, a special target's list (.PHONY), a target-specific
* variable in any spelling, or a static pattern rule. */
TEST(probe_make_prerequisites_depend_on_their_rules) {
static const GpfFile files[] = {
{"Makefile", "include mk/tools.mk\n"
"BIN := bin\n"
"TOOL := $(BIN)/tool\n\n"
"ifeq ($(OS),linux)\n"
"install: build\n"
"\tcp bin/tool /usr/local/bin\n"
"endif\n\n"
".PHONY: all build test\n"
"all: build test\n\n"
"build: generate | dirs\n"
"\tgo build ./...\n\n"
"test lint: build $(TOOL) tool\n"
"\tgo test ./...\n\n"
"generate: \\\n"
" proto \\\n"
" docs\n"
"\techo gen\n\n"
"proto docs dirs:\n"
"\techo $@\n\n"
"$(TOOL): go.mod dirs\n"
"\tgo build -o $@ ./cmd/tool\n\n"
"build: MODE = docs\n"
"build: export KIND := proto\n"
"lint: override FAST = dirs\n\n"
"%.o: %.c generate\n"
"\tcc -c $<\n\n"
"objs: a.o b.o c.o\n\n"
"a.o b.o: %.o: %.c dirs\n"
"\tcc -c $<\n\n"
"release:: build\n"
"\techo one\n"
"release:: test build\n"
"\techo two\n\n"
"deploy: build-$(ENV) *.yaml deploy all\n"
"\techo deploy\n\n"
"stamp: | dirs\n"
"stamp: dirs\n"
"mark: dirs\n"
"mark: | dirs\n"},
{"mk/tools.mk", "tool: build\n"
"\techo tool\n\n"
"tools: tool\n"},
{"go.mod", "module example.com/x\n"}};
int n = (int)(sizeof(files) / sizeof(files[0]));
char *got = gpf_make_prerequisites(files, n);
static const char want[] = "Makefile:$(TOOL) -> Makefile:dirs (prerequisite:27)\n"
"Makefile:%.o -> Makefile:generate (prerequisite:34)\n"
"Makefile:all -> Makefile:build (prerequisite:11)\n"
"Makefile:all -> Makefile:test (prerequisite:11)\n"
"Makefile:build -> Makefile:dirs (prerequisite:13 order-only)\n"
"Makefile:build -> Makefile:generate (prerequisite:13)\n"
"Makefile:deploy -> Makefile:all (prerequisite:47)\n"
"Makefile:generate -> Makefile:docs (prerequisite:21)\n"
"Makefile:generate -> Makefile:proto (prerequisite:20)\n"
"Makefile:install -> Makefile:build (prerequisite:6)\n"
"Makefile:lint -> Makefile:build (prerequisite:16)\n"
"Makefile:mark -> Makefile:dirs (prerequisite:52)\n"
"Makefile:objs -> Makefile:a.o (prerequisite:37)\n"
"Makefile:objs -> Makefile:b.o (prerequisite:37)\n"
"Makefile:release -> Makefile:build (prerequisite:42)\n"
"Makefile:release -> Makefile:test (prerequisite:44)\n"
"Makefile:stamp -> Makefile:dirs (prerequisite:51)\n"
"Makefile:test -> Makefile:build (prerequisite:16)\n"
"mk/tools.mk:tools -> mk/tools.mk:tool (prerequisite:4)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "make prerequisites got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
free(got);
FAIL("make prerequisites");
}
free(got);
PASS();
}
/* Complexity guard counter of the Make dependency drawing (pass_shell.c). */
extern _Atomic uint64_t g_sh_make_pairs;
/* A rule line that repeats a target or a prerequisite states each pair once:
* the drawing looks at the line's words and at its distinct pairs, not at
* the product of the repeats. One rule with n copies of one target and n
* copies of one prerequisite, counted at 1x, 4x and 16x: one edge each time,
* and work that grows with n. */
TEST(probe_make_repeated_names_cost_linear_work) {
static const int sizes[] = {50, 200, 800};
uint64_t work[3] = {0, 0, 0};
for (int s = 0; s < 3; s++) {
size_t cap = (size_t)sizes[s] * 4 + 64;
char *mk = malloc(cap);
if (!mk) {
FAIL("alloc");
}
size_t n = 0;
for (int i = 0; i < sizes[s]; i++) {
n += (size_t)snprintf(mk + n, cap - n, "t ");
}
n += (size_t)snprintf(mk + n, cap - n, ":");
for (int i = 0; i < sizes[s]; i++) {
n += (size_t)snprintf(mk + n, cap - n, " d");
}
(void)snprintf(mk + n, cap - n, "\n\t@true\n\nd:\n\t@true\n");
const GpfFile files[] = {{"Makefile", mk}};
uint64_t before = atomic_load_explicit(&g_sh_make_pairs, memory_order_relaxed);
char *got = gpf_make_prerequisites(files, 1);
work[s] = atomic_load_explicit(&g_sh_make_pairs, memory_order_relaxed) - before;
bool one = got && strcmp(got, "Makefile:t -> Makefile:d (prerequisite:1)") == 0;
if (!one) {
fprintf(stderr, "repeated names at n=%d got:\n%s\n", sizes[s], got ? got : "(null)");
}
free(got);
free(mk);
if (!one) {
FAIL("a repeated pair is one edge");
}
}
if (work[0] == 0 || work[2] > work[0] * 20) {
fprintf(stderr, "make pair work at 50 / 200 / 800: %llu / %llu / %llu\n",
(unsigned long long)work[0], (unsigned long long)work[1],
(unsigned long long)work[2]);
FAIL("the work of a repeated rule line grows linearly");
}
PASS();
}
/* The Make grammar cannot parse a nested conditional indented with tabs
* inside an indented one (`envs` below): everything from there to the end of
* the file is one error region. The rules after it are still rules, and
* each has its node. A rule standing at the start of its line there has its
* prerequisites like any other. No edge for what the grammar read
* differently inside the region: a rule line indented with spaces, a rule
* under a conditional that follows a recipe; and none for what is no rule
* line at all: a define body, a recipe's continuation line. */
TEST(probe_make_prerequisites_after_a_region_the_grammar_cannot_parse) {
static const GpfFile files[] = {{"Makefile", "all: build pack\n\n"
"envs:\n"
" ifeq ($(A),)\n"
" \t\texport A := 1\n"
" \telse\n"
"\t\tifeq ($(B),)\n"
"\t\t\texport A := 2\n"
"\t\telse\n"
"\t\t\texport A := 3\n"
"\t\tendif\n"
" \tendif\n\n"
"build: envs\n"
"\techo build\n\n"
"pack: build\n"
"\tdocker run \\\n"
"-v out:/out build\n\n"
"define HELP\n"
"usage: build\n"
"endef\n\n"
" check: build\n"
"\techo check\n\n"
"ifeq ($(C),)\n"
"late: pack\n"
"\techo late\n"
"endif\n\n"
"usage:\n"
"\techo \"$(HELP)\"\n\n"
"lint: build | envs\n"
"\techo lint\n"}};
char *got = gpf_make_prerequisites(files, 1);
static const char want[] = "Makefile:all -> Makefile:build (prerequisite:1)\n"
"Makefile:all -> Makefile:pack (prerequisite:1)\n"
"Makefile:build -> Makefile:envs (prerequisite:14)\n"
"Makefile:lint -> Makefile:build (prerequisite:36)\n"
"Makefile:lint -> Makefile:envs (prerequisite:36 order-only)\n"
"Makefile:pack -> Makefile:build (prerequisite:17)";
if (!got || strcmp(got, want) != 0) {
fprintf(stderr, "make prerequisites in an error region got:\n%s\nwant:\n%s\n",
got ? got : "(null)", want);
free(got);
FAIL("make prerequisites in an error region");
}
free(got);
PASS();
}
/* make TARGET SPAWNS the rule of TARGET the makefile reads: the
* directory's Makefile (-C, --directory=), a -f file, a rule of a file it
* includes; from scripts, CI steps and recipes ($(MAKE)), on the line of
@@ -7171,6 +7918,7 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_kustomize_module_node);
RUN_TEST(probe_kustomize_imports_edges);
RUN_TEST(probe_kustomize_with_patches);
RUN_TEST(probe_kustomize_generator_files_are_file_references);
RUN_TEST(probe_k8s_manifest_after_leading_comment);
RUN_TEST(probe_kustomize_imports_after_leading_comment);
RUN_TEST(probe_k8s_selector_after_leading_separator);
@@ -7219,6 +7967,10 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_mcp_trace_topology);
RUN_TEST(probe_mcp_trace_topology_follows_deploys);
RUN_TEST(probe_mcp_trace_run);
RUN_TEST(probe_dockerfile_copy_sources_are_file_references);
RUN_TEST(probe_dockerfile_copy_source_under_two_contexts_is_no_reference);
RUN_TEST(probe_compose_service_files_are_file_references);
RUN_TEST(probe_compose_service_files_resolve_from_the_compose_directory);
RUN_TEST(probe_mcp_trace_deploy);
RUN_TEST(probe_dockerfile_bases_are_images);
RUN_TEST(probe_image_without_registry_host_stays_unknown);
@@ -7235,6 +7987,7 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_kustomize_patches_override_their_base);
RUN_TEST(probe_kustomize_helm_charts_deploy_their_chart);
RUN_TEST(probe_terraform_refs_resolve_in_their_module);
RUN_TEST(probe_terraform_file_functions_reference_their_files);
RUN_TEST(probe_terraform_module_files_extract_no_generic_refs);
RUN_TEST(probe_terraform_module_calls_import_their_source);
RUN_TEST(probe_terraform_tfvars_override_their_variables);
@@ -7253,8 +8006,12 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_shell_programs_by_path_spawn);
RUN_TEST(probe_make_programs_by_path_spawn);
RUN_TEST(probe_ci_and_scripts_run_scripts);
RUN_TEST(probe_github_actions_local_uses_reference_their_files);
RUN_TEST(probe_make_targets_spawn_their_rules);
RUN_TEST(probe_make_rules_have_a_node_per_target);
RUN_TEST(probe_make_prerequisites_depend_on_their_rules);
RUN_TEST(probe_make_repeated_names_cost_linear_work);
RUN_TEST(probe_make_prerequisites_after_a_region_the_grammar_cannot_parse);
RUN_TEST(probe_helmrelease_chartref_deploys_its_oci_chart);
RUN_TEST(probe_go_installer_deploys_charts);
RUN_TEST(probe_terraform_helm_release_deploys_its_chart);
+6
View File
@@ -1677,6 +1677,7 @@ extern void suite_path_alias(void);
extern void suite_site_bind(void);
extern void suite_scope_facts(void);
extern void suite_include_path(void);
extern void suite_scope_closure(void);
extern void suite_svn_state(void);
extern void suite_watcher(void);
extern void suite_lz4(void);
@@ -1686,6 +1687,8 @@ extern void suite_sqlite_writer(void);
extern void suite_go_lsp(void);
extern void suite_c_lsp(void);
extern void suite_php_lsp(void);
extern void suite_member_walk(void);
extern void suite_php_member_walk(void);
extern void suite_cs_lsp(void);
extern void suite_cs_lsp_bench(void);
extern void suite_perl_lsp(void);
@@ -2545,6 +2548,7 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(site_bind);
RUN_SELECTED_SUITE(scope_facts);
RUN_SELECTED_SUITE(include_path);
RUN_SELECTED_SUITE(scope_closure);
/* Watcher (M10) */
RUN_SELECTED_SUITE(svn_state);
@@ -2564,6 +2568,8 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(go_lsp);
RUN_SELECTED_SUITE(c_lsp);
RUN_SELECTED_SUITE(php_lsp);
RUN_SELECTED_SUITE(member_walk);
RUN_SELECTED_SUITE(php_member_walk);
RUN_SELECTED_SUITE(cs_lsp);
RUN_SELECTED_SUITE_PERF(cs_lsp_bench);
RUN_SELECTED_SUITE(perl_lsp);
File diff suppressed because it is too large Load Diff
+989
View File
@@ -0,0 +1,989 @@
/*
* test_php_member_walk.c — PHP on the shared member lookup (lsp/member_walk.h).
*
* Each fixture is indexed through the real pipeline twice: as it is (fewer than
* 50 files: the sequential resolver) and padded past 50 files (the parallel
* resolver); both must give the same CALLS edge. The PHP each fixture encodes
* was run with php 8.4 (docker php:8.4-cli-bookworm, script on stdin); the
* method PHP runs is named in a comment beside each assertion.
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
#include "test_helpers.h"
#include "cbm.h"
#include <mcp/mcp.h>
#include <store/store.h>
#include <pipeline/pipeline.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef struct {
const char *name;
const char *content;
} PmwFile;
typedef struct {
char tmpdir[256];
char dbpath[512];
char *project;
cbm_mcp_server_t *srv;
cbm_store_t *store;
} PmwProj;
enum { PMW_PAD = 52, PMW_FILES_MAX = 80 };
static void pmw_close(PmwProj *p) {
if (p->store) {
cbm_store_close(p->store);
}
if (p->srv) {
cbm_mcp_server_free(p->srv);
}
free(p->project);
if (p->tmpdir[0]) {
th_rmtree(p->tmpdir);
}
if (p->dbpath[0]) {
unlink(p->dbpath);
char side[600];
snprintf(side, sizeof(side), "%s-wal", p->dbpath);
unlink(side);
snprintf(side, sizeof(side), "%s-shm", p->dbpath);
unlink(side);
}
memset(p, 0, sizeof(*p));
}
/* Write the files (plus PMW_PAD Python files when padded) and index them. */
static bool pmw_index(PmwProj *p, const PmwFile *files, int n, bool padded) {
memset(p, 0, sizeof(*p));
snprintf(p->tmpdir, sizeof(p->tmpdir), "/tmp/cbm_pmw_XXXXXX");
if (!cbm_mkdtemp(p->tmpdir)) {
p->tmpdir[0] = '\0';
return false;
}
int total = padded ? n + PMW_PAD : n;
for (int i = 0; i < total; i++) {
char path[700];
char body[96];
const char *name;
const char *content;
char pad_name[64];
if (i < n) {
name = files[i].name;
content = files[i].content;
} else {
snprintf(pad_name, sizeof(pad_name), "pad/pad_%02d.py", i - n);
snprintf(body, sizeof(body), "def pad_%02d():\n return %d\n", i - n, i - n);
name = pad_name;
content = body;
}
snprintf(path, sizeof(path), "%s/%s", p->tmpdir, name);
char *slash = strrchr(path, '/');
if (slash && slash > path + strlen(p->tmpdir)) {
*slash = '\0';
cbm_mkdir_p(path, 0755);
*slash = '/';
}
FILE *f = fopen(path, "wb");
if (!f) {
return false;
}
fputs(content, f);
fclose(f);
}
p->project = cbm_project_name_from_path(p->tmpdir);
if (!p->project) {
return false;
}
const char *home = getenv("HOME");
char cache_dir[512];
snprintf(cache_dir, sizeof(cache_dir), "%s/.cache/codebase-memory-mcp", home ? home : "/tmp");
cbm_mkdir(cache_dir);
snprintf(p->dbpath, sizeof(p->dbpath), "%s/%s.db", cache_dir, p->project);
unlink(p->dbpath);
p->srv = cbm_mcp_server_new(NULL);
if (!p->srv) {
return false;
}
char args[700];
snprintf(args, sizeof(args), "{\"repo_path\":\"%s\"}", p->tmpdir);
char *resp = cbm_mcp_handle_tool(p->srv, "index_repository", args);
free(resp);
p->store = cbm_store_open_path(p->dbpath);
return p->store != NULL;
}
static bool pmw_tail(const char *qn, const char *tail) {
size_t q = qn ? strlen(qn) : 0;
size_t t = strlen(tail);
return q >= t && strcmp(qn + q - t, tail) == 0 && (q == t || qn[q - t - 1] == '.');
}
/* The strategy of the CALLS edge from a node whose QN ends in src_tail to one
* whose QN ends in tgt_tail, into out; false when there is no such edge. */
static bool pmw_edge(PmwProj *p, const char *src_tail, const char *tgt_tail, char *out,
size_t out_len) {
cbm_edge_t *edges = NULL;
int n = 0;
bool found = false;
if (out_len) {
out[0] = '\0';
}
if (cbm_store_find_edges_by_type(p->store, p->project, "CALLS", &edges, &n) != CBM_STORE_OK) {
return false;
}
for (int i = 0; i < n && !found; i++) {
cbm_node_t src;
cbm_node_t tgt;
if (cbm_store_find_node_by_id(p->store, edges[i].source_id, &src) != CBM_STORE_OK) {
continue;
}
if (cbm_store_find_node_by_id(p->store, edges[i].target_id, &tgt) != CBM_STORE_OK) {
cbm_node_free_fields(&src);
continue;
}
if (pmw_tail(src.qualified_name, src_tail) && pmw_tail(tgt.qualified_name, tgt_tail)) {
found = true;
const char *props = edges[i].properties_json ? edges[i].properties_json : "";
const char *s = strstr(props, "\"strategy\":\"");
if (s && out_len) {
s += strlen("\"strategy\":\"");
size_t k = 0;
while (s[k] && s[k] != '"' && k + 1 < out_len) {
out[k] = s[k];
k++;
}
out[k] = '\0';
}
}
cbm_node_free_fields(&src);
cbm_node_free_fields(&tgt);
}
cbm_store_free_edges(edges, n);
return found;
}
static bool pmw_php_strategy(const char *s) {
return strncmp(s, "php_", 4) == 0;
}
/* One expectation on a fixture: the edge src -> tgt, and whether the PHP
* engine drew it (strategy php_*) or not; want_edge false = no edge at all.
* want_edge false with want_php true: no edge the PHP engine drew, whatever a
* name guess does (main's guesses differ by route on some shapes). */
typedef struct {
const char *src;
const char *tgt;
bool want_edge;
bool want_php; /* when want_edge: drawn by the PHP engine (true) or by a name guess */
} PmwExpect;
/* Index the fixture on both routes and check every expectation on each. */
static int pmw_check(const PmwFile *files, int n, const PmwExpect *want, int nwant) {
int failures = 0;
for (int route = 0; route < 2; route++) {
PmwProj p;
if (!pmw_index(&p, files, n, route == 1)) {
printf(" [pmw] index failed (route %d)\n", route);
pmw_close(&p);
return failures + 1;
}
for (int i = 0; i < nwant; i++) {
char strategy[64];
bool edge = pmw_edge(&p, want[i].src, want[i].tgt, strategy, sizeof(strategy));
bool no_typed = !want[i].want_edge && want[i].want_php;
bool ok = no_typed ? !edge || !pmw_php_strategy(strategy)
: edge == want[i].want_edge &&
(!edge || pmw_php_strategy(strategy) == want[i].want_php);
if (!ok) {
printf(" [pmw] %s route: %s -> %s: edge=%d strategy=%s (want edge=%d php=%d)\n",
route ? "parallel" : "sequential", want[i].src, want[i].tgt, edge,
strategy, want[i].want_edge, want[i].want_php);
failures++;
}
}
pmw_close(&p);
}
return failures;
}
/* The parent's concrete method, not the interface's declaration: today's
* walk searched the interfaces first (a stack over the bases, last listed
* first). php: `$l->both()` runs Base::both. Partner: a method only the
* interface declares answers from the interface. */
TEST(phpmw_parent_method_beats_interface_declaration) {
static const PmwFile f[] = {
{"src/Shapes.php", "<?php\n"
"interface Ifc { public function both(): string;"
" public function idecl(): string; }\n"
"class Base { public function both(): string { return 'b'; } }\n"
"abstract class Leaf extends Base implements Ifc {}\n"
"class Caller {\n"
" public function run(Leaf $l): void { $l->both(); }\n"
" public function decl(Leaf $l): void { $l->idecl(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"Caller.run", "Base.both", true, true},
{"Caller.run", "Ifc.both", false, false},
{"Caller.decl", "Ifc.idecl", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 3), 0);
PASS();
}
/* A chain deeper than today's walk could see (it stopped after 32 types). */
TEST(phpmw_chain_past_the_old_cap) {
static char src[4096];
size_t used = (size_t)snprintf(src, sizeof(src),
"<?php\nclass C0 { public function rootm(): int { return 0; } }\n");
for (int i = 1; i <= 40; i++) {
used += (size_t)snprintf(src + used, sizeof(src) - used, "class C%d extends C%d {}\n", i,
i - 1);
}
snprintf(src + used, sizeof(src) - used,
"class Caller { public function run(C40 $c): void { $c->rootm(); } }\n");
PmwFile f[] = {{"src/Chain.php", src}};
static const PmwExpect want[] = {
{"Caller.run", "C0.rootm", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 1), 0);
PASS();
}
/* A parent outside the project: the lookup passes it as an unknown place, so
* the interface's declaration behind it is a possible answer (prefix not
* complete), drawn as today's engine drew it. php: Vendor's both() runs; the
* edge names the declaration the call is checked against. Kept, not new:
* the base draws the same. Partner: the class's own method. */
TEST(phpmw_vendor_parent_keeps_todays_answer) {
static const PmwFile f[] = {
{"src/Kid.php", "<?php\n"
"namespace App;\n"
"use Vendor\\Pkg\\Base;\n"
"interface Ifc { public function both(): string; }\n"
"class Kid extends Base implements Ifc {\n"
" public function own(): int { return 1; }\n"
"}\n"
"class Caller {\n"
" public function run(Kid $k): void { $k->both(); $k->own(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"Caller.run", "Ifc.both", true, true},
{"Caller.run", "Kid.own", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* A trait from outside the project beside the parent's method: passed as an
* unknown place, the parent's method a possible answer, drawn as today (the
* vendor trait could shadow it; then PHP runs the trait's). Kept, not new.
* Partner: the same name on an unrelated class gets no edge. */
TEST(phpmw_vendor_trait_keeps_todays_answer) {
static const PmwFile f[] = {
{"app/Models/Contact.php",
"<?php\nnamespace App\\Models;\nuse Vendor\\Pkg\\HasFactory;\n"
"class BaseModel { public function helper(): int { return 1; }"
" public function getName(): string { return 'b'; } }\n"
"class Contact extends BaseModel {\n use HasFactory;\n"
" public function run(): void { $this->helper(); $this->getName(); }\n}\n"
"class Other { public function getName(): string { return 'o'; } }\n"},
};
static const PmwExpect want[] = {
{"Contact.run", "BaseModel.helper", true, true},
{"Contact.run", "BaseModel.getName", true, true},
{"Contact.run", "Other.getName", false, false},
};
ASSERT_EQ(pmw_check(f, 1, want, 3), 0);
PASS();
}
/* `B::m insteadof A`: the trait the clause names answers (today the clause was
* never read and the first trait's copy won). php: B::m runs, its Y return
* makes pick() Y::pick. */
TEST(phpmw_insteadof_picks_the_named_trait) {
static const PmwFile f[] = {
{"src/Pick.php", "<?php\n"
"class X { public function pick(): string { return 'x'; } }\n"
"class Y { public function pick(): string { return 'y'; } }\n"
"trait A { public function m(): X { return new X(); } }\n"
"trait B { public function m(): Y { return new Y(); } }\n"
"class C {\n"
" use A, B { B::m insteadof A; }\n"
" public function run(): void { $this->m()->pick(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"C.run", "Y.pick", true, true},
{"C.run", "X.pick", false, false},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* `make as build`: the alias answers with the trait's method (today the
* clause was never read). php: build() runs T::make; spin() is Z::spin.
* Partner: the original name answers too. */
TEST(phpmw_trait_alias_answers) {
static const PmwFile f[] = {
{"src/Alias.php", "<?php\n"
"class Z { public function spin(): int { return 1; } }\n"
"class Q { public function spin(): int { return 2; } }\n"
"trait T { public function make(): Z { return new Z(); } }\n"
"class C {\n"
" use T { make as build; }\n"
" public function viaAlias(): void { $this->build()->spin(); }\n"
" public function viaName(): void { $this->make()->spin(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"C.viaAlias", "Z.spin", true, true},
{"C.viaName", "Z.spin", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* A trait used by a class declared in another file: today the cross-file pass
* knew nothing of it (trait uses were not extracted). The caller's per-file
* registry holds its own module and the modules it imports, so the trait
* answers when it is declared there (a trait in a module the caller does not
* import stays unknown, as a parent class there does). php: widget() runs
* HasWidget::widget, spin() is Widget::spin. */
TEST(phpmw_cross_file_trait_member) {
static const PmwFile f[] = {
{"lib/User.php", "<?php\nnamespace Lib;\n"
"class Widget { public function spin(): int { return 1; } }\n"
"trait HasWidget { public function widget(): Widget"
" { return new Widget(); } }\n"
"class User { use HasWidget; }\n"},
{"lib/Gadget.php", "<?php\nnamespace Lib;\n"
"class Gadget { public function spin(): int { return 2; } }\n"},
{"app/Run.php", "<?php\nnamespace App;\n"
"use Lib\\User;\n"
"class Runner {\n"
" public function run(User $u): void { $u->widget()->spin(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"Runner.run", "Widget.spin", true, true},
{"Runner.run", "Gadget.spin", false, false},
};
ASSERT_EQ(pmw_check(f, 3, want, 2), 0);
PASS();
}
/* A trait's abstract method is a requirement the parent satisfies. php:
* `$this->need()` in a class using the trait runs Base::need. (With no
* implementation anywhere the declaration answers: member_walk's
* member_walk_mixin_requirement_defers.) */
TEST(phpmw_trait_abstract_method_is_a_requirement) {
static const PmwFile f[] = {
{"src/Req.php", "<?php\n"
"trait Needs { abstract public function need(): int;"
" public function useIt(): int { return $this->need(); } }\n"
"class Base { public function need(): int { return 1; } }\n"
"class Kid extends Base { use Needs;"
" public function run(): int { return $this->need(); } }\n"},
};
static const PmwExpect want[] = {
{"Kid.run", "Base.need", true, true},
{"Kid.run", "Needs.need", false, false},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* A trait spelled in another file names, there, a vendor trait; a project
* trait with the same short name is not it (F2, fx/vtrait; php: the vendor
* trait runs, `Right`, never Wrong::spin). Nothing is drawn from the wrong
* trait. Partner: a class whose file imports the project trait gets its
* member, typed. */
TEST(phpmw_trait_resolved_where_written) {
static const PmwFile f[] = {
{"src/Other/Stuff.php",
"<?php\nnamespace App\\Other;\n"
"trait HasThing { public function thing(): Wrong { return new Wrong(); } }\n"
"class Wrong { public function spin() { return 'Wrong'; } }\n"
"class Helper { public static function make() { return 1; } }\n"},
{"src/Models/Model.php", "<?php\nnamespace App\\Models;\nuse Vendor\\Pkg\\HasThing;\n"
"class Model { use HasThing; }\n"},
{"src/Models/Good.php", "<?php\nnamespace App\\Models;\nuse App\\Other\\HasThing;\n"
"class Good { use HasThing; }\n"},
{"src/Other2/Right.php", "<?php\nnamespace App\\Other2;\n"
"class Right { public function spin() { return 'Right'; } }\n"},
{"src/Http/Caller.php",
"<?php\nnamespace App\\Http;\nuse App\\Models\\Model;\nuse App\\Models\\Good;\n"
"use App\\Other\\Helper;\n"
"class Caller {\n"
" public function run(Model $m) { Helper::make(); return $m->thing()->spin(); }\n"
" public function ok(Good $g) { return $g->thing()->spin(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"Caller.run", "Wrong.spin", false, false},
{"Caller.ok", "Wrong.spin", true, true},
};
ASSERT_EQ(pmw_check(f, 5, want, 2), 0);
PASS();
}
/* A file with several namespaces (phpunit's bundled tools): a trait declared
* in a later one is known by its own namespace, not the file's first. php:
* Zs::spin runs. Partner: the same-named method of another class gets no
* edge. */
TEST(phpmw_trait_in_a_later_namespace) {
static const PmwFile f[] = {
{"src/Bundle.php", "<?php\nnamespace App;\nuse Lib\\HasZ;\n"
"class Zdecoy { public function spin(): int { return 2; } }\n"
"class UsesZ {\n use HasZ;\n"
" public function run(): void { $this->z()->spin(); }\n}\n"
"namespace Lib;\n"
"class Zs { public function spin(): int { return 1; } }\n"
"trait HasZ { public function z(): Zs { return new Zs; } }\n"},
};
static const PmwExpect want[] = {
{"UsesZ.run", "Zs.spin", true, true},
{"UsesZ.run", "Zdecoy.spin", false, false},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* A trait's abstract method beside a vendor trait: the vendor trait may
* implement it (php: fx/req2, `Zv`, its m runs), so the requirement itself
* answers, as today's flattened copy did, and the parent's m is not reached
* (F3). Partner: the requirement's return type still types the chained call,
* as on main. */
TEST(phpmw_requirement_beside_vendor_trait) {
static const PmwFile f[] = {
{"src/Req2.php",
"<?php\nnamespace App\\Req2;\nuse Vendor\\Pkg\\VTrait;\n"
"class Zi { public function spin() { return 'Zi'; } }\n"
"class Zp extends Zi { public function spin() { return 'Zp'; } }\n"
"class Zv extends Zp { public function spin() { return 'Zv'; } }\n"
"trait NeedM { abstract public function m(): Zi; }\n"
"class P { public function m(): Zp { return new Zp; } }\n"
"class C extends P {\n use NeedM, VTrait;\n"
" public function run() { return $this->m()->spin(); }\n}\n"
"class QCaller { public function go(C $c) { return $c->m()->spin(); } }\n"},
};
static const PmwExpect want[] = {
{"C.run", "P.m", false, false},
{"C.run", "Zp.spin", false, false},
{"C.run", "Zi.spin", true, true},
{"QCaller.go", "P.m", false, false},
{"QCaller.go", "Zi.spin", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 5), 0);
PASS();
}
/* Behind a vendor parent both interfaces declare m (fx/twoifc): a possible
* answer, drawn because today's engine drew one here; the walk's order (the
* first interface, as php's member table) stands where the old stack took
* the last (F5, an accepted change). Partner: the other declaration gets no
* edge. */
TEST(phpmw_possible_answer_in_the_walks_order) {
static const PmwFile f[] = {
{"src/Two.php", "<?php\nnamespace App\\Two;\nuse Vendor\\Pkg\\VBase;\n"
"interface I1 { public function m(): int; }\n"
"interface I2 { public function m(): int; }\n"
"class C extends VBase implements I1, I2 {}\n"
"class TCaller { public function go(C $c) { return $c->m(); } }\n"},
};
static const PmwExpect want[] = {
{"TCaller.go", "I1.m", true, true},
{"TCaller.go", "I2.m", false, false},
};
ASSERT_EQ(pmw_check(f, 1, want, 2), 0);
PASS();
}
/* A possible trait member is drawn when every class or trait on its `use`
* path, from the holder down to the trait that uses the owner, is declared in
* the file walked; the owner may be anywhere (review 3; what main's
* flattening reached). fx/tt: all in one file (php: Za for all four; main
* types all four). fx/ttx: the owner Inner in another file, the path P, Outer
* here, behind the vendor trait V (php: Za for every V php accepts, review
* 3; main typed): kept. fx/d1x: depth 1, the owner T2 imported (php: Za; main
* typed): kept. Negative partner fx/pathx: the path leaves the file (P here
* uses Outer of another file; php: Za, but main draws nothing there and the
* walk's answer is only possible): no edge; without V the hit is proven and
* drawn. fx/ttown and fx/d1y below: a non-leaf trait's own member. */
TEST(phpmw_possible_trait_member_same_file) {
static const PmwFile f[] = {
{"src/TT.php", "<?php\nnamespace App\\TT;\nuse Vendor\\Pkg\\V;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait Inner { public function deep(): Za { return new Za; } }\n"
"trait Outer { use Inner; }\n"
"class P { use Outer; }\n"
"class PB { public function deep(): Zb { return new Zb; } }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class Direct { use Outer; }\n"
"class DirectV { use Outer, V; }\n"
"class TCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Plain $p) { return $p->deep()->spin(); }\n"
" public function c(Direct $d) { return $d->deep()->spin(); }\n"
" public function d(DirectV $d) { return $d->deep()->spin(); }\n"
"}\n"},
};
static const PmwExpect want[] = {
{"TCall.a", "Za.spin", true, true},
{"TCall.b", "Za.spin", true, true},
{"TCall.c", "Za.spin", true, true},
{"TCall.d", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(f, 1, want, 4), 0);
static const PmwFile g[] = {
{"src/In/Inner.php", "<?php\nnamespace App\\In;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait Inner { public function deep(): Za { return new Za; } }\n"},
{"src/TT.php", "<?php\nnamespace App\\TT;\nuse Vendor\\Pkg\\V;\nuse App\\In\\Inner;\n"
"trait Outer { use Inner; }\n"
"class P { use Outer; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class TCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Plain $p) { return $p->deep()->spin(); }\n"
"}\n"},
};
static const PmwExpect gwant[] = {
{"TCall.a", "Za.spin", true, true},
{"TCall.b", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(g, 2, gwant, 2), 0);
static const PmwFile d[] = {
{"src/Lib/T2.php", "<?php\nnamespace App\\Lib;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait T2 { public function deep(): Za { return new Za; } }\n"},
{"src/D1.php", "<?php\nnamespace App\\D1;\nuse Vendor\\Pkg\\V;\nuse App\\Lib\\T2;\n"
"class P { use T2; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class DCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Plain $p) { return $p->deep()->spin(); }\n"
"}\n"},
};
static const PmwExpect dwant[] = {
{"DCall.a", "Za.spin", true, true},
{"DCall.b", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(d, 2, dwant, 2), 0);
static const PmwFile x[] = {
{"src/In/Inner.php", "<?php\nnamespace App\\In;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait Inner { public function deep(): Za { return new Za; } }\n"},
{"src/Lib/Outer.php",
"<?php\nnamespace App\\Lib;\nuse App\\In\\Inner;\ntrait Outer { use Inner; }\n"},
{"src/TT.php", "<?php\nnamespace App\\TT;\nuse Vendor\\Pkg\\V;\nuse App\\Lib\\Outer;\n"
"use App\\In\\Inner;\n"
"class P { use Outer; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class TCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Plain $p) { return $p->deep()->spin(); }\n"
"}\n"},
};
/* No edge at all for TCall.a: TT.php imports neither Za nor Zb, so no
* name guess stands in (one would differ by route, main's). */
static const PmwExpect xwant[] = {
{"TCall.a", "Za.spin", false, false},
{"TCall.b", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(x, 3, xwant, 2), 0);
/* A member a trait declares itself while it also uses a trait (review 4,
* F-A): the path below its owner is empty. fx/ttown, all in one file (php:
* O1 Hidden->shallow Za, O2 Za, O3 Hidden->deep Za; main types a and c);
* fx/d1y, depth 1, the owner T2 { use U; deep } in another file (php: Y1,
* Y2 Za; main types both). */
static const PmwFile o[] = {
{"src/TO.php",
"<?php\nnamespace App\\TO;\nuse Vendor\\Pkg\\V;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait Inner { public function deep(): Za { return new Za; } }\n"
"trait Outer { use Inner; public function shallow(): Za { return new Za; } }\n"
"class P { use Outer; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class TCall {\n"
" public function a(Hidden $h) { return $h->shallow()->spin(); }\n"
" public function b(Plain $p) { return $p->shallow()->spin(); }\n"
" public function c(Hidden $h) { return $h->deep()->spin(); }\n"
"}\n"},
};
static const PmwExpect owant[] = {
{"TCall.a", "Za.spin", true, true},
{"TCall.b", "Za.spin", true, true},
{"TCall.c", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(o, 1, owant, 3), 0);
static const PmwFile y[] = {
{"src/Lib/T2.php", "<?php\nnamespace App\\Lib;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait U { public function other() { return 1; } }\n"
"trait T2 { use U; public function deep(): Za { return new Za; } }\n"},
{"src/D1.php", "<?php\nnamespace App\\D1;\nuse Vendor\\Pkg\\V;\nuse App\\Lib\\T2;\n"
"class P { use T2; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class DCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Plain $p) { return $p->deep()->spin(); }\n"
"}\n"},
};
static const PmwExpect ywant[] = {
{"DCall.a", "Za.spin", true, true},
{"DCall.b", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(y, 2, ywant, 2), 0);
/* fx/u2 (review 5): T (here) uses U (U { use W; deep }) and the leaf U2
* (deep2), both in another file; P uses T; behind V at depth 2 (php: U1-U4
* Za; main types all four). */
static const PmwFile u[] = {
{"src/Lib/U.php", "<?php\nnamespace App\\Lib;\n"
"class Za { public function spin() { return 'Za'; } }\n"
"class Zb { public function spin() { return 'Zb'; } }\n"
"trait W { public function other() { return 1; } }\n"
"trait U { use W; public function deep(): Za { return new Za; } }\n"
"trait U2 { public function deep2(): Za { return new Za; } }\n"},
{"src/TT.php", "<?php\nnamespace App\\U2;\nuse Vendor\\Pkg\\V;\nuse App\\Lib\\U;\n"
"use App\\Lib\\U2;\n"
"trait T { use U, U2; }\n"
"class P { use T; }\n"
"class Hidden extends P { use V; }\n"
"class Plain extends P {}\n"
"class UCall {\n"
" public function a(Hidden $h) { return $h->deep()->spin(); }\n"
" public function b(Hidden $h) { return $h->deep2()->spin(); }\n"
" public function c(Plain $p) { return $p->deep()->spin(); }\n"
" public function d(Plain $p) { return $p->deep2()->spin(); }\n"
"}\n"},
};
static const PmwExpect uwant[] = {
{"UCall.a", "Za.spin", true, true},
{"UCall.b", "Za.spin", true, true},
{"UCall.c", "Za.spin", true, true},
{"UCall.d", "Za.spin", true, true},
};
ASSERT_EQ(pmw_check(u, 2, uwant, 4), 0);
PASS();
}
/* A trait's requirement in another file, beside a vendor trait (review 3,
* fx/rqx; php: the vendor trait's m runs, Zv): the per-file pass, which
* cannot see NeedM, must not leave the parent's P.m standing; the
* requirement's copy answers, as on main (Zi.spin typed by its declared
* type, no edge the engine draws to P.m). Positive partner fx/rqxp: without
* the vendor trait the parent implements it (php: P::m runs, Zp): P.m and
* Zp.spin typed (main misses both). */
TEST(phpmw_requirement_in_another_file) {
static const char *need = "<?php\nnamespace App\\Lib;\n"
"class Zi { public function spin() { return 'Zi'; } }\n"
"class Zp extends Zi { public function spin() { return 'Zp'; } }\n"
"class Zv extends Zp { public function spin() { return 'Zv'; } }\n"
"trait NeedM { abstract public function m(): Zi; }\n";
const PmwFile f[] = {
{"src/Lib/NeedM.php", need},
{"src/RQ.php", "<?php\nnamespace App\\RQ;\nuse Vendor\\Pkg\\VTrait;\nuse App\\Lib\\NeedM;\n"
"use App\\Lib\\Zp;\n"
"class P { public function m(): Zp { return new Zp; } }\n"
"class C extends P {\n use NeedM, VTrait;\n"
" public function run() { return $this->m()->spin(); }\n}\n"},
};
static const PmwExpect want[] = {
{"C.run", "P.m", false, true}, /* no typed edge (main guesses it by name on one route) */
{"C.run", "Zi.spin", true, true},
{"C.run", "Zp.spin", false, true},
};
ASSERT_EQ(pmw_check(f, 2, want, 3), 0);
const PmwFile g[] = {
{"src/Lib/NeedM.php", need},
{"src/RQ.php", "<?php\nnamespace App\\RQ;\nuse App\\Lib\\NeedM;\nuse App\\Lib\\Zp;\n"
"class P { public function m(): Zp { return new Zp; } }\n"
"class D extends P {\n use NeedM;\n"
" public function run() { return $this->m()->spin(); }\n}\n"},
};
static const PmwExpect gwant[] = {
{"D.run", "P.m", true, true},
{"D.run", "Zp.spin", true, true},
};
ASSERT_EQ(pmw_check(g, 2, gwant, 2), 0);
PASS();
}
/* "Declared in this file" compares the module exactly (N1): the module of
* src/Foo.php is a prefix of every class of src/Foo/Kid.php (fx/prefix). A
* possible trait member of such a class is not drawn (php: the vendor trait's
* m runs, Zv; main's guess stays); the control layout (fx/prefixctl) draws
* nothing either. Positive partner: the same shape with the classes really
* declared in the caller's file is drawn typed. */
TEST(phpmw_same_file_is_exact) {
static const char *kid = "<?php\nnamespace App\\Foo;\nuse Vendor\\Pkg\\V;\n"
"class Zt { public function spin() { return 'Zt'; } }\n"
"class Zv extends Zt { public function spin() { return 'Zv'; } }\n"
"trait T { public function m(): Zt { return new Zt; } }\n"
"class P { use T; }\n"
"class Kid extends P { use V; }\n";
const PmwFile f[] = {
{"src/Foo/Kid.php", kid},
{"src/Foo.php",
"<?php\nnamespace App;\nuse App\\Foo\\Kid;\n"
"class Caller { public function go(Kid $k) { return $k->m()->spin(); } }\n"},
};
static const PmwExpect want[] = {
{"Caller.go", "Zt.spin", true, false}, /* main's guess, as on main */
};
ASSERT_EQ(pmw_check(f, 2, want, 1), 0);
const PmwFile g[] = {
{"src/Foo/Kid.php", kid},
{"src/Bar.php",
"<?php\nnamespace App;\nuse App\\Foo\\Kid;\n"
"class Caller { public function go(Kid $k) { return $k->m()->spin(); } }\n"},
};
static const PmwExpect gwant[] = {
{"Caller.go", "Zt.spin", false, false},
};
ASSERT_EQ(pmw_check(g, 2, gwant, 1), 0);
static const PmwFile h[] = {
{"src/Foo.php",
"<?php\nnamespace App;\nuse Vendor\\Pkg\\V;\n"
"class Zh { public function spin() { return 'Zh'; } }\n"
"class Zw extends Zh { public function spin() { return 'Zw'; } }\n"
"trait H { public function h(): Zh { return new Zh; } }\n"
"class PH { use H; }\n"
"class KidH extends PH { use V; }\n"
"class Caller { public function here(KidH $k) { return $k->h()->spin(); } }\n"},
};
static const PmwExpect hwant[] = {
{"Caller.here", "Zh.spin", true, true},
};
ASSERT_EQ(pmw_check(h, 1, hwant, 1), 0);
PASS();
}
/* A 40,000-deep chain of traits using traits (F1, fx/deep40k): no worker
* crashes, the file is indexed on both routes; the member at the bottom is the
* using class's copy (main's guess draws the call, as on main) and its return
* type types the chained call (php: Zd::spin runs; main guessed the pair). */
TEST(phpmw_trait_chain_40k) {
enum { DEPTH = 40000 };
size_t cap = (size_t)DEPTH * 40 + 1024;
char *src = (char *)malloc(cap);
ASSERT_NOT_NULL(src);
size_t used = (size_t)snprintf(src, cap,
"<?php\nnamespace App\\Deep;\n"
"class Zd { public function spin() { return 'Zd'; } }\n"
"trait T0 { public function m0(): Zd { return new Zd; } }\n");
for (int i = 1; i <= DEPTH; i++) {
used += (size_t)snprintf(src + used, cap - used, "trait T%d { use T%d; }\n", i, i - 1);
}
snprintf(src + used, cap - used,
"class D { use T%d; public function run() { return $this->m0()->spin(); } }\n"
"class DCaller { public function go(D $d) { return $d->m0()->spin(); } }\n",
DEPTH);
PmwFile f[] = {{"src/Deep.php", src}};
static const PmwExpect want[] = {
{"D.run", "T0.m0", true, false},
{"D.run", "Zd.spin", true, true},
{"DCaller.go", "Zd.spin", true, true},
};
int failures = pmw_check(f, 1, want, 3);
free(src);
ASSERT_EQ(failures, 0);
PASS();
}
/* The extractor records what the lookup needs and INHERITS does not take:
* the kind of each base, the traits, and their rules. */
TEST(phpmw_extractor_records_kinds_traits_rules) {
const char *src = "<?php\n"
"interface I1 {} interface I2 {}\n"
"trait T1 { public function m() {} } trait T2 { public function m() {} }\n"
"class P {}\n"
"class C extends P implements I1, \\Ns\\I2 {\n"
" use T1, T2 { T1::m insteadof T2; T2::m as m2; m as protected; }\n"
" use \\Ns\\T3;\n"
"}\n"
"interface J extends I1, I2 {}\n";
CBMFileResult *r =
cbm_extract_file(src, (int)strlen(src), CBM_LANG_PHP, "test", "main.php", 0, NULL, NULL);
ASSERT_NOT_NULL(r);
const CBMDefinition *c = NULL;
const CBMDefinition *j = NULL;
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (d->name && strcmp(d->name, "C") == 0) {
c = d;
} else if (d->name && strcmp(d->name, "J") == 0) {
j = d;
}
}
ASSERT_NOT_NULL(c);
ASSERT_NOT_NULL(j);
ASSERT_NOT_NULL(c->type_facts);
ASSERT_NOT_NULL(j->type_facts);
const CBMDefTypeFacts *cf = c->type_facts;
const CBMDefTypeFacts *jf = j->type_facts;
ASSERT_STR_EQ(cf->base_kinds, "eii");
ASSERT_NOT_NULL(cf->mixins);
/* Traits as the file names them (global namespace here). */
ASSERT_STR_EQ(cf->mixins[0], "\\T1");
ASSERT_STR_EQ(cf->mixins[1], "\\T2");
ASSERT_STR_EQ(cf->mixins[2], "\\Ns\\T3");
ASSERT_NULL(cf->mixins[3]);
ASSERT_STR_EQ(cf->mixin_kinds, "ttt");
ASSERT_STR_EQ(cf->member_rules, "x \\T1 m \\T2;a \\T2 m m2");
/* Traits stay out of base_classes (INHERITS). */
ASSERT_STR_EQ(c->base_classes[0], "P");
ASSERT_NULL(c->base_classes[3]);
ASSERT_STR_EQ(jf->base_kinds, "ee");
ASSERT_NULL(jf->mixins);
cbm_free_result(r);
PASS();
}
/* A trait's name is qualified where the class is written, by PHP's own rule:
* a `use` alias (plain, `as`, grouped), else the namespace; a bracketed
* namespace has its own uses; a function `use` aliases no class. */
TEST(phpmw_extractor_qualifies_trait_names) {
const char *src = "<?php\n"
"namespace App\\Models;\n"
"use Vendor\\Pkg\\HasThing;\n"
"use App\\Traits\\{Greets, Waves as W};\n"
"use function App\\Helpers\\Local;\n"
"class M { use HasThing, Greets, W, Local, Sub\\Deep; }\n"
"class R { use namespace\\Sub\\Rel, NameSpace\\Rel2; }\n"
"namespace Other;\n"
"class N { use HasThing; }\n";
CBMFileResult *r =
cbm_extract_file(src, (int)strlen(src), CBM_LANG_PHP, "test", "m.php", 0, NULL, NULL);
ASSERT_NOT_NULL(r);
const CBMDefTypeFacts *mf = NULL;
const CBMDefTypeFacts *nf = NULL;
const CBMDefTypeFacts *rf = NULL;
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (d->name && strcmp(d->name, "M") == 0) {
mf = d->type_facts;
} else if (d->name && strcmp(d->name, "N") == 0) {
nf = d->type_facts;
} else if (d->name && strcmp(d->name, "R") == 0) {
rf = d->type_facts;
}
}
ASSERT_NOT_NULL(mf);
ASSERT_NOT_NULL(nf);
ASSERT_NOT_NULL(rf);
/* `namespace\X` is relative to the current namespace, the keyword in any
* case (review 2, C8: php resolves it to App\Q\Sub\Rel there). */
ASSERT_STR_EQ(rf->mixins[0], "\\App\\Models\\Sub\\Rel");
ASSERT_STR_EQ(rf->mixins[1], "\\App\\Models\\Rel2");
ASSERT_STR_EQ(mf->mixins[0], "\\Vendor\\Pkg\\HasThing");
ASSERT_STR_EQ(mf->mixins[1], "\\App\\Traits\\Greets");
ASSERT_STR_EQ(mf->mixins[2], "\\App\\Traits\\Waves");
ASSERT_STR_EQ(mf->mixins[3], "\\App\\Models\\Local");
ASSERT_STR_EQ(mf->mixins[4], "\\App\\Models\\Sub\\Deep");
/* `namespace Other;` starts anew: no alias carries over. */
ASSERT_STR_EQ(nf->mixins[0], "\\Other\\HasThing");
/* Each type's own namespace (the file-level one keeps only the first). */
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (d->name && strcmp(d->name, "M") == 0) {
ASSERT_STR_EQ(d->decl_namespace, "App\\Models");
} else if (d->name && strcmp(d->name, "N") == 0) {
ASSERT_STR_EQ(d->decl_namespace, "Other");
}
}
cbm_free_result(r);
const char *br = "<?php\n"
"namespace A { use X\\Y; }\n"
"namespace B { use Q\\Y; class K { use Y; } }\n";
r = cbm_extract_file(br, (int)strlen(br), CBM_LANG_PHP, "test", "b.php", 0, NULL, NULL);
ASSERT_NOT_NULL(r);
const CBMDefTypeFacts *kf = NULL;
for (int i = 0; i < r->defs.count; i++) {
const CBMDefinition *d = &r->defs.items[i];
if (d->name && strcmp(d->name, "K") == 0) {
kf = d->type_facts;
}
}
ASSERT_NOT_NULL(kf);
ASSERT_STR_EQ(kf->mixins[0], "\\Q\\Y");
cbm_free_result(r);
PASS();
}
/* `use namespace\Sub\Rel` names App\Q\Sub\Rel, never the App\Q\Rel beside it
* (review 2, C8; php: ZRel), from a caller in the class's own file (the
* engine's own reader) and in another file (the extractor's names). Both
* callers' files import the traits and ZRel, as fx/qual's XCall does: what
* a file sees of other files' types comes through its imports. */
TEST(phpmw_relative_trait_name_through_the_pipeline) {
static const PmwFile f[] = {
{"src/Q.php", "<?php\nnamespace App\\Q;\nuse App\\Q\\Rel as QRel;\n"
"use App\\Q\\Sub\\Rel as SubRel;\nuse App\\Z\\ZRel;\n"
"class C8 { use namespace\\Sub\\Rel; }\n"
"class QCall { public function h8(C8 $x) { return $x->m()->spin(); } }\n"},
{"src/QDecoy.php",
"<?php\nnamespace App\\Q;\n"
"trait Rel { public function m(): \\App\\Z\\ZDecoy { return new \\App\\Z\\ZDecoy; } }\n"},
{"src/QSub.php",
"<?php\nnamespace App\\Q\\Sub;\n"
"trait Rel { public function m(): \\App\\Z\\ZRel { return new \\App\\Z\\ZRel; } }\n"},
{"src/Z.php", "<?php\nnamespace App\\Z;\n"
"class ZRel { public function spin() { return 'ZRel'; } }\n"
"class ZDecoy { public function spin() { return 'ZDecoy'; } }\n"},
{"src/Http/XCall.php",
"<?php\nnamespace App\\Http;\nuse App\\Q\\C8;\nuse App\\Q\\Rel as QRel;\n"
"use App\\Q\\Sub\\Rel as SubRel;\nuse App\\Z\\ZRel;\n"
"class XCall { public function g8(C8 $x) { return $x->m()->spin(); } }\n"},
};
static const PmwExpect want[] = {
{"XCall.g8", "ZRel.spin", true, true},
{"QCall.h8", "ZRel.spin", true, true},
{"XCall.g8", "ZDecoy.spin", false, false},
{"QCall.h8", "ZDecoy.spin", false, false},
};
ASSERT_EQ(pmw_check(f, 5, want, 4), 0);
PASS();
}
SUITE(php_member_walk) {
RUN_TEST(phpmw_extractor_records_kinds_traits_rules);
RUN_TEST(phpmw_extractor_qualifies_trait_names);
RUN_TEST(phpmw_relative_trait_name_through_the_pipeline);
RUN_TEST(phpmw_trait_resolved_where_written);
RUN_TEST(phpmw_trait_in_a_later_namespace);
RUN_TEST(phpmw_requirement_beside_vendor_trait);
RUN_TEST(phpmw_possible_answer_in_the_walks_order);
RUN_TEST(phpmw_possible_trait_member_same_file);
RUN_TEST(phpmw_requirement_in_another_file);
RUN_TEST(phpmw_same_file_is_exact);
RUN_TEST(phpmw_trait_chain_40k);
RUN_TEST(phpmw_parent_method_beats_interface_declaration);
RUN_TEST(phpmw_chain_past_the_old_cap);
RUN_TEST(phpmw_vendor_parent_keeps_todays_answer);
RUN_TEST(phpmw_vendor_trait_keeps_todays_answer);
RUN_TEST(phpmw_insteadof_picks_the_named_trait);
RUN_TEST(phpmw_trait_alias_answers);
RUN_TEST(phpmw_cross_file_trait_member);
RUN_TEST(phpmw_trait_abstract_method_is_a_requirement);
}
+617 -15
View File
@@ -5159,6 +5159,597 @@ TEST(incremental_deleted_spawner_drops_its_process) {
PASS();
}
/* A Dockerfile below the root reads a COPY source under its own directory or
* under the repository root, the one that holds the file; a source both hold
* is no REFERENCES_FILE edge. Deleting one file of such a pair leaves a single
* candidate, and the edge to it comes from a Dockerfile that did not change:
* the planner declines to the full route, and the graph is the fresh index's.
* Both directions: the root's file of a pair goes (both.sh), and the
* Dockerfile directory's file of a pair goes (svc/twin.sh). Deleting a file
* that has no partner stays a repair. */
TEST(incremental_docker_context_pair_deleted_takes_the_full_route) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_dkpair_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
write_temp_file(tmp, "svc/Dockerfile", "FROM alpine:3.20\n"
"COPY both.sh /both.sh\n"
"COPY entry.sh /entry.sh\n"
"COPY twin.sh /twin.sh\n");
write_temp_file(tmp, "svc/entry.sh", "#!/bin/sh\necho entry\n");
write_temp_file(tmp, "svc/both.sh", "#!/bin/sh\necho svc\n");
write_temp_file(tmp, "both.sh", "#!/bin/sh\necho root\n");
write_temp_file(tmp, "svc/twin.sh", "#!/bin/sh\necho svc twin\n");
write_temp_file(tmp, "twin.sh", "#!/bin/sh\necho root twin\n");
write_temp_file(tmp, "other.sh", "#!/bin/sh\necho other\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/dkpair.db", tmp);
static const char refs[] = "SELECT COUNT(*) FROM edges WHERE type='REFERENCES_FILE' AND "
"json_extract(properties,'$.via')='copy'";
static const char to_svc_both[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='svc/both.sh'";
static const char to_root_twin[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='twin.sh'";
int rc_full = k8s_inc_index(tmp, db_path);
int refs_full = k8s_inc_count(db_path, refs);
char path[512];
snprintf(path, sizeof(path), "%s/other.sh", tmp);
(void)remove(path);
int rc_other = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t other_route = cbm_pipeline_incremental_test_last_route();
int refs_other = k8s_inc_count(db_path, refs);
snprintf(path, sizeof(path), "%s/both.sh", tmp);
(void)remove(path);
int rc_pair = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t pair_route = cbm_pipeline_incremental_test_last_route();
int refs_pair = k8s_inc_count(db_path, refs);
int svc_both = k8s_inc_count(db_path, to_svc_both);
snprintf(path, sizeof(path), "%s/svc/twin.sh", tmp);
(void)remove(path);
int rc_twin = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t twin_route = cbm_pipeline_incremental_test_last_route();
int refs_twin = k8s_inc_count(db_path, refs);
int root_twin = k8s_inc_count(db_path, to_root_twin);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(refs_full, 1); /* entry.sh; both.sh and twin.sh are files under both contexts */
ASSERT_EQ(rc_other, 0);
ASSERT_EQ(other_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(refs_other, 1);
ASSERT_EQ(rc_pair, 0);
ASSERT_EQ(refs_pair, 2); /* svc/both.sh is the only candidate now */
ASSERT_EQ(svc_both, 1);
ASSERT_EQ(pair_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
ASSERT_EQ(rc_twin, 0);
ASSERT_EQ(refs_twin, 3); /* the root's twin.sh is the only candidate now */
ASSERT_EQ(root_twin, 1);
ASSERT_EQ(twin_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
PASS();
}
/* A source that is a file under one context and a directory under the other
* is no edge either: with the other context the instruction copies the
* directory. When the directory's last file goes, the file is the single
* candidate, and the edge comes from a Dockerfile that did not change: the
* planner declines to the full route. Both directions: the directory under
* the Dockerfile's own directory (svc/conf.sh/), and the directory under
* the root (tool.sh/). Deleting a file with no such partner stays a repair.
*
* The deletion of a file an image copies takes the full route already (the
* env join's rule), and an image copies a directory's files in the context
* its sources vote for. So each Dockerfile here has two more sources that
* put its image in the OTHER context than the directory's: svc's image is
* built from the root (a.sh, b.sh), app's from its own directory (c.sh,
* d.sh), and neither holds the file that goes. Shell scripts, so no rule
* for YAML sends the deletions to the full route either. */
TEST(incremental_docker_context_directory_deleted_takes_the_full_route) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_dkdir_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
write_temp_file(tmp, "svc/Dockerfile", "FROM alpine:3.20\n"
"COPY conf.sh /etc/conf.sh\n"
"COPY a.sh /a.sh\n"
"COPY b.sh /b.sh\n");
write_temp_file(tmp, "conf.sh", "#!/bin/sh\necho root\n");
write_temp_file(tmp, "a.sh", "#!/bin/sh\necho a\n");
write_temp_file(tmp, "b.sh", "#!/bin/sh\necho b\n");
write_temp_file(tmp, "svc/conf.sh/part.sh", "#!/bin/sh\necho part\n");
write_temp_file(tmp, "app/Dockerfile", "FROM alpine:3.20\n"
"COPY tool.sh /etc/tool.sh\n"
"COPY c.sh /c.sh\n"
"COPY d.sh /d.sh\n");
write_temp_file(tmp, "app/tool.sh", "#!/bin/sh\necho app\n");
write_temp_file(tmp, "app/c.sh", "#!/bin/sh\necho c\n");
write_temp_file(tmp, "app/d.sh", "#!/bin/sh\necho d\n");
write_temp_file(tmp, "tool.sh/part.sh", "#!/bin/sh\necho part\n");
write_temp_file(tmp, "other.sh", "#!/bin/sh\necho other\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/dkdir.db", tmp);
static const char refs[] = "SELECT COUNT(*) FROM edges WHERE type='REFERENCES_FILE' AND "
"json_extract(properties,'$.via')='copy'";
static const char to_root_conf[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='conf.sh'";
static const char to_app_tool[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='app/tool.sh'";
int rc_full = k8s_inc_index(tmp, db_path);
int refs_full = k8s_inc_count(db_path, refs);
int conf_full = k8s_inc_count(db_path, to_root_conf);
int tool_full = k8s_inc_count(db_path, to_app_tool);
char path[512];
snprintf(path, sizeof(path), "%s/other.sh", tmp);
(void)remove(path);
int rc_other = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t other_route = cbm_pipeline_incremental_test_last_route();
int refs_other = k8s_inc_count(db_path, refs);
snprintf(path, sizeof(path), "%s/svc/conf.sh/part.sh", tmp);
(void)remove(path);
int rc_svc = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t svc_route = cbm_pipeline_incremental_test_last_route();
int refs_svc = k8s_inc_count(db_path, refs);
int conf_svc = k8s_inc_count(db_path, to_root_conf);
snprintf(path, sizeof(path), "%s/tool.sh/part.sh", tmp);
(void)remove(path);
int rc_root = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t root_route = cbm_pipeline_incremental_test_last_route();
int refs_root = k8s_inc_count(db_path, refs);
int tool_root = k8s_inc_count(db_path, to_app_tool);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(refs_full, 4); /* a.sh, b.sh, app/c.sh, app/d.sh */
ASSERT_EQ(conf_full, 0); /* a directory under the Dockerfile's own directory */
ASSERT_EQ(tool_full, 0); /* a directory under the root */
ASSERT_EQ(rc_other, 0);
ASSERT_EQ(refs_other, 4);
ASSERT_EQ(other_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_svc, 0);
ASSERT_EQ(refs_svc, 5); /* the root's conf.sh is the only candidate now */
ASSERT_EQ(conf_svc, 1);
ASSERT_EQ(svc_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
ASSERT_EQ(rc_root, 0);
ASSERT_EQ(refs_root, 6); /* app/tool.sh is the only candidate now */
ASSERT_EQ(tool_root, 1);
ASSERT_EQ(root_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
PASS();
}
/* A COPY source's REFERENCES_FILE edge belongs to the Dockerfile. Editing the
* target keeps it: the Dockerfile did not change, and the edge is re-linked to
* the target's new node. Editing the Dockerfile redraws its edges from the new
* text, each once: a source it gains is drawn, a source it loses is gone. */
TEST(incremental_docker_copy_reference_follows_edits) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_dkedit_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
write_temp_file(tmp, "Dockerfile", "FROM alpine:3.20\n"
"COPY entry.sh /entry.sh\n");
write_temp_file(tmp, "entry.sh", "#!/bin/sh\necho entry\n");
write_temp_file(tmp, "tool.sh", "#!/bin/sh\necho tool\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/dkedit.db", tmp);
static const char refs[] = "SELECT COUNT(*) FROM edges WHERE type='REFERENCES_FILE' AND "
"json_extract(properties,'$.via')='copy'";
static const char to_entry[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='entry.sh'";
static const char to_tool[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='tool.sh'";
int rc_full = k8s_inc_index(tmp, db_path);
int refs_full = k8s_inc_count(db_path, refs);
write_temp_file(tmp, "entry.sh", "#!/bin/sh\necho entry\necho edited\n");
int rc_target = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t target_route = cbm_pipeline_incremental_test_last_route();
int refs_target = k8s_inc_count(db_path, refs);
int entry_target = k8s_inc_count(db_path, to_entry);
write_temp_file(tmp, "Dockerfile", "FROM alpine:3.20\n"
"COPY entry.sh /entry.sh\n"
"COPY tool.sh /tool.sh\n");
int rc_gain = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t gain_route = cbm_pipeline_incremental_test_last_route();
int refs_gain = k8s_inc_count(db_path, refs);
int entry_gain = k8s_inc_count(db_path, to_entry);
int tool_gain = k8s_inc_count(db_path, to_tool);
write_temp_file(tmp, "Dockerfile", "FROM alpine:3.20\n"
"COPY tool.sh /tool.sh\n");
int rc_lose = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t lose_route = cbm_pipeline_incremental_test_last_route();
int refs_lose = k8s_inc_count(db_path, refs);
int entry_lose = k8s_inc_count(db_path, to_entry);
int tool_lose = k8s_inc_count(db_path, to_tool);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(refs_full, 1);
ASSERT_EQ(rc_target, 0);
ASSERT_EQ(refs_target, 1);
ASSERT_EQ(entry_target, 1);
ASSERT_EQ(target_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_gain, 0);
ASSERT_EQ(refs_gain, 2);
ASSERT_EQ(entry_gain, 1);
ASSERT_EQ(tool_gain, 1);
ASSERT_EQ(gain_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_lose, 0);
ASSERT_EQ(refs_lose, 1);
ASSERT_EQ(entry_lose, 0);
ASSERT_EQ(tool_lose, 1);
ASSERT_EQ(lose_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
PASS();
}
/* A compose service's REFERENCES_FILE edge to a file it mounts follows the
* files, with the compose file untouched: editing the target keeps the edge,
* deleting the target removes it, bringing the target back draws it again.
* Editing the compose file redraws its services' edges from the new text. */
TEST(incremental_compose_file_reference_follows_edits) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_cmpref_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
write_temp_file(tmp, "compose.yaml", "services:\n"
" web:\n"
" image: nginx:1.27\n"
" volumes:\n"
" - ./nginx.conf:/etc/nginx/nginx.conf:ro\n");
write_temp_file(tmp, "nginx.conf", "worker_processes 1;\n");
write_temp_file(tmp, "extra.conf", "gzip on;\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/cmpref.db", tmp);
static const char refs[] = "SELECT COUNT(*) FROM edges WHERE type='REFERENCES_FILE' AND "
"json_extract(properties,'$.via')='volume'";
static const char to_nginx[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='nginx.conf'";
static const char to_extra[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='extra.conf'";
int rc_full = k8s_inc_index(tmp, db_path);
int refs_full = k8s_inc_count(db_path, refs);
write_temp_file(tmp, "nginx.conf", "worker_processes 2;\n");
int rc_edit = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t edit_route = cbm_pipeline_incremental_test_last_route();
int refs_edit = k8s_inc_count(db_path, refs);
int nginx_edit = k8s_inc_count(db_path, to_nginx);
char path[512];
snprintf(path, sizeof(path), "%s/nginx.conf", tmp);
(void)remove(path);
int rc_gone = k8s_inc_index(tmp, db_path);
int refs_gone = k8s_inc_count(db_path, refs);
write_temp_file(tmp, "nginx.conf", "worker_processes 3;\n");
int rc_back = k8s_inc_index(tmp, db_path);
int refs_back = k8s_inc_count(db_path, refs);
int nginx_back = k8s_inc_count(db_path, to_nginx);
write_temp_file(tmp, "compose.yaml", "services:\n"
" web:\n"
" image: nginx:1.27\n"
" volumes:\n"
" - ./extra.conf:/etc/nginx/extra.conf:ro\n");
int rc_swap = k8s_inc_index(tmp, db_path);
int refs_swap = k8s_inc_count(db_path, refs);
int nginx_swap = k8s_inc_count(db_path, to_nginx);
int extra_swap = k8s_inc_count(db_path, to_extra);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(refs_full, 1);
ASSERT_EQ(rc_edit, 0);
ASSERT_EQ(refs_edit, 1);
ASSERT_EQ(nginx_edit, 1);
ASSERT_EQ(edit_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_gone, 0);
ASSERT_EQ(refs_gone, 0);
ASSERT_EQ(rc_back, 0);
ASSERT_EQ(refs_back, 1);
ASSERT_EQ(nginx_back, 1);
ASSERT_EQ(rc_swap, 0);
ASSERT_EQ(refs_swap, 1);
ASSERT_EQ(nginx_swap, 0);
ASSERT_EQ(extra_swap, 1);
PASS();
}
/* One referring file `ref_path` (text `ref_text`) names one target file that
* does not exist yet. With the referring file untouched: the target appears
* (the edge is drawn), is edited (the edge stays), is deleted (the edge is
* gone). counts[0..4): the REFERENCES_FILE edges {via: `via`} after the first
* index and after each of the three steps. Returns 0, or -1 when a run fails. */
static int incremental_file_reference_steps(const char *ref_path, const char *ref_text,
const char *other_path, const char *other_text,
const char *target, const char *via, int counts[4]) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_fileref_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
return -1;
}
write_temp_file(tmp, ref_path, ref_text);
if (other_path) {
write_temp_file(tmp, other_path, other_text);
}
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/fileref.db", tmp);
char sql[512];
snprintf(sql, sizeof(sql),
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND json_extract(e.properties,'$.via')='%s' AND "
"t.file_path='%s'",
via, target);
int rc = k8s_inc_index(tmp, db_path);
counts[0] = k8s_inc_count(db_path, sql);
write_temp_file(tmp, target, "first = 1\n");
rc |= k8s_inc_index(tmp, db_path);
counts[1] = k8s_inc_count(db_path, sql);
write_temp_file(tmp, target, "first = 1\nsecond = 2\n");
rc |= k8s_inc_index(tmp, db_path);
counts[2] = k8s_inc_count(db_path, sql);
char path[512];
snprintf(path, sizeof(path), "%s/%s", tmp, target);
(void)remove(path);
rc |= k8s_inc_index(tmp, db_path);
counts[3] = k8s_inc_count(db_path, sql);
th_rmtree(tmp);
return rc == 0 ? 0 : -1;
}
/* A Dockerfile's COPY source that appears after the Dockerfile was indexed. */
TEST(incremental_docker_copy_reference_follows_its_file) {
int counts[4] = {-1, -1, -1, -1};
int rc = incremental_file_reference_steps("Dockerfile",
"FROM alpine:3.20\n"
"COPY late.properties /late.properties\n",
NULL, NULL, "late.properties", "copy", counts);
ASSERT_EQ(rc, 0);
ASSERT_EQ(counts[0], 0);
ASSERT_EQ(counts[1], 1);
ASSERT_EQ(counts[2], 1);
ASSERT_EQ(counts[3], 0);
PASS();
}
/* A compose bind mount whose host file appears after the compose file was
* indexed. */
TEST(incremental_compose_file_reference_follows_its_file) {
int counts[4] = {-1, -1, -1, -1};
int rc = incremental_file_reference_steps("compose.yaml",
"services:\n"
" web:\n"
" image: nginx:1.27\n"
" volumes:\n"
" - ./late.properties:/etc/late.properties\n",
NULL, NULL, "late.properties", "volume", counts);
ASSERT_EQ(rc, 0);
ASSERT_EQ(counts[0], 0);
ASSERT_EQ(counts[1], 1);
ASSERT_EQ(counts[2], 1);
ASSERT_EQ(counts[3], 0);
PASS();
}
/* A Terraform file function whose file appears after the module was indexed. */
TEST(incremental_terraform_file_reference_follows_its_file) {
int counts[4] = {-1, -1, -1, -1};
int rc = incremental_file_reference_steps(
"infra/main.tf",
"locals {\n"
" settings = file(\"${path.module}/late.properties\")\n"
"}\n",
NULL, NULL, "infra/late.properties", "file", counts);
ASSERT_EQ(rc, 0);
ASSERT_EQ(counts[0], 0);
ASSERT_EQ(counts[1], 1);
ASSERT_EQ(counts[2], 1);
ASSERT_EQ(counts[3], 0);
PASS();
}
/* A workflow's local action whose action file appears after the workflow was
* indexed. */
TEST(incremental_local_uses_reference_follows_its_file) {
int counts[4] = {-1, -1, -1, -1};
int rc = incremental_file_reference_steps(".github/workflows/ci.yml",
"name: ci\n"
"on: [push]\n"
"jobs:\n"
" build:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - uses: ./.github/actions/late\n",
NULL, NULL, ".github/actions/late/action.yml",
"uses", counts);
ASSERT_EQ(rc, 0);
ASSERT_EQ(counts[0], 0);
ASSERT_EQ(counts[1], 1);
ASSERT_EQ(counts[2], 1);
ASSERT_EQ(counts[3], 0);
PASS();
}
/* A local action is named by its directory, and the edge goes to the one
* action file it holds. With both spellings there is none; deleting one of
* the two makes the other the action, although no workflow changed. The
* repair reads no workflow again, so that deletion takes the full route. */
TEST(incremental_local_action_pair_deleted_takes_the_full_route) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_actpair_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
write_temp_file(tmp, ".github/workflows/ci.yml", "name: ci\n"
"on: [push]\n"
"jobs:\n"
" build:\n"
" runs-on: ubuntu-latest\n"
" steps:\n"
" - uses: ./.github/actions/both\n");
static const char action[] = "name: both\nruns:\n using: composite\n steps: []\n";
write_temp_file(tmp, ".github/actions/both/action.yml", action);
write_temp_file(tmp, ".github/actions/both/action.yaml", action);
write_temp_file(tmp, "hack/x.sh", "#!/bin/sh\necho x\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/actpair.db", tmp);
static const char uses[] = "SELECT COUNT(*) FROM edges WHERE type='REFERENCES_FILE' AND "
"json_extract(properties,'$.via')='uses'";
static const char to_yml[] =
"SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id=e.target_id WHERE "
"e.type='REFERENCES_FILE' AND t.file_path='.github/actions/both/action.yml'";
int rc_full = k8s_inc_index(tmp, db_path);
int uses_full = k8s_inc_count(db_path, uses);
write_temp_file(tmp, "hack/x.sh", "#!/bin/sh\necho x\necho edited\n");
int rc_other = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t other_route = cbm_pipeline_incremental_test_last_route();
int uses_other = k8s_inc_count(db_path, uses);
char path[512];
snprintf(path, sizeof(path), "%s/.github/actions/both/action.yaml", tmp);
(void)remove(path);
int rc_pair = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t pair_route = cbm_pipeline_incremental_test_last_route();
int uses_pair = k8s_inc_count(db_path, uses);
int yml_pair = k8s_inc_count(db_path, to_yml);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(uses_full, 0); /* two action files: which one GitHub reads is not ours to say */
ASSERT_EQ(rc_other, 0);
ASSERT_EQ(uses_other, 0);
ASSERT_EQ(other_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_pair, 0);
ASSERT_EQ(uses_pair, 1); /* action.yml is the action now */
ASSERT_EQ(yml_pair, 1);
ASSERT_EQ(pair_route, CBM_INCREMENTAL_ROUTE_FORCED_FULL);
PASS();
}
/* A kustomization's generator file that appears after the kustomization was
* indexed. */
TEST(incremental_kustomize_file_reference_follows_its_file) {
int counts[4] = {-1, -1, -1, -1};
int rc = incremental_file_reference_steps("deploy/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\n"
"kind: Kustomization\n"
"resources:\n"
" - deployment.yaml\n"
"configMapGenerator:\n"
" - name: app-config\n"
" files:\n"
" - late.properties\n",
"deploy/deployment.yaml",
"apiVersion: apps/v1\n"
"kind: Deployment\n"
"metadata:\n"
" name: app\n"
"spec:\n"
" replicas: 1\n",
"deploy/late.properties", "configMapGenerator",
counts);
ASSERT_EQ(rc, 0);
ASSERT_EQ(counts[0], 0);
ASSERT_EQ(counts[1], 1);
ASSERT_EQ(counts[2], 1);
ASSERT_EQ(counts[3], 0);
PASS();
}
/* A Make prerequisite's DEPENDS_ON edge lies inside its makefile. Editing
* another file keeps it: the makefile is not read again. Editing the makefile
* redraws its edges from the new text, each once: a prerequisite a rule gains
* is drawn, one it loses is gone. */
TEST(incremental_make_prerequisite_follows_edits) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_mkdep_XXXXXX");
if (!cbm_mkdtemp(tmp)) {
FAIL("tmpdir");
}
static const char rules[] = "build:\n"
"\techo build\n\n"
"test:\n"
"\techo test\n";
char text[512];
snprintf(text, sizeof(text), "all: build\n\techo all\n\n%s", rules);
write_temp_file(tmp, "Makefile", text);
write_temp_file(tmp, "hack/x.sh", "#!/bin/sh\necho x\n");
char db_path[512];
snprintf(db_path, sizeof(db_path), "%s/mkdep.db", tmp);
static const char deps[] = "SELECT COUNT(*) FROM edges WHERE type='DEPENDS_ON' AND "
"json_extract(properties,'$.via')='prerequisite'";
static const char to_build[] =
"SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
"t.id=e.target_id WHERE e.type='DEPENDS_ON' AND s.name='all' AND t.name='build'";
static const char to_test[] =
"SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id=e.source_id JOIN nodes t ON "
"t.id=e.target_id WHERE e.type='DEPENDS_ON' AND s.name='all' AND t.name='test'";
int rc_full = k8s_inc_index(tmp, db_path);
int deps_full = k8s_inc_count(db_path, deps);
int build_full = k8s_inc_count(db_path, to_build);
write_temp_file(tmp, "hack/x.sh", "#!/bin/sh\necho x\necho edited\n");
int rc_other = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t other_route = cbm_pipeline_incremental_test_last_route();
int deps_other = k8s_inc_count(db_path, deps);
int build_other = k8s_inc_count(db_path, to_build);
snprintf(text, sizeof(text), "all: build test\n\techo all\n\n%s", rules);
write_temp_file(tmp, "Makefile", text);
int rc_gain = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t gain_route = cbm_pipeline_incremental_test_last_route();
int deps_gain = k8s_inc_count(db_path, deps);
int build_gain = k8s_inc_count(db_path, to_build);
int test_gain = k8s_inc_count(db_path, to_test);
snprintf(text, sizeof(text), "all: test\n\techo all\n\n%s", rules);
write_temp_file(tmp, "Makefile", text);
int rc_lose = k8s_inc_index(tmp, db_path);
cbm_incremental_route_t lose_route = cbm_pipeline_incremental_test_last_route();
int deps_lose = k8s_inc_count(db_path, deps);
int build_lose = k8s_inc_count(db_path, to_build);
int test_lose = k8s_inc_count(db_path, to_test);
th_rmtree(tmp);
ASSERT_EQ(rc_full, 0);
ASSERT_EQ(deps_full, 1);
ASSERT_EQ(build_full, 1);
ASSERT_EQ(rc_other, 0);
ASSERT_EQ(deps_other, 1);
ASSERT_EQ(build_other, 1);
ASSERT_EQ(other_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_gain, 0);
ASSERT_EQ(deps_gain, 2);
ASSERT_EQ(build_gain, 1);
ASSERT_EQ(test_gain, 1);
ASSERT_EQ(gain_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
ASSERT_EQ(rc_lose, 0);
ASSERT_EQ(deps_lose, 1);
ASSERT_EQ(build_lose, 0);
ASSERT_EQ(test_lose, 1);
ASSERT_EQ(lose_route, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR);
PASS();
}
/* Deleting the only script requesting a URL leaves no Route behind -- a full
* index never makes one without an edge; the Route a kept script requests
* stays. `legacy`: through the full-load route, else closure repair. Returns
@@ -32948,7 +33539,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\":5,\"lang\":0,\"lsp\":[],\"reg\":[],\"py\":null}";
const char *non_python = "{\"v\":6,\"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]);
@@ -33079,24 +33670,24 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) {
* it re-extracts in full. */
const char *bad[] = {
"{\"v\":1,\"lsp\":[]}",
"{\"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,"
"{\"v\":6,\"lang\":1,\"lsp\":[]}",
"{\"v\":6,\"lang\":1,\"lsp\":[],\"py\":null}",
"{\"v\":6,\"lang\":1.0,\"lsp\":[],\"py\":null}",
"{\"v\":6,\"v\":6,\"lang\":0,\"lsp\":[],\"py\":null}",
"{\"v\":6,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":3,\"failure\":2,\"events\":[]}}",
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1,"
"{\"v\":6,\"lang\":1,\"lsp\":[],\"py\":{\"v\":1,\"lang\":1,"
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}",
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1,"
"{\"v\":6,\"lang\":1,\"lsp\":[],\"py\":{\"v\":99,\"lang\":1,"
"\"module\":\"p.m\",\"path\":\"m.py\",\"status\":2,\"failure\":0,\"events\":[]}}",
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
"{\"v\":6,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
"\"module\":\"p.m\",\"path\":\"m.py\\u0000suffix\",\"status\":2,"
"\"failure\":0,\"events\":[]}}",
"{\"v\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
"{\"v\":6,\"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\":5,\"lang\":1,\"lsp\":[],\"py\":{\"v\":2,\"lang\":1,"
"{\"v\":6,\"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\":[]}]}}",
@@ -33116,7 +33707,7 @@ TEST(pipeline_python_namespace_codec_rejects_non_authoritative_rows) {
cbm_arena_destroy(&arena);
}
const char *unknown =
"{\"v\":5,\"lang\":1,\"lsp\":[],\"reg\":[],\"py\":{\"v\":2,\"lang\":1,"
"{\"v\":6,\"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\":[]}]}}";
@@ -33144,7 +33735,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\":5,\"lang\":0,\"py\":null,\"lsp\":[");
size_t used = (size_t)snprintf(json, capacity, "{\"v\":6,\"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\","
@@ -33234,10 +33825,10 @@ TEST(pipeline_lsp_surface_persisted_and_body_edit_invariant) {
ASSERT_TRUE(row_a->surface_sha && row_a->surface_sha[0]);
if (round == 0) {
snprintf(sha_baseline, sizeof(sha_baseline), "%s", row_a->surface_sha);
/* The row is the versioned codec envelope (codec version 4) with
/* The row is the versioned codec envelope (codec version 6) with
* the def present. */
snprintf(json_probe, sizeof(json_probe), "%.20s", row_a->defs_json);
ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":5") != NULL);
ASSERT_TRUE(strstr(row_a->defs_json, "\"v\":6") != NULL);
ASSERT_TRUE(strstr(row_a->defs_json, "surface_probe") != NULL);
} else if (round == 1) {
ASSERT_STR_EQ(row_a->surface_sha, sha_baseline);
@@ -38058,6 +38649,17 @@ SUITE(pipeline_semantic_manifest_repro) {
RUN_TEST(pipeline_ansible_under_deploy_sequential_pass);
RUN_TEST(incremental_deleted_spawner_drops_its_process);
RUN_TEST(incremental_deleted_caller_drops_its_route);
RUN_TEST(incremental_docker_context_pair_deleted_takes_the_full_route);
RUN_TEST(incremental_docker_context_directory_deleted_takes_the_full_route);
RUN_TEST(incremental_docker_copy_reference_follows_edits);
RUN_TEST(incremental_compose_file_reference_follows_edits);
RUN_TEST(incremental_docker_copy_reference_follows_its_file);
RUN_TEST(incremental_compose_file_reference_follows_its_file);
RUN_TEST(incremental_terraform_file_reference_follows_its_file);
RUN_TEST(incremental_local_uses_reference_follows_its_file);
RUN_TEST(incremental_local_action_pair_deleted_takes_the_full_route);
RUN_TEST(incremental_kustomize_file_reference_follows_its_file);
RUN_TEST(incremental_make_prerequisite_follows_edits);
RUN_TEST(incremental_script_request_to_compose_service_keeps_host);
RUN_TEST(incremental_deleted_dockerfile_drops_its_image);
RUN_TEST(incremental_dockerfile_edit_keeps_build_edges);
+593
View File
@@ -0,0 +1,593 @@
/*
* test_scope_closure.c -- the unordered closure and lookup of the shared
* cross-file layer (src/pipeline/scope_closure.h), on scopes built by hand.
*/
#include "test_framework.h"
#include "../src/pipeline/scope_closure.h"
#include <stdio.h>
#include <string.h>
static const cbm_closure_lang_t ROW = {.lang = CBM_LANG_PROTOBUF};
static const cbm_closure_lang_t ROW_QUAL = {.lang = CBM_LANG_PROTOBUF, .qualified_refs = true};
static const cbm_closure_lang_t ROW_PKG = {.lang = CBM_LANG_GO, .package_visible = true};
static const cbm_closure_lang_t ROW_PRELUDE = {.lang = CBM_LANG_SCALA, .prelude_external = true};
static const cbm_closure_lang_t ROW_STRICT = {.lang = CBM_LANG_SCALA, .ambiguity_is_error = true};
/* `written`: the reference as written, NULL for the bare name. No memo: each
* answer computed afresh (sc_ask_memo shares one). */
static cbm_closure_answer_t sc_ask(cbm_closure_t *s, int file, const char *name,
const char *written, uint8_t flags) {
cbm_closure_ref_t ref = {.name = name, .written = written, .flags = flags};
return cbm_closure_lookup(s, NULL, file, &ref);
}
static cbm_closure_answer_t sc_ask_memo(cbm_closure_t *s, cbm_closure_memo_t *m, int file,
const char *name, const char *written) {
cbm_closure_ref_t ref = {.name = name, .written = written};
return cbm_closure_lookup(s, m, file, &ref);
}
/* user includes lib, which defines T: the one T, proven */
TEST(scope_closure_one_definition_through_an_include_is_proven) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "u");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW, "l");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "l.T", "p.lib.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t a = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(a.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(a.qn, "p.lib.T");
ASSERT_EQ(a.file, lib);
ASSERT_EQ(a.visible, 1);
ASSERT_TRUE(a.complete);
ASSERT_EQ(a.via, CBM_CLOSURE_VIA_INCLUDE);
/* a name nobody defines, closure complete: proven absent (counted only) */
ASSERT_EQ(sc_ask(s, user, "Nope", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
/* bound locally: no answer */
cbm_closure_answer_t local = sc_ask(s, user, "T", NULL, CBM_CLOSURE_REF_LOCAL);
ASSERT_EQ(local.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(local.why, CBM_CLOSURE_WHY_LOCAL);
cbm_closure_free(s);
PASS();
}
/* a plain include is not passed on; a re-exporting one is, along a chain;
* an import cycle (public or plain) is a file protoc refuses ("File
* recursively imports itself"): nothing through it or in it is proven */
TEST(scope_closure_reexport_chain_and_cycle) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int mid = cbm_closure_add_file(s, "mid.proto", &ROW, "");
int deep = cbm_closure_add_file(s, "deep.proto", &ROW, "");
int user2 = cbm_closure_add_file(s, "user2.proto", &ROW, "");
int a = cbm_closure_add_file(s, "a.proto", &ROW, "");
int b = cbm_closure_add_file(s, "b.proto", &ROW, "");
int pub = cbm_closure_add_file(s, "pub.proto", &ROW, "");
int x = cbm_closure_add_file(s, "x.proto", &ROW, "");
int y = cbm_closure_add_file(s, "y.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, deep, "D", NULL, "q.D", false));
ASSERT_TRUE(cbm_closure_add_def(s, b, "B", NULL, "q.B", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "Y", NULL, "q.Y", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, mid, false));
ASSERT_TRUE(cbm_closure_add_include(s, mid, deep, false)); /* plain: not passed on */
ASSERT_TRUE(cbm_closure_add_include(s, user, pub, false));
ASSERT_TRUE(cbm_closure_add_include(s, pub, deep, true)); /* public: passed on */
ASSERT_TRUE(cbm_closure_add_include(s, user2, a, false));
ASSERT_TRUE(cbm_closure_add_include(s, a, b, true)); /* public, and back: a cycle */
ASSERT_TRUE(cbm_closure_add_include(s, b, a, true));
ASSERT_TRUE(cbm_closure_add_include(s, x, y, false)); /* plain, and back: a cycle too */
ASSERT_TRUE(cbm_closure_add_include(s, y, x, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
ASSERT_EQ(sc_ask(s, mid, "D", NULL, 0).verdict, CBM_CLOSURE_PROVEN);
cbm_closure_answer_t chain = sc_ask(s, user, "D", NULL, 0);
ASSERT_EQ(chain.verdict, CBM_CLOSURE_PROVEN); /* through pub's re-export, not mid's */
ASSERT_STR_EQ(chain.qn, "q.D");
cbm_closure_t *s2 = cbm_closure_new(); /* the plain include alone */
int u2 = cbm_closure_add_file(s2, "user.proto", &ROW, "");
int m2 = cbm_closure_add_file(s2, "mid.proto", &ROW, "");
int d2 = cbm_closure_add_file(s2, "deep.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s2, d2, "D", NULL, "q.D", false));
ASSERT_TRUE(cbm_closure_add_include(s2, u2, m2, false));
ASSERT_TRUE(cbm_closure_add_include(s2, m2, d2, false));
ASSERT_EQ(cbm_closure_seal(s2), 0);
ASSERT_EQ(sc_ask(s2, u2, "D", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
cbm_closure_free(s2);
/* the cycles: possible at most, opaque */
cbm_closure_answer_t through = sc_ask(s, user2, "B", NULL, 0);
ASSERT_EQ(through.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(through.qn, "q.B");
ASSERT_EQ(through.why & CBM_CLOSURE_WHY_OPAQUE, CBM_CLOSURE_WHY_OPAQUE);
ASSERT_EQ(sc_ask(s, a, "B", NULL, 0).verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(sc_ask(s, x, "Y", NULL, 0).verdict, CBM_CLOSURE_POSSIBLE);
cbm_closure_free(s);
PASS();
}
/* incomplete closures: an unresolved include, an opaque file on the way */
TEST(scope_closure_incomplete_is_possible_or_no_answer) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW, "");
int dark = cbm_closure_add_file(s, "dark.proto", &ROW, "");
int user2 = cbm_closure_add_file(s, "user2.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", NULL, "q.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, -1, false)); /* names no repository file */
ASSERT_TRUE(cbm_closure_add_def(s, dark, "U", NULL, "q.U", false));
ASSERT_TRUE(cbm_closure_add_opaque(s, dark));
ASSERT_TRUE(cbm_closure_add_include(s, user2, dark, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t t = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(t.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(t.qn, "q.T");
ASSERT_FALSE(t.complete);
ASSERT_EQ(t.why & CBM_CLOSURE_WHY_UNRESOLVED, CBM_CLOSURE_WHY_UNRESOLVED);
ASSERT_EQ(sc_ask(s, user, "Gone", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER);
cbm_closure_answer_t u = sc_ask(s, user2, "U", NULL, 0);
ASSERT_EQ(u.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(u.why & CBM_CLOSURE_WHY_OPAQUE, CBM_CLOSURE_WHY_OPAQUE);
cbm_closure_free(s);
PASS();
}
/* two visible definitions: no answer; a conditional one: possible; one
* without a node: no answer */
TEST(scope_closure_ambiguous_conditional_and_nodeless) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW, "");
int x = cbm_closure_add_file(s, "x.proto", &ROW, "");
int y = cbm_closure_add_file(s, "y.proto", &ROW, "");
ASSERT_TRUE(cbm_closure_add_def(s, x, "T", NULL, "q.x.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "T", NULL, "q.y.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, x, "C", NULL, "q.x.C", true));
ASSERT_TRUE(cbm_closure_add_def(s, y, "N", NULL, NULL, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, x, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, y, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t two = sc_ask(s, user, "T", NULL, 0);
ASSERT_EQ(two.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(two.visible, 2);
ASSERT_EQ(two.why & CBM_CLOSURE_WHY_AMBIGUOUS, CBM_CLOSURE_WHY_AMBIGUOUS);
cbm_closure_answer_t cond = sc_ask(s, user, "C", NULL, 0);
ASSERT_EQ(cond.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(cond.why & CBM_CLOSURE_WHY_CONDITIONAL, CBM_CLOSURE_WHY_CONDITIONAL);
cbm_closure_answer_t none = sc_ask(s, user, "N", NULL, 0);
ASSERT_EQ(none.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(none.why & CBM_CLOSURE_WHY_NO_NODE, CBM_CLOSURE_WHY_NO_NODE);
cbm_closure_free(s);
PASS();
}
/* protoc's scope walk: the innermost scope around the site in which the FIRST
* component names a symbol decides, the rest must be there, no backtracking;
* the enclosing message is not known, so a name a message of the file holds
* is at most possible (protoc takes a bare nested name only inside it) */
TEST(scope_closure_qualified_reference) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "a/b/user.proto", &ROW_QUAL, "a.b");
int common = cbm_closure_add_file(s, "common.proto", &ROW_QUAL, "common");
int y = cbm_closure_add_file(s, "y.proto", &ROW_QUAL, "y");
int near = cbm_closure_add_file(s, "a/n.proto", &ROW_QUAL, "a.n");
int xc = cbm_closure_add_file(s, "x/y.proto", &ROW_QUAL, "x.common");
ASSERT_TRUE(
cbm_closure_add_def(s, common, "Status", "common.Status", "q.common.Status", false));
ASSERT_TRUE(cbm_closure_add_def(s, y, "Status", "y.Status", "q.y.Status", false));
ASSERT_TRUE(cbm_closure_add_def(s, near, "Kind", "a.n.Kind", "q.a.n.Kind", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, common, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, y, false));
ASSERT_TRUE(cbm_closure_add_include(s, user, near, false));
ASSERT_TRUE(cbm_closure_add_include(s, xc, common, false));
/* the user's own messages, top-level and nested */
ASSERT_TRUE(cbm_closure_add_def(s, user, "Outer", "a.b.Outer", "q.Outer", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Inner", "a.b.Outer.Inner", "q.Outer.Inner", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Mid", "a.b.Outer.Mid", "q.Mid", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Deep", "a.b.Outer.Mid.Deep", "q.Deep", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "One", "a.b.One", "q.One", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Two", "a.b.Two", "q.Two", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Twin", "a.b.One.Twin", "q.One.Twin", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "Twin", "a.b.Two.Twin", "q.Two.Twin", false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t c = sc_ask(s, user, "Status", "common.Status", 0);
ASSERT_EQ(c.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(c.qn, "q.common.Status");
ASSERT_STR_EQ(sc_ask(s, user, "Status", ".y.Status", 0).qn, "q.y.Status");
/* bare `Status` inside package a.b reads a.b.Status, a.Status, Status:
* neither common.Status nor y.Status */
ASSERT_EQ(sc_ask(s, user, "Status", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
/* `n.Kind` inside package a.b: `n` first names the package a.n */
ASSERT_STR_EQ(sc_ask(s, user, "Kind", "n.Kind", 0).qn, "q.a.n.Kind");
/* `common.Status` inside package x.common: `common` first names x.common,
* so protoc reads x.common.Status, which is not defined: no answer */
cbm_closure_answer_t pre = sc_ask(s, xc, "Status", "common.Status", 0);
ASSERT_TRUE(pre.verdict != CBM_CLOSURE_PROVEN && pre.verdict != CBM_CLOSURE_POSSIBLE);
/* a message of the file holds the name: only inside it does protoc take
* it, and the site's message is unknown: possible */
cbm_closure_answer_t inner = sc_ask(s, user, "Inner", NULL, 0);
ASSERT_EQ(inner.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(inner.qn, "q.Outer.Inner");
ASSERT_EQ(inner.why & CBM_CLOSURE_WHY_SCOPE, CBM_CLOSURE_WHY_SCOPE);
cbm_closure_answer_t deep = sc_ask(s, user, "Deep", "Mid.Deep", 0);
ASSERT_EQ(deep.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_STR_EQ(deep.qn, "q.Deep");
/* from the root, or through a top-level message: proven */
cbm_closure_answer_t lead = sc_ask(s, user, "Inner", ".a.b.Outer.Inner", 0);
ASSERT_EQ(lead.verdict, CBM_CLOSURE_PROVEN);
ASSERT_STR_EQ(sc_ask(s, user, "Inner", "Outer.Inner", 0).qn, "q.Outer.Inner");
ASSERT_EQ(sc_ask(s, user, "Inner", "Outer.Inner", 0).verdict, CBM_CLOSURE_PROVEN);
/* `Twin` from inside One is One.Twin, from inside Two is Two.Twin: the
* enclosing message is not known here, so no answer */
cbm_closure_answer_t twin = sc_ask(s, user, "Twin", NULL, 0);
ASSERT_EQ(twin.verdict, CBM_CLOSURE_NO_ANSWER);
ASSERT_EQ(twin.why & CBM_CLOSURE_WHY_AMBIGUOUS, CBM_CLOSURE_WHY_AMBIGUOUS);
ASSERT_STR_EQ(sc_ask(s, user, "Twin", "Two.Twin", 0).qn, "q.Two.Twin");
cbm_closure_free(s);
PASS();
}
/* a file whose package is unknown (no fact names it) reads every scope as
* possibly around its sites: more candidates, never fewer */
TEST(scope_closure_unknown_package_reads_every_scope) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW_QUAL, NULL);
int lib = cbm_closure_add_file(s, "lib.proto", &ROW_QUAL, "l");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "l.T", "q.l.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, user, "T", "x.M.T", "q.x.T", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, lib, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
ASSERT_EQ(sc_ask(s, user, "T", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER); /* l.T and x.M.T */
ASSERT_STR_EQ(sc_ask(s, user, "T", "l.T", 0).qn, "q.l.T");
cbm_closure_free(s);
PASS();
}
/* Answers do not depend on the memo: none, a fresh one, or one filled by
* other lookups (in any order) give the same. */
TEST(scope_closure_answers_do_not_depend_on_the_memo) {
cbm_closure_t *s = cbm_closure_new();
int user = cbm_closure_add_file(s, "user.proto", &ROW_QUAL, "u");
int pub = cbm_closure_add_file(s, "pub.proto", &ROW_QUAL, "u");
int lib = cbm_closure_add_file(s, "lib.proto", &ROW_QUAL, "u");
int far = cbm_closure_add_file(s, "far.proto", &ROW_QUAL, "f");
ASSERT_TRUE(cbm_closure_add_def(s, lib, "T", "u.T", "q.u.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, far, "T", "f.T", "q.f.T", false));
ASSERT_TRUE(cbm_closure_add_def(s, far, "V", "f.V", "q.f.V", false));
ASSERT_TRUE(cbm_closure_add_include(s, user, pub, false));
ASSERT_TRUE(cbm_closure_add_include(s, pub, lib, true));
ASSERT_TRUE(cbm_closure_add_include(s, pub, far, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
const struct {
int file;
const char *name;
const char *written;
} asks[] = {{user, "T", NULL}, {pub, "T", NULL}, {user, "V", NULL},
{pub, "V", "f.V"}, {far, "T", NULL}, {user, "T", "u.T"},
{lib, "T", ".u.T"}, {pub, "T", ".f.T"}, {user, "Nope", NULL}};
enum { N_ASKS = sizeof(asks) / sizeof(asks[0]) };
cbm_closure_answer_t fresh[N_ASKS];
for (int i = 0; i < N_ASKS; i++) {
fresh[i] = sc_ask(s, asks[i].file, asks[i].name, asks[i].written, 0);
}
for (int round = 0; round < 2; round++) {
cbm_closure_memo_t *m = cbm_closure_memo_new();
ASSERT_NOT_NULL(m);
for (int k = 0; k < N_ASKS; k++) {
int i = round == 0 ? k : N_ASKS - 1 - k; /* forward, then backward */
cbm_closure_answer_t a = sc_ask_memo(s, m, asks[i].file, asks[i].name, asks[i].written);
ASSERT_EQ(a.verdict, fresh[i].verdict);
ASSERT_EQ(a.visible, fresh[i].visible);
ASSERT_EQ(a.why, fresh[i].why);
ASSERT_EQ(a.file, fresh[i].file);
ASSERT_TRUE((a.qn == NULL) == (fresh[i].qn == NULL));
if (a.qn) {
ASSERT_STR_EQ(a.qn, fresh[i].qn);
}
}
cbm_closure_memo_free(m);
}
ASSERT_STR_EQ(fresh[0].qn, "q.u.T"); /* through pub's re-export */
ASSERT_STR_EQ(fresh[1].qn, "q.u.T"); /* f.T is no bare T in package u */
ASSERT_EQ(fresh[2].verdict, CBM_CLOSURE_PROVEN_ABSENT); /* far is not passed on */
ASSERT_STR_EQ(fresh[3].qn, "q.f.V");
ASSERT_EQ(cbm_closure_file(s, "pub.proto"), pub);
ASSERT_EQ(cbm_closure_file(s, "nope.proto"), -1);
ASSERT_EQ(cbm_closure_add_file(s, "late.proto", &ROW_QUAL, ""), -1); /* sealed */
cbm_closure_free(s);
PASS();
}
/* rows: package mates, a prelude, ambiguity as an error */
TEST(scope_closure_rows) {
cbm_closure_t *s = cbm_closure_new();
int p1 = cbm_closure_add_file(s, "pkg/a.go", &ROW_PKG, "pkg");
int p2 = cbm_closure_add_file(s, "pkg/b.go", &ROW_PKG, "pkg");
int other = cbm_closure_add_file(s, "other/c.go", &ROW_PKG, "other");
ASSERT_TRUE(cbm_closure_add_def(s, p2, "F", NULL, "q.pkg.F", false));
int pre = cbm_closure_add_file(s, "s/a.scala", &ROW_PRELUDE, "s");
int pre_lib = cbm_closure_add_file(s, "s/l.scala", &ROW_PRELUDE, "s");
ASSERT_TRUE(cbm_closure_add_def(s, pre_lib, "G", NULL, "q.s.G", false));
ASSERT_TRUE(cbm_closure_add_include(s, pre, pre_lib, false));
int strict = cbm_closure_add_file(s, "t/a.scala", &ROW_STRICT, "t");
int strict_lib = cbm_closure_add_file(s, "t/l.scala", &ROW_STRICT, "t");
ASSERT_TRUE(cbm_closure_add_def(s, strict_lib, "H", NULL, "q.t.H", false));
ASSERT_TRUE(cbm_closure_add_include(s, strict, strict_lib, false));
ASSERT_TRUE(cbm_closure_add_include(s, strict, -1, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
cbm_closure_answer_t mate = sc_ask(s, p1, "F", NULL, 0);
ASSERT_EQ(mate.verdict, CBM_CLOSURE_PROVEN);
ASSERT_EQ(mate.via, CBM_CLOSURE_VIA_PACKAGE);
ASSERT_EQ(sc_ask(s, other, "F", NULL, 0).verdict, CBM_CLOSURE_PROVEN_ABSENT);
cbm_closure_answer_t prelude = sc_ask(s, pre, "G", NULL, 0);
ASSERT_EQ(prelude.verdict, CBM_CLOSURE_POSSIBLE);
ASSERT_EQ(prelude.why & CBM_CLOSURE_WHY_PRELUDE, CBM_CLOSURE_WHY_PRELUDE);
ASSERT_EQ(sc_ask(s, pre, "Absent", NULL, 0).verdict, CBM_CLOSURE_NO_ANSWER);
cbm_closure_answer_t one = sc_ask(s, strict, "H", NULL, 0);
ASSERT_EQ(one.verdict, CBM_CLOSURE_PROVEN);
ASSERT_FALSE(one.complete);
cbm_closure_free(s);
PASS();
}
/* Counted work of a header-heavy shape at n: (fan) one file defining N
* included by n files, each asking N and one undefined name; (chain) n files
* each re-exporting the next, the last defining N, each asking N. `lookups`:
* the lookups' work (one memo for all, as one resolver thread), else the
* build's (files, definitions, includes, components). */
static uint64_t sc_work(int n, bool chain, bool lookups) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
int shared = cbm_closure_add_file(s, "shared.proto", &ROW, "");
int first = -1;
for (int i = 0; i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
int f = cbm_closure_add_file(s, rel, &ROW, "");
first = first < 0 ? f : first;
}
for (int i = 0; i < n; i++) { /* every file exists before an include names it */
int f = first + i;
bool ok = chain ? cbm_closure_add_include(s, f, i + 1 < n ? f + 1 : shared, true)
: cbm_closure_add_include(s, f, shared, false);
if (!ok) {
cbm_closure_free(s);
return 0;
}
}
if (!cbm_closure_add_def(s, shared, "N", NULL, "q.N", false) || cbm_closure_seal(s) != 0) {
cbm_closure_free(s);
return 0;
}
/* one memo, as one resolver thread has */
cbm_closure_memo_t *m = cbm_closure_memo_new();
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
right = sc_ask_memo(s, m, first + i, "N", NULL).verdict == CBM_CLOSURE_PROVEN &&
sc_ask_memo(s, m, first + i, "Unknown", NULL).verdict == CBM_CLOSURE_PROVEN_ABSENT;
}
uint64_t w = lookups ? cbm_closure_memo_work(m) : cbm_closure_work(s);
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
/* Counted lookup work of review 1's three shapes at n (one memo, as one
* resolver thread): (0, chain) f_i `import public` f_{i+1}, each defines T_i,
* a top file includes f_0 and asks every T_i; (1, fan) a top file includes n
* files and asks each one's T_i; (2, hub) n files `package p_i; Status`, a hub
* re-exports all, n users each include the hub and ask p_i.Status. */
static uint64_t sc_shape_work(int n, int shape) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
char name[32];
char full[32];
char pkg[32];
int top = cbm_closure_add_file(s, "top.proto", &ROW_QUAL, "u");
int hub = cbm_closure_add_file(s, "hub.proto", &ROW_QUAL, "h");
int first = -1;
bool ok = true;
for (int i = 0; ok && i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
snprintf(pkg, sizeof(pkg), "p%d", i);
int f = cbm_closure_add_file(s, rel, &ROW_QUAL, shape == 2 ? pkg : "u");
first = first < 0 ? f : first;
if (shape == 2) {
snprintf(rel, sizeof(rel), "user%d.proto", i);
ok = cbm_closure_add_file(s, rel, &ROW_QUAL, "u") >= 0;
}
}
for (int i = 0; ok && i < n; i++) {
int f = first + i * (shape == 2 ? 2 : 1);
snprintf(name, sizeof(name), "T%d", i);
snprintf(full, sizeof(full), shape == 2 ? "p%d.Status" : "u.T%d", i);
ok = cbm_closure_add_def(s, f, shape == 2 ? "Status" : name, full, full, false);
if (shape == 0) {
ok = ok && (i + 1 >= n || cbm_closure_add_include(s, f, f + 1, true));
} else if (shape == 1) {
ok = ok && cbm_closure_add_include(s, top, f, false);
} else {
ok = ok && cbm_closure_add_include(s, hub, f, true) &&
cbm_closure_add_include(s, f + 1, hub, false);
}
}
if (shape == 0) {
ok = ok && cbm_closure_add_include(s, top, first, false);
}
ok = ok && cbm_closure_seal(s) == 0;
cbm_closure_memo_t *m = ok ? cbm_closure_memo_new() : NULL;
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
snprintf(name, sizeof(name), "T%d", i);
snprintf(full, sizeof(full), "p%d.Status", i);
cbm_closure_answer_t a = shape == 2 ? sc_ask_memo(s, m, first + i * 2 + 1, "Status", full)
: sc_ask_memo(s, m, top, name, NULL);
right = a.verdict == CBM_CLOSURE_PROVEN;
}
uint64_t w = m ? cbm_closure_memo_work(m) : 0;
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
TEST(scope_closure_review_shapes_grow_linearly) {
static const char *const names[] = {"chain", "fan", "hub"};
for (int shape = 0; shape < 3; shape++) {
uint64_t w1 = sc_shape_work(100, shape);
uint64_t w4 = sc_shape_work(400, shape);
uint64_t w16 = sc_shape_work(1600, shape);
printf("\n %s lookups: %llu / %llu / %llu at 1x / 4x / 16x", names[shape],
(unsigned long long)w1, (unsigned long long)w4, (unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
printf("\n");
PASS();
}
/* Counted lookup work of review 3's R2 shape at n (one memo): n files
* `package p_i; message M { enum Type {..} Type t = 1; }`, each asking its
* own Type. `scoped`: the reference carries its enclosing message (proven
* p_i.M.Type); otherwise the scope is unknown and the file's own nested Type
* may decide (possible). */
static uint64_t sc_nested_work(int n, bool scoped) {
cbm_closure_t *s = cbm_closure_new();
if (!s) {
return 0;
}
char rel[32];
char pkg[32];
char msg[32];
char full[48];
int first = -1;
bool ok = true;
for (int i = 0; ok && i < n; i++) {
snprintf(rel, sizeof(rel), "f%d.proto", i);
snprintf(pkg, sizeof(pkg), "p%d", i);
snprintf(msg, sizeof(msg), "p%d.M", i);
snprintf(full, sizeof(full), "p%d.M.Type", i);
int f = cbm_closure_add_file(s, rel, &ROW_QUAL, pkg);
first = first < 0 ? f : first;
ok = f >= 0 && cbm_closure_add_def(s, f, "M", msg, msg, false) &&
cbm_closure_add_def(s, f, "Type", full, full, false);
}
ok = ok && cbm_closure_seal(s) == 0;
cbm_closure_memo_t *m = ok ? cbm_closure_memo_new() : NULL;
bool right = m != NULL;
for (int i = 0; right && i < n; i++) {
snprintf(msg, sizeof(msg), "p%d.M", i);
snprintf(full, sizeof(full), "p%d.M.Type", i);
cbm_closure_ref_t ref = {.name = "Type", .scope = scoped ? msg : NULL};
cbm_closure_answer_t a = cbm_closure_lookup(s, m, first + i, &ref);
right = a.verdict == (scoped ? CBM_CLOSURE_PROVEN : CBM_CLOSURE_POSSIBLE) && a.qn &&
strcmp(a.qn, full) == 0;
}
uint64_t w = m ? cbm_closure_memo_work(m) : 0;
cbm_closure_memo_free(m);
cbm_closure_free(s);
return right ? w : 0;
}
TEST(scope_closure_nested_name_in_every_file_grows_linearly) {
for (int scoped = 0; scoped < 2; scoped++) {
uint64_t w1 = sc_nested_work(250, scoped);
uint64_t w4 = sc_nested_work(1000, scoped);
uint64_t w16 = sc_nested_work(4000, scoped);
printf("\n nested %s: %llu / %llu / %llu at 250 / 1,000 / 4,000", scoped ? "scoped" : "unscoped",
(unsigned long long)w1, (unsigned long long)w4, (unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
printf("\n");
PASS();
}
/* protoc on review 3's fx4/scope: `package p; import "t.proto"; message A {
* enum Type {..} Type t = 1; } message B { Type t = 1; }` with t.proto's
* `package p; enum Type {..}` gives A's field .p.A.Type and B's .p.Type. The
* reference's own scope decides innermost first; an outer Type is never the
* answer where an inner one is around the site. */
TEST(scope_closure_reference_scope_decides_innermost_first) {
cbm_closure_t *s = cbm_closure_new();
int a = cbm_closure_add_file(s, "a.proto", &ROW_QUAL, "p");
int t = cbm_closure_add_file(s, "t.proto", &ROW_QUAL, "p");
ASSERT_TRUE(cbm_closure_add_def(s, t, "Type", "p.Type", "t.Type", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "A", "p.A", "a.A", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "Type", "p.A.Type", "a.A.Type", false));
ASSERT_TRUE(cbm_closure_add_def(s, a, "B", "p.B", "a.B", false));
ASSERT_TRUE(cbm_closure_add_include(s, a, t, false));
ASSERT_EQ(cbm_closure_seal(s), 0);
static const struct {
const char *scope;
const char *written;
const char *want; /* the proven node */
} cases[] = {
{"p.A", NULL, "a.A.Type"}, /* A's field: the enclosing message first */
{"p.B", NULL, "t.Type"}, /* B's field: B holds no Type, the package's */
{"p", NULL, "t.Type"}, /* outside any message */
{"p.B", "A.Type", "a.A.Type"}, /* qualified from B: A decides at p */
{"", "p.Type", "t.Type"}, /* from the root */
};
for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {
cbm_closure_ref_t ref = {.name = "Type", .written = cases[i].written, .scope = cases[i].scope};
cbm_closure_answer_t x = cbm_closure_lookup(s, NULL, a, &ref);
if (x.verdict != CBM_CLOSURE_PROVEN || !x.qn || strcmp(x.qn, cases[i].want) != 0) {
printf("\n scope %s written %s: verdict %d qn %s, want proven %s\n", cases[i].scope,
cases[i].written ? cases[i].written : "-", (int)x.verdict, x.qn ? x.qn : "-",
cases[i].want);
cbm_closure_free(s);
FAIL("the reference's own scope did not decide");
}
}
/* `B.Type` from A: B is found at p and holds no Type, no backtracking */
cbm_closure_ref_t miss = {.name = "Type", .written = "B.Type", .scope = "p.A"};
ASSERT_NEQ(cbm_closure_lookup(s, NULL, a, &miss).verdict, CBM_CLOSURE_PROVEN);
cbm_closure_free(s);
PASS();
}
TEST(scope_closure_work_grows_linearly) {
for (int chain = 0; chain < 2; chain++) {
for (int lookups = 0; lookups < 2; lookups++) { /* the build, then the lookups */
uint64_t w1 = sc_work(100, chain, lookups);
uint64_t w4 = sc_work(400, chain, lookups);
uint64_t w16 = sc_work(1600, chain, lookups);
printf("\n %s %s: %llu / %llu / %llu at 1x / 4x / 16x", chain ? "chain" : "fan",
lookups ? "lookups" : "build", (unsigned long long)w1, (unsigned long long)w4,
(unsigned long long)w16);
ASSERT_GT(w1, 0);
ASSERT_GT(w4, 0);
ASSERT_GT(w16, 0);
/* at most 4.5 times the work per 4 times the files */
ASSERT_TRUE(w4 * 2 <= w1 * 9);
ASSERT_TRUE(w16 * 2 <= w4 * 9);
}
}
printf("\n");
PASS();
}
SUITE(scope_closure) {
RUN_TEST(scope_closure_review_shapes_grow_linearly);
RUN_TEST(scope_closure_nested_name_in_every_file_grows_linearly);
RUN_TEST(scope_closure_reference_scope_decides_innermost_first);
RUN_TEST(scope_closure_one_definition_through_an_include_is_proven);
RUN_TEST(scope_closure_reexport_chain_and_cycle);
RUN_TEST(scope_closure_incomplete_is_possible_or_no_answer);
RUN_TEST(scope_closure_ambiguous_conditional_and_nodeless);
RUN_TEST(scope_closure_qualified_reference);
RUN_TEST(scope_closure_unknown_package_reads_every_scope);
RUN_TEST(scope_closure_answers_do_not_depend_on_the_memo);
RUN_TEST(scope_closure_rows);
RUN_TEST(scope_closure_work_grows_linearly);
}
+684 -1
View File
@@ -6,12 +6,25 @@
* of it gets NO_ANSWER (main's name chain decides, unchanged) and the end
* step draws no edge. Go has an engine and never gets a row of this layer,
* so these hold as rows for other languages arrive.
*
* Protobuf has a row: a type reference names the definition the scope facts
* prove it names (protoc's scope walk over the file's imports), on both
* resolver routes and incrementally as in a full index. The expected targets
* were decided by protoc 3.21.12 (descriptor set of the fixture, see
* resolver-evidence/.../shared/scope.md, A3b).
*/
#include "../src/foundation/compat.h"
#include "test_framework.h"
#include "test_helpers.h"
#include "../src/pipeline/site_bind.h"
#include "../src/graph_buffer/graph_buffer.h"
#include "pipeline/pipeline.h"
#include "pipeline/pipeline_internal.h"
#include "sqlite3.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
TEST(site_bind_language_without_row_answers_nothing) {
@@ -39,8 +52,9 @@ TEST(site_bind_language_without_row_answers_nothing) {
result.usages.items = usages;
result.usages.count = 1;
cbm_site_memo_t *memo = NULL;
cbm_site_file_t sf;
cbm_pipeline_site_bind_begin(&sf, NULL, gb, "a.go", CBM_LANG_GO, &result);
cbm_pipeline_site_bind_begin(&sf, NULL, gb, "a.go", CBM_LANG_GO, &result, &memo, NULL);
ASSERT_FALSE(sf.active);
cbm_site_answer_t at_call = cbm_pipeline_site_bind_call(&sf, &calls[0], source);
@@ -56,11 +70,680 @@ TEST(site_bind_language_without_row_answers_nothing) {
int edges_before = cbm_gbuf_edge_count(gb);
cbm_pipeline_site_bind_end(&sf, gb);
ASSERT_EQ(cbm_gbuf_edge_count(gb), edges_before);
ASSERT_NULL(memo); /* nothing was looked up */
cbm_gbuf_free(gb);
PASS();
}
/* ── Indexing helpers ────────────────────────────────────────────────── */
/* Index `repo` into `db` (a second call on the same database takes the
* incremental route) with `workers` workers (0: leave CBM_WORKERS as it is);
* `marks` (test seam, NULL-terminated name/target-suffix/verdict triples)
* are set once the project name is known. */
typedef struct {
const char *name;
const char *rel; /* the target's file */
const char *symbol; /* the target's name in it */
cbm_site_verdict_t verdict;
} sb_mark_t;
static int sb_index(const char *repo, const char *db, int workers, const sb_mark_t *marks) {
const char *saved = getenv("CBM_WORKERS");
char *saved_copy = saved ? strdup(saved) : NULL;
if (workers > 0) {
char w[8];
snprintf(w, sizeof(w), "%d", workers);
cbm_setenv("CBM_WORKERS", w, 1);
}
int rc = -1;
cbm_pipeline_t *p = cbm_pipeline_new(repo, db, CBM_MODE_FULL);
if (p) {
for (int i = 0; marks && marks[i].name; i++) {
char *qn = cbm_pipeline_fqn_compute(cbm_pipeline_project_name(p), marks[i].rel,
marks[i].symbol);
cbm_pipeline_site_bind_test_mark(marks[i].name, qn, marks[i].verdict);
free(qn);
}
rc = cbm_pipeline_run(p);
cbm_pipeline_site_bind_test_mark(NULL, NULL, CBM_SITE_NO_ANSWER);
cbm_pipeline_free(p);
}
if (saved_copy) {
cbm_setenv("CBM_WORKERS", saved_copy, 1);
free(saved_copy);
} else {
cbm_unsetenv("CBM_WORKERS");
}
return rc;
}
static void sb_unlink_db(const char *db) {
char side[600];
unlink(db);
snprintf(side, sizeof(side), "%s-wal", db);
unlink(side);
snprintf(side, sizeof(side), "%s-shm", db);
unlink(side);
}
/* The edges of the given types as "type source -> target [strategy]" lines,
* sorted: what two indexes of one tree must agree on (D1: property text left
* out). The caller frees it; NULL when the database cannot be read. */
static char *sb_state(const char *db) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return NULL;
}
size_t cap = 4096;
size_t len = 0;
char *buf = malloc(cap);
buf[0] = '\0';
sqlite3_stmt *st = NULL;
const char *sql =
"SELECT e.type || ' ' || s.qualified_name || ' -> ' || t.qualified_name || ' [' || "
"coalesce(json_extract(e.properties, '$.strategy'), '') || ']' FROM edges e "
"JOIN nodes s ON s.id = e.source_id JOIN nodes t ON t.id = e.target_id "
"WHERE e.type IN ('USAGE', 'IMPORTS', 'CALLS', 'HTTP_CALLS', 'ASYNC_CALLS', "
"'CALL_REFERENCE', 'SPAWNS') ORDER BY 1";
if (sqlite3_prepare_v2(h, sql, -1, &st, NULL) == SQLITE_OK) {
while (sqlite3_step(st) == SQLITE_ROW) {
const char *line = (const char *)sqlite3_column_text(st, 0);
size_t l = strlen(line);
if (len + l + 2 > cap) {
cap = (len + l + 2) * 2;
buf = realloc(buf, cap);
}
memcpy(buf + len, line, l);
len += l;
buf[len++] = '\n';
buf[len] = '\0';
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return buf;
}
/* The strategy of the `type` edge from the node whose QN ends in `.<src>`
* to the node whose QN ends in `.<tgt>` ("" when it has none) into out;
* returns how many such edges there are. */
static int sb_edge(const char *db, const char *type, const char *src, const char *tgt, char *out,
size_t cap) {
out[0] = '\0';
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int n = 0;
const char *sql = "SELECT coalesce(json_extract(e.properties, '$.strategy'), '') FROM edges e "
"JOIN nodes s ON s.id = e.source_id JOIN nodes t ON t.id = e.target_id "
"WHERE e.type = ?1 AND s.qualified_name LIKE '%.' || ?2 "
"AND t.qualified_name LIKE '%.' || ?3";
if (sqlite3_prepare_v2(h, sql, -1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, type, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 2, src, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(st, 3, tgt, -1, SQLITE_TRANSIENT);
while (sqlite3_step(st) == SQLITE_ROW) {
n++;
snprintf(out, cap, "%s", (const char *)sqlite3_column_text(st, 0));
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return n;
}
/* One edge with this strategy ("*": any; want NULL: no such edge at all). */
static int sb_expect(const char *db, const char *venue, const char *type, const char *src,
const char *tgt, const char *want) {
char got[64];
int n = sb_edge(db, type, src, tgt, got, sizeof(got));
if (!want && n == 0) {
return 1;
}
if (want && n == 1 && (strcmp(want, "*") == 0 || strcmp(got, want) == 0)) {
return 1;
}
printf("\n [%s] %s %s -> %s: want %s%s%s, have %d edge(s), strategy '%s'\n", venue, type, src,
tgt, want ? "one edge, strategy '" : "no edge", want ? want : "", want ? "'" : "", n,
got);
return 0;
}
/* ── The Protobuf fixture ────────────────────────────────────────────── */
static const char *const SB_PROTO[][2] = {
{"x/common.proto", "syntax = \"proto3\";\npackage common;\n\n"
"message Status { int32 code = 1; }\nmessage Only { int32 v = 1; }\n"},
{"y/twin.proto", "syntax = \"proto3\";\npackage y;\n\nmessage Status { string y = 1; }\n"},
{"x/shared.proto",
"syntax = \"proto3\";\npackage shared;\n\nimport public \"x/common.proto\";\n\n"
"message Shared { int32 s = 1; }\n"},
/* two imported Status messages: the qualifier decides (protoc: y.Status,
* common.Status, common.Only); main's name chain gives both the same */
{"u/user.proto", "syntax = \"proto3\";\npackage u;\n\nimport \"x/common.proto\";\n"
"import \"y/twin.proto\";\n\nmessage User {\n y.Status st = 1;\n"
" common.Status cs = 2;\n common.Only only = 3;\n}\n"},
/* common.Status through shared's `import public` */
{"u/via.proto", "syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n\n"
"message Via {\n common.Status st = 1;\n shared.Shared sh = 2;\n}\n"},
/* nested messages; rpc request and response */
{"n/nested.proto", "syntax = \"proto3\";\npackage n.m;\n\nmessage L1 {\n message L2 {\n"
" message L3 { int32 v = 1; }\n }\n L2.L3 deep = 1;\n}\n\n"
"service S { rpc Get(L1) returns (L1.L2.L3); }\n"},
/* an import outside the repository: one candidate, not proven (main's
* chain names the same target: nothing added) */
{"p/outside.proto",
"syntax = \"proto3\";\npackage p;\n\nimport \"google/protobuf/empty.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Outside {\n y.Status st = 1;\n"
" google.protobuf.Empty e = 2;\n}\n"},
/* the same, with common imported too: main's chain names common.Status,
* the possible answer y.Status; main's edge stays alone */
{"p/outside2.proto", "syntax = \"proto3\";\npackage p;\n\n"
"import \"google/protobuf/empty.proto\";\nimport \"x/common.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Outside2 {\n y.Status st = 1;\n"
" google.protobuf.Empty e = 2;\n}\n"},
};
static int sb_write_proto(const char *dir, int pad) {
for (size_t i = 0; i < sizeof(SB_PROTO) / sizeof(SB_PROTO[0]); i++) {
if (th_write_file(TH_PATH(dir, SB_PROTO[i][0]), SB_PROTO[i][1]) != 0) {
return -1;
}
}
for (int i = 0; i < pad; i++) { /* past MIN_FILES_FOR_PARALLEL (50) */
char rel[64];
char body[128];
snprintf(rel, sizeof(rel), "pad/p%02d.proto", i);
snprintf(body, sizeof(body),
"syntax = \"proto3\";\npackage pad;\n\nmessage P%02d { int32 v = 1; }\n", i);
if (th_write_file(TH_PATH(dir, rel), body) != 0) {
return -1;
}
}
return 0;
}
static int sb_check_proto(const char *db, const char *venue) {
int ok = 1;
ok &= sb_expect(db, venue, "USAGE", "u.user", "y.twin.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.user", "x.common.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.user", "x.common.Only", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.via", "x.common.Status", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "u.via", "x.shared.Shared", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "n.nested.Get", "n.nested.L1", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "n.nested.Get", "n.nested.L3", "include_scope");
ok &= sb_expect(db, venue, "USAGE", "p.outside", "y.twin.Status", "");
ok &= sb_expect(db, venue, "USAGE", "p.outside2", "x.common.Status", "");
ok &= sb_expect(db, venue, "USAGE", "p.outside2", "y.twin.Status", NULL);
return ok;
}
/* A type reference binds the definition its qualifier names, on both
* routes, and the routes agree edge for edge. */
TEST(site_bind_protobuf_reference_binds_what_protoc_resolves) {
char *tmp = th_mktempdir("sb_proto");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_proto(dir, 55), 0);
char seq_db[512];
char par_db[512];
snprintf(seq_db, sizeof(seq_db), "%s/seq.db", tmp);
snprintf(par_db, sizeof(par_db), "%s/par.db", tmp);
ASSERT_EQ(sb_index(dir, seq_db, 1, NULL), 0);
ASSERT_EQ(sb_index(dir, par_db, 4, NULL), 0);
int ok = sb_check_proto(seq_db, "sequential") & sb_check_proto(par_db, "parallel");
char *seq = sb_state(seq_db);
char *par = sb_state(par_db);
bool same = seq && par && strcmp(seq, par) == 0;
if (!same) {
printf("\n parallel != sequential\n--- parallel\n%s--- sequential\n%s", par ? par : "",
seq ? seq : "");
}
free(seq);
free(par);
th_cleanup(tmp);
ASSERT_TRUE(ok);
ASSERT_TRUE(same);
PASS();
}
/* ── Incremental equals full ─────────────────────────────────────────── */
/* After the caller edited the tree: index incrementally into `inc_db`, then
* fully into a fresh `full_db`; the edges must be the same and the route the
* expected one. Returns 0, or -1 after printing what differs. */
static int sb_step(const char *repo, const char *inc_db, const char *full_db, const char *what,
cbm_incremental_route_t want_route, const char *want_decline) {
cbm_pipeline_incremental_test_reset_faults();
if (sb_index(repo, inc_db, 0, NULL) != 0) {
printf(" %s: incremental index failed\n", what);
return -1;
}
cbm_incremental_route_t route = cbm_pipeline_incremental_test_last_route();
cbm_incremental_closure_plan_t plan = cbm_pipeline_incremental_test_last_closure_plan();
sb_unlink_db(full_db);
if (sb_index(repo, full_db, 0, NULL) != 0) {
printf(" %s: full index failed\n", what);
return -1;
}
char *inc = sb_state(inc_db);
char *full = sb_state(full_db);
int rc = 0;
if (!inc || !full || strcmp(inc, full) != 0) {
printf(" %s: incremental != full\n--- incremental (route %d)\n%s--- full\n%s", what,
(int)route, inc ? inc : "(null)", full ? full : "(null)");
rc = -1;
} else if (route != want_route) {
printf(" %s: route %d (decline %s), expected %d\n", what, (int)route,
plan.decline ? plan.decline : "-", (int)want_route);
rc = -1;
} else if (want_decline && (!plan.decline || strcmp(plan.decline, want_decline) != 0)) {
printf(" %s: decline %s, expected %s\n", what, plan.decline ? plan.decline : "(none)",
want_decline);
rc = -1;
}
free(inc);
free(full);
return rc;
}
/* Remove the stored scope facts of one file (a row an older binary wrote). */
static int sb_strip_facts(const char *db, const char *rel) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READWRITE, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int rc = -1;
if (sqlite3_prepare_v2(h,
"UPDATE lsp_surface SET defs_json = json_remove(defs_json, '$.is') "
"WHERE rel_path = ?1",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, rel, -1, SQLITE_TRANSIENT);
rc = sqlite3_step(st) == SQLITE_DONE && sqlite3_changes(h) == 1 ? 0 : -1;
}
sqlite3_finalize(st);
sqlite3_close(h);
return rc;
}
/* An import added or removed repairs incrementally to what a full index
* draws; a stored row without scope facts declines to a full index. */
TEST(site_bind_protobuf_incremental_equals_full) {
char *tmp = th_mktempdir("sb_proto_incr");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_proto(dir, 0), 0);
char inc_db[512];
char full_db[512];
snprintf(inc_db, sizeof(inc_db), "%s/inc.db", tmp);
snprintf(full_db, sizeof(full_db), "%s/full.db", tmp);
ASSERT_EQ(sb_index(dir, inc_db, 0, NULL), 0);
ASSERT_TRUE(sb_check_proto(inc_db, "full"));
/* via imports twin and names y.Status */
ASSERT_EQ(th_write_file(TH_PATH(dir, "u/via.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n"
"import \"y/twin.proto\";\n\nmessage Via {\n common.Status st = 1;\n"
" shared.Shared sh = 2;\n y.Status ys = 3;\n}\n"),
0);
ASSERT_EQ(
sb_step(dir, inc_db, full_db, "import added", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, NULL),
0);
ASSERT_TRUE(
sb_expect(inc_db, "import added", "USAGE", "u.via", "y.twin.Status", "include_scope"));
/* user drops twin: its y.Status is no longer seen, common.Status is */
ASSERT_EQ(
th_write_file(TH_PATH(dir, "u/user.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/common.proto\";\n\n"
"message User {\n common.Status cs = 2;\n common.Only only = 3;\n}\n"),
0);
ASSERT_EQ(
sb_step(dir, inc_db, full_db, "import removed", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, NULL),
0);
ASSERT_TRUE(sb_expect(inc_db, "import removed", "USAGE", "u.user", "y.twin.Status", NULL));
ASSERT_TRUE(
sb_expect(inc_db, "import removed", "USAGE", "u.user", "x.common.Status", "include_scope"));
/* a re-exported file's surface changes (shared re-exports common): the
* re-exporter's includers have no edge into it, so the repair declines */
ASSERT_EQ(th_write_file(TH_PATH(dir, "x/common.proto"),
"syntax = \"proto3\";\npackage common;\n\n"
"message Status { int32 code = 1; }\n"),
0);
ASSERT_EQ(sb_step(dir, inc_db, full_db, "re-exported file changed",
CBM_INCREMENTAL_ROUTE_FORCED_FULL, "scope_reexport_changed"),
0);
/* a stored row without facts: the repair cannot read that file's scope */
ASSERT_EQ(sb_strip_facts(inc_db, "x/common.proto"), 0);
ASSERT_EQ(th_write_file(TH_PATH(dir, "u/via.proto"),
"syntax = \"proto3\";\npackage u;\n\nimport \"x/shared.proto\";\n\n"
"message Via {\n common.Status st = 1;\n shared.Shared sh = 2;\n}\n"),
0);
ASSERT_EQ(sb_step(dir, inc_db, full_db, "stored row without facts",
CBM_INCREMENTAL_ROUTE_FORCED_FULL, "scope_facts_missing"),
0);
th_cleanup(tmp);
PASS();
}
/* ── The guarded call shapes, through the test seam ──────────────────── */
/* Every mark has its own target, so an edge shows which site it came from. */
static const char *const SB_SEAM[][2] = {
{"lib.lua", "function target_fn()\n return 1\nend\n\nfunction other_fn()\n return 2\nend\n\n"
"function third_fn()\n return 3\nend\n\nfunction svc_fn()\n return 5\nend\n\n"
"function swift_fn()\n return 6\nend\n\nfunction php_fn()\n return 7\nend\n\n"
"function rust_fn()\n return 8\nend\n\nfunction java_fn()\n return 9\nend\n"},
/* markd proven, markp possible where main draws nothing, markq possible
* where main draws another target; markv a proven usage; a service call */
{"app.lua", "function markq()\n return 4\nend\n\nfunction run()\n markd()\n markp()\n"
" markq()\n local v = markv\n requests.get(\"http://svc/api/items\")\n"
" return v\nend\n"},
/* Swift label candidates: one compatible overload, and none */
{"s/Labels.swift", "func marks(a: Int) {}\nfunc marks(b: Int) {}\n\n"
"func use() {\n marks(a: 1)\n marks(c: 2)\n}\n"},
/* a PHP call on a vendor class */
{"php/Go.php", "<?php\nuse GuzzleHttp\\Client;\n\nfunction go() {\n $c = new Client();\n"
" $c->markh();\n}\n"},
/* a Rust call the engine places on an external type */
{"r/main.rs", "use std::path::Path;\n\nfn main() {\n let p = Path::new(\"x\");\n"
" p.markr();\n}\n"},
/* a Java call on a JDK type */
{"j/J.java", "import java.util.List;\n\nclass J {\n void f(List<String> l) {\n"
" l.markj();\n }\n}\n"},
};
static int sb_write_seam(const char *dir) {
for (size_t i = 0; i < sizeof(SB_SEAM) / sizeof(SB_SEAM[0]); i++) {
if (th_write_file(TH_PATH(dir, SB_SEAM[i][0]), SB_SEAM[i][1]) != 0) {
return -1;
}
}
for (int i = 0; i < 55; i++) {
char rel[64];
char body[128];
snprintf(rel, sizeof(rel), "pad/p%02d.lua", i);
snprintf(body, sizeof(body), "function pad%02d()\n return %d\nend\n", i, i);
if (th_write_file(TH_PATH(dir, rel), body) != 0) {
return -1;
}
}
return 0;
}
static const sb_mark_t SB_MARKS[] = {
{"markd", "lib.lua", "target_fn", CBM_SITE_PROVEN},
{"markp", "lib.lua", "other_fn", CBM_SITE_POSSIBLE},
{"markq", "lib.lua", "third_fn", CBM_SITE_POSSIBLE},
{"markv", "lib.lua", "target_fn", CBM_SITE_PROVEN},
{"requests.get", "lib.lua", "svc_fn", CBM_SITE_PROVEN},
{"marks", "lib.lua", "swift_fn", CBM_SITE_PROVEN},
{"markh", "lib.lua", "php_fn", CBM_SITE_PROVEN},
{"markr", "lib.lua", "rust_fn", CBM_SITE_PROVEN},
{"markj", "lib.lua", "java_fn", CBM_SITE_PROVEN},
{NULL, NULL, NULL, CBM_SITE_NO_ANSWER},
};
static int sb_check_seam(const char *db, const char *venue) {
int ok = 1;
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.target_fn", "include_scope");
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.other_fn", "include_scope_may");
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.third_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "app.run", "app.markq", "*");
ok &= sb_expect(db, venue, "USAGE", "app.run", "lib.target_fn", "include_scope");
/* the guards keep main's answer: a service call is classified as such, a
* Swift label set, a vendor call and an engine-placed call bind nothing
* of the layer */
ok &= sb_expect(db, venue, "CALLS", "app.run", "lib.svc_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "Labels.use", "lib.swift_fn", NULL);
ok &= sb_expect(db, venue, "CALLS", "Go.go", "lib.php_fn", NULL);
return ok;
}
/* A proven call answer is applied the same way on both routes at every
* guarded shape (Swift label candidates, a vendor call, an engine-placed
* external call, a service call); a possible one is drawn only where main
* drew nothing at the site. */
TEST(site_bind_seam_answers_agree_on_both_routes) {
char *tmp = th_mktempdir("sb_seam");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
ASSERT_EQ(sb_write_seam(dir), 0);
char seq_db[512];
char par_db[512];
snprintf(seq_db, sizeof(seq_db), "%s/seq.db", tmp);
snprintf(par_db, sizeof(par_db), "%s/par.db", tmp);
ASSERT_EQ(sb_index(dir, seq_db, 1, SB_MARKS), 0);
ASSERT_EQ(sb_index(dir, par_db, 4, SB_MARKS), 0);
int ok = sb_check_seam(seq_db, "sequential") & sb_check_seam(par_db, "parallel");
char *seq = sb_state(seq_db);
char *par = sb_state(par_db);
bool same = seq && par && strcmp(seq, par) == 0;
if (!same) {
printf("\n parallel != sequential\n--- parallel\n%s--- sequential\n%s", par ? par : "",
seq ? seq : "");
}
free(seq);
free(par);
th_cleanup(tmp);
ASSERT_TRUE(ok);
ASSERT_TRUE(same);
PASS();
}
/* USAGE edges proven by the layer (strategy include_scope) into a node whose
* QN ends in `.tgt`. */
static int sb_proven_to(const char *db, const char *tgt) {
sqlite3 *h = NULL;
if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) {
sqlite3_close(h);
return -1;
}
sqlite3_stmt *st = NULL;
int n = -1;
if (sqlite3_prepare_v2(h,
"SELECT count(*) FROM edges e JOIN nodes t ON t.id = e.target_id "
"WHERE e.type = 'USAGE' AND t.qualified_name LIKE '%.' || ?1 "
"AND json_extract(e.properties, '$.strategy') = 'include_scope'",
-1, &st, NULL) == SQLITE_OK) {
sqlite3_bind_text(st, 1, tgt, -1, SQLITE_TRANSIENT);
if (sqlite3_step(st) == SQLITE_ROW) {
n = sqlite3_column_int(st, 0);
}
}
sqlite3_finalize(st);
sqlite3_close(h);
return n;
}
/* One tree of the protoc fixtures (review 1, B2), indexed on one route; the
* proven USAGE edges into `tgt`. */
static int sb_protoc_case(const char *const files[][2], int nfiles, const char *tgt) {
char *tmp = th_mktempdir("sb_protoc");
if (!tmp) {
return -1;
}
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
int rc = 0;
for (int i = 0; i < nfiles && rc == 0; i++) {
rc = th_write_file(TH_PATH(dir, files[i][0]), files[i][1]);
}
char db[512];
snprintf(db, sizeof(db), "%s/p.db", tmp);
int n = rc == 0 && sb_index(dir, db, 1, NULL) == 0 ? sb_proven_to(db, tgt) : -1;
th_cleanup(tmp);
return n;
}
/* One protoc case: the proven edges it should have; a miss is printed, so
* every shape is reported. */
static int sb_protoc_expect(const char *shape, int got, int want) {
if (got != want) {
printf("\n protoc case %s: %d proven edge(s), want %d\n", shape, got, want);
}
return got == want;
}
/* Proven never where protoc resolves nothing (protoc 3.21.12 on each tree,
* review 1 fixtures, messages quoted): the first component decides the scope
* with no backtracking; a MISSING token; an import cycle; one file under two
* spellings; a path protoc refuses. The compiling partner stays proven. */
TEST(site_bind_protobuf_never_proven_where_protoc_rejects) {
int ok = 1;
/* "common.Status" is resolved to "x.common.Status", which is not defined */
static const char *const prefix[][2] = {
{"common.proto", "syntax = \"proto3\";\npackage common;\nmessage Status { int32 a = 1; }\n"},
{"x/y.proto", "syntax = \"proto3\";\npackage x.common;\nimport \"common.proto\";\n"
"message M { common.Status s = 1; }\n"}};
ok &= sb_protoc_expect("prefix", sb_protoc_case(prefix, 2, "common.Status"), 0);
/* "b.C" is resolved to "a.b.C", which is not defined */
static const char *const pk2[][2] = {
{"c2.proto", "syntax = \"proto3\";\npackage b;\nmessage C { int32 a = 1; }\n"},
{"pk2.proto", "syntax = \"proto3\";\npackage a.b;\nimport \"c2.proto\";\n"
"message M2 { b.C x = 1; }\n"}};
ok &= sb_protoc_expect("pk2", sb_protoc_case(pk2, 2, "c2.C"), 0);
/* compiles: b.D is .a.b.b.D (the innermost scope holding `b`) */
static const char *const pk[][2] = {
{"pk.proto", "syntax = \"proto3\";\npackage a.b;\nmessage b { message D {} }\n"
"message M { b.D x = 1; }\n"}};
ok &= sb_protoc_expect("pk", sb_protoc_case(pk, 1, "pk.D"), 1); /* node pk.D: the file and its name */
/* Expected ";" (a MISSING token after the field), Expected field number */
static const char *const missing[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage t;\nmessage T { int32 a = 1; }\n"},
{"u.proto", "syntax = \"proto3\";\npackage u;\nimport \"t.proto\";\n"
"message M { t.T x = 1 }\n"},
{"w.proto", "syntax = \"proto3\";\npackage w;\nimport \"t.proto\";\n"
"message P { int32 y = ; t.T x = 1; }\n"}};
ok &= sb_protoc_expect("missing", sb_protoc_case(missing, 3, "t.T"), 0);
/* File recursively imports itself */
static const char *const cycle[][2] = {
{"k1.proto", "syntax = \"proto3\";\npackage k;\nimport public \"k2.proto\";\n"
"message K1 { int32 a = 1; }\n"},
{"k2.proto", "syntax = \"proto3\";\npackage k;\nimport public \"k1.proto\";\n"
"message K2 { K1 a = 1; }\n"}};
ok &= sb_protoc_expect("cycle", sb_protoc_case(cycle, 2, "k1.K1"), 0);
/* "cc.T" is already defined in file "common/c.proto" (two spellings) */
static const char *const spell[][2] = {
{"proto/common/c.proto", "syntax = \"proto3\";\npackage cc;\nmessage T { int32 a = 1; }\n"},
{"x.proto", "syntax = \"proto3\";\nimport public \"common/c.proto\";\n"},
{"y.proto", "syntax = \"proto3\";\nimport public \"proto/common/c.proto\";\n"},
{"z.proto", "syntax = \"proto3\";\nimport \"x.proto\";\nimport \"y.proto\";\n"
"message Z { cc.T t = 1; }\n"}};
ok &= sb_protoc_expect("spell", sb_protoc_case(spell, 4, "c.T"), 0);
/* Backslashes, consecutive slashes, ".", or ".." are not allowed in the
* virtual path */
static const char *const dot[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage t;\nmessage T { int32 a = 1; }\n"},
{"dot.proto", "syntax = \"proto3\";\npackage dot;\nimport \"./t.proto\";\n"
"message D { t.T x = 1; }\n"}};
ok &= sb_protoc_expect("dot", sb_protoc_case(dot, 2, "t.T"), 0);
ASSERT_TRUE(ok);
PASS();
}
/* protoc 3.21.12 on rpc types (scope-evidence/review-3/rpc): protoc searches
* an rpc's types from its service, so a method named like the type is found
* first: `rpc Foo(Foo)` gives "Foo" is not a message type, as does a method
* named like an imported message and a response named like its method.
* `.p.Foo` from the root and a method named unlike every type compile. In
* the graph the method Foo and the message Foo are one node (`s.Foo`, the
* method's), so `rpc Foo(.p.Foo)` has no node of protoc's target and nothing
* is proven there; `rpc Get(.p.Foo)` is the root reference's partner. The
* same collision leaves nothing to prove in `same` and `response` before the
* fix too: the imported cases (method and message in two files) are the ones
* the walk proved wrong. */
TEST(site_bind_protobuf_rpc_type_a_method_hides_is_never_proven) {
static const char *const same[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Foo(Foo) returns (Bar);\n}\n"}};
static const char *const dotted[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Foo(.p.Foo) returns (Bar);\n}\n"}};
static const char *const dotted_get[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Get(.p.Foo) returns (Bar);\n}\n"}};
static const char *const partner[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Get(Foo) returns (Bar);\n}\n"}};
static const char *const imported[][2] = {
{"q.proto", "syntax = \"proto3\";\npackage p;\nmessage Baz { int32 a = 1; }\n"},
{"s.proto", "syntax = \"proto3\";\npackage p;\nimport \"q.proto\";\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Baz(Baz) returns (Bar);\n}\n"}};
static const char *const imported_response[][2] = {
{"q.proto", "syntax = \"proto3\";\npackage p;\nmessage Baz { int32 a = 1; }\n"},
{"s.proto", "syntax = \"proto3\";\npackage p;\nimport \"q.proto\";\n"
"message Foo { int32 b = 1; }\nservice S {\n rpc Baz(Foo) returns (Baz);\n}\n"}};
static const char *const response[][2] = {
{"s.proto", "syntax = \"proto3\";\npackage p;\nmessage Foo { int32 a = 1; }\n"
"message Bar { int32 b = 1; }\nservice S {\n rpc Bar(Foo) returns (Bar);\n}\n"}};
int ok = 1;
ok &= sb_protoc_expect("rpc same", sb_protoc_case(same, 1, "s.Foo"), 0);
ok &= sb_protoc_expect("rpc dotted", sb_protoc_case(dotted, 1, "s.Foo"), 0);
ok &= sb_protoc_expect("rpc dotted get", sb_protoc_case(dotted_get, 1, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc partner request", sb_protoc_case(partner, 1, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc partner response", sb_protoc_case(partner, 1, "s.Bar"), 1);
ok &= sb_protoc_expect("rpc imported", sb_protoc_case(imported, 2, "q.Baz"), 0);
ok &= sb_protoc_expect("rpc imported response", sb_protoc_case(imported_response, 2, "q.Baz"),
0);
ok &= sb_protoc_expect("rpc imported response request",
sb_protoc_case(imported_response, 2, "s.Foo"), 1);
ok &= sb_protoc_expect("rpc response", sb_protoc_case(response, 1, "s.Bar"), 0);
ok &= sb_protoc_expect("rpc response request", sb_protoc_case(response, 1, "s.Foo"), 1);
ASSERT_TRUE(ok);
PASS();
}
/* protoc 3.21.12 on review 3's fx4/scope: A's field is .p.A.Type (the
* enclosing message is searched first), B's is .p.Type. Both are proven to
* those, and the outer Type never at A's site, where the inner one shadows
* it. */
TEST(site_bind_protobuf_enclosing_message_decides_first) {
static const char *const scope[][2] = {
{"t.proto", "syntax = \"proto3\";\npackage p;\nenum Type { T0 = 0; }\n"},
{"a.proto", "syntax = \"proto3\";\npackage p;\nimport \"t.proto\";\n"
"message A {\n enum Type { A0 = 0; }\n Type t = 1;\n}\n"
"message B {\n Type t = 1;\n}\n"}};
char *tmp = th_mktempdir("sb_scope");
ASSERT_NOT_NULL(tmp);
char dir[512];
snprintf(dir, sizeof(dir), "%s/repo", tmp);
int rc = 0;
for (int i = 0; i < 2 && rc == 0; i++) {
rc = th_write_file(TH_PATH(dir, scope[i][0]), scope[i][1]);
}
char db[512];
snprintf(db, sizeof(db), "%s/p.db", tmp);
int indexed = rc == 0 ? sb_index(dir, db, 1, NULL) : -1;
int inner = indexed == 0 ? sb_proven_to(db, "a.Type") : -1; /* A's site */
int outer = indexed == 0 ? sb_proven_to(db, "t.Type") : -1; /* B's site only */
th_cleanup(tmp);
printf("\n proven: a.Type %d, t.Type %d\n", inner, outer);
ASSERT_EQ(indexed, 0);
ASSERT_EQ(inner, 1);
ASSERT_EQ(outer, 1);
PASS();
}
SUITE(site_bind) {
RUN_TEST(site_bind_protobuf_never_proven_where_protoc_rejects);
RUN_TEST(site_bind_protobuf_enclosing_message_decides_first);
RUN_TEST(site_bind_protobuf_rpc_type_a_method_hides_is_never_proven);
RUN_TEST(site_bind_language_without_row_answers_nothing);
RUN_TEST(site_bind_protobuf_reference_binds_what_protoc_resolves);
RUN_TEST(site_bind_protobuf_incremental_equals_full);
RUN_TEST(site_bind_seam_answers_agree_on_both_routes);
}
+3 -3
View File
@@ -1057,19 +1057,19 @@ static uint64_t ts_decline_work(int n, const char **reason) {
for (int i = 0; i < n; i++) {
char *json = (char *)malloc(256);
snprintf(json, 256,
"{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.f%d.New\",\"sn\":\"New\",\"lb\":"
"{\"v\":6,\"lang\":%d,\"lsp\":[{\"qn\":\"p.f%d.New\",\"sn\":\"New\",\"lb\":"
"\"Function\",\"lg\":%d,\"ty\":\"store.T%d=p.store.T%d\"}],\"reg\":[],\"py\":null}",
(int)CBM_LANG_GO, i, (int)CBM_LANG_GO, i, i);
rows[i].defs_json = json;
}
char before_row[256];
snprintf(before_row, sizeof(before_row),
"{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\","
"{\"v\":6,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\","
"\"lg\":%d,\"al\":\"Impl\"}],\"reg\":[],\"py\":null}",
(int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO);
char after_row[256];
snprintf(after_row, sizeof(after_row),
"{\"v\":5,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\","
"{\"v\":6,\"lang\":%d,\"lsp\":[{\"qn\":\"p.store.T%d\",\"sn\":\"T%d\",\"lb\":\"Struct\","
"\"lg\":%d,\"al\":null}],\"reg\":[],\"py\":null}",
(int)CBM_LANG_GO, n - 1, n - 1, (int)CBM_LANG_GO);
const char *old_rows[] = {before_row};