Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
Add Kotlin hybrid LSP resolver
Martin Vogelfd6c003dfc93
diff --git a/Makefile.cbm b/Makefile.cbmindex 03ef78398..f45a88755 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -334,6 +334,7 @@ TEST_PY_LSP_SCALE_SRCS = tests/test_py_lsp_scale.cTEST_TS_LSP_SRCS = tests/test_ts_lsp.cTEST_JAVA_LSP_SRCS = tests/test_java_lsp.c tests/test_java_lsp_coverage.c+TEST_KOTLIN_LSP_SRCS = tests/test_kotlin_lsp.cTEST_INTEGRATION_SRCS = tests/test_integration.c tests/test_incremental.c@@ -354,7 +355,7 @@ TEST_SIMHASH_SRCS = tests/test_simhash.cTEST_STACK_OVERFLOW_SRCS = tests/test_stack_overflow.c-ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_ZSTD_SRCS) $(TEST_ARTIFACT_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_PHP_LSP_SRCS) $(TEST_CS_LSP_SRCS) $(TEST_CS_LSP_BENCH_SRCS) $(TEST_SCOPE_SRCS) $(TEST_TYPE_REP_SRCS) $(TEST_PY_LSP_SRCS) $(TEST_PY_LSP_BENCH_SRCS) $(TEST_PY_LSP_STRESS_SRCS) $(TEST_PY_LSP_SCALE_SRCS) $(TEST_TS_LSP_SRCS) $(TEST_JAVA_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)+ALL_TEST_SRCS = $(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DISCOVER_SRCS) $(TEST_GRAPH_BUFFER_SRCS) $(TEST_PIPELINE_SRCS) $(TEST_WATCHER_SRCS) $(TEST_LZ4_SRCS) $(TEST_ZSTD_SRCS) $(TEST_ARTIFACT_SRCS) $(TEST_SQLITE_WRITER_SRCS) $(TEST_GO_LSP_SRCS) $(TEST_C_LSP_SRCS) $(TEST_PHP_LSP_SRCS) $(TEST_CS_LSP_SRCS) $(TEST_CS_LSP_BENCH_SRCS) $(TEST_SCOPE_SRCS) $(TEST_TYPE_REP_SRCS) $(TEST_PY_LSP_SRCS) $(TEST_PY_LSP_BENCH_SRCS) $(TEST_PY_LSP_STRESS_SRCS) $(TEST_PY_LSP_SCALE_SRCS) $(TEST_TS_LSP_SRCS) $(TEST_JAVA_LSP_SRCS) $(TEST_KOTLIN_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)# ── Build directories ────────────────────────────────────────────diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex bde5002c0..0ab5a73ea 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -10,6 +10,7 @@#include "lsp/ts_lsp.h"#include "lsp/cs_lsp.h"#include "lsp/java_lsp.h"+#include "lsp/kotlin_lsp.h"#include "preprocessor.h"#include "foundation/compat.h"#include "tree_sitter/api.h" // TSParser, TSNode, TSTree, TSInput, TSLanguage, TSPoint, TSParseOptions, TSParseState@@ -507,6 +508,9 @@ CBMFileResult *cbm_extract_file(const char *source, int source_len, CBMLanguageif (language == CBM_LANG_JAVA) {cbm_run_java_lsp(a, result, source, source_len, root);}+ if (language == CBM_LANG_KOTLIN) {+ cbm_run_kotlin_lsp(a, result, source, source_len, root);+ }atomic_fetch_add(&total_lsp_ns, now_ns() - lsp_start);// Calls extracted so far all carry ORIGINAL-source line numbers; the C/C++diff --git a/internal/cbm/lsp/generated/kotlin_stdlib_data.c b/internal/cbm/lsp/generated/kotlin_stdlib_data.cnew file mode 100644index 000000000..60ddbf71c--- /dev/null+++ b/internal/cbm/lsp/generated/kotlin_stdlib_data.c@@ -0,0 +1,517 @@+/*+ * kotlin_stdlib_data.c — Curated Kotlin stdlib registration for the LSP.+ *+ * Hand-distilled subset of the Kotlin standard library: the types and+ * functions that account for the vast majority of real-world usages.+ * The reverse-engineered LSP relies on this to resolve calls into+ * `kotlin.*`, `kotlin.collections.*`, `kotlin.text.*`, `kotlin.io.*`,+ * `kotlin.ranges.*`, `kotlin.sequences.*`, and a few `java.lang.*` /+ * `java.util.*` types reachable from default imports under the JVM+ * target.+ *+ * Source of truth: the Kotlin language specification + kotlin-stdlib API+ * docs (1.9.x). We do NOT vendor or fetch any new source — all type+ * shapes here were transcribed by hand from the public spec to match+ * the resolver's expectations.+ *+ * This file is included from lsp_all.c.+ */++#include "../type_rep.h"+#include "../type_registry.h"+#include "../kotlin_lsp.h"+#include <string.h>++/* Convenience macros to compress the repetitive registration calls. */++#define KT_TYPE_SIMPLE(qn_, short_) \+ do { \+ CBMRegisteredType rt = {0}; \+ rt.qualified_name = (qn_); \+ rt.short_name = (short_); \+ cbm_registry_add_type(reg, rt); \+ } while (0)++#define KT_TYPE_WITH_METHODS(qn_, short_, methods_) \+ do { \+ CBMRegisteredType rt = {0}; \+ rt.qualified_name = (qn_); \+ rt.short_name = (short_); \+ rt.method_names = (methods_); \+ cbm_registry_add_type(reg, rt); \+ } while (0)++#define KT_FUNC0(qn_, short_, ret_qn_) \+ do { \+ CBMRegisteredFunc rf = {0}; \+ rf.qualified_name = (qn_); \+ rf.short_name = (short_); \+ rf.min_params = 0; \+ cbm_registry_add_func(reg, rf); \+ (void)(ret_qn_); \+ } while (0)++#define KT_METHOD(class_qn_, method_qn_, short_) \+ do { \+ CBMRegisteredFunc rf = {0}; \+ rf.qualified_name = (method_qn_); \+ rf.receiver_type = (class_qn_); \+ rf.short_name = (short_); \+ rf.min_params = 0; \+ cbm_registry_add_func(reg, rf); \+ } while (0)++/* Default-imported package list, exposed to the LSP context for+ * wildcard-style resolution of bare names (e.g. `println` resolves into+ * `kotlin.io`). Order matters: more-specific shadows less-specific. */+static const char *const KT_DEFAULT_IMPORTS[] = {+ "kotlin",+ "kotlin.annotation",+ "kotlin.collections",+ "kotlin.comparisons",+ "kotlin.io",+ "kotlin.ranges",+ "kotlin.sequences",+ "kotlin.text",+ /* JVM target adds: */+ "java.lang",+ "kotlin.jvm",+};++const char *const *cbm_kotlin_default_import_packages(int *count_out) {+ if (count_out) {+ *count_out = (int)(sizeof(KT_DEFAULT_IMPORTS) / sizeof(KT_DEFAULT_IMPORTS[0]));+ }+ return KT_DEFAULT_IMPORTS;+}++/* Method-name tables (NULL-terminated). Used for is_member checks+ * — the resolver walks these to decide whether `obj.foo()` should+ * be attributed as a method call on a known type. */++static const char *KT_ANY_METHODS[] = {+ "equals", "hashCode", "toString", NULL,+};++static const char *KT_STRING_METHODS[] = {+ "length", "isEmpty", "isNotEmpty", "isBlank", "isNotBlank", "compareTo", "contains",+ "startsWith", "endsWith", "indexOf", "lastIndexOf", "substring", "replace", "split",+ "trim", "trimStart", "trimEnd", "trimIndent", "trimMargin", "toUpperCase", "toLowerCase",+ "uppercase", "lowercase", "uppercaseChar", "lowercaseChar", "capitalize", "decapitalize",+ "reversed", "lines", "padStart", "padEnd", "repeat", "removePrefix", "removeSuffix",+ "removeSurrounding", "toByteArray", "toCharArray", "toInt", "toIntOrNull", "toLong",+ "toLongOrNull", "toDouble", "toDoubleOrNull", "toFloat", "toFloatOrNull", "toBoolean",+ "format", "intern", "matches", "replaceFirst", "filter", "filterNot", "filterIndexed",+ "map", "flatMap", "fold", "reduce", "forEach", "any", "all", "none", "count", "first",+ "firstOrNull", "last", "lastOrNull", "single", "singleOrNull", "take", "takeLast",+ "takeWhile", "drop", "dropLast", "dropWhile", "windowed", "chunked", "zip", "associate",+ "associateBy", "associateWith", "groupBy", "partition", "joinToString", "iterator",+ "subSequence", "get", "set", "plus", "minus", "times", "div", "rem", "compareTo",+ "hashCode", "toString", "equals", NULL,+};++static const char *KT_LIST_METHODS[] = {+ "size", "isEmpty", "contains", "containsAll", "iterator", "listIterator", "subList",+ "indexOf", "lastIndexOf", "get", "first", "firstOrNull", "last", "lastOrNull", "single",+ "singleOrNull", "elementAt", "elementAtOrNull", "elementAtOrElse", "find", "findLast",+ "filter", "filterNot", "filterNotNull", "filterIndexed", "filterIsInstance", "map",+ "mapNotNull", "mapIndexed", "mapIndexedNotNull", "flatMap", "flatten", "fold", "foldRight",+ "foldIndexed", "reduce", "reduceRight", "reduceIndexed", "scan", "runningFold",+ "runningReduce", "forEach", "forEachIndexed", "any", "all", "none", "count", "sum",+ "sumBy", "sumOf", "max", "maxOrNull", "maxBy", "maxByOrNull", "maxOf", "maxOfOrNull",+ "min", "minOrNull", "minBy", "minByOrNull", "minOf", "minOfOrNull", "average", "sorted",+ "sortedBy", "sortedDescending", "sortedByDescending", "sortedWith", "reversed",+ "shuffled", "distinct", "distinctBy", "intersect", "union", "subtract", "groupBy",+ "groupingBy", "associate", "associateBy", "associateWith", "partition", "windowed",+ "chunked", "zip", "zipWithNext", "joinToString", "joinTo", "take", "takeLast",+ "takeWhile", "takeLastWhile", "drop", "dropLast", "dropWhile", "dropLastWhile",+ "asSequence", "asIterable", "toList", "toMutableList", "toSet", "toMutableSet",+ "toHashSet", "toSortedSet", "toTypedArray", "toCollection", "plus", "minus",+ "ifEmpty", "stream", NULL,+};++static const char *KT_MUTABLE_LIST_METHODS[] = {+ "add", "addAll", "remove", "removeAt", "removeAll", "removeFirst", "removeLast",+ "removeIf", "retainAll", "clear", "set", "fill", "sort", "sortBy", "sortByDescending",+ "sortWith", "reverse", "shuffle", "swap", "trimToSize",+ /* Plus all read-only methods (inherited): */+ "size", "isEmpty", "contains", "containsAll", "iterator", "listIterator", "subList",+ "indexOf", "lastIndexOf", "get", "first", "firstOrNull", "last", "lastOrNull", "single",+ "singleOrNull", "find", "findLast", "elementAt", "elementAtOrNull", "elementAtOrElse",+ "filter", "filterNot", "filterNotNull", "filterIndexed", "filterIsInstance", "map",+ "mapNotNull", "mapIndexed", "flatMap", "flatten", "fold", "foldRight", "reduce",+ "reduceRight", "forEach", "forEachIndexed", "any", "all", "none", "count", "sum",+ "sumBy", "sumOf", "max", "maxOrNull", "maxBy", "min", "minOrNull", "minBy", "average",+ "sorted", "sortedBy", "sortedDescending", "sortedByDescending", "sortedWith",+ "reversed", "shuffled", "distinct", "distinctBy", "groupBy", "groupingBy", "associate",+ "associateBy", "associateWith", "partition", "windowed", "chunked", "zip", "zipWithNext",+ "joinToString", "joinTo", "take", "takeLast", "takeWhile", "drop", "dropLast",+ "dropWhile", "asSequence", "asIterable", "toList", "toMutableList", "toSet",+ "toMutableSet", "toHashSet", "toTypedArray", "toCollection", "ifEmpty", "stream", NULL,+};++static const char *KT_MAP_METHODS[] = {+ "size", "isEmpty", "containsKey", "containsValue", "get", "getOrDefault", "getOrElse",+ "getOrNull", "getValue", "keys", "values", "entries", "iterator", "forEach", "filter",+ "filterKeys", "filterValues", "filterNot", "filterTo", "map", "mapKeys", "mapValues",+ "mapNotNull", "any", "all", "none", "count", "max", "min", "maxBy", "minBy", "toList",+ "toMap", "toMutableMap", "toSortedMap", "asSequence", "asIterable", "plus", "minus",+ "ifEmpty", NULL,+};++static const char *KT_MUTABLE_MAP_METHODS[] = {+ "put", "putAll", "putIfAbsent", "remove", "clear", "computeIfAbsent", "computeIfPresent",+ "compute", "merge", "replace", "replaceAll", "getOrPut",+ /* Plus read-only methods: */+ "size", "isEmpty", "containsKey", "containsValue", "get", "keys", "values", "entries",+ "iterator", "forEach", "filter", "map", NULL,+};++static const char *KT_SET_METHODS[] = {+ "size", "isEmpty", "contains", "containsAll", "iterator", "intersect", "union",+ "subtract", "filter", "map", "fold", "reduce", "forEach", "any", "all", "none",+ "count", "first", "last", "elementAt", NULL,+};++static const char *KT_ITERATOR_METHODS[] = {+ "hasNext", "next", "remove", "nextIndex", "previousIndex", "previous", "hasPrevious",+ "set", "add", NULL,+};++static const char *KT_SEQUENCE_METHODS[] = {+ "iterator", "filter", "filterNot", "filterNotNull", "filterIndexed", "filterIsInstance",+ "map", "mapNotNull", "mapIndexed", "flatMap", "flatten", "fold", "foldIndexed", "reduce",+ "reduceIndexed", "forEach", "forEachIndexed", "any", "all", "none", "count", "sum",+ "sumBy", "sumOf", "max", "maxOrNull", "min", "minOrNull", "first", "firstOrNull",+ "last", "lastOrNull", "single", "singleOrNull", "find", "findLast", "elementAt",+ "elementAtOrNull", "take", "takeWhile", "drop", "dropWhile", "windowed", "chunked",+ "zip", "zipWithNext", "distinct", "distinctBy", "sorted", "sortedBy", "sortedDescending",+ "sortedWith", "associate", "associateBy", "associateWith", "groupBy", "partition",+ "joinToString", "toList", "toSet", "toMap", "toCollection", "asIterable", "constrainOnce",+ NULL,+};++static const char *KT_INT_RANGE_METHODS[] = {+ "first", "last", "step", "isEmpty", "iterator", "contains", "reversed", "forEach",+ "map", "filter", "sum", "count", "any", "all", "none", "elementAt", NULL,+};++static const char *KT_PAIR_METHODS[] = {+ "first", "second", "toString", "toList", "component1", "component2", "copy",+ NULL,+};++static const char *KT_TRIPLE_METHODS[] = {+ "first", "second", "third", "toString", "toList", "component1", "component2",+ "component3", "copy", NULL,+};++static const char *KT_THROWABLE_METHODS[] = {+ "message", "cause", "stackTrace", "stackTraceToString", "printStackTrace",+ "addSuppressed", "getSuppressed", "fillInStackTrace", "initCause", "toString", NULL,+};++static const char *KT_EXCEPTION_METHODS[] = {+ "message", "cause", "stackTrace", "stackTraceToString", "printStackTrace", "toString",+ NULL,+};++static const char *KT_NUMBER_METHODS[] = {+ "toByte", "toShort", "toInt", "toLong", "toFloat", "toDouble", "toChar", "toString",+ "compareTo", "equals", "hashCode",+ /* Operator conventions */+ "plus", "minus", "times", "div", "rem", "mod", "inc", "dec", "unaryMinus", "unaryPlus",+ "and", "or", "xor", "inv", "shl", "shr", "ushr",+ "rangeTo", "rangeUntil", "downTo", "until", "coerceAtLeast", "coerceAtMost", "coerceIn",+ NULL,+};++static const char *KT_BOOLEAN_METHODS[] = {+ "and", "or", "xor", "not", "compareTo", "toString", "equals", "hashCode", NULL,+};++static const char *KT_CHAR_METHODS[] = {+ "isDigit", "isLetter", "isLetterOrDigit", "isWhitespace", "isUpperCase", "isLowerCase",+ "uppercase", "lowercase", "uppercaseChar", "lowercaseChar", "digitToInt", "code",+ "compareTo", "toString", "equals", "hashCode", "plus", "minus", "rangeTo",+ "isHighSurrogate", "isLowSurrogate", "isSurrogate", NULL,+};++static const char *KT_ARRAY_METHODS[] = {+ "size", "get", "set", "iterator", "isEmpty", "isNotEmpty", "contains", "indexOf",+ "lastIndexOf", "first", "last", "filter", "map", "fold", "reduce", "forEach", "any",+ "all", "none", "count", "sum", "max", "min", "joinToString", "asList", "asSequence",+ "toList", "toMutableList", "toSet", "copyOf", "copyOfRange", "fill", "sort", "sorted",+ "reversed", "reverse", "binarySearch", "plus", "component1", "component2", NULL,+};++static const char *KT_REGEX_METHODS[] = {+ "matchEntire", "matches", "containsMatchIn", "find", "findAll", "replace",+ "replaceFirst", "split", "splitToSequence", "toPattern", "pattern", NULL,+};++static const char *KT_MATCH_RESULT_METHODS[] = {+ "value", "range", "groups", "groupValues", "destructured", "next", NULL,+};++static const char *KT_FILE_METHODS[] = {+ "path", "name", "parent", "exists", "isFile", "isDirectory", "isAbsolute", "length",+ "lastModified", "canRead", "canWrite", "delete", "deleteRecursively", "createNewFile",+ "mkdir", "mkdirs", "renameTo", "list", "listFiles", "walk", "walkTopDown",+ "walkBottomUp", "readText", "readLines", "readBytes", "writeText", "writeBytes",+ "appendText", "appendBytes", "useLines", "forEachLine", "bufferedReader",+ "bufferedWriter", "inputStream", "outputStream", "reader", "writer", "printWriter",+ "absolutePath", "absoluteFile", "canonicalPath", "canonicalFile", "extension",+ "nameWithoutExtension", "toPath", "toURI", "resolve", "resolveSibling", "relativeTo",+ "copyTo", "copyRecursively", "endsWith", "startsWith", "normalize", NULL,+};++static const char *KT_SCOPE_METHODS[] = {+ "let", "run", "with", "apply", "also", "takeIf", "takeUnless", "use", NULL,+};++static const char *KT_LAZY_METHODS[] = {+ "value", "isInitialized", "getValue", NULL,+};++static const char *KT_RESULT_METHODS[] = {+ "getOrNull", "exceptionOrNull", "isSuccess", "isFailure", "getOrThrow", "getOrDefault",+ "getOrElse", "fold", "map", "mapCatching", "recover", "recoverCatching", "onSuccess",+ "onFailure", NULL,+};++/* ── Top-level builtin function registration. ──────────────────────+ * We register the names that show up in the wild as bare calls and+ * route them to their kotlin.* / kotlin.io.* QNs. The resolver checks+ * in-package and class-method lookups before falling through to these.+ */++void cbm_kotlin_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena) {+ (void)arena;++ /* Core types — kotlin.* */+ KT_TYPE_WITH_METHODS("kotlin.Any", "Any", KT_ANY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Number", "Number", KT_NUMBER_METHODS);+ KT_TYPE_SIMPLE("kotlin.Unit", "Unit");+ KT_TYPE_SIMPLE("kotlin.Nothing", "Nothing");+ KT_TYPE_WITH_METHODS("kotlin.Boolean", "Boolean", KT_BOOLEAN_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Byte", "Byte", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Short", "Short", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Int", "Int", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Long", "Long", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Float", "Float", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Double", "Double", KT_NUMBER_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Char", "Char", KT_CHAR_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.String", "String", KT_STRING_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.CharSequence", "CharSequence", KT_STRING_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Throwable", "Throwable", KT_THROWABLE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Pair", "Pair", KT_PAIR_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Triple", "Triple", KT_TRIPLE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Result", "Result", KT_RESULT_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.Lazy", "Lazy", KT_LAZY_METHODS);+ KT_TYPE_SIMPLE("kotlin.Enum", "Enum");+ KT_TYPE_SIMPLE("kotlin.Function", "Function");+ KT_TYPE_SIMPLE("kotlin.KotlinVersion", "KotlinVersion");++ /* Common exceptions */+ KT_TYPE_WITH_METHODS("kotlin.Exception", "Exception", KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.RuntimeException", "RuntimeException", KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.IllegalArgumentException", "IllegalArgumentException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.IllegalStateException", "IllegalStateException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.IndexOutOfBoundsException", "IndexOutOfBoundsException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.NoSuchElementException", "NoSuchElementException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.NumberFormatException", "NumberFormatException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.NullPointerException", "NullPointerException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ClassCastException", "ClassCastException", KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.UnsupportedOperationException", "UnsupportedOperationException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ArithmeticException", "ArithmeticException",+ KT_EXCEPTION_METHODS);++ /* Collections */+ KT_TYPE_WITH_METHODS("kotlin.collections.Iterable", "Iterable", KT_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.Collection", "Collection", KT_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.MutableCollection", "MutableCollection",+ KT_MUTABLE_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.List", "List", KT_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.MutableList", "MutableList", KT_MUTABLE_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.Set", "Set", KT_SET_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.MutableSet", "MutableSet", KT_SET_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.HashSet", "HashSet", KT_SET_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.LinkedHashSet", "LinkedHashSet", KT_SET_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.Map", "Map", KT_MAP_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.MutableMap", "MutableMap", KT_MUTABLE_MAP_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.HashMap", "HashMap", KT_MUTABLE_MAP_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.LinkedHashMap", "LinkedHashMap",+ KT_MUTABLE_MAP_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.ArrayList", "ArrayList", KT_MUTABLE_LIST_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.Iterator", "Iterator", KT_ITERATOR_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.MutableIterator", "MutableIterator",+ KT_ITERATOR_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.collections.ListIterator", "ListIterator", KT_ITERATOR_METHODS);++ /* Sequences */+ KT_TYPE_WITH_METHODS("kotlin.sequences.Sequence", "Sequence", KT_SEQUENCE_METHODS);++ /* Arrays */+ KT_TYPE_WITH_METHODS("kotlin.Array", "Array", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.IntArray", "IntArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.LongArray", "LongArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.DoubleArray", "DoubleArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.FloatArray", "FloatArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ByteArray", "ByteArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ShortArray", "ShortArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.BooleanArray", "BooleanArray", KT_ARRAY_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.CharArray", "CharArray", KT_ARRAY_METHODS);++ /* Ranges */+ KT_TYPE_WITH_METHODS("kotlin.ranges.IntRange", "IntRange", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.LongRange", "LongRange", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.CharRange", "CharRange", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.IntProgression", "IntProgression", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.LongProgression", "LongProgression", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.ClosedRange", "ClosedRange", KT_INT_RANGE_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.ranges.ClosedFloatingPointRange", "ClosedFloatingPointRange",+ KT_INT_RANGE_METHODS);++ /* Text */+ KT_TYPE_WITH_METHODS("kotlin.text.Regex", "Regex", KT_REGEX_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.text.MatchResult", "MatchResult", KT_MATCH_RESULT_METHODS);+ KT_TYPE_WITH_METHODS("kotlin.text.StringBuilder", "StringBuilder", KT_STRING_METHODS);++ /* IO (java.io.File is reachable through kotlin.io extension functions) */+ KT_TYPE_WITH_METHODS("java.io.File", "File", KT_FILE_METHODS);+ KT_TYPE_WITH_METHODS("java.io.PrintStream", "PrintStream", KT_FILE_METHODS);++ /* java.lang basics that come in via default JVM imports */+ KT_TYPE_WITH_METHODS("java.lang.String", "String", KT_STRING_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.Object", "Object", KT_ANY_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.Throwable", "Throwable", KT_THROWABLE_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.Exception", "Exception", KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.RuntimeException", "RuntimeException", KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.IllegalArgumentException", "IllegalArgumentException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.IllegalStateException", "IllegalStateException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_WITH_METHODS("java.lang.NumberFormatException", "NumberFormatException",+ KT_EXCEPTION_METHODS);+ KT_TYPE_SIMPLE("java.lang.System", "System");+ KT_TYPE_SIMPLE("java.lang.Math", "Math");+ KT_TYPE_SIMPLE("java.lang.Integer", "Integer");+ KT_TYPE_SIMPLE("java.lang.Long", "Long");+ KT_TYPE_SIMPLE("java.lang.Double", "Double");+ KT_TYPE_SIMPLE("java.lang.Float", "Float");+ KT_TYPE_SIMPLE("java.lang.Boolean", "Boolean");++ /* ── Top-level functions ── */+ /* kotlin.io */+ KT_FUNC0("kotlin.io.println", "println", "kotlin.Unit");+ KT_FUNC0("kotlin.io.print", "print", "kotlin.Unit");+ KT_FUNC0("kotlin.io.readLine", "readLine", "kotlin.String");+ KT_FUNC0("kotlin.io.readln", "readln", "kotlin.String");+ KT_FUNC0("kotlin.io.readlnOrNull", "readlnOrNull", "kotlin.String");++ /* kotlin (root) */+ KT_FUNC0("kotlin.error", "error", "kotlin.Nothing");+ KT_FUNC0("kotlin.check", "check", "kotlin.Unit");+ KT_FUNC0("kotlin.checkNotNull", "checkNotNull", "kotlin.Any");+ KT_FUNC0("kotlin.require", "require", "kotlin.Unit");+ KT_FUNC0("kotlin.requireNotNull", "requireNotNull", "kotlin.Any");+ KT_FUNC0("kotlin.assert", "assert", "kotlin.Unit");+ KT_FUNC0("kotlin.TODO", "TODO", "kotlin.Nothing");+ KT_FUNC0("kotlin.runCatching", "runCatching", "kotlin.Result");+ KT_FUNC0("kotlin.run", "run", "kotlin.Any");+ KT_FUNC0("kotlin.with", "with", "kotlin.Any");+ KT_FUNC0("kotlin.repeat", "repeat", "kotlin.Unit");+ KT_FUNC0("kotlin.synchronized", "synchronized", "kotlin.Any");+ KT_FUNC0("kotlin.lazy", "lazy", "kotlin.Lazy");+ KT_FUNC0("kotlin.lazyOf", "lazyOf", "kotlin.Lazy");+ KT_FUNC0("kotlin.to", "to", "kotlin.Pair");++ /* kotlin.collections — top-level builders */+ KT_FUNC0("kotlin.collections.listOf", "listOf", "kotlin.collections.List");+ KT_FUNC0("kotlin.collections.mutableListOf", "mutableListOf",+ "kotlin.collections.MutableList");+ KT_FUNC0("kotlin.collections.arrayListOf", "arrayListOf", "kotlin.collections.ArrayList");+ KT_FUNC0("kotlin.collections.emptyList", "emptyList", "kotlin.collections.List");+ KT_FUNC0("kotlin.collections.listOfNotNull", "listOfNotNull", "kotlin.collections.List");+ KT_FUNC0("kotlin.collections.setOf", "setOf", "kotlin.collections.Set");+ KT_FUNC0("kotlin.collections.mutableSetOf", "mutableSetOf", "kotlin.collections.MutableSet");+ KT_FUNC0("kotlin.collections.hashSetOf", "hashSetOf", "kotlin.collections.HashSet");+ KT_FUNC0("kotlin.collections.linkedSetOf", "linkedSetOf",+ "kotlin.collections.LinkedHashSet");+ KT_FUNC0("kotlin.collections.emptySet", "emptySet", "kotlin.collections.Set");+ KT_FUNC0("kotlin.collections.sortedSetOf", "sortedSetOf", "kotlin.collections.Set");+ KT_FUNC0("kotlin.collections.mapOf", "mapOf", "kotlin.collections.Map");+ KT_FUNC0("kotlin.collections.mutableMapOf", "mutableMapOf", "kotlin.collections.MutableMap");+ KT_FUNC0("kotlin.collections.hashMapOf", "hashMapOf", "kotlin.collections.HashMap");+ KT_FUNC0("kotlin.collections.linkedMapOf", "linkedMapOf",+ "kotlin.collections.LinkedHashMap");+ KT_FUNC0("kotlin.collections.emptyMap", "emptyMap", "kotlin.collections.Map");+ KT_FUNC0("kotlin.collections.sortedMapOf", "sortedMapOf", "kotlin.collections.Map");+ KT_FUNC0("kotlin.arrayOf", "arrayOf", "kotlin.Array");+ KT_FUNC0("kotlin.arrayOfNulls", "arrayOfNulls", "kotlin.Array");+ KT_FUNC0("kotlin.emptyArray", "emptyArray", "kotlin.Array");+ KT_FUNC0("kotlin.intArrayOf", "intArrayOf", "kotlin.IntArray");+ KT_FUNC0("kotlin.longArrayOf", "longArrayOf", "kotlin.LongArray");+ KT_FUNC0("kotlin.floatArrayOf", "floatArrayOf", "kotlin.FloatArray");+ KT_FUNC0("kotlin.doubleArrayOf", "doubleArrayOf", "kotlin.DoubleArray");+ KT_FUNC0("kotlin.byteArrayOf", "byteArrayOf", "kotlin.ByteArray");+ KT_FUNC0("kotlin.shortArrayOf", "shortArrayOf", "kotlin.ShortArray");+ KT_FUNC0("kotlin.booleanArrayOf", "booleanArrayOf", "kotlin.BooleanArray");+ KT_FUNC0("kotlin.charArrayOf", "charArrayOf", "kotlin.CharArray");++ /* kotlin.sequences */+ KT_FUNC0("kotlin.sequences.sequenceOf", "sequenceOf", "kotlin.sequences.Sequence");+ KT_FUNC0("kotlin.sequences.emptySequence", "emptySequence", "kotlin.sequences.Sequence");+ KT_FUNC0("kotlin.sequences.generateSequence", "generateSequence",+ "kotlin.sequences.Sequence");+ KT_FUNC0("kotlin.sequences.sequence", "sequence", "kotlin.sequences.Sequence");++ /* kotlin.ranges */+ KT_FUNC0("kotlin.ranges.until", "until", "kotlin.ranges.IntRange");+ KT_FUNC0("kotlin.ranges.downTo", "downTo", "kotlin.ranges.IntProgression");+ KT_FUNC0("kotlin.ranges.coerceAtLeast", "coerceAtLeast", "kotlin.Int");+ KT_FUNC0("kotlin.ranges.coerceAtMost", "coerceAtMost", "kotlin.Int");+ KT_FUNC0("kotlin.ranges.coerceIn", "coerceIn", "kotlin.Int");++ /* kotlin.comparisons */+ KT_FUNC0("kotlin.comparisons.compareValues", "compareValues", "kotlin.Int");+ KT_FUNC0("kotlin.comparisons.compareBy", "compareBy", "java.util.Comparator");+ KT_FUNC0("kotlin.comparisons.compareByDescending", "compareByDescending",+ "java.util.Comparator");+ KT_FUNC0("kotlin.comparisons.minOf", "minOf", "kotlin.Comparable");+ KT_FUNC0("kotlin.comparisons.maxOf", "maxOf", "kotlin.Comparable");+ KT_FUNC0("kotlin.comparisons.naturalOrder", "naturalOrder", "java.util.Comparator");+ KT_FUNC0("kotlin.comparisons.reverseOrder", "reverseOrder", "java.util.Comparator");++ /* kotlin.text — useful builders on String companion */+ KT_FUNC0("kotlin.text.buildString", "buildString", "kotlin.String");+ KT_FUNC0("kotlin.text.toRegex", "toRegex", "kotlin.text.Regex");++ /* kotlin scope-functions are registered as extension functions+ * (receiver_type = "kotlin.Any") so that resolver finds them on every+ * receiver. Their full QN is kotlin.<name>. */+ {+ const char *names[] = {"let", "run", "apply", "also", "takeIf", "takeUnless", "use", NULL};+ const char *qns[] = {"kotlin.let", "kotlin.run", "kotlin.apply", "kotlin.also",+ "kotlin.takeIf", "kotlin.takeUnless",+ "kotlin.io.use", /* `use` lives in kotlin.io for Closeable */+ NULL};+ for (int i = 0; names[i]; i++) {+ CBMRegisteredFunc rf = {0};+ rf.qualified_name = qns[i];+ rf.short_name = names[i];+ rf.receiver_type = "kotlin.Any";+ rf.min_params = 1; /* the lambda */+ cbm_registry_add_func(reg, rf);+ }+ }+ (void)KT_SCOPE_METHODS; /* reserved for future tightening */+}diff --git a/internal/cbm/lsp/kotlin_lsp.c b/internal/cbm/lsp/kotlin_lsp.cnew file mode 100644index 000000000..f2c6b2145--- /dev/null+++ b/internal/cbm/lsp/kotlin_lsp.c@@ -0,0 +1,4072 @@+/*+ * kotlin_lsp.c — Kotlin Light Semantic Pass implementation.+ *+ * See kotlin_lsp.h for the architectural overview. This file walks the+ * tree-sitter Kotlin AST, populates a per-file CBMTypeRegistry, builds+ * lexical scopes, infers expression types, and emits CBMResolvedCall+ * entries when a call's target FQN can be determined statically.+ *+ * Reverse-engineered from the official Kotlin language specification+ * (kotlinlang.org/spec/) and the reference fwcd/kotlin-language-server+ * implementation. No JVM, no PSI, no BindingContext — pure C, walking+ * tree-sitter syntax with hand-rolled name resolution.+ *+ * Confidence model:+ * - 0.95 — direct constructor call, top-level fun, exact registry hit+ * - 0.90 — method dispatch through known receiver type+ * - 0.85 — extension function dispatch+ * - 0.80 — companion / object-singleton call+ * - 0.75 — super-call (with class-hierarchy lookup)+ * - 0.70 — `this.x()` where `this_type` is known+ * - 0.65 — partially resolved navigation (last segment)+ * - 0.60 — minimum floor for the LSP override path; below = drop+ *+ * Strategies emitted:+ * - "lsp_kt_constructor" — Foo() / Foo(args)+ * - "lsp_kt_method" — receiver.method() with known receiver type+ * - "lsp_kt_extension" — extension function dispatch+ * - "lsp_kt_static" — Foo.bar() where Foo is object/companion+ * - "lsp_kt_top_level" — bare top-level fun call+ * - "lsp_kt_super" — super.foo() / super<Type>.foo()+ * - "lsp_kt_this" — this.foo() with resolved this-type+ * - "lsp_kt_safe" — obj?.foo() with known obj type+ * - "lsp_kt_lambda_it" — it.foo() inside scope-function lambda+ * - "lsp_kt_import" — direct import target hit (no receiver)+ */++#include "kotlin_lsp.h"+#include "../helpers.h"+#include <ctype.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define KT_EVAL_MAX_DEPTH 32+#define KT_IMPORT_INITIAL_CAP 16++#define KT_CONF_CONSTRUCTOR 0.95f+#define KT_CONF_METHOD 0.90f+#define KT_CONF_EXTENSION 0.85f+#define KT_CONF_STATIC 0.80f+#define KT_CONF_SUPER 0.75f+#define KT_CONF_THIS 0.70f+#define KT_CONF_PARTIAL 0.65f+#define KT_CONF_TOP_LEVEL 0.95f+#define KT_CONF_LAMBDA_IT 0.78f+#define KT_CONF_IMPORT 0.92f++/* ── forward declarations ─────────────────────────────────────────── */++static void kt_resolve_calls_in_node(KotlinLSPContext *ctx, TSNode node);+static void kt_process_class_decl(KotlinLSPContext *ctx, TSNode node);+static void kt_process_object_decl(KotlinLSPContext *ctx, TSNode node, bool is_companion,+ const char *outer_class_qn);+static void kt_process_function_decl(KotlinLSPContext *ctx, TSNode node);+static void kt_process_property_decl(KotlinLSPContext *ctx, TSNode node);+static void kt_register_class_members(KotlinLSPContext *ctx, const char *class_qn, TSNode body,+ bool is_object);+static const CBMType *kt_eval_call_expression_type(KotlinLSPContext *ctx, TSNode node);+static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx, TSNode node);+static const CBMType *kt_eval_user_type(KotlinLSPContext *ctx, TSNode node);+static void kt_process_block_stmts(KotlinLSPContext *ctx, TSNode block);+static void kt_bind_function_params(KotlinLSPContext *ctx, TSNode func_node);+static const char *kt_type_qn_of(const CBMType *t);+static char *kt_join_dot(CBMArena *a, const char *prefix, const char *name);+static const char *kt_short(const char *qn);+static char *kt_node_text(KotlinLSPContext *ctx, TSNode node);+static TSNode kt_child_kind(TSNode parent, const char *kind);+static TSNode kt_child_kind_named(TSNode parent, const char *kind);+static TSNode kt_field_named(TSNode parent, const char *field);+static bool kt_node_is(TSNode n, const char *kind);+static bool kt_node_kind_in(TSNode n, const char *const *kinds);+static const char *kt_resolve_in_default_imports(KotlinLSPContext *ctx, const char *name,+ CBMKotlinUseKind kind);+static const CBMType *kt_try_smart_cast(KotlinLSPContext *ctx, TSNode call_or_nav);++/* ── helpers ──────────────────────────────────────────────────────── */++static char *kt_node_text(KotlinLSPContext *ctx, TSNode node) {+ if (ts_node_is_null(node)) {+ return NULL;+ }+ return cbm_node_text(ctx->arena, node, ctx->source);+}++/* Cross-grammar name-child resolver. Newer tree-sitter-kotlin dropped the+ * `name` field and names value decls (functions, vars, params) with+ * `simple_identifier` and type decls (classes, objects) with `type_identifier`;+ * older grammars and import/package paths use `identifier`. kt_child_kind_named+ * searches DIRECT named children only, so a class's nested constructor-param+ * simple_identifiers are never mistaken for the class name. */+static TSNode kt_name_child(TSNode node) {+ static const char *const kinds[] = {"simple_identifier", "type_identifier", "identifier"};+ for (int i = 0; i < 3; i++) {+ TSNode n = kt_child_kind_named(node, kinds[i]);+ if (!ts_node_is_null(n)) {+ return n;+ }+ }+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ return null_node;+}++static bool kt_node_is(TSNode n, const char *kind) {+ if (ts_node_is_null(n)) {+ return false;+ }+ return strcmp(ts_node_type(n), kind) == 0;+}++static bool kt_node_kind_in(TSNode n, const char *const *kinds) {+ if (ts_node_is_null(n)) {+ return false;+ }+ const char *k = ts_node_type(n);+ for (int i = 0; kinds[i]; i++) {+ if (strcmp(k, kinds[i]) == 0) {+ return true;+ }+ }+ return false;+}++static TSNode kt_child_kind(TSNode parent, const char *kind) {+ if (ts_node_is_null(parent)) {+ return parent;+ }+ uint32_t nc = ts_node_child_count(parent);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_child(parent, i);+ if (!ts_node_is_null(c) && strcmp(ts_node_type(c), kind) == 0) {+ return c;+ }+ }+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ return null_node;+}++static TSNode kt_child_kind_named(TSNode parent, const char *kind) {+ if (ts_node_is_null(parent)) {+ return parent;+ }+ uint32_t nc = ts_node_named_child_count(parent);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(parent, i);+ if (!ts_node_is_null(c) && strcmp(ts_node_type(c), kind) == 0) {+ return c;+ }+ }+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ return null_node;+}++static TSNode kt_field_named(TSNode parent, const char *field) {+ if (ts_node_is_null(parent)) {+ return parent;+ }+ return ts_node_child_by_field_name(parent, field, (uint32_t)strlen(field));+}++/* Find the first descendant matching kind, depth-first, capped at max_depth. */+static TSNode kt_find_descendant_kind(TSNode node, const char *kind, int max_depth) {+ if (ts_node_is_null(node) || max_depth <= 0) {+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ return null_node;+ }+ if (strcmp(ts_node_type(node), kind) == 0) {+ return node;+ }+ uint32_t nc = ts_node_child_count(node);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode found = kt_find_descendant_kind(ts_node_child(node, i), kind, max_depth - 1);+ if (!ts_node_is_null(found)) {+ return found;+ }+ }+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ return null_node;+}++/* Return last segment after final '.'. */+static const char *kt_short(const char *qn) {+ if (!qn) {+ return NULL;+ }+ const char *last = qn;+ for (const char *p = qn; *p; p++) {+ if (*p == '.') {+ last = p + 1;+ }+ }+ return last;+}++static char *kt_join_dot(CBMArena *a, const char *prefix, const char *name) {+ if (!a || !name) {+ return NULL;+ }+ if (!prefix || !*prefix) {+ return cbm_arena_strdup(a, name);+ }+ size_t pl = strlen(prefix);+ size_t nl = strlen(name);+ char *out = (char *)cbm_arena_alloc(a, pl + 1 + nl + 1);+ if (!out) {+ return NULL;+ }+ memcpy(out, prefix, pl);+ out[pl] = '.';+ memcpy(out + pl + 1, name, nl);+ out[pl + 1 + nl] = '\0';+ return out;+}++static const char *kt_type_qn_of(const CBMType *t) {+ if (!t) {+ return NULL;+ }+ switch (t->kind) {+ case CBM_TYPE_NAMED:+ return t->data.named.qualified_name;+ case CBM_TYPE_BUILTIN:+ return t->data.builtin.name;+ case CBM_TYPE_TEMPLATE:+ return t->data.template_type.template_name;+ case CBM_TYPE_ALIAS:+ if (t->data.alias.underlying) {+ return kt_type_qn_of(t->data.alias.underlying);+ }+ return t->data.alias.alias_qn;+ case CBM_TYPE_POINTER:+ return kt_type_qn_of(t->data.pointer.elem);+ case CBM_TYPE_REFERENCE:+ return kt_type_qn_of(t->data.reference.elem);+ default:+ return NULL;+ }+}++/* Strip a single trailing '?' (nullable type). The tree-sitter grammar+ * exposes `nullable_type`; this utility flattens it. */+static const CBMType *kt_unwrap_nullable(const CBMType *t) {+ /* For our purposes, T? and T are the same — we don't track nullability+ * at the type level. Smart-cast handlers below treat them as the same.+ */+ return t;+}++/* Append a CBMResolvedCall to the output array. */+static void kt_emit_resolved(KotlinLSPContext *ctx, const char *callee_qn, const char *strategy,+ float confidence) {+ if (ctx->debug) {+ fprintf(stderr, "[kotlin_lsp] EMIT %s -> %s [%s %.2f] (resolved_calls=%p enc=%s)\n",+ ctx->enclosing_func_qn ? ctx->enclosing_func_qn : "(null)",+ callee_qn ? callee_qn : "(null)",+ strategy ? strategy : "(null)", (double)confidence,+ (void *)ctx->resolved_calls,+ ctx->enclosing_func_qn ? ctx->enclosing_func_qn : "(null)");+ }+ if (!ctx->resolved_calls || !ctx->enclosing_func_qn || !callee_qn) {+ return;+ }+ if (confidence < 0.60f) {+ return;+ }++ CBMResolvedCallArray *arr = ctx->resolved_calls;+ if (arr->count >= arr->cap) {+ int new_cap = arr->cap == 0 ? 16 : arr->cap * 2;+ CBMResolvedCall *new_items = (CBMResolvedCall *)cbm_arena_alloc(+ ctx->arena, (size_t)new_cap * sizeof(CBMResolvedCall));+ if (!new_items) {+ return;+ }+ if (arr->items && arr->count > 0) {+ memcpy(new_items, arr->items, (size_t)arr->count * sizeof(CBMResolvedCall));+ }+ arr->items = new_items;+ arr->cap = new_cap;+ }+ CBMResolvedCall *rc = &arr->items[arr->count];+ memset(rc, 0, sizeof(CBMResolvedCall));+ rc->caller_qn = ctx->enclosing_func_qn;+ rc->callee_qn = cbm_arena_strdup(ctx->arena, callee_qn);+ rc->strategy = strategy;+ rc->confidence = confidence;+ arr->count++;+}++/* Detect a function_declaration's extension receiver type. The+ * tree-sitter Kotlin grammar inlines the rule `_receiver_type` (a hidden+ * rule starting with '_'), so the receiver doesn't appear as a named+ * child of that name — instead, a `user_type` (or `nullable_type` /+ * `parenthesized_type`) named child appears in source order BEFORE the+ * `identifier` (function name).+ *+ * Returns the inner type node and writes its raw text to `recv_text_out`+ * (arena-allocated). Returns null-node if the function is not an+ * extension function. */+static TSNode kt_find_extension_receiver(KotlinLSPContext *ctx, TSNode func_node,+ TSNode name_node, char **recv_text_out) {+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ if (recv_text_out) {+ *recv_text_out = NULL;+ }+ if (ts_node_is_null(func_node) || ts_node_is_null(name_node)) {+ return null_node;+ }+ /* Try field first (some grammar variants expose this). */+ TSNode by_field = kt_field_named(func_node, "receiver");+ if (!ts_node_is_null(by_field)) {+ if (recv_text_out) {+ *recv_text_out = kt_node_text(ctx, by_field);+ }+ return by_field;+ }+ /* Walk named children for a type-shaped node before the name. */+ uint32_t name_start = ts_node_start_byte(name_node);+ uint32_t nc = ts_node_named_child_count(func_node);+ static const char *type_kinds[] = {"user_type", "nullable_type", "non_nullable_type",+ "parenthesized_type", "type", NULL};+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(func_node, i);+ if (ts_node_is_null(c)) {+ continue;+ }+ if (ts_node_start_byte(c) >= name_start) {+ break;+ }+ if (kt_node_kind_in(c, type_kinds)) {+ if (recv_text_out) {+ *recv_text_out = kt_node_text(ctx, c);+ }+ return c;+ }+ }+ return null_node;+}++/* Extract the return type node from a function_declaration. The grammar+ * exposes it via a `type` field or as a `type`/`user_type`/`nullable_type`+ * named child appearing AFTER the `function_value_parameters` and+ * BEFORE the `function_body`. */+static TSNode kt_find_return_type(TSNode func_node) {+ TSNode null_node;+ memset(&null_node, 0, sizeof(null_node));+ if (ts_node_is_null(func_node)) {+ return null_node;+ }+ TSNode by_field = kt_field_named(func_node, "type");+ if (!ts_node_is_null(by_field)) {+ return by_field;+ }+ /* Walk children for a type appearing after the parameters. */+ TSNode params = kt_child_kind(func_node, "function_value_parameters");+ uint32_t after_params = ts_node_is_null(params) ? 0 : ts_node_end_byte(params);+ uint32_t nc = ts_node_named_child_count(func_node);+ static const char *type_kinds[] = {"user_type", "nullable_type", "non_nullable_type",+ "parenthesized_type", "type", "function_type", NULL};+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(func_node, i);+ if (ts_node_is_null(c)) {+ continue;+ }+ if (ts_node_start_byte(c) < after_params) {+ continue;+ }+ const char *k = ts_node_type(c);+ if (strcmp(k, "function_body") == 0 || strcmp(k, "block") == 0) {+ break;+ }+ if (kt_node_kind_in(c, type_kinds)) {+ return c;+ }+ }+ return null_node;+}++/* Build a CBM_TYPE_FUNC signature carrying just the return type, so that+ * cbm_registry_lookup_method's caller can read rf->signature->return_types+ * to determine the chained receiver. param_names/param_types are left+ * empty — we only care about the return type for chain tracking. */+static const CBMType *kt_build_func_sig_with_return(KotlinLSPContext *ctx,+ const CBMType *return_type) {+ if (!return_type || cbm_type_is_unknown(return_type)) {+ return NULL;+ }+ const char **empty_pn = (const char **)cbm_arena_alloc(ctx->arena, sizeof(const char *));+ if (!empty_pn) {+ return NULL;+ }+ empty_pn[0] = NULL;+ const CBMType **empty_pt =+ (const CBMType **)cbm_arena_alloc(ctx->arena, sizeof(const CBMType *));+ if (!empty_pt) {+ return NULL;+ }+ empty_pt[0] = NULL;+ const CBMType **rt = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const CBMType *));+ if (!rt) {+ return NULL;+ }+ rt[0] = return_type;+ rt[1] = NULL;+ return cbm_type_func(ctx->arena, empty_pn, empty_pt, rt);+}++/* ── public API ───────────────────────────────────────────────────── */++void kotlin_lsp_init(KotlinLSPContext *ctx, CBMArena *arena, const char *source, int source_len,+ const CBMTypeRegistry *registry, const char *package_qn,+ const char *module_qn, const char *project_name, const char *rel_path,+ CBMResolvedCallArray *out) {+ memset(ctx, 0, sizeof(KotlinLSPContext));+ ctx->arena = arena;+ ctx->source = source;+ ctx->source_len = source_len;+ ctx->registry = registry;+ ctx->package_qn = package_qn ? cbm_arena_strdup(arena, package_qn) : "";+ ctx->module_qn = module_qn ? cbm_arena_strdup(arena, module_qn) : "";+ ctx->project_name = project_name ? cbm_arena_strdup(arena, project_name) : "";+ ctx->rel_path = rel_path ? cbm_arena_strdup(arena, rel_path) : "";+ ctx->resolved_calls = out;+ ctx->import_cap = KT_IMPORT_INITIAL_CAP;+ ctx->import_locals =+ (const char **)cbm_arena_alloc(arena, sizeof(const char *) * (size_t)ctx->import_cap);+ ctx->import_targets =+ (const char **)cbm_arena_alloc(arena, sizeof(const char *) * (size_t)ctx->import_cap);+ ctx->import_kinds = (CBMKotlinUseKind *)cbm_arena_alloc(+ arena, sizeof(CBMKotlinUseKind) * (size_t)ctx->import_cap);+ ctx->import_count = 0;+ ctx->debug = (getenv("CBM_LSP_DEBUG") != NULL);++ /* Compute the JVM file class name. The Kotlin convention is that+ * top-level functions/properties live in a synthetic class named+ * "<FilenameWithoutExt>Kt". For internal references we don't usually+ * need this, but we expose it for completeness. */+ if (rel_path && *rel_path) {+ const char *base = rel_path;+ for (const char *p = rel_path; *p; p++) {+ if (*p == '/' || *p == '\\') {+ base = p + 1;+ }+ }+ const char *dot = strrchr(base, '.');+ size_t name_len = dot ? (size_t)(dot - base) : strlen(base);+ char *fn = (char *)cbm_arena_alloc(arena, name_len + 3);+ if (fn) {+ memcpy(fn, base, name_len);+ /* Capitalize first letter (Kotlin file class convention is+ * to keep filename casing, but for our purposes the literal+ * filename suffices). */+ if (name_len > 0 && fn[0] >= 'a' && fn[0] <= 'z') {+ fn[0] = (char)(fn[0] - 'a' + 'A');+ }+ fn[name_len] = 'K';+ fn[name_len + 1] = 't';+ fn[name_len + 2] = '\0';+ ctx->file_class_qn = kt_join_dot(arena, ctx->package_qn, fn);+ }+ }++ /* Push the file-level scope. */+ ctx->current_scope = cbm_scope_push(arena, NULL);+}++void kotlin_lsp_add_import(KotlinLSPContext *ctx, const char *local_name, const char *target_qn,+ CBMKotlinUseKind kind) {+ if (!ctx || !target_qn) {+ return;+ }+ if (ctx->import_count >= ctx->import_cap) {+ int new_cap = ctx->import_cap * 2;+ const char **new_locals = (const char **)cbm_arena_alloc(+ ctx->arena, sizeof(const char *) * (size_t)new_cap);+ const char **new_targets = (const char **)cbm_arena_alloc(+ ctx->arena, sizeof(const char *) * (size_t)new_cap);+ CBMKotlinUseKind *new_kinds = (CBMKotlinUseKind *)cbm_arena_alloc(+ ctx->arena, sizeof(CBMKotlinUseKind) * (size_t)new_cap);+ if (!new_locals || !new_targets || !new_kinds) {+ return;+ }+ memcpy(new_locals, ctx->import_locals,+ sizeof(const char *) * (size_t)ctx->import_count);+ memcpy(new_targets, ctx->import_targets,+ sizeof(const char *) * (size_t)ctx->import_count);+ memcpy(new_kinds, ctx->import_kinds,+ sizeof(CBMKotlinUseKind) * (size_t)ctx->import_count);+ ctx->import_locals = new_locals;+ ctx->import_targets = new_targets;+ ctx->import_kinds = new_kinds;+ ctx->import_cap = new_cap;+ }+ ctx->import_locals[ctx->import_count] =+ local_name ? cbm_arena_strdup(ctx->arena, local_name) : NULL;+ ctx->import_targets[ctx->import_count] = cbm_arena_strdup(ctx->arena, target_qn);+ ctx->import_kinds[ctx->import_count] = kind;+ ctx->import_count++;+}++const char *kotlin_resolve_class_name(KotlinLSPContext *ctx, const char *name) {+ if (!ctx || !name || !*name) {+ return NULL;+ }+ /* Already qualified? */+ if (strchr(name, '.')) {+ /* Prefix with project? Best-effort heuristic: leave as-is, the+ * pipeline will retry with project prefix on miss. */+ return cbm_arena_strdup(ctx->arena, name);+ }++ /* Same-package lookup: <package>.<name> */+ if (ctx->package_qn && *ctx->package_qn) {+ char *cand = kt_join_dot(ctx->arena, ctx->package_qn, name);+ if (ctx->registry && cbm_registry_lookup_type(ctx->registry, cand)) {+ return cand;+ }+ /* Project-qualified candidate — keep alongside as fallback */+ }++ /* Bare-name lookup: when the file has no `package` declaration, all+ * user-defined types are registered under their unqualified name.+ * Check this BEFORE default imports so a user-defined `StringBuilder`+ * or `Logger` shadows the stdlib one with the same short name —+ * matching how the official compiler resolves names. */+ if (ctx->registry && cbm_registry_lookup_type(ctx->registry, name)) {+ return cbm_arena_strdup(ctx->arena, name);+ }++ /* Explicit imports */+ for (int i = 0; i < ctx->import_count; i++) {+ const char *local = ctx->import_locals[i];+ if (local && strcmp(local, name) == 0 &&+ (ctx->import_kinds[i] == CBM_KT_USE_TYPE ||+ ctx->import_kinds[i] == CBM_KT_USE_UNKNOWN)) {+ return ctx->import_targets[i];+ }+ }++ /* Wildcard imports + default imports */+ for (int i = 0; i < ctx->import_count; i++) {+ if (ctx->import_kinds[i] == CBM_KT_USE_WILDCARD && ctx->import_targets[i]) {+ char *cand = kt_join_dot(ctx->arena, ctx->import_targets[i], name);+ if (ctx->registry && cbm_registry_lookup_type(ctx->registry, cand)) {+ return cand;+ }+ }+ }++ int n = 0;+ const char *const *defs = cbm_kotlin_default_import_packages(&n);+ for (int i = 0; i < n; i++) {+ char *cand = kt_join_dot(ctx->arena, defs[i], name);+ if (ctx->registry && cbm_registry_lookup_type(ctx->registry, cand)) {+ return cand;+ }+ }++ /* Same-package fallback — even if not in registry, useful for cross-file+ * lookups via the pipeline's <project>.<qn> retry. */+ if (ctx->package_qn && *ctx->package_qn) {+ return kt_join_dot(ctx->arena, ctx->package_qn, name);+ }+ return cbm_arena_strdup(ctx->arena, name);+}++const char *kotlin_resolve_function_name(KotlinLSPContext *ctx, const char *name) {+ if (!ctx || !name || !*name) {+ return NULL;+ }+ if (strchr(name, '.')) {+ return cbm_arena_strdup(ctx->arena, name);+ }++ /* Explicit function import */+ for (int i = 0; i < ctx->import_count; i++) {+ const char *local = ctx->import_locals[i];+ if (local && strcmp(local, name) == 0 &&+ (ctx->import_kinds[i] == CBM_KT_USE_FUNCTION ||+ ctx->import_kinds[i] == CBM_KT_USE_UNKNOWN ||+ ctx->import_kinds[i] == CBM_KT_USE_TYPE)) {+ return ctx->import_targets[i];+ }+ }++ /* Same-package top-level fun */+ if (ctx->package_qn && *ctx->package_qn) {+ char *cand = kt_join_dot(ctx->arena, ctx->package_qn, name);+ if (ctx->registry && cbm_registry_lookup_func(ctx->registry, cand)) {+ return cand;+ }+ }++ /* Bare-name lookup for files without a package declaration. */+ if (ctx->registry && cbm_registry_lookup_func(ctx->registry, name)) {+ return cbm_arena_strdup(ctx->arena, name);+ }++ /* Wildcard imports */+ for (int i = 0; i < ctx->import_count; i++) {+ if (ctx->import_kinds[i] == CBM_KT_USE_WILDCARD && ctx->import_targets[i]) {+ char *cand = kt_join_dot(ctx->arena, ctx->import_targets[i], name);+ if (ctx->registry && cbm_registry_lookup_func(ctx->registry, cand)) {+ return cand;+ }+ }+ }++ /* Default imports */+ return kt_resolve_in_default_imports(ctx, name, CBM_KT_USE_FUNCTION);+}++static const char *kt_resolve_in_default_imports(KotlinLSPContext *ctx, const char *name,+ CBMKotlinUseKind kind) {+ int n = 0;+ const char *const *defs = cbm_kotlin_default_import_packages(&n);+ for (int i = 0; i < n; i++) {+ char *cand = kt_join_dot(ctx->arena, defs[i], name);+ if (!ctx->registry) {+ continue;+ }+ if (kind == CBM_KT_USE_FUNCTION || kind == CBM_KT_USE_UNKNOWN) {+ if (cbm_registry_lookup_func(ctx->registry, cand)) {+ return cand;+ }+ }+ if (kind == CBM_KT_USE_TYPE || kind == CBM_KT_USE_UNKNOWN) {+ if (cbm_registry_lookup_type(ctx->registry, cand)) {+ return cand;+ }+ }+ }+ return NULL;+}++/* Synthesize a CBMRegisteredFunc on the fly for stdlib types where we+ * only have a method_names array (no full func registration). The+ * lifetime of the synthesized struct is the LSP context's arena. */+static const CBMRegisteredFunc *kt_synth_method(KotlinLSPContext *ctx, const char *class_qn,+ const char *method_name) {+ CBMRegisteredFunc *rf =+ (CBMRegisteredFunc *)cbm_arena_alloc(ctx->arena, sizeof(CBMRegisteredFunc));+ if (!rf) {+ return NULL;+ }+ memset(rf, 0, sizeof(CBMRegisteredFunc));+ rf->qualified_name = kt_join_dot(ctx->arena, class_qn, method_name);+ rf->receiver_type = cbm_arena_strdup(ctx->arena, class_qn);+ rf->short_name = cbm_arena_strdup(ctx->arena, method_name);+ rf->min_params = 0;+ return rf;+}++/* Heuristic: stdlib methods that return the same receiver type+ * (fluent style) — used for return-type tracking across chains. */+static bool kt_method_returns_self(const char *class_qn, const char *method) {+ if (!class_qn || !method) {+ return false;+ }+ if (strcmp(class_qn, "kotlin.String") == 0 || strcmp(class_qn, "java.lang.String") == 0 ||+ strcmp(class_qn, "kotlin.CharSequence") == 0 ||+ strcmp(class_qn, "kotlin.text.StringBuilder") == 0) {+ const char *self_returning[] = {+ "trim", "trimStart", "trimEnd", "trimIndent",+ "trimMargin", "uppercase", "lowercase", "replace",+ "padStart", "padEnd", "repeat", "removePrefix",+ "removeSuffix", "removeSurrounding", "replaceFirst", "reversed",+ "substring", "intern", "format", "plus",+ "subSequence", NULL,+ };+ for (int i = 0; self_returning[i]; i++) {+ if (strcmp(method, self_returning[i]) == 0) {+ return true;+ }+ }+ }+ if (strstr(class_qn, ".List") || strstr(class_qn, ".MutableList") ||+ strstr(class_qn, ".Iterable") || strstr(class_qn, ".Collection")) {+ const char *self_returning[] = {+ "filter", "filterNot", "filterNotNull", "filterIndexed",+ "map", "mapNotNull", "mapIndexed", "flatMap",+ "sorted", "sortedBy", "sortedDescending", "sortedByDescending",+ "sortedWith", "reversed", "distinct", "distinctBy",+ "take", "takeLast", "takeWhile", "takeLastWhile",+ "drop", "dropLast", "dropWhile", "dropLastWhile",+ "shuffled", "asReversed", "toList", "toMutableList",+ "ifEmpty", NULL,+ };+ for (int i = 0; self_returning[i]; i++) {+ if (strcmp(method, self_returning[i]) == 0) {+ return true;+ }+ }+ }+ /* Builder pattern — methods named `add`, `append`, `with` typically+ * return self. Only triggered when no other info is available. */+ if (strcmp(method, "add") == 0 || strcmp(method, "append") == 0 ||+ strcmp(method, "with") == 0 || strcmp(method, "set") == 0) {+ return true;+ }+ return false;+}++/* Returns the return type of a known stdlib method when we can determine+ * it from heuristic rules (self-returning, common String/Int/Boolean+ * results). Best-effort — returns UNKNOWN when we don't know. */+static const CBMType *kt_stdlib_method_return_type(KotlinLSPContext *ctx, const char *class_qn,+ const char *method) {+ if (!class_qn || !method) {+ return cbm_type_unknown();+ }+ if (kt_method_returns_self(class_qn, method)) {+ return cbm_type_named(ctx->arena, class_qn);+ }+ if (strcmp(method, "toString") == 0 || strcmp(method, "toRegex") == 0 ||+ strcmp(method, "joinToString") == 0 || strcmp(method, "toLowerCase") == 0 ||+ strcmp(method, "toUpperCase") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.String");+ }+ if (strcmp(method, "size") == 0 || strcmp(method, "length") == 0 ||+ strcmp(method, "count") == 0 || strcmp(method, "indexOf") == 0 ||+ strcmp(method, "lastIndexOf") == 0 || strcmp(method, "compareTo") == 0 ||+ strcmp(method, "hashCode") == 0 || strcmp(method, "code") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Int");+ }+ if (strcmp(method, "isEmpty") == 0 || strcmp(method, "isNotEmpty") == 0 ||+ strcmp(method, "isBlank") == 0 || strcmp(method, "isNotBlank") == 0 ||+ strcmp(method, "contains") == 0 || strcmp(method, "containsAll") == 0 ||+ strcmp(method, "containsKey") == 0 || strcmp(method, "containsValue") == 0 ||+ strcmp(method, "startsWith") == 0 || strcmp(method, "endsWith") == 0 ||+ strcmp(method, "equals") == 0 || strcmp(method, "any") == 0 ||+ strcmp(method, "all") == 0 || strcmp(method, "none") == 0 ||+ strcmp(method, "matches") == 0 || strcmp(method, "isDigit") == 0 ||+ strcmp(method, "isLetter") == 0 || strcmp(method, "isWhitespace") == 0 ||+ strcmp(method, "isFile") == 0 || strcmp(method, "isDirectory") == 0 ||+ strcmp(method, "exists") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Boolean");+ }+ if (strcmp(method, "sum") == 0 || strcmp(method, "sumOf") == 0 ||+ strcmp(method, "sumBy") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Int");+ }+ return cbm_type_unknown();+}++/* Iterative method lookup with a single depth bound on the combined+ * alias-then-super-chain walk. We never recurse — a class's alias chain+ * is followed first (capped at 16 hops to break self-referential cycles+ * that arise when a typealias resolves to a name that the registry maps+ * back to the same type), then the super chain is walked breadth-first+ * with a small visited set to break diamond inheritance. */+const CBMRegisteredFunc *kotlin_lookup_method(KotlinLSPContext *ctx, const char *class_qn,+ const char *method_name) {+ if (!ctx || !class_qn || !method_name || !ctx->registry) {+ return NULL;+ }++ /* Walk the alias chain iteratively, then the super chain, all using+ * a single visited-set so we cannot loop. */+ enum { VISIT_CAP = 32 };+ const char *visited[VISIT_CAP];+ int visited_n = 0;++ const char *queue[VISIT_CAP];+ int qhead = 0;+ int qtail = 0;+ queue[qtail++] = class_qn;++ while (qhead < qtail) {+ const char *cur_qn = queue[qhead++];+ if (!cur_qn) {+ continue;+ }+ bool seen = false;+ for (int v = 0; v < visited_n; v++) {+ if (strcmp(visited[v], cur_qn) == 0) {+ seen = true;+ break;+ }+ }+ if (seen) {+ continue;+ }+ if (visited_n < VISIT_CAP) {+ visited[visited_n++] = cur_qn;+ }++ /* Direct func registry hit (also follows alias chain internally+ * via cbm_registry_lookup_method_aliased). */+ const CBMRegisteredFunc *rf =+ cbm_registry_lookup_method_aliased(ctx->registry, cur_qn, method_name);+ if (rf) {+ return rf;+ }++ /* method_names fallback */+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, cur_qn);+ if (rt && rt->method_names) {+ for (int i = 0; rt->method_names[i]; i++) {+ if (strcmp(rt->method_names[i], method_name) == 0) {+ return kt_synth_method(ctx, cur_qn, method_name);+ }+ }+ }+ if (!rt) {+ continue;+ }+ /* Enqueue alias target */+ if (rt->alias_of && qtail < VISIT_CAP) {+ queue[qtail++] = rt->alias_of;+ }+ /* Enqueue super-chain */+ if (rt->embedded_types) {+ for (int i = 0; rt->embedded_types[i] && qtail < VISIT_CAP; i++) {+ queue[qtail++] = rt->embedded_types[i];+ }+ }+ }+ return NULL;+}++const CBMType *kotlin_lookup_property_type(KotlinLSPContext *ctx, const char *class_qn,+ const char *prop_name) {+ if (!ctx || !class_qn || !prop_name || !ctx->registry) {+ return cbm_type_unknown();+ }+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, class_qn);+ if (!rt) {+ return cbm_type_unknown();+ }+ if (rt->field_names && rt->field_types) {+ for (int i = 0; rt->field_names[i]; i++) {+ if (strcmp(rt->field_names[i], prop_name) == 0) {+ return rt->field_types[i];+ }+ }+ }+ if (rt->embedded_types) {+ for (int i = 0; rt->embedded_types[i]; i++) {+ const CBMType *t = kotlin_lookup_property_type(ctx, rt->embedded_types[i], prop_name);+ if (!cbm_type_is_unknown(t)) {+ return t;+ }+ }+ }+ return cbm_type_unknown();+}++/* ── package and import parsing ───────────────────────────────────── */++static const char *kt_parse_package_header(KotlinLSPContext *ctx, TSNode header) {+ if (ts_node_is_null(header)) {+ return "";+ }+ /* package_header: 'package' identifier ('.' identifier)* ';'+ * The grammar has either `qualified_identifier` or a sequence of+ * identifiers; we extract the textual span between 'package' and+ * the trailing semi/newline. */+ TSNode qid = kt_child_kind_named(header, "qualified_identifier");+ if (ts_node_is_null(qid)) {+ qid = kt_name_child(header);+ }+ if (ts_node_is_null(qid)) {+ return "";+ }+ char *txt = kt_node_text(ctx, qid);+ if (!txt) {+ return "";+ }+ /* Strip whitespace around dots */+ char *out = (char *)cbm_arena_alloc(ctx->arena, strlen(txt) + 1);+ if (!out) {+ return "";+ }+ int oi = 0;+ for (int i = 0; txt[i]; i++) {+ if (txt[i] != ' ' && txt[i] != '\t' && txt[i] != '\n' && txt[i] != '\r') {+ out[oi++] = txt[i];+ }+ }+ out[oi] = '\0';+ return out;+}++static void kt_parse_import_directive(KotlinLSPContext *ctx, TSNode imp) {+ if (ts_node_is_null(imp)) {+ return;+ }+ /* Tree-sitter shape:+ * import 'import' qualified_identifier ('.*' | 'as' identifier)?+ */+ TSNode qid = kt_child_kind_named(imp, "qualified_identifier");+ if (ts_node_is_null(qid)) {+ qid = kt_name_child(imp);+ }+ if (ts_node_is_null(qid)) {+ return;+ }+ char *qid_text = kt_node_text(ctx, qid);+ if (!qid_text) {+ return;+ }+ /* Compress whitespace */+ char *cleaned = (char *)cbm_arena_alloc(ctx->arena, strlen(qid_text) + 1);+ int oi = 0;+ for (int i = 0; qid_text[i]; i++) {+ if (qid_text[i] != ' ' && qid_text[i] != '\t' && qid_text[i] != '\n' &&+ qid_text[i] != '\r') {+ cleaned[oi++] = qid_text[i];+ }+ }+ cleaned[oi] = '\0';++ /* Detect wildcard suffix `.*` in raw text */+ char *full_text = kt_node_text(ctx, imp);+ bool wildcard = (full_text && strstr(full_text, ".*"));++ /* Detect `as <alias>` */+ const char *alias = NULL;+ if (full_text) {+ const char *as_kw = strstr(full_text, " as ");+ if (as_kw) {+ const char *p = as_kw + 4;+ while (*p == ' ' || *p == '\t') {+ p++;+ }+ char *al = (char *)cbm_arena_alloc(ctx->arena, 128);+ if (al) {+ int ai = 0;+ while (*p && (isalnum((unsigned char)*p) || *p == '_') && ai < 127) {+ al[ai++] = *p++;+ }+ al[ai] = '\0';+ if (ai > 0) {+ alias = al;+ }+ }+ }+ }++ if (wildcard) {+ kotlin_lsp_add_import(ctx, NULL, cleaned, CBM_KT_USE_WILDCARD);+ return;+ }++ /* Default: kind = UNKNOWN — we'll match it both ways at lookup time. */+ const char *local = alias ? alias : kt_short(cleaned);+ kotlin_lsp_add_import(ctx, local, cleaned, CBM_KT_USE_UNKNOWN);+}++/* ── definition collection ────────────────────────────────────────── */++/* Walk top-level declarations once to discover classes and top-level fns+ * so that intra-file references can resolve regardless of ordering. */+static void kt_collect_top_level_decls(KotlinLSPContext *ctx, TSNode root) {+ if (ts_node_is_null(root)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(root);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(root, i);+ const char *kind = ts_node_type(c);+ /* The vendored Kotlin grammar can't parse `interface` at file+ * scope (and a few other constructs), producing an ERROR node+ * that wraps everything that followed. Recurse into ERROR so+ * we can still register the class/function declarations the+ * parser managed to recognize inside it. */+ if (strcmp(kind, "ERROR") == 0) {+ kt_collect_top_level_decls(ctx, c);+ continue;+ }+ if (strcmp(kind, "class_declaration") == 0) {+ kt_process_class_decl(ctx, c);+ } else if (strcmp(kind, "object_declaration") == 0) {+ kt_process_object_decl(ctx, c, false, NULL);+ } else if (strcmp(kind, "function_declaration") == 0) {+ kt_process_function_decl(ctx, c);+ } else if (strcmp(kind, "property_declaration") == 0) {+ kt_process_property_decl(ctx, c);+ } else if (strcmp(kind, "type_alias") == 0) {+ /* type_alias: 'typealias' name '=' type */+ TSNode name = kt_field_named(c, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(c);+ }+ char *n = kt_node_text(ctx, name);+ if (!n) {+ continue;+ }+ CBMRegisteredType rt = {0};+ rt.qualified_name = kt_join_dot(ctx->arena, ctx->package_qn, n);+ rt.short_name = n;+ /* Capture the underlying type and stamp alias_of so that+ * cbm_registry_resolve_alias / lookup_method_aliased follow+ * the chain to e.g. kotlin.Int's methods. */+ TSNode rhs = kt_field_named(c, "type");+ if (ts_node_is_null(rhs)) {+ /* Find first type-shaped named child after the name */+ static const char *type_kinds[] = {"user_type", "nullable_type",+ "non_nullable_type", "parenthesized_type",+ "type", "function_type", NULL};+ uint32_t name_end = ts_node_end_byte(name);+ uint32_t kc = ts_node_named_child_count(c);+ for (uint32_t j = 0; j < kc; j++) {+ TSNode tc = ts_node_named_child(c, j);+ if (ts_node_is_null(tc)) {+ continue;+ }+ if (ts_node_start_byte(tc) < name_end) {+ continue;+ }+ if (kt_node_kind_in(tc, type_kinds)) {+ rhs = tc;+ break;+ }+ }+ }+ if (!ts_node_is_null(rhs)) {+ const CBMType *underlying = kotlin_parse_type_node(ctx, rhs);+ if (underlying && underlying->kind == CBM_TYPE_NAMED &&+ underlying->data.named.qualified_name) {+ rt.alias_of = underlying->data.named.qualified_name;+ }+ }+ cbm_registry_add_type((CBMTypeRegistry *)ctx->registry, rt);+ }+ }+}++static const char *kt_qn_for_class_decl(KotlinLSPContext *ctx, TSNode class_node) {+ TSNode name = kt_field_named(class_node, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(class_node);+ }+ if (ts_node_is_null(name)) {+ return NULL;+ }+ char *short_name = kt_node_text(ctx, name);+ if (!short_name) {+ return NULL;+ }+ if (ctx->enclosing_class_qn) {+ return kt_join_dot(ctx->arena, ctx->enclosing_class_qn, short_name);+ }+ return kt_join_dot(ctx->arena, ctx->package_qn, short_name);+}++static void kt_process_class_decl(KotlinLSPContext *ctx, TSNode node) {+ const char *class_qn = kt_qn_for_class_decl(ctx, node);+ if (!class_qn) {+ return;+ }+ /* Register the class skeleton */+ CBMRegisteredType rt = {0};+ rt.qualified_name = class_qn;+ rt.short_name = kt_short(class_qn);++ /* Collect inheritance. Older grammars wrap specifiers in a+ * `delegation_specifiers` node; newer tree-sitter-kotlin places+ * `delegation_specifier` directly under the class declaration. */+ TSNode delegation = kt_child_kind(node, "delegation_specifiers");+ {+ TSNode dcontainer = ts_node_is_null(delegation) ? node : delegation;+ const char *parents[16];+ int parent_count = 0;+ uint32_t dnc = ts_node_named_child_count(dcontainer);+ for (uint32_t di = 0; di < dnc && parent_count < 15; di++) {+ TSNode dc = ts_node_named_child(dcontainer, di);+ if (kt_node_is(dc, "delegation_specifier")) {+ /* Find user_type or constructor_invocation */+ TSNode ut = kt_find_descendant_kind(dc, "user_type", 4);+ if (ts_node_is_null(ut)) {+ ut = kt_find_descendant_kind(dc, "constructor_invocation", 4);+ if (!ts_node_is_null(ut)) {+ ut = kt_find_descendant_kind(ut, "user_type", 3);+ }+ }+ if (!ts_node_is_null(ut)) {+ char *name_text = kt_node_text(ctx, ut);+ if (name_text) {+ /* Strip generics */+ char *lt = strchr(name_text, '<');+ if (lt) {+ *lt = '\0';+ }+ const char *resolved = kotlin_resolve_class_name(ctx, name_text);+ if (resolved) {+ parents[parent_count++] = resolved;+ }+ }+ }+ }+ }+ if (parent_count > 0) {+ const char **embedded = (const char **)cbm_arena_alloc(+ ctx->arena, sizeof(const char *) * (size_t)(parent_count + 1));+ if (embedded) {+ for (int p = 0; p < parent_count; p++) {+ embedded[p] = parents[p];+ }+ embedded[parent_count] = NULL;+ rt.embedded_types = embedded;+ }+ }+ }++ /* Determine if interface */+ TSNode mods = kt_child_kind(node, "modifiers");+ bool is_interface = false;+ if (!ts_node_is_null(mods)) {+ char *mod_text = kt_node_text(ctx, mods);+ if (mod_text && strstr(mod_text, "interface") != NULL) {+ is_interface = true;+ }+ }+ /* Also possible: the class_declaration's first child is 'class' or+ * 'interface' keyword text. */+ {+ char *full = kt_node_text(ctx, node);+ if (full) {+ /* crude check: starts-with "interface " (after modifiers). */+ const char *p = full;+ while (*p && (*p == ' ' || *p == '\t' || *p == '\n')) {+ p++;+ }+ /* Skip annotations + modifiers tokens */+ while (*p && *p != 'c' && *p != 'i') {+ /* find class/interface keyword */+ const char *cls = strstr(p, "class ");+ const char *iface = strstr(p, "interface ");+ if (cls && (!iface || cls < iface)) {+ p = cls;+ break;+ }+ if (iface) {+ p = iface;+ break;+ }+ p = "";+ }+ if (p && strncmp(p, "interface", 9) == 0) {+ is_interface = true;+ }+ }+ }+ rt.is_interface = is_interface;++ /* Collect class fields BEFORE registering the type. Source 1: primary+ * constructor val/var parameters. Source 2: class-body val/var+ * `property_declaration` nodes (e.g. `private val data = ...`). Both+ * become accessible via `name`-based scope lookup inside any method. */+ const char *fnames[64];+ const CBMType *ftypes[64];+ int field_count = 0;++ TSNode pc = kt_child_kind(node, "primary_constructor");+ if (!ts_node_is_null(pc)) {+ /* Older grammars wrap params in a `class_parameters` node; newer+ * tree-sitter-kotlin places `class_parameter` directly under the+ * primary_constructor. */+ TSNode params = kt_find_descendant_kind(pc, "class_parameters", 3);+ TSNode pcontainer = ts_node_is_null(params) ? pc : params;+ {+ uint32_t pnc = ts_node_named_child_count(pcontainer);+ for (uint32_t pi = 0; pi < pnc && field_count < 63; pi++) {+ TSNode p = ts_node_named_child(pcontainer, pi);+ if (!kt_node_is(p, "class_parameter")) {+ continue;+ }+ char *p_text = kt_node_text(ctx, p);+ if (!p_text) {+ continue;+ }+ bool has_val_var = (strstr(p_text, "val ") || strstr(p_text, "var "));+ if (!has_val_var) {+ continue;+ }+ TSNode name_node = kt_field_named(p, "name");+ if (ts_node_is_null(name_node)) {+ name_node = kt_name_child(p);+ }+ if (ts_node_is_null(name_node)) {+ continue;+ }+ char *fname = kt_node_text(ctx, name_node);+ if (!fname) {+ continue;+ }+ TSNode type_node = kt_field_named(p, "type");+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(p, "user_type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(p, "nullable_type");+ }+ const CBMType *ft =+ ts_node_is_null(type_node) ? cbm_type_unknown()+ : kotlin_parse_type_node(ctx, type_node);+ fnames[field_count] = fname;+ ftypes[field_count] = ft;+ field_count++;+ }+ }+ }++ /* Class-body property declarations. */+ TSNode body_for_props = kt_child_kind(node, "class_body");+ if (!ts_node_is_null(body_for_props)) {+ uint32_t bnc = ts_node_named_child_count(body_for_props);+ for (uint32_t i = 0; i < bnc && field_count < 63; i++) {+ TSNode m = ts_node_named_child(body_for_props, i);+ if (!kt_node_is(m, "property_declaration")) {+ continue;+ }+ TSNode var = kt_child_kind(m, "variable_declaration");+ if (ts_node_is_null(var)) {+ continue;+ }+ TSNode id = kt_name_child(var);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(var, "simple_identifier");+ }+ if (ts_node_is_null(id)) {+ continue;+ }+ char *pname = kt_node_text(ctx, id);+ if (!pname) {+ continue;+ }+ /* Determine type from annotation or initializer. */+ TSNode type_node = kt_child_kind(var, "type");+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "user_type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "nullable_type");+ }+ const CBMType *pt = cbm_type_unknown();+ if (!ts_node_is_null(type_node)) {+ pt = kotlin_parse_type_node(ctx, type_node);+ } else {+ /* Try inferring from initializer expression. */+ uint32_t mnc = ts_node_named_child_count(m);+ for (uint32_t k = 0; k < mnc; k++) {+ TSNode mc = ts_node_named_child(m, k);+ const char *mk = ts_node_type(mc);+ if (strcmp(mk, "variable_declaration") == 0 ||+ strcmp(mk, "modifiers") == 0) {+ continue;+ }+ pt = kotlin_eval_expr_type(ctx, mc);+ if (!cbm_type_is_unknown(pt)) {+ break;+ }+ }+ }+ fnames[field_count] = pname;+ ftypes[field_count] = pt;+ field_count++;+ }+ }++ if (field_count > 0) {+ const char **fn = (const char **)cbm_arena_alloc(+ ctx->arena, sizeof(const char *) * (size_t)(field_count + 1));+ const CBMType **ft = (const CBMType **)cbm_arena_alloc(+ ctx->arena, sizeof(const CBMType *) * (size_t)(field_count + 1));+ if (fn && ft) {+ for (int i = 0; i < field_count; i++) {+ fn[i] = fnames[i];+ ft[i] = ftypes[i];+ }+ fn[field_count] = NULL;+ ft[field_count] = NULL;+ rt.field_names = fn;+ rt.field_types = ft;+ }+ }++ cbm_registry_add_type((CBMTypeRegistry *)ctx->registry, rt);++ /* Recurse into body for nested types and members */+ TSNode body = kt_child_kind(node, "class_body");+ if (ts_node_is_null(body)) {+ body = kt_child_kind(node, "enum_class_body");+ }+ if (!ts_node_is_null(body)) {+ const char *prev_class = ctx->enclosing_class_qn;+ ctx->enclosing_class_qn = class_qn;+ kt_register_class_members(ctx, class_qn, body, false);+ ctx->enclosing_class_qn = prev_class;+ }+}++static void kt_process_object_decl(KotlinLSPContext *ctx, TSNode node, bool is_companion,+ const char *outer_class_qn) {+ TSNode name = kt_field_named(node, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(node);+ }+ char *short_name = ts_node_is_null(name) ? NULL : kt_node_text(ctx, name);+ const char *obj_qn = NULL;+ if (is_companion) {+ /* `companion object [Name]` — if no name given, use "Companion" */+ const char *companion_name = (short_name && *short_name) ? short_name : "Companion";+ obj_qn = kt_join_dot(ctx->arena, outer_class_qn ? outer_class_qn : ctx->enclosing_class_qn,+ companion_name);+ } else {+ if (!short_name) {+ return;+ }+ if (ctx->enclosing_class_qn) {+ obj_qn = kt_join_dot(ctx->arena, ctx->enclosing_class_qn, short_name);+ } else {+ obj_qn = kt_join_dot(ctx->arena, ctx->package_qn, short_name);+ }+ }++ CBMRegisteredType rt = {0};+ rt.qualified_name = obj_qn;+ rt.short_name = kt_short(obj_qn);++ /* Inheritance for object (delegation_specifiers wrapper in older grammars,+ * else delegation_specifier directly under the object declaration). */+ TSNode delegation = kt_child_kind(node, "delegation_specifiers");+ {+ TSNode dcontainer = ts_node_is_null(delegation) ? node : delegation;+ const char *parents[16];+ int parent_count = 0;+ uint32_t dnc = ts_node_named_child_count(dcontainer);+ for (uint32_t di = 0; di < dnc && parent_count < 15; di++) {+ TSNode dc = ts_node_named_child(dcontainer, di);+ if (!kt_node_is(dc, "delegation_specifier")) {+ continue;+ }+ TSNode ut = kt_find_descendant_kind(dc, "user_type", 4);+ if (!ts_node_is_null(ut)) {+ char *t = kt_node_text(ctx, ut);+ if (t) {+ char *lt = strchr(t, '<');+ if (lt) {+ *lt = '\0';+ }+ const char *resolved = kotlin_resolve_class_name(ctx, t);+ if (resolved) {+ parents[parent_count++] = resolved;+ }+ }+ }+ }+ if (parent_count > 0) {+ const char **embedded = (const char **)cbm_arena_alloc(+ ctx->arena, sizeof(const char *) * (size_t)(parent_count + 1));+ if (embedded) {+ for (int p = 0; p < parent_count; p++) {+ embedded[p] = parents[p];+ }+ embedded[parent_count] = NULL;+ rt.embedded_types = embedded;+ }+ }+ }++ cbm_registry_add_type((CBMTypeRegistry *)ctx->registry, rt);++ /* Recurse into body */+ TSNode body = kt_child_kind(node, "class_body");+ if (ts_node_is_null(body)) {+ body = kt_child_kind(node, "enum_class_body");+ }+ if (!ts_node_is_null(body)) {+ const char *prev_class = ctx->enclosing_class_qn;+ const char *prev_companion = ctx->enclosing_companion_qn;+ ctx->enclosing_class_qn = obj_qn;+ if (is_companion) {+ ctx->enclosing_companion_qn = obj_qn;+ }+ kt_register_class_members(ctx, obj_qn, body, true);+ ctx->enclosing_class_qn = prev_class;+ ctx->enclosing_companion_qn = prev_companion;+ }+}++static void kt_register_class_members(KotlinLSPContext *ctx, const char *class_qn, TSNode body,+ bool is_object) {+ (void)is_object;+ if (ts_node_is_null(body)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(body);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(body, i);+ const char *kind = ts_node_type(c);+ if (strcmp(kind, "function_declaration") == 0) {+ /* Method */+ TSNode name = kt_field_named(c, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(c);+ }+ char *fname = kt_node_text(ctx, name);+ if (!fname) {+ continue;+ }+ CBMRegisteredFunc rf = {0};+ rf.qualified_name = kt_join_dot(ctx->arena, class_qn, fname);+ rf.short_name = fname;+ rf.receiver_type = class_qn;+ rf.min_params = 0;+ /* Capture return type for chain tracking. */+ TSNode rt_node = kt_find_return_type(c);+ if (!ts_node_is_null(rt_node)) {+ const CBMType *rt = kotlin_parse_type_node(ctx, rt_node);+ rf.signature = kt_build_func_sig_with_return(ctx, rt);+ }+ /* DSL receiver detection: scan the function's parameters for+ * a function_type node whose first child is a `user_type`+ * (the receiver, as in `Foo.() -> Unit`). Stash the receiver+ * QN in decorator_qns[0] with a `lambda_receiver:` prefix+ * so kt_process_call_with_lambda can pick it up at the call+ * site and propagate it as the lambda's `this`. */+ {+ TSNode params = kt_child_kind(c, "function_value_parameters");+ if (!ts_node_is_null(params)) {+ uint32_t pnc = ts_node_named_child_count(params);+ for (uint32_t pi = 0; pi < pnc; pi++) {+ TSNode p = ts_node_named_child(params, pi);+ if (!kt_node_is(p, "parameter")) {+ continue;+ }+ TSNode tn = kt_field_named(p, "type");+ if (ts_node_is_null(tn)) {+ tn = kt_child_kind(p, "type");+ }+ if (ts_node_is_null(tn)) {+ tn = kt_child_kind(p, "function_type");+ }+ TSNode ft = kt_node_is(tn, "function_type")+ ? tn+ : kt_find_descendant_kind(tn, "function_type", 3);+ if (ts_node_is_null(ft)) {+ continue;+ }+ TSNode recv = kt_child_kind_named(ft, "user_type");+ if (ts_node_is_null(recv)) {+ continue;+ }+ char *rt_text = kt_node_text(ctx, recv);+ if (!rt_text) {+ continue;+ }+ const char *resolved = kotlin_resolve_class_name(ctx, rt_text);+ if (!resolved) {+ continue;+ }+ const char **dq =+ (const char **)cbm_arena_alloc(ctx->arena, 2 * sizeof(const char *));+ if (dq) {+ char *tag = (char *)cbm_arena_alloc(+ ctx->arena, strlen("lambda_receiver:") + strlen(resolved) + 1);+ if (tag) {+ strcpy(tag, "lambda_receiver:");+ strcat(tag, resolved);+ dq[0] = tag;+ dq[1] = NULL;+ rf.decorator_qns = dq;+ }+ }+ break;+ }+ }+ }+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);+ } else if (strcmp(kind, "property_declaration") == 0) {+ /* Property — we don't track types deeply here, just register existence */+ (void)c;+ } else if (strcmp(kind, "object_declaration") == 0) {+ /* Could be `companion object` or nested `object` */+ char *otext = kt_node_text(ctx, c);+ bool is_comp = otext && strstr(otext, "companion");+ const char *prev_class = ctx->enclosing_class_qn;+ ctx->enclosing_class_qn = class_qn;+ kt_process_object_decl(ctx, c, is_comp, class_qn);+ ctx->enclosing_class_qn = prev_class;+ } else if (strcmp(kind, "companion_object") == 0) {+ const char *prev_class = ctx->enclosing_class_qn;+ ctx->enclosing_class_qn = class_qn;+ kt_process_object_decl(ctx, c, true, class_qn);+ ctx->enclosing_class_qn = prev_class;+ } else if (strcmp(kind, "class_declaration") == 0) {+ const char *prev_class = ctx->enclosing_class_qn;+ ctx->enclosing_class_qn = class_qn;+ kt_process_class_decl(ctx, c);+ ctx->enclosing_class_qn = prev_class;+ } else if (strcmp(kind, "secondary_constructor") == 0) {+ CBMRegisteredFunc rf = {0};+ rf.qualified_name = kt_join_dot(ctx->arena, class_qn, "<init>");+ rf.short_name = "<init>";+ rf.receiver_type = class_qn;+ rf.min_params = 0;+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);+ } else if (strcmp(kind, "enum_entry") == 0) {+ /* Enum entry — register a "field" of the enum class */+ }+ }+}++static void kt_process_function_decl(KotlinLSPContext *ctx, TSNode node) {+ TSNode name = kt_field_named(node, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(node);+ }+ if (ts_node_is_null(name)) {+ return;+ }+ char *fname = kt_node_text(ctx, name);+ if (!fname) {+ return;+ }+ /* Detect extension function via the new helper which walks children+ * for a type-shaped node preceding the name. Handles the inlined+ * `_receiver_type` rule that tree-sitter doesn't expose as a named+ * child. */+ char *recv_text = NULL;+ TSNode receiver = kt_find_extension_receiver(ctx, node, name, &recv_text);+ (void)receiver;+ if (recv_text) {+ char *lt = strchr(recv_text, '<');+ if (lt) {+ *lt = '\0';+ }+ size_t rlen = strlen(recv_text);+ while (rlen > 0 && (recv_text[rlen - 1] == '?' || recv_text[rlen - 1] == ' ' ||+ recv_text[rlen - 1] == '\t' || recv_text[rlen - 1] == '\n')) {+ recv_text[--rlen] = '\0';+ }+ }++ CBMRegisteredFunc rf = {0};+ rf.short_name = fname;+ rf.min_params = 0;++ if (recv_text && *recv_text) {+ const char *recv_qn = kotlin_resolve_class_name(ctx, recv_text);+ rf.receiver_type = recv_qn;+ rf.qualified_name = kt_join_dot(ctx->arena, ctx->package_qn, fname);+ } else if (ctx->enclosing_class_qn) {+ rf.receiver_type = ctx->enclosing_class_qn;+ rf.qualified_name = kt_join_dot(ctx->arena, ctx->enclosing_class_qn, fname);+ } else {+ rf.qualified_name = kt_join_dot(ctx->arena, ctx->package_qn, fname);+ }+ /* Capture return type for chain tracking. */+ TSNode rt_node = kt_find_return_type(node);+ if (!ts_node_is_null(rt_node)) {+ const CBMType *rt = kotlin_parse_type_node(ctx, rt_node);+ rf.signature = kt_build_func_sig_with_return(ctx, rt);+ }+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, rf);+}++static void kt_process_property_decl(KotlinLSPContext *ctx, TSNode node) {+ /* property_declaration: ('val'|'var') variable_declaration ('=' expr)? */+ TSNode var = kt_child_kind(node, "variable_declaration");+ if (ts_node_is_null(var)) {+ return;+ }+ /* The variable_declaration's identifier becomes a top-level binding. */+ TSNode id = kt_name_child(var);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(var, "simple_identifier");+ }+ if (ts_node_is_null(id)) {+ return;+ }+ char *pname = kt_node_text(ctx, id);+ if (!pname) {+ return;+ }+ /* Type annotation? */+ TSNode type_node = kt_child_kind(var, "type");+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "user_type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "nullable_type");+ }+ const CBMType *pt = cbm_type_unknown();+ if (!ts_node_is_null(type_node)) {+ pt = kotlin_parse_type_node(ctx, type_node);+ } else {+ /* Try inferring from the initializer */+ TSNode init = kt_field_named(node, "value");+ if (ts_node_is_null(init)) {+ /* Last named child may be the initializer */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc > 0) {+ TSNode last = ts_node_named_child(node, nc - 1);+ const char *kk = ts_node_type(last);+ if (strstr(kk, "expression") || strstr(kk, "literal") ||+ strcmp(kk, "call_expression") == 0 ||+ strcmp(kk, "navigation_expression") == 0 ||+ strcmp(kk, "lambda_literal") == 0) {+ init = last;+ }+ }+ }+ if (!ts_node_is_null(init)) {+ pt = kotlin_eval_expr_type(ctx, init);+ }+ }+ /* Bind into file scope so top-level-property references resolve. */+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, pname), pt);+}++/* ── type parsing ─────────────────────────────────────────────────── */++const CBMType *kotlin_parse_type_node(KotlinLSPContext *ctx, TSNode node) {+ if (ts_node_is_null(node)) {+ return cbm_type_unknown();+ }+ const char *kind = ts_node_type(node);+ if (strcmp(kind, "type") == 0) {+ /* Unwrap to inner type */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc > 0) {+ return kotlin_parse_type_node(ctx, ts_node_named_child(node, 0));+ }+ }+ if (strcmp(kind, "nullable_type") == 0) {+ TSNode inner = ts_node_named_child(node, 0);+ return kotlin_parse_type_node(ctx, inner);+ }+ if (strcmp(kind, "non_nullable_type") == 0) {+ TSNode inner = ts_node_named_child(node, 0);+ return kotlin_parse_type_node(ctx, inner);+ }+ if (strcmp(kind, "parenthesized_type") == 0) {+ TSNode inner = ts_node_named_child(node, 0);+ return kotlin_parse_type_node(ctx, inner);+ }+ if (strcmp(kind, "function_type") == 0) {+ /* (A, B) -> R — represent as CALLABLE for completeness */+ return cbm_type_unknown();+ }+ if (strcmp(kind, "user_type") == 0 || strcmp(kind, "_simple_user_type") == 0) {+ return kt_eval_user_type(ctx, node);+ }+ /* Fallback: textual */+ char *txt = kt_node_text(ctx, node);+ if (!txt) {+ return cbm_type_unknown();+ }+ /* Strip generics and nullability */+ char *lt = strchr(txt, '<');+ if (lt) {+ *lt = '\0';+ }+ size_t tl = strlen(txt);+ while (tl > 0 && txt[tl - 1] == '?') {+ txt[--tl] = '\0';+ }+ /* Trim whitespace */+ while (*txt == ' ' || *txt == '\t') {+ txt++;+ }+ const char *resolved = kotlin_resolve_class_name(ctx, txt);+ if (resolved) {+ return cbm_type_named(ctx->arena, resolved);+ }+ return cbm_type_named(ctx->arena, txt);+}++static const CBMType *kt_eval_user_type(KotlinLSPContext *ctx, TSNode node) {+ /* user_type: simple_user_type ('.' simple_user_type)*+ * simple_user_type: identifier type_arguments? */+ char *txt = kt_node_text(ctx, node);+ if (!txt) {+ return cbm_type_unknown();+ }+ /* Strip generics */+ char *lt = strchr(txt, '<');+ if (lt) {+ *lt = '\0';+ }+ /* Strip whitespace */+ char *clean = (char *)cbm_arena_alloc(ctx->arena, strlen(txt) + 1);+ int oi = 0;+ for (int i = 0; txt[i]; i++) {+ if (txt[i] != ' ' && txt[i] != '\t' && txt[i] != '\n') {+ clean[oi++] = txt[i];+ }+ }+ clean[oi] = '\0';+ if (oi == 0) {+ return cbm_type_unknown();+ }+ const char *resolved = kotlin_resolve_class_name(ctx, clean);+ if (!resolved) {+ return cbm_type_named(ctx->arena, clean);+ }+ return cbm_type_named(ctx->arena, resolved);+}++/* ── expression type inference ────────────────────────────────────── */++static const CBMType *kt_eval_literal_type(KotlinLSPContext *ctx, TSNode node) {+ const char *kind = ts_node_type(node);+ if (strcmp(kind, "string_literal") == 0 || strcmp(kind, "multiline_string_literal") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.String");+ }+ if (strcmp(kind, "character_literal") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Char");+ }+ if (strcmp(kind, "number_literal") == 0) {+ char *txt = kt_node_text(ctx, node);+ if (!txt) {+ return cbm_type_named(ctx->arena, "kotlin.Int");+ }+ size_t l = strlen(txt);+ if (l == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Int");+ }+ char tail = (char)tolower((unsigned char)txt[l - 1]);+ if (tail == 'l') {+ return cbm_type_named(ctx->arena, "kotlin.Long");+ }+ if (tail == 'f') {+ return cbm_type_named(ctx->arena, "kotlin.Float");+ }+ if (strchr(txt, '.') || strchr(txt, 'e') || strchr(txt, 'E')) {+ return cbm_type_named(ctx->arena, "kotlin.Double");+ }+ return cbm_type_named(ctx->arena, "kotlin.Int");+ }+ if (strcmp(kind, "float_literal") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Double");+ }+ if (strcmp(kind, "boolean_literal") == 0) {+ return cbm_type_named(ctx->arena, "kotlin.Boolean");+ }+ if (strcmp(kind, "null_literal") == 0 ||+ (kt_node_text(ctx, node) && strcmp(kt_node_text(ctx, node), "null") == 0)) {+ return cbm_type_named(ctx->arena, "kotlin.Nothing");+ }+ return cbm_type_unknown();+}++const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node) {+ if (ts_node_is_null(node) || !ctx) {+ return cbm_type_unknown();+ }+ if (ctx->eval_depth >= KT_EVAL_MAX_DEPTH) {+ return cbm_type_unknown();+ }+ ctx->eval_depth++;+ const CBMType *result = cbm_type_unknown();+ const char *kind = ts_node_type(node);++ if (strcmp(kind, "expression") == 0 || strcmp(kind, "primary_expression") == 0 ||+ strcmp(kind, "parenthesized_expression") == 0 ||+ strcmp(kind, "annotated_expression") == 0 ||+ strcmp(kind, "labeled_expression") == 0) {+ uint32_t nc = ts_node_named_child_count(node);+ if (nc > 0) {+ result = kotlin_eval_expr_type(ctx, ts_node_named_child(node, 0));+ }+ goto out;+ }+ if (strcmp(kind, "string_literal") == 0 || strcmp(kind, "multiline_string_literal") == 0 ||+ strcmp(kind, "character_literal") == 0 || strcmp(kind, "number_literal") == 0 ||+ strcmp(kind, "float_literal") == 0 || strcmp(kind, "boolean_literal") == 0) {+ result = kt_eval_literal_type(ctx, node);+ goto out;+ }+ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0) {+ char *name = kt_node_text(ctx, node);+ if (!name) {+ goto out;+ }+ if (strcmp(name, "true") == 0 || strcmp(name, "false") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.Boolean");+ goto out;+ }+ if (strcmp(name, "null") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.Nothing");+ goto out;+ }+ if (strcmp(name, "it") == 0 && ctx->it_type) {+ result = ctx->it_type;+ goto out;+ }+ /* Scope lookup */+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, name);+ if (!cbm_type_is_unknown(t)) {+ result = t;+ goto out;+ }+ /* Maybe a class name (object reference) */+ const char *cls_qn = kotlin_resolve_class_name(ctx, name);+ if (cls_qn) {+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, cls_qn);+ if (rt) {+ result = cbm_type_named(ctx->arena, cls_qn);+ goto out;+ }+ }+ /* Maybe top-level property */+ goto out;+ }+ if (strcmp(kind, "this_expression") == 0) {+ result = ctx->this_type ? ctx->this_type : cbm_type_unknown();+ goto out;+ }+ if (strcmp(kind, "super_expression") == 0) {+ result = ctx->super_type ? ctx->super_type : cbm_type_unknown();+ goto out;+ }+ if (strcmp(kind, "call_expression") == 0) {+ result = kt_eval_call_expression_type(ctx, node);+ goto out;+ }+ if (strcmp(kind, "navigation_expression") == 0) {+ result = kt_eval_navigation_expression_type(ctx, node);+ goto out;+ }+ if (strcmp(kind, "as_expression") == 0) {+ /* obj as Foo / obj as? Foo — result is Foo */+ TSNode rhs = ts_node_named_child(node, ts_node_named_child_count(node) - 1);+ result = kotlin_parse_type_node(ctx, rhs);+ goto out;+ }+ if (strcmp(kind, "is_expression") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.Boolean");+ goto out;+ }+ if (strcmp(kind, "binary_expression") == 0 ||+ strcmp(kind, "additive_expression") == 0 ||+ strcmp(kind, "multiplicative_expression") == 0 ||+ strcmp(kind, "comparison_expression") == 0 ||+ strcmp(kind, "equality_expression") == 0 ||+ strcmp(kind, "range_expression") == 0) {+ /* Operator-convention dispatch: Kotlin desugars `a OP b` to+ * `a.<method>(b)` for a fixed set of operators. We detect the+ * operator token, evaluate `a`'s type, and emit a method-call+ * edge — matching what the official Kotlin compiler frontend+ * does in BindingContext.RESOLVED_CALL. Newer tree-sitter-kotlin+ * splits the old `binary_expression` into precedence-specific nodes. */+ TSNode lhs = kt_field_named(node, "left");+ TSNode rhs = kt_field_named(node, "right");+ if (ts_node_is_null(lhs) && ts_node_named_child_count(node) >= 1) {+ lhs = ts_node_named_child(node, 0);+ }+ if (ts_node_is_null(rhs) && ts_node_named_child_count(node) >= 2) {+ rhs = ts_node_named_child(node, ts_node_named_child_count(node) - 1);+ }+ const CBMType *lhs_t = kotlin_eval_expr_type(ctx, lhs);+ /* The operator token is between named children; extract from+ * source range. */+ char *full = kt_node_text(ctx, node);+ const char *op_method = NULL;+ if (full) {+ /* Common operator → method mapping. We check the FIRST+ * occurrence of each token after the lhs end and before+ * the rhs start. As a simple heuristic we check the raw+ * source text for canonical operator strings; the order+ * matters to disambiguate `==` vs `=` and `..` vs `.`. */+ uint32_t lhs_end = ts_node_is_null(lhs) ? 0 : ts_node_end_byte(lhs);+ uint32_t rhs_start =+ ts_node_is_null(rhs) ? ts_node_end_byte(node) : ts_node_start_byte(rhs);+ uint32_t node_start = ts_node_start_byte(node);+ const char *between = ctx->source + lhs_end;+ int between_len = (int)(rhs_start - lhs_end);+ if (between_len > 0 && lhs_end > node_start) {+ /* Check operators in disambiguation order. */+ if (memmem(between, (size_t)between_len, "===", 3)) {+ op_method = NULL; /* identity, no method */+ } else if (memmem(between, (size_t)between_len, "!==", 3)) {+ op_method = NULL;+ } else if (memmem(between, (size_t)between_len, "==", 2)) {+ op_method = "equals";+ } else if (memmem(between, (size_t)between_len, "!=", 2)) {+ op_method = "equals";+ } else if (memmem(between, (size_t)between_len, "..<", 3)) {+ op_method = "rangeUntil";+ } else if (memmem(between, (size_t)between_len, "..", 2)) {+ op_method = "rangeTo";+ } else if (memmem(between, (size_t)between_len, "+=", 2)) {+ op_method = "plusAssign";+ } else if (memmem(between, (size_t)between_len, "-=", 2)) {+ op_method = "minusAssign";+ } else if (memmem(between, (size_t)between_len, "*=", 2)) {+ op_method = "timesAssign";+ } else if (memmem(between, (size_t)between_len, "/=", 2)) {+ op_method = "divAssign";+ } else if (memmem(between, (size_t)between_len, "%=", 2)) {+ op_method = "remAssign";+ } else if (memmem(between, (size_t)between_len, "<=", 2) ||+ memmem(between, (size_t)between_len, ">=", 2) ||+ memmem(between, (size_t)between_len, "<", 1) ||+ memmem(between, (size_t)between_len, ">", 1)) {+ op_method = "compareTo";+ } else if (memmem(between, (size_t)between_len, "+", 1)) {+ op_method = "plus";+ } else if (memmem(between, (size_t)between_len, "-", 1)) {+ op_method = "minus";+ } else if (memmem(between, (size_t)between_len, "*", 1)) {+ op_method = "times";+ } else if (memmem(between, (size_t)between_len, "/", 1)) {+ op_method = "div";+ } else if (memmem(between, (size_t)between_len, "%", 1)) {+ op_method = "rem";+ }+ }+ (void)node_start;+ }+ if (op_method && lhs_t && !cbm_type_is_unknown(lhs_t)) {+ const char *lhs_qn = kt_type_qn_of(lhs_t);+ if (lhs_qn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, lhs_qn, op_method);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator",+ KT_CONF_METHOD);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ result = rf->signature->data.func.return_types[0];+ goto out;+ }+ }+ }+ }+ /* Default: type is LHS type (numeric ops, etc.) */+ result = lhs_t;+ goto out;+ }+ if (strcmp(kind, "unary_expression") == 0 ||+ strcmp(kind, "prefix_expression") == 0 ||+ strcmp(kind, "postfix_expression") == 0) {+ /* Unary operator desugars to method call:+ * +x → x.unaryPlus(), -x → x.unaryMinus(),+ * !x → x.not(), ++x → x.inc(), --x → x.dec()+ * Newer tree-sitter-kotlin uses prefix_expression/postfix_expression. */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc > 0) {+ TSNode operand = ts_node_named_child(node, nc - 1);+ const CBMType *t = kotlin_eval_expr_type(ctx, operand);+ char *full = kt_node_text(ctx, node);+ const char *op_method = NULL;+ if (full) {+ /* Look at chars before operand */+ uint32_t op_end = ts_node_start_byte(operand);+ uint32_t node_start = ts_node_start_byte(node);+ if (op_end > node_start) {+ const char *prefix = ctx->source + node_start;+ int prefix_len = (int)(op_end - node_start);+ if (memmem(prefix, (size_t)prefix_len, "++", 2)) {+ op_method = "inc";+ } else if (memmem(prefix, (size_t)prefix_len, "--", 2)) {+ op_method = "dec";+ } else if (memmem(prefix, (size_t)prefix_len, "!", 1)) {+ op_method = "not";+ } else if (memmem(prefix, (size_t)prefix_len, "-", 1)) {+ op_method = "unaryMinus";+ } else if (memmem(prefix, (size_t)prefix_len, "+", 1)) {+ op_method = "unaryPlus";+ }+ }+ }+ if (op_method && t && !cbm_type_is_unknown(t)) {+ const char *qn = kt_type_qn_of(t);+ if (qn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, qn, op_method);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator",+ KT_CONF_METHOD);+ }+ }+ }+ result = t;+ }+ goto out;+ }+ if (strcmp(kind, "in_expression") == 0 || strcmp(kind, "check_expression") == 0) {+ /* `a in b` desugars to `b.contains(a)`; `a is T` is a Boolean type+ * check (no method). Newer tree-sitter-kotlin emits both as+ * `check_expression`; disambiguate via the operator token. */+ char *ntext = kt_node_text(ctx, node);+ bool is_membership =+ ntext && (memmem(ntext, strlen(ntext), " in ", 4) || strstr(ntext, "!in") != NULL);+ uint32_t nc = ts_node_named_child_count(node);+ if (is_membership && nc >= 2) {+ TSNode container = ts_node_named_child(node, nc - 1);+ const CBMType *ct = kotlin_eval_expr_type(ctx, container);+ const char *cqn = kt_type_qn_of(ct);+ if (cqn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, cqn, "contains");+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator",+ KT_CONF_METHOD);+ }+ }+ }+ result = cbm_type_named(ctx->arena, "kotlin.Boolean");+ goto out;+ }+ if (strcmp(kind, "index_expression") == 0 || strcmp(kind, "indexing_expression") == 0) {+ /* `a[i]` desugars to `a.get(i)`. */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc >= 1) {+ TSNode recv = ts_node_named_child(node, 0);+ const CBMType *rt = kotlin_eval_expr_type(ctx, recv);+ const char *rqn = kt_type_qn_of(rt);+ if (rqn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, rqn, "get");+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_operator",+ KT_CONF_METHOD);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ result = rf->signature->data.func.return_types[0];+ goto out;+ }+ }+ }+ }+ result = cbm_type_unknown();+ goto out;+ }+ if (strcmp(kind, "callable_reference") == 0) {+ /* Callable references take three shapes:+ * `::topLevelFn` — bound to receiverless top-level function+ * `Foo::method` — bound class method or property+ * `instance::method`— bound to instance method+ * `Foo::class` — class literal (KClass<Foo>)+ * `T::class` (reified) — class literal of reified type param+ *+ * We emit an edge with strategy `lsp_kt_callable_ref` so the call+ * graph captures the reference even when it's not invoked here.+ * The grammar exposes the LHS (optional) and RHS via named+ * children — typically two identifiers separated by `::`. */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc >= 1) {+ TSNode last = ts_node_named_child(node, nc - 1);+ char *member = kt_node_text(ctx, last);+ if (member) {+ if (nc >= 2) {+ TSNode lhs = ts_node_named_child(node, 0);+ /* lhs may be a type or expression. Try type-resolve+ * first (for `Foo::method`), then expression eval+ * (for `obj::method`). */+ char *lhs_text = kt_node_text(ctx, lhs);+ const char *recv_qn = NULL;+ if (lhs_text) {+ recv_qn = kotlin_resolve_class_name(ctx, lhs_text);+ }+ if (!recv_qn) {+ const CBMType *t = kotlin_eval_expr_type(ctx, lhs);+ recv_qn = kt_type_qn_of(t);+ }+ if (recv_qn) {+ if (strcmp(member, "class") == 0) {+ /* `Foo::class` produces KClass<Foo>. We track+ * the reference but don't emit an edge — it's+ * a literal, not a call. */+ result = cbm_type_named(ctx->arena, "kotlin.reflect.KClass");+ goto out;+ }+ const CBMRegisteredFunc *rf =+ kotlin_lookup_method(ctx, recv_qn, member);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name,+ "lsp_kt_callable_ref", KT_CONF_METHOD);+ }+ }+ } else {+ /* `::name` — bound to top-level fn or local. */+ const char *fn_qn = kotlin_resolve_function_name(ctx, member);+ if (fn_qn) {+ kt_emit_resolved(ctx, fn_qn, "lsp_kt_callable_ref",+ KT_CONF_TOP_LEVEL);+ }+ }+ }+ }+ result = cbm_type_unknown();+ goto out;+ }+ if (strcmp(kind, "if_expression") == 0) {+ /* Pick first branch type */+ TSNode then_b = kt_field_named(node, "then");+ if (!ts_node_is_null(then_b)) {+ result = kotlin_eval_expr_type(ctx, then_b);+ goto out;+ }+ }+ if (strcmp(kind, "when_expression") == 0) {+ /* Find first when_entry's body */+ uint32_t nc = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(node, i);+ if (kt_node_is(c, "when_entry")) {+ /* Last named child is the body expression */+ uint32_t en = ts_node_named_child_count(c);+ if (en > 0) {+ TSNode body = ts_node_named_child(c, en - 1);+ result = kotlin_eval_expr_type(ctx, body);+ if (!cbm_type_is_unknown(result)) {+ goto out;+ }+ }+ }+ }+ }+ if (strcmp(kind, "lambda_literal") == 0 ||+ strcmp(kind, "annotated_lambda") == 0 ||+ strcmp(kind, "anonymous_function") == 0) {+ /* Lambda — result type is unknown without context. */+ result = cbm_type_unknown();+ goto out;+ }+ if (strcmp(kind, "object_literal") == 0) {+ /* Anonymous object — closest thing is the inferred parent type */+ TSNode delegation = kt_child_kind(node, "delegation_specifiers");+ if (!ts_node_is_null(delegation)) {+ TSNode ut = kt_find_descendant_kind(delegation, "user_type", 5);+ if (!ts_node_is_null(ut)) {+ result = kt_eval_user_type(ctx, ut);+ goto out;+ }+ }+ result = cbm_type_named(ctx->arena, "kotlin.Any");+ goto out;+ }+ if (strcmp(kind, "collection_literal") == 0) {+ /* [a, b, c] — typically a List */+ result = cbm_type_named(ctx->arena, "kotlin.collections.List");+ goto out;+ }+ if (strcmp(kind, "range_expression") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.ranges.IntRange");+ goto out;+ }+ if (strcmp(kind, "throw_expression") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.Nothing");+ goto out;+ }+ if (strcmp(kind, "return_expression") == 0) {+ result = cbm_type_named(ctx->arena, "kotlin.Nothing");+ goto out;+ }+ /* Fallthrough: unwrap single-named-child wrappers */+ {+ uint32_t nc = ts_node_named_child_count(node);+ if (nc == 1) {+ result = kotlin_eval_expr_type(ctx, ts_node_named_child(node, 0));+ }+ }+out:+ ctx->eval_depth--;+ return result ? result : cbm_type_unknown();+}++static const CBMType *kt_eval_constructor_or_func_call(KotlinLSPContext *ctx, TSNode call_node,+ const char *callee_text) {+ /* callee_text is a bare identifier — it may be:+ * 1) A class constructor: `Foo(...)` → returns Foo+ * 2) A top-level function: `foo(...)` → returns its declared return+ * 3) A scope binding (function reference held in a val): use type+ * 4) `it(arg)` if `it` is callable+ */+ if (!callee_text) {+ return cbm_type_unknown();+ }+ /* 0. `this`-method dispatch: if we're inside a class method or DSL+ * lambda, bare calls resolve against this_type's members first. This+ * matches Kotlin's resolution order: implicit-receiver before global. */+ if (ctx->this_type && !cbm_type_is_unknown(ctx->this_type)) {+ const char *this_qn = kt_type_qn_of(ctx->this_type);+ if (this_qn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, this_qn, callee_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ return rf->signature->data.func.return_types[0];+ }+ return cbm_type_unknown();+ }+ }+ }++ /* 1. Class? */+ const char *cls_qn = kotlin_resolve_class_name(ctx, callee_text);+ if (cls_qn && ctx->registry) {+ const CBMRegisteredType *rt = cbm_registry_lookup_type(ctx->registry, cls_qn);+ if (rt) {+ kt_emit_resolved(ctx, kt_join_dot(ctx->arena, cls_qn, "<init>"),+ "lsp_kt_constructor", KT_CONF_CONSTRUCTOR);+ return cbm_type_named(ctx->arena, cls_qn);+ }+ }+ /* 2. Top-level fun */+ const char *fn_qn = kotlin_resolve_function_name(ctx, callee_text);+ if (fn_qn) {+ kt_emit_resolved(ctx, fn_qn, "lsp_kt_top_level", KT_CONF_TOP_LEVEL);+ if (ctx->registry) {+ const CBMRegisteredFunc *rf = cbm_registry_lookup_func(ctx->registry, fn_qn);+ if (rf && rf->signature && rf->signature->kind == CBM_TYPE_FUNC) {+ if (rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ return rf->signature->data.func.return_types[0];+ }+ }+ }+ /* Heuristic return types for stdlib top-level builders. The+ * curated stdlib registers these by name only (no signature)+ * to keep the data table compact; we provide return types here+ * so chains like `mutableListOf<X>().filter { … }` propagate. */+ struct {+ const char *qn;+ const char *ret;+ } stdlib_returns[] = {+ {"kotlin.collections.listOf", "kotlin.collections.List"},+ {"kotlin.collections.listOfNotNull", "kotlin.collections.List"},+ {"kotlin.collections.mutableListOf", "kotlin.collections.MutableList"},+ {"kotlin.collections.arrayListOf", "kotlin.collections.ArrayList"},+ {"kotlin.collections.emptyList", "kotlin.collections.List"},+ {"kotlin.collections.setOf", "kotlin.collections.Set"},+ {"kotlin.collections.mutableSetOf", "kotlin.collections.MutableSet"},+ {"kotlin.collections.hashSetOf", "kotlin.collections.HashSet"},+ {"kotlin.collections.linkedSetOf", "kotlin.collections.LinkedHashSet"},+ {"kotlin.collections.emptySet", "kotlin.collections.Set"},+ {"kotlin.collections.mapOf", "kotlin.collections.Map"},+ {"kotlin.collections.mutableMapOf", "kotlin.collections.MutableMap"},+ {"kotlin.collections.hashMapOf", "kotlin.collections.HashMap"},+ {"kotlin.collections.linkedMapOf", "kotlin.collections.LinkedHashMap"},+ {"kotlin.collections.emptyMap", "kotlin.collections.Map"},+ {"kotlin.arrayOf", "kotlin.Array"},+ {"kotlin.arrayOfNulls", "kotlin.Array"},+ {"kotlin.emptyArray", "kotlin.Array"},+ {"kotlin.intArrayOf", "kotlin.IntArray"},+ {"kotlin.longArrayOf", "kotlin.LongArray"},+ {"kotlin.floatArrayOf", "kotlin.FloatArray"},+ {"kotlin.doubleArrayOf", "kotlin.DoubleArray"},+ {"kotlin.byteArrayOf", "kotlin.ByteArray"},+ {"kotlin.booleanArrayOf", "kotlin.BooleanArray"},+ {"kotlin.charArrayOf", "kotlin.CharArray"},+ {"kotlin.sequences.sequenceOf", "kotlin.sequences.Sequence"},+ {"kotlin.sequences.emptySequence", "kotlin.sequences.Sequence"},+ {"kotlin.sequences.generateSequence", "kotlin.sequences.Sequence"},+ {"kotlin.sequences.sequence", "kotlin.sequences.Sequence"},+ {"kotlin.io.readLine", "kotlin.String"},+ {"kotlin.io.readln", "kotlin.String"},+ {"kotlin.text.buildString", "kotlin.String"},+ {"kotlin.lazy", "kotlin.Lazy"},+ {"kotlin.lazyOf", "kotlin.Lazy"},+ {"kotlin.runCatching", "kotlin.Result"},+ {"kotlin.to", "kotlin.Pair"},+ {NULL, NULL},+ };+ for (int i = 0; stdlib_returns[i].qn; i++) {+ if (strcmp(stdlib_returns[i].qn, fn_qn) == 0) {+ return cbm_type_named(ctx->arena, stdlib_returns[i].ret);+ }+ }+ }+ (void)call_node;+ return cbm_type_unknown();+}++static const CBMType *kt_eval_call_expression_type(KotlinLSPContext *ctx, TSNode node) {+ /* call_expression: <expr> value_arguments (annotated_lambda)? */+ /* The first named child is the callee expression. */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc == 0) {+ return cbm_type_unknown();+ }+ TSNode callee = ts_node_named_child(node, 0);+ const char *kind = ts_node_type(callee);++ if (strcmp(kind, "identifier") == 0 || strcmp(kind, "simple_identifier") == 0) {+ char *name = kt_node_text(ctx, callee);+ return kt_eval_constructor_or_func_call(ctx, node, name);+ }+ if (strcmp(kind, "navigation_expression") == 0) {+ /* obj.method(...) — inner type evaluation handles emission */+ const CBMType *t = kt_eval_navigation_expression_type(ctx, callee);+ return t;+ }+ /* Could also be `call_expression` for chained calls like foo()(args) */+ return kotlin_eval_expr_type(ctx, callee);+}++/* Extract the member-name node from a navigation_expression. Newer+ * tree-sitter-kotlin wraps the member in a `navigation_suffix` node+ * (`. simple_identifier`); older grammars placed the simple_identifier+ * directly as the trailing named child. */+static TSNode kt_nav_member_node(TSNode nav) {+ uint32_t nc = ts_node_named_child_count(nav);+ if (nc == 0) {+ TSNode z;+ memset(&z, 0, sizeof(z));+ return z;+ }+ TSNode sel = ts_node_named_child(nav, nc - 1);+ if (kt_node_is(sel, "navigation_suffix")) {+ TSNode inner = kt_child_kind_named(sel, "simple_identifier");+ if (!ts_node_is_null(inner)) {+ return inner;+ }+ }+ return sel;+}++static const CBMType *kt_eval_navigation_expression_type(KotlinLSPContext *ctx, TSNode node) {+ /* navigation_expression: <expr> ('.'|'?.'|'!!.') (simple_identifier | navigation_suffix) */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc < 2) {+ return cbm_type_unknown();+ }+ TSNode receiver_node = ts_node_named_child(node, 0);+ TSNode selector = kt_nav_member_node(node);+ char *member_text = kt_node_text(ctx, selector);+ if (!member_text) {+ return cbm_type_unknown();+ }++ /* Special: super.foo */+ if (kt_node_is(receiver_node, "super_expression")) {+ if (ctx->enclosing_super_qn) {+ const CBMRegisteredFunc *rf =+ kotlin_lookup_method(ctx, ctx->enclosing_super_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_super", KT_CONF_SUPER);+ return cbm_type_unknown();+ }+ }+ return cbm_type_unknown();+ }++ /* Special: this.foo */+ if (kt_node_is(receiver_node, "this_expression")) {+ if (ctx->enclosing_class_qn) {+ const CBMRegisteredFunc *rf =+ kotlin_lookup_method(ctx, ctx->enclosing_class_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_this", KT_CONF_THIS);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ return rf->signature->data.func.return_types[0];+ }+ return cbm_type_unknown();+ }+ /* Property access? */+ const CBMType *pt = kotlin_lookup_property_type(ctx, ctx->enclosing_class_qn,+ member_text);+ if (!cbm_type_is_unknown(pt)) {+ return pt;+ }+ }+ return cbm_type_unknown();+ }++ const CBMType *recv_type = kotlin_eval_expr_type(ctx, receiver_node);+ recv_type = kt_unwrap_nullable(recv_type);+ const char *recv_qn = kt_type_qn_of(recv_type);++ /* Receiver might be a class reference itself — `Foo.bar()` where Foo is+ * a singleton object or an enum class with a companion. */+ if (recv_qn && ctx->registry) {+ /* Check object-singleton or companion lookup */+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, recv_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_method", KT_CONF_METHOD);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ return rf->signature->data.func.return_types[0];+ }+ /* Heuristic: stdlib self-returning / known-result methods. */+ const CBMType *guess = kt_stdlib_method_return_type(ctx, recv_qn, member_text);+ if (!cbm_type_is_unknown(guess)) {+ return guess;+ }+ return cbm_type_unknown();+ }++ /* Companion fallback: receiver is class Foo, lookup Foo.Companion.<member> */+ char *companion_qn = kt_join_dot(ctx->arena, recv_qn, "Companion");+ rf = kotlin_lookup_method(ctx, companion_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_static", KT_CONF_STATIC);+ if (rf->signature && rf->signature->kind == CBM_TYPE_FUNC &&+ rf->signature->data.func.return_types &&+ rf->signature->data.func.return_types[0]) {+ return rf->signature->data.func.return_types[0];+ }+ return cbm_type_unknown();+ }++ /* Property */+ const CBMType *pt = kotlin_lookup_property_type(ctx, recv_qn, member_text);+ if (!cbm_type_is_unknown(pt)) {+ return pt;+ }++ /* Extension function: search for any registered func with+ * receiver_type == recv_qn and short_name == member_text. */+ rf = cbm_registry_lookup_method(ctx->registry, recv_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_extension", KT_CONF_EXTENSION);+ return cbm_type_unknown();+ }+ }++ /* Bare receiver via `it.member` when inside scope-function lambda. */+ if (ctx->it_type && kt_node_is(receiver_node, "identifier")) {+ char *recv_text = kt_node_text(ctx, receiver_node);+ if (recv_text && strcmp(recv_text, "it") == 0) {+ const char *it_qn = kt_type_qn_of(ctx->it_type);+ if (it_qn) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, it_qn, member_text);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_lambda_it",+ KT_CONF_LAMBDA_IT);+ return cbm_type_unknown();+ }+ }+ }+ }++ /* Universal-method fallback: if the receiver type is unknown but the+ * member is a method that EVERY Kotlin reference has via kotlin.Any+ * (toString, equals, hashCode), emit on kotlin.Any. This is what+ * the fwcd LSP also resolves to when no narrower receiver is known —+ * Any is the supertype of every Kotlin reference. We emit at slightly+ * lower confidence (KT_CONF_PARTIAL) since we couldn't pin the exact+ * override target. */+ {+ static const char *kt_any_methods[] = {"toString", "equals", "hashCode", NULL};+ bool is_any = false;+ for (int i = 0; kt_any_methods[i]; i++) {+ if (strcmp(member_text, kt_any_methods[i]) == 0) {+ is_any = true;+ break;+ }+ }+ if (is_any) {+ char *q = kt_join_dot(ctx->arena, "kotlin.Any", member_text);+ kt_emit_resolved(ctx, q, "lsp_kt_any", KT_CONF_PARTIAL);+ }+ }++ return cbm_type_unknown();+}++/* ── statement processing ─────────────────────────────────────────── */++static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt);++static void kt_process_block_stmts(KotlinLSPContext *ctx, TSNode block) {+ if (ts_node_is_null(block)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(block);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(block, i);+ kt_process_statement(ctx, c);+ }+}++static void kt_bind_property_to_scope(KotlinLSPContext *ctx, TSNode prop) {+ /* property_declaration: ('val'|'var') (variable_declaration | multi_variable_declaration)+ * ('=' expr | property_delegate)?+ *+ * Handles three shapes:+ * 1. `val x: T = expr` — single binding, optional type or initializer+ * 2. `val (a, b) = expr` — destructuring; emits expr.component1(),+ * expr.component2() per official LSP convention+ * 3. `val x by lazy { ... }` — property delegation; emits delegate.getValue()+ * (and delegate.setValue() for var) per the+ * KProperty contract.+ */+ /* Multi-variable destructuring */+ TSNode multi = kt_child_kind(prop, "multi_variable_declaration");+ if (!ts_node_is_null(multi)) {+ /* Find the initializer expression — the last named child of `prop`+ * that's not the modifiers/multi_variable_declaration. */+ uint32_t nc = ts_node_named_child_count(prop);+ TSNode init;+ memset(&init, 0, sizeof(init));+ for (uint32_t i = nc; i > 0; i--) {+ TSNode c = ts_node_named_child(prop, i - 1);+ const char *k = ts_node_type(c);+ if (strcmp(k, "modifiers") == 0 ||+ strcmp(k, "multi_variable_declaration") == 0) {+ continue;+ }+ init = c;+ break;+ }+ const CBMType *init_t = cbm_type_unknown();+ if (!ts_node_is_null(init)) {+ init_t = kotlin_eval_expr_type(ctx, init);+ }+ /* Emit componentN calls for each variable in the multi-decl. */+ if (init_t && !cbm_type_is_unknown(init_t)) {+ const char *iqn = kt_type_qn_of(init_t);+ uint32_t mnc = ts_node_named_child_count(multi);+ for (uint32_t i = 0; i < mnc; i++) {+ TSNode v = ts_node_named_child(multi, i);+ if (!kt_node_is(v, "variable_declaration")) {+ continue;+ }+ if (iqn) {+ char comp[16];+ snprintf(comp, sizeof(comp), "component%u", i + 1);+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, iqn, comp);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_destructure",+ KT_CONF_METHOD);+ }+ }+ /* Bind variable to unknown type for now. */+ TSNode vid = kt_name_child(v);+ if (!ts_node_is_null(vid)) {+ char *vname = kt_node_text(ctx, vid);+ if (vname) {+ cbm_scope_bind(ctx->current_scope,+ cbm_arena_strdup(ctx->arena, vname),+ cbm_type_unknown());+ }+ }+ }+ }+ return;+ }++ TSNode var = kt_child_kind(prop, "variable_declaration");+ if (ts_node_is_null(var)) {+ return;+ }+ TSNode id = kt_name_child(var);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(var, "simple_identifier");+ }+ if (ts_node_is_null(id)) {+ return;+ }+ char *name = kt_node_text(ctx, id);+ if (!name) {+ return;+ }+ /* Type annotation? */+ TSNode type_node = kt_child_kind(var, "type");+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "user_type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(var, "nullable_type");+ }++ /* Property delegation: `val x by Foo()` — emit getValue (and setValue+ * for var) on the delegate's type. */+ TSNode delegate = kt_child_kind(prop, "property_delegate");+ if (!ts_node_is_null(delegate)) {+ /* Find inner expression of the delegate. */+ uint32_t dnc = ts_node_named_child_count(delegate);+ if (dnc > 0) {+ TSNode inner = ts_node_named_child(delegate, 0);+ const CBMType *dt = kotlin_eval_expr_type(ctx, inner);+ if (dt && !cbm_type_is_unknown(dt)) {+ const char *dqn = kt_type_qn_of(dt);+ if (dqn) {+ const CBMRegisteredFunc *gv = kotlin_lookup_method(ctx, dqn, "getValue");+ if (gv && gv->qualified_name) {+ kt_emit_resolved(ctx, gv->qualified_name, "lsp_kt_delegate",+ KT_CONF_METHOD);+ }+ /* Detect var (mutable) by looking for `var` keyword in+ * the property's source range. */+ char *src_text = kt_node_text(ctx, prop);+ if (src_text && strstr(src_text, "var ")) {+ const CBMRegisteredFunc *sv =+ kotlin_lookup_method(ctx, dqn, "setValue");+ if (sv && sv->qualified_name) {+ kt_emit_resolved(ctx, sv->qualified_name, "lsp_kt_delegate",+ KT_CONF_METHOD);+ }+ }+ }+ }+ }+ }++ const CBMType *t = cbm_type_unknown();+ if (!ts_node_is_null(type_node)) {+ t = kotlin_parse_type_node(ctx, type_node);+ } else {+ /* Scan named children of the property_declaration for an+ * initializer expression after the variable_declaration. */+ uint32_t nc = ts_node_named_child_count(prop);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(prop, i);+ const char *k = ts_node_type(c);+ if (strcmp(k, "variable_declaration") == 0 || strcmp(k, "modifiers") == 0 ||+ strcmp(k, "property_delegate") == 0) {+ continue;+ }+ t = kotlin_eval_expr_type(ctx, c);+ if (!cbm_type_is_unknown(t)) {+ break;+ }+ }+ }+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t);+}++/* Smart-cast inside `if (x is Foo)`. Detects pattern in stmt and binds+ * narrowed type into a child scope on the then-branch. */+static void kt_apply_smart_cast(KotlinLSPContext *ctx, TSNode condition_expr, bool then_branch) {+ if (ts_node_is_null(condition_expr) || !then_branch) {+ return;+ }+ /* is_expression (older) or check_expression (newer grammar): <expr> 'is'+ * <type>. Only `is`/`!is` narrows the type — skip `in` membership. */+ bool is_check = kt_node_is(condition_expr, "is_expression");+ if (!is_check && kt_node_is(condition_expr, "check_expression")) {+ char *ctext = kt_node_text(ctx, condition_expr);+ if (ctext &&+ (memmem(ctext, strlen(ctext), " is ", 4) != NULL || strstr(ctext, "!is") != NULL)) {+ is_check = true;+ }+ }+ if (!is_check) {+ return;+ }+ TSNode lhs = ts_node_named_child(condition_expr, 0);+ TSNode rhs = ts_node_named_child(condition_expr, ts_node_named_child_count(condition_expr) - 1);+ if (ts_node_is_null(lhs) || ts_node_is_null(rhs)) {+ return;+ }+ if (!(kt_node_is(lhs, "identifier") || kt_node_is(lhs, "simple_identifier"))) {+ return;+ }+ char *name = kt_node_text(ctx, lhs);+ if (!name) {+ return;+ }+ const CBMType *t = kotlin_parse_type_node(ctx, rhs);+ if (!cbm_type_is_unknown(t)) {+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t);+ }+}++static void kt_process_if_expression(KotlinLSPContext *ctx, TSNode node) {+ TSNode cond = kt_field_named(node, "condition");+ if (ts_node_is_null(cond)) {+ cond = kt_child_kind(node, "condition");+ }+ if (ts_node_is_null(cond)) {+ /* parenthesized condition fallback */+ cond = ts_node_named_child(node, 0);+ }++ TSNode then_b = kt_field_named(node, "then");+ if (ts_node_is_null(then_b)) {+ /* Find the first non-condition block/expression */+ uint32_t nc = ts_node_named_child_count(node);+ for (uint32_t i = 1; i < nc; i++) {+ TSNode c = ts_node_named_child(node, i);+ const char *k = ts_node_type(c);+ if (strcmp(k, "block") == 0 || strcmp(k, "control_structure_body") == 0 ||+ strstr(k, "expression")) {+ then_b = c;+ break;+ }+ }+ }++ if (!ts_node_is_null(then_b)) {+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ if (!ts_node_is_null(cond)) {+ kt_apply_smart_cast(ctx, cond, true);+ }+ if (kt_node_is(then_b, "block") || kt_node_is(then_b, "control_structure_body")) {+ kt_process_block_stmts(ctx, then_b);+ } else {+ kt_resolve_calls_in_node(ctx, then_b);+ kotlin_eval_expr_type(ctx, then_b);+ }+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ }+ /* Resolve calls inside the condition itself */+ if (!ts_node_is_null(cond)) {+ kt_resolve_calls_in_node(ctx, cond);+ }+}++static void kt_process_when_expression(KotlinLSPContext *ctx, TSNode node) {+ /* when (subject) { entries } — bind subject type as `it`-like? Actually+ * Kotlin's `when (x) { is Foo -> ... }` creates smart-cast on x. */+ TSNode subject = kt_child_kind(node, "when_subject");+ char *subject_name = NULL;+ const CBMType *subject_type = NULL;+ if (!ts_node_is_null(subject)) {+ /* when_subject: '(' expression ')' or '(' val name = expr ')' */+ TSNode inner = ts_node_named_child(subject, 0);+ if (!ts_node_is_null(inner)) {+ subject_type = kotlin_eval_expr_type(ctx, inner);+ if (kt_node_is(inner, "identifier") || kt_node_is(inner, "simple_identifier")) {+ subject_name = kt_node_text(ctx, inner);+ }+ }+ }+ uint32_t nc = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(node, i);+ if (!kt_node_is(c, "when_entry")) {+ continue;+ }+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ /* Look for `is Type` conditions */+ uint32_t en = ts_node_named_child_count(c);+ for (uint32_t e = 0; e < en; e++) {+ TSNode ec = ts_node_named_child(c, e);+ if (kt_node_is(ec, "_when_condition") || kt_node_is(ec, "when_condition") ||+ kt_node_is(ec, "type_test")) {+ /* Find a 'type' node and apply smart-cast on subject_name */+ TSNode tt = kt_find_descendant_kind(ec, "type", 3);+ if (ts_node_is_null(tt)) {+ tt = kt_find_descendant_kind(ec, "user_type", 3);+ }+ if (!ts_node_is_null(tt) && subject_name) {+ const CBMType *narrow = kotlin_parse_type_node(ctx, tt);+ if (!cbm_type_is_unknown(narrow)) {+ cbm_scope_bind(ctx->current_scope,+ cbm_arena_strdup(ctx->arena, subject_name), narrow);+ }+ }+ }+ }+ /* Process entry body */+ if (en > 0) {+ TSNode body = ts_node_named_child(c, en - 1);+ if (kt_node_is(body, "block")) {+ kt_process_block_stmts(ctx, body);+ } else {+ kt_resolve_calls_in_node(ctx, body);+ kotlin_eval_expr_type(ctx, body);+ }+ }+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ }+ (void)subject_type;+}++static void kt_process_for_statement(KotlinLSPContext *ctx, TSNode node) {+ /* for (x in iter) body+ *+ * Kotlin desugars this to roughly:+ * val it = iter.iterator()+ * while (it.hasNext()) {+ * val x = it.next()+ * body+ * }+ *+ * We emit method calls for `iterator()`, `hasNext()`, and `next()`+ * to match what the official LSP's BindingContext.LOOP_RANGE_*+ * slices contain — these are real graph edges users care about. */+ TSNode loop_var = kt_child_kind_named(node, "variable_declaration");+ TSNode iter = kt_field_named(node, "iterable");+ if (ts_node_is_null(iter)) {+ /* Find 'in' position — iterable is the expr after 'in' */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc >= 2) {+ iter = ts_node_named_child(node, 1);+ }+ }+ const CBMType *iter_t = kotlin_eval_expr_type(ctx, iter);+ if (iter_t && !cbm_type_is_unknown(iter_t)) {+ const char *iqn = kt_type_qn_of(iter_t);+ if (iqn) {+ const char *protocol[] = {"iterator", "hasNext", "next", NULL};+ for (int i = 0; protocol[i]; i++) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, iqn, protocol[i]);+ if (rf && rf->qualified_name) {+ kt_emit_resolved(ctx, rf->qualified_name, "lsp_kt_iterator",+ KT_CONF_METHOD);+ }+ }+ }+ }+ (void)iter_t;++ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ if (!ts_node_is_null(loop_var)) {+ TSNode id = kt_name_child(loop_var);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(loop_var, "simple_identifier");+ }+ if (!ts_node_is_null(id)) {+ char *name = kt_node_text(ctx, id);+ if (name) {+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name),+ cbm_type_unknown());+ }+ }+ }+ /* Body */+ uint32_t nc = ts_node_named_child_count(node);+ if (nc > 0) {+ TSNode body = ts_node_named_child(node, nc - 1);+ if (kt_node_is(body, "block")) {+ kt_process_block_stmts(ctx, body);+ } else {+ kt_resolve_calls_in_node(ctx, body);+ kotlin_eval_expr_type(ctx, body);+ }+ }+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+}++static void kt_process_lambda(KotlinLSPContext *ctx, TSNode lambda, const CBMType *receiver_type) {+ /* lambda_literal: '{' lambda_parameters? '->' statements '}'+ * If no parameters, `it` is bound to the receiver. */+ if (ts_node_is_null(lambda)) {+ return;+ }+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ const CBMType *prev_it = ctx->it_type;+ /* DSL receiver: when the callee's lambda parameter has a function-with-+ * receiver type (`Foo.() -> Unit`), the lambda's `this` is Foo and bare+ * calls inside resolve against Foo's members. The dsl_this_type is+ * passed via receiver_type when the caller can determine it. */+ const CBMType *prev_this = ctx->this_type;+ if (receiver_type && !cbm_type_is_unknown(receiver_type)) {+ ctx->this_type = receiver_type;+ }+ TSNode params = kt_child_kind(lambda, "lambda_parameters");+ if (ts_node_is_null(params)) {+ if (receiver_type && !cbm_type_is_unknown(receiver_type)) {+ ctx->it_type = receiver_type;+ }+ } else {+ uint32_t pnc = ts_node_named_child_count(params);+ for (uint32_t i = 0; i < pnc; i++) {+ TSNode pn = ts_node_named_child(params, i);+ TSNode id = kt_name_child(pn);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(pn, "simple_identifier");+ }+ if (!ts_node_is_null(id)) {+ char *name = kt_node_text(ctx, id);+ if (name) {+ /* Type annotation? */+ TSNode tn = kt_child_kind(pn, "type");+ const CBMType *t = ts_node_is_null(tn) ? cbm_type_unknown()+ : kotlin_parse_type_node(ctx, tn);+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, name), t);+ }+ }+ }+ }+ /* Walk lambda body */+ uint32_t nc = ts_node_named_child_count(lambda);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(lambda, i);+ const char *k = ts_node_type(c);+ if (strcmp(k, "lambda_parameters") == 0) {+ continue;+ }+ kt_process_statement(ctx, c);+ }+ ctx->it_type = prev_it;+ ctx->this_type = prev_this;+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+}++static void kt_process_call_with_lambda(KotlinLSPContext *ctx, TSNode call_node) {+ /* If call has trailing lambda, propagate the receiver type as `it`.+ * xs.forEach { println(it) } — `it` is element type of xs+ * "abc".let { … } — `it` is String+ */+ uint32_t nc = ts_node_named_child_count(call_node);+ /* Resolve callee normally for emission */+ (void)kt_eval_call_expression_type(ctx, call_node);+ /* Find trailing lambda */+ TSNode lambda;+ memset(&lambda, 0, sizeof(lambda));+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(call_node, i);+ /* Newer tree-sitter-kotlin nests the trailing lambda inside a+ * `call_suffix` node; descend into it. */+ if (kt_node_is(c, "call_suffix")) {+ TSNode al = kt_child_kind(c, "annotated_lambda");+ if (ts_node_is_null(al)) {+ al = kt_child_kind(c, "lambda_literal");+ }+ if (ts_node_is_null(al)) {+ continue;+ }+ c = al;+ }+ if (kt_node_is(c, "annotated_lambda") || kt_node_is(c, "lambda_literal")) {+ lambda = c;+ /* Could be wrapped in annotated_lambda */+ if (kt_node_is(c, "annotated_lambda")) {+ TSNode inner = kt_child_kind(c, "lambda_literal");+ if (!ts_node_is_null(inner)) {+ lambda = inner;+ }+ }+ break;+ }+ }+ if (ts_node_is_null(lambda)) {+ return;+ }+ /* Receiver type for `it` and DSL `this`:+ * - If callee is `recv.fn` and the resolved fn has a+ * `lambda_receiver:` decorator hint stamped at registration, use+ * that as the lambda's `this` (DSL builders).+ * - Otherwise pass the navigation receiver's type as `it`.+ */+ const CBMType *recv_t = NULL;+ TSNode callee = ts_node_named_child(call_node, 0);+ if (kt_node_is(callee, "navigation_expression")) {+ TSNode rcv_node = ts_node_named_child(callee, 0);+ const CBMType *outer_recv = kotlin_eval_expr_type(ctx, rcv_node);+ const char *outer_qn = kt_type_qn_of(outer_recv);+ if (outer_qn) {+ TSNode sel = kt_nav_member_node(callee);+ char *member = kt_node_text(ctx, sel);+ if (member) {+ const CBMRegisteredFunc *rf = kotlin_lookup_method(ctx, outer_qn, member);+ if (rf && rf->decorator_qns) {+ for (int i = 0; rf->decorator_qns[i]; i++) {+ const char *d = rf->decorator_qns[i];+ if (strncmp(d, "lambda_receiver:", 16) == 0) {+ recv_t = cbm_type_named(ctx->arena, d + 16);+ break;+ }+ }+ }+ }+ }+ if (!recv_t) {+ recv_t = outer_recv;+ }+ } else if (kt_node_is(callee, "identifier") || kt_node_is(callee, "simple_identifier")) {+ /* Bare-fun call: check the resolved function's lambda receiver. */+ char *fname = kt_node_text(ctx, callee);+ if (fname) {+ const char *fn_qn = kotlin_resolve_function_name(ctx, fname);+ if (fn_qn && ctx->registry) {+ const CBMRegisteredFunc *rf = cbm_registry_lookup_func(ctx->registry, fn_qn);+ if (rf && rf->decorator_qns) {+ for (int i = 0; rf->decorator_qns[i]; i++) {+ const char *d = rf->decorator_qns[i];+ if (strncmp(d, "lambda_receiver:", 16) == 0) {+ recv_t = cbm_type_named(ctx->arena, d + 16);+ break;+ }+ }+ }+ }+ }+ }+ kt_process_lambda(ctx, lambda, recv_t);+}++static void kt_process_statement(KotlinLSPContext *ctx, TSNode stmt) {+ if (ts_node_is_null(stmt)) {+ return;+ }+ const char *kind = ts_node_type(stmt);+ /* Newer tree-sitter-kotlin wraps a body's statements in a `statements`+ * node (where older grammars used `block`/bare children). Unwrap either so+ * each real statement is bound + resolved in order. */+ if (strcmp(kind, "statements") == 0 || strcmp(kind, "block") == 0) {+ kt_process_block_stmts(ctx, stmt);+ return;+ }+ if (strcmp(kind, "property_declaration") == 0) {+ kt_bind_property_to_scope(ctx, stmt);+ /* Resolve calls within initializer */+ kt_resolve_calls_in_node(ctx, stmt);+ return;+ }+ if (strcmp(kind, "function_declaration") == 0) {+ /* Local function — register and recurse */+ TSNode name = kt_field_named(stmt, "name");+ if (ts_node_is_null(name)) {+ name = kt_child_kind_named(stmt, "simple_identifier");+ }+ if (ts_node_is_null(name)) {+ name = kt_name_child(stmt);+ }+ char *fname = kt_node_text(ctx, name);+ if (!fname) {+ return;+ }+ /* Register the local fn so call sites in the enclosing scope+ * can resolve it via kotlin_resolve_function_name. The QN is+ * "<enclosing_func_qn>.<fname>" so it's distinct from a top-level+ * function with the same short name. */+ const char *prev_func = ctx->enclosing_func_qn;+ const char *new_qn = kt_join_dot(ctx->arena, prev_func ? prev_func : ctx->module_qn, fname);+ {+ CBMRegisteredFunc lrf = {0};+ lrf.qualified_name = new_qn;+ lrf.short_name = fname;+ lrf.min_params = 0;+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, lrf);+ /* Also register a same-package alias so bare `inner()` calls+ * succeed via the same-package fallback in+ * kotlin_resolve_function_name. */+ if (ctx->package_qn && *ctx->package_qn) {+ CBMRegisteredFunc alias = lrf;+ alias.qualified_name = kt_join_dot(ctx->arena, ctx->package_qn, fname);+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, alias);+ } else {+ /* No package — register at root. */+ CBMRegisteredFunc alias = lrf;+ alias.qualified_name = cbm_arena_strdup(ctx->arena, fname);+ cbm_registry_add_func((CBMTypeRegistry *)ctx->registry, alias);+ }+ }+ ctx->enclosing_func_qn = new_qn;+ TSNode body = kt_field_named(stmt, "body");+ if (ts_node_is_null(body)) {+ body = kt_child_kind(stmt, "function_body");+ }+ if (ts_node_is_null(body)) {+ body = kt_child_kind(stmt, "block");+ }+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ kt_bind_function_params(ctx, stmt);+ if (!ts_node_is_null(body)) {+ kt_resolve_calls_in_node(ctx, body);+ }+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ ctx->enclosing_func_qn = prev_func;+ return;+ }+ if (strcmp(kind, "class_declaration") == 0 || strcmp(kind, "object_declaration") == 0) {+ /* Already registered in kt_collect_top_level_decls; recurse for nested */+ return;+ }+ if (strcmp(kind, "if_expression") == 0) {+ kt_process_if_expression(ctx, stmt);+ return;+ }+ if (strcmp(kind, "when_expression") == 0) {+ kt_process_when_expression(ctx, stmt);+ return;+ }+ if (strcmp(kind, "for_statement") == 0) {+ kt_process_for_statement(ctx, stmt);+ return;+ }+ if (strcmp(kind, "while_statement") == 0 || strcmp(kind, "do_while_statement") == 0) {+ kt_resolve_calls_in_node(ctx, stmt);+ return;+ }+ if (strcmp(kind, "try_expression") == 0) {+ kt_resolve_calls_in_node(ctx, stmt);+ return;+ }+ if (strcmp(kind, "call_expression") == 0) {+ kt_process_call_with_lambda(ctx, stmt);+ return;+ }+ if (strcmp(kind, "navigation_expression") == 0) {+ kt_eval_navigation_expression_type(ctx, stmt);+ return;+ }+ if (strcmp(kind, "block") == 0) {+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ kt_process_block_stmts(ctx, stmt);+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ return;+ }+ if (strcmp(kind, "assignment") == 0) {+ kt_resolve_calls_in_node(ctx, stmt);+ return;+ }+ /* Fallthrough: treat as expression — eval to populate scope, recurse for calls */+ kotlin_eval_expr_type(ctx, stmt);+ kt_resolve_calls_in_node(ctx, stmt);+}++/* Generic walker that fires call resolution on every call_expression in+ * a subtree, *without* descending into nested function/class bodies (those+ * are processed separately with their own scope). */+static void kt_resolve_calls_in_node(KotlinLSPContext *ctx, TSNode node) {+ if (ts_node_is_null(node)) {+ return;+ }+ const char *kind = ts_node_type(node);+ if (strcmp(kind, "function_declaration") == 0 || strcmp(kind, "class_declaration") == 0 ||+ strcmp(kind, "object_declaration") == 0 || strcmp(kind, "lambda_literal") == 0 ||+ strcmp(kind, "anonymous_function") == 0) {+ /* Skip — handled elsewhere */+ return;+ }+ if (strcmp(kind, "call_expression") == 0) {+ kt_process_call_with_lambda(ctx, node);+ } else if (strcmp(kind, "navigation_expression") == 0) {+ kt_eval_navigation_expression_type(ctx, node);+ } else if (strcmp(kind, "if_expression") == 0) {+ kt_process_if_expression(ctx, node);+ return;+ } else if (strcmp(kind, "when_expression") == 0) {+ kt_process_when_expression(ctx, node);+ return;+ } else if (strcmp(kind, "for_statement") == 0) {+ kt_process_for_statement(ctx, node);+ return;+ } else if (strcmp(kind, "property_declaration") == 0) {+ kt_bind_property_to_scope(ctx, node);+ }+ uint32_t nc = ts_node_child_count(node);+ for (uint32_t i = 0; i < nc; i++) {+ kt_resolve_calls_in_node(ctx, ts_node_child(node, i));+ }+}++static void kt_bind_function_params(KotlinLSPContext *ctx, TSNode func_node) {+ TSNode params = kt_field_named(func_node, "parameters");+ if (ts_node_is_null(params)) {+ params = kt_child_kind(func_node, "function_value_parameters");+ }+ if (ts_node_is_null(params)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(params);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(params, i);+ if (!kt_node_is(p, "parameter") && !kt_node_is(p, "_lambda_parameter")) {+ continue;+ }+ TSNode name = kt_field_named(p, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(p);+ }+ if (ts_node_is_null(name)) {+ name = kt_child_kind_named(p, "simple_identifier");+ }+ if (ts_node_is_null(name)) {+ continue;+ }+ char *pname = kt_node_text(ctx, name);+ if (!pname) {+ continue;+ }+ TSNode type_node = kt_field_named(p, "type");+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(p, "type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(p, "user_type");+ }+ if (ts_node_is_null(type_node)) {+ type_node = kt_child_kind(p, "nullable_type");+ }+ const CBMType *t = ts_node_is_null(type_node) ? cbm_type_unknown()+ : kotlin_parse_type_node(ctx, type_node);+ cbm_scope_bind(ctx->current_scope, cbm_arena_strdup(ctx->arena, pname), t);+ }++ /* For extension fun and method: bind `this` */+ if (ctx->this_type) {+ cbm_scope_bind(ctx->current_scope, "this", ctx->this_type);+ }+}++/* ── top-level walking ────────────────────────────────────────────── */++static void kt_process_function_body(KotlinLSPContext *ctx, TSNode func_node, const char *func_qn,+ const char *receiver_class_qn) {+ const char *prev_func = ctx->enclosing_func_qn;+ const char *prev_class = ctx->enclosing_class_qn;+ const CBMType *prev_this = ctx->this_type;+ const CBMType *prev_super = ctx->super_type;+ const char *prev_super_qn = ctx->enclosing_super_qn;++ ctx->enclosing_func_qn = func_qn;+ const CBMRegisteredType *receiver_rt = NULL;+ if (receiver_class_qn) {+ ctx->this_type = cbm_type_named(ctx->arena, receiver_class_qn);+ receiver_rt = cbm_registry_lookup_type(ctx->registry, receiver_class_qn);+ if (receiver_rt && receiver_rt->embedded_types && receiver_rt->embedded_types[0]) {+ ctx->enclosing_super_qn = receiver_rt->embedded_types[0];+ ctx->super_type = cbm_type_named(ctx->arena, receiver_rt->embedded_types[0]);+ }+ }++ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ kt_bind_function_params(ctx, func_node);++ /* Bind class fields (primary-constructor val/var properties) into the+ * method scope so bare references like `name.uppercase()` inside a+ * method body resolve to the field's type. */+ if (receiver_rt && receiver_rt->field_names && receiver_rt->field_types) {+ for (int i = 0; receiver_rt->field_names[i]; i++) {+ cbm_scope_bind(ctx->current_scope,+ cbm_arena_strdup(ctx->arena, receiver_rt->field_names[i]),+ receiver_rt->field_types[i]);+ }+ }++ TSNode body = kt_field_named(func_node, "body");+ if (ts_node_is_null(body)) {+ body = kt_child_kind(func_node, "function_body");+ }+ if (ts_node_is_null(body)) {+ body = kt_child_kind(func_node, "block");+ }+ /* Fallback: some grammar variants emit the single-expression body+ * directly as a child of function_declaration without wrapping it in+ * `function_body`. Scan the named children for the last node that+ * looks like an expression or statement (i.e. not modifiers, name,+ * type parameters, or value parameters). */+ if (ts_node_is_null(body)) {+ uint32_t nc = ts_node_named_child_count(func_node);+ for (uint32_t i = nc; i > 0; i--) {+ TSNode c = ts_node_named_child(func_node, i - 1);+ if (ts_node_is_null(c)) {+ continue;+ }+ const char *k = ts_node_type(c);+ if (strcmp(k, "modifiers") == 0 || strcmp(k, "identifier") == 0 ||+ strcmp(k, "simple_identifier") == 0 ||+ strcmp(k, "function_value_parameters") == 0 ||+ strcmp(k, "type_parameters") == 0 ||+ strcmp(k, "type_constraints") == 0 ||+ strcmp(k, "annotation") == 0) {+ continue;+ }+ /* Skip the return-type node — the return type appears AFTER+ * the parameters but is itself not the body. We identify it+ * heuristically: type-shaped nodes appearing immediately+ * after parameters when there's also a later body candidate.+ * Since we want the LAST candidate, we accept any non-skip+ * kind here — this is the body. */+ body = c;+ break;+ }+ }+ if (!ts_node_is_null(body)) {+ /* Three body shapes:+ * 1. `block` — { ... }, walk via kt_process_block_stmts so local+ * function declarations are registered before being called.+ * 2. `function_body` — wrapper around either a block or an expr.+ * 3. Bare expression — single-expression body.+ *+ * For (2) and (3) we walk every named child via+ * kt_resolve_calls_in_node, which already handles call_expression /+ * navigation_expression / nested constructs. We deliberately walk+ * ALL children of function_body (not just the first) because the+ * grammar may emit additional siblings under it (e.g. annotation+ * decorations) and we want to be conservative. We also evaluate+ * the body expression to populate any chained types. */+ if (kt_node_is(body, "block")) {+ kt_process_block_stmts(ctx, body);+ } else if (kt_node_is(body, "function_body")) {+ uint32_t nc = ts_node_named_child_count(body);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(body, i);+ if (ts_node_is_null(c)) {+ continue;+ }+ if (kt_node_is(c, "block") || kt_node_is(c, "statements")) {+ kt_process_block_stmts(ctx, c);+ } else {+ kt_resolve_calls_in_node(ctx, c);+ kotlin_eval_expr_type(ctx, c);+ }+ }+ } else {+ kt_resolve_calls_in_node(ctx, body);+ kotlin_eval_expr_type(ctx, body);+ }+ }++ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ ctx->enclosing_func_qn = prev_func;+ ctx->enclosing_class_qn = prev_class;+ ctx->this_type = prev_this;+ ctx->super_type = prev_super;+ ctx->enclosing_super_qn = prev_super_qn;+}++static void kt_walk_top_level_for_resolution(KotlinLSPContext *ctx, TSNode root,+ const char *enclosing_class_qn) {+ if (ts_node_is_null(root)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(root);+ if (ctx->debug) {+ fprintf(stderr, "[kotlin_lsp] walk_top_level enclosing=%s root_kind=%s nc=%u\n",+ enclosing_class_qn ? enclosing_class_qn : "(top)", ts_node_type(root), nc);+ }+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(root, i);+ const char *kind = ts_node_type(c);+ if (ctx->debug) {+ uint32_t sb = ts_node_start_byte(c);+ uint32_t eb = ts_node_end_byte(c);+ int len = (int)(eb - sb);+ if (len > 50) {+ len = 50;+ }+ fprintf(stderr, "[kotlin_lsp] child[%u]: %s '%.*s'\n", i, kind, len,+ ctx->source + sb);+ }+ /* Recurse into ERROR nodes so partial parses (e.g. when the+ * grammar can't parse `interface` at file scope) still get their+ * recoverable function/class bodies resolved. */+ if (strcmp(kind, "ERROR") == 0) {+ kt_walk_top_level_for_resolution(ctx, c, enclosing_class_qn);+ continue;+ }+ if (strcmp(kind, "function_declaration") == 0) {+ TSNode name = kt_field_named(c, "name");+ if (ts_node_is_null(name)) {+ name = kt_name_child(c);+ }+ char *fname = kt_node_text(ctx, name);+ if (!fname) {+ continue;+ }+ /* Detect extension receiver */+ TSNode receiver = kt_field_named(c, "receiver");+ const char *ext_recv_qn = NULL;+ if (!ts_node_is_null(receiver)) {+ char *rt = kt_node_text(ctx, receiver);+ if (rt) {+ char *lt = strchr(rt, '<');+ if (lt) {+ *lt = '\0';+ }+ size_t rl = strlen(rt);+ while (rl > 0 && rt[rl - 1] == '?') {+ rt[--rl] = '\0';+ }+ ext_recv_qn = kotlin_resolve_class_name(ctx, rt);+ }+ }+ char *func_qn = NULL;+ if (enclosing_class_qn) {+ func_qn = kt_join_dot(ctx->arena, enclosing_class_qn, fname);+ } else {+ func_qn = kt_join_dot(ctx->arena, ctx->package_qn, fname);+ }+ const char *recv_qn = enclosing_class_qn ? enclosing_class_qn : ext_recv_qn;+ kt_process_function_body(ctx, c, func_qn, recv_qn);+ } else if (strcmp(kind, "class_declaration") == 0 ||+ strcmp(kind, "object_declaration") == 0) {+ const char *cls_qn = kt_qn_for_class_decl(ctx, c);+ if (!cls_qn) {+ continue;+ }+ TSNode body = kt_child_kind(c, "class_body");+ if (ts_node_is_null(body)) {+ body = kt_child_kind(c, "enum_class_body");+ }+ const char *prev_class = ctx->enclosing_class_qn;+ ctx->enclosing_class_qn = cls_qn;+ kt_walk_top_level_for_resolution(ctx, body, cls_qn);+ ctx->enclosing_class_qn = prev_class;+ } else if (strcmp(kind, "companion_object") == 0) {+ const char *companion_qn =+ kt_join_dot(ctx->arena, enclosing_class_qn ? enclosing_class_qn : ctx->package_qn,+ "Companion");+ TSNode body = kt_child_kind(c, "class_body");+ kt_walk_top_level_for_resolution(ctx, body, companion_qn);+ } else if (strcmp(kind, "property_declaration") == 0) {+ /* Top-level property — bind into file scope and resolve calls+ * in initializer (with caller QN = property's getter QN). */+ const char *prev = ctx->enclosing_func_qn;+ char *prop_name = NULL;+ TSNode var = kt_child_kind(c, "variable_declaration");+ if (!ts_node_is_null(var)) {+ TSNode id = kt_name_child(var);+ if (ts_node_is_null(id)) {+ id = kt_child_kind_named(var, "simple_identifier");+ }+ if (!ts_node_is_null(id)) {+ prop_name = kt_node_text(ctx, id);+ }+ }+ if (prop_name) {+ ctx->enclosing_func_qn = kt_join_dot(+ ctx->arena, enclosing_class_qn ? enclosing_class_qn : ctx->package_qn,+ prop_name);+ }+ kt_bind_property_to_scope(ctx, c);+ kt_resolve_calls_in_node(ctx, c);+ ctx->enclosing_func_qn = prev;+ } else if (strcmp(kind, "secondary_constructor") == 0) {+ const char *prev_func = ctx->enclosing_func_qn;+ ctx->enclosing_func_qn = kt_join_dot(+ ctx->arena, enclosing_class_qn ? enclosing_class_qn : ctx->package_qn, "<init>");+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);+ kt_bind_function_params(ctx, c);+ TSNode body = kt_child_kind(c, "block");+ if (!ts_node_is_null(body)) {+ kt_process_block_stmts(ctx, body);+ }+ ctx->current_scope = cbm_scope_pop(ctx->current_scope);+ ctx->enclosing_func_qn = prev_func;+ } else if (strcmp(kind, "anonymous_initializer") == 0) {+ const char *prev_func = ctx->enclosing_func_qn;+ ctx->enclosing_func_qn = kt_join_dot(+ ctx->arena, enclosing_class_qn ? enclosing_class_qn : ctx->package_qn, "<init>");+ kt_resolve_calls_in_node(ctx, c);+ ctx->enclosing_func_qn = prev_func;+ }+ }+}++/* Debug AST dumper — only active when CBM_LSP_KOTLIN_AST=1 in env. */+static void kt_debug_dump_ast(TSNode node, const char *src, int depth) {+ if (depth > 8) {+ return;+ }+ const char *kind = ts_node_type(node);+ uint32_t sb = ts_node_start_byte(node);+ uint32_t eb = ts_node_end_byte(node);+ int len = (int)(eb - sb);+ if (len > 40) {+ len = 40;+ }+ fprintf(stderr, "%*s[%s] %.*s%s\n", depth * 2, "", kind, len, src + sb,+ (int)(eb - sb) > 40 ? "…" : "");+ uint32_t nc = ts_node_named_child_count(node);+ for (uint32_t i = 0; i < nc; i++) {+ kt_debug_dump_ast(ts_node_named_child(node, i), src, depth + 1);+ }+}++void kotlin_lsp_process_file(KotlinLSPContext *ctx, TSNode root) {+ if (ts_node_is_null(root)) {+ return;+ }+ if (getenv("CBM_LSP_KOTLIN_AST")) {+ fprintf(stderr, "=== AST for %s ===\n",+ ctx->rel_path ? ctx->rel_path : "<unknown>");+ kt_debug_dump_ast(root, ctx->source, 0);+ fprintf(stderr, "=== END AST ===\n");+ }++ /* 1. Package + imports */+ uint32_t nc = ts_node_named_child_count(root);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(root, i);+ const char *kind = ts_node_type(c);+ if (strcmp(kind, "package_header") == 0) {+ const char *pkg = kt_parse_package_header(ctx, c);+ if (pkg && *pkg) {+ ctx->package_qn = pkg;+ }+ } else if (strcmp(kind, "import_list") == 0) {+ /* Newer tree-sitter-kotlin wraps imports in an import_list node. */+ uint32_t inc = ts_node_named_child_count(c);+ for (uint32_t j = 0; j < inc; j++) {+ kt_parse_import_directive(ctx, ts_node_named_child(c, j));+ }+ } else if (strcmp(kind, "import") == 0 || strcmp(kind, "import_directive") == 0 ||+ strcmp(kind, "import_header") == 0) {+ kt_parse_import_directive(ctx, c);+ }+ }++ /* 2. Collect top-level definitions for intra-file resolution. */+ kt_collect_top_level_decls(ctx, root);++ /* 3. Walk for call resolution. */+ kt_walk_top_level_for_resolution(ctx, root, NULL);+}++static const CBMType *kt_try_smart_cast(KotlinLSPContext *ctx, TSNode call_or_nav) {+ /* Currently a stub — smart-cast is applied during if/when traversal. */+ (void)ctx;+ (void)call_or_nav;+ return NULL;+}++/* ── public entry point used by cbm.c dispatcher ──────────────────── */++/* Tree-sitter handle for re-parsing repaired sources. */+extern const TSLanguage *tree_sitter_kotlin(void);++/* Detect bodyless interface methods (`fun foo()` without `: ReturnType`+ * and without `{ … }`) inside `interface X { … }` bodies — the vendored+ * tree-sitter-kotlin grammar produces an `ERROR` node for these and+ * loses the rest of the file. We patch the source by inserting `: Unit`+ * right after the closing paren of each affected method, then re-parse+ * with tree-sitter.+ *+ * Heuristic and intentionally permissive: walk the source byte-by-byte,+ * track whether we're inside an `interface ... { ... }` block (depth+ * counter on '{' / '}') and, while inside, look for `fun ` followed by+ * an identifier, optional whitespace, '(', balanced parens, then check+ * what follows — if it's whitespace + (',' | ';' | '\n' | '}' ) without+ * an intervening ':' or '=' or '{', insert `: Unit`.+ *+ * Returns NULL when no patches were applied (caller keeps original+ * source). Otherwise the returned arena-allocated buffer is a complete+ * patched source. */+static char *kt_repair_bodyless_interface_methods(CBMArena *arena, const char *src, int src_len,+ int *out_len) {+ if (!src || src_len <= 0) {+ return NULL;+ }+ /* Cheap early-out: skip when neither `interface` nor a function-type+ * with a receiver (`X.() ->`) appears anywhere — those are the two+ * grammar pain points this pass repairs. */+ if (!strstr(src, "interface") && !strstr(src, ".() ->") &&+ !strstr(src, ".()->")) {+ return NULL;+ }++ /* Two-pass: first scan to find insertion points, then build.+ * Each fix has an offset (insert BEFORE this src index) and an+ * insertion string. The insertion strings are static const so they+ * don't need to be arena-copied. */+ enum {+ MAX_FIXES = 64,+ };+ typedef struct {+ int offset;+ const char *text;+ int text_len;+ } kt_fix_t;+ kt_fix_t fixes[MAX_FIXES];+ int fix_count = 0;+ static const char insert_unit[] = ": Unit";+ static const int insert_unit_len = (int)(sizeof(insert_unit) - 1);+ static const char insert_parens[] = "()";+ static const int insert_parens_len = (int)(sizeof(insert_parens) - 1);++ const char *p = src;+ const char *end = src + src_len;+ int iface_depth = 0; /* nesting of `interface ... { ... }` blocks */+ int brace_depth = 0; /* total braces (so we can subtract on '}') */+ int iface_brace_at[16]; /* brace_depth at which each interface opened */+ int iface_stack_n = 0;++ while (p < end) {+ char c = *p;+ /* Skip line comments */+ if (c == '/' && p + 1 < end && p[1] == '/') {+ while (p < end && *p != '\n') {+ p++;+ }+ continue;+ }+ /* Skip block comments */+ if (c == '/' && p + 1 < end && p[1] == '*') {+ p += 2;+ while (p + 1 < end && !(*p == '*' && p[1] == '/')) {+ p++;+ }+ if (p + 1 < end) {+ p += 2;+ } else {+ p = end;+ }+ continue;+ }+ /* Skip string literals */+ if (c == '"') {+ p++;+ while (p < end && *p != '"') {+ if (*p == '\\' && p + 1 < end) {+ p += 2;+ } else {+ p++;+ }+ }+ if (p < end) {+ p++;+ }+ continue;+ }++ /* Detect `interface ` keyword at word boundary */+ if (c == 'i' && p + 9 < end && strncmp(p, "interface", 9) == 0 &&+ (p == src || !isalnum((unsigned char)p[-1])) &&+ (isspace((unsigned char)p[9]) || p[9] == '\n')) {+ /* Skip ahead to opening brace of interface body */+ const char *q = p + 9;+ while (q < end && *q != '{' && *q != ';' && *q != '\n') {+ q++;+ }+ if (q < end && *q == '{') {+ if (iface_stack_n < 16) {+ iface_brace_at[iface_stack_n++] = brace_depth;+ }+ iface_depth++;+ brace_depth++;+ p = q + 1;+ continue;+ }+ p = q;+ continue;+ }++ if (c == '{') {+ brace_depth++;+ p++;+ continue;+ }+ if (c == '}') {+ brace_depth--;+ if (iface_stack_n > 0 && iface_brace_at[iface_stack_n - 1] == brace_depth) {+ iface_stack_n--;+ iface_depth--;+ }+ p++;+ continue;+ }++ /* Inside an interface body, detect `fun NAME(...)` followed by+ * end-of-statement without a return type or body. */+ if (iface_depth > 0 && c == 'f' && p + 3 < end && strncmp(p, "fun", 3) == 0 &&+ (p == src || !isalnum((unsigned char)p[-1])) &&+ (isspace((unsigned char)p[3]) || p[3] == '\n')) {+ const char *q = p + 3;+ while (q < end && (isspace((unsigned char)*q) || *q == '\n')) {+ q++;+ }+ /* Identifier */+ while (q < end &&+ (isalnum((unsigned char)*q) || *q == '_' || *q == '`')) {+ q++;+ }+ /* Optional generic type parameters */+ if (q < end && *q == '<') {+ int g = 1;+ q++;+ while (q < end && g > 0) {+ if (*q == '<') {+ g++;+ } else if (*q == '>') {+ g--;+ }+ q++;+ }+ }+ /* Optional whitespace, then '(' */+ while (q < end && (isspace((unsigned char)*q) || *q == '\n')) {+ q++;+ }+ if (q >= end || *q != '(') {+ p++;+ continue;+ }+ int paren = 1;+ q++;+ while (q < end && paren > 0) {+ if (*q == '(') {+ paren++;+ } else if (*q == ')') {+ paren--;+ }+ q++;+ }+ /* q is now positioned just past the ')'. */+ int paren_close = (int)(q - src) - 1;+ /* Skip whitespace */+ const char *r = q;+ while (r < end && (*r == ' ' || *r == '\t')) {+ r++;+ }+ /* Check what follows */+ if (r < end && (*r == ':' || *r == '=' || *r == '{')) {+ /* Has return type, body, or expression — fine. */+ p = r;+ continue;+ }+ /* Bodyless / no return type — insert `: Unit` after the ')'. */+ if (fix_count < MAX_FIXES) {+ fixes[fix_count].offset = paren_close + 1;+ fixes[fix_count].text = insert_unit;+ fixes[fix_count].text_len = insert_unit_len;+ fix_count++;+ }+ p = r;+ continue;+ }+ p++;+ }++ /* Second pass: strip the receiver-with-dot from `<Type>.() -> X`+ * function-type patterns. The vendored grammar can't parse the+ * receiver-style function type at file scope, so removing the+ * `<Type>.` prefix preserves parseability while losing only the+ * receiver-binding hint (which we recover separately via+ * decorator_qns at registration time). */+ typedef struct {+ int start; /* inclusive */+ int end; /* exclusive */+ } cut_range_t;+ enum { MAX_CUTS = 64 };+ cut_range_t cuts[MAX_CUTS];+ int cut_count = 0;+ {+ const char *p2 = src;+ const char *end2 = src + src_len;+ while (p2 < end2 - 4) {+ /* Skip strings/comments to keep things simple */+ if (*p2 == '"') {+ p2++;+ while (p2 < end2 && *p2 != '"') {+ if (*p2 == '\\' && p2 + 1 < end2) {+ p2 += 2;+ } else {+ p2++;+ }+ }+ if (p2 < end2) {+ p2++;+ }+ continue;+ }+ if (*p2 == '/' && p2 + 1 < end2 && p2[1] == '/') {+ while (p2 < end2 && *p2 != '\n') {+ p2++;+ }+ continue;+ }+ if (*p2 == '/' && p2 + 1 < end2 && p2[1] == '*') {+ p2 += 2;+ while (p2 + 1 < end2 && !(*p2 == '*' && p2[1] == '/')) {+ p2++;+ }+ p2 += (p2 + 1 < end2 ? 2 : 1);+ continue;+ }+ /* Look for `.()` */+ if (*p2 == '.' && p2 + 2 < end2 && p2[1] == '(' && p2[2] == ')') {+ /* Walk backwards to find the identifier preceding '.' */+ const char *q = p2 - 1;+ while (q > src && (*q == ' ' || *q == '\t')) {+ q--;+ }+ /* q now points at the last char of the identifier (or+ * a non-identifier character). */+ const char *id_end = q + 1;+ while (q >= src &&+ (isalnum((unsigned char)*q) || *q == '_' || *q == '`')) {+ q--;+ }+ const char *id_start = q + 1;+ if (id_start >= id_end) {+ p2++;+ continue;+ }+ /* Look ahead past `.()` for ` -> ` or `->` to confirm+ * this is a function-type receiver and not a method+ * reference. */+ const char *r = p2 + 3;+ while (r < end2 && (*r == ' ' || *r == '\t')) {+ r++;+ }+ if (r + 1 >= end2 || r[0] != '-' || r[1] != '>') {+ p2++;+ continue;+ }+ /* Cut range: from id_start to (p2+1), removing the+ * "<Name>." prefix and leaving "()". */+ if (cut_count < MAX_CUTS) {+ cuts[cut_count].start = (int)(id_start - src);+ cuts[cut_count].end = (int)(p2 + 1 - src);+ cut_count++;+ }+ p2 += 3;+ continue;+ }+ p2++;+ }+ }++ /* Third pass: add `()` after `: <Type>` in class delegation when+ * the next token is `{` (interface inheritance). The vendored+ * tree-sitter-kotlin grammar treats `class X : Y { ... }` as a+ * parse error and produces an ERROR node swallowing the rest of+ * the file; rewriting to `class X : Y() { ... }` keeps the parse+ * intact (even though, for interface inheritance, parens are+ * non-idiomatic Kotlin). We only insert when no parens already+ * follow the type. */+ {+ const char *p3 = src;+ const char *end3 = src + src_len;+ while (p3 < end3) {+ if (*p3 == '"') {+ p3++;+ while (p3 < end3 && *p3 != '"') {+ if (*p3 == '\\' && p3 + 1 < end3) {+ p3 += 2;+ } else {+ p3++;+ }+ }+ if (p3 < end3) {+ p3++;+ }+ continue;+ }+ if (*p3 == '/' && p3 + 1 < end3 && p3[1] == '/') {+ while (p3 < end3 && *p3 != '\n') {+ p3++;+ }+ continue;+ }+ if (*p3 == '/' && p3 + 1 < end3 && p3[1] == '*') {+ p3 += 2;+ while (p3 + 1 < end3 && !(*p3 == '*' && p3[1] == '/')) {+ p3++;+ }+ p3 += (p3 + 1 < end3 ? 2 : 1);+ continue;+ }+ if (*p3 == ':' && p3 + 1 < end3 &&+ (p3[1] == ' ' || p3[1] == '\t' || p3[1] == '\n')) {+ /* Walk back: ensure preceded by `class IDENT[(params)]?`. */+ /* Walk forward: skip ws, read identifier (possibly dotted),+ * skip generics, then check for parens or `{`. */+ const char *q = p3 + 1;+ while (q < end3 && (*q == ' ' || *q == '\t' || *q == '\n')) {+ q++;+ }+ /* dotted identifier */+ while (q < end3 && (isalnum((unsigned char)*q) || *q == '_' || *q == '.')) {+ q++;+ }+ /* generics? */+ if (q < end3 && *q == '<') {+ int g = 1;+ q++;+ while (q < end3 && g > 0) {+ if (*q == '<') {+ g++;+ } else if (*q == '>') {+ g--;+ }+ q++;+ }+ }+ /* Skip ws */+ while (q < end3 && (*q == ' ' || *q == '\t' || *q == '\n')) {+ q++;+ }+ if (q >= end3) {+ p3++;+ continue;+ }+ if (*q == '(') {+ /* Already has parens. */+ p3 = q;+ continue;+ }+ if (*q != '{') {+ p3++;+ continue;+ }+ /* Walk back to verify this is class inheritance: look for+ * "class " keyword on the same logical line before `:`. */+ const char *back = p3 - 1;+ while (back > src && *back != '\n' && back > p3 - 200) {+ back--;+ }+ if (back <= src || back < p3 - 200) {+ p3++;+ continue;+ }+ if (!strstr(back, "class ") && !strstr(back, "object ")) {+ p3++;+ continue;+ }+ /* Insert `()` right before `{` (which is at position q). */+ if (fix_count < MAX_FIXES) {+ fixes[fix_count].offset = (int)(q - src);+ fixes[fix_count].text = insert_parens;+ fixes[fix_count].text_len = insert_parens_len;+ fix_count++;+ }+ p3 = q;+ continue;+ }+ p3++;+ }+ }++ if (fix_count == 0 && cut_count == 0) {+ return NULL;+ }++ /* Sort cuts by start offset (small N — bubble sort is fine). */+ for (int i = 0; i < cut_count - 1; i++) {+ for (int j = i + 1; j < cut_count; j++) {+ if (cuts[j].start < cuts[i].start) {+ cut_range_t tmp = cuts[i];+ cuts[i] = cuts[j];+ cuts[j] = tmp;+ }+ }+ }++ /* Sort fixes by offset (different passes may interleave). */+ for (int i = 0; i < fix_count - 1; i++) {+ for (int j = i + 1; j < fix_count; j++) {+ if (fixes[j].offset < fixes[i].offset) {+ kt_fix_t tmp = fixes[i];+ fixes[i] = fixes[j];+ fixes[j] = tmp;+ }+ }+ }++ /* Build patched source. Cuts remove a [start, end) range. */+ int new_len = src_len;+ for (int i = 0; i < fix_count; i++) {+ new_len += fixes[i].text_len;+ }+ for (int i = 0; i < cut_count; i++) {+ new_len -= (cuts[i].end - cuts[i].start);+ }+ char *out = (char *)cbm_arena_alloc(arena, (size_t)new_len + 1);+ if (!out) {+ return NULL;+ }+ int oi = 0;+ int next_fix = 0;+ int next_cut = 0;+ for (int i = 0; i <= src_len; i++) {+ while (next_fix < fix_count && fixes[next_fix].offset == i) {+ memcpy(out + oi, fixes[next_fix].text, (size_t)fixes[next_fix].text_len);+ oi += fixes[next_fix].text_len;+ next_fix++;+ }+ /* Skip range [start, end) when cutting */+ if (next_cut < cut_count && cuts[next_cut].start == i) {+ i = cuts[next_cut].end - 1; /* loop's i++ moves past `end-1` */+ next_cut++;+ continue;+ }+ if (i < src_len) {+ out[oi++] = src[i];+ }+ }+ out[oi] = '\0';+ if (out_len) {+ *out_len = oi;+ }+ return out;+}++void cbm_run_kotlin_lsp(CBMArena *arena, CBMFileResult *result, const char *source,+ int source_len, TSNode root) {+ if (!arena || !result || !source || ts_node_is_null(root)) {+ return;+ }++ /* Repair pass: if the source uses interface declarations with+ * bodyless `fun X()` methods or function-types with receivers+ * (`Foo.() -> X`), our vendored tree-sitter grammar produces+ * ERROR nodes and loses parts of the file. Patch the source and+ * re-parse. */+ int patched_len = 0;+ char *patched_src = kt_repair_bodyless_interface_methods(arena, source, source_len,+ &patched_len);+ TSTree *patched_tree = NULL;+ TSNode use_root = root;+ const char *use_source = source;+ int use_source_len = source_len;+ bool debug = (getenv("CBM_LSP_DEBUG") != NULL);+ if (debug && patched_src) {+ fprintf(stderr, "[kotlin_lsp] preprocessed %d → %d bytes\n", source_len, patched_len);+ fprintf(stderr, "[kotlin_lsp] patched source:\n%s\n[end patched]\n", patched_src);+ } else if (debug) {+ fprintf(stderr, "[kotlin_lsp] no preprocessing applied (no interface or .() patterns)\n");+ }+ if (patched_src) {+ TSParser *parser = ts_parser_new();+ if (parser) {+ const TSLanguage *lang = tree_sitter_kotlin();+ if (debug) {+ fprintf(stderr, "[kotlin_lsp] tree_sitter_kotlin lang=%p\n", (void *)lang);+ }+ ts_parser_set_language(parser, lang);+ patched_tree = ts_parser_parse_string(parser, NULL, patched_src,+ (uint32_t)patched_len);+ ts_parser_delete(parser);+ if (debug) {+ fprintf(stderr, "[kotlin_lsp] re-parse result tree=%p\n", (void *)patched_tree);+ }+ if (patched_tree) {+ use_root = ts_tree_root_node(patched_tree);+ use_source = patched_src;+ use_source_len = patched_len;+ }+ }+ }++ /* Build per-file registry. */+ CBMTypeRegistry registry;+ cbm_registry_init(®istry, arena);++ /* Curated stdlib */+ cbm_kotlin_stdlib_register(®istry, arena);++ /* Compute project name + package_qn from result->module_qn (which is+ * "<project>.<rel.path.parts>"). The Kotlin convention places the+ * file class as "<project>.<package>" — or "<project>.<rel-path>" for+ * the module_qn. We honour module_qn as-is and strip the trailing+ * filename to derive the package_qn at the FS-path level — but for+ * cross-file resolution we additionally need the dotted package+ * declared in the source. The kotlin_lsp_process_file pass updates+ * package_qn from the actual `package_header` node when present.+ */+ const char *project_name = "";+ const char *module_qn = result->module_qn ? result->module_qn : "";+ const char *first_dot = strchr(module_qn, '.');+ if (first_dot) {+ size_t pl = (size_t)(first_dot - module_qn);+ char *pn = (char *)cbm_arena_alloc(arena, pl + 1);+ if (pn) {+ memcpy(pn, module_qn, pl);+ pn[pl] = '\0';+ project_name = pn;+ }+ } else {+ project_name = module_qn;+ }++ /* Initial package_qn is empty — overridden by kotlin_lsp_process_file+ * when it sees the `package_header` AST node. */+ KotlinLSPContext ctx;+ kotlin_lsp_init(&ctx, arena, use_source, use_source_len, ®istry, "", module_qn,+ project_name, /*rel_path=*/NULL, &result->resolved_calls);++ kotlin_lsp_process_file(&ctx, use_root);++ if (patched_tree) {+ ts_tree_delete(patched_tree);+ }+}diff --git a/internal/cbm/lsp/kotlin_lsp.h b/internal/cbm/lsp/kotlin_lsp.hnew file mode 100644index 000000000..f44165abb--- /dev/null+++ b/internal/cbm/lsp/kotlin_lsp.h@@ -0,0 +1,168 @@+/*+ * kotlin_lsp.h — Kotlin Light Semantic Pass.+ *+ * In-process type-aware call resolver for Kotlin. Mirrors go_lsp / php_lsp+ * shape: a per-file pass that walks the tree-sitter Kotlin AST, tracks+ * scope, infers expression types, and emits CBMResolvedCall entries for+ * call_expression / navigation_expression nodes whose target FQN can be+ * determined statically.+ *+ * Reverse-engineered from the fwcd kotlin-language-server reference+ * implementation (Kotlin compiler frontend) plus the official Kotlin+ * language specification — distilled into a pure-C resolver with no JVM+ * dependency. The goal is ≥ 90% quality parity with the LSP for the+ * call-edge and method-dispatch attribution problems CBM cares about.+ *+ * The Kotlin features handled:+ * - Package declaration (`package a.b.c`)+ * - Default Kotlin imports (kotlin.*, kotlin.collections.*, etc.)+ * - Explicit imports with optional `as` aliases+ * - Wildcard imports (`import a.b.*`)+ * - Top-level functions and properties+ * - Class / interface / object / data class / enum / sealed class+ * - Companion objects (named and anonymous) with `Foo.bar()` static-style dispatch+ * - Primary and secondary constructors (incl. `class Foo(val x: Int)`)+ * - Inheritance: delegation_specifier list, super-method lookup+ * - Extension functions and properties (`fun String.uppercaseFirst()`)+ * - Infix and operator functions (`a foo b`, `a + b`)+ * - Smart casts after `is` / `as` / null-checks+ * - Generics (basic substitution; we track but don't fully unify)+ * - Nullable types (T?), safe calls (?.) and not-null assertions (!!)+ * - `lateinit var` and `by` delegation (best-effort)+ * - Lambdas with implicit `it` parameter+ * - `with`, `let`, `also`, `apply`, `run`, `takeIf` scope functions+ * - `when` expressions with subject smart-cast+ * - `object` declarations as singletons+ *+ * Out of scope (low value or impractical without the Kotlin compiler):+ * - Reified generics across call boundaries+ * - Full type unification with constraints+ * - Decompilation of compiled Kotlin/Java bytecode+ * - DSL-style type-safe builders beyond direct lambda receivers+ * - Inline class boxing/unboxing+ *+ * The unresolved fallthrough goes to the registry's name-based matcher,+ * just like Go/Python/PHP. We never produce *worse* attribution than the+ * pre-LSP baseline; if the LSP can't decide, it emits nothing.+ */+#ifndef CBM_LSP_KOTLIN_LSP_H+#define CBM_LSP_KOTLIN_LSP_H++#include "type_rep.h"+#include "scope.h"+#include "type_registry.h"+#include "../cbm.h"++/* Use-kind for `import a.b.c.foo` — tracks whether the import refers to a+ * type, a function/extension, a property, or an object. Determines how+ * `foo` is resolved when used as a bare identifier. */+typedef enum {+ CBM_KT_USE_UNKNOWN = 0,+ CBM_KT_USE_TYPE, /* class / interface / object / typealias */+ CBM_KT_USE_FUNCTION, /* top-level fun, extension fun */+ CBM_KT_USE_PROPERTY, /* top-level val/var */+ CBM_KT_USE_WILDCARD, /* import a.b.* — local_name is a.b prefix */+} CBMKotlinUseKind;++/* KotlinLSPContext — per-file state for Kotlin call resolution. */+typedef struct KotlinLSPContext {+ CBMArena *arena;+ const char *source;+ int source_len;+ const CBMTypeRegistry *registry;+ CBMScope *current_scope;++ /* Package context. Empty string for default package. */+ const char *package_qn; /* dotted form, e.g. "com.example.foo" */+ const char *module_qn; /* file-level QN, e.g. "<project>.com.example.foo.<File>" */+ const char *project_name; /* project prefix (without trailing dot) */+ const char *file_class_qn; /* JVM file-class QN, "<package>.<File>Kt" */+ const char *rel_path; /* for diagnostics */++ /* Import map (parallel arrays). Kotlin imports are flat — no grouping+ * — but each may have an `as` alias. Wildcard imports record the+ * package prefix in `import_targets[i]` with `import_kinds[i] = WILDCARD`+ * and `import_locals[i] = NULL`. */+ const char **import_locals; /* alias name (or short name) used in code */+ const char **import_targets; /* full FQN being imported */+ CBMKotlinUseKind *import_kinds;+ int import_count;+ int import_cap;++ /* Current declaration context. */+ const char *enclosing_func_qn; /* function we are resolving inside */+ const char *enclosing_class_qn; /* innermost class/interface/object QN, or NULL */+ const char *enclosing_companion_qn; /* if inside a companion object body */+ const char *enclosing_super_qn; /* primary super-class QN of current class, or NULL */++ /* Current `this` and `super` types. */+ const CBMType *this_type;+ const CBMType *super_type;++ /* `it` lambda parameter type, when inside a single-arg lambda.+ * Saved/restored across nested lambdas. */+ const CBMType *it_type;++ /* Output: resolved calls accumulate here. */+ CBMResolvedCallArray *resolved_calls;++ /* Recursion guard for kotlin_eval_expr_type. */+ int eval_depth;++ /* Debug mode (CBM_LSP_DEBUG env). */+ bool debug;+} KotlinLSPContext;++/* Initialize a KotlinLSPContext for processing one file. */+void kotlin_lsp_init(KotlinLSPContext *ctx, CBMArena *arena, const char *source, int source_len,+ const CBMTypeRegistry *registry, const char *package_qn,+ const char *module_qn, const char *project_name, const char *rel_path,+ CBMResolvedCallArray *out);++/* Add an import mapping. local_name is the name used in code (alias or+ * short name); target_qn is the full dotted FQN. For wildcard imports,+ * pass the package prefix as target_qn and CBM_KT_USE_WILDCARD as kind. */+void kotlin_lsp_add_import(KotlinLSPContext *ctx, const char *local_name, const char *target_qn,+ CBMKotlinUseKind kind);++/* Walk a file's AST: top-level decls, then function/method bodies. */+void kotlin_lsp_process_file(KotlinLSPContext *ctx, TSNode root);++/* Evaluate a Kotlin expression's type. Returns cbm_type_unknown() on+ * failure — never NULL. */+const CBMType *kotlin_eval_expr_type(KotlinLSPContext *ctx, TSNode node);++/* Parse a Kotlin type-AST node (user_type, nullable_type, function_type, …)+ * to CBMType. */+const CBMType *kotlin_parse_type_node(KotlinLSPContext *ctx, TSNode node);++/* Resolve a bare class name (possibly qualified like "Foo" or "a.Foo")+ * to its full QN using current package + import map. NULL if unresolved. */+const char *kotlin_resolve_class_name(KotlinLSPContext *ctx, const char *name);++/* Resolve a bare top-level function name to its target QN. */+const char *kotlin_resolve_function_name(KotlinLSPContext *ctx, const char *name);++/* Look up a method on a class, walking the super-chain (registry-based). */+const CBMRegisteredFunc *kotlin_lookup_method(KotlinLSPContext *ctx, const char *class_qn,+ const char *method_name);++/* Look up a property/field on a class, walking super-chain. */+const CBMType *kotlin_lookup_property_type(KotlinLSPContext *ctx, const char *class_qn,+ const char *prop_name);++/* Entry point: build registry from file defs + stdlib, then run resolution.+ * Called from cbm_extract_file() after definitions and imports have been+ * extracted. */+void cbm_run_kotlin_lsp(CBMArena *arena, CBMFileResult *result, const char *source,+ int source_len, TSNode root);++/* Register the curated Kotlin stdlib (kotlin.*, kotlin.collections.*, …)+ * into a registry. Implemented in lsp/generated/kotlin_stdlib_data.c. */+void cbm_kotlin_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);++/* Register Kotlin default-import targets — the prefixes auto-imported+ * by every Kotlin file. Used by the LSP context init. */+const char *const *cbm_kotlin_default_import_packages(int *count_out);++#endif /* CBM_LSP_KOTLIN_LSP_H */diff --git a/internal/cbm/lsp_all.c b/internal/cbm/lsp_all.cindex 0d6818c09..d4c55a885 100644--- a/internal/cbm/lsp_all.c+++ b/internal/cbm/lsp_all.c@@ -19,3 +19,5 @@#include "lsp/generated/cs_stdlib_data.c"#include "lsp/java_lsp.c"#include "lsp/generated/java_stdlib_data.c"+#include "lsp/generated/kotlin_stdlib_data.c"+#include "lsp/kotlin_lsp.c"diff --git a/tests/test_kotlin_lsp.c b/tests/test_kotlin_lsp.cnew file mode 100644index 000000000..ed0f6cf22--- /dev/null+++ b/tests/test_kotlin_lsp.c@@ -0,0 +1,1192 @@+/*+ * test_kotlin_lsp.c — Tests for Kotlin LSP type-aware call resolution.+ *+ * Coverage areas (mirrors fwcd kotlin-language-server's reference test+ * suite at a feature level — we don't run their JVM tests, we test+ * equivalent semantic outcomes through our pure-C resolver):+ *+ * 1. Package + import resolution (default, explicit, alias, wildcard)+ * 2. Top-level function calls+ * 3. Class instantiation (constructor calls)+ * 4. Method dispatch on instance+ * 5. Companion object dispatch (Foo.bar() static-style)+ * 6. Object singleton dispatch+ * 7. Extension functions+ * 8. Inheritance / super-method lookup+ * 9. Smart-casts after `is`, `as`, `as?`+ * 10. Nullable types and safe calls (?.)+ * 11. Lambda `it` parameter type propagation+ * 12. Scope functions (let, run, also, apply, with, takeIf, takeUnless)+ * 13. Type aliases+ * 14. Generic type parameters (basic)+ * 15. Constructor parameter properties (val/var in primary constructor)+ * 16. Enum classes+ * 17. Data classes+ * 18. Sealed classes+ * 19. Interface dispatch+ * 20. Stdlib resolution (println, listOf, mapOf, ...)+ * 21. Quality parity benchmarks vs tree-sitter-only baseline+ */+#include "test_framework.h"+#include "cbm.h"+#include "lsp/kotlin_lsp.h"+#include <string.h>++/* ── helpers ───────────────────────────────────────────────── */++static CBMFileResult *extract_kotlin(const char *source) {+ return cbm_extract_file(source, (int)strlen(source), CBM_LANG_KOTLIN, "test", "Main.kt", 0,+ NULL, NULL);+}++static CBMFileResult *extract_kotlin_path(const char *source, const char *rel_path) {+ return cbm_extract_file(source, (int)strlen(source), CBM_LANG_KOTLIN, "test", rel_path, 0,+ NULL, NULL);+}++/* Search resolved_calls for a match where caller contains callerSub+ * and callee contains calleeSub. Returns index or -1. */+static int find_resolved(const CBMFileResult *r, const char *callerSub, const char *calleeSub) {+ for (int i = 0; i < r->resolved_calls.count; i++) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];+ if (rc->caller_qn && strstr(rc->caller_qn, callerSub) && rc->callee_qn &&+ strstr(rc->callee_qn, calleeSub)) {+ return i;+ }+ }+ return -1;+}++static int require_resolved(const CBMFileResult *r, const char *callerSub, const char *calleeSub) {+ int idx = find_resolved(r, callerSub, calleeSub);+ if (idx < 0) {+ printf(" MISSING resolved call: caller~%s -> callee~%s (have %d)\n", callerSub, calleeSub,+ r->resolved_calls.count);+ for (int i = 0; i < r->resolved_calls.count; i++) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];+ printf(" %s -> %s [%s %.2f]\n", rc->caller_qn ? rc->caller_qn : "(null)",+ rc->callee_qn ? rc->callee_qn : "(null)", rc->strategy ? rc->strategy : "(null)",+ rc->confidence);+ }+ }+ return idx;+}++static int count_resolved(const CBMFileResult *r, const char *callerSub, const char *calleeSub) {+ int n = 0;+ for (int i = 0; i < r->resolved_calls.count; i++) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];+ if (rc->caller_qn && strstr(rc->caller_qn, callerSub) && rc->callee_qn &&+ strstr(rc->callee_qn, calleeSub)) {+ n++;+ }+ }+ return n;+}++/* ── 1. Package + import resolution ────────────────────────── */++TEST(ktlsp_package_set) {+ CBMFileResult *r = extract_kotlin("package com.example.foo\n\n"+ "fun greet() { println(\"hi\") }\n");+ ASSERT_NOT_NULL(r);+ /* greet should resolve to println in kotlin.io */+ ASSERT_GTE(require_resolved(r, "greet", "println"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_explicit_import_function) {+ CBMFileResult *r = extract_kotlin("package com.example\n\n"+ "import kotlin.io.println\n\n"+ "fun greet() { println(\"hi\") }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "greet", "println"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_explicit_import_type) {+ CBMFileResult *r = extract_kotlin("package com.example\n\n"+ "import java.io.File\n\n"+ "fun open(): File = File(\"/tmp/x\")\n");+ ASSERT_NOT_NULL(r);+ /* File() constructor resolved */+ ASSERT_GTE(require_resolved(r, "open", "File"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_import_alias) {+ CBMFileResult *r = extract_kotlin("package com.example\n\n"+ "import java.io.File as JFile\n\n"+ "fun open(): JFile = JFile(\"/tmp/x\")\n");+ ASSERT_NOT_NULL(r);+ /* The constructor target should still resolve to java.io.File */+ ASSERT_GTE(require_resolved(r, "open", "File"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_wildcard_import) {+ CBMFileResult *r = extract_kotlin("package com.example\n\n"+ "import kotlin.collections.*\n\n"+ "fun build() = listOf(1, 2, 3)\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "build", "listOf"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 2. Top-level function calls ───────────────────────────── */++TEST(ktlsp_top_level_call_default_imports) {+ CBMFileResult *r = extract_kotlin("fun main() { println(\"hi\") }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "println"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_top_level_listof) {+ CBMFileResult *r = extract_kotlin("fun build() { val xs = listOf(1, 2, 3) }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "build", "listOf"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_top_level_setof_mapof) {+ CBMFileResult *r = extract_kotlin("fun build() {\n"+ " val s = setOf(1, 2, 3)\n"+ " val m = mapOf(\"a\" to 1, \"b\" to 2)\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "build", "setOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "mapOf"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_intra_file_top_level) {+ CBMFileResult *r = extract_kotlin("package myapp\n\n"+ "fun helper(x: Int): Int = x + 1\n"+ "fun main() { val r = helper(42) }\n");+ ASSERT_NOT_NULL(r);+ /* main should resolve to helper */+ ASSERT_GTE(require_resolved(r, "main", "helper"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 3. Class instantiation ────────────────────────────────── */++TEST(ktlsp_class_constructor) {+ CBMFileResult *r = extract_kotlin("class Greeter(val name: String) {\n"+ " fun greet() = println(\"Hello, $name\")\n"+ "}\n"+ "fun main() { val g = Greeter(\"world\"); g.greet() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "Greeter"), 0);+ /* Method dispatch on g */+ ASSERT_GTE(require_resolved(r, "main", "greet"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_data_class) {+ CBMFileResult *r = extract_kotlin("data class User(val id: Int, val name: String)\n"+ "fun create(): User = User(1, \"Alice\")\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "create", "User"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_secondary_constructor) {+ CBMFileResult *r = extract_kotlin("class Box {\n"+ " constructor() {}\n"+ " constructor(x: Int) {}\n"+ " fun open() {}\n"+ "}\n"+ "fun main() { val b = Box(); b.open() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "Box"), 0);+ ASSERT_GTE(require_resolved(r, "main", "open"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 4. Method dispatch ────────────────────────────────────── */++TEST(ktlsp_method_on_known_type) {+ CBMFileResult *r = extract_kotlin("class Service {\n"+ " fun query(sql: String): String = \"\"\n"+ "}\n"+ "fun work(s: Service) { s.query(\"SELECT 1\") }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "work", "query"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_method_chain) {+ CBMFileResult *r = extract_kotlin("class Builder {\n"+ " fun add(s: String): Builder = this\n"+ " fun build(): String = \"\"\n"+ "}\n"+ "fun make(b: Builder): String = b.add(\"x\").build()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "make", "add"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_string_method_dispatch) {+ CBMFileResult *r = extract_kotlin("fun shout(s: String): String = s.uppercase()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "shout", "uppercase"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_list_method_dispatch) {+ CBMFileResult *r = extract_kotlin("fun first_n(xs: List<Int>): List<Int> = xs.take(3)\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "first_n", "take"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 5. Companion object dispatch ──────────────────────────── */++TEST(ktlsp_companion_object_call) {+ CBMFileResult *r = extract_kotlin("class Logger {\n"+ " companion object {\n"+ " fun create(): Logger = Logger()\n"+ " }\n"+ "}\n"+ "fun main() { val log = Logger.create() }\n");+ ASSERT_NOT_NULL(r);+ /* Foo.bar() with bar in Companion */+ ASSERT_GTE(require_resolved(r, "main", "create"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 6. Object singleton ───────────────────────────────────── */++TEST(ktlsp_object_singleton) {+ CBMFileResult *r = extract_kotlin("object Constants {\n"+ " fun get(key: String): String = \"\"\n"+ "}\n"+ "fun read() { val v = Constants.get(\"name\") }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "read", "get"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 7. Extension functions ────────────────────────────────── */++TEST(ktlsp_extension_function) {+ CBMFileResult *r =+ extract_kotlin("fun String.shout(): String = this.uppercase() + \"!\"\n"+ "fun cheer(s: String): String = s.shout()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "cheer", "shout"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_extension_method_on_list) {+ CBMFileResult *r = extract_kotlin("fun List<Int>.sumPlus(n: Int): Int = this.sum() + n\n"+ "fun calc(xs: List<Int>): Int = xs.sumPlus(10)\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "calc", "sumPlus"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 8. Inheritance ────────────────────────────────────────── */++TEST(ktlsp_super_call) {+ CBMFileResult *r = extract_kotlin("open class Animal {\n"+ " open fun speak() = println(\"...\")\n"+ "}\n"+ "class Dog : Animal() {\n"+ " override fun speak() {\n"+ " super.speak()\n"+ " println(\"Woof\")\n"+ " }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* Inside Dog.speak, the super.speak should resolve. */+ ASSERT_GTE(require_resolved(r, "speak", "speak"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_interface_dispatch) {+ CBMFileResult *r = extract_kotlin("interface Closer { fun close() }\n"+ "class FileHandle : Closer { override fun close() {} }\n"+ "fun shutdown(c: Closer) { c.close() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "shutdown", "close"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 9. Smart casts ────────────────────────────────────────── */++TEST(ktlsp_smartcast_is) {+ CBMFileResult *r = extract_kotlin("class Animal { fun speak() {} }\n"+ "fun handle(x: Any) {\n"+ " if (x is Animal) {\n"+ " x.speak()\n"+ " }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "handle", "speak"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_smartcast_as) {+ CBMFileResult *r = extract_kotlin("class Animal { fun speak() {} }\n"+ "fun handle(x: Any) { (x as Animal).speak() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "handle", "speak"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_when_smartcast) {+ CBMFileResult *r = extract_kotlin("interface Shape { fun area(): Double }\n"+ "class Square(val side: Double) : Shape {\n"+ " override fun area() = side * side\n"+ "}\n"+ "fun describe(s: Any): Double = when (s) {\n"+ " is Square -> s.area()\n"+ " else -> 0.0\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "describe", "area"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 10. Safe calls / nullable ─────────────────────────────── */++TEST(ktlsp_safe_call) {+ CBMFileResult *r = extract_kotlin("class User { fun getName(): String = \"\" }\n"+ "fun displayName(u: User?): String? = u?.getName()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "displayName", "getName"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_not_null_assertion) {+ CBMFileResult *r = extract_kotlin("class User { fun getName(): String = \"\" }\n"+ "fun mustHave(u: User?): String = u!!.getName()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "mustHave", "getName"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 11. Lambda `it` parameter ─────────────────────────────── */++TEST(ktlsp_lambda_it_string) {+ CBMFileResult *r = extract_kotlin("fun upper(s: String): String = s.let { it.uppercase() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "upper", "uppercase"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_lambda_it_object) {+ CBMFileResult *r = extract_kotlin("class User { fun login() {} }\n"+ "fun signIn(u: User) { u.let { it.login() } }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "signIn", "login"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 12. Scope functions ───────────────────────────────────── */++TEST(ktlsp_scope_let) {+ CBMFileResult *r =+ extract_kotlin("fun upper(s: String?): String? = s?.let { it.uppercase() }\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "upper", "uppercase"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_scope_apply) {+ CBMFileResult *r = extract_kotlin("class Builder { fun setName(n: String) {} }\n"+ "fun build() = Builder().apply { setName(\"x\") }\n");+ ASSERT_NOT_NULL(r);+ /* `Builder()` is a constructor */+ ASSERT_GTE(require_resolved(r, "build", "Builder"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 13. Type aliases ──────────────────────────────────────── */++TEST(ktlsp_typealias) {+ CBMFileResult *r = extract_kotlin("typealias UserId = Int\n"+ "fun id(): UserId = 42\n"+ "fun show(id: UserId): String = id.toString()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "show", "toString"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 14. Enums ────────────────────────────────────────────── */++TEST(ktlsp_enum_class) {+ CBMFileResult *r = extract_kotlin("enum class Color { RED, GREEN, BLUE }\n"+ "fun pick(): Color = Color.RED\n");+ ASSERT_NOT_NULL(r);+ /* Color.RED — for our purposes, the enum entry access doesn't need a+ * resolved call edge. We just verify it doesn't crash. */+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++/* ── 15. Sealed classes ────────────────────────────────────── */++TEST(ktlsp_sealed_when) {+ CBMFileResult *r = extract_kotlin("sealed class Event\n"+ "class Login(val user: String) : Event()\n"+ "class Logout : Event()\n"+ "fun handle(e: Event): String = when (e) {\n"+ " is Login -> e.user\n"+ " is Logout -> \"bye\"\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++/* ── 16. Generics (basic) ──────────────────────────────────── */++TEST(ktlsp_generic_call) {+ CBMFileResult *r = extract_kotlin("class Box<T>(val value: T) {\n"+ " fun unwrap(): T = value\n"+ "}\n"+ "fun get(b: Box<String>): String = b.unwrap()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "get", "unwrap"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 17. Stdlib resolution ─────────────────────────────────── */++TEST(ktlsp_stdlib_println) {+ CBMFileResult *r = extract_kotlin("fun main() {\n"+ " println(\"a\")\n"+ " print(\"b\")\n"+ " error(\"c\")\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "println"), 0);+ ASSERT_GTE(require_resolved(r, "main", "print"), 0);+ ASSERT_GTE(require_resolved(r, "main", "error"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_stdlib_collection_builders) {+ CBMFileResult *r = extract_kotlin("fun build() {\n"+ " val a = arrayOf(1, 2, 3)\n"+ " val l = listOf(1, 2, 3)\n"+ " val ml = mutableListOf(1, 2, 3)\n"+ " val m = mapOf(\"a\" to 1)\n"+ " val mm = mutableMapOf<String, Int>()\n"+ " val s = setOf(1, 2, 3)\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "build", "arrayOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "listOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "mutableListOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "mapOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "mutableMapOf"), 0);+ ASSERT_GTE(require_resolved(r, "build", "setOf"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_stdlib_require_check) {+ CBMFileResult *r = extract_kotlin("fun validate(x: Int) {\n"+ " require(x > 0)\n"+ " check(x < 100)\n"+ " requireNotNull(x)\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "validate", "require"), 0);+ ASSERT_GTE(require_resolved(r, "validate", "check"), 0);+ ASSERT_GTE(require_resolved(r, "validate", "requireNotNull"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_stdlib_string_chain) {+ CBMFileResult *r = extract_kotlin("fun proc(s: String): String =\n"+ " s.trim().uppercase().replace(\"x\", \"y\")\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "proc", "trim"), 0);+ ASSERT_GTE(require_resolved(r, "proc", "uppercase"), 0);+ ASSERT_GTE(require_resolved(r, "proc", "replace"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_stdlib_collection_pipe) {+ CBMFileResult *r =+ extract_kotlin("fun pipe(xs: List<Int>): Int = xs.filter { it > 0 }.map { it * 2 }.sum()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "pipe", "filter"), 0);+ ASSERT_GTE(require_resolved(r, "pipe", "map"), 0);+ ASSERT_GTE(require_resolved(r, "pipe", "sum"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 18. Function reference handling ───────────────────────── */++TEST(ktlsp_constructor_param_property) {+ CBMFileResult *r = extract_kotlin("class Repo(val name: String) {\n"+ " fun describe(): String = name.uppercase()\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* `name.uppercase()` inside describe should resolve via String.uppercase() */+ ASSERT_GTE(require_resolved(r, "describe", "uppercase"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 19. Local function ────────────────────────────────────── */++TEST(ktlsp_local_function) {+ CBMFileResult *r = extract_kotlin("fun outer() {\n"+ " fun inner() { println(\"hi\") }\n"+ " inner()\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "inner", "println"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 20. Companion + factory pattern ───────────────────────── */++TEST(ktlsp_factory_pattern) {+ CBMFileResult *r = extract_kotlin("class Database private constructor() {\n"+ " fun query() {}\n"+ " companion object {\n"+ " fun create(): Database = Database()\n"+ " }\n"+ "}\n"+ "fun main() {\n"+ " val db = Database.create()\n"+ " db.query()\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "create"), 0);+ ASSERT_GTE(require_resolved(r, "main", "query"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 21. Quality parity vs tree-sitter baseline ────────────── */++TEST(ktlsp_resolves_more_than_textual) {+ /* Without LSP, a simple textual matcher would attribute foo() to any+ * function named foo. The LSP resolver disambiguates by package. */+ CBMFileResult *r = extract_kotlin("package myapp\n\n"+ "fun helper() = println(\"x\")\n"+ "fun main() { helper() }\n");+ ASSERT_NOT_NULL(r);+ /* helper() must resolve to myapp.helper, not some random helper. */+ int idx = require_resolved(r, "main", "helper");+ ASSERT_GTE(idx, 0);+ if (idx >= 0) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[idx];+ /* Confidence should be >= 0.9 for a top-level call. */+ ASSERT_TRUE(rc->confidence >= 0.85f);+ }+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_empty_file) {+ CBMFileResult *r = extract_kotlin("");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->resolved_calls.count, 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_only_package) {+ CBMFileResult *r = extract_kotlin("package myapp\n");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->resolved_calls.count, 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_only_imports) {+ CBMFileResult *r = extract_kotlin("package myapp\n"+ "import java.io.File\n"+ "import kotlin.collections.List as KList\n"+ "import kotlin.text.*\n");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_kts_script) {+ CBMFileResult *r =+ extract_kotlin_path("println(\"hello from script\")\n", "build.gradle.kts");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++/* ── 22. No regressions for unresolvable code ──────────────── */++TEST(ktlsp_unknown_external_unresolved) {+ /* Calls to symbols we have no info about should not produce+ * spurious LSP overrides. They fall through to the registry. */+ CBMFileResult *r = extract_kotlin("fun work(x: SomeUnknownType): UnknownReturn {\n"+ " return x.doMagic()\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* x.doMagic should NOT be in resolved_calls — it's unresolvable. */+ ASSERT_EQ(find_resolved(r, "work", "doMagic"), -1);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_no_duplicate_emission) {+ /* Same call shouldn't emit twice. */+ CBMFileResult *r = extract_kotlin("fun main() { println(\"a\"); println(\"b\") }\n");+ ASSERT_NOT_NULL(r);+ int n = count_resolved(r, "main", "println");+ /* We expect 2 entries (one per call), not duplicated more than that. */+ ASSERT_TRUE(n >= 2 && n <= 4);+ cbm_free_result(r);+ PASS();+}++/* ── 23. Confidence sanity ─────────────────────────────────── */++TEST(ktlsp_constructor_high_confidence) {+ CBMFileResult *r = extract_kotlin("class Foo\n"+ "fun make(): Foo = Foo()\n");+ ASSERT_NOT_NULL(r);+ int idx = require_resolved(r, "make", "Foo");+ ASSERT_GTE(idx, 0);+ if (idx >= 0) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[idx];+ ASSERT_TRUE(rc->confidence >= 0.90f);+ ASSERT_TRUE(rc->strategy != NULL);+ ASSERT_TRUE(strstr(rc->strategy, "lsp_kt_") != NULL);+ }+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_method_high_confidence) {+ CBMFileResult *r = extract_kotlin("class Service { fun run() {} }\n"+ "fun start(s: Service) { s.run() }\n");+ ASSERT_NOT_NULL(r);+ int idx = require_resolved(r, "start", "run");+ ASSERT_GTE(idx, 0);+ if (idx >= 0) {+ const CBMResolvedCall *rc = &r->resolved_calls.items[idx];+ ASSERT_TRUE(rc->confidence >= 0.85f);+ }+ cbm_free_result(r);+ PASS();+}++/* ── 24. Mixed real-world patterns ─────────────────────────── */++TEST(ktlsp_real_world_repository_pattern) {+ CBMFileResult *r =+ extract_kotlin("package myapp.repo\n\n"+ "import kotlin.collections.List\n\n"+ "interface UserRepository {\n"+ " fun findById(id: Int): User?\n"+ " fun all(): List<User>\n"+ "}\n"+ "class User(val id: Int, val name: String)\n"+ "class InMemoryRepo : UserRepository {\n"+ " private val data = mutableListOf<User>()\n"+ " override fun findById(id: Int): User? = data.find { it.id == id }\n"+ " override fun all(): List<User> = data.toList()\n"+ "}\n"+ "fun main(repo: UserRepository) {\n"+ " val u = repo.findById(42)\n"+ " val xs = repo.all()\n"+ " println(xs.size)\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "findById"), 0);+ ASSERT_GTE(require_resolved(r, "main", "all"), 0);+ ASSERT_GTE(require_resolved(r, "main", "println"), 0);+ /* InMemoryRepo.findById uses .find { ... } on the list */+ ASSERT_GTE(require_resolved(r, "findById", "find"), 0);+ /* and .toList in `all` */+ ASSERT_GTE(require_resolved(r, "all", "toList"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_real_world_builder) {+ CBMFileResult *r = extract_kotlin("class StringBuilder {\n"+ " fun append(s: String): StringBuilder = this\n"+ " fun build(): String = \"\"\n"+ "}\n"+ "fun build(): String = StringBuilder()\n"+ " .append(\"a\")\n"+ " .append(\"b\")\n"+ " .build()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "build", "StringBuilder"), 0);+ /* append should resolve through the chained returns */+ int n_append = count_resolved(r, "build", "append");+ ASSERT_TRUE(n_append >= 1); /* tree-sitter only would get 0 */+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_real_world_dsl) {+ CBMFileResult *r = extract_kotlin("class Html {\n"+ " fun head(block: Head.() -> Unit) {}\n"+ " fun body(block: Body.() -> Unit) {}\n"+ "}\n"+ "class Head { fun title(s: String) {} }\n"+ "class Body { fun p(s: String) {} }\n"+ "fun page() {\n"+ " val h = Html()\n"+ " h.head { title(\"X\") }\n"+ " h.body { p(\"hi\") }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "page", "Html"), 0);+ ASSERT_GTE(require_resolved(r, "page", "head"), 0);+ ASSERT_GTE(require_resolved(r, "page", "body"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 25. Defensive — malformed input ───────────────────────── */++TEST(ktlsp_malformed_recovery) {+ /* Tree-sitter recovers — LSP must not crash. */+ CBMFileResult *r = extract_kotlin("fun broken( {\n}\n");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_unicode_identifier) {+ CBMFileResult *r = extract_kotlin("class Café {\n"+ " fun servir() = println(\"ok\")\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_long_chain) {+ /* Stress the chain depth */+ CBMFileResult *r =+ extract_kotlin("fun chain(s: String) =\n"+ " s.trim().uppercase().replace(\"a\",\"b\").substring(0).reversed()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "chain", "trim"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 26. Operator conventions ───────────────────────────────── */++TEST(ktlsp_operator_plus) {+ /* `a + b` desugars to `a.plus(b)` for any registered type. */+ CBMFileResult *r = extract_kotlin("class Money(val cents: Int) {\n"+ " operator fun plus(o: Money): Money = Money(cents + o.cents)\n"+ "}\n"+ "fun add(a: Money, b: Money): Money = a + b\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "add", "plus"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_operator_compareTo) {+ CBMFileResult *r = extract_kotlin("class Version(val n: Int) {\n"+ " operator fun compareTo(o: Version): Int = n - o.n\n"+ "}\n"+ "fun cmp(a: Version, b: Version): Boolean = a < b\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "cmp", "compareTo"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_operator_in_contains) {+ CBMFileResult *r = extract_kotlin("class Bag(val items: List<String>) {\n"+ " operator fun contains(s: String): Boolean = items.contains(s)\n"+ "}\n"+ "fun has(b: Bag): Boolean = \"x\" in b\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "has", "contains"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_operator_get) {+ CBMFileResult *r = extract_kotlin("class Cache {\n"+ " operator fun get(key: String): Int = 0\n"+ "}\n"+ "fun lookup(c: Cache): Int = c[\"k\"]\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "lookup", "get"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_operator_unary) {+ CBMFileResult *r = extract_kotlin("class Vec(val x: Int) {\n"+ " operator fun unaryMinus(): Vec = Vec(-x)\n"+ "}\n"+ "fun negate(v: Vec): Vec = -v\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "negate", "unaryMinus"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_operator_int_plus) {+ /* Builtin Int.plus dispatch via stdlib method_names. */+ CBMFileResult *r = extract_kotlin("fun add(a: Int, b: Int): Int = a + b\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "add", "plus"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 27. Iterator protocol ──────────────────────────────────── */++TEST(ktlsp_for_iterator_protocol) {+ /* `for (x in xs)` should emit iterator/hasNext/next */+ CBMFileResult *r = extract_kotlin("fun walk(xs: List<Int>) {\n"+ " for (x in xs) { println(x) }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "walk", "iterator"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_for_range_iterator) {+ CBMFileResult *r = extract_kotlin("fun count() {\n"+ " for (i in 1..10) { println(i) }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* The for loop should emit println at minimum; iterator protocol is+ * a bonus when range type is detected. */+ ASSERT_GTE(require_resolved(r, "count", "println"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 28. Destructuring ──────────────────────────────────────── */++TEST(ktlsp_destructuring_pair) {+ CBMFileResult *r = extract_kotlin("fun unpack(p: Pair<String, Int>): String {\n"+ " val (a, b) = p\n"+ " return a\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* Destructuring should emit component1 and component2 calls. */+ ASSERT_GTE(require_resolved(r, "unpack", "component1"), 0);+ ASSERT_GTE(require_resolved(r, "unpack", "component2"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_destructuring_data_class) {+ CBMFileResult *r = extract_kotlin("data class Point(val x: Int, val y: Int)\n"+ "fun split(p: Point): Int {\n"+ " val (xx, yy) = p\n"+ " return xx + yy\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* For data classes, componentN is auto-generated; we don't track that+ * explicitly, but we still want the call to attempt to emit. */+ cbm_free_result(r);+ PASS();+}++/* ── 29. Property delegation ───────────────────────────────── */++TEST(ktlsp_property_delegation_lazy) {+ CBMFileResult *r = extract_kotlin("class Service {\n"+ " val expensive: String by lazy { computeIt() }\n"+ " fun computeIt(): String = \"x\"\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* Should emit at least the lazy() top-level call. getValue support+ * comes from KT_LAZY_METHODS. */+ int n_lazy = count_resolved(r, "expensive", "lazy");+ int n_get = count_resolved(r, "expensive", "getValue");+ ASSERT_TRUE(n_lazy + n_get >= 1);+ cbm_free_result(r);+ PASS();+}++/* ── 30. String template / interpolation ───────────────────── */++TEST(ktlsp_string_interpolation) {+ /* String templates with $expr internally call toString. We don't+ * desugar this, but at minimum the inner expression should be+ * evaluated for any embedded calls. */+ CBMFileResult *r = extract_kotlin("class Item { fun label(): String = \"x\" }\n"+ "fun show(item: Item): String = \"Got: ${item.label()}\"\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "show", "label"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 31. Range / progression operations ────────────────────── */++TEST(ktlsp_range_rangeTo) {+ /* `1..10` desugars to `1.rangeTo(10)`. */+ CBMFileResult *r = extract_kotlin("fun mkRange(): IntRange = 1..10\n");+ ASSERT_NOT_NULL(r);+ /* Best-effort — if rangeTo is in stdlib method_names for Int, emit. */+ cbm_free_result(r);+ PASS();+}++/* ── 32. Inline function lambda body attribution ───────────── */++TEST(ktlsp_inline_lambda_body_to_caller) {+ /* For inline functions, the lambda body conceptually expands into the+ * caller. Our walker already attributes calls inside trailing lambdas+ * to the OUTER caller (we don't change enclosing_func_qn when entering+ * the lambda). This matches the LSP's effective output. */+ CBMFileResult *r =+ extract_kotlin("inline fun retry(block: () -> Unit) { block() }\n"+ "fun main() {\n"+ " retry {\n"+ " println(\"hi\")\n"+ " }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* main → retry edge */+ ASSERT_GTE(require_resolved(r, "main", "retry"), 0);+ /* Inline expansion: println should be attributed to main (the outer+ * caller), not to retry. */+ ASSERT_GTE(require_resolved(r, "main", "println"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_inline_run_block) {+ /* `run { ... }` is a stdlib inline function. Inside the block, calls+ * should be attributed to the enclosing function. */+ CBMFileResult *r =+ extract_kotlin("class Logger { fun log(msg: String) {} }\n"+ "fun setup(l: Logger) {\n"+ " run {\n"+ " l.log(\"started\")\n"+ " }\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "setup", "log"), 0);+ cbm_free_result(r);+ PASS();+}++/* ── 33. Reified generics ───────────────────────────────────── */++TEST(ktlsp_reified_class_literal) {+ /* `T::class` inside reified inline functions doesn't crash; we treat+ * it as a class-literal and don't emit a call edge for it. The+ * function and its callers should still resolve normally. */+ CBMFileResult *r =+ extract_kotlin("inline fun <reified T> typeName(): String = T::class.toString()\n"+ "fun main(): String = typeName<String>()\n");+ ASSERT_NOT_NULL(r);+ ASSERT_GTE(require_resolved(r, "main", "typeName"), 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_reified_doesnt_crash) {+ /* Reified inline functions with `<reified T>` declaration parse and+ * their bodies/calls resolve. The call site uses explicit type+ * arguments which the grammar accepts via the standard+ * `simple_user_type` syntax; we don't track T-substitution but we do+ * emit the function call edge. */+ CBMFileResult *r = extract_kotlin(+ "inline fun <reified T> classify(x: Any): Boolean = x is T\n"+ "fun pickFirst(): Boolean = classify<String>(\"hi\")\n"+ "fun pickSecond(): Boolean = classify<Int>(42)\n");+ ASSERT_NOT_NULL(r);+ /* The grammar may not produce a clean call_expression for explicit-+ * generic calls; accept either a direct hit OR no crash. The test+ * documents the limitation. */+ cbm_free_result(r);+ PASS();+}++/* ── 34. Callable references ────────────────────────────────── */++TEST(ktlsp_callable_ref_top_level) {+ /* `::topLevelFn` references a top-level function. */+ CBMFileResult *r = extract_kotlin("fun helper(x: Int): Int = x + 1\n"+ "fun main() {\n"+ " val ref = ::helper\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* Should emit a callable-ref edge. */+ int idx = find_resolved(r, "main", "helper");+ ASSERT_GTE(idx, 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_callable_ref_method) {+ /* `Foo::method` references a class method. */+ CBMFileResult *r = extract_kotlin("class Service { fun run() {} }\n"+ "fun main() {\n"+ " val ref = Service::run\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ int idx = find_resolved(r, "main", "run");+ ASSERT_GTE(idx, 0);+ cbm_free_result(r);+ PASS();+}++TEST(ktlsp_callable_ref_class_literal) {+ /* `Foo::class` produces a KClass — should not emit a method-call edge+ * but should not crash. */+ CBMFileResult *r =+ extract_kotlin("class Service\n"+ "fun main() {\n"+ " val k = Service::class\n"+ "}\n");+ ASSERT_NOT_NULL(r);+ /* Specifically NO call edge for `class` since it's a literal. */+ cbm_free_result(r);+ PASS();+}++/* ── suite registration ────────────────────────────────────── */++SUITE(kotlin_lsp) {+ RUN_TEST(ktlsp_package_set);+ RUN_TEST(ktlsp_explicit_import_function);+ RUN_TEST(ktlsp_explicit_import_type);+ RUN_TEST(ktlsp_import_alias);+ RUN_TEST(ktlsp_wildcard_import);+ RUN_TEST(ktlsp_top_level_call_default_imports);+ RUN_TEST(ktlsp_top_level_listof);+ RUN_TEST(ktlsp_top_level_setof_mapof);+ RUN_TEST(ktlsp_intra_file_top_level);+ RUN_TEST(ktlsp_class_constructor);+ RUN_TEST(ktlsp_data_class);+ RUN_TEST(ktlsp_secondary_constructor);+ RUN_TEST(ktlsp_method_on_known_type);+ RUN_TEST(ktlsp_method_chain);+ RUN_TEST(ktlsp_string_method_dispatch);+ RUN_TEST(ktlsp_list_method_dispatch);+ RUN_TEST(ktlsp_companion_object_call);+ RUN_TEST(ktlsp_object_singleton);+ RUN_TEST(ktlsp_extension_function);+ RUN_TEST(ktlsp_extension_method_on_list);+ RUN_TEST(ktlsp_super_call);+ RUN_TEST(ktlsp_interface_dispatch);+ RUN_TEST(ktlsp_smartcast_is);+ RUN_TEST(ktlsp_smartcast_as);+ RUN_TEST(ktlsp_when_smartcast);+ RUN_TEST(ktlsp_safe_call);+ RUN_TEST(ktlsp_not_null_assertion);+ RUN_TEST(ktlsp_lambda_it_string);+ RUN_TEST(ktlsp_lambda_it_object);+ RUN_TEST(ktlsp_scope_let);+ RUN_TEST(ktlsp_scope_apply);+ RUN_TEST(ktlsp_typealias);+ RUN_TEST(ktlsp_enum_class);+ RUN_TEST(ktlsp_sealed_when);+ RUN_TEST(ktlsp_generic_call);+ RUN_TEST(ktlsp_stdlib_println);+ RUN_TEST(ktlsp_stdlib_collection_builders);+ RUN_TEST(ktlsp_stdlib_require_check);+ RUN_TEST(ktlsp_stdlib_string_chain);+ RUN_TEST(ktlsp_stdlib_collection_pipe);+ RUN_TEST(ktlsp_constructor_param_property);+ RUN_TEST(ktlsp_local_function);+ RUN_TEST(ktlsp_factory_pattern);+ RUN_TEST(ktlsp_resolves_more_than_textual);+ RUN_TEST(ktlsp_empty_file);+ RUN_TEST(ktlsp_only_package);+ RUN_TEST(ktlsp_only_imports);+ RUN_TEST(ktlsp_kts_script);+ RUN_TEST(ktlsp_unknown_external_unresolved);+ RUN_TEST(ktlsp_no_duplicate_emission);+ RUN_TEST(ktlsp_constructor_high_confidence);+ RUN_TEST(ktlsp_method_high_confidence);+ RUN_TEST(ktlsp_real_world_repository_pattern);+ RUN_TEST(ktlsp_real_world_builder);+ RUN_TEST(ktlsp_real_world_dsl);+ RUN_TEST(ktlsp_malformed_recovery);+ RUN_TEST(ktlsp_unicode_identifier);+ RUN_TEST(ktlsp_long_chain);+ /* Operator conventions */+ RUN_TEST(ktlsp_operator_plus);+ RUN_TEST(ktlsp_operator_compareTo);+ RUN_TEST(ktlsp_operator_in_contains);+ RUN_TEST(ktlsp_operator_get);+ RUN_TEST(ktlsp_operator_unary);+ RUN_TEST(ktlsp_operator_int_plus);+ /* Iterator protocol */+ RUN_TEST(ktlsp_for_iterator_protocol);+ RUN_TEST(ktlsp_for_range_iterator);+ /* Destructuring */+ RUN_TEST(ktlsp_destructuring_pair);+ RUN_TEST(ktlsp_destructuring_data_class);+ /* Property delegation */+ RUN_TEST(ktlsp_property_delegation_lazy);+ /* String interpolation */+ RUN_TEST(ktlsp_string_interpolation);+ /* Range */+ RUN_TEST(ktlsp_range_rangeTo);+ /* Inline expansion */+ RUN_TEST(ktlsp_inline_lambda_body_to_caller);+ RUN_TEST(ktlsp_inline_run_block);+ /* Reified generics */+ RUN_TEST(ktlsp_reified_class_literal);+ RUN_TEST(ktlsp_reified_doesnt_crash);+ /* Callable references */+ RUN_TEST(ktlsp_callable_ref_top_level);+ RUN_TEST(ktlsp_callable_ref_method);+ RUN_TEST(ktlsp_callable_ref_class_literal);+}diff --git a/tests/test_main.c b/tests/test_main.cindex 0238fc829..fced5d636 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -54,6 +54,7 @@ extern void suite_py_lsp_scale(void);extern void suite_ts_lsp(void);extern void suite_java_lsp(void);extern void suite_java_lsp_coverage(void);+extern void suite_kotlin_lsp(void);extern void suite_store_arch(void);extern void suite_store_bulk(void);extern void suite_store_pragmas(void);@@ -139,6 +140,7 @@ int main(void) {RUN_SUITE(cs_lsp);RUN_SUITE(cs_lsp_bench);RUN_SUITE(py_lsp);+ RUN_SUITE(kotlin_lsp);RUN_SUITE(py_lsp_bench);RUN_SUITE(py_lsp_stress);RUN_SUITE(py_lsp_scale);