Skip to content

Commit 67ff40d

Browse files
committed
fix(kotlin): resolve calls through typed class properties (DeusData#1555)
The cross-file Kotlin walk resolved a call on a typed method parameter by type, but a call on a class property - a primary-constructor val, a body property or `this.prop` - fell to the name guess. The cross registry held each own-file class from its extraction defs, whose properties carry no type (constructor vals none at all), and the walk's typed AST registration of the same class was added behind that entry under the same QN, so every lookup returned the field-less one. Constructor injection is the common Kotlin dependency shape, so `repository.inserir(...)` on an injected port bound to whichever same-named method the guess found, including an implementation of another port (DeusData#1555). The walk now registers the file's own declarations into an overlay chained to the cross registry and checked first, indexed once the top-level declarations are collected. The sole-definer fallback walks the whole chain so its candidate set is unchanged. Typing more receivers exposed resolution gaps that the untyped receivers had hidden; each would otherwise turn a typed call into a wrong name guess: - a member of the receiver class wins over a same-named extension of the same file (Kotlin resolution order; the overlay holds both); - `x.hashCode()` / `toString()` / `equals()` on a receiver typed by another file: the per-file pass emits the kotlin.Any placeholder, the cross pass the declared override, and two targets at one occurrence are ambiguous to the call join. The per-file placeholder is dropped when the cross pass resolves the same occurrence; - the same members on a stdlib or JDK type (`count.toString()` on an Int) resolve to the kotlin.Any builtin instead of a seeded stdlib member that has no graph node; - a property READ on a typed receiver whose QN the graph spells differently (a nested class's property) never becomes a CALL_REFERENCE to a same-named function: the reference join falls back by name to non-callable targets only, which binds the property's own node; - a typed value without an `invoke` operator (`private val handshake: Handshake?`) no longer shadows the same-named member function; - inside a lambda whose typed receiver becomes `this` (`repo.let { .. }`), and inside a member extension, the enclosing class's members stay callable bare (the implicit-receiver chain); a call naming a class stays a constructor call. Fixes DeusData#1555 Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent 354ccec commit 67ff40d

9 files changed

Lines changed: 628 additions & 15 deletions

File tree

‎Makefile.cbm‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -846,7 +846,7 @@ TEST_PY_LSP_SCALE_SRCS = tests/test_py_lsp_scale.c
846846

847847
TEST_TS_LSP_SRCS = tests/test_ts_lsp.c
848848
TEST_JAVA_LSP_SRCS = tests/test_java_lsp.c tests/test_java_lsp_coverage.c
849-
TEST_KOTLIN_LSP_SRCS = tests/test_kotlin_lsp.c
849+
TEST_KOTLIN_LSP_SRCS = tests/test_kotlin_lsp.c tests/test_kotlin_typed_calls.c
850850
TEST_RUST_LSP_SRCS = tests/test_rust_lsp.c
851851

852852
TEST_INTEGRATION_SRCS = tests/test_integration.c tests/test_incremental.c tests/test_lang_contract.c tests/test_edge_imports.c tests/test_edge_structural.c tests/test_lsp_resolution_probe.c tests/test_node_creation_probe.c tests/test_edge_types_probe.c tests/test_convergence_probe.c tests/test_matrix_known_classes.c tests/test_matrix_new_constructs.c tests/test_grammar_probe_a.c tests/test_grammar_probe_b.c tests/test_grammar_probe_c.c tests/test_grammar_probe_d.c tests/test_grammar_probe_e.c tests/test_grammar_probe_f.c tests/test_grammar_probe_g.c tests/test_conditional_variants.c tests/test_spawns.c

‎internal/cbm/lsp/kotlin_lsp.c‎

Lines changed: 156 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -395,9 +395,47 @@ static const CBMType *kt_unwrap_nullable(const CBMType *t) {
395395
return t;
396396
}
397397

398+
/* A kotlin.Any member (toString / equals / hashCode) resolved on a stdlib or
399+
* JDK type -- `count.toString()` on `val count: Int` binds kotlin.Int.toString
400+
* from the stdlib seed. That target has no graph node, so the call join fell
401+
* back to a name guess and bound the call to whichever project class declares
402+
* a same-named override (#1555: detekt `defaultValue.toString()` ->
403+
* Entity.toString). The member is the universal kotlin.Any one, an external
404+
* builtin node: emit that, no project edge. `kotlin.` and `java.` are reserved
405+
* packages (the compilers reject project declarations in them), so the prefix
406+
* proves the owner is not a project type; project QNs in this resolver are
407+
* package-spelled and keep their declared override. */
408+
static bool kt_is_any_member(const char *name) {
409+
return strcmp(name, "toString") == 0 || strcmp(name, "equals") == 0 ||
410+
strcmp(name, "hashCode") == 0;
411+
}
412+
413+
static const char *kt_external_any_member(KotlinLSPContext *ctx, const char *callee_qn) {
414+
const char *dot = strrchr(callee_qn, '.');
415+
if (!dot || !kt_is_any_member(dot + 1)) {
416+
return NULL;
417+
}
418+
if (strncmp(callee_qn, "kotlin.Any.", strlen("kotlin.Any.")) == 0) {
419+
return NULL; /* already the builtin */
420+
}
421+
if (strncmp(callee_qn, "kotlin.", strlen("kotlin.")) != 0 &&
422+
strncmp(callee_qn, "java.", strlen("java.")) != 0) {
423+
return NULL; /* a project override: a real node */
424+
}
425+
return kt_join_dot(ctx->arena, "kotlin.Any", dot + 1);
426+
}
427+
398428
/* Append a typed resolution result to the output array. */
399429
static void kt_emit_resolved_kind(KotlinLSPContext *ctx, const char *callee_qn,
400430
const char *strategy, float confidence, CBMResolvedKind kind) {
431+
if (kind == CBM_RESOLVED_INVOCATION && callee_qn) {
432+
const char *any_qn = kt_external_any_member(ctx, callee_qn);
433+
if (any_qn) {
434+
callee_qn = any_qn;
435+
strategy = "lsp_kt_any";
436+
confidence = confidence < KT_CONF_PARTIAL ? confidence : KT_CONF_PARTIAL;
437+
}
438+
}
401439
if (ctx->debug) {
402440
fprintf(stderr, "[kotlin_lsp] EMIT %s -> %s [%s %.2f] (resolved_calls=%p enc=%s)\n",
403441
ctx->enclosing_func_qn ? ctx->enclosing_func_qn : "(null)",
@@ -1127,20 +1165,26 @@ const char *kotlin_resolve_function_name(KotlinLSPContext *ctx, const char *name
11271165
* package/import/bare/default-import lookups miss, so it never overrides a
11281166
* more specific match; in the per-file pass the registry holds just this
11291167
* file's defs, so the candidate is the file's own sole top-level fun. */
1130-
if (ctx->registry && ctx->registry->funcs) {
1168+
/* The cross-file walk runs on an own-file overlay chained to the cross
1169+
* registry (#1555), so the candidates span the whole chain; a function
1170+
* registered in both layers under one QN is one candidate. */
1171+
{
11311172
const char *only_qn = NULL;
11321173
int matches = 0;
1133-
for (int i = 0; i < ctx->registry->func_count && matches < 2; i++) {
1134-
const CBMRegisteredFunc *f = &ctx->registry->funcs[i];
1135-
if (!f->qualified_name || !f->short_name) {
1136-
continue;
1137-
}
1138-
if (f->receiver_type) { /* method / extension — not a bare top-level fun */
1139-
continue;
1140-
}
1141-
if (strcmp(f->short_name, name) == 0) {
1142-
only_qn = f->qualified_name;
1143-
matches++;
1174+
for (const CBMTypeRegistry *r = ctx->registry; r && matches < 2; r = r->fallback) {
1175+
for (int i = 0; r->funcs && i < r->func_count && matches < 2; i++) {
1176+
const CBMRegisteredFunc *f = &r->funcs[i];
1177+
if (!f->qualified_name || !f->short_name) {
1178+
continue;
1179+
}
1180+
if (f->receiver_type) { /* method / extension — not a bare top-level fun */
1181+
continue;
1182+
}
1183+
if (strcmp(f->short_name, name) == 0 &&
1184+
!(only_qn && strcmp(only_qn, f->qualified_name) == 0)) {
1185+
only_qn = f->qualified_name;
1186+
matches++;
1187+
}
11441188
}
11451189
}
11461190
if (matches == 1 && only_qn) {
@@ -1335,6 +1379,22 @@ const CBMRegisteredFunc *kotlin_lookup_method(KotlinLSPContext *ctx, const char
13351379
const CBMRegisteredFunc *rf =
13361380
cbm_registry_lookup_method_aliased(ctx->registry, cur_qn, method_name);
13371381
if (rf) {
1382+
/* A member wins over an extension of the same name (Kotlin
1383+
* resolution). The file's own extension functions carry the
1384+
* extended class as receiver_type, so the receiver lookup can
1385+
* return `fun Builder.add(..)` for a call meant for the member
1386+
* `Builder.add`; the member's QN nests under the class. */
1387+
size_t cur_len = strlen(cur_qn);
1388+
bool is_member = rf->qualified_name &&
1389+
strncmp(rf->qualified_name, cur_qn, cur_len) == 0 &&
1390+
rf->qualified_name[cur_len] == '.';
1391+
if (!is_member) {
1392+
const CBMRegisteredFunc *member = cbm_registry_lookup_func(
1393+
ctx->registry, kt_join_dot(ctx->arena, cur_qn, method_name));
1394+
if (member) {
1395+
return member;
1396+
}
1397+
}
13381398
return rf;
13391399
}
13401400

@@ -2907,6 +2967,37 @@ const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {
29072967
return result ? result : cbm_type_unknown();
29082968
}
29092969

2970+
/* `handshake()` inside a class whose constructor declares `private val
2971+
* handshake: Handshake?` next to `override fun handshake()` (okhttp
2972+
* RealConnection): the property is in the method scope (class fields are bound
2973+
* there), but a value of a known type without an `invoke` operator is no call
2974+
* candidate, so Kotlin resolves the call to the member function. Once #1555
2975+
* typed the class's constructor vals, the lexical-shadow rule below failed
2976+
* such calls closed and they fell to a name guess. An unknown or callable
2977+
* binding still shadows, as before. */
2978+
static bool kt_value_binding_yields_to_member(KotlinLSPContext *ctx, const CBMType *bound,
2979+
const char *name) {
2980+
if (!bound || cbm_type_is_unknown(bound) || bound->kind == CBM_TYPE_CALLABLE ||
2981+
bound->kind == CBM_TYPE_FUNC || !ctx->this_type || cbm_type_is_unknown(ctx->this_type)) {
2982+
return false;
2983+
}
2984+
const CBMType *value = kt_unwrap_nullable(bound);
2985+
const char *value_qn = kt_type_qn_of(value);
2986+
if (value_qn && kotlin_lookup_method(ctx, value_qn, "invoke")) {
2987+
return false; /* an invokable value: the call may be `value.invoke()` */
2988+
}
2989+
const char *this_qn = kt_type_qn_of(ctx->this_type);
2990+
if (!this_qn) {
2991+
return false;
2992+
}
2993+
const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, this_qn, name);
2994+
if (!rf || !rf->qualified_name) {
2995+
return false;
2996+
}
2997+
size_t len = strlen(this_qn);
2998+
return strncmp(rf->qualified_name, this_qn, len) == 0 && rf->qualified_name[len] == '.';
2999+
}
3000+
29103001
static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TSNode call_node,
29113002
const char *callee_text) {
29123003
/* callee_text is a bare identifier — it may be:
@@ -2944,7 +3035,10 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
29443035
bound->data.func.return_types[0]) {
29453036
return bound->data.func.return_types[0];
29463037
}
2947-
return cbm_type_unknown();
3038+
if (!kt_value_binding_yields_to_member(ctx, bound, callee_text)) {
3039+
return cbm_type_unknown();
3040+
}
3041+
/* A known non-invokable value yields to the member function: step 1. */
29483042
}
29493043

29503044
/* 1. `this`-method dispatch: if we're inside a class method or DSL
@@ -2967,6 +3061,37 @@ static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TS
29673061
}
29683062
}
29693063

3064+
/* 1b. Implicit receivers form a chain, innermost first: inside a lambda
3065+
* whose receiver (or `it` type, which kt_process_lambda also installs as
3066+
* `this`) is another type, and inside a member extension whose extension
3067+
* receiver is another type, the enclosing class's members stay callable
3068+
* bare. Once #1555 typed more receivers, `repo.let { ping() }` resolved
3069+
* against Repo only and fell to a name guess. A call naming a class is a
3070+
* constructor call, left to step 2 (a secondary constructor is registered
3071+
* as a same-named member and would otherwise be taken for a method). */
3072+
const char *ctor_cls = kotlin_resolve_class_name(ctx, callee_text);
3073+
bool is_ctor_call =
3074+
ctor_cls && ctx->registry && cbm_registry_lookup_type(ctx->registry, ctor_cls) != NULL;
3075+
if (ctx->enclosing_class_qn && !is_ctor_call) {
3076+
const char *this_qn = (ctx->this_type && !cbm_type_is_unknown(ctx->this_type))
3077+
? kt_type_qn_of(ctx->this_type)
3078+
: NULL;
3079+
if (!this_qn || strcmp(this_qn, ctx->enclosing_class_qn) != 0) {
3080+
const CBMRegisteredFunc *rf =
3081+
kotlin_lookup_method(ctx, ctx->enclosing_class_qn, callee_text);
3082+
if (rf && rf->qualified_name) {
3083+
kt_emit_resolved_at(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS,
3084+
call_node);
3085+
if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&
3086+
rf->signature->data.func.return_types &&
3087+
rf->signature->data.func.return_types[0]) {
3088+
return rf->signature->data.func.return_types[0];
3089+
}
3090+
return cbm_type_unknown();
3091+
}
3092+
}
3093+
}
3094+
29703095
/* 2. Class? */
29713096
const char *cls_qn = kotlin_resolve_class_name(ctx, callee_text);
29723097
if (cls_qn && ctx->registry) {
@@ -4533,6 +4658,11 @@ void kotlin_lsp_process_file(KotlinLSPContext *ctx, TSNode root) {
45334658

45344659
/* 2. Collect top-level definitions for intra-file resolution. */
45354660
kt_collect_top_level_decls(ctx, root);
4661+
/* Cross-file: index the own-file overlay now that its declarations are
4662+
* in; later additions stay visible through the post-finalize tail. */
4663+
if (ctx->overlay_index_arena && ctx->registry) {
4664+
cbm_registry_finalize_into((CBMTypeRegistry *)ctx->registry, ctx->overlay_index_arena);
4665+
}
45364666

45374667
/* 3. Walk for call resolution. */
45384668
kt_walk_top_level_for_resolution(ctx, root, NULL);
@@ -5436,12 +5566,24 @@ void cbm_run_kotlin_lsp_cross(CBMArena *arena, const char *source, int source_le
54365566
project_name = module_qn;
54375567
}
54385568

5569+
/* Own-file overlay (#1555). The cross registry above already holds this
5570+
* file's classes, built from extraction defs whose properties carry no
5571+
* type (primary-constructor vals none at all). The walk re-registers each
5572+
* class from the AST with typed fields; registered into `reg` under the
5573+
* same QN that entry was shadowed by the earlier one, so every
5574+
* `repository.inserir()` on an injected property fell to the name guess.
5575+
* In an overlay checked first, the AST entry wins. */
5576+
CBMTypeRegistry overlay;
5577+
cbm_registry_init(&overlay, arena);
5578+
overlay.fallback = &reg;
5579+
54395580
KotlinLSPContext ctx;
54405581
/* Match the per-file pass: until a source package declaration overrides
54415582
* it, the path-derived module is the callable-QN prefix. This preserves
54425583
* exact caller identity for default-package functions across files. */
5443-
kotlin_lsp_init(&ctx, arena, source, source_len, &reg, module_qn ? module_qn : "",
5584+
kotlin_lsp_init(&ctx, arena, source, source_len, &overlay, module_qn ? module_qn : "",
54445585
module_qn ? module_qn : "", project_name, /*rel_path=*/NULL, out);
5586+
ctx.overlay_index_arena = &idx_arena;
54455587

54465588
/* Unique short type name -> registered QN, for receiver annotations that
54475589
* name a type defined in another file without an import. Two types

‎internal/cbm/lsp/kotlin_lsp.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ typedef struct KotlinLSPContext {
147147
* each field's REAL def QN here (kotlin class properties are minted with
148148
* module-level QNs, so composing <class>.<member> would miss the node). */
149149
const void *cross_field_map;
150+
/* Cross-file only (NULL per-file): when set, `registry` is a per-file
151+
* overlay chained to the cross registry, and kotlin_lsp_process_file
152+
* indexes the overlay into this scratch arena once the file's own
153+
* declarations are collected. The overlay holds the AST registrations
154+
* (typed primary-constructor and body properties), so they are found
155+
* before the extraction-built entries of the same QN (#1555). */
156+
CBMArena *overlay_index_arena;
150157
} KotlinLSPContext;
151158

152159
/* Initialize a KotlinLSPContext for processing one file. */

‎src/pipeline/lsp_resolve.h‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,24 @@ static inline bool cbm_pipeline_node_is_callable_target(const cbm_gbuf_node_t *n
223223
strcmp(node->label, "Constructor") == 0 || strcmp(node->label, "Class") == 0;
224224
}
225225

226+
/* The Kotlin resolver claims a property READ on a typed receiver with an exact
227+
* row (lsp_kt_property_ref) so that the raw-name fallback cannot borrow a
228+
* same-named function. That row names a property, never a function value. Its
229+
* QN is not always materialized under that spelling (a property of a nested
230+
* class); the graph lookup then finds nothing, or its unique-callable step
231+
* picks a same-named function elsewhere (#1555: okhttp `server.webSocket` -> a
232+
* test function `webSocket`, a fabricated CALL_REFERENCE). Such a row is not
233+
* admissible: the caller falls back by name, restricted to non-callable
234+
* targets, which binds the property's own node as before the receiver was
235+
* typed and can never borrow a function. */
236+
static inline bool cbm_pipeline_reference_target_admissible(const CBMResolvedCall *ref,
237+
const cbm_gbuf_node_t *tgt) {
238+
if (!ref || !ref->strategy || strcmp(ref->strategy, "lsp_kt_property_ref") != 0) {
239+
return true;
240+
}
241+
return tgt && !cbm_pipeline_node_is_callable_target(tgt);
242+
}
243+
226244
static inline int cbm_pipeline_qn_class_method_tail_eq(const char *qn, const char *tail) {
227245
const char *qt = cbm_pipeline_qn_class_method_tail(qn);
228246
return qt && tail && strcmp(qt, tail) == 0;

‎src/pipeline/pass_lsp_cross.c‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1285,6 +1285,68 @@ static void pxc_supersede_occurrence(CBMArena *dst_arena, CBMResolvedCallArray *
12851285
dst_calls->count = kept;
12861286
}
12871287

1288+
/* The Kotlin universal-member placeholder: `x.hashCode()` / `toString()` /
1289+
* `equals()` on a receiver the resolver could not type is emitted on kotlin.Any
1290+
* (strategy lsp_kt_any, reduced confidence) -- the "no narrower receiver known"
1291+
* answer. */
1292+
static bool pxc_is_kt_any_placeholder(const CBMResolvedCall *rc) {
1293+
return rc->strategy && strcmp(rc->strategy, "lsp_kt_any") == 0;
1294+
}
1295+
1296+
static char *pxc_occurrence_key(CBMArena *keys, const CBMResolvedCall *rc) {
1297+
return cbm_arena_sprintf(keys, "%u\x1f%s\x1f%u:%u\x1f%u", (unsigned)rc->kind, rc->caller_qn,
1298+
rc->site_start_byte, rc->site_end_byte, (unsigned)rc->source_origin);
1299+
}
1300+
1301+
/* #1555: the per-file pass sees only the file's own declarations, so a receiver
1302+
* typed by another file (`val type: ProtoType`) is unknown there and
1303+
* `type.hashCode()` gets the kotlin.Any placeholder. The cross pass types the
1304+
* receiver and answers with the declared override (`ProtoType.hashCode`), or
1305+
* with kotlin.Any again when no class on the receiver's chain declares one. Two
1306+
* distinct targets at one occurrence are a tombstone in the call join
1307+
* (pass_parallel.c LSP_IDX_AMBIGUOUS), so the occurrence fell to the name-based
1308+
* registry guess (wire: `type.hashCode` -> AllTypes.hashCode). A placeholder is
1309+
* therefore dropped when a cross row resolves the same occurrence; the cross row
1310+
* is then the only evidence. One hash pass per side keeps this linear. */
1311+
static void pxc_drop_superseded_kt_any(CBMArena *keys, CBMResolvedCallArray *dst_calls,
1312+
const CBMResolvedCallArray *src_out) {
1313+
bool has_placeholder = false;
1314+
for (int i = 0; i < dst_calls->count && !has_placeholder; i++) {
1315+
has_placeholder = pxc_is_kt_any_placeholder(&dst_calls->items[i]);
1316+
}
1317+
if (!has_placeholder) {
1318+
return;
1319+
}
1320+
CBMHashTable *resolved = cbm_ht_create((uint32_t)src_out->count + 1);
1321+
for (int j = 0; j < src_out->count; j++) {
1322+
const CBMResolvedCall *src = &src_out->items[j];
1323+
if (!src->caller_qn || !src->callee_qn || pxc_is_kt_any_placeholder(src) ||
1324+
src->site_end_byte <= src->site_start_byte) {
1325+
continue;
1326+
}
1327+
char *k = pxc_occurrence_key(keys, src);
1328+
if (k) {
1329+
cbm_ht_set(resolved, k, (void *)(uintptr_t)1);
1330+
}
1331+
}
1332+
int kept = 0;
1333+
for (int i = 0; i < dst_calls->count; i++) {
1334+
const CBMResolvedCall *cur = &dst_calls->items[i];
1335+
if (pxc_is_kt_any_placeholder(cur) && cur->caller_qn) {
1336+
char *k = pxc_occurrence_key(keys, cur);
1337+
if (k && cbm_ht_get(resolved, k)) {
1338+
continue;
1339+
}
1340+
}
1341+
if (kept != i) {
1342+
dst_calls->items[kept] = *cur;
1343+
}
1344+
kept++;
1345+
}
1346+
dst_calls->count = kept;
1347+
cbm_ht_free(resolved);
1348+
}
1349+
12881350
static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_calls,
12891351
const CBMResolvedCallArray *src_out) {
12901352
if (!dst_calls || !src_out)
@@ -1312,6 +1374,7 @@ static void pxc_append_results(CBMArena *dst_arena, CBMResolvedCallArray *dst_ca
13121374
}
13131375
pxc_supersede_occurrence(dst_arena, dst_calls, src);
13141376
}
1377+
pxc_drop_superseded_kt_any(&keys, dst_calls, src_out);
13151378

13161379
for (int i = 0; i < dst_calls->count; i++) {
13171380
const CBMResolvedCall *rc = &dst_calls->items[i];

0 commit comments

Comments
 (0)