fix(scala): name a companion object Owner#object, collision-only

A Scala object with a same-named class, trait or enum in the same scope
(its companion) is now named <Owner>#object and its members
<Owner>#object.<m>, in place of the `$` suffix of the merged change. The
fence works like C's `#macro`: no plain Scala identifier ends in `#object`,
so the registry no longer needs a table of companion owners, the declaring
file's language, or an extra parameter on its helpers to tell a Scala
companion from a Java or JavaScript class named `Foo$`. An object without
such a type beside it keeps its plain QN.

The lookups that let `Owner.m` written in source reach `Owner#object.m`
try the fenced form: the import map (exact and suffix), the same-module
probe, the qualified-tail match, the receiver-chain guard and the package
map's member import. The registry runs the import and same-module probes
only once a Scala companion has been registered. The enclosing-function QN
used by the usage, throw, type-assignment and env-access walkers fences the
object the same way, so those source to the method the def walk emits.

Companion detection answers each object in O(1). A scope's children are
read once with a tree cursor: the def walk reads every class body ahead and
the first query reads the file's top level, where the previous code walked
down from the root for every parent lookup and indexed children one at a
time. The answers are held by pointer in the extraction context and tied to
the source they were built for, so a copied context with another source
builds its own instead of sharing a by-value copy.

CBM_SEMANTIC_INDEX_VERSION goes from 13 to 14: an index built before holds
one merged node for a type and its companion and rebuilds once.

Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
This commit is contained in:
Martin Vogel
2026-11-26 22:39:41 +01:00
parent 0bc6577db6
commit be95b8f7b4
11 changed files with 539 additions and 345 deletions
+15 -26
View File
@@ -398,6 +398,16 @@ typedef struct {
* definition is the target, and the macro only when no definition is visible. */
#define CBM_MACRO_QN_SUFFIX "#macro"
/* The qualified name of a Scala companion object -- an `object` with a
* same-named class, trait or enum in the same scope -- is `<Owner QN>#object`,
* and its members are `<Owner QN>#object.<member>`. The class and its companion
* share one source name; the fence gives the object an identity of its own, and
* the plain `<Owner QN>` always belongs to the type. An object without such a
* type beside it keeps its plain QN. `name` stays Owner. A plain Scala
* identifier never ends in `#object` (operator characters such as '#' do not
* mix with letters outside backquotes), so no other definition spells it. */
#define CBM_SCALA_OBJECT_QN_SUFFIX "#object"
/* Byte offsets are meaningful only within the source buffer that produced
* them. C/C++/CUDA run both raw and preprocessed extraction passes, and those
* buffers can contain unrelated occurrences at the same numeric span. */
@@ -1203,24 +1213,6 @@ typedef struct {
int count;
} CBMReturnTypeTable;
// --- Scala companion cache ---
// The class/trait/enum names of every scope an object_definition has asked
// about, keyed by (scope node, name bytes). A scope is scanned once, on its
// first query; names are byte ranges into the source, never copied. One extra
// key per scanned scope (len == 0) records the scan itself, so a scope without
// any class is not rescanned either. Open addressing, power-of-two capacity.
typedef struct {
const void *scope; // ts_node id of the scope (parent) node; NULL = empty slot
uint32_t off;
uint32_t len;
} CBMScalaScopeName;
typedef struct {
CBMScalaScopeName *slots;
uint32_t cap; // 0 until the first query
uint32_t count;
} CBMScalaCompanionCache;
typedef struct {
CBMArena *arena;
/* Scratch for AST traversal, owned by the cbm_extract_file_ex call that
@@ -1293,6 +1285,11 @@ typedef struct {
/* Go: what each block's statements bind (extract_calls.c), NULL until a route call asks;
* allocated in `scratch`. */
void *go_block_bindings;
/* Scala: the companion-object answers (helpers.c cbm_scala_is_companion_object),
* NULL until the first object asks; allocated in `scratch` (or `arena`) and
* tied to the `source` it was built for, so a copy of this context with
* another source builds its own. Nothing in a CBMFileResult points at it. */
void *scala_companions;
/* C++/CUDA raw view: the GoogleTest definitions the def walk named
* (CBMTestSpan, in `scratch`), in walk order. */
CBMTestSpan *test_spans;
@@ -1301,9 +1298,6 @@ 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;
/* Scala only; lives in `scratch` (or `arena` without one). Nothing in a
* CBMFileResult points at it. */
CBMScalaCompanionCache scala_companions;
} CBMExtractCtx;
/* Internal configured-definition seams. No declarations pointer enters a result. */
@@ -1640,11 +1634,6 @@ void cbm_resolvedcall_push(CBMResolvedCallArray *arr, CBMArena *a, CBMResolvedCa
void cbm_channels_push(CBMChannelArray *arr, CBMArena *a, CBMChannel ch);
void cbm_diagram_arrows_push(CBMDiagramArrowArray *arr, CBMArena *a, CBMDiagramArrow da);
/* True for a Scala object_definition with a same-named class/trait/enum
* sibling. O(1) per query after the first one in a scope, which scans the
* scope's named children once into ctx->scala_companions. */
bool cbm_scala_is_companion_object(CBMExtractCtx *ctx, TSNode node);
// --- Sub-extractor entry points ---
void cbm_extract_definitions(CBMExtractCtx *ctx);
+18 -14
View File
@@ -227,6 +227,7 @@ static void extract_func_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec
static void extract_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec);
static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec,
const char *kind, char *name);
static TSNode find_class_member_body(TSNode class_node, CBMLanguage lang);
static void extract_c_typedef(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *spec);
static void walk_defs(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec, int depth_unused);
static void extract_variables(CBMExtractCtx *ctx, TSNode root, const CBMLangSpec *spec);
@@ -9745,11 +9746,15 @@ static void emit_class_def(CBMExtractCtx *ctx, TSNode node, const CBMLangSpec *s
} else {
class_qn = cbm_fqn_compute_source_lang(a, ctx->project, ctx->rel_path, name, ctx->language);
}
/* A Scala class and its companion object are distinct owners despite sharing
* the source-level name. Use Scala's conventional singleton-class suffix so
* neither container nor their methods overwrite each other in the graph. */
if (ctx->language == CBM_LANG_SCALA && cbm_scala_is_companion_object(ctx, node)) {
class_qn = cbm_arena_sprintf(a, "%s$", class_qn);
/* Scala: a companion object shares its class's source name; it is
* Owner#object (CBM_SCALA_OBJECT_QN_SUFFIX), so neither owner nor its
* members overwrite the other's. Members, fields and nested types follow
* from class_qn; `name` stays Owner. The body is read ahead here, before
* the walk reaches its nested objects, so each of them is answered in O(1). */
if (ctx->language == CBM_LANG_SCALA) {
TSNode no_scope = {0};
class_qn = cbm_scala_object_qn(ctx, node, no_scope, class_qn);
cbm_scala_prime_scope(ctx, find_class_member_body(node, ctx->language));
}
const char *label = class_label_for_kind(kind);
@@ -14171,19 +14176,18 @@ static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const char
if (!ts_node_is_null(name_node)) {
char *cname = cbm_node_text(ctx->arena, name_node, ctx->source);
if (cname && cname[0]) {
TSNode no_scope = {0}; /* Scala: a companion is Owner#object (emit_class_def) */
if (saved_enclosing) {
const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", saved_enclosing, cname);
return ctx->language == CBM_LANG_SCALA && cbm_scala_is_companion_object(ctx, node)
? cbm_arena_sprintf(ctx->arena, "%s$", qn)
: qn;
return cbm_scala_object_qn(
ctx, node, no_scope,
cbm_arena_sprintf(ctx->arena, "%s.%s", saved_enclosing, cname));
}
/* Top-level: language-aware module so Java/Go don't double the
* filename stem (matches extract_class_def above). */
const char *qn = cbm_fqn_compute_source_lang(ctx->arena, ctx->project, ctx->rel_path,
cname, ctx->language);
return ctx->language == CBM_LANG_SCALA && cbm_scala_is_companion_object(ctx, node)
? cbm_arena_sprintf(ctx->arena, "%s$", qn)
: qn;
return cbm_scala_object_qn(ctx, node, no_scope,
cbm_fqn_compute_source_lang(ctx->arena, ctx->project,
ctx->rel_path, cname,
ctx->language));
}
}
return saved_enclosing;
+27 -9
View File
@@ -1413,6 +1413,25 @@ static const char *compute_func_qn(CBMExtractCtx *ctx, TSNode node, const CBMLan
}
// Compute class QN for scope tracking.
/* Scala: the scope of the object_definition the walk stands on, read off the
* walk's own cursor (one parent step) so a companion query never re-walks the
* tree from the root. The def walk has read every class body and the file's top
* level already; this matters for objects declared in a block. A null node
* when the cursor is elsewhere (the query then finds the scope itself). */
static TSNode scala_object_scope(const CBMExtractCtx *ctx, TSNode node, const WalkState *state) {
TSNode none = {0};
if (ctx->language != CBM_LANG_SCALA || strcmp(ts_node_type(node), "object_definition") != 0 ||
!state || !state->current_cursor || !state->occurrence_cursor ||
!ts_node_eq(ts_tree_cursor_current_node(state->current_cursor), node)) {
return none;
}
ts_tree_cursor_reset_to(state->occurrence_cursor, state->current_cursor);
if (!ts_tree_cursor_goto_parent(state->occurrence_cursor)) {
return none;
}
return ts_tree_cursor_current_node(state->occurrence_cursor);
}
static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const WalkState *state) {
if (ctx->language == CBM_LANG_OBJECTSCRIPT_UDL) {
return objectscript_get_class_name(ctx, node);
@@ -1479,19 +1498,18 @@ static const char *compute_class_qn(CBMExtractCtx *ctx, TSNode node, const WalkS
outer_qn = ctx->language == CBM_LANG_PYTHON ? py_nearest_scope_qn(state)
: state->enclosing_class_qn;
}
/* Scala: a companion object's scope is Owner#object, as the def walk names
* the object (extract_defs.c emit_class_def). */
TSNode scope = scala_object_scope(ctx, node, state);
if (outer_qn) {
const char *qn = cbm_arena_sprintf(ctx->arena, "%s.%s", outer_qn, name);
return ctx->language == CBM_LANG_SCALA && cbm_scala_is_companion_object(ctx, node)
? cbm_arena_sprintf(ctx->arena, "%s$", qn)
: qn;
return cbm_scala_object_qn(ctx, node, scope,
cbm_arena_sprintf(ctx->arena, "%s.%s", outer_qn, name));
}
/* Java/Go: directory-based module (see compute_func_qn). */
const char *qn =
cbm_fqn_compute_source_lang(ctx->arena, ctx->project, ctx->rel_path, name, ctx->language);
return ctx->language == CBM_LANG_SCALA && cbm_scala_is_companion_object(ctx, node)
? cbm_arena_sprintf(ctx->arena, "%s$", qn)
: qn;
return cbm_scala_object_qn(
ctx, node, scope,
cbm_fqn_compute_source_lang(ctx->arena, ctx->project, ctx->rel_path, name, ctx->language));
}
/* Forward declaration */
+255 -88
View File
@@ -173,118 +173,277 @@ bool cbm_label_is_type_like(const char *label) {
strcmp(label, "Type") == 0 || strcmp(label, "Trait") == 0;
}
/* --- Scala companion cache (CBMScalaCompanionCache) --- */
/* --- Scala companion objects ---
*
* The answer for every Scala object_definition whose scope has been read: is
* there a class, trait or enum of the same name beside it. The table is keyed
* by node id (open addressing, power-of-two capacity) and holds one more key
* per read scope, so no scope is read twice. Reading a scope walks its children
* with a cursor: indexed child access and ts_node_parent both re-walk from the
* start, which made a wide scope quadratic. The table lives in `scratch` (or
* `arena`) for one file and records the source it was built for: a copy of the
* context with another source (extract_defs.c's spliced-source audit) builds a
* table of its own instead of answering from another tree's node ids. */
enum { SCC_EMPTY = 0, SCC_PLAIN = 1, SCC_COMPANION = 2, SCC_SCOPE = 3 };
enum { SCC_MIN_CAP = 64 };
static uint64_t scc_hash(const void *scope, const char *bytes, uint32_t len) {
uint64_t h = 1469598103934665603ULL;
const unsigned char *p = (const unsigned char *)&scope;
for (size_t i = 0; i < sizeof(scope); i++) {
h = (h ^ p[i]) * 1099511628211ULL;
}
typedef struct {
const void *id;
uint8_t kind; /* SCC_*; SCC_EMPTY marks a free slot */
} scc_slot_t;
typedef struct {
const char *source;
scc_slot_t *slots;
uint32_t cap;
uint32_t count;
bool root_read;
} scc_table_t;
/* The class/trait/enum names of one scope while it is read: byte ranges into
* the source, len 0 = free slot. */
typedef struct {
uint32_t off;
uint32_t len;
} scc_name_t;
static uint32_t scc_id_hash(const void *id) {
uint64_t x = (uint64_t)(uintptr_t)id;
x ^= x >> 33;
x *= 0xff51afd7ed558ccdULL;
x ^= x >> 33;
return (uint32_t)x;
}
static uint32_t scc_bytes_hash(const char *p, uint32_t len) {
uint32_t h = 2166136261U;
for (uint32_t i = 0; i < len; i++) {
h = (h ^ (unsigned char)bytes[i]) * 1099511628211ULL;
h = (h ^ (unsigned char)p[i]) * 16777619U;
}
return h;
}
/* Slot holding (scope, name), or the empty slot where it would go. */
static CBMScalaScopeName *scc_find(const CBMScalaCompanionCache *c, const char *source,
const void *scope, uint32_t off, uint32_t len) {
uint32_t mask = c->cap - 1;
uint32_t i = (uint32_t)scc_hash(scope, source + off, len) & mask;
for (;;) {
CBMScalaScopeName *s = &c->slots[i];
if (!s->scope) {
/* The slot holding `id` (an object answer, or with `scope` the read mark), or
* the free slot where it would go. */
static scc_slot_t *scc_find(const scc_table_t *t, const void *id, bool scope) {
uint32_t mask = t->cap - 1;
for (uint32_t i = scc_id_hash(id) & mask;; i = (i + 1) & mask) {
scc_slot_t *s = &t->slots[i];
if (s->kind == SCC_EMPTY || (s->id == id && (s->kind == SCC_SCOPE) == scope)) {
return s;
}
if (s->scope == scope && s->len == len &&
(len == 0 || memcmp(source + s->off, source + off, len) == 0)) {
return s;
}
i = (i + 1) & mask;
}
}
static bool scc_insert(CBMScalaCompanionCache *c, CBMArena *a, const char *source,
const void *scope, uint32_t off, uint32_t len) {
if ((c->count + 1) * 2 > c->cap) {
uint32_t new_cap = c->cap ? c->cap * 2 : 64;
CBMScalaScopeName *old = c->slots;
uint32_t old_cap = c->cap;
c->slots = cbm_arena_calloc(a, (size_t)new_cap * sizeof(*c->slots));
if (!c->slots) {
c->slots = old;
return false;
}
c->cap = new_cap;
for (uint32_t i = 0; i < old_cap; i++) {
if (old[i].scope) {
*scc_find(c, source, old[i].scope, old[i].off, old[i].len) = old[i];
}
}
/* Room for `more` new keys at half load; false on OOM (the table is kept). */
static bool scc_reserve(scc_table_t *t, CBMArena *a, uint32_t more) {
if (t->count > UINT32_MAX / 4 || more > UINT32_MAX / 4 - t->count) {
return false;
}
CBMScalaScopeName *s = scc_find(c, source, scope, off, len);
if (!s->scope) {
s->scope = scope;
s->off = off;
s->len = len;
c->count++;
}
return true;
}
/* First query in a scope: record its class/trait/enum names, plus the
* (scope, "") marker that says the scope has been scanned. */
static bool scc_scan_scope(CBMScalaCompanionCache *c, CBMArena *a, const char *source,
TSNode scope) {
const void *id = scope.id;
if (c->cap && scc_find(c, source, id, 0, 0)->scope) {
uint32_t need = (t->count + more) * 2;
if (need <= t->cap) {
return true;
}
if (!scc_insert(c, a, source, id, 0, 0)) {
uint32_t cap = t->cap ? t->cap : SCC_MIN_CAP;
while (cap < need) {
cap *= 2;
}
scc_slot_t *slots = cbm_arena_calloc(a, (size_t)cap * sizeof(*slots));
if (!slots) {
return false;
}
uint32_t count = ts_node_named_child_count(scope);
for (uint32_t i = 0; i < count; i++) {
TSNode sibling = ts_node_named_child(scope, i);
const char *kind = ts_node_type(sibling);
if (strcmp(kind, "class_definition") != 0 && strcmp(kind, "trait_definition") != 0 &&
strcmp(kind, "enum_definition") != 0) {
continue;
}
TSNode name = ts_node_child_by_field_name(sibling, TS_FIELD("name"));
if (ts_node_is_null(name)) {
continue;
}
uint32_t off = ts_node_start_byte(name);
uint32_t len = ts_node_end_byte(name) - off;
if (len && !scc_insert(c, a, source, id, off, len)) {
return false;
scc_table_t grown = {.source = t->source, .slots = slots, .cap = cap};
for (uint32_t i = 0; i < t->cap; i++) {
if (t->slots[i].kind != SCC_EMPTY) {
*scc_find(&grown, t->slots[i].id, t->slots[i].kind == SCC_SCOPE) = t->slots[i];
}
}
t->slots = slots;
t->cap = cap;
return true;
}
bool cbm_scala_is_companion_object(CBMExtractCtx *ctx, TSNode node) {
if (!ctx || !ctx->source || strcmp(ts_node_type(node), "object_definition") != 0) {
static void scc_put(scc_table_t *t, const void *id, uint8_t kind) {
scc_slot_t *s = scc_find(t, id, kind == SCC_SCOPE);
if (s->kind == SCC_EMPTY) {
t->count++;
}
s->id = id;
s->kind = kind;
}
static bool scc_is_type_kind(const char *kind) {
return strcmp(kind, "class_definition") == 0 || strcmp(kind, "trait_definition") == 0 ||
strcmp(kind, "enum_definition") == 0;
}
/* The name of a definition as a byte range of the source; false when it has
* none (or it lies outside the source). */
static bool scc_name_range(const CBMExtractCtx *ctx, TSNode def, uint32_t *off, uint32_t *len) {
TSNode name = ts_node_child_by_field_name(def, TS_FIELD("name"));
if (ts_node_is_null(name)) {
return false;
}
TSNode name_node = ts_node_child_by_field_name(node, TS_FIELD("name"));
TSNode parent = ts_node_parent(node);
if (ts_node_is_null(name_node) || ts_node_is_null(parent)) {
uint32_t start = ts_node_start_byte(name);
uint32_t end = ts_node_end_byte(name);
if (end <= start || ctx->source_len < 0 || end > (uint32_t)ctx->source_len) {
return false;
}
uint32_t off = ts_node_start_byte(name_node);
uint32_t len = ts_node_end_byte(name_node) - off;
if (len == 0 || ts_node_end_byte(name_node) > (uint32_t)ctx->source_len) {
return false;
*off = start;
*len = end - start;
return true;
}
static scc_name_t *scc_name_find(scc_name_t *names, uint32_t mask, const char *source, uint32_t off,
uint32_t len) {
for (uint32_t i = scc_bytes_hash(source + off, len) & mask;; i = (i + 1) & mask) {
scc_name_t *n = &names[i];
if (n->len == 0 || (n->len == len && memcmp(source + n->off, source + off, len) == 0)) {
return n;
}
}
}
/* Read `scope` once: answer each of its object_definition children and mark
* the scope read. Three linear cursor passes over the children, the last two
* only for a scope that holds an object: count, collect the type names, answer
* the objects (a companion may come before or after its type). */
static void scc_read_scope(CBMExtractCtx *ctx, scc_table_t *t, CBMArena *a, TSNode scope) {
if (ts_node_is_null(scope) || (t->cap && scc_find(t, scope.id, true)->kind != SCC_EMPTY)) {
return;
}
uint32_t types = 0;
uint32_t objects = 0;
TSTreeCursor cur = ts_tree_cursor_new(scope);
if (ts_tree_cursor_goto_first_child(&cur)) {
do {
const char *kind = ts_node_type(ts_tree_cursor_current_node(&cur));
if (strcmp(kind, "object_definition") == 0) {
objects++;
} else if (scc_is_type_kind(kind)) {
types++;
}
} while (ts_tree_cursor_goto_next_sibling(&cur));
}
if (!scc_reserve(t, a, objects + 1)) {
ts_tree_cursor_delete(&cur);
return;
}
scc_name_t *names = NULL;
uint32_t mask = 0;
if (objects && types && types <= UINT32_MAX / 4) {
uint32_t cap = SCC_MIN_CAP;
while (cap < types * 2) {
cap *= 2;
}
names = cbm_arena_calloc(a, (size_t)cap * sizeof(*names));
mask = cap - 1;
}
if (names) {
ts_tree_cursor_reset(&cur, scope);
if (ts_tree_cursor_goto_first_child(&cur)) {
do {
TSNode kid = ts_tree_cursor_current_node(&cur);
uint32_t off = 0;
uint32_t len = 0;
if (scc_is_type_kind(ts_node_type(kid)) && scc_name_range(ctx, kid, &off, &len)) {
scc_name_t *n = scc_name_find(names, mask, ctx->source, off, len);
n->off = off;
n->len = len;
}
} while (ts_tree_cursor_goto_next_sibling(&cur));
}
}
if (objects) {
ts_tree_cursor_reset(&cur, scope);
if (ts_tree_cursor_goto_first_child(&cur)) {
do {
TSNode kid = ts_tree_cursor_current_node(&cur);
if (strcmp(ts_node_type(kid), "object_definition") != 0) {
continue;
}
uint32_t off = 0;
uint32_t len = 0;
bool companion = names && scc_name_range(ctx, kid, &off, &len) &&
scc_name_find(names, mask, ctx->source, off, len)->len != 0;
scc_put(t, kid.id, companion ? SCC_COMPANION : SCC_PLAIN);
} while (ts_tree_cursor_goto_next_sibling(&cur));
}
}
ts_tree_cursor_delete(&cur);
scc_put(t, scope.id, SCC_SCOPE);
}
/* This context's table, built for its own source; NULL without an arena. */
static scc_table_t *scc_table(CBMExtractCtx *ctx, CBMArena **arena) {
CBMArena *a = ctx->scratch ? ctx->scratch : ctx->arena;
CBMScalaCompanionCache *c = &ctx->scala_companions;
if (!a || !scc_scan_scope(c, a, ctx->source, parent)) {
if (!a || !ctx->source) {
return NULL;
}
*arena = a;
scc_table_t *t = (scc_table_t *)ctx->scala_companions;
if (t && t->source == ctx->source) {
return t;
}
t = cbm_arena_calloc(a, sizeof(*t));
if (!t) {
return NULL;
}
t->source = ctx->source;
ctx->scala_companions = t;
return t;
}
void cbm_scala_prime_scope(CBMExtractCtx *ctx, TSNode scope) {
CBMArena *a = NULL;
scc_table_t *t = ctx && ctx->language == CBM_LANG_SCALA ? scc_table(ctx, &a) : NULL;
if (t) {
scc_read_scope(ctx, t, a, scope);
}
}
/* The answer recorded for `node`: SCC_EMPTY until its scope has been read. */
static uint8_t scc_answer(const scc_table_t *t, TSNode node) {
return t->cap ? scc_find(t, node.id, false)->kind : SCC_EMPTY;
}
bool cbm_scala_is_companion_object(CBMExtractCtx *ctx, TSNode node, TSNode scope) {
if (!ctx || ctx->language != CBM_LANG_SCALA || ts_node_is_null(node) ||
strcmp(ts_node_type(node), "object_definition") != 0) {
return false;
}
return scc_find(c, ctx->source, parent.id, off, len)->scope != NULL;
CBMArena *a = NULL;
scc_table_t *t = scc_table(ctx, &a);
if (!t) {
return false;
}
uint8_t kind = scc_answer(t, node);
if (kind == SCC_EMPTY && !t->root_read) {
t->root_read = true;
scc_read_scope(ctx, t, a, ctx->root);
kind = scc_answer(t, node);
}
if (kind == SCC_EMPTY && !ts_node_is_null(scope)) {
scc_read_scope(ctx, t, a, scope);
kind = scc_answer(t, node);
}
if (kind == SCC_EMPTY) {
/* An object in a scope nobody read ahead (a block, a package body):
* one parent step, and that whole scope is answered with it. */
scc_read_scope(ctx, t, a, ts_node_parent(node));
kind = scc_answer(t, node);
}
return kind == SCC_COMPANION;
}
const char *cbm_scala_object_qn(CBMExtractCtx *ctx, TSNode node, TSNode scope,
const char *plain_qn) {
if (!ctx || ctx->language != CBM_LANG_SCALA || !plain_qn ||
!cbm_scala_is_companion_object(ctx, node, scope)) {
return plain_qn;
}
const char *qn = cbm_arena_sprintf(ctx->arena, "%s" CBM_SCALA_OBJECT_QN_SUFFIX, plain_qn);
return qn ? qn : plain_qn;
}
// True when `label` names a data relation: SQL CREATE TABLE / CREATE VIEW, and
@@ -1680,7 +1839,8 @@ static const char *func_node_name(CBMArena *a, TSNode func_node, const char *sou
const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source,
const char *project, const char *rel_path, const char *module_qn,
bool test_macro_names, const CBMTestSpanMap *pp_test_spans) {
bool test_macro_names, const CBMTestSpanMap *pp_test_spans,
CBMExtractCtx *scala_ctx) {
TSNode func_node = cbm_find_enclosing_func(node, lang);
if (ts_node_is_null(func_node)) {
return module_qn;
@@ -1715,8 +1875,9 @@ const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, co
// to the innermost. Walk parents collecting class names innermost-first,
// then prepend each as we ascend so the result reads Outer.Inner.
const char *class_chain = NULL;
for (TSNode cur = ts_node_parent(func_node); !ts_node_is_null(cur);
cur = ts_node_parent(cur)) {
TSNode next = {0};
for (TSNode cur = ts_node_parent(func_node); !ts_node_is_null(cur); cur = next) {
next = ts_node_parent(cur);
if (!cbm_kind_in_set(cur, spec->class_node_types) &&
!cbm_is_namespace_scope_kind(lang, ts_node_type(cur))) {
continue;
@@ -1725,10 +1886,15 @@ const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, co
if (ts_node_is_null(class_name)) {
continue;
}
char *cname = cbm_node_text(a, class_name, source);
const char *cname = cbm_node_text(a, class_name, source);
if (!cname || !cname[0]) {
continue;
}
/* Scala: a companion object is Owner#object in the def walk, and
* `next` is its scope. */
if (scala_ctx) {
cname = cbm_scala_object_qn(scala_ctx, cur, next, cname);
}
class_chain = class_chain ? cbm_arena_sprintf(a, "%s.%s", cname, class_chain) : cname;
}
if (class_chain) {
@@ -1769,7 +1935,8 @@ const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node) {
// Cache miss: compute via parent walk
const char *qn = cbm_enclosing_func_qn(
ctx->arena, node, ctx->language, ctx->source, ctx->project, ctx->rel_path, ctx->module_qn,
cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), ctx->pp_test_spans);
cbm_cpp_test_macro_names_on(ctx->language, ctx->test_declarations), ctx->pp_test_spans,
ctx);
// Cache the result: find the enclosing function's byte range
TSNode func_node = cbm_find_enclosing_func(node, ctx->language);
+18 -2
View File
@@ -52,14 +52,30 @@ TSNode cbm_find_enclosing_func(TSNode node, CBMLanguage lang);
// a GoogleTest macro head is named as the def walk names it
// (cbm_cpp_test_macro_name; cbm_cpp_test_macro_names_on gives the value).
// pp_test_spans: the preprocessed view's map to the raw tests
// (cbm_test_span_owner_qn), NULL in a raw view.
// (cbm_test_span_owner_qn), NULL in a raw view. scala_ctx: the extraction
// context whose companion answers fence a Scala companion object in the class
// chain (Owner#object.m, as the def walk names it); NULL names bare chains.
const char *cbm_enclosing_func_qn(CBMArena *a, TSNode node, CBMLanguage lang, const char *source,
const char *project, const char *rel_path, const char *module_qn,
bool test_macro_names, const CBMTestSpanMap *pp_test_spans);
bool test_macro_names, const CBMTestSpanMap *pp_test_spans,
CBMExtractCtx *scala_ctx);
// Cached version: uses ctx->ef_cache to avoid repeated parent-chain walks.
const char *cbm_enclosing_func_qn_cached(CBMExtractCtx *ctx, TSNode node);
// Scala: true for an object_definition with a class, trait or enum of the same
// name in the same scope (its companion). `scope` is the node's parent when the
// caller holds it, else a null node. An answered object costs O(1): a scope's
// children are read once, with a cursor, and every object among them answered
// (the first query reads ctx->root; cbm_scala_prime_scope reads others ahead).
bool cbm_scala_is_companion_object(CBMExtractCtx *ctx, TSNode node, TSNode scope);
void cbm_scala_prime_scope(CBMExtractCtx *ctx, TSNode scope);
// Scala: `plain_qn` + CBM_SCALA_OBJECT_QN_SUFFIX for a companion object, else
// `plain_qn` unchanged (every other node and language).
const char *cbm_scala_object_qn(CBMExtractCtx *ctx, TSNode node, TSNode scope,
const char *plain_qn);
// Max declarator-chain descent depth for C/C++/CUDA/GLSL function-name
// resolution. Single source of truth — extract_defs.c's DECLARATOR_DEPTH_LIMIT
// is derived from this so the three extractors cannot drift.
+10 -5
View File
@@ -2938,13 +2938,18 @@ static const cbm_gbuf_node_t *resolve_scala_namespace_import(const cbm_pipeline_
}
/* `import pkg.Owner.member`: the member must exist under the owner's
* QN. Binding the owner instead would mislabel the edge. Only object
* members are importable, so when Owner has a companion the `Owner$`
* scope is tried before the class. */
static const char *const scopes[] = {"$", ""};
* members are importable, so when Owner has a companion object its
* scope (Owner#object, CBM_SCALA_OBJECT_QN_SUFFIX) is tried before the
* class's. A name too long for the fenced probe still gets the plain one. */
static const char *const scopes[] = {CBM_SCALA_OBJECT_QN_SUFFIX, ""};
for (size_t si = 0; si < sizeof(scopes) / sizeof(scopes[0]); si++) {
char member_qn[CBM_SZ_512];
if (snprintf(member_qn, sizeof(member_qn), "%s%s.%s", owner->qualified_name, scopes[si],
remainder + top_len + 1) >= (int)sizeof(member_qn)) {
int n = snprintf(member_qn, sizeof(member_qn), "%s%s.%s", owner->qualified_name,
scopes[si], remainder + top_len + 1);
if (n < 0 || n >= (int)sizeof(member_qn)) {
if (scopes[si][0]) {
continue;
}
return NULL;
}
const cbm_gbuf_node_t *scoped = cbm_gbuf_find_by_qn(ctx->gbuf, member_qn);
+5 -1
View File
@@ -1813,8 +1813,12 @@ int cbm_pipeline_build_fresh_semantic_manifest(cbm_pipeline_t *p, const char *pr
* directories name and HANDLES its Route (extract_nextjs.c). An index
* built before has none of these Routes for its unchanged route files,
* so it rebuilds once on upgrade.
* 14: a Scala object with a same-named class, trait or enum beside it is
* <Owner>#object and its members <Owner>#object.<m> (extract_defs.c,
* helpers.c cbm_scala_object_qn). An index built before holds one merged
* node for the type and its companion, so it rebuilds once on upgrade.
* The unresolved-call coverage threshold remains independent. */
enum { CBM_SEMANTIC_INDEX_VERSION = 13 };
enum { CBM_SEMANTIC_INDEX_VERSION = 14 };
typedef struct {
cbm_gbuf_t *gbuf;
+102 -133
View File
@@ -151,12 +151,10 @@ struct cbm_registry {
CBMHashTable *swift_signatures; /* borrowed exact-map keys; owned values */
CBMHashTable *swift_overloads; /* base callable QN -> overloads */
swift_owners_t *swift_owners;
/* Scala companion owners (`pkg.Foo$`), recorded by
* cbm_registry_add_lang_in_module for type-like Scala definitions only. Keys borrow `exact`'s
* owned QN. NULL until the first companion, so every other language's
* registry never allocates it and every `$` probe below is one NULL test. */
CBMHashTable *companions;
/* A Scala companion object (CBM_SCALA_OBJECT_QN_SUFFIX) is registered: the
* lookups that read `Owner.m` as `Owner#object.m` run only then, so every
* registry without one resolves exactly as before. */
bool scala_object_fences;
};
/* ── Helpers ─────────────────────────────────────────────────────── */
@@ -180,6 +178,18 @@ static const char *simple_name(const char *qn) {
return seg;
}
/* A Scala companion object is `<Owner>#object` (CBM_SCALA_OBJECT_QN_SUFFIX,
* cbm.h); source spells it `Owner`. The length of a QN segment without that
* trailing fence (unchanged when it has none). */
enum { OBJECT_FENCE_LEN = sizeof(CBM_SCALA_OBJECT_QN_SUFFIX) - 1 };
static size_t seg_len_without_object_fence(const char *seg, size_t len) {
if (len > OBJECT_FENCE_LEN &&
memcmp(seg + len - OBJECT_FENCE_LEN, CBM_SCALA_OBJECT_QN_SUFFIX, OBJECT_FENCE_LEN) == 0) {
return len - OBJECT_FENCE_LEN;
}
return len;
}
/* Extract everything before the last dot. Returns heap-allocated string. */
/* Count common dot-separated prefix segments. One pass over the shared prefix:
@@ -1702,7 +1712,6 @@ void cbm_registry_free(cbm_registry_t *r) {
cbm_ht_free(r->swift_overloads);
}
swift_owners_free(r->swift_owners);
cbm_ht_free(r->companions); /* keys borrow exact's */
cbm_ht_foreach(r->exact, free_label, NULL);
cbm_ht_free(r->exact);
for (int i = 0; i < r->label_pool_n; i++) {
@@ -1928,18 +1937,9 @@ void cbm_registry_add_lang_in_module(cbm_registry_t *r, const char *name,
if (name && name[0] && strchr(derived, '#') && strcmp(name, primary) != 0) {
index_under_name(r, name, owned_qn, is_test, lang);
}
/* A type-like `Foo$` declared in a Scala file is recorded as a companion
* owner, which is the only thing that lets the resolver read `Foo.m` as
* `Foo$.m`. `Foo$` from any other language is an ordinary name. */
size_t qn_len = strlen(owned_qn);
if (lang == CBM_LANG_SCALA && qn_len >= 2 && owned_qn[qn_len - 1] == '$' &&
cbm_label_is_type_like(label)) {
if (!r->companions) {
r->companions = cbm_ht_create(CBM_SZ_256);
}
if (r->companions) {
cbm_ht_set(r->companions, owned_qn, (void *)owned_qn);
}
if (lang == CBM_LANG_SCALA && !r->scala_object_fences) {
size_t derived_len = strlen(derived);
r->scala_object_fences = seg_len_without_object_fence(derived, derived_len) != derived_len;
}
}
@@ -2032,20 +2032,6 @@ bool cbm_node_props_generated(const char *properties_json) {
return properties_json && strstr(properties_json, "\"" CBM_PROP_GENERATED "\":\"") != NULL;
}
/* True when the first `owner_len` bytes of `owner` name a class whose Scala
* companion (`<owner>$`) is registered. The only gate on every `$` probe in
* the resolver: a Java or JS `Foo$` next to `Foo` is never a companion. */
static bool companion_known(const cbm_registry_t *r, const char *owner, size_t owner_len) {
if (!r->companions || owner_len == 0 || owner_len + 2 > CBM_SZ_512) {
return false;
}
char key[CBM_SZ_512];
memcpy(key, owner, owner_len);
key[owner_len] = '$';
key[owner_len + 1] = '\0';
return cbm_ht_has(r->companions, key);
}
/* ── Lookup ──────────────────────────────────────────────────────── */
bool cbm_registry_exists(const cbm_registry_t *r, const char *qn) {
@@ -2248,46 +2234,44 @@ static cbm_resolution_t resolve_import_map(const cbm_registry_t *r, const char *
if (stored_key) {
return (cbm_resolution_t){stored_key, "import_map", CONF_IMPORT_MAP, REG_RESOLVED};
}
if (suffix && suffix[0]) {
/* Scala: an import binds the class, but `Foo.method()` on a class name
* is a call into the companion object, whose QN carries a trailing `$`.
* Probed only when `<resolved>$` is a registered Scala companion, so a
* Java or JS class that happens to be named `Foo$` never takes part. */
bool companion = companion_known(r, resolved, strlen(resolved));
if (companion) {
snprintf(candidate, sizeof(candidate), "%s$.%s", resolved, suffix);
stored_key = cbm_ht_get_key(r->exact, candidate);
if (stored_key) {
return (cbm_resolution_t){stored_key, "import_map", CONF_IMPORT_MAP, REG_RESOLVED};
}
/* Scala: an import binds the class, but `Owner.m()` on the class's name is
* a call into its companion object, Owner#object. */
if (r->scala_object_fences && suffix && suffix[0]) {
int n = snprintf(candidate, sizeof(candidate), "%s" CBM_SCALA_OBJECT_QN_SUFFIX ".%s",
resolved, suffix);
stored_key =
n > 0 && n < (int)sizeof(candidate) ? cbm_ht_get_key(r->exact, candidate) : NULL;
if (stored_key) {
return (cbm_resolution_t){stored_key, "import_map", CONF_IMPORT_MAP, REG_RESOLVED};
}
}
/* import_map_suffix fallback: find a QN starting with resolved+"." and
* ending with "."+suffix. Any such QN's last segment equals the last
* segment of suffix, so probe the by_name index and tail-check the
* (few) candidates instead of cbm_ht_foreach over the WHOLE exact
* table — that scan ran per unresolved call and dominated
* elasticsearch's resolve phase (94% of samples: 700k-entry foreach +
* strlen per entry). */
/* import_map_suffix fallback: find a QN starting with resolved+"." and
* ending with "."+suffix. Any such QN's last segment equals the last
* segment of suffix, so probe the by_name index and tail-check the (few)
* candidates instead of cbm_ht_foreach over the WHOLE exact table — that
* scan ran per unresolved call and dominated elasticsearch's resolve
* phase (94% of samples: 700k-entry foreach + strlen per entry). */
if (suffix && suffix[0]) {
char resolved_dot[CBM_SZ_512];
char companion_dot[CBM_SZ_512];
char dot_suffix[CBM_SZ_256];
snprintf(resolved_dot, sizeof(resolved_dot), "%s.", resolved);
snprintf(companion_dot, sizeof(companion_dot), "%s$.", resolved);
snprintf(dot_suffix, sizeof(dot_suffix), ".%s", suffix);
qn_array_t *arr = cbm_ht_get(r->by_name, simple_name(suffix));
if (arr) {
size_t rd_len = strlen(resolved_dot);
size_t cd_len = strlen(companion_dot);
size_t ds_len = strlen(dot_suffix);
size_t r_len = strlen(resolved);
for (int i = 0; i < arr->count; i++) {
const char *qn = arr->items[i];
size_t klen = strlen(qn);
bool under_owner =
klen >= rd_len + ds_len && strncmp(qn, resolved_dot, rd_len) == 0;
bool under_companion =
companion && klen >= cd_len + ds_len && strncmp(qn, companion_dot, cd_len) == 0;
if ((under_owner || under_companion) &&
/* ... or under its companion object, resolved#object. */
bool under_object =
r->scala_object_fences && klen >= r_len + OBJECT_FENCE_LEN + 1 + ds_len &&
strncmp(qn, resolved, r_len) == 0 &&
memcmp(qn + r_len, CBM_SCALA_OBJECT_QN_SUFFIX ".", OBJECT_FENCE_LEN + 1) == 0;
if ((under_object ||
(klen >= rd_len + ds_len && strncmp(qn, resolved_dot, rd_len) == 0)) &&
strcmp(qn + klen - ds_len, dot_suffix) == 0) {
return (cbm_resolution_t){qn, "import_map_suffix", CONF_IMPORT_MAP_SUFFIX,
REG_RESOLVED};
@@ -2337,32 +2321,19 @@ static cbm_resolution_t resolve_same_module(const cbm_registry_t *r, const char
stored_key = same_module_candidate(r, module_qn, scope_len, suffix);
if (stored_key)
return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};
/* Scala `Owner.member` in the declaring file: the member may live under
* the companion `Owner$`. Each owner segment is tried once, and only when
* `<module>.<owner>$` is a registered Scala companion. */
for (const char *dot = r->companions && module_qn && callee_name ? strchr(callee_name, '.')
: NULL;
dot; dot = strchr(dot + 1, '.')) {
size_t owner_len = (size_t)(dot - callee_name);
char owner_qn[CBM_SZ_512];
if (scope_len + owner_len + 2 > sizeof(owner_qn)) {
break;
}
memcpy(owner_qn, module_qn, scope_len);
owner_qn[scope_len] = '.';
memcpy(owner_qn + scope_len + 1, callee_name, owner_len);
if (!companion_known(r, owner_qn, scope_len + 1 + owner_len)) {
continue;
}
/* Scala `Owner.m` in the declaring file: the member may live under the
* companion object, Owner#object.m. Each owner segment is tried once; a
* name too long for the buffer is skipped. */
for (const char *dot = r->scala_object_fences && callee_name ? strchr(callee_name, '.') : NULL;
dot; dot = strchr(dot + SKIP_ONE, '.')) {
char fenced[CBM_SZ_512];
int n = snprintf(fenced, sizeof(fenced), "%.*s$%s", (int)owner_len, callee_name, dot);
if (n < 0 || n >= (int)sizeof(fenced)) {
continue;
}
stored_key = same_module_candidate(r, module_qn, scope_len, fenced);
if (stored_key) {
int n = snprintf(fenced, sizeof(fenced), "%.*s" CBM_SCALA_OBJECT_QN_SUFFIX "%s",
(int)(dot - callee_name), callee_name, dot);
stored_key = n > 0 && n < (int)sizeof(fenced)
? same_module_candidate(r, module_qn, scope_len, fenced)
: NULL;
if (stored_key)
return (cbm_resolution_t){stored_key, "same_module", CONF_SAME_MODULE, REG_RESOLVED};
}
}
return empty_result();
}
@@ -2414,46 +2385,40 @@ static cbm_resolution_t resolve_multi_with_imports(const cbm_registry_t *r, cons
* as trustworthy as a same-module hit. */
#define CONF_QUALIFIED_SUFFIX 0.90
/* Segment equality that lets a Scala companion object stand in for its class:
* a call written `Foo.make` reaches the method declared under `Foo$`. `cand`
* points into `cand_qn`; the `$` form is accepted only when the candidate QN
* up to and including that segment is a registered Scala companion, so a
* Java or JS segment `Foo$` is plain text that does not equal `Foo`. */
static bool qn_seg_matches(const cbm_registry_t *r, const char *cand_qn, const char *seg,
size_t seg_len, const char *cand, size_t cand_len) {
if (cand_len == seg_len) {
return strncmp(seg, cand, seg_len) == 0;
}
return cand_len == seg_len + 1 && cand[seg_len] == '$' && strncmp(seg, cand, seg_len) == 0 &&
companion_known(r, cand_qn, (size_t)(cand - cand_qn) + seg_len);
}
/* True when `qn` equals `dotted` or ends with ".<dotted>", compared segment by
* segment from the right so companion segments (`Foo$`) match `Foo`. */
static bool qn_tail_matches(const cbm_registry_t *r, const char *qn, const char *dotted) {
const char *q_end = qn + strlen(qn);
const char *d_end = dotted + strlen(dotted);
for (;;) {
const char *q_dot = q_end;
while (q_dot > qn && q_dot[-1] != '.') {
q_dot--;
/* qualified_suffix_match's second look at a candidate that carries a '#':
* `qn` (qlen bytes) ends with the dotted callee (w bytes) at a segment
* boundary once a Scala object fence is dropped from each candidate segment
* before the last -- `Owner.make` names Owner#object.make. The last segment
* is compared as it is, so a fenced definition (#field, #macro) never answers
* a bare name. */
static bool object_fenced_tail_matches(const char *qn, size_t qlen, const char *dotted, size_t w) {
const char *q_end = qn + qlen;
const char *d_end = dotted + w;
for (bool last = true;; last = false) {
const char *q_seg = q_end;
while (q_seg > qn && q_seg[-1] != '.') {
q_seg--;
}
const char *d_dot = d_end;
while (d_dot > dotted && d_dot[-1] != '.') {
d_dot--;
const char *d_seg = d_end;
while (d_seg > dotted && d_seg[-1] != '.') {
d_seg--;
}
if (!qn_seg_matches(r, qn, d_dot, (size_t)(d_end - d_dot), q_dot,
(size_t)(q_end - q_dot))) {
size_t q_len = (size_t)(q_end - q_seg);
if (!last) {
q_len = seg_len_without_object_fence(q_seg, q_len);
}
size_t d_len = (size_t)(d_end - d_seg);
if (q_len != d_len || memcmp(q_seg, d_seg, d_len) != 0) {
return false;
}
if (d_dot == dotted) {
if (d_seg == dotted) {
return true; /* every callee segment matched at a segment boundary */
}
if (q_dot == qn) {
return false; /* callee has more segments than the candidate */
if (q_seg == qn) {
return false; /* the callee has more segments than the candidate */
}
q_end = q_dot - 1;
d_end = d_dot - 1;
q_end = q_seg - SKIP_ONE;
d_end = d_seg - SKIP_ONE;
}
}
@@ -2468,8 +2433,7 @@ static bool qn_tail_matches(const cbm_registry_t *r, const char *qn, const char
* both reduce to "run", so the bare-name scorer would route every caller to a
* single winner. Language agnostic: callees with no separator return NULL and
* leave behavior unchanged. */
static const char *qualified_suffix_match(const cbm_registry_t *r, const qn_array_t *arr,
const char *callee_name) {
static const char *qualified_suffix_match(const qn_array_t *arr, const char *callee_name) {
/* Normalize "::" → "." so the tail composes with dotted candidate QNs. */
char dotted[CBM_SZ_512];
size_t w = 0;
@@ -2490,7 +2454,11 @@ static const char *qualified_suffix_match(const cbm_registry_t *r, const qn_arra
const char *match = NULL;
for (int i = 0; i < arr->count; i++) {
const char *qn = arr->items[i];
if (!qn_tail_matches(r, qn, dotted)) {
size_t qlen = strlen(qn);
const char *tail = qlen >= w ? qn + (qlen - w) : NULL;
/* Segment boundary: tail is the whole QN or is preceded by '.'. */
if (!(tail && strcmp(tail, dotted) == 0 && (tail == qn || tail[-1] == '.')) &&
!(strchr(qn, '#') && object_fenced_tail_matches(qn, qlen, dotted, w))) {
continue;
}
if (match) {
@@ -2544,8 +2512,8 @@ static bool cs_type_keyword_root(const char *dotted) {
*
* Otherwise language agnostic by design: every language that writes receiver
* chains gains the same protection. */
static bool receiver_chain_admits(const cbm_registry_t *r, const char *callee_name,
const char *candidate_qn, CBMLanguage lang) {
static bool receiver_chain_admits(const char *callee_name, const char *candidate_qn,
CBMLanguage lang) {
/* Normalize "::" -> "." so the chain composes with dotted candidate QNs,
* the same way qualified_suffix_match does. */
char dotted[CBM_SZ_512];
@@ -2611,8 +2579,9 @@ static bool receiver_chain_admits(const cbm_registry_t *r, const char *callee_na
}
for (const char *anc = candidate_qn; anc < cand_last;) {
const char *anc_end = strchr(anc, '.');
size_t anc_len = (size_t)(anc_end - anc);
if (len > 0 && qn_seg_matches(r, candidate_qn, seg, len, anc, anc_len)) {
/* A companion object Owner#object is written Owner in the chain. */
size_t anc_len = seg_len_without_object_fence(anc, (size_t)(anc_end - anc));
if (anc_len == len && len > 0 && strncmp(seg, anc, len) == 0) {
return true;
}
anc = anc_end + SKIP_ONE;
@@ -3098,9 +3067,9 @@ static gate_scope_t gate_scope(CBMLanguage lang) {
* candidate's ancestry is not in the chain and no candidate's is by the same
* words (Elixir's `Scheduler` names the scheduler module) -- when one is, the
* pick is left for the parallel resolver's field-type hint. */
static bool type_receiver_blind(const cbm_registry_t *r, const qn_array_t *arr,
const char *callee_name, const char *chosen, CBMLanguage lang) {
if (receiver_chain_admits(r, callee_name, chosen, lang)) {
static bool type_receiver_blind(const qn_array_t *arr, const char *callee_name, const char *chosen,
CBMLanguage lang) {
if (receiver_chain_admits(callee_name, chosen, lang)) {
return false;
}
for (int i = 0; i < arr->count; i++) {
@@ -3180,7 +3149,7 @@ static cbm_resolution_t scala_local_first(const cbm_registry_t *r, const qn_arra
const char *callee_name, const char *module_qn,
bool caller_test) {
const char *local = scala_module_local_pick(r, arr, module_qn, caller_test);
if (!local || !receiver_chain_admits(r, callee_name, local, CBM_LANG_SCALA) ||
if (!local || !receiver_chain_admits(callee_name, local, CBM_LANG_SCALA) ||
value_receiver_blind(r, arr, callee_name, local, module_qn, NULL, 0, CBM_LANG_SCALA)) {
return empty_result();
}
@@ -3201,7 +3170,7 @@ static cbm_resolution_t resolve_name_candidates(const cbm_registry_t *r, const q
* candidates by full qualified tail, before bare-name scoring collapses
* them onto a single winner. */
if (arr->count > 1) {
const char *q = qualified_suffix_match(r, arr, callee_name);
const char *q = qualified_suffix_match(arr, callee_name);
if (q) {
return (cbm_resolution_t){q, "qualified_suffix", CONF_QUALIFIED_SUFFIX, REG_RESOLVED};
}
@@ -3210,7 +3179,7 @@ static cbm_resolution_t resolve_name_candidates(const cbm_registry_t *r, const q
/* Strategy 3: unique name, judged by the receiver gate only where it is
* whole (gate_scope). */
if (arr->count == SKIP_ONE) {
if (!receiver_chain_admits(r, callee_name, arr->items[0], lang) ||
if (!receiver_chain_admits(callee_name, arr->items[0], lang) ||
(gate == GATE_FULL &&
value_receiver_blind(r, arr, callee_name, arr->items[0], module_qn, import_vals,
import_count, lang))) {
@@ -3239,7 +3208,7 @@ static cbm_resolution_t resolve_name_candidates(const cbm_registry_t *r, const q
* so on the CALLS path it passes the same receiver gates. */
if (gate != GATE_OFF && res.qualified_name && res.qualified_name[0] &&
!is_import_reachable(res.qualified_name, import_vals, import_count) &&
(type_receiver_blind(r, arr, callee_name, res.qualified_name, lang) ||
(type_receiver_blind(arr, callee_name, res.qualified_name, lang) ||
value_receiver_blind(r, arr, callee_name, res.qualified_name, module_qn, import_vals,
import_count, lang))) {
return empty_result();
@@ -3250,7 +3219,7 @@ static cbm_resolution_t resolve_name_candidates(const cbm_registry_t *r, const q
best_by_import_distance(r, (const char **)arr->items, qn_test_flags(arr),
qn_lang_flags(arr), arr->count, module_qn, caller_test);
if (best) {
if (!receiver_chain_admits(r, callee_name, best, lang) ||
if (!receiver_chain_admits(callee_name, best, lang) ||
(gate != GATE_OFF &&
value_receiver_blind(r, arr, callee_name, best, module_qn, NULL, 0, lang))) {
return empty_result();
@@ -4490,7 +4459,7 @@ int cbm_registry_swift_candidates(const cbm_registry_t *r, const CBMCall *call,
const char *qn = bucket->items[i];
swift_signature_t *meta = cbm_ht_get(r->swift_signatures, qn);
has_swift = has_swift || meta != NULL;
if (meta && receiver_chain_admits(r, call->callee_name, qn, CBM_LANG_SWIFT) &&
if (meta && receiver_chain_admits(call->callee_name, qn, CBM_LANG_SWIFT) &&
swift_signature_matches(meta, call)) {
match_test[matched] = bucket_test[i];
matches[matched++] = qn;
+57 -18
View File
@@ -10749,9 +10749,9 @@ TEST(extract_scala_companion_owners_are_distinct) {
ASSERT_FALSE(r->has_error);
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational"));
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational$"));
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational#object"));
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational.reciprocal"));
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational$.apply"));
ASSERT_TRUE(has_def_qn(r, "t.Rational.Rational#object.apply"));
/* Class-body vals keep their module-level QN like every other language;
* parent_class tells the two owners apart. */
ASSERT_TRUE(has_def_qn(r, "t.Rational.isWhole"));
@@ -10777,12 +10777,12 @@ TEST(extract_scala_trait_companion_and_standalone_object) {
/* Trait companions collide just like class companions. */
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec$"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec#object"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec.encode"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec$.utf8"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Codec#object.utf8"));
/* A standalone object has nothing to collide with and keeps its plain QN. */
ASSERT_TRUE(has_def_qn(r, "t.Codec.Registry"));
ASSERT_FALSE(has_def_qn(r, "t.Codec.Registry$"));
ASSERT_FALSE(has_def_qn(r, "t.Codec.Registry#object"));
ASSERT_TRUE(has_def_qn(r, "t.Codec.Registry.lookup"));
cbm_free_result(r);
@@ -10819,39 +10819,77 @@ TEST(extract_scala_companion_detection_is_scoped) {
ASSERT_FALSE(r->has_error);
ASSERT_TRUE(has_def_qn(r, "t.Ast.Node"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Node$"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Node$.leaf"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Node#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Node#object.leaf"));
/* Inside `Tree` there is no class Node, so its `object Node` is standalone,
* while `Leaf` has a class sibling there. */
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Node"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Tree.Node$"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Tree.Node#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Node.root"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Leaf"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Leaf$"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Leaf$.make"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Leaf#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Tree.Leaf#object.make"));
/* `Ops` holds objects only; nothing there is a companion, whatever the
* neighbouring scopes declare. */
ASSERT_TRUE(has_def_qn(r, "t.Ast.Ops.Node"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Ops.Node$"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Ops.Node#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Ops.Leaf"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Ops.Leaf$"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Ops.Leaf#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Ops.Node.count"));
/* Sealed hierarchy in one scope: companions of a case class and of the
* sealed trait get `$`, a case object without a class sibling does not. */
* sealed trait get `#object`, a case object without a class sibling does not. */
ASSERT_TRUE(has_def_qn(r, "t.Ast.Add"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Add$"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Add#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Sub"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Sub$"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Sub#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Neg"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Neg$"));
ASSERT_FALSE(has_def_qn(r, "t.Ast.Neg#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Op"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Op$"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Op$.all"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Op#object"));
ASSERT_TRUE(has_def_qn(r, "t.Ast.Op#object.all"));
cbm_free_result(r);
PASS();
}
/* #2154: an object beside a same-named class is its companion and gets the
* Owner#object fence (CBM_SCALA_OBJECT_QN_SUFFIX): `name` stays Owner, the
* label is the object's own, and its members live under the fence. An object
* with no such type beside it keeps its plain QN, and no QN carries `$`. */
TEST(extract_scala_object_beside_class_gets_object_fence) {
CBMFileResult *r = extract("class Rational(n: Int, d: Int)\n"
"object Rational {\n"
" def make(n: Int, d: Int): Rational = new Rational(n, d)\n"
"}\n"
"object Registry {\n"
" def lookup(name: String): Option[Rational] = None\n"
"}\n",
CBM_LANG_SCALA, "t", "Rational.scala");
ASSERT_NOT_NULL(r);
ASSERT_FALSE(r->has_error);
const CBMDefinition *cls = pyn_def(r, "t.Rational.Rational");
ASSERT_NOT_NULL(cls);
const CBMDefinition *obj = pyn_def(r, "t.Rational.Rational" CBM_SCALA_OBJECT_QN_SUFFIX);
ASSERT_NOT_NULL(obj);
ASSERT_STR_EQ(obj->name, "Rational");
ASSERT_STR_EQ(obj->label, "Class");
const CBMDefinition *make = pyn_def(r, "t.Rational.Rational#object.make");
ASSERT_NOT_NULL(make);
ASSERT_STR_EQ(make->parent_class, "t.Rational.Rational#object");
/* Control: no type named Registry, so the object keeps its plain QN. */
ASSERT_NOT_NULL(pyn_def(r, "t.Rational.Registry"));
ASSERT_NOT_NULL(pyn_def(r, "t.Rational.Registry.lookup"));
ASSERT_FALSE(has_def_qn(r, "t.Rational.Registry#object"));
for (int i = 0; i < r->defs.count; i++) {
const char *qn = r->defs.items[i].qualified_name;
ASSERT(!qn || !strchr(qn, '$'));
}
cbm_free_result(r);
PASS();
}
TEST(extract_scala_import_selectors_and_aliases) {
CBMFileResult *r = extract("import foo.Direct\n"
"import foo.{Selected, Original => Alias, Hidden => _, _}\n"
@@ -16504,6 +16542,7 @@ SUITE(extraction) {
RUN_TEST(extract_scala_companion_owners_are_distinct);
RUN_TEST(extract_scala_trait_companion_and_standalone_object);
RUN_TEST(extract_scala_companion_detection_is_scoped);
RUN_TEST(extract_scala_object_beside_class_gets_object_fence);
RUN_TEST(extract_scala_import_selectors_and_aliases);
RUN_TEST(extract_scala_package_namespace);
RUN_TEST(extract_scala_chained_package_clauses);
+9 -6
View File
@@ -15367,16 +15367,19 @@ static void write_scala_companion_fixture(const char *tmp) {
}
static bool scala_companion_edges_are_exact(cbm_store_t *s, const char *project) {
return cross_file_call_to_owner_has_strategy(s, project, "half", "make", "Rational$.make",
"import_map") &&
cross_file_call_to_owner_has_strategy(s, project, "two", "fromInt", "Rational$.fromInt",
"import_map");
return cross_file_call_to_owner_has_strategy(s, project, "half", "make",
"Rational#object.make", "import_map") &&
cross_file_call_to_owner_has_strategy(s, project, "two", "fromInt",
"Rational#object.fromInt", "import_map") &&
cross_file_call_to_owner_has_strategy(s, project, "fromInt", "make",
"Rational#object.make", "");
}
/* A class with a companion object is one importable name. `import pkg.Foo`
* must not fail closed as ambiguous now that class and companion have
* distinct QNs, `Foo.factory()` must bind into the companion (`Foo$`), and
* `import pkg.Foo.member` must bind the companion member. */
* distinct QNs, `Foo.factory()` must bind into the companion (`Foo#object`),
* `import pkg.Foo.member` must bind the companion member, and a bare call
* between two members of the object stays inside it. */
TEST(pipeline_scala_companion_import_and_factory_call) {
char tmp[256];
snprintf(tmp, sizeof(tmp), "/tmp/cbm_scala_companion_XXXXXX");
+23 -43
View File
@@ -2741,39 +2741,40 @@ TEST(resolve_import_map_alias_with_suffix_hits_method) {
PASS();
}
/* Scala companion objects carry a `$` suffix on their QN. A call written on
* the class name (`Rational.make`) must reach the companion member through
* every strategy that compares owner segments: import_map, same_module and
* the qualified-tail disambiguator. Non-`$` QNs are matched exactly as before. */
/* A Scala companion object is Owner#object (CBM_SCALA_OBJECT_QN_SUFFIX). A
* call written on the class name (`Rational.make`) must reach the companion
* member through every strategy that compares owner segments: import_map,
* same_module and the qualified-tail disambiguator. Unfenced QNs are matched
* exactly as before. */
TEST(resolve_scala_companion_owner_matches_class_name) {
cbm_registry_t *r = cbm_registry_new();
cbm_registry_add_lang(r, "Rational", "proj.num.Rational.Rational", "Class", CBM_LANG_SCALA,
false);
cbm_registry_add_lang(r, "Rational", "proj.num.Rational.Rational$", "Class", CBM_LANG_SCALA,
false);
cbm_registry_add_lang(r, "make", "proj.num.Rational.Rational$.make", "Method", CBM_LANG_SCALA,
false);
cbm_registry_add_lang(r, "Rational", "proj.num.Rational.Rational#object", "Class",
CBM_LANG_SCALA, false);
cbm_registry_add_lang(r, "make", "proj.num.Rational.Rational#object.make", "Method",
CBM_LANG_SCALA, false);
cbm_registry_add_lang(r, "make", "proj.other.Builder.Builder.make", "Method", CBM_LANG_SCALA,
false);
/* import_map: the import binds the class; the method lives in Rational$ */
/* import_map: the import binds the class; the method lives in Rational#object */
const char *keys[] = {"Rational"};
const char *vals[] = {"proj.num.Rational.Rational"};
cbm_resolution_t res = cbm_registry_resolve(r, "Rational.make", "proj.app.Main", keys, vals, 1);
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational$.make");
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational#object.make");
ASSERT_STR_EQ(res.strategy, "import_map");
/* same_module: called from the declaring file */
res = cbm_registry_resolve(r, "Rational.make", "proj.num.Rational", NULL, NULL, 0);
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational$.make");
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational#object.make");
ASSERT_STR_EQ(res.strategy, "same_module");
/* qualified_suffix: two `make` candidates, the owner segment picks Rational$ */
/* qualified_suffix: two `make` candidates, the owner segment picks the object */
res = cbm_registry_resolve(r, "Rational.make", "proj.elsewhere.X", NULL, NULL, 0);
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational$.make");
ASSERT_STR_EQ(res.qualified_name, "proj.num.Rational.Rational#object.make");
ASSERT_STR_EQ(res.strategy, "qualified_suffix");
/* A plain owner does not match a `$`-less candidate any more loosely. */
/* A plain owner does not match an unfenced candidate any more loosely. */
res = cbm_registry_resolve(r, "Builder.make", "proj.elsewhere.X", NULL, NULL, 0);
ASSERT_STR_EQ(res.qualified_name, "proj.other.Builder.Builder.make");
ASSERT_STR_EQ(res.strategy, "qualified_suffix");
@@ -2783,34 +2784,14 @@ TEST(resolve_scala_companion_owner_matches_class_name) {
PASS();
}
/* The companion rules are keyed on the registry's own record of Scala
* companions, not on the `$` character: the language-less cbm_registry_add
* records nothing, and neither does a registration from a non-Scala file. */
TEST(resolve_dollar_owner_is_companion_only_when_registered_from_scala) {
cbm_registry_t *r = cbm_registry_new();
cbm_registry_add(r, "Rational", "proj.num.Rational.Rational", "Class", false);
cbm_registry_add(r, "Rational", "proj.num.Rational.Rational$", "Class", false);
cbm_registry_add(r, "make", "proj.num.Rational.Rational$.make", "Method", false);
cbm_registry_add(r, "make", "proj.other.Builder.Builder.make", "Method", false);
const char *keys[] = {"Rational"};
const char *vals[] = {"proj.num.Rational.Rational"};
cbm_resolution_t res = cbm_registry_resolve(r, "Rational.make", "proj.app.Main", keys, vals, 1);
ASSERT(res.strategy == NULL || strcmp(res.strategy, "import_map") != 0);
res = cbm_registry_resolve(r, "Rational.make", "proj.num.Rational", NULL, NULL, 0);
ASSERT(res.strategy == NULL || strcmp(res.strategy, "same_module") != 0);
res = cbm_registry_resolve(r, "Rational.make", "proj.elsewhere.X", NULL, NULL, 0);
ASSERT(res.strategy == NULL || strcmp(res.strategy, "qualified_suffix") != 0);
cbm_registry_free(r);
PASS();
}
/* `$` is a legal identifier character in Java and JS/TS (`user$` streams,
* `Foo$` helper classes), so a class `Foo$` next to `Foo` is an ordinary
* sibling there. With both registered from a Java or a TypeScript file,
* `Foo.m` resolves exactly as it does on a registry without any companion
* rule (the expectations below were taken from that registry): import_map,
* same_module and the qualified tail never reach the `$` owner's member, and
* the receiver chain does not admit it as a unique-name hit. */
/* `$` is not special: it is a legal identifier character in Java and JS/TS
* (`user$` streams, `Foo$` helper classes), so a class `Foo$` next to `Foo` is
* an ordinary sibling there, and only the Scala object fence (`#object`)
* makes `Foo.m` read as a companion member. With both registered from a Java
* or a TypeScript file, `Foo.m` resolves exactly as it does on a registry
* without any companion rule: import_map, same_module and the qualified tail
* never reach the `$` owner's member, and the receiver chain does not admit it
* as a unique-name hit. */
TEST(resolve_java_ts_dollar_class_next_to_class_is_unchanged) {
const CBMLanguage langs[] = {CBM_LANG_JAVA, CBM_LANG_TYPESCRIPT};
for (size_t li = 0; li < sizeof(langs) / sizeof(langs[0]); li++) {
@@ -3790,7 +3771,6 @@ SUITE(registry) {
RUN_TEST(resolve_import_map_aliased_from_import);
RUN_TEST(resolve_import_map_alias_with_suffix_hits_method);
RUN_TEST(resolve_scala_companion_owner_matches_class_name);
RUN_TEST(resolve_dollar_owner_is_companion_only_when_registered_from_scala);
RUN_TEST(resolve_java_ts_dollar_class_next_to_class_is_unchanged);
RUN_TEST(swift_receiver_resolution_is_independent_of_registration_order);
RUN_TEST(swift_manifest_root_targets_respect_nested_package_boundaries);