Skip to content

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.

feat(lsp): add the Ruby per-file resolver

Ben Fairlesse9f87efe6abf
diff --git a/Makefile.cbm b/Makefile.cbm
index bf51a5a8c..9e5564cc6 100644
--- a/Makefile.cbm
+++ b/Makefile.cbm
@@ -579,6 +579,7 @@ TEST_CS_LSP_SRCS = tests/test_cs_lsp.c
TEST_CS_LSP_BENCH_SRCS = tests/test_cs_lsp_bench.c
TEST_PERL_LSP_SRCS = tests/test_perl_lsp.c
+TEST_RUBY_LSP_SRCS = tests/test_ruby_lsp.c
TEST_SCOPE_SRCS = tests/test_scope.c
@@ -701,7 +702,7 @@ TEST_REPRO_SRCS = \
tests/repro/repro_lsp_java_cs.c \
tests/repro/repro_lsp_kt_php_rust.c
-ALL_TEST_SRCS =$(TEST_FOUNDATION_SRCS) $(TEST_EXTRACTION_SRCS) $(TEST_STORE_SRCS) $(TEST_CYPHER_SRCS) $(TEST_MCP_SRCS) $(TEST_DAEMON_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_PERL_LSP_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_RUST_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_HTTPD_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SEMANTIC_SRCS) $(TEST_AST_PROFILE_SRCS) $(TEST_SLAB_ALLOC_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_DAEMON_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_PERL_LSP_SRCS) $(TEST_RUBY_LSP_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_RUST_LSP_SRCS) $(TEST_TRACES_SRCS) $(TEST_CLI_SRCS) $(TEST_MEM_SRCS) $(TEST_UI_SRCS) $(TEST_HTTPD_SRCS) $(TEST_SECURITY_SRCS) $(TEST_YAML_SRCS) $(TEST_SEMANTIC_SRCS) $(TEST_AST_PROFILE_SRCS) $(TEST_SLAB_ALLOC_SRCS) $(TEST_SIMHASH_SRCS) $(TEST_STACK_OVERFLOW_SRCS) $(TEST_INTEGRATION_SRCS)
# ── Build directories ────────────────────────────────────────────
diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.c
index d7468af5a..edf1b63d7 100644
--- a/internal/cbm/cbm.c
+++ b/internal/cbm/cbm.c
@@ -8,6 +8,7 @@
#include "lsp/php_lsp.h"
#include "lsp/perl_lsp.h"
#include "lsp/py_lsp.h"
+#include "lsp/ruby_lsp.h"
#include "lsp/ts_lsp.h"
#include "lsp/cs_lsp.h"
#include "lsp/java_lsp.h"
@@ -1320,6 +1321,9 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua
if (language == CBM_LANG_PERL) {
cbm_run_perl_lsp(a, result, source, source_len, root);
}
+ if (language == CBM_LANG_RUBY) {
+ cbm_run_ruby_lsp(a, result, source, source_len, root);
+ }
if (language == CBM_LANG_PYTHON) {
cbm_run_py_lsp(a, result, source, source_len, root);
}
diff --git a/internal/cbm/lsp/generated/ruby_stdlib_data.c b/internal/cbm/lsp/generated/ruby_stdlib_data.c
new file mode 100644
index 000000000..83e853e65
--- /dev/null
+++ b/internal/cbm/lsp/generated/ruby_stdlib_data.c
@@ -0,0 +1,461 @@
+/*
+ * ruby_stdlib_data.c — hand-written Ruby core + curated Rails type data.
+ *
+ * Strategy mirrors perl_stdlib_data.c / php_stdlib_data.c:
+ * 1. Ruby core classes (String, Array, Hash, Integer, ...) registered as
+ * types with receiver-keyed instance methods whose return types enable
+ * call-chain typing ("a,b".split(",").first). Method QNs are bare
+ * ("String.upcase") — no project prefix — so they can never collide
+ * with an indexed def; they exist for TYPING, not for edge emission
+ * (the resolver only emits edges to project-defined methods).
+ * 2. Kernel built-ins (puts, require, raise, ...) as global functions so
+ * bare calls to them type-check without producing spurious edges.
+ * 3. A curated Rails surface: ActiveRecord::Base class-side query methods
+ * and instance persistence methods, ActionController::Base helpers,
+ * and ActiveSupport-style predicates on Object. Registered under
+ * dotted QNs ("ActiveRecord.Base") to match ruby path dotting
+ * (Foo::Bar -> Foo.Bar). The resolver special-cases ActiveRecord
+ * query methods to return the *receiving model's* type (User.find ->
+ * User), which these generic entries cannot express.
+ *
+ * Return types are left UNKNOWN where the real type is polymorphic; the
+ * seed only needs to be right where chaining matters.
+ */
+
+#include "../type_rep.h"
+#include "../type_registry.h"
+#include "../../arena.h"
+#include "../ruby_lsp.h"
+#include <string.h>
+
+#define MIXED cbm_type_unknown()
+
+/* Register a type by bare dotted QN (e.g. "String", "ActiveRecord.Base"). */
+#define REG_TYPE(qn_) \
+ do { \
+ CBMRegisteredType rt; \
+ memset(&rt, 0, sizeof(rt)); \
+ rt.qualified_name = (qn_); \
+ rt.short_name = (qn_); \
+ cbm_registry_add_type(reg, rt); \
+ } while (0)
+
+/* Register an instance method on receiver type `recv_` returning `ret_`. */
+#define REG_METHOD(recv_, name_, ret_) \
+ do { \
+ memset(&rf, 0, sizeof(rf)); \
+ rf.min_params = -1; \
+ rf.qualified_name = cbm_arena_sprintf(arena, "%s.%s", (recv_), (name_)); \
+ rf.short_name = (name_); \
+ rf.receiver_type = (recv_); \
+ { \
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(*rets)); \
+ rets[0] = (ret_); \
+ rets[1] = NULL; \
+ rf.signature = cbm_type_func(arena, NULL, NULL, rets); \
+ } \
+ cbm_registry_add_func(reg, rf); \
+ } while (0)
+
+/* Register a singleton (class-side) method: receiver key "<qn>.self"
+ * matches ruby_lookup_singleton_method's keying convention. */
+#define REG_SMETHOD(recv_, name_, ret_) \
+ do { \
+ memset(&rf, 0, sizeof(rf)); \
+ rf.min_params = -1; \
+ rf.qualified_name = cbm_arena_sprintf(arena, "%s.%s", (recv_), (name_)); \
+ rf.short_name = (name_); \
+ rf.receiver_type = cbm_arena_sprintf(arena, "%s.self", (recv_)); \
+ { \
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(*rets)); \
+ rets[0] = (ret_); \
+ rets[1] = NULL; \
+ rf.signature = cbm_type_func(arena, NULL, NULL, rets); \
+ } \
+ cbm_registry_add_func(reg, rf); \
+ } while (0)
+
+/* Register a global (Kernel) built-in function returning `ret_`. */
+#define REG_BUILTIN(name_, ret_) \
+ do { \
+ memset(&rf, 0, sizeof(rf)); \
+ rf.min_params = -1; \
+ rf.qualified_name = (name_); \
+ rf.short_name = (name_); \
+ { \
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(arena, 2 * sizeof(*rets)); \
+ rets[0] = (ret_); \
+ rets[1] = NULL; \
+ rf.signature = cbm_type_func(arena, NULL, NULL, rets); \
+ } \
+ cbm_registry_add_func(reg, rf); \
+ } while (0)
+
+void cbm_ruby_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena) {
+ CBMRegisteredFunc rf;
+
+ const CBMType *T_STRING = cbm_type_named(arena, "String");
+ const CBMType *T_ARRAY = cbm_type_named(arena, "Array");
+ const CBMType *T_HASH = cbm_type_named(arena, "Hash");
+ const CBMType *T_INT = cbm_type_named(arena, "Integer");
+ const CBMType *T_FLOAT = cbm_type_named(arena, "Float");
+ const CBMType *T_SYM = cbm_type_named(arena, "Symbol");
+ const CBMType *T_BOOL = cbm_type_builtin(arena, "bool");
+
+ /* ── Core class constants (resolvable as superclasses / receivers) ── */
+ static const char *core_types[] = {"Object",
+ "BasicObject",
+ "String",
+ "Array",
+ "Hash",
+ "Integer",
+ "Float",
+ "Numeric",
+ "Symbol",
+ "Range",
+ "Regexp",
+ "Time",
+ "Date",
+ "DateTime",
+ "File",
+ "IO",
+ "Dir",
+ "Struct",
+ "OpenStruct",
+ "StringIO",
+ "Set",
+ "Proc",
+ "Method",
+ "Thread",
+ "Mutex",
+ "Queue",
+ "Rational",
+ "Complex",
+ "NilClass",
+ "TrueClass",
+ "FalseClass",
+ "Exception",
+ "StandardError",
+ "RuntimeError",
+ "ArgumentError",
+ "TypeError",
+ "NameError",
+ "NoMethodError",
+ "IOError",
+ "KeyError",
+ "IndexError",
+ "RangeError",
+ "NotImplementedError",
+ "StopIteration",
+ "Comparable",
+ "Enumerable",
+ "Kernel",
+ "Math",
+ "JSON",
+ "ERB",
+ "Logger",
+ "Enumerator",
+ NULL};
+ for (int i = 0; core_types[i]; i++)
+ REG_TYPE(core_types[i]);
+
+ /* ── String ── */
+ REG_METHOD("String", "upcase", T_STRING);
+ REG_METHOD("String", "downcase", T_STRING);
+ REG_METHOD("String", "capitalize", T_STRING);
+ REG_METHOD("String", "strip", T_STRING);
+ REG_METHOD("String", "chomp", T_STRING);
+ REG_METHOD("String", "gsub", T_STRING);
+ REG_METHOD("String", "sub", T_STRING);
+ REG_METHOD("String", "split", T_ARRAY);
+ REG_METHOD("String", "chars", T_ARRAY);
+ REG_METHOD("String", "lines", T_ARRAY);
+ REG_METHOD("String", "bytes", T_ARRAY);
+ REG_METHOD("String", "to_s", T_STRING);
+ REG_METHOD("String", "to_str", T_STRING);
+ REG_METHOD("String", "to_i", T_INT);
+ REG_METHOD("String", "to_f", T_FLOAT);
+ REG_METHOD("String", "to_sym", T_SYM);
+ REG_METHOD("String", "length", T_INT);
+ REG_METHOD("String", "size", T_INT);
+ REG_METHOD("String", "reverse", T_STRING);
+ REG_METHOD("String", "include?", T_BOOL);
+ REG_METHOD("String", "start_with?", T_BOOL);
+ REG_METHOD("String", "end_with?", T_BOOL);
+ REG_METHOD("String", "empty?", T_BOOL);
+ REG_METHOD("String", "match?", T_BOOL);
+ REG_METHOD("String", "freeze", T_STRING);
+ REG_METHOD("String", "dup", T_STRING);
+
+ /* ── Array ── */
+ REG_METHOD("Array", "map", T_ARRAY);
+ REG_METHOD("Array", "flat_map", T_ARRAY);
+ REG_METHOD("Array", "select", T_ARRAY);
+ REG_METHOD("Array", "filter", T_ARRAY);
+ REG_METHOD("Array", "reject", T_ARRAY);
+ REG_METHOD("Array", "sort", T_ARRAY);
+ REG_METHOD("Array", "sort_by", T_ARRAY);
+ REG_METHOD("Array", "uniq", T_ARRAY);
+ REG_METHOD("Array", "compact", T_ARRAY);
+ REG_METHOD("Array", "flatten", T_ARRAY);
+ REG_METHOD("Array", "reverse", T_ARRAY);
+ REG_METHOD("Array", "concat", T_ARRAY);
+ REG_METHOD("Array", "push", T_ARRAY);
+ REG_METHOD("Array", "join", T_STRING);
+ REG_METHOD("Array", "first", MIXED);
+ REG_METHOD("Array", "last", MIXED);
+ REG_METHOD("Array", "sample", MIXED);
+ REG_METHOD("Array", "length", T_INT);
+ REG_METHOD("Array", "size", T_INT);
+ REG_METHOD("Array", "count", T_INT);
+ REG_METHOD("Array", "sum", MIXED);
+ REG_METHOD("Array", "min", MIXED);
+ REG_METHOD("Array", "max", MIXED);
+ REG_METHOD("Array", "include?", T_BOOL);
+ REG_METHOD("Array", "empty?", T_BOOL);
+ REG_METHOD("Array", "any?", T_BOOL);
+ REG_METHOD("Array", "all?", T_BOOL);
+ REG_METHOD("Array", "none?", T_BOOL);
+ REG_METHOD("Array", "each", T_ARRAY);
+ REG_METHOD("Array", "each_with_index", T_ARRAY);
+ REG_METHOD("Array", "to_a", T_ARRAY);
+ REG_METHOD("Array", "group_by", T_HASH);
+ REG_METHOD("Array", "each_slice", MIXED);
+ REG_METHOD("Array", "zip", T_ARRAY);
+
+ /* ── Hash ── */
+ REG_METHOD("Hash", "keys", T_ARRAY);
+ REG_METHOD("Hash", "values", T_ARRAY);
+ REG_METHOD("Hash", "merge", T_HASH);
+ REG_METHOD("Hash", "merge!", T_HASH);
+ REG_METHOD("Hash", "fetch", MIXED);
+ REG_METHOD("Hash", "dig", MIXED);
+ REG_METHOD("Hash", "key?", T_BOOL);
+ REG_METHOD("Hash", "has_key?", T_BOOL);
+ REG_METHOD("Hash", "include?", T_BOOL);
+ REG_METHOD("Hash", "empty?", T_BOOL);
+ REG_METHOD("Hash", "size", T_INT);
+ REG_METHOD("Hash", "length", T_INT);
+ REG_METHOD("Hash", "count", T_INT);
+ REG_METHOD("Hash", "each", T_HASH);
+ REG_METHOD("Hash", "map", T_ARRAY);
+ REG_METHOD("Hash", "select", T_HASH);
+ REG_METHOD("Hash", "reject", T_HASH);
+ REG_METHOD("Hash", "to_a", T_ARRAY);
+ REG_METHOD("Hash", "to_h", T_HASH);
+ REG_METHOD("Hash", "transform_values", T_HASH);
+ REG_METHOD("Hash", "transform_keys", T_HASH);
+ REG_METHOD("Hash", "symbolize_keys", T_HASH); /* ActiveSupport */
+ REG_METHOD("Hash", "stringify_keys", T_HASH); /* ActiveSupport */
+ REG_METHOD("Hash", "deep_symbolize_keys", T_HASH);
+ REG_METHOD("Hash", "with_indifferent_access", T_HASH);
+
+ /* ── Integer / Float ── */
+ REG_METHOD("Integer", "to_s", T_STRING);
+ REG_METHOD("Integer", "to_i", T_INT);
+ REG_METHOD("Integer", "to_f", T_FLOAT);
+ REG_METHOD("Integer", "times", MIXED);
+ REG_METHOD("Integer", "upto", MIXED);
+ REG_METHOD("Integer", "abs", T_INT);
+ REG_METHOD("Integer", "zero?", T_BOOL);
+ REG_METHOD("Integer", "positive?", T_BOOL);
+ REG_METHOD("Integer", "negative?", T_BOOL);
+ REG_METHOD("Integer", "even?", T_BOOL);
+ REG_METHOD("Integer", "odd?", T_BOOL);
+ REG_METHOD("Float", "to_s", T_STRING);
+ REG_METHOD("Float", "to_i", T_INT);
+ REG_METHOD("Float", "round", T_INT);
+ REG_METHOD("Float", "ceil", T_INT);
+ REG_METHOD("Float", "floor", T_INT);
+ REG_METHOD("Float", "abs", T_FLOAT);
+
+ /* ── Symbol / misc ── */
+ REG_METHOD("Symbol", "to_s", T_STRING);
+ REG_METHOD("Symbol", "to_sym", T_SYM);
+ REG_METHOD("Symbol", "to_proc", cbm_type_named(arena, "Proc"));
+ REG_METHOD("Range", "to_a", T_ARRAY);
+ REG_METHOD("Range", "each", MIXED);
+ REG_METHOD("Range", "map", T_ARRAY);
+ REG_METHOD("Range", "include?", T_BOOL);
+ REG_METHOD("Time", "to_s", T_STRING);
+ REG_METHOD("Time", "to_i", T_INT);
+ REG_METHOD("Time", "strftime", T_STRING);
+ REG_METHOD("Time", "year", T_INT);
+ REG_METHOD("Time", "month", T_INT);
+ REG_METHOD("Time", "day", T_INT);
+ REG_SMETHOD("Time", "now", cbm_type_named(arena, "Time"));
+ REG_SMETHOD("Time", "at", cbm_type_named(arena, "Time"));
+ REG_SMETHOD("Time", "parse", cbm_type_named(arena, "Time"));
+ REG_SMETHOD("Time", "current", cbm_type_named(arena, "Time")); /* ActiveSupport */
+ REG_SMETHOD("Time", "zone", MIXED);
+ REG_SMETHOD("File", "read", T_STRING);
+ REG_SMETHOD("File", "readlines", T_ARRAY);
+ REG_SMETHOD("File", "open", cbm_type_named(arena, "File"));
+ REG_SMETHOD("File", "exist?", T_BOOL);
+ REG_SMETHOD("File", "basename", T_STRING);
+ REG_SMETHOD("File", "dirname", T_STRING);
+ REG_SMETHOD("File", "join", T_STRING);
+ REG_SMETHOD("File", "expand_path", T_STRING);
+ REG_SMETHOD("JSON", "parse", MIXED);
+ REG_SMETHOD("JSON", "generate", T_STRING);
+ REG_SMETHOD("JSON", "pretty_generate", T_STRING);
+ REG_SMETHOD("Math", "sqrt", T_FLOAT);
+ REG_SMETHOD("Math", "pow", T_FLOAT);
+ REG_SMETHOD("Math", "sin", T_FLOAT);
+ REG_SMETHOD("Math", "cos", T_FLOAT);
+ REG_SMETHOD("Math", "log", T_FLOAT);
+
+ /* ── Object (universal receivers; ActiveSupport predicates) ── */
+ REG_METHOD("Object", "to_s", T_STRING);
+ REG_METHOD("Object", "inspect", T_STRING);
+ REG_METHOD("Object", "freeze", MIXED);
+ REG_METHOD("Object", "frozen?", T_BOOL);
+ REG_METHOD("Object", "dup", MIXED);
+ REG_METHOD("Object", "clone", MIXED);
+ REG_METHOD("Object", "tap", MIXED);
+ REG_METHOD("Object", "then", MIXED);
+ REG_METHOD("Object", "nil?", T_BOOL);
+ REG_METHOD("Object", "is_a?", T_BOOL);
+ REG_METHOD("Object", "kind_of?", T_BOOL);
+ REG_METHOD("Object", "instance_of?", T_BOOL);
+ REG_METHOD("Object", "respond_to?", T_BOOL);
+ REG_METHOD("Object", "blank?", T_BOOL); /* ActiveSupport */
+ REG_METHOD("Object", "present?", T_BOOL); /* ActiveSupport */
+ REG_METHOD("Object", "presence", MIXED); /* ActiveSupport */
+ REG_METHOD("Object", "to_json", T_STRING); /* ActiveSupport / json */
+
+ /* ── Kernel built-ins (global functions) ── */
+ REG_BUILTIN("puts", MIXED);
+ REG_BUILTIN("print", MIXED);
+ REG_BUILTIN("p", MIXED);
+ REG_BUILTIN("pp", MIXED);
+ REG_BUILTIN("require", T_BOOL);
+ REG_BUILTIN("require_relative", T_BOOL);
+ REG_BUILTIN("raise", MIXED);
+ REG_BUILTIN("fail", MIXED);
+ REG_BUILTIN("loop", MIXED);
+ REG_BUILTIN("sleep", T_INT);
+ REG_BUILTIN("rand", MIXED);
+ REG_BUILTIN("format", T_STRING);
+ REG_BUILTIN("sprintf", T_STRING);
+ REG_BUILTIN("gets", T_STRING);
+ REG_BUILTIN("exit", MIXED);
+ REG_BUILTIN("abort", MIXED);
+ REG_BUILTIN("lambda", cbm_type_named(arena, "Proc"));
+ REG_BUILTIN("proc", cbm_type_named(arena, "Proc"));
+ REG_BUILTIN("binding", MIXED);
+ REG_BUILTIN("catch", MIXED);
+ REG_BUILTIN("throw", MIXED);
+ REG_BUILTIN("attr_accessor", MIXED);
+ REG_BUILTIN("attr_reader", MIXED);
+ REG_BUILTIN("attr_writer", MIXED);
+
+ /* ── Rails: ActiveRecord::Base ──────────────────────────────────
+ * Class-side query interface. Return types here are generic; the
+ * resolver's AR special case substitutes the receiving model's type
+ * (User.find -> User) when the receiver's ancestry reaches
+ * ActiveRecord.Base / ApplicationRecord. */
+ REG_TYPE("ActiveRecord.Base");
+ REG_TYPE("ApplicationRecord");
+ static const char *ar_class_methods[] = {"find",
+ "find_by",
+ "find_by!",
+ "find_or_create_by",
+ "find_or_initialize_by",
+ "where",
+ "all",
+ "first",
+ "last",
+ "take",
+ "create",
+ "create!",
+ "new",
+ "count",
+ "order",
+ "limit",
+ "offset",
+ "joins",
+ "left_joins",
+ "includes",
+ "preload",
+ "eager_load",
+ "group",
+ "having",
+ "distinct",
+ "pluck",
+ "ids",
+ "exists?",
+ "none",
+ "unscoped",
+ "select",
+ "sum",
+ "maximum",
+ "minimum",
+ "average",
+ "destroy_all",
+ "delete_all",
+ "update_all",
+ "transaction",
+ "find_each",
+ NULL};
+ for (int i = 0; ar_class_methods[i]; i++)
+ REG_SMETHOD("ActiveRecord.Base", ar_class_methods[i], MIXED);
+ REG_METHOD("ActiveRecord.Base", "save", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "save!", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "update", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "update!", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "destroy", MIXED);
+ REG_METHOD("ActiveRecord.Base", "destroy!", MIXED);
+ REG_METHOD("ActiveRecord.Base", "delete", MIXED);
+ REG_METHOD("ActiveRecord.Base", "reload", MIXED);
+ REG_METHOD("ActiveRecord.Base", "valid?", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "invalid?", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "persisted?", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "new_record?", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "errors", MIXED);
+ REG_METHOD("ActiveRecord.Base", "attributes", T_HASH);
+ REG_METHOD("ActiveRecord.Base", "assign_attributes", MIXED);
+ REG_METHOD("ActiveRecord.Base", "update_attribute", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "touch", T_BOOL);
+ REG_METHOD("ActiveRecord.Base", "id", T_INT);
+
+ /* ── Rails: ActionController::Base / ::API ── */
+ REG_TYPE("ActionController.Base");
+ REG_TYPE("ActionController.API");
+ static const char *ac_receivers[] = {"ActionController.Base", "ActionController.API", NULL};
+ for (int i = 0; ac_receivers[i]; i++) {
+ const char *acr = ac_receivers[i];
+ REG_METHOD(acr, "render", MIXED);
+ REG_METHOD(acr, "redirect_to", MIXED);
+ REG_METHOD(acr, "head", MIXED);
+ REG_METHOD(acr, "params", MIXED);
+ REG_METHOD(acr, "session", MIXED);
+ REG_METHOD(acr, "cookies", MIXED);
+ REG_METHOD(acr, "request", MIXED);
+ REG_METHOD(acr, "response", MIXED);
+ REG_METHOD(acr, "respond_to", MIXED);
+ REG_METHOD(acr, "flash", MIXED);
+ }
+ REG_SMETHOD("ActionController.Base", "before_action", MIXED);
+ REG_SMETHOD("ActionController.Base", "after_action", MIXED);
+ REG_SMETHOD("ActionController.Base", "skip_before_action", MIXED);
+ REG_SMETHOD("ActionController.API", "before_action", MIXED);
+ REG_SMETHOD("ActionController.API", "after_action", MIXED);
+
+ /* ── Rails: jobs / mailers (constants only, for superclass chains) ── */
+ REG_TYPE("ActiveJob.Base");
+ REG_TYPE("ApplicationJob");
+ REG_TYPE("ActionMailer.Base");
+ REG_TYPE("ApplicationMailer");
+ REG_TYPE("ApplicationController");
+ REG_SMETHOD("ActiveJob.Base", "perform_later", MIXED);
+ REG_SMETHOD("ActiveJob.Base", "perform_now", MIXED);
+ REG_SMETHOD("ActiveJob.Base", "set", MIXED);
+ REG_METHOD("ActionMailer.Base", "mail", MIXED);
+ REG_SMETHOD("ActionMailer.Base", "with", MIXED);
+
+ /* ── Minitest/RSpec anchors (superclass chains in test files) ── */
+ REG_TYPE("Minitest.Test");
+ REG_TYPE("ActiveSupport.TestCase");
+ REG_TYPE("ActionDispatch.IntegrationTest");
+}
diff --git a/internal/cbm/lsp/ruby_lsp.c b/internal/cbm/lsp/ruby_lsp.c
new file mode 100644
index 000000000..2ca944df2
--- /dev/null
+++ b/internal/cbm/lsp/ruby_lsp.c
@@ -0,0 +1,1261 @@
+/*
+ * ruby_lsp.c — Ruby Light Semantic Pass.
+ *
+ * In-process type-aware call resolver for Ruby. Mirrors the perl_lsp.c /
+ * php_lsp.c shape:
+ * 1. Build a CBMTypeRegistry from file-local definitions + stdlib
+ * (Ruby core classes + curated Rails surface), with per-class method
+ * tables keyed by receiver QN. Singleton (class-side) methods are
+ * keyed "<class_qn>.self" — Ruby constants cannot be lowercase, so
+ * the suffix never collides with a real nested-constant path.
+ * 2. ruby_lsp_process_file does a multi-pass walk:
+ * PASS 1 — collect class/module declarations (with lexical nesting),
+ * superclasses, include/prepend/extend mixins, and method tables
+ * (instance vs singleton classified from the AST — `def m` vs
+ * `def self.m` / `class << self`).
+ * PASS 1.5 — infer instance-variable types from `@x = Const.new`
+ * assignments inside method bodies (conflicting types latch to
+ * "conflicted" and resolve to nothing).
+ * PASS 2 — walk method bodies, track local variable types through
+ * assignments, and resolve call expressions into CBMResolvedCall
+ * edges via Ruby method lookup (prepends → own → includes →
+ * superclass chain; extends feed the singleton side).
+ *
+ * Verified tree-sitter-ruby node/field names (vendored compiled grammar at
+ * internal/cbm/vendored/grammars/ruby/parser.c — ts_symbol_names and
+ * ts_field_names tables):
+ * - call : fields `receiver`, `method`, `arguments`, `block`. Both
+ * `foo(x)` and command calls (`foo x`) surface as "call" nodes.
+ * - class : fields `name` (constant | scope_resolution), `superclass`
+ * (a `superclass` wrapper node), `body` (body_statement).
+ * - module : fields `name`, `body`.
+ * - method : fields `name`, `parameters`, `body`.
+ * - singleton_method : fields `object` (self | constant), `name`, `body`.
+ * - singleton_class : `class << self` — fields `value`, body children.
+ * - assignment : fields `left`, `right`.
+ * - scope_resolution : fields `scope` (may be absent for ::Foo), `name`.
+ * - leaves: constant, identifier, self, instance_variable, super,
+ * string, array, hash, integer, float, simple_symbol, regex.
+ *
+ * QN scheme (matches the structural extractor): Ruby HAS class node types
+ * (class/module), so defs are named `module_qn.<ConstPath>.<method>` with
+ * parent_class = `module_qn.<ConstPath>`. Constructor calls: the textual
+ * extractor rewrites `Widget.new` to callee "Widget" (extract_calls.c), so
+ * constructor rows emit the CLASS QN — the edge lands on the Class node,
+ * exactly like Python's lsp_constructor.
+ *
+ * Zero-edge guarantee: if a receiver's type is unknown/unindexed, NO edge
+ * is emitted (false edges are worse than missing edges). Dynamic dispatch
+ * (`send`, `public_send`, `method_missing`, `define_method`) is
+ * intentionally ignored.
+ */
+
+#include "ruby_lsp.h"
+#include "../helpers.h"
+#include "../arena.h"
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* Recursion cap for ruby_eval_expr_type — mirrors perl/php (unknown past 8). */
+#define RUBY_EVAL_MAX_DEPTH 8
+
+/* Confidence levels. */
+#define RUBY_CONF_HIGH 0.95f /* constructor / static constant dispatch */
+#define RUBY_CONF_TYPED 0.90f /* inferred receiver type (locals, ivars, chains) */
+
+/* Maximum AST-walk recursion depth (see scope.h rationale — graceful
+ * degradation on pathologically nested sources, never a crash). */
+#define CBM_LSP_RUBY_MAX_WALK_DEPTH 512
+
+/* ── forward declarations ───────────────────────────────────────── */
+
+static void ruby_resolve_calls_in_node(RubyLSPContext *ctx, TSNode node);
+static void ruby_resolve_calls_in_node_inner(RubyLSPContext *ctx, TSNode node);
+static void ruby_pass1_scan(RubyLSPContext *ctx, TSNode node);
+static void ruby_pass1_scan_inner(RubyLSPContext *ctx, TSNode node);
+static void ruby_ivar_scan(RubyLSPContext *ctx, TSNode node);
+static void ruby_ivar_scan_inner(RubyLSPContext *ctx, TSNode node);
+static const CBMType *ruby_eval_call_type(RubyLSPContext *ctx, TSNode call, bool emit);
+
+/* ── helpers ────────────────────────────────────────────────────── */
+
+static char *ruby_node_text(RubyLSPContext *ctx, TSNode node) {
+ return cbm_node_text(ctx->arena, node, ctx->source);
+}
+
+/* Convert a constant expression node (constant | scope_resolution) into a
+ * dotted path ("Foo", "A.B.C"). Returns NULL for anything else. A leading
+ * "::Foo" (scope_resolution without a scope) yields "Foo" — the resolver's
+ * table probe covers the top-level meaning. */
+static const char *ruby_const_path(RubyLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return NULL;
+ const char *k = ts_node_type(node);
+ if (strcmp(k, "constant") == 0)
+ return ruby_node_text(ctx, node);
+ if (strcmp(k, "scope_resolution") != 0)
+ return NULL;
+ TSNode scope = ts_node_child_by_field_name(node, "scope", 5);
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ if (ts_node_is_null(name))
+ return NULL;
+ char *nm = ruby_node_text(ctx, name);
+ if (!nm || !nm[0])
+ return NULL;
+ if (ts_node_is_null(scope))
+ return nm; /* ::Foo */
+ const char *sp = ruby_const_path(ctx, scope);
+ if (!sp || !sp[0])
+ return nm;
+ return cbm_arena_sprintf(ctx->arena, "%s.%s", sp, nm);
+}
+
+/* Join two dotted path fragments; either side may be empty/NULL. */
+static const char *ruby_path_join(CBMArena *a, const char *left, const char *right) {
+ if (!left || !left[0])
+ return right;
+ if (!right || !right[0])
+ return left;
+ return cbm_arena_sprintf(a, "%s.%s", left, right);
+}
+
+/* True when a QN belongs to the indexed project (module_qn's first segment
+ * is its prefix). Stdlib seed QNs ("String.upcase", "ActiveRecord.Base")
+ * never carry the project prefix, so edges are only ever emitted at
+ * project-defined targets. */
+static bool ruby_is_project_qn(RubyLSPContext *ctx, const char *qn) {
+ if (!qn || !ctx->module_qn || !ctx->module_qn[0])
+ return false;
+ const char *dot = strchr(ctx->module_qn, '.');
+ size_t plen = dot ? (size_t)(dot - ctx->module_qn) : strlen(ctx->module_qn);
+ return strncmp(qn, ctx->module_qn, plen) == 0 && qn[plen] == '.';
+}
+
+/* ── table growth helpers ───────────────────────────────────────── */
+
+static RubyClassInfo *ruby_add_class(RubyLSPContext *ctx, const char *path, const char *qn,
+ bool is_module) {
+ if (!ctx || !path || !qn)
+ return NULL;
+ /* Reopened class/module: reuse the existing record. */
+ for (int i = 0; i < ctx->class_count; i++) {
+ if (strcmp(ctx->classes[i].path, path) == 0)
+ return &ctx->classes[i];
+ }
+ if (ctx->class_count >= ctx->class_cap) {
+ int newcap = ctx->class_cap ? ctx->class_cap * 2 : 8;
+ RubyClassInfo *nc =
+ (RubyClassInfo *)cbm_arena_alloc(ctx->arena, (size_t)newcap * sizeof(RubyClassInfo));
+ if (!nc)
+ return NULL;
+ for (int i = 0; i < ctx->class_count; i++)
+ nc[i] = ctx->classes[i];
+ ctx->classes = nc;
+ ctx->class_cap = newcap;
+ }
+ RubyClassInfo *ci = &ctx->classes[ctx->class_count++];
+ memset(ci, 0, sizeof(*ci));
+ ci->path = cbm_arena_strdup(ctx->arena, path);
+ ci->qn = cbm_arena_strdup(ctx->arena, qn);
+ ci->is_module = is_module;
+ return ci;
+}
+
+static void ruby_add_mixin(RubyLSPContext *ctx, const char *owner_qn, const char *module_ref,
+ RubyMixinKind kind) {
+ if (!ctx || !owner_qn || !module_ref)
+ return;
+ if (ctx->mixin_count >= ctx->mixin_cap) {
+ int newcap = ctx->mixin_cap ? ctx->mixin_cap * 2 : 8;
+ RubyMixinInfo *nm =
+ (RubyMixinInfo *)cbm_arena_alloc(ctx->arena, (size_t)newcap * sizeof(RubyMixinInfo));
+ if (!nm)
+ return;
+ for (int i = 0; i < ctx->mixin_count; i++)
+ nm[i] = ctx->mixins[i];
+ ctx->mixins = nm;
+ ctx->mixin_cap = newcap;
+ }
+ RubyMixinInfo *mi = &ctx->mixins[ctx->mixin_count++];
+ memset(mi, 0, sizeof(*mi));
+ mi->owner_qn = cbm_arena_strdup(ctx->arena, owner_qn);
+ mi->module_ref = cbm_arena_strdup(ctx->arena, module_ref);
+ mi->kind = kind;
+}
+
+static void ruby_add_ivar(RubyLSPContext *ctx, const char *class_qn, const char *ivar_name,
+ const char *type_qn) {
+ if (!ctx || !class_qn || !ivar_name || !type_qn)
+ return;
+ for (int i = 0; i < ctx->ivar_count; i++) {
+ RubyIvarInfo *iv = &ctx->ivars[i];
+ if (strcmp(iv->class_qn, class_qn) == 0 && strcmp(iv->ivar_name, ivar_name) == 0) {
+ if (strcmp(iv->type_qn, type_qn) != 0)
+ iv->conflicted = true; /* disagreeing assignments — no type */
+ return;
+ }
+ }
+ if (ctx->ivar_count >= ctx->ivar_cap) {
+ int newcap = ctx->ivar_cap ? ctx->ivar_cap * 2 : 8;
+ RubyIvarInfo *ni =
+ (RubyIvarInfo *)cbm_arena_alloc(ctx->arena, (size_t)newcap * sizeof(RubyIvarInfo));
+ if (!ni)
+ return;
+ for (int i = 0; i < ctx->ivar_count; i++)
+ ni[i] = ctx->ivars[i];
+ ctx->ivars = ni;
+ ctx->ivar_cap = newcap;
+ }
+ RubyIvarInfo *iv = &ctx->ivars[ctx->ivar_count++];
+ memset(iv, 0, sizeof(*iv));
+ iv->class_qn = cbm_arena_strdup(ctx->arena, class_qn);
+ iv->ivar_name = cbm_arena_strdup(ctx->arena, ivar_name);
+ iv->type_qn = cbm_arena_strdup(ctx->arena, type_qn);
+}
+
+static const char *ruby_ivar_type(RubyLSPContext *ctx, const char *class_qn,
+ const char *ivar_name) {
+ if (!ctx || !class_qn || !ivar_name)
+ return NULL;
+ for (int i = 0; i < ctx->ivar_count; i++) {
+ RubyIvarInfo *iv = &ctx->ivars[i];
+ if (!iv->conflicted && strcmp(iv->class_qn, class_qn) == 0 &&
+ strcmp(iv->ivar_name, ivar_name) == 0)
+ return iv->type_qn;
+ }
+ return NULL;
+}
+
+static RubyClassInfo *ruby_class_by_qn(RubyLSPContext *ctx, const char *qn) {
+ if (!qn)
+ return NULL;
+ for (int i = 0; i < ctx->class_count; i++) {
+ if (strcmp(ctx->classes[i].qn, qn) == 0)
+ return &ctx->classes[i];
+ }
+ return NULL;
+}
+
+/* Conventional Rails superclasses for stdlib-seeded types the class table
+ * does not carry (per-file extraction cannot see app/models/
+ * application_record.rb from another file; the convention is fixed). */
+static const char *ruby_stdlib_superclass(const char *qn) {
+ if (!qn)
+ return NULL;
+ if (strcmp(qn, "ApplicationRecord") == 0)
+ return "ActiveRecord.Base";
+ if (strcmp(qn, "ApplicationController") == 0)
+ return "ActionController.Base";
+ if (strcmp(qn, "ApplicationJob") == 0)
+ return "ActiveJob.Base";
+ if (strcmp(qn, "ApplicationMailer") == 0)
+ return "ActionMailer.Base";
+ return NULL;
+}
+
+/* Superclass QN of a class: table entry first, then the conventional
+ * stdlib chain above. */
+static const char *ruby_superclass_qn(RubyLSPContext *ctx, const char *class_qn) {
+ RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
+ if (ci)
+ return ci->superclass_qn;
+ return ruby_stdlib_superclass(class_qn);
+}
+
+/* ── constant resolution ────────────────────────────────────────── */
+
+const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path) {
+ if (!ctx || !path || !path[0])
+ return NULL;
+ /* Lexical nesting probe: for nesting "A.B" try "A.B.path", "A.path",
+ * then "path" (innermost first — Ruby's constant lookup order). */
+ const char *nest = ctx->nesting ? ctx->nesting : "";
+ char prefix[512];
+ size_t nlen = strlen(nest);
+ if (nlen < sizeof(prefix)) {
+ memcpy(prefix, nest, nlen + 1);
+ while (1) {
+ if (prefix[0]) {
+ const char *cand = cbm_arena_sprintf(ctx->arena, "%s.%s", prefix, path);
+ for (int i = 0; i < ctx->class_count; i++) {
+ if (strcmp(ctx->classes[i].path, cand) == 0)
+ return ctx->classes[i].qn;
+ }
+ char *last_dot = strrchr(prefix, '.');
+ if (last_dot)
+ *last_dot = '\0';
+ else
+ prefix[0] = '\0';
+ continue;
+ }
+ break;
+ }
+ }
+ for (int i = 0; i < ctx->class_count; i++) {
+ if (strcmp(ctx->classes[i].path, path) == 0)
+ return ctx->classes[i].qn;
+ }
+ /* Stdlib types are keyed by their dotted bare path. */
+ const CBMRegisteredType *t = cbm_registry_lookup_type(ctx->registry, path);
+ if (t)
+ return t->qualified_name;
+ return NULL;
+}
+
+/* ── method lookup (Ruby MRO approximation) ─────────────────────── */
+
+/* Depth cap shared by the instance/singleton lookup walks. */
+#define RUBY_LOOKUP_MAX_DEPTH CBM_LSP_MAX_LOOKUP_DEPTH
+
+/* Own instance method of one exact class (no ancestry walk). */
+static const CBMRegisteredFunc *ruby_own_instance_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name) {
+ return cbm_registry_lookup_method(ctx->registry, class_qn, method_name);
+}
+
+/* Own singleton method of one exact class ("<qn>.self" receiver key). */
+static const CBMRegisteredFunc *ruby_own_singleton_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name) {
+ const char *key = cbm_arena_sprintf(ctx->arena, "%s.self", class_qn);
+ return cbm_registry_lookup_method(ctx->registry, key, method_name);
+}
+
+static const CBMRegisteredFunc *ruby_lookup_instance_method_depth(RubyLSPContext *ctx,
+ const char *class_qn,
+ const char *method_name,
+ int depth);
+
+/* Search a mixin kind on `owner_qn` (most recent first — later mixins win),
+ * recursing into each module's own include chain. */
+static const CBMRegisteredFunc *ruby_lookup_in_mixins(RubyLSPContext *ctx, const char *owner_qn,
+ RubyMixinKind kind, const char *method_name,
+ int depth) {
+ for (int i = ctx->mixin_count - 1; i >= 0; i--) {
+ RubyMixinInfo *mi = &ctx->mixins[i];
+ if (mi->kind != kind || strcmp(mi->owner_qn, owner_qn) != 0 || !mi->module_qn)
+ continue;
+ const CBMRegisteredFunc *f =
+ ruby_lookup_instance_method_depth(ctx, mi->module_qn, method_name, depth + 1);
+ if (f)
+ return f;
+ }
+ return NULL;
+}
+
+static const CBMRegisteredFunc *ruby_lookup_instance_method_depth(RubyLSPContext *ctx,
+ const char *class_qn,
+ const char *method_name,
+ int depth) {
+ if (!ctx || !class_qn || !method_name || depth > RUBY_LOOKUP_MAX_DEPTH)
+ return NULL;
+ /* Prepended modules shadow the class's own methods. */
+ const CBMRegisteredFunc *f =
+ ruby_lookup_in_mixins(ctx, class_qn, RUBY_MIXIN_PREPEND, method_name, depth);
+ if (f)
+ return f;
+ f = ruby_own_instance_method(ctx, class_qn, method_name);
+ if (f)
+ return f;
+ f = ruby_lookup_in_mixins(ctx, class_qn, RUBY_MIXIN_INCLUDE, method_name, depth);
+ if (f)
+ return f;
+ const char *sup = ruby_superclass_qn(ctx, class_qn);
+ if (sup && strcmp(sup, class_qn) != 0)
+ return ruby_lookup_instance_method_depth(ctx, sup, method_name, depth + 1);
+ return NULL;
+}
+
+const CBMRegisteredFunc *ruby_lookup_instance_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name) {
+ const CBMRegisteredFunc *f = ruby_lookup_instance_method_depth(ctx, class_qn, method_name, 0);
+ if (f)
+ return f;
+ /* Universal receiver fallback (Object / ActiveSupport predicates) —
+ * typing only; Object methods are stdlib entries, never project defs. */
+ if (class_qn && strcmp(class_qn, "Object") != 0)
+ return cbm_registry_lookup_method(ctx->registry, "Object", method_name);
+ return NULL;
+}
+
+static const CBMRegisteredFunc *ruby_lookup_singleton_method_depth(RubyLSPContext *ctx,
+ const char *class_qn,
+ const char *method_name,
+ int depth) {
+ if (!ctx || !class_qn || !method_name || depth > RUBY_LOOKUP_MAX_DEPTH)
+ return NULL;
+ const CBMRegisteredFunc *f = ruby_own_singleton_method(ctx, class_qn, method_name);
+ if (f)
+ return f;
+ /* `extend Mod` adds Mod's instance methods class-side. */
+ f = ruby_lookup_in_mixins(ctx, class_qn, RUBY_MIXIN_EXTEND, method_name, depth);
+ if (f)
+ return f;
+ const char *sup = ruby_superclass_qn(ctx, class_qn);
+ if (sup && strcmp(sup, class_qn) != 0)
+ return ruby_lookup_singleton_method_depth(ctx, sup, method_name, depth + 1);
+ return NULL;
+}
+
+const CBMRegisteredFunc *ruby_lookup_singleton_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name) {
+ return ruby_lookup_singleton_method_depth(ctx, class_qn, method_name, 0);
+}
+
+/* ── ActiveRecord model detection (typing special case) ─────────── */
+
+/* True when class_qn's superclass chain reaches ActiveRecord::Base (or the
+ * conventional ApplicationRecord intermediary, which per-file extraction
+ * usually cannot see through). */
+static bool ruby_is_ar_model(RubyLSPContext *ctx, const char *class_qn, int depth) {
+ if (!class_qn || depth > RUBY_LOOKUP_MAX_DEPTH)
+ return false;
+ if (strcmp(class_qn, "ActiveRecord.Base") == 0 || strcmp(class_qn, "ApplicationRecord") == 0)
+ return true;
+ RubyClassInfo *ci = ruby_class_by_qn(ctx, class_qn);
+ if (ci && ci->superclass_ref &&
+ (strcmp(ci->superclass_ref, "ApplicationRecord") == 0 ||
+ strcmp(ci->superclass_ref, "ActiveRecord.Base") == 0))
+ return true;
+ const char *sup = ruby_superclass_qn(ctx, class_qn);
+ if (sup && strcmp(sup, class_qn) != 0)
+ return ruby_is_ar_model(ctx, sup, depth + 1);
+ return false;
+}
+
+/* ActiveRecord class-side query methods that return the model (or a
+ * relation we approximate as the model, so chains like
+ * `User.where(...).first` keep their type). */
+static bool ruby_ar_returns_model(const char *m) {
+ static const char *names[] = {"find",
+ "find_by",
+ "find_by!",
+ "find_or_create_by",
+ "find_or_initialize_by",
+ "where",
+ "all",
+ "first",
+ "last",
+ "take",
+ "create",
+ "create!",
+ "new",
+ "order",
+ "limit",
+ "offset",
+ "joins",
+ "left_joins",
+ "includes",
+ "preload",
+ "eager_load",
+ "group",
+ "having",
+ "distinct",
+ "none",
+ "unscoped",
+ "find_each",
+ NULL};
+ for (int i = 0; names[i]; i++) {
+ if (strcmp(m, names[i]) == 0)
+ return true;
+ }
+ return false;
+}
+
+/* ── emit ───────────────────────────────────────────────────────── */
+
+static void ruby_emit_resolved(RubyLSPContext *ctx, const char *callee_qn, const char *strategy,
+ float confidence, TSNode site) {
+ if (!ctx->resolved_calls || !callee_qn || !ctx->enclosing_func_qn)
+ return;
+ /* Only project-defined targets become edges (stdlib rows would never
+ * land on a node and merely add noise). */
+ if (!ruby_is_project_qn(ctx, callee_qn))
+ return;
+ CBMResolvedCall rc = {0};
+ rc.caller_qn = ctx->enclosing_func_qn;
+ rc.callee_qn = callee_qn;
+ rc.strategy = strategy;
+ rc.confidence = confidence;
+ rc.reason = NULL;
+ rc.kind = CBM_RESOLVED_INVOCATION;
+ if (!ts_node_is_null(site)) {
+ rc.site_start_byte = ts_node_start_byte(site);
+ rc.site_end_byte = ts_node_end_byte(site);
+ }
+ cbm_resolvedcall_push(ctx->resolved_calls, ctx->arena, rc);
+}
+
+/* ── expression typing ──────────────────────────────────────────── */
+
+/* Return type of a registered func's signature, or unknown. */
+static const CBMType *ruby_func_return_type(const CBMRegisteredFunc *f) {
+ if (f && f->signature && f->signature->kind == CBM_TYPE_FUNC &&
+ f->signature->data.func.return_types && f->signature->data.func.return_types[0]) {
+ return f->signature->data.func.return_types[0];
+ }
+ return cbm_type_unknown();
+}
+
+const CBMType *ruby_eval_expr_type(RubyLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return cbm_type_unknown();
+ if (ctx->eval_depth >= RUBY_EVAL_MAX_DEPTH)
+ return cbm_type_unknown();
+ ctx->eval_depth++;
+ const CBMType *result = cbm_type_unknown();
+ const char *k = ts_node_type(node);
+
+ if (strcmp(k, "identifier") == 0) {
+ char *txt = ruby_node_text(ctx, node);
+ if (txt) {
+ const CBMType *t = cbm_scope_lookup(ctx->current_scope, txt);
+ if (t)
+ result = t;
+ }
+ } else if (strcmp(k, "instance_variable") == 0) {
+ char *txt = ruby_node_text(ctx, node);
+ const char *tqn = ruby_ivar_type(ctx, ctx->enclosing_class_qn, txt);
+ if (tqn)
+ result = cbm_type_named(ctx->arena, tqn);
+ } else if (strcmp(k, "self") == 0) {
+ if (ctx->enclosing_class_qn && !ctx->in_singleton_method)
+ result = cbm_type_named(ctx->arena, ctx->enclosing_class_qn);
+ } else if (strcmp(k, "call") == 0) {
+ result = ruby_eval_call_type(ctx, node, false);
+ } else if (strcmp(k, "assignment") == 0) {
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(right))
+ result = ruby_eval_expr_type(ctx, right);
+ } else if (strcmp(k, "string") == 0 || strcmp(k, "string_content") == 0 ||
+ strcmp(k, "heredoc_body") == 0 || strcmp(k, "chained_string") == 0) {
+ result = cbm_type_named(ctx->arena, "String");
+ } else if (strcmp(k, "array") == 0 || strcmp(k, "string_array") == 0 ||
+ strcmp(k, "symbol_array") == 0) {
+ result = cbm_type_named(ctx->arena, "Array");
+ } else if (strcmp(k, "hash") == 0) {
+ result = cbm_type_named(ctx->arena, "Hash");
+ } else if (strcmp(k, "integer") == 0) {
+ result = cbm_type_named(ctx->arena, "Integer");
+ } else if (strcmp(k, "float") == 0) {
+ result = cbm_type_named(ctx->arena, "Float");
+ } else if (strcmp(k, "simple_symbol") == 0 || strcmp(k, "delimited_symbol") == 0) {
+ result = cbm_type_named(ctx->arena, "Symbol");
+ } else if (strcmp(k, "regex") == 0) {
+ result = cbm_type_named(ctx->arena, "Regexp");
+ } else if (strcmp(k, "parenthesized_statements") == 0 || strcmp(k, "begin") == 0) {
+ /* Type of the last meaningful child. */
+ uint32_t nc = ts_node_named_child_count(node);
+ for (uint32_t i = nc; i > 0; i--) {
+ TSNode c = ts_node_named_child(node, i - 1);
+ if (ts_node_is_null(c))
+ continue;
+ const char *ck = ts_node_type(c);
+ if (strcmp(ck, "comment") == 0)
+ continue;
+ result = ruby_eval_expr_type(ctx, c);
+ break;
+ }
+ }
+
+ ctx->eval_depth--;
+ return result;
+}
+
+/* ── call resolution core ───────────────────────────────────────── */
+
+/* Dynamic-dispatch method names the resolver must never guess through. */
+static bool ruby_is_dynamic_dispatch(const char *m) {
+ return strcmp(m, "send") == 0 || strcmp(m, "public_send") == 0 || strcmp(m, "__send__") == 0 ||
+ strcmp(m, "method_missing") == 0 || strcmp(m, "define_method") == 0 ||
+ strcmp(m, "instance_eval") == 0 || strcmp(m, "class_eval") == 0 ||
+ strcmp(m, "module_eval") == 0 || strcmp(m, "instance_variable_get") == 0 ||
+ strcmp(m, "instance_variable_set") == 0;
+}
+
+/* Class-body macro-ish names PASS 1 already interpreted (or that never
+ * denote resolvable user calls). */
+static bool ruby_is_body_macro(const char *m) {
+ return strcmp(m, "include") == 0 || strcmp(m, "extend") == 0 || strcmp(m, "prepend") == 0 ||
+ strcmp(m, "require") == 0 || strcmp(m, "require_relative") == 0 ||
+ strcmp(m, "attr_accessor") == 0 || strcmp(m, "attr_reader") == 0 ||
+ strcmp(m, "attr_writer") == 0 || strcmp(m, "private") == 0 || strcmp(m, "public") == 0 ||
+ strcmp(m, "protected") == 0 || strcmp(m, "module_function") == 0 ||
+ strcmp(m, "alias_method") == 0 || strcmp(m, "loop") == 0 || strcmp(m, "lambda") == 0 ||
+ strcmp(m, "proc") == 0;
+}
+
+/* Resolve a singleton-side dispatch on a resolved class QN. Emits (when
+ * `emit`) and returns the call's type. Also owns the ActiveRecord typing
+ * special case (User.find -> User). */
+static const CBMType *ruby_dispatch_singleton(RubyLSPContext *ctx, const char *class_qn,
+ const char *mname, bool emit, TSNode site) {
+ const CBMRegisteredFunc *f = ruby_lookup_singleton_method(ctx, class_qn, mname);
+ if (f) {
+ if (emit)
+ ruby_emit_resolved(ctx, f->qualified_name, "ruby_class_method", RUBY_CONF_HIGH, site);
+ const CBMType *rt = ruby_func_return_type(f);
+ if (!cbm_type_is_unknown(rt))
+ return rt;
+ /* Stdlib AR query entries return unknown; substitute the model. */
+ if (ruby_is_ar_model(ctx, class_qn, 0) && ruby_ar_returns_model(mname))
+ return cbm_type_named(ctx->arena, class_qn);
+ return rt;
+ }
+ if (ruby_is_ar_model(ctx, class_qn, 0) && ruby_ar_returns_model(mname))
+ return cbm_type_named(ctx->arena, class_qn);
+ return cbm_type_unknown();
+}
+
+/* Resolve an instance-side dispatch on a receiver type QN. */
+static const CBMType *ruby_dispatch_instance(RubyLSPContext *ctx, const char *class_qn,
+ const char *mname, const char *strategy, bool emit,
+ TSNode site) {
+ const CBMRegisteredFunc *f = ruby_lookup_instance_method(ctx, class_qn, mname);
+ if (!f)
+ return cbm_type_unknown();
+ if (emit)
+ ruby_emit_resolved(ctx, f->qualified_name, strategy, RUBY_CONF_TYPED, site);
+ return ruby_func_return_type(f);
+}
+
+/* Resolve one `call` node. When `emit` is set, resolved project targets are
+ * appended as CBMResolvedCall edges; the call's result type is returned
+ * either way (so chains and assignments can type through it). */
+static const CBMType *ruby_eval_call_type(RubyLSPContext *ctx, TSNode call, bool emit) {
+ TSNode meth = ts_node_child_by_field_name(call, "method", 6);
+ TSNode recv = ts_node_child_by_field_name(call, "receiver", 8);
+ if (ts_node_is_null(meth))
+ return cbm_type_unknown();
+
+ /* `super(...)` is dispatched by the walker (ruby_resolve_super); as an
+ * expression its type is not modeled. */
+ if (strcmp(ts_node_type(meth), "super") == 0)
+ return cbm_type_unknown();
+
+ char *mname = ruby_node_text(ctx, meth);
+ if (!mname || !mname[0])
+ return cbm_type_unknown();
+ if (ruby_is_dynamic_dispatch(mname))
+ return cbm_type_unknown(); /* zero-edge guarantee */
+
+ /* Constructor: Const.new / A::B.new — the textual extractor rewrites
+ * the callee to the constant, so the row targets the CLASS QN. */
+ if (strcmp(mname, "new") == 0 && !ts_node_is_null(recv)) {
+ const char *cpath = ruby_const_path(ctx, recv);
+ if (cpath) {
+ const char *cqn = ruby_resolve_constant(ctx, cpath);
+ if (cqn) {
+ if (emit)
+ ruby_emit_resolved(ctx, cqn, "ruby_constructor", RUBY_CONF_HIGH, call);
+ return cbm_type_named(ctx->arena, cqn);
+ }
+ return cbm_type_unknown();
+ }
+ /* Fall through: `expr.new` on a non-constant receiver. */
+ }
+
+ if (ts_node_is_null(recv)) {
+ /* Bare call: self-dispatch inside methods, then file-level funcs. */
+ if (ruby_is_body_macro(mname))
+ return cbm_type_unknown();
+ if (ctx->enclosing_class_qn) {
+ const CBMRegisteredFunc *f =
+ ctx->in_singleton_method
+ ? ruby_lookup_singleton_method(ctx, ctx->enclosing_class_qn, mname)
+ : ruby_lookup_instance_method_depth(ctx, ctx->enclosing_class_qn, mname, 0);
+ if (f) {
+ if (emit)
+ ruby_emit_resolved(ctx, f->qualified_name, "ruby_self_dispatch", RUBY_CONF_HIGH,
+ call);
+ return ruby_func_return_type(f);
+ }
+ }
+ const CBMRegisteredFunc *f =
+ cbm_registry_lookup_symbol(ctx->registry, ctx->module_qn, mname);
+ if (!f)
+ f = cbm_registry_lookup_func(ctx->registry, mname); /* Kernel builtins */
+ if (f) {
+ if (emit)
+ ruby_emit_resolved(ctx, f->qualified_name, "ruby_function_local", RUBY_CONF_HIGH,
+ call);
+ return ruby_func_return_type(f);
+ }
+ return cbm_type_unknown();
+ }
+
+ const char *rk = ts_node_type(recv);
+
+ /* self.m — explicit self dispatch. */
+ if (strcmp(rk, "self") == 0) {
+ if (!ctx->enclosing_class_qn)
+ return cbm_type_unknown();
+ const CBMRegisteredFunc *f =
+ ctx->in_singleton_method
+ ? ruby_lookup_singleton_method(ctx, ctx->enclosing_class_qn, mname)
+ : ruby_lookup_instance_method_depth(ctx, ctx->enclosing_class_qn, mname, 0);
+ if (f) {
+ if (emit)
+ ruby_emit_resolved(ctx, f->qualified_name, "ruby_self_dispatch", RUBY_CONF_HIGH,
+ call);
+ return ruby_func_return_type(f);
+ }
+ return cbm_type_unknown();
+ }
+
+ /* Const.m / A::B.m — singleton dispatch on the resolved class. */
+ if (strcmp(rk, "constant") == 0 || strcmp(rk, "scope_resolution") == 0) {
+ const char *cpath = ruby_const_path(ctx, recv);
+ const char *cqn = cpath ? ruby_resolve_constant(ctx, cpath) : NULL;
+ if (!cqn)
+ return cbm_type_unknown(); /* unknown constant — zero-edge */
+ return ruby_dispatch_singleton(ctx, cqn, mname, emit, call);
+ }
+
+ /* Typed receiver: locals, ivars, chained calls, literals. */
+ const CBMType *rt = ruby_eval_expr_type(ctx, recv);
+ if (!rt || rt->kind != CBM_TYPE_NAMED)
+ return cbm_type_unknown(); /* unknown receiver — zero-edge */
+ const char *strategy = "ruby_method_typed";
+ if (strcmp(rk, "instance_variable") == 0)
+ strategy = "ruby_ivar_method";
+ else if (strcmp(rk, "call") == 0)
+ strategy = "ruby_method_chained";
+ const CBMType *out =
+ ruby_dispatch_instance(ctx, rt->data.named.qualified_name, mname, strategy, emit, call);
+ if (!cbm_type_is_unknown(out))
+ return out;
+ /* AR relation approximation: chains on a model type keep the model. */
+ if (ruby_is_ar_model(ctx, rt->data.named.qualified_name, 0) && ruby_ar_returns_model(mname))
+ return rt;
+ return out;
+}
+
+/* `super` / `super(...)`: resolve the enclosing method's name starting at
+ * the enclosing class's ancestry (own def skipped — that IS the caller). */
+static void ruby_resolve_super(RubyLSPContext *ctx, TSNode site) {
+ if (!ctx->enclosing_class_qn || !ctx->enclosing_func_qn)
+ return;
+ const char *fq = ctx->enclosing_func_qn;
+ const char *mname = strrchr(fq, '.');
+ mname = mname ? mname + 1 : fq;
+ const CBMRegisteredFunc *f = NULL;
+ /* Search order mirrors Ruby: includes of the class, then superclass
+ * chain — the class's OWN def is the caller and must be skipped. */
+ f = ruby_lookup_in_mixins(ctx, ctx->enclosing_class_qn,
+ ctx->in_singleton_method ? RUBY_MIXIN_EXTEND : RUBY_MIXIN_INCLUDE,
+ mname, 0);
+ if (!f) {
+ const char *sup = ruby_superclass_qn(ctx, ctx->enclosing_class_qn);
+ if (sup) {
+ f = ctx->in_singleton_method ? ruby_lookup_singleton_method_depth(ctx, sup, mname, 0)
+ : ruby_lookup_instance_method_depth(ctx, sup, mname, 0);
+ }
+ }
+ if (f)
+ ruby_emit_resolved(ctx, f->qualified_name, "ruby_method_super", RUBY_CONF_HIGH, site);
+ /* No known parent or unresolved — zero-edge guarantee. */
+}
+
+/* ── assignment observer (scope binding) ────────────────────────── */
+
+static void ruby_process_assignment(RubyLSPContext *ctx, TSNode assign) {
+ TSNode left = ts_node_child_by_field_name(assign, "left", 4);
+ TSNode right = ts_node_child_by_field_name(assign, "right", 5);
+ if (ts_node_is_null(left) || ts_node_is_null(right))
+ return;
+ if (strcmp(ts_node_type(left), "identifier") != 0)
+ return; /* only simple local targets are tracked */
+ char *vname = ruby_node_text(ctx, left);
+ if (!vname || !vname[0])
+ return;
+ const CBMType *rt = ruby_eval_expr_type(ctx, right);
+ if (rt && rt->kind == CBM_TYPE_NAMED)
+ cbm_scope_bind(ctx->current_scope, vname, rt);
+}
+
+/* ── PASS 2: resolution walk ────────────────────────────────────── */
+
+/* Process one method/singleton_method definition node. */
+static void ruby_process_method(RubyLSPContext *ctx, TSNode node, bool singleton) {
+ CBMScope *saved_scope = ctx->current_scope;
+ const char *saved_func = ctx->enclosing_func_qn;
+ bool saved_singleton = ctx->in_singleton_method;
+
+ ctx->current_scope = cbm_scope_push(ctx->arena, ctx->current_scope);
+ ctx->in_singleton_method = singleton;
+
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ char *mname = ts_node_is_null(name) ? NULL : ruby_node_text(ctx, name);
+ if (mname && mname[0]) {
+ const char *owner = ctx->enclosing_class_qn ? ctx->enclosing_class_qn : ctx->module_qn;
+ if (owner)
+ ctx->enclosing_func_qn = cbm_arena_sprintf(ctx->arena, "%s.%s", owner, mname);
+ else
+ ctx->enclosing_func_qn = cbm_arena_strdup(ctx->arena, mname);
+ }
+
+ TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ if (!ts_node_is_null(body))
+ ruby_resolve_calls_in_node(ctx, body);
+
+ ctx->current_scope = saved_scope;
+ ctx->enclosing_func_qn = saved_func;
+ ctx->in_singleton_method = saved_singleton;
+}
+
+/* Process a class/module node during PASS 2: update nesting + enclosing
+ * class, then walk the body. */
+static void ruby_process_class_body(RubyLSPContext *ctx, TSNode node) {
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ const char *cpath = ruby_const_path(ctx, name);
+ if (!cpath)
+ return;
+
+ const char *saved_nesting = ctx->nesting;
+ const char *saved_class = ctx->enclosing_class_qn;
+ bool saved_singleton = ctx->in_singleton_method;
+
+ ctx->nesting = ruby_path_join(ctx->arena, saved_nesting, cpath);
+ const char *qn = ruby_resolve_constant(ctx, cpath);
+ ctx->enclosing_class_qn = qn;
+ ctx->in_singleton_method = false;
+
+ TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ if (!ts_node_is_null(body))
+ ruby_resolve_calls_in_node(ctx, body);
+
+ ctx->nesting = saved_nesting;
+ ctx->enclosing_class_qn = saved_class;
+ ctx->in_singleton_method = saved_singleton;
+}
+
+static void ruby_resolve_calls_in_node(RubyLSPContext *ctx, TSNode node) {
+ if (ctx->walk_depth >= CBM_LSP_RUBY_MAX_WALK_DEPTH)
+ return;
+ ctx->walk_depth++;
+ ruby_resolve_calls_in_node_inner(ctx, node);
+ ctx->walk_depth--;
+}
+
+static void ruby_resolve_calls_in_node_inner(RubyLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return;
+ const char *k = ts_node_type(node);
+
+ if (strcmp(k, "class") == 0 || strcmp(k, "module") == 0) {
+ ruby_process_class_body(ctx, node);
+ return;
+ }
+ if (strcmp(k, "singleton_class") == 0) {
+ /* `class << self` — methods inside are singleton methods. */
+ bool saved = ctx->in_singleton_method;
+ ctx->in_singleton_method = true;
+ uint32_t nc = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < nc; i++)
+ ruby_resolve_calls_in_node(ctx, ts_node_named_child(node, i));
+ ctx->in_singleton_method = saved;
+ return;
+ }
+ if (strcmp(k, "method") == 0) {
+ ruby_process_method(ctx, node, ctx->in_singleton_method);
+ return;
+ }
+ if (strcmp(k, "singleton_method") == 0) {
+ ruby_process_method(ctx, node, true);
+ return;
+ }
+
+ if (strcmp(k, "assignment") == 0)
+ ruby_process_assignment(ctx, node);
+
+ if (strcmp(k, "call") == 0) {
+ TSNode meth = ts_node_child_by_field_name(node, "method", 6);
+ if (!ts_node_is_null(meth) && strcmp(ts_node_type(meth), "super") == 0)
+ ruby_resolve_super(ctx, node);
+ else
+ ruby_eval_call_type(ctx, node, true);
+ /* Recurse into receiver/arguments/blocks for nested calls. */
+ } else if (strcmp(k, "super") == 0) {
+ /* Bare `super` (no argument list) appears as a standalone node. */
+ ruby_resolve_super(ctx, node);
+ return;
+ }
+
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode c = ts_node_child(node, i);
+ if (!ts_node_is_null(c))
+ ruby_resolve_calls_in_node(ctx, c);
+ }
+}
+
+/* ── PASS 1: class/mixin/method collection ──────────────────────── */
+
+/* Register one method into the registry with the proper receiver key. */
+static void ruby_register_method(RubyLSPContext *ctx, CBMTypeRegistry *reg, const char *owner_qn,
+ const char *mname, bool singleton) {
+ if (!mname || !mname[0])
+ return;
+ CBMRegisteredFunc rf;
+ memset(&rf, 0, sizeof(rf));
+ rf.min_params = -1;
+ const char *owner = owner_qn ? owner_qn : ctx->module_qn;
+ rf.qualified_name = owner ? cbm_arena_sprintf(ctx->arena, "%s.%s", owner, mname)
+ : cbm_arena_strdup(ctx->arena, mname);
+ rf.short_name = cbm_arena_strdup(ctx->arena, mname);
+ if (owner_qn) {
+ rf.receiver_type = singleton ? cbm_arena_sprintf(ctx->arena, "%s.self", owner_qn)
+ : cbm_arena_strdup(ctx->arena, owner_qn);
+ }
+ const CBMType **rets = (const CBMType **)cbm_arena_alloc(ctx->arena, 2 * sizeof(*rets));
+ if (rets) {
+ rets[0] = cbm_type_unknown();
+ rets[1] = NULL;
+ }
+ rf.signature = cbm_type_func(ctx->arena, NULL, NULL, rets);
+ cbm_registry_add_func(reg, rf);
+}
+
+/* PASS-1 refs are nesting-scoped: the finalize step resolves superclass and
+ * mixin references once the class table is complete, so PASS 1 records raw
+ * dotted refs plus the nesting string active at the declaration site
+ * (packed as "<nesting>|<ref>" when nesting is set). */
+static const char *ruby_pack_ref(RubyLSPContext *ctx, const char *ref) {
+ const char *nest = ctx->nesting ? ctx->nesting : "";
+ if (!nest[0])
+ return ref;
+ return cbm_arena_sprintf(ctx->arena, "%s|%s", nest, ref);
+}
+
+/* Resolve a packed "<nesting>|<ref>" (or bare "<ref>") against the class
+ * table + stdlib, honoring the recorded lexical nesting. */
+static const char *ruby_resolve_packed_ref(RubyLSPContext *ctx, const char *packed) {
+ if (!packed)
+ return NULL;
+ const char *bar = strchr(packed, '|');
+ const char *saved_nesting = ctx->nesting;
+ const char *ref = packed;
+ if (bar) {
+ ctx->nesting = cbm_arena_strndup(ctx->arena, packed, (size_t)(bar - packed));
+ ref = bar + 1;
+ } else {
+ ctx->nesting = "";
+ }
+ const char *qn = ruby_resolve_constant(ctx, ref);
+ ctx->nesting = saved_nesting;
+ return qn;
+}
+
+/* Bare ref portion of a packed "<nesting>|<ref>" string. */
+static const char *ruby_packed_bare_ref(const char *packed) {
+ if (!packed)
+ return NULL;
+ const char *bar = strchr(packed, '|');
+ return bar ? bar + 1 : packed;
+}
+
+/* Interpret a class-body `include X` / `prepend X` / `extend X` call,
+ * recording the mixin with the nesting packed for finalize-time resolve. */
+static void ruby_collect_mixin_call(RubyLSPContext *ctx, TSNode call) {
+ if (!ctx->enclosing_class_qn)
+ return;
+ TSNode meth = ts_node_child_by_field_name(call, "method", 6);
+ TSNode recv = ts_node_child_by_field_name(call, "receiver", 8);
+ if (ts_node_is_null(meth))
+ return;
+ if (!ts_node_is_null(recv) && strcmp(ts_node_type(recv), "self") != 0)
+ return; /* not a bare/self class-body macro */
+ char *mname = ruby_node_text(ctx, meth);
+ if (!mname)
+ return;
+ RubyMixinKind kind;
+ if (strcmp(mname, "include") == 0)
+ kind = RUBY_MIXIN_INCLUDE;
+ else if (strcmp(mname, "prepend") == 0)
+ kind = RUBY_MIXIN_PREPEND;
+ else if (strcmp(mname, "extend") == 0)
+ kind = RUBY_MIXIN_EXTEND;
+ else
+ return;
+ TSNode args = ts_node_child_by_field_name(call, "arguments", 9);
+ if (ts_node_is_null(args))
+ return;
+ uint32_t nc = ts_node_named_child_count(args);
+ for (uint32_t i = 0; i < nc; i++) {
+ const char *mpath = ruby_const_path(ctx, ts_node_named_child(args, i));
+ if (!mpath)
+ continue; /* `extend self` etc. — not a constant */
+ ruby_add_mixin(ctx, ctx->enclosing_class_qn, ruby_pack_ref(ctx, mpath), kind);
+ }
+}
+
+static void ruby_pass1_class(RubyLSPContext *ctx, TSNode node, bool is_module) {
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ const char *cpath = ruby_const_path(ctx, name);
+ if (!cpath)
+ return;
+
+ const char *saved_nesting = ctx->nesting;
+ const char *full_path = ruby_path_join(ctx->arena, saved_nesting, cpath);
+ const char *qn = ctx->module_qn
+ ? cbm_arena_sprintf(ctx->arena, "%s.%s", ctx->module_qn, full_path)
+ : full_path;
+ RubyClassInfo *ci = ruby_add_class(ctx, full_path, qn, is_module);
+
+ /* Superclass: `class C < Base` — the `superclass` field wraps the
+ * expression after `<`. */
+ if (ci && !is_module && !ci->superclass_ref) {
+ TSNode sup = ts_node_child_by_field_name(node, "superclass", 10);
+ if (!ts_node_is_null(sup)) {
+ uint32_t sc = ts_node_named_child_count(sup);
+ for (uint32_t i = 0; i < sc; i++) {
+ const char *spath = ruby_const_path(ctx, ts_node_named_child(sup, i));
+ if (spath) {
+ ci->superclass_ref = ruby_pack_ref(ctx, spath);
+ break;
+ }
+ }
+ }
+ }
+
+ ctx->nesting = full_path;
+ const char *saved_class = ctx->enclosing_class_qn;
+ bool saved_singleton = ctx->in_singleton_method;
+ ctx->enclosing_class_qn = qn;
+ ctx->in_singleton_method = false;
+ TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ if (!ts_node_is_null(body))
+ ruby_pass1_scan(ctx, body);
+ ctx->nesting = saved_nesting;
+ ctx->enclosing_class_qn = saved_class;
+ ctx->in_singleton_method = saved_singleton;
+}
+
+static void ruby_pass1_scan(RubyLSPContext *ctx, TSNode node) {
+ if (ctx->walk_depth >= CBM_LSP_RUBY_MAX_WALK_DEPTH)
+ return;
+ ctx->walk_depth++;
+ ruby_pass1_scan_inner(ctx, node);
+ ctx->walk_depth--;
+}
+
+/* Registry under construction during PASS 1 (methods are registered as
+ * they are discovered). Held in a file-scope slot only for the duration of
+ * cbm_run_ruby_lsp's pass-1 invocation — single-threaded per file. */
+static void ruby_pass1_scan_inner(RubyLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return;
+ const char *k = ts_node_type(node);
+
+ if (strcmp(k, "class") == 0) {
+ ruby_pass1_class(ctx, node, false);
+ return;
+ }
+ if (strcmp(k, "module") == 0) {
+ ruby_pass1_class(ctx, node, true);
+ return;
+ }
+ if (strcmp(k, "singleton_class") == 0) {
+ bool saved = ctx->in_singleton_method;
+ ctx->in_singleton_method = true;
+ uint32_t nc = ts_node_named_child_count(node);
+ for (uint32_t i = 0; i < nc; i++)
+ ruby_pass1_scan(ctx, ts_node_named_child(node, i));
+ ctx->in_singleton_method = saved;
+ return;
+ }
+ if (strcmp(k, "method") == 0 || strcmp(k, "singleton_method") == 0) {
+ bool singleton = ctx->in_singleton_method || strcmp(k, "singleton_method") == 0;
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ char *mname = ts_node_is_null(name) ? NULL : ruby_node_text(ctx, name);
+ if (ctx->build_reg)
+ ruby_register_method(ctx, ctx->build_reg, ctx->enclosing_class_qn, mname, singleton);
+ return; /* method bodies are PASS-2 territory */
+ }
+ if (strcmp(k, "call") == 0) {
+ TSNode meth = ts_node_child_by_field_name(node, "method", 6);
+ if (!ts_node_is_null(meth)) {
+ char *mn = ruby_node_text(ctx, meth);
+ if (mn && (strcmp(mn, "include") == 0 || strcmp(mn, "prepend") == 0 ||
+ strcmp(mn, "extend") == 0)) {
+ ruby_collect_mixin_call(ctx, node);
+ return;
+ }
+ }
+ }
+
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode c = ts_node_child(node, i);
+ if (!ts_node_is_null(c))
+ ruby_pass1_scan(ctx, c);
+ }
+}
+
+/* Finalize PASS 1: resolve superclass + mixin references now that the class
+ * table is complete. */
+static void ruby_finalize_refs(RubyLSPContext *ctx) {
+ for (int i = 0; i < ctx->class_count; i++) {
+ RubyClassInfo *ci = &ctx->classes[i];
+ if (ci->superclass_ref) {
+ ci->superclass_qn = ruby_resolve_packed_ref(ctx, ci->superclass_ref);
+ /* Keep the bare ref spelling for AR-model heuristics. */
+ ci->superclass_ref = ruby_packed_bare_ref(ci->superclass_ref);
+ }
+ }
+ for (int i = 0; i < ctx->mixin_count; i++) {
+ RubyMixinInfo *mi = &ctx->mixins[i];
+ mi->module_qn = ruby_resolve_packed_ref(ctx, mi->module_ref);
+ mi->module_ref = ruby_packed_bare_ref(mi->module_ref);
+ }
+}
+
+/* ── PASS 1.5: instance-variable type inference ─────────────────── */
+
+/* Statically evaluate `Const.new` / `A::B.new` without scope context. */
+static const char *ruby_static_ctor_type(RubyLSPContext *ctx, TSNode expr) {
+ if (ts_node_is_null(expr) || strcmp(ts_node_type(expr), "call") != 0)
+ return NULL;
+ TSNode meth = ts_node_child_by_field_name(expr, "method", 6);
+ TSNode recv = ts_node_child_by_field_name(expr, "receiver", 8);
+ if (ts_node_is_null(meth) || ts_node_is_null(recv))
+ return NULL;
+ char *mname = ruby_node_text(ctx, meth);
+ if (!mname || strcmp(mname, "new") != 0)
+ return NULL;
+ const char *cpath = ruby_const_path(ctx, recv);
+ if (!cpath)
+ return NULL;
+ return ruby_resolve_constant(ctx, cpath);
+}
+
+static void ruby_ivar_scan(RubyLSPContext *ctx, TSNode node) {
+ if (ctx->walk_depth >= CBM_LSP_RUBY_MAX_WALK_DEPTH)
+ return;
+ ctx->walk_depth++;
+ ruby_ivar_scan_inner(ctx, node);
+ ctx->walk_depth--;
+}
+
+static void ruby_ivar_scan_inner(RubyLSPContext *ctx, TSNode node) {
+ if (ts_node_is_null(node))
+ return;
+ const char *k = ts_node_type(node);
+
+ if (strcmp(k, "class") == 0 || strcmp(k, "module") == 0) {
+ TSNode name = ts_node_child_by_field_name(node, "name", 4);
+ const char *cpath = ruby_const_path(ctx, name);
+ if (!cpath)
+ return;
+ const char *saved_nesting = ctx->nesting;
+ const char *saved_class = ctx->enclosing_class_qn;
+ ctx->nesting = ruby_path_join(ctx->arena, saved_nesting, cpath);
+ ctx->enclosing_class_qn = ruby_resolve_constant(ctx, cpath);
+ TSNode body = ts_node_child_by_field_name(node, "body", 4);
+ if (!ts_node_is_null(body))
+ ruby_ivar_scan(ctx, body);
+ ctx->nesting = saved_nesting;
+ ctx->enclosing_class_qn = saved_class;
+ return;
+ }
+
+ if (strcmp(k, "assignment") == 0 && ctx->enclosing_class_qn) {
+ TSNode left = ts_node_child_by_field_name(node, "left", 4);
+ TSNode right = ts_node_child_by_field_name(node, "right", 5);
+ if (!ts_node_is_null(left) && !ts_node_is_null(right) &&
+ strcmp(ts_node_type(left), "instance_variable") == 0) {
+ const char *tqn = ruby_static_ctor_type(ctx, right);
+ if (tqn) {
+ char *ivar = ruby_node_text(ctx, left);
+ ruby_add_ivar(ctx, ctx->enclosing_class_qn, ivar, tqn);
+ }
+ }
+ }
+
+ uint32_t nc = ts_node_child_count(node);
+ for (uint32_t i = 0; i < nc; i++) {
+ TSNode c = ts_node_child(node, i);
+ if (!ts_node_is_null(c))
+ ruby_ivar_scan(ctx, c);
+ }
+}
+
+/* ── public API ─────────────────────────────────────────────────── */
+
+void ruby_lsp_init(RubyLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn,
+ CBMResolvedCallArray *out) {
+ memset(ctx, 0, sizeof(*ctx));
+ ctx->arena = arena;
+ ctx->source = source;
+ ctx->source_len = source_len;
+ ctx->registry = registry;
+ ctx->module_qn = module_qn;
+ ctx->nesting = "";
+ ctx->resolved_calls = out;
+ ctx->current_scope = cbm_scope_push(arena, NULL);
+
+ const char *dbg = getenv("CBM_LSP_DEBUG");
+ ctx->debug = (dbg && dbg[0]);
+}
+
+/* ── entry: cbm_run_ruby_lsp ────────────────────────────────────── */
+
+void cbm_run_ruby_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root) {
+ if (!result || !arena || ts_node_is_null(root))
+ return;
+
+ CBMTypeRegistry reg;
+ cbm_registry_init(&reg, arena);
+
+ /* Phase A: stdlib (Ruby core + curated Rails surface). */
+ cbm_ruby_stdlib_register(&reg, arena);
+
+ const char *module_qn = result->module_qn;
+
+ RubyLSPContext ctx;
+ ruby_lsp_init(&ctx, arena, source, source_len, &reg, module_qn, &result->resolved_calls);
+
+ /* Phase B: PASS 1 — collect classes/modules, mixins, and methods from
+ * the AST (methods register directly into `reg`; the AST is ground
+ * truth for the instance-vs-singleton split the defs don't carry). */
+ ctx.build_reg = &reg;
+ ruby_pass1_scan(&ctx, root);
+ ctx.build_reg = NULL;
+ ruby_finalize_refs(&ctx);
+
+ /* Finalize the registry for O(1) lookups — index allocations go to a
+ * per-call scratch arena that dies with this call (see perl_lsp.c). */
+ CBMArena idx_arena;
+ cbm_arena_init(&idx_arena);
+ cbm_registry_finalize_into(&reg, &idx_arena);
+
+ /* Phase B.5: PASS 1.5 — instance-variable types (needs the finished
+ * class table + registry for constant resolution). */
+ ctx.nesting = "";
+ ctx.enclosing_class_qn = NULL;
+ ruby_ivar_scan(&ctx, root);
+
+ /* Phase C: PASS 2 — resolution walk. */
+ ctx.nesting = "";
+ ctx.enclosing_class_qn = NULL;
+ ctx.enclosing_func_qn = NULL;
+ ctx.in_singleton_method = false;
+ ruby_resolve_calls_in_node(&ctx, root);
+
+ if (ctx.debug) {
+ fprintf(stderr, "[ruby_lsp] module_qn=%s defs=%d resolved=%d classes=%d mixins=%d\n",
+ module_qn ? module_qn : "(null)", result->defs.count, result->resolved_calls.count,
+ ctx.class_count, ctx.mixin_count);
+ for (int i = 0; i < result->resolved_calls.count; i++) {
+ CBMResolvedCall *r = &result->resolved_calls.items[i];
+ fprintf(stderr, "[ruby_lsp] %s -> %s [%s %.2f]\n", r->caller_qn, r->callee_qn,
+ r->strategy, r->confidence);
+ }
+ }
+
+ cbm_arena_destroy(&idx_arena);
+}
diff --git a/internal/cbm/lsp/ruby_lsp.h b/internal/cbm/lsp/ruby_lsp.h
new file mode 100644
index 000000000..f6de32943
--- /dev/null
+++ b/internal/cbm/lsp/ruby_lsp.h
@@ -0,0 +1,148 @@
+#ifndef CBM_LSP_RUBY_LSP_H
+#define CBM_LSP_RUBY_LSP_H
+
+#include "type_rep.h"
+#include "scope.h"
+#include "type_registry.h"
+#include "../cbm.h"
+
+/* Ruby mixin kinds. Lookup order for an instance method on class C:
+ * prepended modules (last prepended first) → C's own methods →
+ * included modules (last included first) → superclass chain.
+ * `extend` adds a module's instance methods to C's singleton (class-side). */
+typedef enum {
+ RUBY_MIXIN_INCLUDE = 0,
+ RUBY_MIXIN_PREPEND,
+ RUBY_MIXIN_EXTEND,
+} RubyMixinKind;
+
+/* One class/module discovered in the file (or, cross-file, in the project).
+ * `path` is the dotted source-level constant path (e.g. "Admin.User" for
+ * `Admin::User`); `qn` is the full graph QN (module_qn.path for file-local
+ * classes; the extractor QN for cross-file defs). `superclass_qn` is resolved
+ * against the class table + stdlib after collection; NULL when unknown. */
+typedef struct {
+ const char *path;
+ const char *qn;
+ const char *superclass_ref; /* raw dotted superclass spelling, or NULL */
+ const char *superclass_qn; /* resolved QN (table/stdlib), or NULL */
+ bool is_module; /* `module` (mixin source) vs `class` */
+} RubyClassInfo;
+
+/* One `include`/`prepend`/`extend` record: owner class QN → module ref. */
+typedef struct {
+ const char *owner_qn; /* class/module whose body held the call */
+ const char *module_ref; /* raw dotted module spelling */
+ const char *module_qn; /* resolved QN, or NULL */
+ RubyMixinKind kind;
+} RubyMixinInfo;
+
+/* One inferred instance-variable type: (class QN, @name) → type QN.
+ * `conflicted` latches when two assignments disagree — lookup then returns
+ * nothing (zero-edge guarantee beats a coin-flip type). */
+typedef struct {
+ const char *class_qn;
+ const char *ivar_name; /* including the leading '@' */
+ const char *type_qn;
+ bool conflicted;
+} RubyIvarInfo;
+
+/* RubyLSPContext — per-file state for Ruby type-aware call resolution.
+ * Mirrors PerlLSPContext / PHPLSPContext structure.
+ *
+ * Ruby specifics that shape this context:
+ * - Classes/modules nest lexically (`module A; class B`), and constants
+ * resolve through the lexical nesting outward (A::B sees A's constants
+ * before top-level ones). `nesting` tracks the current dotted path.
+ * - Inheritance is `class C < Base`; mixins arrive via include/prepend/
+ * extend and participate in method lookup (see RubyMixinKind).
+ * - `Foo.new` constructs a Foo and dispatches to Foo#initialize.
+ * - `def m` defines an instance method; `def self.m` a singleton (class)
+ * method. Singleton methods are registered under the receiver key
+ * "<class_qn>.self" — constants cannot be lowercase, so the suffix can
+ * never collide with a real nested-constant path. */
+typedef struct {
+ CBMArena *arena;
+ const char *source;
+ int source_len;
+ const CBMTypeRegistry *registry;
+ /* Mutable alias of `registry`, set only while PASS 1 populates method
+ * tables (mirrors perl_lsp's mutable-reg build phase). NULL afterwards. */
+ CBMTypeRegistry *build_reg;
+ CBMScope *current_scope;
+
+ /* Lexical nesting: dotted constant path of the enclosing class/module
+ * chain ("" at top level, "A.B" inside `module A; class B`). */
+ const char *nesting;
+
+ /* Class/module table (pass 1). */
+ RubyClassInfo *classes;
+ int class_count;
+ int class_cap;
+
+ /* Mixin table (pass 1). */
+ RubyMixinInfo *mixins;
+ int mixin_count;
+ int mixin_cap;
+
+ /* Instance-variable type table (pass 1). */
+ RubyIvarInfo *ivars;
+ int ivar_count;
+ int ivar_cap;
+
+ /* Cross-file import map (require/require_relative resolved by the
+ * pipeline). Unused per-file: Ruby constants are file-global. */
+ const char **import_names;
+ const char **import_qns;
+ int import_count;
+
+ /* Current enclosing context during the resolution walk. */
+ const char *enclosing_class_qn; /* class QN, or NULL at top level */
+ const char *enclosing_func_qn; /* enclosing method QN, or NULL */
+ bool in_singleton_method; /* `def self.m` / class << self scope */
+ const char *module_qn;
+
+ /* Output: resolved calls accumulate here. */
+ CBMResolvedCallArray *resolved_calls;
+
+ /* Recursion guards. */
+ int eval_depth;
+ int walk_depth;
+
+ /* Debug mode (CBM_LSP_DEBUG env). */
+ bool debug;
+} RubyLSPContext;
+
+/* Initialize a RubyLSPContext for processing one file. */
+void ruby_lsp_init(RubyLSPContext *ctx, CBMArena *arena, const char *source, int source_len,
+ const CBMTypeRegistry *registry, const char *module_qn,
+ CBMResolvedCallArray *out);
+
+/* Resolve a dotted constant path (e.g. "Foo", "A.B") against the class
+ * table using the current lexical nesting, then the stdlib. Returns the
+ * resolved QN or NULL. */
+const char *ruby_resolve_constant(RubyLSPContext *ctx, const char *path);
+
+/* Look up an instance method on a class, walking prepends → own → includes →
+ * superclass chain. Returns the resolved CBMRegisteredFunc or NULL. */
+const CBMRegisteredFunc *ruby_lookup_instance_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name);
+
+/* Look up a singleton (class-side) method: own singleton methods →
+ * `extend`ed modules' instance methods → superclass singleton chain. */
+const CBMRegisteredFunc *ruby_lookup_singleton_method(RubyLSPContext *ctx, const char *class_qn,
+ const char *method_name);
+
+/* Evaluate a Ruby expression's type. May return CBM_TYPE_UNKNOWN. */
+const CBMType *ruby_eval_expr_type(RubyLSPContext *ctx, TSNode node);
+
+/* Entry point: build registry from file defs + stdlib, then run resolution.
+ * Called from cbm_extract_file() via the language dispatch in cbm.c. */
+void cbm_run_ruby_lsp(CBMArena *arena, CBMFileResult *result, const char *source, int source_len,
+ TSNode root);
+
+/* Register Ruby core stdlib types/methods + a curated Rails surface
+ * (ActiveRecord/ActiveSupport/ActionController) into a registry. */
+void cbm_ruby_stdlib_register(CBMTypeRegistry *reg, CBMArena *arena);
+
+#endif /* CBM_LSP_RUBY_LSP_H */
diff --git a/internal/cbm/lsp_all.c b/internal/cbm/lsp_all.c
index 4ab1f5155..7cf05a0c4 100644
--- a/internal/cbm/lsp_all.c
+++ b/internal/cbm/lsp_all.c
@@ -14,6 +14,8 @@
#include "lsp/generated/php_stdlib_data.c"
#include "lsp/perl_lsp.c"
#include "lsp/generated/perl_stdlib_data.c"
+#include "lsp/ruby_lsp.c"
+#include "lsp/generated/ruby_stdlib_data.c"
#include "lsp/generated/python_stdlib_data.c"
#include "lsp/py_lsp.c"
#include "lsp/ts_lsp.c"
diff --git a/scripts/check-lsp-originality.sh b/scripts/check-lsp-originality.sh
index a50af9de4..f02b9cc8b 100755
--- a/scripts/check-lsp-originality.sh
+++ b/scripts/check-lsp-originality.sh
@@ -27,7 +27,7 @@
# USAGE
# bash scripts/check-lsp-originality.sh [--lang NAME] [--refresh]
# [--list-candidates] [--help]
-# --lang NAME scan against ONE reference only (py|ts|go|cs|c|java|kotlin|rust|php|perl)
+# --lang NAME scan against ONE reference only (py|ts|go|cs|c|java|kotlin|rust|php|perl|ruby)
# --refresh re-fetch reference sources even if cached
# --list-candidates print the extracted local tokens and exit (no fetch; self-test)
# Exit 0 = no verbatim overlap found. Exit 1 = overlap(s) to review by a human.
@@ -64,6 +64,10 @@ REFS=(
# Perl (PR #461) was authored clean-room. We scan against PerlNavigator (MIT)
# — the leading OSS Perl language server — for defensive copy-detection.
"perl|https://github.com/bscan/PerlNavigator|server/src"
+ # Ruby was authored clean-room from the tree-sitter-ruby grammar + Ruby
+ # language semantics. We scan against Shopify's ruby-lsp (MIT) — the
+ # leading OSS Ruby language server — for defensive copy-detection.
+ "ruby|https://github.com/Shopify/ruby-lsp|lib"
)
ONLY_LANG=""; REFRESH=0; LIST_ONLY=0
diff --git a/tests/test_main.c b/tests/test_main.c
index ba6f26d45..883ba4ed6 100644
--- a/tests/test_main.c
+++ b/tests/test_main.c
@@ -733,6 +733,7 @@ extern void suite_php_lsp(void);
extern void suite_cs_lsp(void);
extern void suite_cs_lsp_bench(void);
extern void suite_perl_lsp(void);
+extern void suite_ruby_lsp(void);
extern void suite_scope(void);
extern void suite_type_rep(void);
extern void suite_py_lsp(void);
@@ -1026,6 +1027,7 @@ int main(int argc, char **argv) {
RUN_SELECTED_SUITE(cs_lsp);
RUN_SELECTED_SUITE_PERF(cs_lsp_bench);
RUN_SELECTED_SUITE(perl_lsp);
+ RUN_SELECTED_SUITE(ruby_lsp);
RUN_SELECTED_SUITE(py_lsp);
RUN_SELECTED_SUITE(kotlin_lsp);
RUN_SELECTED_SUITE(rust_lsp);
diff --git a/tests/test_ruby_lsp.c b/tests/test_ruby_lsp.c
new file mode 100644
index 000000000..23c37314e
--- /dev/null
+++ b/tests/test_ruby_lsp.c
@@ -0,0 +1,636 @@
+/*
+ * test_ruby_lsp.c — Tests for the Ruby Light Semantic Pass.
+ *
+ * Coverage mirrors tests/test_perl_lsp.c / tests/test_php_lsp.c, exercising
+ * the foundational Ruby resolution scenarios:
+ * 1. QN contract (defs carry module_qn.ClassPath.method — the join key
+ * the resolver's emitted rows depend on)
+ * 2. Constructor typing + edge (a = Animal.new; a.speak)
+ * 3. Constructor edge targets CLASS (textual `Widget.new` -> "Widget")
+ * 4. Implicit/explicit self dispatch
+ * 5. Singleton (class) methods (def self.m; Animal.m)
+ * 6. Superclass chain lookup (class B < A)
+ * 7. include + prepend mixin lookup (prepend shadows the class's own)
+ * 8. extend mixin (class-side) lookup
+ * 9. super dispatch
+ * 10. Instance-variable typing (@thing = Foo.new; @thing.bar)
+ * 11. Chained call typing (Foo.new.bar)
+ * 12. Nested modules (lexical nesting + `A::B` references)
+ * 13. ActiveRecord model typing (User.find(1).full_name)
+ * 14. Top-level function calls
+ * 15. Unresolvable receiver emits NO spurious edge (negative)
+ * 16. send() / the whole dynamic-dispatch family emits NO edge (negative)
+ *
+ * Scope: every row here is SINGLE-FILE, driven through cbm_extract_file so it
+ * exercises the per-file resolver exactly as the extraction pipeline calls it.
+ * Cross-file resolution (cbm_run_ruby_lsp_cross, wired through
+ * pass_lsp_cross.c) is a separate tier and is covered by its own rows.
+ *
+ * The resolver populates result->resolved_calls with CBMResolvedCall rows.
+ * Ruby defs weave the class path into the QN (module_qn.Animal.speak), so
+ * for these single-file fixtures ("test"/"main.rb" -> module QN test.main)
+ * callee fragments like "main.Animal.speak" are unique join keys.
+ */
+#include "test_framework.h"
+#include "cbm.h"
+#include "../src/pipeline/lsp_resolve.h"
+#include "lsp/ruby_lsp.h"
+#include <string.h>
+
+/* ── Helpers (mirror test_perl_lsp.c) ──────────────────────────── */
+
+static CBMFileResult *extract_ruby(const char *source) {
+ return cbm_extract_file(source, (int)strlen(source), CBM_LANG_RUBY, "test", "main.rb", 0, NULL,
+ NULL);
+}
+
+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 const CBMResolvedCall *find_resolved_with_strategy(const CBMFileResult *r,
+ const char *callerSub,
+ const char *calleeSub,
+ const char *strategy) {
+ for (int i = 0; i < r->resolved_calls.count; i++) {
+ const CBMResolvedCall *rc = &r->resolved_calls.items[i];
+ if (!rc->caller_qn || !rc->callee_qn)
+ continue;
+ if (!strstr(rc->caller_qn, callerSub))
+ continue;
+ if (!strstr(rc->callee_qn, calleeSub))
+ continue;
+ if (strategy && (!rc->strategy || strcmp(rc->strategy, strategy) != 0))
+ continue;
+ return rc;
+ }
+ return NULL;
+}
+
+static const CBMDefinition *find_def(const CBMFileResult *r, const char *label, const char *name) {
+ for (int i = 0; i < r->defs.count; i++) {
+ const CBMDefinition *d = &r->defs.items[i];
+ if (d->label && d->name && strcmp(d->label, label) == 0 && strcmp(d->name, name) == 0)
+ return d;
+ }
+ return NULL;
+}
+
+/* ── 1. QN contract: defs weave the class path into method QNs ─── */
+
+TEST(rubylsp_qn_contract) {
+ const char *src = "class Animal\n"
+ " def speak\n"
+ " 'woof'\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ const CBMDefinition *m = find_def(r, "Method", "speak");
+ if (!m) {
+ printf(" no Method speak def; defs:\n");
+ for (int i = 0; i < r->defs.count; i++)
+ printf(" [%s] %s qn=%s parent=%s\n", r->defs.items[i].label, r->defs.items[i].name,
+ r->defs.items[i].qualified_name,
+ r->defs.items[i].parent_class ? r->defs.items[i].parent_class : "(null)");
+ }
+ ASSERT(m);
+ if (strcmp(m->qualified_name, "test.main.Animal.speak") != 0) {
+ printf(" QN scheme mismatch: got %s (resolver assumes module_qn.ClassPath.method)\n",
+ m->qualified_name);
+ }
+ ASSERT(strcmp(m->qualified_name, "test.main.Animal.speak") == 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 2. Constructor typing: a = Animal.new; a.speak ────────────── */
+
+TEST(rubylsp_method_via_constructor_assignment) {
+ const char *src = "class Animal\n"
+ " def initialize(name)\n"
+ " @name = name\n"
+ " end\n"
+ " def speak\n"
+ " @name\n"
+ " end\n"
+ "end\n"
+ "class Runner\n"
+ " def run\n"
+ " a = Animal.new('rex')\n"
+ " a.speak\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "Runner.run", "Animal.speak") >= 0);
+ ASSERT(find_resolved_with_strategy(r, "Runner.run", "Animal.speak", "ruby_method_typed"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 3. Constructor edge targets the CLASS node ─────────────────── */
+
+TEST(rubylsp_constructor_edge_targets_class) {
+ const char *src = "class Widget\n"
+ " def initialize\n"
+ " end\n"
+ "end\n"
+ "class Maker\n"
+ " def build\n"
+ " Widget.new\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ const CBMResolvedCall *rc =
+ find_resolved_with_strategy(r, "Maker.build", "Widget", "ruby_constructor");
+ ASSERT(rc);
+ /* Callee is the class QN (leaf "Widget"), matching the textual
+ * extractor's Widget.new -> "Widget" rewrite so the row joins. */
+ ASSERT(strcmp(rc->callee_qn, "test.main.Widget") == 0);
+ ASSERT(rc->confidence >= CBM_LSP_CONFIDENCE_FLOOR);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 4. Implicit + explicit self dispatch ───────────────────────── */
+
+TEST(rubylsp_self_dispatch) {
+ const char *src = "class Greeter\n"
+ " def greet\n"
+ " build_greeting('hi')\n"
+ " self.build_greeting('yo')\n"
+ " end\n"
+ " def build_greeting(word)\n"
+ " word\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "Greeter.greet", "Greeter.build_greeting") >= 0);
+ ASSERT(find_resolved_with_strategy(r, "Greeter.greet", "Greeter.build_greeting",
+ "ruby_self_dispatch"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 5. Singleton (class) methods ───────────────────────────────── */
+
+TEST(rubylsp_singleton_method_dispatch) {
+ const char *src = "class Registry\n"
+ " def self.register(key)\n"
+ " key\n"
+ " end\n"
+ "end\n"
+ "class App\n"
+ " def boot\n"
+ " Registry.register(:db)\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "App.boot", "Registry.register") >= 0);
+ ASSERT(find_resolved_with_strategy(r, "App.boot", "Registry.register", "ruby_class_method"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* Singleton methods must NOT satisfy instance dispatch (and vice versa). */
+TEST(rubylsp_singleton_instance_split) {
+ const char *src = "class Config\n"
+ " def self.load\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class App\n"
+ " def boot\n"
+ " c = Config.new\n"
+ " c.load\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* c.load is an INSTANCE call; Config only defines a singleton `load`.
+ * Zero-edge guarantee: no resolved row may bind them. */
+ ASSERT(find_resolved(r, "App.boot", "Config.load") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 6. Superclass chain ────────────────────────────────────────── */
+
+TEST(rubylsp_inheritance) {
+ const char *src = "class Base\n"
+ " def helper\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class Child < Base\n"
+ " def work\n"
+ " helper\n"
+ " self.helper\n"
+ " end\n"
+ "end\n"
+ "class Driver\n"
+ " def drive\n"
+ " c = Child.new\n"
+ " c.helper\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* Inherited method resolves to Base.helper from both dispatch shapes. */
+ ASSERT(require_resolved(r, "Child.work", "Base.helper") >= 0);
+ ASSERT(require_resolved(r, "Driver.drive", "Base.helper") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 7. include mixin ───────────────────────────────────────────── */
+
+TEST(rubylsp_include_mixin) {
+ const char *src = "module Greetable\n"
+ " def greet\n"
+ " 'hello'\n"
+ " end\n"
+ "end\n"
+ "class Person\n"
+ " include Greetable\n"
+ " def hail\n"
+ " greet()\n"
+ " end\n"
+ "end\n"
+ "class Caller\n"
+ " def run\n"
+ " p = Person.new\n"
+ " p.greet\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "Person.hail", "Greetable.greet") >= 0);
+ ASSERT(require_resolved(r, "Caller.run", "Greetable.greet") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 7b. prepend mixin shadows the class's own method ───────────── */
+
+/* Ruby's lookup order puts prepended modules AHEAD of the class itself, which
+ * is the whole point of `prepend` over `include`. Both an own method and a
+ * prepended one exist here, so a resolver that walked the class first would
+ * still emit an edge — just the wrong one. Pin the winner, not merely that
+ * something resolved. */
+TEST(rubylsp_prepend_mixin) {
+ const char *src = "module Audited\n"
+ " def save\n"
+ " 'audited'\n"
+ " end\n"
+ "end\n"
+ "class Record\n"
+ " prepend Audited\n"
+ " def save\n"
+ " 'plain'\n"
+ " end\n"
+ "end\n"
+ "class App\n"
+ " def run\n"
+ " r = Record.new\n"
+ " r.save\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* The prepended module wins. */
+ ASSERT(require_resolved(r, "App.run", "Audited.save") >= 0);
+ /* And the shadowed own method must NOT also be emitted. */
+ ASSERT(find_resolved(r, "App.run", "Record.save") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 8. extend mixin (class-side) ───────────────────────────────── */
+
+TEST(rubylsp_extend_mixin) {
+ const char *src = "module Findable\n"
+ " def locate(id)\n"
+ " id\n"
+ " end\n"
+ "end\n"
+ "class Record\n"
+ " extend Findable\n"
+ "end\n"
+ "class App\n"
+ " def run\n"
+ " Record.locate(7)\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "App.run", "Findable.locate") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 9. super dispatch ──────────────────────────────────────────── */
+
+TEST(rubylsp_super_dispatch) {
+ const char *src = "class Base\n"
+ " def setup\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class Child < Base\n"
+ " def setup\n"
+ " super\n"
+ " 2\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ const CBMResolvedCall *rc =
+ find_resolved_with_strategy(r, "Child.setup", "Base.setup", "ruby_method_super");
+ if (!rc)
+ (void)require_resolved(r, "Child.setup", "Base.setup");
+ ASSERT(rc);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 10. Instance-variable typing ───────────────────────────────── */
+
+TEST(rubylsp_ivar_typing) {
+ const char *src = "class Engine\n"
+ " def start\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class Car\n"
+ " def initialize\n"
+ " @engine = Engine.new\n"
+ " end\n"
+ " def drive\n"
+ " @engine.start\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "Car.drive", "Engine.start") >= 0);
+ ASSERT(find_resolved_with_strategy(r, "Car.drive", "Engine.start", "ruby_ivar_method"));
+ cbm_free_result(r);
+ PASS();
+}
+
+/* Conflicting ivar assignments must suppress the type (zero-edge). */
+TEST(rubylsp_ivar_conflict_no_edge) {
+ const char *src = "class A\n"
+ " def go\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class B\n"
+ " def go\n"
+ " 2\n"
+ " end\n"
+ "end\n"
+ "class Holder\n"
+ " def initialize(flag)\n"
+ " @x = A.new\n"
+ " @x = B.new\n"
+ " end\n"
+ " def run\n"
+ " @x.go\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(find_resolved(r, "Holder.run", ".go") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 11. Chained calls ──────────────────────────────────────────── */
+
+TEST(rubylsp_chained_constructor_call) {
+ const char *src = "class Builder\n"
+ " def finish\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class App\n"
+ " def run\n"
+ " Builder.new.finish\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(require_resolved(r, "App.run", "Builder.finish") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 12. Nested modules + lexical nesting ───────────────────────── */
+
+TEST(rubylsp_nested_modules) {
+ const char *src = "module Admin\n"
+ " class User\n"
+ " def self.lookup(id)\n"
+ " id\n"
+ " end\n"
+ " def name\n"
+ " 'n'\n"
+ " end\n"
+ " end\n"
+ " class Panel\n"
+ " def show\n"
+ " User.lookup(1)\n"
+ " u = User.new\n"
+ " u.name\n"
+ " end\n"
+ " end\n"
+ "end\n"
+ "class Outside\n"
+ " def probe\n"
+ " Admin::User.lookup(2)\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* Lexical reference from sibling class inside the module. */
+ ASSERT(require_resolved(r, "Panel.show", "User.lookup") >= 0);
+ ASSERT(require_resolved(r, "Panel.show", "User.name") >= 0);
+ /* Fully-qualified reference from outside. */
+ ASSERT(require_resolved(r, "Outside.probe", "User.lookup") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 13. ActiveRecord model typing ──────────────────────────────── */
+
+TEST(rubylsp_activerecord_model_typing) {
+ const char *src = "class User < ApplicationRecord\n"
+ " def full_name\n"
+ " 'x'\n"
+ " end\n"
+ "end\n"
+ "class UsersController < ApplicationController\n"
+ " def show\n"
+ " u = User.find(1)\n"
+ " u.full_name\n"
+ " end\n"
+ " def index\n"
+ " User.where(active: true).first.full_name\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* User.find returns User (AR query typing); u.full_name resolves. */
+ ASSERT(require_resolved(r, "UsersController.show", "User.full_name") >= 0);
+ /* Relation approximation keeps the model type through where/first. */
+ ASSERT(require_resolved(r, "UsersController.index", "User.full_name") >= 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 14. Top-level functions ────────────────────────────────────── */
+
+TEST(rubylsp_top_level_function) {
+ const char *src = "def helper(x)\n"
+ " x\n"
+ "end\n"
+ "def run\n"
+ " helper(1)\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ const CBMResolvedCall *rc =
+ find_resolved_with_strategy(r, "main.run", "main.helper", "ruby_function_local");
+ if (!rc)
+ (void)require_resolved(r, "main.run", "main.helper");
+ ASSERT(rc);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 15. Negative: unresolvable receiver emits no edge ──────────── */
+
+TEST(rubylsp_unknown_receiver_no_edge) {
+ const char *src = "class Safe\n"
+ " def process(payload)\n"
+ " payload.transform\n"
+ " mystery = fetch_thing\n"
+ " mystery.explode\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ /* Neither the untyped parameter nor the unresolved local may produce
+ * a resolved row. */
+ ASSERT(find_resolved(r, "Safe.process", "transform") < 0);
+ ASSERT(find_resolved(r, "Safe.process", "explode") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 16. Negative: dynamic dispatch emits no edge ───────────────── */
+
+TEST(rubylsp_send_no_edge) {
+ const char *src = "class Target\n"
+ " def hidden\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class Meta\n"
+ " def invoke\n"
+ " t = Target.new\n"
+ " t.send(:hidden)\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(find_resolved(r, "Meta.invoke", "hidden") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── 16b. Negative: the whole dynamic-dispatch family emits no edge ── */
+
+/* `send` has its own row above. The zero-edge guarantee is advertised for the
+ * whole reflective family, so pin the rest of it too: a resolver that treated
+ * any of these as an ordinary call would invent an edge to `hidden`. */
+TEST(rubylsp_dynamic_dispatch_family_no_edge) {
+ const char *src = "class Target\n"
+ " def hidden\n"
+ " 1\n"
+ " end\n"
+ "end\n"
+ "class Meta\n"
+ " def via_public_send\n"
+ " Target.new.public_send(:hidden)\n"
+ " end\n"
+ " def via_underscore_send\n"
+ " Target.new.__send__(:hidden)\n"
+ " end\n"
+ " def via_define_method\n"
+ " Target.define_method(:hidden) { 2 }\n"
+ " end\n"
+ " def via_instance_eval\n"
+ " Target.new.instance_eval { hidden }\n"
+ " end\n"
+ "end\n";
+ CBMFileResult *r = extract_ruby(src);
+ ASSERT(r);
+ ASSERT(find_resolved(r, "Meta.via_public_send", "hidden") < 0);
+ ASSERT(find_resolved(r, "Meta.via_underscore_send", "hidden") < 0);
+ ASSERT(find_resolved(r, "Meta.via_define_method", "hidden") < 0);
+ ASSERT(find_resolved(r, "Meta.via_instance_eval", "hidden") < 0);
+ cbm_free_result(r);
+ PASS();
+}
+
+/* ── suite ──────────────────────────────────────────────────────── */
+
+void suite_ruby_lsp(void) {
+ RUN_TEST(rubylsp_qn_contract);
+ RUN_TEST(rubylsp_method_via_constructor_assignment);
+ RUN_TEST(rubylsp_constructor_edge_targets_class);
+ RUN_TEST(rubylsp_self_dispatch);
+ RUN_TEST(rubylsp_singleton_method_dispatch);
+ RUN_TEST(rubylsp_singleton_instance_split);
+ RUN_TEST(rubylsp_inheritance);
+ RUN_TEST(rubylsp_include_mixin);
+ RUN_TEST(rubylsp_prepend_mixin);
+ RUN_TEST(rubylsp_extend_mixin);
+ RUN_TEST(rubylsp_super_dispatch);
+ RUN_TEST(rubylsp_ivar_typing);
+ RUN_TEST(rubylsp_ivar_conflict_no_edge);
+ RUN_TEST(rubylsp_chained_constructor_call);
+ RUN_TEST(rubylsp_nested_modules);
+ RUN_TEST(rubylsp_activerecord_model_typing);
+ RUN_TEST(rubylsp_top_level_function);
+ RUN_TEST(rubylsp_unknown_receiver_no_edge);
+ RUN_TEST(rubylsp_send_no_edge);
+ RUN_TEST(rubylsp_dynamic_dispatch_family_no_edge);
+}