From 7289f0f37c6581ca7e5957d9be7c9493671590b7 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 13:47:50 +0530 Subject: [PATCH 01/29] The code extra installs tree-sitter-ruby and the parse child loads it The Ruby lane parses with tree-sitter-ruby. Every parse runs in the bounded child first, so the child has to load the grammar as well. uv.lock is regenerated with uv 0.13.12 and keeps lock revision 5. Signed-off-by: Vanshaj Poonia --- pyproject.toml | 3 ++- server/code/domain/extract/bounded_parse.py | 1 + uv.lock | 17 +++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 08f4b9dd1fe..f978e0ab737 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -150,9 +150,10 @@ code = [ "tree-sitter-typescript>=0.23", "tree-sitter-javascript>=0.23", "tree-sitter-rust>=0.23", - # Go and Java (lane parsers + SQL islands) + # Go, Java and Ruby (lane parsers + SQL islands) "tree-sitter-go>=0.23", "tree-sitter-java>=0.23", + "tree-sitter-ruby>=0.23", "numpy>=1.26", ] # scripts/scip_harness only (protobuf parse of scip-clang output). Never a diff --git a/server/code/domain/extract/bounded_parse.py b/server/code/domain/extract/bounded_parse.py index 94b8e13bb01..bdeaec85560 100644 --- a/server/code/domain/extract/bounded_parse.py +++ b/server/code/domain/extract/bounded_parse.py @@ -64,6 +64,7 @@ "tree_sitter_java:language", "tree_sitter_javascript:language", "tree_sitter_python:language", + "tree_sitter_ruby:language", "tree_sitter_rust:language", "tree_sitter_tlaplus:language", "tree_sitter_typescript:language_typescript", diff --git a/uv.lock b/uv.lock index 9181e25e3c7..3ac5eaeb69f 100644 --- a/uv.lock +++ b/uv.lock @@ -841,6 +841,7 @@ code = [ { name = "tree-sitter-java" }, { name = "tree-sitter-javascript" }, { name = "tree-sitter-python" }, + { name = "tree-sitter-ruby" }, { name = "tree-sitter-rust" }, { name = "tree-sitter-typescript" }, ] @@ -955,6 +956,7 @@ requires-dist = [ { name = "tree-sitter-java", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-javascript", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-python", marker = "extra == 'code'", specifier = ">=0.23" }, + { name = "tree-sitter-ruby", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-rust", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-typescript", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "types-jsonschema", marker = "extra == 'dev'", specifier = ">=4.20" }, @@ -3951,6 +3953,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/07/19/4b5569d9b1ebebb5907d11554a96ef3fa09364a30fcfabeff587495b512f/tree_sitter_python-0.25.0-cp310-abi3-win_arm64.whl", hash = "sha256:0fbf6a3774ad7e89ee891851204c2e2c47e12b63a5edbe2e9156997731c128bb", size = 74169, upload-time = "2025-09-11T06:47:56.747Z" }, ] +[[package]] +name = "tree-sitter-ruby" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/09/5b/6d24be4fde4743481bd8e3fd24b434870cb6612238c8544b71fe129ed850/tree_sitter_ruby-0.23.1.tar.gz", hash = "sha256:886ed200bfd1f3ca7628bf1c9fefd42421bbdba70c627363abda67f662caa21e", size = 489602, upload-time = "2024-11-11T04:51:30.328Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/2e/2717b9451c712b60f833827a696baf29d8e50a0f7dccbf22a8d7006cc19e/tree_sitter_ruby-0.23.1-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:39f391322d2210843f07081182dbf00f8f69cfbfa4687b9575cac6d324bae443", size = 177959, upload-time = "2024-11-11T04:51:19.958Z" }, + { url = "https://files.pythonhosted.org/packages/e7/38/c41ecf7692b8ecccd26861d3293a88150a4a52fc081abe60f837030d7315/tree_sitter_ruby-0.23.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:aa4ee7433bd42fac22e2dad4a3c0f332292ecf482e610316828c711a0bb7f794", size = 195069, upload-time = "2024-11-11T04:51:21.82Z" }, + { url = "https://files.pythonhosted.org/packages/d8/01/14ef2d5107e6f42b64a400c3bbc3dd3b8fd24c3cef5306004ae03668f231/tree_sitter_ruby-0.23.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62b36813a56006b7569db7868f6b762caa3f4e419bd0f8cf9ccbb4abb1b6254c", size = 226761, upload-time = "2024-11-11T04:51:23.021Z" }, + { url = "https://files.pythonhosted.org/packages/23/dd/1171b5dd25da10f768732a20fb62d2e3ae66e3b42329351f2ce5bf723abb/tree_sitter_ruby-0.23.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f7bcd93972b4ca2803856d4fe0fbd04123ff29c4592bbb9f12a27528bd252341", size = 214427, upload-time = "2024-11-11T04:51:24.854Z" }, + { url = "https://files.pythonhosted.org/packages/60/bc/de76c877a90fd8a62cd60f496d7832efddc1b18a148593d9aa9b4a9ce5e0/tree_sitter_ruby-0.23.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66c65d6c2a629783ca4ab2bab539bd6f271ce6f77cacb62845831e11665b5bd3", size = 210409, upload-time = "2024-11-11T04:51:26.093Z" }, + { url = "https://files.pythonhosted.org/packages/dd/4a/f5bcca350b84cdf75a53e918b8efa06c46ed650d99d3ef22195e9d8020cc/tree_sitter_ruby-0.23.1-cp39-abi3-win_amd64.whl", hash = "sha256:02e2c19ebefe29226c14aa63e11e291d990f5b5c20a99940ab6e7eda44e744e5", size = 179843, upload-time = "2024-11-11T04:51:27.265Z" }, + { url = "https://files.pythonhosted.org/packages/71/5c/a2e068ad4b2c4ba9b774a88b24149168d3bcd94f58b964e49dcabfe5fd24/tree_sitter_ruby-0.23.1-cp39-abi3-win_arm64.whl", hash = "sha256:ed042007e89f2cceeb1cbdd8b0caa68af1e2ce54c7eb2053ace760f90657ac9f", size = 178025, upload-time = "2024-11-11T04:51:29.051Z" }, +] + [[package]] name = "tree-sitter-rust" version = "0.24.2" From 71a5334e47e142904c96487c8c8d1e74ac936ff1 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 13:47:53 +0530 Subject: [PATCH 02/29] A lane can cut its chunks on one symbol kind A Ruby class holds its methods. Cut on every top-level symbol, a class would be one chunk however many methods it has. With unit_kinds only symbols of those kinds are units and the class lines stay leftovers. Lanes that pass none keep the chunks they had. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lane_units.py | 19 ++++++++++++++----- .../unit/test_code_proto_gotemplate_lanes.py | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 44eb30dd75f..a7df0a529c7 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -45,9 +45,13 @@ class SiteRule: allow_repo_wide: bool = True -def _top_level(symbols: list[Symbol]) -> list[Symbol]: - """The symbols no other symbol of the file encloses, in file order.""" - ordered = sorted(symbols, key=lambda s: (s.start_line, -s.end_line)) +def _top_level(symbols: list[Symbol], kinds: frozenset[str] | None = None) -> list[Symbol]: + """The symbols of `kinds` (any kind when None) no other of them encloses, in file + order.""" + ordered = sorted( + (s for s in symbols if kinds is None or s.kind in kinds), + key=lambda s: (s.start_line, -s.end_line), + ) out: list[Symbol] = [] end = 0 for s in ordered: @@ -95,6 +99,7 @@ def span_chunks( comment_leaders: tuple[str, ...] = ("//", "/*", "*"), comment_blocks: tuple[tuple[str, str], ...] = (("/*", "*/"),), header_prefixes: tuple[str, ...] = (), + unit_kinds: frozenset[str] | None = None, ) -> list[Chunk]: """Chunks for a tree-less lane file: one `function` chunk per top-level symbol block (its leading comment run attached, oversize blocks split @@ -104,7 +109,9 @@ def span_chunks( symbol's span (a nested message, an rpc inside a service) ride the enclosing block's chunk and are listed in its `symbol_ids`. A block comment (`comment_blocks`: opener / closer pairs, `{{/* … */}}` for a - template) directly above a unit rides the unit like a line comment.""" + template) directly above a unit rides the unit like a line comment. With + `unit_kinds`, only symbols of those kinds are units (a Ruby method, not the + class around it).""" text = pf.source.decode("utf-8", "replace") src_lines = text.splitlines(keepends=True) covered = [False] * (len(src_lines) + 2) @@ -117,6 +124,7 @@ def span_chunks( leader, comment_leaders, comment_blocks, + unit_kinds, ) header = _header_chunk(pf, src_lines, covered, (*header_prefixes, *comment_leaders)) if header is not None: @@ -135,11 +143,12 @@ def _unit_chunks( leader: str, comment_leaders: tuple[str, ...], comment_blocks: tuple[tuple[str, str], ...], + unit_kinds: frozenset[str] | None = None, ) -> list[Chunk]: """One `function` chunk per top-level symbol block, comment run attached.""" n = len(src_lines) chunks: list[Chunk] = [] - for top in _top_level(pf.symbols): + for top in _top_level(pf.symbols, unit_kinds): start = _comment_run_above(src_lines, top.start_line, comment_leaders, comment_blocks) start = max(1, min(start, top.start_line)) end = min(top.end_line, n) diff --git a/tests/unit/test_code_proto_gotemplate_lanes.py b/tests/unit/test_code_proto_gotemplate_lanes.py index eabdf613a9a..e321c781eb4 100644 --- a/tests/unit/test_code_proto_gotemplate_lanes.py +++ b/tests/unit/test_code_proto_gotemplate_lanes.py @@ -303,6 +303,22 @@ def test_span_chunks_units_header_leftovers_and_oversize() -> None: assert pieces[0].start_line == 16 and pieces[-1].end_line == 32 +def test_span_chunks_cuts_on_the_unit_kinds_only() -> None: + pf = _proto() + # the rpcs are functions inside the service: they become the units, and the service + # block's other lines are a leftover + chunks = span_chunks(pf, 6000, unit_kinds=frozenset({"function"})) + functions = [c for c in chunks if c.kind == "function"] + assert [c.scope.rsplit("::", 1)[-1] for c in functions] == [ + "InstanceService.GetInstance", + "InstanceService.Watch", + ] + assert all(len(c.symbol_ids) == 1 for c in functions) + assert not any(c.scope.endswith(("::Instance", "::InstanceService")) for c in chunks) + # no kinds named: every symbol that no other encloses is a unit, as before + assert span_chunks(pf, 6000) == span_chunks(pf, 6000, unit_kinds=None) + + def test_span_chunks_template_comment_block_rides_the_define() -> None: pf = gt.parse_gotemplate("charts/c/templates/_helpers.tpl", HELPERS) chunks = span_chunks(pf, 6000, **gt.CHUNK_OPTIONS) From f457c00529627f9bc87b2a01cf84c9819ffe9bd2 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 13:47:59 +0530 Subject: [PATCH 03/29] Ruby files are indexed with symbols, calls and inheritance A .rb file was chunked as text, so code.symbol, code.callers and code.impact had nothing to return for it. The lane reads classes, modules, methods, requires, call sites, superclasses and mixins, and the SQL handed to ActiveRecord. Its chunks and edges come from lane_units because the shared chunker and edge walker are in the extractor stamp. lane_units counts lines on LF as the parser does, keeps every Ruby line that holds text in a chunk, and binds a call inside a SQL string from the method around it. Its unit and caller lookups take one sweep each, so a class of many methods stays linear. Signed-off-by: Vanshaj Poonia --- server/code/app/index/ingest_chunks.py | 6 +- server/code/app/index/ingest_edges.py | 14 +- server/code/app/index/ingest_parse.py | 33 +- server/code/app/index/ingest_resolve.py | 2 +- server/code/domain/extract/lane_units.py | 92 ++- .../code/domain/extract/lang_code_islands.py | 4 +- server/code/domain/extract/lang_detect.py | 11 +- server/code/domain/extract/lang_ruby.py | 723 ++++++++++++++++++ server/code/domain/extract/lang_text.py | 5 +- server/code/domain/extract/name_scope.py | 1 + tests/code_lanes/corpus.py | 27 +- tests/fixtures/code_lanes/NOTICE.md | 1 + tests/fixtures/code_lanes/expected.json | 131 ++++ .../fixtures/code_lanes/ruby/ledger/Rakefile | 3 + .../code_lanes/ruby/ledger/db/structure.sql | 6 + .../code_lanes/ruby/ledger/ledger.gemspec | 7 + .../code_lanes/ruby/ledger/lib/ledger.rb | 25 + .../ruby/ledger/lib/ledger/account.rb | 47 ++ .../ruby/ledger/lib/ledger/auditable.rb | 14 + .../ruby/ledger/lib/ledger/entry.rb | 16 + .../ruby/ledger/lib/ledger/report.rb | 31 + .../ruby/ledger/lib/ledger/version.rb | 5 + .../ruby/ledger/lib/tasks/close.rake | 12 + tests/inventory/build.py | 1 + tests/unit/lane_walks.py | 1 + tests/unit/test_code_extractor_stamp.py | 7 +- tests/unit/test_code_kind_prior.py | 2 +- tests/unit/test_code_lanes_manifest.py | 2 +- tests/unit/test_code_lang_ruby.py | 713 +++++++++++++++++ tests/unit/test_lang_text.py | 1 - tests/unit/test_plugin_code_query_contract.py | 14 +- 31 files changed, 1881 insertions(+), 76 deletions(-) create mode 100644 server/code/domain/extract/lang_ruby.py create mode 100644 tests/fixtures/code_lanes/ruby/ledger/Rakefile create mode 100644 tests/fixtures/code_lanes/ruby/ledger/db/structure.sql create mode 100644 tests/fixtures/code_lanes/ruby/ledger/ledger.gemspec create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger/account.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger/auditable.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger/entry.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger/report.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/ledger/version.rb create mode 100644 tests/fixtures/code_lanes/ruby/ledger/lib/tasks/close.rake create mode 100644 tests/unit/test_code_lang_ruby.py diff --git a/server/code/app/index/ingest_chunks.py b/server/code/app/index/ingest_chunks.py index 71b6d0aa212..012cee1f01a 100644 --- a/server/code/app/index/ingest_chunks.py +++ b/server/code/app/index/ingest_chunks.py @@ -204,9 +204,9 @@ def _chunks_for( text = source.decode("utf-8", "replace") return prisma_chunks(pf), {}, list(prisma_units(path, text).facets) - if pf.lang in LANE_UNIT_LANGS: - # No tree — the lane's own symbol spans cut the chunks (one per message / - # service / define / manifest document) + if pf.lang in LANE_UNIT_LANGS and not parse_error: + # The lane's own symbol spans cut the chunks (a message, a define, a Ruby method); + # a file whose parse failed is line windows from server.code.domain.extract.lane_units import span_chunks lane = _lane_module(pf.lang) diff --git a/server/code/app/index/ingest_edges.py b/server/code/app/index/ingest_edges.py index 374d210a5ff..18f40c03ddd 100644 --- a/server/code/app/index/ingest_edges.py +++ b/server/code/app/index/ingest_edges.py @@ -896,18 +896,20 @@ async def _text(path: str) -> str: async def _lane_site_edges(repo: CodeRepo, org: str, ns: str, pf: ParsedFile) -> list[Any]: - """The reference sites of a tree-less lane (an rpc's request type, a template's - `include "x"`) bound by `lane_units.bind_sites` over the lane's gated name table — - same-file unique at 1.0, repository-unique at 0.6, nothing when ambiguous.""" + """A `LANE_UNIT_LANGS` lane's reference sites (an rpc's request type, a Ruby call) + bound by `lane_units.bind_sites` over the lane's gated name table — same-file unique + at 1.0, repository-unique at 0.6, nothing when ambiguous.""" from server.code.domain.extract.lane_units import bind_sites lane = _lane_module(pf.lang) sites = lane.reference_sites(pf) if not sites: return [] - names = sorted({n for _l, n, _k in sites}) - table = gate_name_table(await repo.name_candidates(org, ns, names), pf.lang) - return bind_sites(pf, sites, table, lane.SITE_RULES) + rules = lane.SITE_RULES + # a site that binds only inside its file needs no repository-wide candidates + names = sorted({n for _l, n, k in sites if k in rules and rules[k].allow_repo_wide}) + table = gate_name_table(await repo.name_candidates(org, ns, names), pf.lang) if names else {} + return bind_sites(pf, sites, table, rules) async def _ts_island_edges(repo: CodeRepo, org: str, ns: str, pf: ParsedFile) -> list[Any]: diff --git a/server/code/app/index/ingest_parse.py b/server/code/app/index/ingest_parse.py index cd7afe24eb6..1cd6ae6bbd4 100644 --- a/server/code/app/index/ingest_parse.py +++ b/server/code/app/index/ingest_parse.py @@ -148,7 +148,7 @@ def detect_lang(path: str, source: bytes) -> str: # touch. lang = reference_lang_for_path(path) if not lang: - # A text file no parser claims is still chunked and searchable (Kotlin, Ruby, + # A text file no parser claims is still chunked and searchable (Kotlin, PHP, # `.txt`, `.conf`, …); binaries and oversized files stay out. Outside every # extractor stamp. from server.code.domain.extract.lang_text import text_lang_for_path @@ -308,6 +308,14 @@ def _parse_java(path: str, source: bytes) -> ParsedFile: return pf +def _parse_ruby(path: str, source: bytes) -> ParsedFile: + from server.code.domain.extract.lang_ruby import parse_ruby, ruby_sql_units + + pf = parse_ruby(path, source) + _join_island_symbols(pf, ruby_sql_units(pf).symbols) + return pf + + def _parse_thrift(path: str, source: bytes) -> ParsedFile: from server.code.domain.extract.lang_thrift import parse_thrift @@ -363,7 +371,7 @@ def _join_island_symbols(pf: ParsedFile, symbols: list[Any]) -> None: pf.symbols.extend(x for x in symbols if (x.qualified_name, x.id) not in known) -CODE_ISLAND_LANGS: frozenset[str] = frozenset({"go", "java"}) +CODE_ISLAND_LANGS: frozenset[str] = frozenset({"go", "java", "ruby"}) def _code_sql_units(pf: ParsedFile) -> Any: @@ -371,6 +379,10 @@ def _code_sql_units(pf: ParsedFile) -> Any: from server.code.domain.extract.lang_go import go_sql_units return go_sql_units(pf) + if pf.lang == "ruby": + from server.code.domain.extract.lang_ruby import ruby_sql_units + + return ruby_sql_units(pf) from server.code.domain.extract.lang_java import java_sql_units return java_sql_units(pf) @@ -455,6 +467,7 @@ def _parse_doc(path: str, source: bytes) -> ParsedFile: "prisma": _parse_prisma, "go": _parse_go, "java": _parse_java, + "ruby": _parse_ruby, "vue": _parse_vue, "svelte": _parse_svelte, "astro": _parse_astro, @@ -477,17 +490,17 @@ def _parse_doc(path: str, source: bytes) -> ParsedFile: {"tla", "tla_config", "flatbuffers", "cmake", "doc"} ) -# The lanes without a tree-sitter grammar — chunks from their symbol spans, edges from -# their reference sites (`lane_units`) +# The lanes cut on their symbol spans and bound by their reference sites (`lane_units`): +# those without a grammar, and Ruby, which stays out of the stamped chunker and edge walker LANE_UNIT_LANGS: frozenset[str] = frozenset( - {"proto", "thrift", "gotemplate", "hcl", "k8s", "jsonnet", "lua", "graphql"} + {"proto", "thrift", "gotemplate", "hcl", "k8s", "jsonnet", "lua", "graphql", "ruby"} ) def _lane_module(lang: str) -> Any: - """The lane module of a tree-less lane: `parse_*`, `reference_sites`, - `SITE_RULES`, `CHUNK_OPTIONS`, and `wanted_paths` / `resolve_imports` for a - lane with imports.""" + """The lane module of a `LANE_UNIT_LANGS` lane: `parse_*`, `reference_sites`, + `SITE_RULES`, `CHUNK_OPTIONS`, `wanted_paths` / `resolve_imports` for a lane with + imports, and `facets` for one with facet rows.""" from server.code.domain.extract import lang_gotemplate, lang_hcl, lang_k8s, lang_proto if lang == "hcl": @@ -510,6 +523,10 @@ def _lane_module(lang: str) -> Any: from server.code.domain.extract import lang_graphql return lang_graphql + if lang == "ruby": + from server.code.domain.extract import lang_ruby + + return lang_ruby return lang_proto if lang == "proto" else lang_gotemplate diff --git a/server/code/app/index/ingest_resolve.py b/server/code/app/index/ingest_resolve.py index 35a55186278..32a9c2d68bd 100644 --- a/server/code/app/index/ingest_resolve.py +++ b/server/code/app/index/ingest_resolve.py @@ -182,7 +182,7 @@ async def _resolve_lane_includes(repo: CodeRepo, org: str, ns: str, pf: ParsedFi """A TypeScript import specifier or a Rust `use` path names a repository file only through a probing ladder; the namespace's live paths are the oracle, read once per file. A specifier nothing indexed satisfies (a package, `std`) is not an edge.""" - if pf.lang in CODE_ISLAND_LANGS: + if pf.lang in CODE_ISLAND_LANGS and pf.lang not in LANE_UNIT_LANGS: await _resolve_code_lane_imports(repo, org, ns, pf) return if pf.lang == "config" and not pf.includes: diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index a7df0a529c7..000a21336c1 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -1,4 +1,4 @@ -"""What a lane without a tree-sitter grammar shares. +"""What the lanes cut on their own symbol spans share. The protobuf and Go-template lanes read their files with hand-written scanners: `ParsedFile.tree` stays None, so `chunker.chunk_file` would fall @@ -17,16 +17,21 @@ when ambiguous or unknown. Outside the extractor stamp with the lane modules: neither `chunker.py` nor -`edges_treesitter.py` changes for a new lane. +`edges_treesitter.py` changes for a new lane. That is why the Ruby lane, which +has a grammar, takes its chunks and edges from here too. """ from __future__ import annotations import functools +import heapq +import io +from bisect import bisect_left, bisect_right from dataclasses import dataclass from server.code.domain.extract.chunker import Chunk, _assign_ordinals, _split_oversized from server.code.domain.extract.edges_treesitter import REPO_WIDE_CONFIDENCE, Edge +from server.code.domain.extract.lang_sql_model import STATEMENT_KIND from server.code.domain.extract.treesitter import ParsedFile, Symbol _MIN_CHUNK_CHARS = 40 # the chunker's floor for a body / leftover chunk @@ -37,12 +42,14 @@ @dataclass(frozen=True) class SiteRule: - """How one kind of site binds: the edge it records, the symbol kinds it - may land on, and whether a repository-unique definition counts.""" + """How one kind of site binds: the edge it records, the symbol kinds it may land on, + whether a repository-unique definition counts, and whether the caller's own definition + of the name makes a same-file one ambiguous.""" edge_kind: str target_kinds: frozenset[str] allow_repo_wide: bool = True + caller_counts: bool = False def _top_level(symbols: list[Symbol], kinds: frozenset[str] | None = None) -> list[Symbol]: @@ -101,7 +108,7 @@ def span_chunks( header_prefixes: tuple[str, ...] = (), unit_kinds: frozenset[str] | None = None, ) -> list[Chunk]: - """Chunks for a tree-less lane file: one `function` chunk per top-level + """Chunks for a `LANE_UNIT_LANGS` file: one `function` chunk per top-level symbol block (its leading comment run attached, oversize blocks split on line boundaries), a `file_header` chunk for the leading run of header lines (`header_prefixes`, comments, blanks), and every leftover @@ -111,9 +118,11 @@ def span_chunks( comment (`comment_blocks`: opener / closer pairs, `{{/* … */}}` for a template) directly above a unit rides the unit like a line comment. With `unit_kinds`, only symbols of those kinds are units (a Ruby method, not the - class around it).""" + class around it), and every other line with text is in a chunk: the lines + between two units are one `other` chunk however short, blank lines inside + it included.""" text = pf.source.decode("utf-8", "replace") - src_lines = text.splitlines(keepends=True) + src_lines = list(io.StringIO(text, newline="\n")) # Parser coordinates count LF. covered = [False] * (len(src_lines) + 2) leader = comment_leaders[0] if comment_leaders else "//" chunks = _unit_chunks( @@ -129,7 +138,8 @@ class around it).""" header = _header_chunk(pf, src_lines, covered, (*header_prefixes, *comment_leaders)) if header is not None: chunks.append(header) - chunks.extend(_leftover_chunks(pf, src_lines, covered, max_chars, leader)) + keep_all = unit_kinds is not None + chunks.extend(_leftover_chunks(pf, src_lines, covered, keep_all, max_chars, leader)) chunks.sort(key=lambda c: (c.start_line, c.end_line)) _assign_ordinals(chunks) return chunks @@ -143,22 +153,22 @@ def _unit_chunks( leader: str, comment_leaders: tuple[str, ...], comment_blocks: tuple[tuple[str, str], ...], - unit_kinds: frozenset[str] | None = None, + unit_kinds: frozenset[str] | None, ) -> list[Chunk]: """One `function` chunk per top-level symbol block, comment run attached.""" n = len(src_lines) chunks: list[Chunk] = [] + by_start = sorted(pf.symbols, key=lambda s: s.start_line) + starts = [s.start_line for s in by_start] for top in _top_level(pf.symbols, unit_kinds): start = _comment_run_above(src_lines, top.start_line, comment_leaders, comment_blocks) start = max(1, min(start, top.start_line)) end = min(top.end_line, n) if end < start: continue - inner = [ - s.id - for s in pf.symbols - if s is not top and top.start_line <= s.start_line and s.end_line <= top.end_line - ] + # units do not overlap, so each symbol is read for one unit at most + held = by_start[bisect_left(starts, top.start_line) : bisect_right(starts, top.end_line)] + inner = [s.id for s in held if s is not top and s.end_line <= top.end_line] ids = [top.id, *dict.fromkeys(inner)] content = "".join(src_lines[start - 1 : end]) for i in range(start, end + 1): @@ -219,15 +229,17 @@ def _leftover_chunks( pf: ParsedFile, src_lines: list[str], covered: list[bool], + keep_all: bool, max_chars: int, leader: str, ) -> list[Chunk]: - """Every uncovered run of non-blank lines as an `other` chunk.""" + """Every uncovered run of non-blank lines as an `other` chunk of at least the floor; + with `keep_all`, every uncovered run with text, blank lines inside it included.""" n = len(src_lines) runs: list[tuple[int, int]] = [] run_start: int | None = None for i in range(1, n + 1): - uncovered = not covered[i] and src_lines[i - 1].strip() != "" + uncovered = not covered[i] and (keep_all or src_lines[i - 1].strip() != "") if uncovered and run_start is None: run_start = i boundary = (not uncovered) or i == n @@ -236,8 +248,12 @@ def _leftover_chunks( run_start = None chunks: list[Chunk] = [] for a, b in runs: + while a <= b and not src_lines[a - 1].strip(): + a += 1 + while b >= a and not src_lines[b - 1].strip(): + b -= 1 content = "".join(src_lines[a - 1 : b]) - if len(content.strip()) < _MIN_CHUNK_CHARS: + if a > b or (len(content.strip()) < _MIN_CHUNK_CHARS and not keep_all): continue pieces = ( [(content, a, b)] @@ -258,15 +274,23 @@ def _leftover_chunks( return chunks -def enclosing_symbol(pf: ParsedFile, line: int) -> Symbol | None: - """The innermost symbol of any kind whose span holds `line`.""" - best: Symbol | None = None - for s in pf.symbols: - if s.start_line <= line <= s.end_line and ( - best is None or (s.end_line - s.start_line) < (best.end_line - best.start_line) - ): - best = s - return best +def _enclosing_by_line(pf: ParsedFile, lines: set[int]) -> dict[int, Symbol]: + """The innermost symbol around each line (the first of two alike spans), in one sweep. + An embedded SQL statement is never one: a call written in it is its method's.""" + starts = sorted((s.start_line, i) for i, s in enumerate(pf.symbols) if s.kind != STATEMENT_KIND) + open_spans: list[tuple[int, int]] = [] # (span length, index in pf.symbols) + out: dict[int, Symbol] = {} + k = 0 + for line in sorted(lines): + while k < len(starts) and starts[k][0] <= line: + s = pf.symbols[starts[k][1]] + heapq.heappush(open_spans, (s.end_line - s.start_line, starts[k][1])) + k += 1 + while open_spans and pf.symbols[open_spans[0][1]].end_line < line: + heapq.heappop(open_spans) + if open_spans: + out[line] = pf.symbols[open_spans[0][1]] + return out def bind_sites( @@ -276,7 +300,8 @@ def bind_sites( rules: dict[str, SiteRule], ) -> list[Edge]: """Edges for the sites under `rules`: from the innermost enclosing - symbol to the same-file unique definition of a target kind at 1.0, + symbol to the same-file unique definition of a target kind at 1.0 (one + qualified name, which a file may write twice, as Ruby reopens a class), else the repository-unique candidate (`name_table`: bare name → [(symbol_id, qualified_name, kind)], already gated to the lane's language class) at `REPO_WIDE_CONFIDENCE` when the rule allows it, @@ -288,19 +313,19 @@ def bind_sites( local.setdefault(s.name, []).append(s) edges: list[Edge] = [] seen: set[tuple[str, str, str, int]] = set() + callers = _enclosing_by_line(pf, {line for line, _name, _kind in sites}) for line, name, site_kind in sites: rule = rules.get(site_kind) - if rule is None: - continue - src = enclosing_symbol(pf, line) - if src is None: + src = callers.get(line) + if rule is None or src is None: continue mine = [ s for s in local.get(name, []) - if s.kind in rule.target_kinds and s.qualified_name != src.qualified_name + if s.kind in rule.target_kinds + and (rule.caller_counts or s.qualified_name != src.qualified_name) ] - if len(mine) == 1: + if len({s.qualified_name for s in mine}) == 1: to_id, to_qn, conf = mine[0].id, mine[0].qualified_name, 1.0 elif mine: continue # several same-file definitions: ambiguous @@ -358,6 +383,5 @@ def ancestor_dirs(from_path: str) -> tuple[str, ...]: "ancestor_candidates", "ancestor_dirs", "bind_sites", - "enclosing_symbol", "span_chunks", ] diff --git a/server/code/domain/extract/lang_code_islands.py b/server/code/domain/extract/lang_code_islands.py index 920952ca5a1..6e145d15033 100644 --- a/server/code/domain/extract/lang_code_islands.py +++ b/server/code/domain/extract/lang_code_islands.py @@ -2,8 +2,8 @@ `lang_py_islands` lifts the SQL a Python file runs; this module is the same contract with the grammar as data, so Go (`db.QueryContext(ctx, "SELECT …")`, `sqlx.Get`, gorm -`Raw`) and Java (`prepareStatement("…")`, `jdbcTemplate.query("…")`, `@Query("…")`) read -through one walker: +`Raw`), Java (`prepareStatement("…")`, `jdbcTemplate.query("…")`, `@Query("…")`) and Ruby +(`connection.execute("…")`, `find_by_sql`) read through one walker: * an `IslandGrammar` names the call node, the string node types, the client method table (method → dialect), the object hints (`spark` → diff --git a/server/code/domain/extract/lang_detect.py b/server/code/domain/extract/lang_detect.py index f08c2edd996..2acaa9e98fd 100644 --- a/server/code/domain/extract/lang_detect.py +++ b/server/code/domain/extract/lang_detect.py @@ -257,6 +257,9 @@ def detect_shell(path: str, source: bytes) -> str: ".rs": "rust", ".go": "go", ".java": "java", + ".rb": "ruby", + ".rake": "ruby", + ".gemspec": "ruby", ".prisma": "prisma", ".vue": "vue", # Parsed as its script's typescript / javascript ".svelte": "svelte", @@ -300,16 +303,20 @@ def detect_shell(path: str, source: bytes) -> str: _CONFIG_BASENAMES: frozenset[str] = frozenset({"go.mod", "go.work"}) +_RUBY_BASENAMES: frozenset[str] = frozenset({"gemfile", "rakefile"}) def detect_by_extension(path: str) -> str: """The language of a path by its extension for the languages the - lane parsers read (TypeScript / JavaScript, Rust, Prisma, Go, Java, + lane parsers read (TypeScript / JavaScript, Rust, Prisma, Go, Java, Ruby, protobuf, Go templates) and the two chunk-only ones (CSS, MDX as a doc); '' when none applies.""" lower = path.lower() - if lower.rsplit("/", 1)[-1] in _CONFIG_BASENAMES: + base = lower.rsplit("/", 1)[-1] + if base in _CONFIG_BASENAMES: return "config" # Go.mod is read for the module path + if base in _RUBY_BASENAMES: + return "ruby" if lower.endswith(".component.html"): return "angular_template" # A component's external template dot = lower.rfind(".") diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py new file mode 100644 index 00000000000..9f8ae02b1f1 --- /dev/null +++ b/server/code/domain/extract/lang_ruby.py @@ -0,0 +1,723 @@ +"""Ruby: classes, modules, methods, mixins, `require`, calls and the SQL a file runs. + +Chunks and edges come from `lane_units`, not the stamped chunker and edge walker, so the +lane moves no stamp: a namespace gains its Ruby rows by a backfill over its Ruby files. +""" + +from __future__ import annotations + +import dataclasses +import functools +import posixpath +import re +import textwrap +from collections import deque +from typing import Any + +from server.code.domain.extract import bounded_parse +from server.code.domain.extract.lane_units import Site, SiteRule, ancestor_dirs +from server.code.domain.extract.lang_code_islands import CodeSqlUnits, IslandGrammar, code_sql_units +from server.code.domain.extract.lang_python import module_scope +from server.code.domain.extract.lang_shell_islands import PLACEHOLDER +from server.code.domain.extract.lang_sql_model import Facet +from server.code.domain.extract.treesitter import ParsedFile, Symbol, node_text + +LANG_RUBY = "ruby" + +KIND_CLASS = "class" +KIND_MODULE = "module" +KIND_FUNCTION = "function" +SITE_CALL = "call" +SITE_BARE = "bare" +SITE_NEW = "new" +SITE_HERITAGE = "heritage" +# The receiver's type is unknown, so a method the caller's class defines under the same +# name is as likely a target as another class's +SITE_RULES: dict[str, SiteRule] = { + SITE_CALL: SiteRule("calls", frozenset({KIND_FUNCTION}), caller_counts=True), + # a bare word may be a local variable, and a common name called on self may be the + # language's own method: either binds only inside its own file + SITE_BARE: SiteRule( + "calls", frozenset({KIND_FUNCTION}), allow_repo_wide=False, caller_counts=True + ), + SITE_NEW: SiteRule("calls", frozenset({KIND_CLASS})), + SITE_HERITAGE: SiteRule("inherits", frozenset({KIND_CLASS, KIND_MODULE})), +} + +# how `lane_units.span_chunks` cuts a Ruby file: one chunk per method +CHUNK_OPTIONS: dict[str, Any] = { + "comment_leaders": ("#",), + "comment_blocks": (("=begin", "=end"),), + "header_prefixes": ("require", "load "), + "unit_kinds": frozenset({KIND_FUNCTION}), +} + +RUBY_CLIENT_METHODS: dict[str, str] = { + # ActiveRecord: finders and the connection + "find_by_sql": "", + "count_by_sql": "", + "execute": "", + "exec_query": "", + "exec_update": "", + "exec_insert": "", + "exec_delete": "", + "select_all": "", + "select_one": "", + "select_rows": "", + "select_value": "", + "select_values": "", + # ActiveRecord: relations that take a SQL fragment + "where": "", + "having": "", + "joins": "", + "order": "", + "from": "", + # pg, mysql2 and sqlite3; `fetch` and `run` are left out, as a Hash and a shell use them + "exec": "", + "exec_params": "", + "query": "", +} + +_MAX_DOC = 2000 +_DEF_NODES = frozenset({"class", "module", "method", "singleton_method"}) +_PARAMETER_NODES = frozenset({"method_parameters", "block_parameters", "lambda_parameters"}) +_PATTERN_NODES = frozenset({"in_clause", "match_pattern", "test_pattern"}) +_MIXINS = frozenset({"include", "extend", "prepend"}) +_REQUIRES = frozenset({"require", "require_relative"}) +_STRING_NODES = frozenset({"string", "heredoc_beginning"}) +_ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'"} +_REQUIRE_LINE_RE = re.compile(rb"(?m)^[ \t]*require[ \t]+[\"']([^\"'\n]+)[\"']") +# the parents under which a lone identifier reads a value: a local variable or a method +_VALUE_PARENTS = frozenset( + { + "program", + "body_statement", + "block_body", + "parenthesized_statements", + "begin", + "then", + "else", + "elsif", + "ensure", + "argument_list", + "call", + "binary", + "unary", + "conditional", + "if", + "unless", + "while", + "until", + "if_modifier", + "unless_modifier", + "while_modifier", + "until_modifier", + "rescue_modifier", + "array", + "pair", + "interpolation", + "assignment", + "operator_assignment", + "element_reference", + "range", + "case", + "case_match", + "pattern", + "match_pattern", + "test_pattern", + "do", + "in", + "right_assignment_list", + "splat_argument", + "optional_parameter", + "keyword_parameter", + "hash_splat_argument", + "block_argument", + "method", + "singleton_method", + } +) +# Methods of the language and of the libraries every Ruby program uses, and the +# declarations of Rails and RSpec: none of them is a definition of the repository +_NOISE: frozenset[str] = frozenset( + ( + "puts print p pp printf sprintf format raise fail loop lambda proc catch throw " + "block_given? binding caller exit abort at_exit sleep rand srand gets require " + "require_relative load autoload attr_reader attr_writer attr_accessor private public " + "protected module_function private_class_method public_class_method private_constant " + "alias_method define_method include extend prepend send public_send __send__ method " + "methods class object_id hash eql? equal? freeze frozen? dup clone tap then " + "yield_self nil? is_a? kind_of? instance_of? respond_to? instance_variable_get " + "instance_variable_set instance_variables instance_eval class_eval instance_exec " + "inspect to_s to_i to_f to_a to_h to_r to_c to_sym to_str to_proc to_json to_yaml " + "each each_with_index each_with_object each_slice each_cons each_pair each_key " + "each_value map flat_map collect select filter filter_map reject find detect find_all " + "find_index reduce inject sum count min max min_by max_by minmax sort sort_by " + "group_by partition zip take take_while drop drop_while first last push pop shift " + "unshift append insert concat compact flatten uniq reverse rotate sample shuffle " + "include? member? index rindex join split strip lstrip rstrip chomp chop chars bytes " + "lines upcase downcase capitalize swapcase gsub sub gsub! sub! tr delete delete_if " + "delete_prefix delete_suffix squeeze match match? scan start_with? end_with? ljust " + "rjust center length size empty? any? all? none? one? key? has_key? value? fetch dig " + "merge merge! keys values slice zero? positive? negative? abs round floor " + "ceil succ pred times upto downto step between? clamp where find_by find_by! " + "find_each find_in_batches all create create! update update! update_all " + "update_attribute update_columns destroy destroy! destroy_all save save! delete_all " + "pluck ids order includes preload eager_load joins left_joins limit offset group " + "having distinct exists? reload touch increment decrement build transaction lock " + "present? blank? presence try validates validate belongs_to has_many has_one scope " + "delegate attribute enum default_scope render redirect_to params head respond_to " + "logger env describe context it specify let let! subject expect allow before after " + "shared_examples include_examples it_behaves_like assert refute eq be" + ).split() +) +_NOISE_PREFIXES = ("before_", "after_", "around_", "validates_", "skip_", "assert_", "refute_") + + +@functools.lru_cache(maxsize=1) +def _parser() -> Any: + import tree_sitter + import tree_sitter_ruby + + return tree_sitter.Parser(tree_sitter.Language(tree_sitter_ruby.language())) + + +def ruby_scope(path: str) -> str: + """The dotted scope a file's definitions are qualified by: `lib/a/b.rb` → `lib.a.b`, + `Rakefile` → `root.Rakefile`. Always dotted, because the name gate classes a definition + by the shape of its scope and reads one without a `.` as native.""" + scope = module_scope(path) + return scope if "." in scope else f"root.{scope}" + + +def _squash(text: str) -> str: + return " ".join(text.split()) + + +def _const_parts(node: Any, source: bytes) -> tuple[list[str], bool]: + """(segments, rooted) of the constant `A::B` / `::A` that `node` names; ([], False) for + any other expression.""" + parts: list[str] = [] + rooted = False + cur = node + while cur is not None: + if cur.type == "constant": + parts.append(node_text(cur, source)) + break + name = cur.child_by_field_name("name") + if cur.type != "scope_resolution" or name is None or name.type != "constant": + return [], False + parts.append(node_text(name, source)) + cur = cur.child_by_field_name("scope") + rooted = cur is None + parts.reverse() + return parts, rooted + + +def _doc_before(siblings: list[Any], i: int, source: bytes) -> str: + """The `#` comment lines directly above `siblings[i]`, read from the sibling list (a + node's own `prev_sibling` walks its parent's children from the first).""" + lines: list[str] = [] + expect = siblings[i].start_point[0] - 1 + j = i - 1 + while j >= 0 and siblings[j].type == "comment" and siblings[j].end_point[0] == expect: + if j > 0 and siblings[j - 1].end_point[0] == siblings[j].start_point[0]: + break # a comment after code on its line + text = node_text(siblings[j], source).strip() + body = text.lstrip("#").strip() + if not text.startswith("#") or body.startswith(("rubocop:", "frozen_string_literal:")): + break + lines.append(body) + expect = siblings[j].start_point[0] - 1 + j -= 1 + return "\n".join(reversed(lines))[:_MAX_DOC].strip() + + +def _params(node: Any, source: bytes) -> str: + p = node.child_by_field_name("parameters") + return _squash(node_text(p, source)) if p is not None else "()" + + +def _string_literal(call: Any, source: bytes) -> str: + """The text of a call's first argument when it is a plain string, '' otherwise (a + string with an interpolation, a call or a constant).""" + args = call.child_by_field_name("arguments") + first = args.named_children[0] if args is not None and args.named_children else None + if first is None or first.type != "string": + return "" + if any(c.type != "string_content" for c in first.named_children): + return "" + return "".join(node_text(c, source) for c in first.named_children) # `%q(x)` too + + +class _Reader: + """The symbols and requires of one file, read from its tree without recursion.""" + + def __init__(self, pf: ParsedFile) -> None: + self.pf, self.source, self.scope = pf, pf.source, ruby_scope(pf.path) + self.requires: list[str] = [] + + def read(self, root: Any) -> None: + # (node, owner names, singleton, doc comment, the siblings before a class body) + stack: list[tuple[Any, tuple[str, ...], bool, str, tuple[Any, ...]]] = [ + (root, (), False, "", ()) + ] + while stack: + node, names, single, doc, lead = stack.pop() + nxt = self._visit(node, names, single, doc) + if nxt is None: + continue + kids = node.named_children + siblings = [*lead, *kids] if lead else kids + for i in range(len(kids) - 1, -1, -1): + kid = kids[i] + kid_doc = "" + if kid.type in _DEF_NODES or kid.type == "call": + kid_doc = _doc_before(siblings, i + len(lead), self.source) + if not kid_doc and node.type in ("call", "argument_list"): + kid_doc = doc # `private def x` takes the comment above the call + # the tree hangs a comment before a body's first statement on the class + kid_lead = tuple(kids[:i]) if kid.type == "body_statement" else () + stack.append((kid, nxt[0], nxt[1], kid_doc, kid_lead)) + + def _visit( + self, node: Any, names: tuple[str, ...], single: bool, doc: str + ) -> tuple[tuple[str, ...], bool] | None: + """The owner names and singleton flag the node's children read under; None skips + them.""" + t = node.type + if t in ("class", "module"): + return self._namespace(node, names, single, doc) + if t == "singleton_class": + # `class << Const` reads as `def Const.x`; an object's singleton class names nothing + value = node.child_by_field_name("value") + if value is not None and value.type == "self": + return names, True + owner = _const_parts(value, self.source)[0] if value is not None else [] + return (tuple(owner), True) if owner else None + if t == "method": + self._method(node, names, single, doc) + elif t == "singleton_method": + self._singleton_method(node, names, doc) + elif t == "call": + self._require(node) + return names, single + + def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: + self.pf.symbols.append( + Symbol( + qualified_name=qn, + name=name, + kind=kind, + signature=sig, + path=self.pf.path, + start_line=node.start_point[0] + 1, + end_line=node.end_point[0] + 1, + doc_comment=doc, + ) + ) + + def _namespace( + self, node: Any, names: tuple[str, ...], single: bool, doc: str + ) -> tuple[tuple[str, ...], bool]: + name_node = node.child_by_field_name("name") + parts, rooted = ( + _const_parts(name_node, self.source) if name_node is not None else ([], False) + ) + if not parts: + return names, single + inner = (*parts,) if rooted else (*names, *parts) + sup = node.child_by_field_name("superclass") + sig = f"{node.type} {node_text(name_node, self.source)}" + if sup is not None and sup.named_children: + sig += f" < {_squash(node_text(sup.named_children[0], self.source))}" + kind = KIND_CLASS if node.type == "class" else KIND_MODULE + self._add(f"{self.scope}::{'::'.join(inner)}", parts[-1], kind, sig, node, doc) + return inner, False + + def _method_qn(self, owner: tuple[str, ...], single: bool, name: str) -> str: + if not owner: + return f"{self.scope}::self.{name}" if single else f"{self.scope}::{name}" + return f"{self.scope}::{'::'.join(owner)}{'.' if single else '#'}{name}" + + def _method(self, node: Any, names: tuple[str, ...], single: bool, doc: str) -> None: + name_node = node.child_by_field_name("name") + if name_node is None: + return + name = node_text(name_node, self.source) + qn = self._method_qn(names, single, name) + self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) + + def _singleton_method(self, node: Any, names: tuple[str, ...], doc: str) -> None: + name_node = node.child_by_field_name("name") + target = node.child_by_field_name("object") + if name_node is None or target is None: + return + owner = names if target.type == "self" else tuple(_const_parts(target, self.source)[0]) + if target.type != "self" and not owner: + return + name = node_text(name_node, self.source) + qn = self._method_qn(owner, True, name) + self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) + + def _require(self, call: Any) -> None: + method = call.child_by_field_name("method") + if call.child_by_field_name("receiver") is not None or method is None: + return + name = node_text(method, self.source) + if name not in _REQUIRES: + return + spec = _string_literal(call, self.source) + if not spec: + return + if name == "require_relative" and not spec.startswith("."): + spec = f"./{spec}" + self.requires.append(spec) + + +def parse_ruby(path: str, source: bytes) -> ParsedFile: + """Every class, module and method of one Ruby file, and its `require` specifiers (raw, + for the resolver; `require_relative "x"` reads `./x`). The tree stays on the result for + the sites and the SQL islands.""" + tree = bounded_parse.parse(_parser(), source) + pf = ParsedFile(path=path, lang=LANG_RUBY, tree=tree, source=source) + reader = _Reader(pf) + reader.read(tree.root_node) + pf.includes = list(dict.fromkeys(reader.requires)) + return pf + + +class _Sites: + """The reference sites of one file, read from its tree without recursion. A bare word + is kept only when the method (or class body) holds no local variable of that name.""" + + def __init__(self, pf: ParsedFile) -> None: + self.source = pf.source + self.found: list[tuple[int, str, str, int]] = [] # line, name, kind, scope node id + self.locals: dict[int, set[str]] = {} + self.skip: set[int] = set() # nodes that are a definition, not a read + + def run(self, root: Any) -> list[Site]: + stack: list[tuple[Any, str, int, str]] = [(root, "", root.id, "")] + while stack: + node, parent_type, scope, owner = stack.pop() + scope, owner = self._visit(node, parent_type, scope, owner) + for child in reversed(node.named_children): + stack.append((child, node.type, scope, owner)) + return [ + (line, name, kind) + for line, name, kind, scope in self.found + if kind != SITE_BARE or name not in self.locals.get(scope, ()) + ] + + def _add(self, line: int, name: str, kind: str, scope: int) -> None: + self.found.append((line, name, kind, scope)) + + def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[int, str]: + t = node.type + if t == "call": + self._call(node, scope, owner) + elif t == "identifier": + self._bare(node, parent_type, scope, owner) + elif t in ("assignment", "operator_assignment"): + self._assignment(node, scope) + elif t in _PARAMETER_NODES: + self._parameters(node, scope) + elif t == "exception_variable": + self._collect(node, scope) + elif t in _PATTERN_NODES: + self._collect(node.child_by_field_name("pattern"), scope) + elif t == "for": + self._collect(node.child_by_field_name("pattern"), scope) + elif t in ("class", "module"): + self._namespace(node, scope) + name = node.child_by_field_name("name") + parts = _const_parts(name, self.source)[0] if name is not None else [] + return node.id, parts[-1] if t == "class" and parts else "" + elif t in ("method", "singleton_method"): + # an endless method's body is read; its name and the object it is defined on are not + for part in (node.child_by_field_name("name"), node.child_by_field_name("object")): + if part is not None: + self.skip.add(part.id) + return node.id, owner + return scope, owner + + def _collect(self, node: Any, scope: int) -> None: + """Every identifier under `node` is a local variable of the scope, and so is the key + of a pattern's `key:` with no pattern of its own.""" + if node is None: + return + names = self.locals.setdefault(scope, set()) + stack = [node] + while stack: + n = stack.pop() + key = n.child_by_field_name("key") if n.type == "keyword_pattern" else None + if n.type == "identifier": + names.add(node_text(n, self.source)) + elif key is not None and n.child_by_field_name("value") is None: + names.add(node_text(key, self.source).rstrip(":")) + stack.extend(n.named_children) + + def _parameters(self, node: Any, scope: int) -> None: + """The names a parameter list binds are local variables; a default value is read.""" + names = self.locals.setdefault(scope, set()) + stack = [node] + while stack: + for kid in stack.pop().named_children: + if kid.type == "destructured_parameter": + stack.append(kid) + continue + name = kid if kid.type == "identifier" else kid.child_by_field_name("name") + if name is not None and name.type == "identifier": + names.add(node_text(name, self.source)) + self.skip.add(name.id) + + def _assignment(self, node: Any, scope: int) -> None: + left = node.child_by_field_name("left") + if left is None: + return + self.skip.add(left.id) # `a.b = 1` writes `b=`, `a = 1` defines a + if left.type in ("identifier", "left_assignment_list", "rest_assignment"): + self._collect(left, scope) + + def _namespace(self, node: Any, scope: int) -> None: + """`class X < Y` is a heritage site on its own line.""" + sup = node.child_by_field_name("superclass") + if sup is None or not sup.named_children: + return + parts = _const_parts(sup.named_children[0], self.source)[0] + if parts: + self._add(node.start_point[0] + 1, parts[-1], SITE_HERITAGE, scope) + + def _bare(self, node: Any, parent_type: str, scope: int, owner: str) -> None: + if parent_type not in _VALUE_PARENTS or node.id in self.skip: + return + name = node_text(node, self.source) + line = node.start_point[0] + 1 + if name == "new": + if owner: + self._add(line, owner, SITE_NEW, scope) + else: + self._add(line, name, SITE_BARE, scope) + + def _call(self, node: Any, scope: int, owner: str) -> None: + method = node.child_by_field_name("method") + if method is None or method.type != "identifier": + return + self.skip.add(method.id) + if node.id in self.skip: + return # the target of an assignment + name = node_text(method, self.source) + line = method.start_point[0] + 1 + receiver = node.child_by_field_name("receiver") + if receiver is None and name in _MIXINS: + self._mixin(node, scope) + elif name == "new": + self._construction(receiver, line, scope, owner) + elif receiver is not None and receiver.type in ("constant", "scope_resolution"): + if _const_parts(receiver, self.source)[0] and not _noisy(name): + self._add(line, name, SITE_CALL, scope) + elif not _noisy(name): + self._add(line, name, SITE_CALL, scope) + elif receiver is None or receiver.type == "self": + self._add(line, name, SITE_BARE, scope) # the class's own `save` or the language's + + def _construction(self, receiver: Any, line: int, scope: int, owner: str) -> None: + """`Const.new` constructs that constant; `new` and `self.new` the enclosing class.""" + if receiver is None or receiver.type == "self": + target = owner + else: + parts = _const_parts(receiver, self.source)[0] + target = parts[-1] if parts else "" + if target: + self._add(line, target, SITE_NEW, scope) + + def _mixin(self, call: Any, scope: int) -> None: + args = call.child_by_field_name("arguments") + for arg in args.named_children if args is not None else []: + parts = _const_parts(arg, self.source)[0] + if parts: + self._add(call.start_point[0] + 1, parts[-1], SITE_HERITAGE, scope) + + +def _noisy(name: str) -> bool: + return name in _NOISE or name.startswith(_NOISE_PREFIXES) + + +def reference_sites(pf: ParsedFile) -> list[Site]: + """(line, name, kind) of every `heritage`, `new`, `call` and `bare` site, in source + order. A local variable names nothing. A method of the language or a framework + (`puts`, `save`) is a site only when called on `self` or nothing, and binds only to + its own file's.""" + if pf.tree is None: + return [] + return _Sites(pf).run(pf.tree.root_node) + + +def _candidates(from_path: str, spec: str) -> list[str]: + """The repository paths a `require` specifier may name: beside the file for a relative + one, otherwise under the file's directory, each ancestor and the root, and their + `lib/`, nearest first.""" + spec = spec.removesuffix(".rb") + if not spec or spec.startswith("/"): + return [] + if spec.startswith("."): + rel = posixpath.normpath(posixpath.join(posixpath.dirname(from_path), spec)) + return [] if rel.startswith("..") else [f"{rel}.rb"] + if ".." in spec.split("/"): + return [] + out: dict[str, None] = {} + for base in (*ancestor_dirs(from_path), ""): + for root in (base, f"{base}/lib" if base else "lib"): + out[f"{root}/{spec}.rb" if root else f"{spec}.rb"] = None + return list(out) + + +def wanted_paths(from_path: str, specs: list[str]) -> list[str]: + """Every repository path the requires may name, for one membership read.""" + out: dict[str, None] = {} + for spec in specs: + out.update(dict.fromkeys(_candidates(from_path, spec))) + return list(out) + + +def resolve_imports(from_path: str, specs: list[str], present: set[str]) -> list[str]: + """One indexed file per require: the nearest candidate `present` holds; a gem or the + standard library resolves to nothing.""" + out: dict[str, None] = {} + for spec in specs: + hit = next((c for c in _candidates(from_path, spec) if c in present), None) + if hit and hit != from_path: + out[hit] = None + return list(out) + + +def ruby_callee(call: Any, source: bytes) -> tuple[str, str]: + """(method, receiver) of a call: `connection.execute(…)` → ("execute", "connection"), + `ActiveRecord::Base.connection.select_all(…)` → ("select_all", "connection").""" + method = call.child_by_field_name("method") + receiver = call.child_by_field_name("receiver") + name = node_text(method, source) if method is not None else "" + # the last name of the receiver: `a.connection` and `A::Base.connection` are `connection` + while receiver is not None and receiver.type in ("call", "scope_resolution"): + receiver = receiver.child_by_field_name("method" if receiver.type == "call" else "name") + return name, node_text(receiver, source) if receiver is not None else "" + + +def _string_value(bodies: dict[int, Any], node: Any, source: bytes) -> tuple[str, bool]: + """A string literal's text: escapes decoded, each `#{…}` a placeholder (interpolated); a + heredoc reads its body, dedented for `<<~`.""" + interpolated = False + pieces: list[str] = [] + if node.type == "heredoc_beginning": + body = bodies.get(node.start_byte) + if body is None: + return "", False + parts = body.children + else: + parts = node.children + for part in parts: + if part.type in ("string_content", "heredoc_content"): + pieces.append(node_text(part, source)) + elif part.type == "escape_sequence": + raw = node_text(part, source) + pieces.append(_ESCAPES.get(raw, raw)) + elif part.type == "interpolation": + pieces.append(PLACEHOLDER) + interpolated = True + text = "".join(pieces) + if node.type == "heredoc_beginning" and source.startswith(b"<<~", node.start_byte): + text = textwrap.dedent(text) + return text, interpolated + + +def _heredoc_bodies(root: Any) -> dict[int, Any]: + """{start byte of a `<<~X` marker: its body node}. A body follows the statement that + holds its marker, in the markers' order, so one walk pairs them.""" + pending: deque[Any] = deque() + bodies: dict[int, Any] = {} + stack = [root] + while stack: + node = stack.pop() + if node.type == "heredoc_beginning": + pending.append(node) + elif node.type == "heredoc_body": + if pending: + bodies[pending.popleft().start_byte] = node + continue + stack.extend(reversed(node.named_children)) + return bodies + + +RUBY_ISLANDS = IslandGrammar( + lang=LANG_RUBY, + call_node="call", + string_nodes=_STRING_NODES, + methods=RUBY_CLIENT_METHODS, + callee=ruby_callee, + string_value=functools.partial(_string_value, {}), + format_methods=frozenset({"format", "sprintf"}), + concat_node="binary", + assign_nodes=(("assignment", "left", "right"),), + aug_assign_node=("operator_assignment", "left", "operator", "right"), +) + + +def ruby_file_dialect(pf: ParsedFile) -> str: + """What the file's requires say it talks to: pg → postgres, mysql2 → mysql, sqlite3 → + sqlite, a ClickHouse gem → clickhouse; '' otherwise.""" + for m in _REQUIRE_LINE_RE.finditer(pf.source): + low = m.group(1).decode("utf-8", "replace").lower() + if "clickhouse" in low or "click_house" in low: + return "clickhouse" + if low == "pg" or "postgres" in low: + return "postgres" + if "mysql" in low or "trilogy" in low: + return "mysql" + if "sqlite" in low: + return "sqlite" + return "" + + +def ruby_sql_units(pf: ParsedFile) -> CodeSqlUnits: + """The statements, symbols and facets of the SQL a Ruby file runs.""" + if pf.tree is None: + return CodeSqlUnits() + grammar = RUBY_ISLANDS + if b"<<" in pf.source: + bodies = _heredoc_bodies(pf.tree.root_node) + if bodies: + grammar = dataclasses.replace( + grammar, string_value=functools.partial(_string_value, bodies) + ) + return code_sql_units(pf, grammar, ruby_file_dialect(pf)) + + +def facets(pf: ParsedFile) -> list[Facet]: + """The file's facet rows: the SQL it runs.""" + return list(ruby_sql_units(pf).facets) + + +__all__ = [ + "CHUNK_OPTIONS", + "KIND_CLASS", + "KIND_FUNCTION", + "KIND_MODULE", + "LANG_RUBY", + "RUBY_CLIENT_METHODS", + "RUBY_ISLANDS", + "SITE_BARE", + "SITE_CALL", + "SITE_HERITAGE", + "SITE_NEW", + "SITE_RULES", + "facets", + "parse_ruby", + "reference_sites", + "resolve_imports", + "ruby_callee", + "ruby_file_dialect", + "ruby_scope", + "ruby_sql_units", + "wanted_paths", +] diff --git a/server/code/domain/extract/lang_text.py b/server/code/domain/extract/lang_text.py index 0e13b6b2899..361988e9e8c 100644 --- a/server/code/domain/extract/lang_text.py +++ b/server/code/domain/extract/lang_text.py @@ -1,6 +1,6 @@ """A text file with no parser is still indexed. -A file whose language the ingest does not recognise — Kotlin, Ruby, PHP, +A file whose language the ingest does not recognise — Kotlin, PHP, Swift, Scala, Lua, Zig, C#, Dart, Elixir sources; `.txt`, `.cfg`, `.conf`, `.properties`, `.gradle`, GraphQL schemas — would otherwise be invisible to `code.grep` and `code.search` although the tree holds it. Such a file is @@ -27,7 +27,6 @@ { ".kt", ".kts", - ".rb", ".php", ".swift", ".scala", @@ -116,8 +115,6 @@ "jenkinsfile", "vagrantfile", "procfile", - "gemfile", - "rakefile", "brewfile", "justfile", "license", diff --git a/server/code/domain/extract/name_scope.py b/server/code/domain/extract/name_scope.py index 78aab49756e..7ed92e20cff 100644 --- a/server/code/domain/extract/name_scope.py +++ b/server/code/domain/extract/name_scope.py @@ -74,6 +74,7 @@ "jsonnet": SCRIPT, "lua": SCRIPT, # Dotted file scopes "graphql": SCRIPT, # Module-scoped `::Type` like protobuf + "ruby": SCRIPT, # Dotted file scopes (`lang_ruby.ruby_scope`) } # Programs a shell test calls that are not, and can never be, symbols of diff --git a/tests/code_lanes/corpus.py b/tests/code_lanes/corpus.py index 901a0c7c619..e369fad588f 100644 --- a/tests/code_lanes/corpus.py +++ b/tests/code_lanes/corpus.py @@ -177,6 +177,15 @@ def langs_for(self, path: str) -> frozenset[str]: ("python/members/svc/__init__.py", "package marker"), ), ), + Lane( + "ruby/", + "ruby", + "a gem: nested modules and classes, a superclass and a mixin as inherits, singleton " + "methods, `new`, calls bound within the file and across it, `require` includes " + "resolved through `lib/`, a rake task and a gemspec, and the SQL ActiveRecord runs " + "(a heredoc, `find_by_sql`, `execute`) bound to a table", + manifests=(("structure.sql", frozenset({"sql"})),), + ), Lane( "rust/", "rust", @@ -347,7 +356,7 @@ def _summarize() -> dict[str, Any]: facets.extend(pl.manifest_facets(rel, source.decode("utf-8", "replace"))) if is_notebook_path(rel): facets.extend(cell_facets(pf.source)) - elif pf.lang in ("go", "java"): + elif pf.lang in ("go", "java", "ruby"): facets = _code_units(pf).facets elif pf.lang in ts_langs: # The island statement symbols join the parse's, @@ -438,7 +447,7 @@ def _summarize() -> dict[str, Any]: pf.includes.append(hit) elif pf.lang == "rust": pf.includes = resolve_uses(rel, pf.includes, present) - elif pf.lang in ("proto", "thrift", "gotemplate", "lua"): + elif pf.lang in ("proto", "thrift", "gotemplate", "lua", "ruby"): # Import candidates settle against the corpus paths lane = _lane_module(pf.lang) pf.includes = lane.resolve_imports(rel, list(pf.includes), present) @@ -565,7 +574,7 @@ def _summarize() -> dict[str, Any]: ] if pf.lang == "prisma": es = [*es, *prisma_edges(pf)] - if pf.lang in ("proto", "thrift", "gotemplate", "lua", "graphql"): + if pf.lang in ("proto", "thrift", "gotemplate", "lua", "graphql", "ruby"): # The reference sites over the lane's table lane = _lane_module(pf.lang) es = [*es, *bind_sites(pf, lane.reference_sites(pf), gated, lane.SITE_RULES)] @@ -579,7 +588,7 @@ def _summarize() -> dict[str, Any]: if ju.dbt: es.extend(jinja_edges(rel, ju, gated)) es.extend(_column_edges(rel, statements, pf, gated)) - if pf.lang in ("python", "go", "java"): + if pf.lang in ("python", "go", "java", "ruby"): # The islands' table edges bind through the # SQL gate, as `ingest._py_island_edges` gates them — a Go caller # may reach a table, a Go call site may not @@ -595,6 +604,7 @@ def _summarize() -> dict[str, Any]: "thrift", "gotemplate", "lua", + "ruby", "config", "python", ): @@ -614,11 +624,14 @@ def _lane_module(lang: str) -> Any: lang_graphql, lang_lua, lang_proto, + lang_ruby, lang_thrift, ) if lang == "lua": return lang_lua + if lang == "ruby": + return lang_ruby if lang == "thrift": return lang_thrift if lang == "graphql": @@ -664,11 +677,15 @@ def _code_lane_includes(rel: str, pf: Any, present: set[str]) -> list[str]: def _code_units(pf: Any) -> Any: - """The SQL islands of a Go or Java file.""" + """The SQL islands of a Go, Java or Ruby file.""" if pf.lang == "go": from server.code.domain.extract.lang_go import go_sql_units return go_sql_units(pf) + if pf.lang == "ruby": + from server.code.domain.extract.lang_ruby import ruby_sql_units + + return ruby_sql_units(pf) from server.code.domain.extract.lang_java import java_sql_units return java_sql_units(pf) diff --git a/tests/fixtures/code_lanes/NOTICE.md b/tests/fixtures/code_lanes/NOTICE.md index 35d6575ee10..9bb3668f8d9 100644 --- a/tests/fixtures/code_lanes/NOTICE.md +++ b/tests/fixtures/code_lanes/NOTICE.md @@ -31,6 +31,7 @@ bats test, a Jinja template, a platform-suffixed Go file), so don't reformat or | vue/ | synthetic single-file components and a composable | — | | proto/, thrift/, helm/ | synthetic | — | | lua/ | synthetic: a vector module and a menu scene that requires it | — | +| ruby/ | synthetic: a ledger gem with a mixin, a subclass, singleton methods, requires, a rake task and ActiveRecord SQL | — | | rust/synthetic/ | synthetic: a trait and its impl, a declarative macro, an async function | — | | sql/views/ | synthetic: a ClickHouse table, a materialized view into its rollup, a view and a CTE | — | | tla/, fbs/, cmake/, md/ | synthetic: one toy ledger described in TLA+, FlatBuffers, CMake and Markdown (with fenced code) | — | diff --git a/tests/fixtures/code_lanes/expected.json b/tests/fixtures/code_lanes/expected.json index 674689790e4..9840a9673b2 100644 --- a/tests/fixtures/code_lanes/expected.json +++ b/tests/fixtures/code_lanes/expected.json @@ -98,6 +98,23 @@ "python/tests/integration/test_kafka_islands/test.py | calls | table": 5, "python/tests/integration/test_kafka_islands/test.py | calls | view": 1, "python/tests/integration/test_kafka_islands/test.py | fixture_use | fixture": 2, + "ruby/ledger/Rakefile | includes | file": 1, + "ruby/ledger/ledger.gemspec | includes | file": 1, + "ruby/ledger/lib/ledger.rb | calls | function": 1, + "ruby/ledger/lib/ledger.rb | includes | file": 3, + "ruby/ledger/lib/ledger/account.rb | calls | class": 2, + "ruby/ledger/lib/ledger/account.rb | calls | function": 6, + "ruby/ledger/lib/ledger/account.rb | includes | file": 2, + "ruby/ledger/lib/ledger/account.rb | inherits | module": 1, + "ruby/ledger/lib/ledger/auditable.rb | calls | function": 1, + "ruby/ledger/lib/ledger/report.rb | calls | class": 1, + "ruby/ledger/lib/ledger/report.rb | calls | column": 6, + "ruby/ledger/lib/ledger/report.rb | calls | function": 1, + "ruby/ledger/lib/ledger/report.rb | calls | table": 3, + "ruby/ledger/lib/ledger/report.rb | includes | file": 1, + "ruby/ledger/lib/ledger/report.rb | inherits | class": 1, + "ruby/ledger/lib/tasks/close.rake | calls | function": 1, + "ruby/ledger/lib/tasks/close.rake | includes | file": 1, "rust/langfuse/ai-gateway/src/capture/mod.rs | calls | function": 7, "rust/langfuse/ai-gateway/src/capture/mod.rs | includes | file": 2, "rust/langfuse/ai-gateway/src/capture/sse.rs | calls | function": 1, @@ -1258,6 +1275,120 @@ "view": 1 } }, + "ruby/ledger/Rakefile": { + "facets": {}, + "includes": [ + "ruby/ledger/lib/ledger.rb" + ], + "lang": "ruby", + "symbols": {} + }, + "ruby/ledger/db/structure.sql": { + "facets": { + "creates": 1, + "dialect": 1, + "function": 1, + "statement_kind": 1 + }, + "includes": [], + "lang": "sql", + "symbols": { + "column": 4, + "statement": 1, + "table": 1 + } + }, + "ruby/ledger/ledger.gemspec": { + "facets": {}, + "includes": [ + "ruby/ledger/lib/ledger/version.rb" + ], + "lang": "ruby", + "symbols": {} + }, + "ruby/ledger/lib/ledger.rb": { + "facets": {}, + "includes": [ + "ruby/ledger/lib/ledger/version.rb", + "ruby/ledger/lib/ledger/account.rb", + "ruby/ledger/lib/ledger/report.rb" + ], + "lang": "ruby", + "symbols": { + "class": 1, + "function": 3, + "module": 1 + } + }, + "ruby/ledger/lib/ledger/account.rb": { + "facets": {}, + "includes": [ + "ruby/ledger/lib/ledger/auditable.rb", + "ruby/ledger/lib/ledger/entry.rb" + ], + "lang": "ruby", + "symbols": { + "class": 1, + "function": 7, + "module": 1 + } + }, + "ruby/ledger/lib/ledger/auditable.rb": { + "facets": {}, + "includes": [], + "lang": "ruby", + "symbols": { + "function": 2, + "module": 2 + } + }, + "ruby/ledger/lib/ledger/entry.rb": { + "facets": {}, + "includes": [], + "lang": "ruby", + "symbols": { + "class": 1, + "function": 2, + "module": 1 + } + }, + "ruby/ledger/lib/ledger/report.rb": { + "facets": { + "dialect": 3, + "function": 2, + "statement_kind": 3, + "table_read": 2, + "table_write": 1 + }, + "includes": [ + "ruby/ledger/lib/ledger/account.rb" + ], + "lang": "ruby", + "symbols": { + "class": 1, + "function": 4, + "module": 1, + "statement": 3 + } + }, + "ruby/ledger/lib/ledger/version.rb": { + "facets": {}, + "includes": [], + "lang": "ruby", + "symbols": { + "module": 1 + } + }, + "ruby/ledger/lib/tasks/close.rake": { + "facets": {}, + "includes": [ + "ruby/ledger/lib/ledger.rb" + ], + "lang": "ruby", + "symbols": { + "function": 1 + } + }, "rust/langfuse/ai-gateway/src/capture/facts.rs": { "facets": {}, "includes": [], diff --git a/tests/fixtures/code_lanes/ruby/ledger/Rakefile b/tests/fixtures/code_lanes/ruby/ledger/Rakefile new file mode 100644 index 00000000000..616e7ab65f2 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/Rakefile @@ -0,0 +1,3 @@ +require "ledger" + +task default: :test diff --git a/tests/fixtures/code_lanes/ruby/ledger/db/structure.sql b/tests/fixtures/code_lanes/ruby/ledger/db/structure.sql new file mode 100644 index 00000000000..ff6af697db2 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/db/structure.sql @@ -0,0 +1,6 @@ +CREATE TABLE entries ( + id bigserial PRIMARY KEY, + owner text NOT NULL, + cents bigint NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); diff --git a/tests/fixtures/code_lanes/ruby/ledger/ledger.gemspec b/tests/fixtures/code_lanes/ruby/ledger/ledger.gemspec new file mode 100644 index 00000000000..35c43cc0e1f --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/ledger.gemspec @@ -0,0 +1,7 @@ +require_relative "lib/ledger/version" + +Gem::Specification.new do |spec| + spec.name = "ledger" + spec.version = Ledger::VERSION + spec.summary = "Accounts and their entries" +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger.rb new file mode 100644 index 00000000000..a2c6d2e9286 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +require_relative "ledger/version" +require "ledger/account" +require "ledger/report" +require "json" + +# Accounts and the entries posted to them. +module Ledger + class Error < StandardError; end + + def self.open(owner) + Account.open(owner) + end + + class << self + def configure + yield config + end + + def config + @config ||= {} + end + end +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/account.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/account.rb new file mode 100644 index 00000000000..c8bd2fbc8e3 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/account.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require "ledger/auditable" +require "ledger/entry" + +module Ledger + # A balance with its history. + class Account < ApplicationRecord + include Auditable + extend Forwardable + + def self.open(owner) + account = new(owner) + account.audit("opened") + account + end + + def initialize(owner) + @owner = owner + @entries = [] + end + + def deposit(cents) + post(Entry.new(cents)) + end + + def balance + @entries.sum(&:cents) + end + + def close! + raise "not empty" unless balanced? + audit("closed") + end + + private + + def post(entry) + @entries << entry + audit("posted") + end + + def balanced? + balance.zero? + end + end +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/auditable.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/auditable.rb new file mode 100644 index 00000000000..ea7a7db1549 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/auditable.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +module Ledger + # Records what happened to an object. + module Auditable + def audit(event) + log.push(event) + end + + def log + @log ||= [] + end + end +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/entry.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/entry.rb new file mode 100644 index 00000000000..76f6dcf58a3 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/entry.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +module Ledger + # One posting: an amount in cents. + class Entry + attr_reader :cents + + def initialize(cents) + @cents = cents + end + + def to_s + format("%d", cents) + end + end +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/report.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/report.rb new file mode 100644 index 00000000000..e9b4185f01f --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/report.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require "pg" +require "ledger/account" + +module Ledger + # Totals per owner, read straight from the entries table. + class Report < Account + def self.run(owner) + new(owner).totals + end + + def totals + rows = connection.select_all(<<~SQL) + SELECT owner, SUM(cents) AS total + FROM entries + WHERE owner = #{quote(owner)} + GROUP BY owner + SQL + rows.to_a + end + + def stale(days) + Entry.find_by_sql("SELECT * FROM entries WHERE created_at < now() - #{days}") + end + + def purge + connection.execute("DELETE FROM entries WHERE cents = 0") + end + end +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/version.rb b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/version.rb new file mode 100644 index 00000000000..393e7827e55 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/ledger/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Ledger + VERSION = "0.1.0" +end diff --git a/tests/fixtures/code_lanes/ruby/ledger/lib/tasks/close.rake b/tests/fixtures/code_lanes/ruby/ledger/lib/tasks/close.rake new file mode 100644 index 00000000000..947123b1409 --- /dev/null +++ b/tests/fixtures/code_lanes/ruby/ledger/lib/tasks/close.rake @@ -0,0 +1,12 @@ +require "ledger" + +def close_books(ids) + ids.each { |id| Ledger::Account.open(id).close! } +end + +namespace :ledger do + desc "Close the books" + task :close do + close_books([1, 2]) + end +end diff --git a/tests/inventory/build.py b/tests/inventory/build.py index 8ad4e8e9e46..c4a6423c76c 100644 --- a/tests/inventory/build.py +++ b/tests/inventory/build.py @@ -84,6 +84,7 @@ "prisma", "proto", "python", + "ruby", "rust", "shell", "sql", diff --git a/tests/unit/lane_walks.py b/tests/unit/lane_walks.py index 3eef9e1393b..fe0fb9a7b97 100644 --- a/tests/unit/lane_walks.py +++ b/tests/unit/lane_walks.py @@ -563,6 +563,7 @@ def over(small: float, big: float) -> bool: "prisma": ("a.prisma", "", "prisma"), "go": ("a.go", "package a\n", "go"), "java": ("A.java", "", "java"), + "ruby": ("a.rb", "", "ruby"), "vue": ("a.vue", "", "javascript"), "svelte": ("a.svelte", "", "javascript"), "astro": ("a.astro", "", "typescript"), diff --git a/tests/unit/test_code_extractor_stamp.py b/tests/unit/test_code_extractor_stamp.py index d95e5e63954..57633084a91 100644 --- a/tests/unit/test_code_extractor_stamp.py +++ b/tests/unit/test_code_extractor_stamp.py @@ -55,7 +55,7 @@ ), "lang_text.py": "text-fallback language table, chunk-only; no extractor stage reads it", "lang_code_islands.py": ( - "the island contract with the grammar as data — Go and Java client " + "the island contract with the grammar as data — Go, Java and Ruby client " "calls, annotations, format templates and literals; dispatched from ingest.py" ), "lang_go.py": ( @@ -93,6 +93,11 @@ "jsonnet bindings, members and imports — a lane module outside the " "stamp like lang_proto.py; rows arrive by a targeted backfill" ), + "lang_ruby.py": ( + "ruby classes, modules, methods, mixins, call sites, require candidates and SQL " + "islands — a lane module outside the stamp like lang_go.py; rows arrive by a " + "targeted backfill" + ), "lang_lua.py": ( "lua functions, call sites and require candidates — a lane module outside the " "stamp like lang_proto.py; rows arrive by a targeted backfill" diff --git a/tests/unit/test_code_kind_prior.py b/tests/unit/test_code_kind_prior.py index f196d8cfdd2..f050e1236dc 100644 --- a/tests/unit/test_code_kind_prior.py +++ b/tests/unit/test_code_kind_prior.py @@ -287,7 +287,7 @@ def test_line_windows_keep_their_place_among_the_functions_of_other_files() -> N "paths", [ ("schemas/migrations/0042_cache_version.sql", "deploy/values.yaml", "docs/cache.md"), - ("app/Cache.kt", "ios/Cache.swift", "src/Cache.cs", "lib/cache.rb", "web/cache.php"), + ("app/Cache.kt", "ios/Cache.swift", "src/Cache.cs", "lib/cache.ex", "web/cache.php"), ("web/cache.css", "notes/cache.txt", "LICENSE", "pyproject.toml", "docs/index.rst"), # a file of HCL values has no block; a CMake target outline is not moved ("envs/prod.tfvars", "envs/dev.auto.tfvars", "cmake/flags.cmake", "CMakeLists.txt"), diff --git a/tests/unit/test_code_lanes_manifest.py b/tests/unit/test_code_lanes_manifest.py index a17ec1546f5..d1a22743840 100644 --- a/tests/unit/test_code_lanes_manifest.py +++ b/tests/unit/test_code_lanes_manifest.py @@ -23,7 +23,7 @@ # The languages whose summary row records includes resolved against the # corpus's own paths; the others record the specifier as written. RESOLVED_INCLUDE_LANGS = frozenset( - {"typescript", "javascript", "rust", "proto", "thrift", "gotemplate", "python"} + {"typescript", "javascript", "rust", "proto", "thrift", "gotemplate", "python", "ruby"} ) _EDGE_KEY = re.compile(r"^(?P.+) \| (?P[a-z_]+) \| (?P[a-z_?]+)$") _SECRET = re.compile( diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py new file mode 100644 index 00000000000..97f956d38b4 --- /dev/null +++ b/tests/unit/test_code_lang_ruby.py @@ -0,0 +1,713 @@ +"""Ruby fast-tier parsing: symbols, `inherits` and call sites bound by `lane_units`, +`require` includes and the SQL a file runs.""" + +from __future__ import annotations + +import asyncio +import time +from typing import Any + +import pytest + +pytest.importorskip("tree_sitter_ruby") + +from server.code.app.index.ingest_chunks import _chunks_for +from server.code.app.index.ingest_edges import _lane_site_edges +from server.code.app.index.ingest_parse import parse_for_ingest +from server.code.app.index.ingest_resolve import _resolve_lane_includes +from server.code.domain.extract.lane_units import bind_sites, span_chunks +from server.code.domain.extract.lang_detect import detect_by_extension +from server.code.domain.extract.lang_ruby import ( + CHUNK_OPTIONS, + SITE_RULES, + parse_ruby, + reference_sites, + resolve_imports, + ruby_sql_units, + wanted_paths, +) +from server.code.domain.extract.lang_text import text_lang_for_path +from server.code.domain.extract.name_scope import qualified_name_class +from server.code.domain.extract.treesitter import ParsedFile +from tests.unit.code_fixtures import assert_linear + +BILLING = b"""# frozen_string_literal: true + +require "json" +require_relative "../lib/util" +require File.join(__dir__, "dynamic") +require "x#{1}" + +module Billing + # An invoice. + class Invoice < Base::Record + include Auditable + extend Forwardable + prepend Loud, Quiet + + TAX = 0.2 + + def initialize(user, amount = 1, *rest, key:, **opts, &blk) + @user = user + end + + def total + subtotal + tax + end + + def self.build(attrs) + new(attrs) + end + + class << self + def make; end + end + + def log(msg) = puts(msg) + end +end + +class Admin::User < ::User + def name=(value); end + def ==(other); end +end + +def helper(a, b); end +""" + +CART = b"""module Shop + class Cart + def checkout(user) + items.each { |i| price(i) } + total = subtotal + tax + Payment.charge(user, total) + Receipt.new(total) + user.notify(total) + puts total + self.finish + log! + end + + def subtotal; end + def tax; end + def price(item); end + def finish; end + def log!; end + end +end +""" + +PAYMENT = b"""module Shop + class Receipt; end + + class Payment + def self.charge(user, amount); end + def notify(a); end + end + + class Mailer + def notify(a); end + end +end +""" + +SQL = b"""require "pg" + +class Report + def totals + rows = connection.select_all(<<~SQL) + SELECT owner, SUM(cents) AS total + FROM entries + WHERE owner = #{quote(owner)} + SQL + rows.to_a + end + + def stale(days) + Entry.find_by_sql("SELECT * FROM entries WHERE created_at < now() - #{days}") + end + + def purge + connection.execute("DELETE FROM entries WHERE cents = 0") + end + + def fragment + Entry.where("owner = ?", owner) + puts "Select a user first" + end + + QUERY = "SELECT id FROM entries ORDER BY id" +end +""" + + +def _table(*files: object) -> dict[str, list[tuple[str, str, str]]]: + table: dict[str, list[tuple[str, str, str]]] = {} + for pf in files: + for s in pf.symbols: # type: ignore[attr-defined] + table.setdefault(s.name, []).append((s.id, s.qualified_name, s.kind)) + return table + + +def test_definitions_nest_and_are_qualified_by_the_file_scope() -> None: + pf = parse_ruby("lib/billing.rb", BILLING) + assert [(s.qualified_name, s.name, s.kind) for s in pf.symbols] == [ + ("lib.billing::Billing", "Billing", "module"), + ("lib.billing::Billing::Invoice", "Invoice", "class"), + ("lib.billing::Billing::Invoice#initialize", "initialize", "function"), + ("lib.billing::Billing::Invoice#total", "total", "function"), + ("lib.billing::Billing::Invoice.build", "build", "function"), + ("lib.billing::Billing::Invoice.make", "make", "function"), + ("lib.billing::Billing::Invoice#log", "log", "function"), + ("lib.billing::Admin::User", "User", "class"), + ("lib.billing::Admin::User#name=", "name=", "function"), + ("lib.billing::Admin::User#==", "==", "function"), + ("lib.billing::helper", "helper", "function"), + ] + by_name = {s.name: s for s in pf.symbols} + assert by_name["Billing"].signature == "module Billing" + assert by_name["Invoice"].signature == "class Invoice < Base::Record" + assert by_name["Invoice"].doc_comment == "An invoice." + assert by_name["User"].signature == "class Admin::User < ::User" + assert by_name["initialize"].signature == "(user, amount = 1, *rest, key:, **opts, &blk)" + assert by_name["make"].signature == "()" + assert (by_name["total"].start_line, by_name["total"].end_line) == (21, 23) + assert (by_name["Billing"].start_line, by_name["Billing"].end_line) == (8, 35) + # a one-line endless def spans its own line + assert (by_name["log"].start_line, by_name["log"].end_line) == (33, 33) + + +def test_names_read_as_script_definitions_even_for_a_root_file() -> None: + for path in ("lib/billing.rb", "billing.rb", "Rakefile"): + pf = parse_ruby(path, b"module A\n class B\n def c; end\n end\nend\n") + assert {qualified_name_class(s.qualified_name) for s in pf.symbols} == {"script"}, path + root = parse_ruby("billing.rb", b"def c; end\n") + assert root.symbols[0].qualified_name == "root.billing::c" + + +def test_the_singleton_class_of_a_constant_holds_its_singleton_methods() -> None: + src = b"class << Config\n def load; end\nend\nclass << config\n def hidden; end\nend\n" + # as `def Config.load` reads; an object's singleton class names no definition + assert [s.qualified_name for s in parse_ruby("a.rb", src).symbols] == ["root.a::Config.load"] + + +def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: + pf = parse_ruby("lib/billing.rb", BILLING) + # `require_relative "x"` keeps a leading `./` so it resolves beside the file + assert pf.includes == ["json", "../lib/util"] + assert parse_ruby("a.rb", b'require_relative "b"\nrequire "b"\n').includes == ["./b", "b"] + assert parse_ruby("a.rb", b"require %q(json)\nrequire %Q{a/b}\n").includes == ["json", "a/b"] + + +def test_a_file_that_does_not_parse_cleanly_keeps_the_symbols_it_can_read() -> None: + pf = parse_ruby("a.rb", b"def ok; end\nclass A\n def broken(\nend\n") + assert "ok" in {s.name for s in pf.symbols} + assert parse_ruby("empty.rb", b"").symbols == [] + + +def test_calls_are_sites_by_receiver_kind_and_skip_the_runtime() -> None: + sites = reference_sites(parse_ruby("shop/cart.rb", CART)) + assert [(n, k) for _line, n, k in sites] == [ + ("items", "bare"), + ("price", "call"), + ("subtotal", "bare"), + ("tax", "bare"), + ("charge", "call"), + ("Receipt", "new"), + ("notify", "call"), + ("puts", "bare"), + ("finish", "call"), + ("log!", "call"), + ] + assert sites[1][0] == 4 # `price(i)` inside the block + # `each` and the locals `user` and `total` name nothing; `log!` can only be a call + + +def test_a_common_name_called_on_self_binds_only_inside_its_own_file() -> None: + src = b"""class Importer + def run(rows) + validate(rows) + self.save(rows) + rows.save + end + + def validate(rows); end + def save(rows); end +end +""" + pf = parse_ruby("importer.rb", src) + record = parse_ruby("record.rb", b"def save(r); end\n") + edges = bind_sites(pf, reference_sites(pf), _table(pf, record), SITE_RULES) + assert [(e.to_qualified_name, e.line, e.confidence) for e in edges] == [ + ("root.importer::Importer#validate", 3, 1.0), + ("root.importer::Importer#save", 4, 1.0), + ] + # the language's own `save` may be the one a class without its own calls + lone = parse_ruby("lone.rb", b"class Lone\n def run\n save(1)\n end\nend\n") + assert bind_sites(lone, reference_sites(lone), _table(lone, record), SITE_RULES) == [] + + +def test_a_parameter_or_an_assignment_shadows_a_method_of_the_same_name() -> None: + src = b"def run(helper)\n helper\n value = helper\n value\nend\ndef helper; end\n" + assert reference_sites(parse_ruby("a.rb", src)) == [] + # a parameter's default reads a name; a pattern binds the names it holds + src = b"""def run(n = size, k: size) + size + case n + in {name:, tags: [first, *rest]} + name + first + rest.size + end +end +def size; end +def name; end +""" + sites = reference_sites(parse_ruby("b.rb", src)) + assert [(line, n, k) for line, n, k in sites] == [ + (1, "size", "bare"), + (1, "size", "bare"), + (2, "size", "bare"), + ] + + +def test_a_doc_comment_is_the_comment_lines_right_above_a_definition() -> None: + src = b"""class A + def self.d; end # trailing + # Builds it. + def self.e; end + + # Helps. + private def helper; end +end +""" + docs = {s.name: s.doc_comment for s in parse_ruby("a.rb", src).symbols} + assert docs == {"A": "", "d": "", "e": "Builds it.", "helper": "Helps."} + + +def test_new_without_a_receiver_constructs_the_enclosing_class() -> None: + src = b"class Cart\n def self.build\n new\n new(1)\n self.new(2)\n end\nend\n" + sites = reference_sites(parse_ruby("cart.rb", src)) + assert [(n, k) for _l, n, k in sites] == [("Cart", "new")] * 3 + + +def test_call_sites_bind_same_file_first_then_repository_unique() -> None: + cart = parse_ruby("shop/cart.rb", CART) + payment = parse_ruby("shop/payment.rb", PAYMENT) + edges = bind_sites(cart, reference_sites(cart), _table(cart, payment), SITE_RULES) + assert { + (e.from_qualified_name.rsplit("::", 1)[1], e.to_qualified_name, e.edge_kind, e.confidence) + for e in edges + } == { + ("Cart#checkout", "shop.cart::Shop::Cart#price", "calls", 1.0), + ("Cart#checkout", "shop.cart::Shop::Cart#subtotal", "calls", 1.0), + ("Cart#checkout", "shop.cart::Shop::Cart#tax", "calls", 1.0), + ("Cart#checkout", "shop.cart::Shop::Cart#finish", "calls", 1.0), + ("Cart#checkout", "shop.cart::Shop::Cart#log!", "calls", 1.0), + ("Cart#checkout", "shop.payment::Shop::Payment.charge", "calls", 0.6), + ("Cart#checkout", "shop.payment::Shop::Receipt", "calls", 0.6), + } + # `notify` is defined in two classes, so the call names neither + + +def test_a_bare_word_binds_only_inside_its_own_file() -> None: + a = parse_ruby("a.rb", b"def run\n helper\nend\n") + b = parse_ruby("b.rb", b"def helper; end\n") + assert bind_sites(a, reference_sites(a), _table(a, b), SITE_RULES) == [] + c = parse_ruby("c.rb", b"def run\n helper()\nend\n") + assert len(bind_sites(c, reference_sites(c), _table(c, b), SITE_RULES)) == 1 + + +def test_a_superclass_and_the_mixins_are_inherits_edges() -> None: + src = b"""module Walk; end +module Swim; end +class Animal; end +class Duck < Animal + include Walk + prepend Swim, Missing + extend Comparable +end +module Pond + include Swim +end +""" + pf = parse_ruby("zoo.rb", src) + sites = reference_sites(pf) + assert [(n, k) for _l, n, k in sites] == [ + ("Animal", "heritage"), + ("Walk", "heritage"), + ("Swim", "heritage"), + ("Missing", "heritage"), + ("Comparable", "heritage"), + ("Swim", "heritage"), + ] + edges = bind_sites(pf, sites, _table(pf), SITE_RULES) + assert [ + (e.from_qualified_name.split("::")[1], e.to_qualified_name.split("::")[1], e.edge_kind) + for e in edges + ] == [ + ("Duck", "Animal", "inherits"), + ("Duck", "Walk", "inherits"), + ("Duck", "Swim", "inherits"), + ("Pond", "Swim", "inherits"), + ] + + +def test_a_name_the_caller_also_defines_is_ambiguous_to_a_call_on_another_object() -> None: + src = b"""class Outer + def call(env) + @app.call(env) + end +end +class Inner + def call(env); end +end +def fact(n) + fact(n - 1) +end +""" + pf = parse_ruby("rack.rb", src) + # `@app` may be an Inner or anything else; `fact` calling itself is no edge + assert bind_sites(pf, reference_sites(pf), _table(pf), SITE_RULES) == [] + + +def test_a_site_on_the_line_of_a_one_line_class_binds_from_the_class() -> None: + src = b"class Base; end\nclass One < Base; def x; end; end\n" + pf = parse_ruby("one.rb", src) + (edge,) = bind_sites(pf, reference_sites(pf), _table(pf), SITE_RULES) + assert (edge.from_qualified_name, edge.to_qualified_name) == ("root.one::One", "root.one::Base") + + +def test_bare_calls_in_loops_patterns_and_lists_are_sites() -> None: + src = b"""def run(v) + while busy? + advance + end + for item in pending do + step + end + case v + when first_kind then 1 + end + computed => found + a, b = left, right + case pick + in 1 then found + a + b + item + end +end +""" + names = [n for _l, n, _k in reference_sites(parse_ruby("loop.rb", src))] + # the body of an endless method reads its value; the method's own name is no site + endless = b"class A\n def full = name\n def self.make = build\n def name = @n\nend\n" + assert reference_sites(parse_ruby("e.rb", endless)) == [ + (2, "name", "bare"), + (3, "build", "bare"), + ] + assert names == [ + "busy?", + "advance", + "pending", + "step", + "first_kind", + "computed", + "left", + "right", + "pick", + ] + + +def test_a_class_reopened_in_its_own_file_is_one_target() -> None: + src = b"""module Walk; end +module Walk + def walk; end +end +class Duck + include Walk +end +class Duck + def self.hatch + Duck.new + end +end +""" + pf = parse_ruby("zoo.rb", src) + edges = bind_sites(pf, reference_sites(pf), _table(pf), SITE_RULES) + assert [ + (e.from_qualified_name, e.to_qualified_name, e.edge_kind, e.confidence) for e in edges + ] == [ + ("root.zoo::Duck", "root.zoo::Walk", "inherits", 1.0), + ("root.zoo::Duck.hatch", "root.zoo::Duck", "calls", 1.0), + ] + + +def test_a_call_inside_a_sql_string_binds_from_its_method_not_the_statement() -> None: + # the statements join the parse, inside the spans of their methods + pf, err = parse_for_ingest("app/report.rb", SQL) + assert err == "" and pf is not None + entry = parse_ruby("lib/entry.rb", b"class Entry\n def self.find_by_sql(q); end\nend\n") + quoting = parse_ruby("lib/quoting.rb", b"def quote(value); end\n") + edges = bind_sites(pf, reference_sites(pf), _table(entry, quoting), SITE_RULES) + assert {(e.from_qualified_name, e.to_qualified_name) for e in edges} == { + ("app.report::Report#totals", "lib.quoting::quote"), + ("app.report::Report#stale", "lib.entry::Entry.find_by_sql"), + } + + +def test_a_base_class_in_another_file_binds_at_the_repository_rung() -> None: + base = parse_ruby("lib/base.rb", b"module Ledger\n class Account; end\nend\n") + sub = parse_ruby("lib/report.rb", b"module Ledger\n class Report < Account; end\nend\n") + (edge,) = bind_sites(sub, reference_sites(sub), _table(base, sub), SITE_RULES) + assert (edge.edge_kind, edge.to_qualified_name, edge.confidence) == ( + "inherits", + "lib.base::Ledger::Account", + 0.6, + ) + + +def test_requires_resolve_beside_the_file_then_up_through_lib() -> None: + assert wanted_paths("lib/ledger/account.rb", ["ledger/entry", "../util", "./x"]) == [ + "lib/ledger/ledger/entry.rb", + "lib/ledger/lib/ledger/entry.rb", + "lib/ledger/entry.rb", + "lib/lib/ledger/entry.rb", + "ledger/entry.rb", + "lib/util.rb", + "lib/ledger/x.rb", + ] + present = {"lib/ledger/entry.rb", "lib/util.rb", "lib/ledger/account.rb"} + assert resolve_imports( + "lib/ledger/account.rb", ["ledger/entry", "../util", "json", "./account"], present + ) == ["lib/ledger/entry.rb", "lib/util.rb"] + # two levels up is a path; an escape above the repository root and an absolute path are not + assert wanted_paths("a/b/c.rb", ["../../x", "./../y"]) == ["x.rb", "a/y.rb"] + assert wanted_paths("a.rb", ["../../etc/passwd", "/etc/passwd", "a/../b"]) == [] + + +def test_ruby_files_are_a_lane_not_plain_text() -> None: + for path in ( + "lib/a.rb", + "tasks/b.rake", + "c.gemspec", + "Gemfile", + "sdk/ruby/Rakefile", + "LIB/A.RB", + ): + assert detect_by_extension(path) == "ruby", path + assert text_lang_for_path(path, b"def a; end\n") == "", path + pf, err = parse_for_ingest(path, b"def a; end\n") + assert err == "" and pf is not None and pf.lang == "ruby" and len(pf.symbols) == 1, path + assert detect_by_extension("lib/gemfile.rb.txt") == "" + assert detect_by_extension("app/Gemfile.lock") == "" + + +def test_chunks_follow_the_method_spans() -> None: + pf = parse_ruby("shop/cart.rb", CART) + chunks = span_chunks(pf, 6000, **CHUNK_OPTIONS) + functions = [c for c in chunks if c.kind == "function"] + assert [c.scope.rsplit("#", 1)[1] for c in functions] == [ + "checkout", + "subtotal", + "tax", + "price", + "finish", + "log!", + ] + # the `module` and `class` lines are not a method's: they stay as leftovers + assert {c.kind for c in chunks} <= {"function", "file_header", "other"} + + +MODEL = b"""class Post < ApplicationRecord + belongs_to :user + + validates :title, presence: true + + def publish + update(published: true) + end + + SORT = :title +end +""" + + +def test_every_line_with_text_is_in_a_chunk_however_short() -> None: + # a Ruby file was text, every line of it searchable; the lines between two methods are + # one chunk, and a gap of blank lines is none + chunks = span_chunks(parse_ruby("app/models/post.rb", MODEL), 6000, **CHUNK_OPTIONS) + assert sorted((c.start_line, c.end_line, c.kind) for c in chunks) == [ + (1, 4, "other"), + (6, 8, "function"), + (10, 11, "other"), + ] + gemfile = b'source "https://rubygems.org"\n\nruby "3.2.2"\n\ngem "pg"\n' + chunks = span_chunks(parse_ruby("Gemfile", gemfile), 6000, **CHUNK_OPTIONS) + assert [(c.start_line, c.end_line, c.content) for c in chunks] == [(1, 5, gemfile.decode())] + + +def test_chunks_count_lines_as_the_parser_does() -> None: + # a form feed and a U+2028 end no line for the parser, so they end none for a chunk + src = 'class A\n X = "a\u2028b"\n\x0c\n def one\n 1\n end\nend\n'.encode() + pf = parse_ruby("a.rb", src) + (one,) = (s for s in pf.symbols if s.name == "one") + (chunk,) = (c for c in span_chunks(pf, 6000, **CHUNK_OPTIONS) if c.kind == "function") + assert (chunk.start_line, chunk.end_line) == (one.start_line, one.end_line) == (4, 6) + assert chunk.content == " def one\n 1\n end\n" + + +def test_a_file_whose_parse_failed_is_chunked_as_line_windows() -> None: + pf = ParsedFile(path="app/models/post.rb", lang="ruby", source=MODEL) + chunks, _prefixes, facets = _chunks_for(pf, pf.path, MODEL, 6000, None, "parse: ParseTimeout") + assert [(c.kind, c.start_line, c.end_line) for c in chunks] == [("other", 1, 11)] + assert facets == [] + + +def test_sql_a_file_runs_is_lifted_from_the_client_calls_and_literals() -> None: + pf = parse_ruby("app/report.rb", SQL) + units = ruby_sql_units(pf) + rows = [(i.via, i.line, i.dialect, i.text.replace("\n", " ").strip()) for i in units.islands] + assert rows == [ + ( + "call", + 5, + "postgres", + "SELECT owner, SUM(cents) AS total FROM entries WHERE owner = __var__", + ), + ("call", 14, "postgres", "SELECT * FROM entries WHERE created_at < now() - __var__"), + ("call", 18, "postgres", "DELETE FROM entries WHERE cents = 0"), + ("literal", 26, "postgres", "SELECT id FROM entries ORDER BY id"), + ] + assert {s.kind for s in units.symbols} == {"statement"} + assert len(units.symbols) == 4 + facets = {(f.kind, f.name) for f in units.facets} + assert { + ("table_read", "entries"), + ("table_write", "entries"), + ("dialect", "postgres"), + } <= facets + # `where("owner = ?")` is a fragment and the prose is not SQL + assert not any("owner = __var__" == i.text for i in units.islands) + assert not any("Select a user" in i.text for i in units.islands) + + +def test_the_statements_join_the_parse_of_an_ingested_file() -> None: + pf, err = parse_for_ingest("app/report.rb", SQL) + assert err == "" and pf is not None + assert [s.kind for s in pf.symbols].count("statement") == 4 + assert {s.name for s in pf.symbols if s.kind == "function"} == { + "totals", + "stale", + "purge", + "fragment", + } + + +class _Repo: + """The reads the ingest makes of the index for a lane file, over a fixed namespace.""" + + def __init__(self, paths: set[str], table: dict[str, list[tuple[str, str, str]]]) -> None: + self.paths, self.table = paths, table + self.asked: list[str] = [] + + async def live_paths_present(self, org: str, ns: str, paths: list[str]) -> list[str]: + return [p for p in paths if p in self.paths] + + async def name_candidates( + self, org: str, ns: str, names: list[str] + ) -> dict[str, list[tuple[str, str, str]]]: + self.asked.extend(names) + return {n: self.table[n] for n in names if n in self.table} + + +def test_the_ingest_resolves_includes_cuts_chunks_and_binds_edges_for_a_ruby_file() -> None: + account = parse_ruby("lib/ledger/account.rb", b"module Ledger\n class Account\n end\nend\n") + source = b"require 'ledger/account'\nrequire 'json'\n" + SQL + pf, err = parse_for_ingest("lib/ledger/report.rb", source) + assert err == "" and pf is not None + repo: Any = _Repo({"lib/ledger/account.rb"}, _table(account)) + asyncio.run(_resolve_lane_includes(repo, "o", "n", pf)) + assert pf.includes == ["lib/ledger/account.rb"] # `pg` and `json` are gems + + chunks, _prefixes, facets = _chunks_for(pf, pf.path, source, 6000) + assert [c.scope.rsplit("#", 1)[-1] for c in chunks if c.kind == "function"] == [ + "totals", + "stale", + "purge", + "fragment", + ] + assert {("table_read", "entries"), ("table_write", "entries")} <= { + (f.kind, f.name) for f in facets + } + + # `Entry.find_by_sql` names a class the namespace defines in another file + entry = parse_ruby("lib/ledger/entry.rb", b"class Entry\n def self.find_by_sql(q); end\nend\n") + repo = _Repo(set(), _table(entry)) + edges = asyncio.run(_lane_site_edges(repo, "o", "n", pf)) + assert [(e.edge_kind, e.to_qualified_name, e.confidence) for e in edges] == [ + ("calls", "lib.ledger.entry::Entry.find_by_sql", 0.6) + ] + # a bare word binds only inside its file, so the index is not asked for it + assert "find_by_sql" in repo.asked and not {"connection", "owner"} & set(repo.asked) + + +@pytest.mark.parametrize( + "unit", + [ + "class A < B\n def a(x) = b(x)\n include C\nend\n", + "def a\n b.c(d)\nend\n", + "module A\n class B\n", + "x = <<~SQL\n SELECT 1 FROM t\nSQL\n", + 'require "a"\n', + "a.b(\n", + "foo bar,\n", + "def a; if b; c; end; end\n", + ], +) +def test_a_file_of_many_units_parses_in_linear_time(unit: str) -> None: + def cost(n: int) -> float: + src = (unit * n).encode() + t0 = time.perf_counter() + reference_sites(parse_ruby("a.rb", src)) + return time.perf_counter() - t0 + + assert_linear(cost, 1_000, 4_000) + + +def test_a_class_of_many_methods_is_chunked_in_linear_time() -> None: + def cost(n: int) -> float: + pf = parse_ruby( + "a.rb", ("class A\n" + " def a; end\n\n attr :x\n" * n + "end\n").encode() + ) + t0 = time.perf_counter() + span_chunks(pf, 6000, **CHUNK_OPTIONS) + return time.perf_counter() - t0 + + assert_linear(cost, 1_000, 4_000) + + +def test_the_calls_of_a_class_of_many_methods_bind_in_linear_time() -> None: + def cost(n: int) -> float: + body = "".join(f" def m{i}(a)\n m{i + 1}(a)\n a.go\n end\n" for i in range(n)) + pf = parse_ruby("a.rb", f"class A\n{body}end\n".encode()) + sites, table = reference_sites(pf), _table(pf) + t0 = time.perf_counter() + bind_sites(pf, sites, table, SITE_RULES) + return time.perf_counter() - t0 + + assert_linear(cost, 500, 2_000) + + +@pytest.mark.parametrize( + "unit", + [ + "x = <<~SQL\n SELECT 1 FROM t\nSQL\n", + 'q = "SELECT a FROM t"\nq += " WHERE x"\n', + 'db.execute("DELETE FROM t WHERE a = #{b}")\n', + "db.select_all(<<-SQL, <<-SQL)\n a\nSQL\n b\nSQL\n", + ], +) +def test_the_sql_of_a_file_of_many_statements_is_lifted_in_linear_time(unit: str) -> None: + def cost(n: int) -> float: + pf = parse_ruby("a.rb", (unit * n).encode()) + t0 = time.perf_counter() + ruby_sql_units(pf) + return time.perf_counter() - t0 + + assert_linear(cost, 500, 2_000) diff --git a/tests/unit/test_lang_text.py b/tests/unit/test_lang_text.py index 69677ac9a04..d84b71fcaf1 100644 --- a/tests/unit/test_lang_text.py +++ b/tests/unit/test_lang_text.py @@ -20,7 +20,6 @@ def _intel_on(monkeypatch): def test_code_without_a_parser_and_plain_text_are_kept_as_text() -> None: for path, src in { "app/Main.kt": b"fun main() {}", - "lib/a.rb": b"def a; end", "web/x.php": b" Date: Fri, 4 Dec 2026 13:48:04 +0530 Subject: [PATCH 04/29] The code index docs list Ruby among the parsed languages The language table, the lane guide, the architecture page and the plugin's place rule still described Ruby as text. Signed-off-by: Vanshaj Poonia --- docs/architecture/code-index-architecture.md | 6 +++--- docs/development/adding-language-support.md | 10 ++++++---- docs/features/code-index/overview.md | 1 + docs/features/integrations/claude-code.md | 3 ++- integrations/claude-code-plugin/hooks/HOOKS.md | 4 ++-- 5 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index bf88c937e4c..f73824ebf8c 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -297,8 +297,8 @@ Tree-sitter modules import lazily, so a server with the code workers off boots w Python search responses omit a prefixed class docstring when the skeleton already contains its text. -Files without a tree fall back to whole-line windows; lanes without a grammar cut on -their symbol spans (`lane_units.span_chunks`). A chunk id is +Files without a tree fall back to whole-line windows; lanes without a grammar, and Ruby, +cut on their symbol spans (`lane_units.span_chunks`, one chunk per method for Ruby). A chunk id is `uuid5("loom://code/{namespace}/{path}#{scope}@{sha16}")`. It is content-addressed, so an unchanged chunk keeps its id and hash and the embed step skips it without a lookup. Identical chunks in one file get an ordinal suffix. @@ -958,7 +958,7 @@ reach for a changed class or module-level chunk (see Cost). INI), a document (Markdown, reStructuredText, MDX, HTML), a style sheet, a Prisma schema, a FlatBuffers schema, an Angular component template, a file of Terraform values (`.tfvars`), a file with no extension, and a language with no parser (Kotlin, - Swift, C#, Ruby, PHP). A unit of such a file has no function of its own file to + Swift, C#, PHP). A unit of such a file has no function of its own file to follow, so it stays where the table scores it, among the functions. A namespace whose main language has no parser is therefore ranked as for a shorter question. A CMake file is among them as a config file, although its functions and macros are diff --git a/docs/development/adding-language-support.md b/docs/development/adding-language-support.md index ec1c13b9b1d..492c740f1e0 100644 --- a/docs/development/adding-language-support.md +++ b/docs/development/adding-language-support.md @@ -23,7 +23,7 @@ Add a new language where it moves no stamp: | `server/code/domain/extract/lang_.py` | no | The lane: `parse_(path, source) -> ParsedFile` with symbols, includes and call sites. | | `server/code/domain/extract/lang_detect.py` | no | `LANG_BY_EXTENSION` (and the shell rules): which files are this language. | | `server/code/app/index/ingest_parse.py` | no | A `_parse_` wrapper in `_PARSERS`; include resolution in `ingest_resolve.py` if the lane has imports. | -| `server/code/domain/extract/lane_units.py` | no | Shared helpers for a lane **without** a grammar: `span_chunks` and the `bind_sites` reference binder. | +| `server/code/domain/extract/lane_units.py` | no | Shared helpers for the `LANE_UNIT_LANGS` lanes: `span_chunks` and the `bind_sites` reference binder. | | `server/code/domain/extract/treesitter.py` | **yes** | `lang_for_path` for the stamped core languages only. Adding an extension here re-chunks every namespace. | | `chunker.py`, `edges_treesitter.py`, the other `STAGE_MODULES` | **yes** | Shared chunking and edge extraction. Change them only when the extraction itself changes for everyone. | @@ -35,21 +35,23 @@ Every module under `server/code/domain/extract/` is either in a stage of `STAGE_ | Shape | Examples | You provide | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Grammar lane | `lang_typescript.py`, `lang_rust.py`, `lang_go.py`, `lang_java.py` | A tree-sitter grammar dependency in `pyproject.toml`; symbols and call sites from the tree; chunks and edges come from the shared chunker and edge walker. | +| Grammar lane | `lang_typescript.py`, `lang_rust.py`, `lang_go.py`, `lang_java.py`, `lang_ruby.py` | A tree-sitter grammar dependency in `pyproject.toml`; symbols and sites from the tree; chunks and edges from the shared chunker and edge walker, or `lane_units` (below). | | Tree-less lane | `lang_proto.py`, `lang_thrift.py`, `lang_gotemplate.py`, `lang_hcl.py`, `lang_k8s.py`, `lang_jsonnet.py`, `lang_lua.py`, `lang_graphql.py` (`LANE_UNIT_LANGS`) | A hand-written scanner; `ParsedFile.tree` stays `None`; chunks from `lane_units.span_chunks`, edges from `reference_sites` + `SITE_RULES` bound by `lane_units.bind_sites`. | | Include-only lane | `tla`, `flatbuffers`, `cmake`, `doc` (`_LANE_INCLUDE_LANGS`) | Symbols and includes resolved by the simple lane resolver. | -| Embedded language | SQL inside Go and Java (`go_sql_units`, `java_sql_units`), shell islands in Dockerfiles and Makefiles | Units joined into the host file's parse (`_join_island_symbols`), usually behind a kill switch setting. | +| Embedded language | SQL inside Go, Java and Ruby (`go_sql_units`, `java_sql_units`, `ruby_sql_units`), shell islands in Dockerfiles and Makefiles | Units joined into the host file's parse (`_join_island_symbols`), usually behind a kill switch setting. | | Chunk-only | `.css`, text files (`lang_text.py`) | Nothing but detection: the file is chunked and searchable with no symbols. | A grammar lane's grammar is **not** in `STAMPED_GRAMMARS`, so upgrading it moves no stamp. The lane owns re-deriving its rows. +The shared chunker and edge walker are in the stamp and know only the stamped languages and the ones already in their tables. A new grammar lane keeps its tree but takes its chunks from `lane_units.span_chunks` and its call and inherits edges from `reference_sites` bound by `lane_units.bind_sites`, as a tree-less lane does. `lang_ruby.py` is the model: add the language to `LANE_UNIT_LANGS` and give the module `CHUNK_OPTIONS`, `SITE_RULES`, `reference_sites`, and `wanted_paths` and `resolve_imports` when it has imports. + ## 2. Write the parser `parse_(path: str, source: bytes) -> ParsedFile` returns the language tag, the symbols (`treesitter.Symbol`: qualified name, kind, span, signature), the includes and what the edge stage needs. Follow the nearest existing lane: - **Qualified names** follow the language's module path (Rust: the crate path from the file path; `mod.rs` / `lib.rs` name their directory). A symbol id hashes the qualified name and normalized signature, so an unstable name churns rows on every re-index. - **Includes** resolve against the paths the namespace holds (`wanted_paths`, then `resolve_imports` / `resolve_uses` in the lane, called from `ingest_resolve.py`). External packages resolve to nothing, not to a guess. -- **Call edges** bind same-file-unique names first, then repository-unique ones at lower confidence, and nothing when a name is ambiguous (`lane_units.bind_sites` does this for tree-less lanes). +- **Call edges** bind same-file-unique names first, then repository-unique ones at lower confidence, and nothing when a name is ambiguous (`lane_units.bind_sites` does this for the `LANE_UNIT_LANGS` lanes). - **Container kinds** (a class, an impl block) belong in the lane. Registering one in the chunker's per-language table changes `chunker.py` and moves the stamp. Register the lane: diff --git a/docs/features/code-index/overview.md b/docs/features/code-index/overview.md index 822e37fed05..caf7dbecadd 100644 --- a/docs/features/code-index/overview.md +++ b/docs/features/code-index/overview.md @@ -141,6 +141,7 @@ still gets file-level impact. | Go (`.go`) | yes | calls, inherits (interface embedding, structural implementation); SQL islands | `scip-go` | | Rust (`.rs`) | yes | calls, `use` imports, inherits (trait impls) | — | | Java (`.java`) | yes | calls (imports bind names, no import edges); SQL islands | — | +| Ruby (`.rb`, `.rake`, `.gemspec`, `Gemfile`, `Rakefile`) | yes | calls, `require` includes, inherits (superclasses, mixins); SQL islands | — | | Shell (`.sh`, `.bash`, `.bats`, shebang, rc files) | yes | calls (commands), `source` includes | — | | Prisma (`.prisma`) | yes | model relations | — | | Protocol Buffers (`.proto`), FlatBuffers (`.fbs`) | yes | imports, type uses | — | diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index 5bb4a477a0b..8e22bb5c511 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -668,7 +668,8 @@ JavaScript, Go, Rust and Java source a unit is a place when it is a definition ( function or method, a class, a named symbol); the file's leading comments and imports and its module-level code are not, and neither is any unit of a source file the index could not parse. A unit of any other file is a place: a notebook, a component file, SQL, -shell, configuration, and source the index reads as text (Kotlin, Ruby, PHP, C#, Swift). +shell, configuration, and source in a language that rule does not name (Kotlin, Ruby, +PHP, C#, Swift). A document is a place when the request asks for documentation or the prompt names the file: `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc`, a change log, release notes or a README by its name (`CHANGES`, `HISTORY` and `NEWS` as written, `changelog`, diff --git a/integrations/claude-code-plugin/hooks/HOOKS.md b/integrations/claude-code-plugin/hooks/HOOKS.md index 3e8cfbe8cee..5e3ac2fd370 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -869,8 +869,8 @@ in. symbol); the file's leading comments and imports and its module-level code are not, and neither is any unit of a source file the index could not parse. A unit of any other file is a place: a notebook, a component file, SQL, - shell, configuration, and source the index reads as text (Kotlin, Ruby, PHP, - C#, Swift). A document is a place when the request asks for documentation + shell, configuration, and source in a language not named above (Kotlin, Ruby, + PHP, C#, Swift). A document is a place when the request asks for documentation or the prompt names the file: `.md`, `.mdx`, `.markdown`, `.rst`, `.adoc`, a change log, release notes or a README by its name (`CHANGES`, `HISTORY` and `NEWS` as written, `changelog`, `release notes` and `readme` in any From 71d466019b54f271958ab4f463d1d53fb309a004 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:21:09 +0530 Subject: [PATCH 05/29] A bare word in a pattern guard, a rescue list or a superclass is a call site The tree hangs those words under node types `_VALUE_PARENTS` did not list, so `in x if allowed`, `rescue retryable => e`, `class A < base`, `lookup::Entry`, `class << target` and `END { flush }` recorded no site. A pinned `^(expr)` is read, not bound. Words after `return`, `break`, `next` and `yield` sit in an argument list and were already sites; the test keeps them. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 13 ++++++++- tests/unit/test_code_lang_ruby.py | 39 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 9f8ae02b1f1..669b754d63c 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -135,6 +135,15 @@ "block_argument", "method", "singleton_method", + "if_guard", + "unless_guard", + "expression_reference_pattern", + "exceptions", + "superclass", + "scope_resolution", + "singleton_class", + "begin_block", + "end_block", } ) # Methods of the language and of the libraries every Ruby program uses, and the @@ -444,13 +453,15 @@ def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[i def _collect(self, node: Any, scope: int) -> None: """Every identifier under `node` is a local variable of the scope, and so is the key - of a pattern's `key:` with no pattern of its own.""" + of a pattern's `key:` with no pattern of its own; a pinned `^(expr)` is read.""" if node is None: return names = self.locals.setdefault(scope, set()) stack = [node] while stack: n = stack.pop() + if n.type == "expression_reference_pattern": + continue key = n.child_by_field_name("key") if n.type == "keyword_pattern" else None if n.type == "identifier": names.add(node_text(n, self.source)) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 97f956d38b4..ffa04476d83 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -414,6 +414,45 @@ def test_bare_calls_in_loops_patterns_and_lists_are_sites() -> None: ] +def test_a_bare_word_after_a_jump_in_a_guard_or_in_a_rescue_list_is_a_site() -> None: + src = b"""class Job < base_job + def run(v) + jobs.each do + break halted if v + next queued + yield ready + end + return pending + case v + in Integer if allowed then 1 + in String unless blocked then 2 + in ^(limit) then 3 + end + lookup::Entry + class << target; end + rescue retryable => e + e + end +end +END { flush } +""" + assert reference_sites(parse_ruby("job.rb", src)) == [ + (1, "base_job", "bare"), + (3, "jobs", "bare"), + (4, "halted", "bare"), + (5, "queued", "bare"), + (6, "ready", "bare"), + (8, "pending", "bare"), + (10, "allowed", "bare"), + (11, "blocked", "bare"), + (12, "limit", "bare"), + (14, "lookup", "bare"), + (15, "target", "bare"), + (16, "retryable", "bare"), + (20, "flush", "bare"), + ] + + def test_a_class_reopened_in_its_own_file_is_one_target() -> None: src = b"""module Walk; end module Walk From 6df1f9b848217840c493626272dd0b1ef1b0fe0d Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:25:18 +0530 Subject: [PATCH 06/29] A method defined on an instance is not indexed as a method of its class In an instance method or a `define_method` block `self` is an instance, so `def self.x` and `class << self` there define on one object and name no class method. An eval block defines on its receiver: `Store.class_eval { def x }` is `Store#x`, `Store.instance_eval { def x }` is `Store.x`, and an eval on a variable names nothing, as `class << obj` already did. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 99 ++++++++++++++++--------- tests/unit/test_code_lang_ruby.py | 44 +++++++++++ 2 files changed, 110 insertions(+), 33 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 669b754d63c..92a17715885 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -84,6 +84,9 @@ _PATTERN_NODES = frozenset({"in_clause", "match_pattern", "test_pattern"}) _MIXINS = frozenset({"include", "extend", "prepend"}) _REQUIRES = frozenset({"require", "require_relative"}) +# the calls whose block a `def` lands in: on the receiver, or on its singleton +_EVALS = frozenset({"class_eval", "class_exec", "module_eval", "module_exec"}) +_INSTANCE_EVALS = frozenset({"instance_eval", "instance_exec"}) _STRING_NODES = frozenset({"string", "heredoc_beginning"}) _ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'"} _REQUIRE_LINE_RE = re.compile(rb"(?m)^[ \t]*require[ \t]+[\"']([^\"'\n]+)[\"']") @@ -259,6 +262,10 @@ def _string_literal(call: Any, source: bytes) -> str: return "".join(node_text(c, source) for c in first.named_children) # `%q(x)` too +# (owner names, a `def` is a singleton method, `self` is an instance) +_Context = tuple[tuple[str, ...], bool, bool] + + class _Reader: """The symbols and requires of one file, read from its tree without recursion.""" @@ -267,13 +274,13 @@ def __init__(self, pf: ParsedFile) -> None: self.requires: list[str] = [] def read(self, root: Any) -> None: - # (node, owner names, singleton, doc comment, the siblings before a class body) - stack: list[tuple[Any, tuple[str, ...], bool, str, tuple[Any, ...]]] = [ - (root, (), False, "", ()) + # (node, context, doc comment, the siblings before a class body) + stack: list[tuple[Any, _Context, str, tuple[Any, ...]]] = [ + (root, ((), False, False), "", ()) ] while stack: - node, names, single, doc, lead = stack.pop() - nxt = self._visit(node, names, single, doc) + node, ctx, doc, lead = stack.pop() + nxt = self._visit(node, ctx, doc) if nxt is None: continue kids = node.named_children @@ -287,30 +294,50 @@ def read(self, root: Any) -> None: kid_doc = doc # `private def x` takes the comment above the call # the tree hangs a comment before a body's first statement on the class kid_lead = tuple(kids[:i]) if kid.type == "body_statement" else () - stack.append((kid, nxt[0], nxt[1], kid_doc, kid_lead)) + stack.append((kid, nxt, kid_doc, kid_lead)) - def _visit( - self, node: Any, names: tuple[str, ...], single: bool, doc: str - ) -> tuple[tuple[str, ...], bool] | None: - """The owner names and singleton flag the node's children read under; None skips - them.""" + def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: + """The context the node's children read under; None skips them.""" + names, single, instance = ctx t = node.type if t in ("class", "module"): - return self._namespace(node, names, single, doc) + return self._namespace(node, ctx, doc) if t == "singleton_class": # `class << Const` reads as `def Const.x`; an object's singleton class names nothing value = node.child_by_field_name("value") if value is not None and value.type == "self": - return names, True + return None if instance else (names, True, False) owner = _const_parts(value, self.source)[0] if value is not None else [] - return (tuple(owner), True) if owner else None + return (tuple(owner), True, False) if owner else None if t == "method": self._method(node, names, single, doc) - elif t == "singleton_method": - self._singleton_method(node, names, doc) - elif t == "call": + return names, single, not single # an instance method runs on an instance + if t == "singleton_method": + return names, single, self._singleton_method(node, names, instance, doc) + if t == "call": self._require(node) - return names, single + return self._block_context(node, ctx) + return ctx + + def _block_context(self, call: Any, ctx: _Context) -> _Context | None: + """Where a `def` in the call's block lands: `define_method`'s block runs on an + instance, `X.class_eval`'s defines in X and `X.instance_eval`'s on X itself. None + for an eval on an object the file does not name.""" + names, single, instance = ctx + method = call.child_by_field_name("method") + if call.child_by_field_name("block") is None or method is None: + return ctx + name = node_text(method, self.source) + if name == "define_method": + return names, single, True + if name not in _EVALS and name not in _INSTANCE_EVALS: + return ctx + on_singleton = name in _INSTANCE_EVALS + receiver = call.child_by_field_name("receiver") + if receiver is None or receiver.type == "self": + return None if instance else (names, single or on_singleton, False) + owner = tuple(_const_parts(receiver, self.source)[0]) + return (owner, on_singleton, False) if owner else None def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: self.pf.symbols.append( @@ -326,23 +353,21 @@ def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> ) ) - def _namespace( - self, node: Any, names: tuple[str, ...], single: bool, doc: str - ) -> tuple[tuple[str, ...], bool]: + def _namespace(self, node: Any, ctx: _Context, doc: str) -> _Context: name_node = node.child_by_field_name("name") parts, rooted = ( _const_parts(name_node, self.source) if name_node is not None else ([], False) ) if not parts: - return names, single - inner = (*parts,) if rooted else (*names, *parts) + return ctx + inner = (*parts,) if rooted else (*ctx[0], *parts) sup = node.child_by_field_name("superclass") sig = f"{node.type} {node_text(name_node, self.source)}" if sup is not None and sup.named_children: sig += f" < {_squash(node_text(sup.named_children[0], self.source))}" kind = KIND_CLASS if node.type == "class" else KIND_MODULE self._add(f"{self.scope}::{'::'.join(inner)}", parts[-1], kind, sig, node, doc) - return inner, False + return inner, False, False def _method_qn(self, owner: tuple[str, ...], single: bool, name: str) -> str: if not owner: @@ -357,17 +382,25 @@ def _method(self, node: Any, names: tuple[str, ...], single: bool, doc: str) -> qn = self._method_qn(names, single, name) self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) - def _singleton_method(self, node: Any, names: tuple[str, ...], doc: str) -> None: + def _singleton_method( + self, node: Any, names: tuple[str, ...], instance: bool, doc: str + ) -> bool: + """`def self.x` or `def Const.x`; one on an instance or a variable names nothing. + Returns whether `self` in its body is an instance.""" name_node = node.child_by_field_name("name") target = node.child_by_field_name("object") - if name_node is None or target is None: - return - owner = names if target.type == "self" else tuple(_const_parts(target, self.source)[0]) - if target.type != "self" and not owner: - return - name = node_text(name_node, self.source) - qn = self._method_qn(owner, True, name) - self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) + owner: tuple[str, ...] | None + if target is None or target.type == "self": + owner = None if instance or target is None else names + body_instance = instance + else: + owner = tuple(_const_parts(target, self.source)[0]) or None + body_instance = owner is None + if name_node is not None and owner is not None: + name = node_text(name_node, self.source) + qn = self._method_qn(owner, True, name) + self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) + return body_instance def _require(self, call: Any) -> None: method = call.child_by_field_name("method") diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index ffa04476d83..e37ebf41ff8 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -191,6 +191,50 @@ def test_the_singleton_class_of_a_constant_holds_its_singleton_methods() -> None assert [s.qualified_name for s in parse_ruby("a.rb", src).symbols] == ["root.a::Config.load"] +def test_a_method_defined_on_an_instance_is_no_method_of_its_class() -> None: + # `self` in an instance method or a `define_method` block is an instance; an eval + # block defines on its receiver, and on nothing the file names for a variable + src = b"""class Session + def open + def self.close; end + class << self + def peek; end + end + def reset; end + end + + define_method(:touch) do + def self.stamp; end + end + + def self.build + def self.again; end + end + + instance_eval do + def made; end + end +end +Store.class_eval do + def fetch; end +end +Store.instance_eval { def connect; end } +helper.class_eval do + def hidden; end +end +""" + assert [s.qualified_name for s in parse_ruby("session.rb", src).symbols] == [ + "root.session::Session", + "root.session::Session#open", + "root.session::Session#reset", + "root.session::Session.build", + "root.session::Session.again", + "root.session::Session.made", + "root.session::Store#fetch", + "root.session::Store.connect", + ] + + def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: pf = parse_ruby("lib/billing.rb", BILLING) # `require_relative "x"` keeps a leading `./` so it resolves beside the file From 5a856507246ee34764a52be77eafd9e5ea2fd785 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:27:21 +0530 Subject: [PATCH 07/29] A method that starts on the last line of another is its own chunk `_top_level` read a unit starting on the previous unit's last line as nested, so `end; def second` folded `second` into the first chunk and left its other lines as an `other` chunk. Such a unit now has its own chunk, sharing that one line, and a comment above it belongs to the earlier unit. A unit wholly on the shared line still rides the earlier chunk. The other lane_units lanes cut the same chunks as before over the 21 lane fixtures and about 3,800 proto, thrift, gotemplate, hcl, k8s, jsonnet, lua and graphql files. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lane_units.py | 14 +++++++++----- tests/unit/test_code_lang_ruby.py | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 000a21336c1..497b67bbe50 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -54,7 +54,8 @@ class SiteRule: def _top_level(symbols: list[Symbol], kinds: frozenset[str] | None = None) -> list[Symbol]: """The symbols of `kinds` (any kind when None) no other of them encloses, in file - order.""" + order. One that starts on the last line of the previous block and runs past it + (`end; def b`) is a block of its own.""" ordered = sorted( (s for s in symbols if kinds is None or s.kind in kinds), key=lambda s: (s.start_line, -s.end_line), @@ -62,10 +63,10 @@ def _top_level(symbols: list[Symbol], kinds: frozenset[str] | None = None) -> li out: list[Symbol] = [] end = 0 for s in ordered: - if s.start_line <= end: + if s.start_line < end or s.end_line <= end: continue # inside the previous top-level block out.append(s) - end = max(end, s.end_line) + end = s.end_line return out @@ -160,13 +161,16 @@ def _unit_chunks( chunks: list[Chunk] = [] by_start = sorted(pf.symbols, key=lambda s: s.start_line) starts = [s.start_line for s in by_start] + prev_end = 0 for top in _top_level(pf.symbols, unit_kinds): start = _comment_run_above(src_lines, top.start_line, comment_leaders, comment_blocks) - start = max(1, min(start, top.start_line)) + # a comment above a unit that starts on the previous one's last line is that unit's + start = max(1, min(max(start, prev_end + 1), top.start_line)) end = min(top.end_line, n) + prev_end = top.end_line if end < start: continue - # units do not overlap, so each symbol is read for one unit at most + # units share a line at most, so each symbol is read for two units at most held = by_start[bisect_left(starts, top.start_line) : bisect_right(starts, top.end_line)] inner = [s.id for s in held if s is not top and s.end_line <= top.end_line] ids = [top.id, *dict.fromkeys(inner)] diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index e37ebf41ff8..359d9322572 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -625,6 +625,30 @@ def test_every_line_with_text_is_in_a_chunk_however_short() -> None: assert [(c.start_line, c.end_line, c.content) for c in chunks] == [(1, 5, gemfile.decode())] +def test_a_method_that_starts_on_the_last_line_of_another_is_its_own_chunk() -> None: + src = b"""class Pair + def first + # the comment of first + end; def second + 2 + end + def a; end; def b; end +end +""" + pf = parse_ruby("pair.rb", src) + chunks = span_chunks(pf, 6000, **CHUNK_OPTIONS) + assert [(c.kind, c.start_line, c.end_line, c.scope.rsplit("#", 1)[-1]) for c in chunks] == [ + ("other", 1, 1, ""), + ("function", 2, 4, "first"), + ("function", 4, 6, "second"), + ("function", 7, 7, "a"), + ("other", 8, 8, ""), + ] + # two methods on one line share its chunk + (line,) = (c for c in chunks if c.start_line == 7) + assert {s.name for s in pf.symbols if s.id in line.symbol_ids} == {"a", "b"} + + def test_chunks_count_lines_as_the_parser_does() -> None: # a form feed and a U+2028 end no line for the parser, so they end none for a chunk src = 'class A\n X = "a\u2028b"\n\x0c\n def one\n 1\n end\nend\n'.encode() From 4f17b0ba55d4466faf04ffcdbf3692f7d8987a4e Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:29:01 +0530 Subject: [PATCH 08/29] The SQL of a root Ruby file is scoped like its methods `code_sql_units` qualified statements and created objects with `module_scope`, which leaves a root file's scope undotted, so the name gate read them as native while the file's methods stayed script. The island grammar names the scope (`ruby_scope` for Ruby) and the units carry it, so the edge stage and the lane corpus name each statement as the parse did. Signed-off-by: Vanshaj Poonia --- server/code/app/index/ingest_edges.py | 24 +++++++++++-------- .../code/domain/extract/lang_code_islands.py | 8 +++++-- server/code/domain/extract/lang_ruby.py | 1 + tests/code_lanes/corpus.py | 21 +++++++++------- tests/unit/test_code_lang_ruby.py | 22 ++++++++++++++++- 5 files changed, 54 insertions(+), 22 deletions(-) diff --git a/server/code/app/index/ingest_edges.py b/server/code/app/index/ingest_edges.py index 18f40c03ddd..1e8def5e5cf 100644 --- a/server/code/app/index/ingest_edges.py +++ b/server/code/app/index/ingest_edges.py @@ -976,10 +976,11 @@ async def _sql_object_edges(repo: CodeRepo, org: str, ns: str, pf: ParsedFile) - names |= col.names table = await repo.name_candidates(org, ns, sorted(names)) if names else {} gated = gate_name_table(table, SQL_LANG) - edges = sql_edges(pf.path, module_scope(pf.path), statements, pf.symbols, gated, rw_kinds=True) + mod = module_scope(pf.path) + edges = sql_edges(pf.path, mod, statements, pf.symbols, gated, rw_kinds=True) if ju.dbt: edges.extend(jinja_edges(pf.path, ju, gated, rw_kinds=True)) - edges.extend(col.edges(pf, statements, gated)) + edges.extend(col.edges(pf, mod, statements, gated)) return edges @@ -1007,8 +1008,9 @@ def for_statements(cls, statements: list[Any]) -> _ColumnAsk: hyps = column_hypotheses(statements, known) return cls(known, hyps, hyps | column_names(statements, known)) - def edges(self, pf: ParsedFile, statements: list[Any], gated: dict[str, Any]) -> list[Any]: - from server.code.domain.extract.lang_python import module_scope + def edges( + self, pf: ParsedFile, mod: str, statements: list[Any], gated: dict[str, Any] + ) -> list[Any]: from server.code.domain.extract.lang_sql_columns import ( column_edges, known_from_name_table, @@ -1020,7 +1022,7 @@ def edges(self, pf: ParsedFile, statements: list[Any], gated: dict[str, Any]) -> known = merge_known(self.known, known_from_name_table(gated, self.hypotheses)) return column_edges( pf.path, - module_scope(pf.path), + mod, statements, known, pf.symbols, @@ -1036,15 +1038,17 @@ async def _py_island_edges(repo: CodeRepo, org: str, ns: str, pf: ParsedFile) -> from server.code.domain.extract.lang_python import module_scope from server.code.domain.extract.lang_sql_objects import reference_names, sql_edges - statements = ( - py_sql_units(pf).statements if pf.lang == "python" else _code_sql_units(pf).statements - ) + if pf.lang == "python": + statements, mod = py_sql_units(pf).statements, module_scope(pf.path) + else: + units = _code_sql_units(pf) + statements, mod = units.statements, units.scope # the scope the parse named them by if not statements: return [] col = _ColumnAsk.for_statements(statements) names = reference_names(statements) | col.names table = await repo.name_candidates(org, ns, sorted(names)) if names else {} gated = gate_name_table(table, SQL_LANG) - edges = sql_edges(pf.path, module_scope(pf.path), statements, pf.symbols, gated, rw_kinds=True) - edges.extend(col.edges(pf, statements, gated)) + edges = sql_edges(pf.path, mod, statements, pf.symbols, gated, rw_kinds=True) + edges.extend(col.edges(pf, mod, statements, gated)) return edges diff --git a/server/code/domain/extract/lang_code_islands.py b/server/code/domain/extract/lang_code_islands.py index 6e145d15033..e07b57819da 100644 --- a/server/code/domain/extract/lang_code_islands.py +++ b/server/code/domain/extract/lang_code_islands.py @@ -75,10 +75,14 @@ class IslandGrammar: # argument starts the chain chain_methods: frozenset[str] = frozenset() chain_seed_node: str = "" + # the scope a file's statements are qualified by: the language's, so they class as its + # definitions do + scope: Callable[[str], str] = module_scope @dataclass class CodeSqlUnits: + scope: str = "" # the statements' and objects' scope, which the edge stage names them by islands: list[Island] = field(default_factory=list) statements: list[Statement] = field(default_factory=list) symbols: list[Symbol] = field(default_factory=list) @@ -482,12 +486,12 @@ def code_sql_units(pf: ParsedFile, g: IslandGrammar, file_default: str = "") -> """Statements, symbols (statement records, created objects, columns when column lineage is on) and facets for the SQL a file runs.""" islands = settle_dialects(find_code_islands(pf, g), file_default) - units = CodeSqlUnits(islands=islands) + mod = g.scope(pf.path) + units = CodeSqlUnits(scope=mod, islands=islands) if not islands: return units pairs = island_statements(islands) statements = [st for st, _ in pairs] - mod = module_scope(pf.path) units.statements = statements symbols = [statement_symbol(pf.path, mod, st) for st in statements] symbols.extend(object_symbols(pf.path, mod, statements)) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 92a17715885..8cc020d2ac3 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -704,6 +704,7 @@ def _heredoc_bodies(root: Any) -> dict[int, Any]: concat_node="binary", assign_nodes=(("assignment", "left", "right"),), aug_assign_node=("operator_assignment", "left", "operator", "right"), + scope=ruby_scope, ) diff --git a/tests/code_lanes/corpus.py b/tests/code_lanes/corpus.py index e369fad588f..3a7afb5affc 100644 --- a/tests/code_lanes/corpus.py +++ b/tests/code_lanes/corpus.py @@ -587,17 +587,19 @@ def _summarize() -> dict[str, Any]: es = [*es, *sql_edges(rel, module_scope(rel), statements, pf.symbols, gated)] if ju.dbt: es.extend(jinja_edges(rel, ju, gated)) - es.extend(_column_edges(rel, statements, pf, gated)) + es.extend(_column_edges(rel, module_scope(rel), statements, pf, gated)) if pf.lang in ("python", "go", "java", "ruby"): # The islands' table edges bind through the # SQL gate, as `ingest._py_island_edges` gates them — a Go caller # may reach a table, a Go call site may not - statements = ( - py_sql_units(pf).statements if pf.lang == "python" else _code_units(pf).statements - ) + if pf.lang == "python": + statements, mod = py_sql_units(pf).statements, module_scope(rel) + else: + units = _code_units(pf) + statements, mod = units.statements, units.scope sql_gated = gate_name_table(name_table, SQL_LANG) - es = [*es, *sql_edges(rel, module_scope(rel), statements, pf.symbols, sql_gated)] - es.extend(_column_edges(rel, statements, pf, sql_gated)) + es = [*es, *sql_edges(rel, mod, statements, pf.symbols, sql_gated)] + es.extend(_column_edges(rel, mod, statements, pf, sql_gated)) if pf.lang in ts_langs or pf.lang in ( "rust", "proto", @@ -691,10 +693,11 @@ def _code_units(pf: Any) -> Any: return java_sql_units(pf) -def _column_edges(rel: str, statements: list[Any], pf: Any, gated: dict[str, Any]) -> list[Any]: +def _column_edges( + rel: str, mod: str, statements: list[Any], pf: Any, gated: dict[str, Any] +) -> list[Any]: """The column edges as `ingest._ColumnAsk` derives them: the file's own columns plus the corpus-confirmed hypotheses, then statement → column.""" - from server.code.domain.extract.lang_python import module_scope from server.code.domain.extract.lang_sql_columns import ( column_edges, column_hypotheses, @@ -706,7 +709,7 @@ def _column_edges(rel: str, statements: list[Any], pf: Any, gated: dict[str, Any known = file_columns(statements) hyps = column_hypotheses(statements, known) known = merge_known(known, known_from_name_table(gated, hyps)) - return column_edges(rel, module_scope(rel), statements, known, pf.symbols, gated) + return column_edges(rel, mod, statements, known, pf.symbols, gated) def main(argv: list[str] | None = None) -> int: diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 359d9322572..b764de298b8 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -12,7 +12,7 @@ pytest.importorskip("tree_sitter_ruby") from server.code.app.index.ingest_chunks import _chunks_for -from server.code.app.index.ingest_edges import _lane_site_edges +from server.code.app.index.ingest_edges import _lane_site_edges, _py_island_edges from server.code.app.index.ingest_parse import parse_for_ingest from server.code.app.index.ingest_resolve import _resolve_lane_includes from server.code.domain.extract.lane_units import bind_sites, span_chunks @@ -754,6 +754,26 @@ def test_the_ingest_resolves_includes_cuts_chunks_and_binds_edges_for_a_ruby_fil assert "find_by_sql" in repo.asked and not {"connection", "owner"} & set(repo.asked) +def test_the_sql_of_a_root_file_is_scoped_like_its_methods() -> None: + src = b"""class Setup + def run + connection.execute("CREATE TABLE entries (id Int64)") + connection.execute("INSERT INTO entries SELECT 1") + end +end +""" + pf, err = parse_for_ingest("setup.rb", src) + assert err == "" and pf is not None + assert {s.qualified_name.split("::")[0] for s in pf.symbols} == {"root.setup"} + assert {qualified_name_class(s.qualified_name) for s in pf.symbols} == {"script"} + # the edge stage names each statement as the parse did + edges = asyncio.run(_py_island_edges(_Repo(set(), {}), "o", "n", pf)) + assert [(e.edge_kind, e.to_qualified_name) for e in edges] == [ + ("writes", "root.setup::entries") + ] + assert {e.from_symbol_id for e in edges} <= {s.id for s in pf.symbols} + + @pytest.mark.parametrize( "unit", [ From 896b0b38fb209e489b9b7be05c1bbc60ec73bfbe Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:29:29 +0530 Subject: [PATCH 09/29] The Ruby lane's doc comment cut is marked as no setting `test_no_new_tunable_constant` failed CI on `lang_ruby._MAX_DOC`. Like the other lanes' cuts it shapes every stored doc_comment, so it carries the `# not a setting:` reason instead of joining the shrinking list. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 8cc020d2ac3..53e75aa32cc 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -78,7 +78,7 @@ "query": "", } -_MAX_DOC = 2000 +_MAX_DOC = 2000 # not a setting: the cut every doc_comment of this lane takes _DEF_NODES = frozenset({"class", "module", "method", "singleton_method"}) _PARAMETER_NODES = frozenset({"method_parameters", "block_parameters", "lambda_parameters"}) _PATTERN_NODES = frozenset({"in_clause", "match_pattern", "test_pattern"}) From b64b8d2a82602fae929a337d21ad9a7ea9c59132 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:31:15 +0530 Subject: [PATCH 10/29] The overview lists Ruby beside Lua so the translated table keeps its rows The committed translations check matches table cells by position. Ruby above the Protocol Buffers row moved that row, so the zh-CN page failed on its protected names. Below Lua it shifts no row that holds one. Signed-off-by: Vanshaj Poonia --- docs/features/code-index/overview.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/features/code-index/overview.md b/docs/features/code-index/overview.md index caf7dbecadd..e86bd9ad6f6 100644 --- a/docs/features/code-index/overview.md +++ b/docs/features/code-index/overview.md @@ -141,7 +141,6 @@ still gets file-level impact. | Go (`.go`) | yes | calls, inherits (interface embedding, structural implementation); SQL islands | `scip-go` | | Rust (`.rs`) | yes | calls, `use` imports, inherits (trait impls) | — | | Java (`.java`) | yes | calls (imports bind names, no import edges); SQL islands | — | -| Ruby (`.rb`, `.rake`, `.gemspec`, `Gemfile`, `Rakefile`) | yes | calls, `require` includes, inherits (superclasses, mixins); SQL islands | — | | Shell (`.sh`, `.bash`, `.bats`, shebang, rc files) | yes | calls (commands), `source` includes | — | | Prisma (`.prisma`) | yes | model relations | — | | Protocol Buffers (`.proto`), FlatBuffers (`.fbs`) | yes | imports, type uses | — | @@ -150,6 +149,7 @@ still gets file-level impact. | Terraform / HCL (`.tf`, `.tfvars`, `.hcl`), Kubernetes manifests | yes | references (`reads`) | — | | Jsonnet (`.jsonnet`, `.libsonnet`) | yes | calls, imports | — | | Lua (`.lua`) | yes | calls, `require` includes | — | +| Ruby (`.rb`, `.rake`, `.gemspec`, `Gemfile`, `Rakefile`) | yes | calls, `require` includes, inherits (superclasses, mixins); SQL islands | — | | GraphQL schemas (`.graphql`, `.gql`) | yes | type uses, inherits (`implements`) | — | | TLA+ (`.tla`, TLC configs), CMake (`CMakeLists.txt`, `.cmake`) | yes | includes; TLA+ operators; the CMake link graph | — | | Markdown and docs (`.md`, `.mdc`, `.mdx`, `.rst`, `.html`, `.htm`) | sections (`.md` only) | relative links, backticked names as `reads` to the code | — | From 7316e3a7a8d2d3864ab5fd94550df8faa5d3cf82 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:32:40 +0530 Subject: [PATCH 11/29] A root Ruby file's tables keep their dialect when an island narrows by it `_scope_dialects_for` keyed each defining file's dialect by `module_scope`, and `narrow_by_dialect` looks a candidate up by the scope in its qualified name. A root Ruby file's table is now `root.::t`, so the two never met. The map is keyed by each candidate's own scope. Signed-off-by: Vanshaj Poonia --- server/code/app/index/ingest_edges.py | 23 +++++++++++++---------- tests/unit/test_code_lang_ruby.py | 21 ++++++++++++++++++++- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/server/code/app/index/ingest_edges.py b/server/code/app/index/ingest_edges.py index 1e8def5e5cf..428032c6752 100644 --- a/server/code/app/index/ingest_edges.py +++ b/server/code/app/index/ingest_edges.py @@ -943,21 +943,24 @@ async def _scope_dialects_for( ) -> dict[str, str]: """{module scope: dialect} for the defining files of every name the table holds MORE than one definition of — the file-level `dialect` facet that `narrow_by_dialect` - reads. One id → path read, then one facet read per path; a file whose tables are all - unambiguous pays nothing.""" - from server.code.domain.extract.lang_python import module_scope - - ambiguous_ids = [c[0] for cands in table.values() if len(cands) > 1 for c in cands] - if not ambiguous_ids: + reads, keyed by the scope each candidate is named in (a root Ruby file's is + `root.`). One id → path read, then one facet read per path; a file whose tables + are all unambiguous pays nothing.""" + ambiguous = [c for cands in table.values() if len(cands) > 1 for c in cands][:200] + if not ambiguous: return {} - paths = await repo.symbol_paths_for_ids(org, ns, ambiguous_ids[:200]) - out: dict[str, str] = {} + paths = await repo.symbol_paths_for_ids(org, ns, [c[0] for c in ambiguous]) + by_path: dict[str, str] = {} for path in sorted(set(paths.values())): for f in await repo.live_facets_for_path(org, ns, path): if str(f["facet_kind"]) == "dialect" and int(f["ordinal"]) == 0: - out[module_scope(path)] = str(f["name"]) + by_path[path] = str(f["name"]) break - return out + return { + qn.split("::", 1)[0]: by_path[paths[sid]] + for sid, qn, _kind in ambiguous + if paths.get(sid) in by_path + } async def _sql_object_edges(repo: CodeRepo, org: str, ns: str, pf: ParsedFile) -> list[Any]: diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index b764de298b8..3143b61efe8 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -12,7 +12,11 @@ pytest.importorskip("tree_sitter_ruby") from server.code.app.index.ingest_chunks import _chunks_for -from server.code.app.index.ingest_edges import _lane_site_edges, _py_island_edges +from server.code.app.index.ingest_edges import ( + _lane_site_edges, + _py_island_edges, + _scope_dialects_for, +) from server.code.app.index.ingest_parse import parse_for_ingest from server.code.app.index.ingest_resolve import _resolve_lane_includes from server.code.domain.extract.lane_units import bind_sites, span_chunks @@ -27,6 +31,7 @@ wanted_paths, ) from server.code.domain.extract.lang_text import text_lang_for_path +from server.code.domain.extract.lang_ts_islands import narrow_by_dialect from server.code.domain.extract.name_scope import qualified_name_class from server.code.domain.extract.treesitter import ParsedFile from tests.unit.code_fixtures import assert_linear @@ -774,6 +779,20 @@ def run assert {e.from_symbol_id for e in edges} <= {s.id for s in pf.symbols} +def test_a_root_files_table_keeps_its_dialect_when_an_island_narrows_by_it() -> None: + class Repo: + async def symbol_paths_for_ids(self, org: str, ns: str, ids: list[str]) -> Any: + return {"rb": "setup.rb", "ch": "db/ch.sql"} + + async def live_facets_for_path(self, org: str, ns: str, path: str) -> Any: + name = "postgres" if path == "setup.rb" else "clickhouse" + return [{"facet_kind": "dialect", "ordinal": 0, "name": name}] + + table = {"entries": [("rb", "root.setup::entries", "table"), ("ch", "db.ch::entries", "table")]} + dialects = asyncio.run(_scope_dialects_for(Repo(), "o", "n", table)) # type: ignore[arg-type] + assert narrow_by_dialect(table, "postgres", dialects)["entries"] == [table["entries"][0]] + + @pytest.mark.parametrize( "unit", [ From 0c56bb522094f1a84677656b47dcb73fd34468fb Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:33:51 +0530 Subject: [PATCH 12/29] A class built by Struct.new or Class.new holds the methods of its block `Point = Struct.new(:x) do def norm; end end` inside `module Geo` indexed `Geo#norm`, a method Geo does not have. The block's defs are now `Geo::Point`'s, for `Struct.new`, `Class.new`, `Module.new` and `Data.define` assigned to a constant. One no constant names holds nothing the index can name, as an eval on a variable. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 16 ++++++++++--- tests/unit/test_code_lang_ruby.py | 30 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 53e75aa32cc..3b382e9bd05 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -87,6 +87,9 @@ # the calls whose block a `def` lands in: on the receiver, or on its singleton _EVALS = frozenset({"class_eval", "class_exec", "module_eval", "module_exec"}) _INSTANCE_EVALS = frozenset({"instance_eval", "instance_exec"}) +_CLASS_BUILDERS = frozenset( + {("Struct", "new"), ("Class", "new"), ("Module", "new"), ("Data", "define")} +) _STRING_NODES = frozenset({"string", "heredoc_beginning"}) _ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'"} _REQUIRE_LINE_RE = re.compile(rb"(?m)^[ \t]*require[ \t]+[\"']([^\"'\n]+)[\"']") @@ -321,19 +324,26 @@ def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: def _block_context(self, call: Any, ctx: _Context) -> _Context | None: """Where a `def` in the call's block lands: `define_method`'s block runs on an - instance, `X.class_eval`'s defines in X and `X.instance_eval`'s on X itself. None - for an eval on an object the file does not name.""" + instance, `X.class_eval`'s and `X = Struct.new`'s define in X and + `X.instance_eval`'s on X itself. None for a class or object the file does not name.""" names, single, instance = ctx method = call.child_by_field_name("method") if call.child_by_field_name("block") is None or method is None: return ctx name = node_text(method, self.source) + receiver = call.child_by_field_name("receiver") if name == "define_method": return names, single, True + if receiver is not None and (node_text(receiver, self.source), name) in _CLASS_BUILDERS: + # `Point = Struct.new(:x) do … end` defines in Point; a class no constant names + # holds nothing the index can name + parent = call.parent + left = parent.child_by_field_name("left") if parent.type == "assignment" else None + parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) + return ((*parts,) if rooted else (*names, *parts), False, False) if parts else None if name not in _EVALS and name not in _INSTANCE_EVALS: return ctx on_singleton = name in _INSTANCE_EVALS - receiver = call.child_by_field_name("receiver") if receiver is None or receiver.type == "self": return None if instance else (names, single or on_singleton, False) owner = tuple(_const_parts(receiver, self.source)[0]) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 3143b61efe8..89f75ad0cf6 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -240,6 +240,36 @@ def hidden; end ] +def test_a_class_built_by_a_call_holds_the_methods_of_its_block() -> None: + src = b"""module Geo + Point = Struct.new(:x, :y) do + def norm; end + end + Shape = Class.new(Base) { def area; end } + Pos = Data.define(:lat) do + def self.origin; end + end + Mixin = Module.new do + def mixed; end + end + def self.build + anon = Class.new do + def hidden; end + end + end +end +""" + # a class no constant names holds nothing the index can name + assert [s.qualified_name for s in parse_ruby("geo.rb", src).symbols] == [ + "root.geo::Geo", + "root.geo::Geo::Point#norm", + "root.geo::Geo::Shape#area", + "root.geo::Geo::Pos.origin", + "root.geo::Geo::Mixin#mixed", + "root.geo::Geo.build", + ] + + def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: pf = parse_ruby("lib/billing.rb", BILLING) # `require_relative "x"` keeps a leading `./` so it resolves beside the file From 8c9db6854539ae9988831d5c767f6483ba61da07 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:39:28 +0530 Subject: [PATCH 13/29] The dialect narrowing test passes its fake repository as Any, as the file's other fakes do A type: ignore on the call hid what the fake stands in for. Signed-off-by: Vanshaj Poonia --- tests/unit/test_code_lang_ruby.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 89f75ad0cf6..d71ec953914 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -819,7 +819,8 @@ async def live_facets_for_path(self, org: str, ns: str, path: str) -> Any: return [{"facet_kind": "dialect", "ordinal": 0, "name": name}] table = {"entries": [("rb", "root.setup::entries", "table"), ("ch", "db.ch::entries", "table")]} - dialects = asyncio.run(_scope_dialects_for(Repo(), "o", "n", table)) # type: ignore[arg-type] + repo: Any = Repo() + dialects = asyncio.run(_scope_dialects_for(repo, "o", "n", table)) assert narrow_by_dialect(table, "postgres", dialects)["entries"] == [table["entries"][0]] From 8fc9b0d18389fc2e33b9ed3bc0af8b9e6ff98848 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:54:33 +0530 Subject: [PATCH 14/29] A call inside SQL that creates a table or function binds from its method `_enclosing_by_line` skipped the statement symbol but not the objects it creates, which share its span. An interpolated call in `CREATE TABLE` or `CREATE FUNCTION` bound from the table or the SQL function. The SQL's symbols follow the lane's own in the parse, statements first, so the walk stops at the first statement; a one-line method holding a statement keeps its calls. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lane_units.py | 6 +++-- tests/unit/test_code_lang_ruby.py | 30 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 497b67bbe50..7575de4914f 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -280,8 +280,10 @@ def _leftover_chunks( def _enclosing_by_line(pf: ParsedFile, lines: set[int]) -> dict[int, Symbol]: """The innermost symbol around each line (the first of two alike spans), in one sweep. - An embedded SQL statement is never one: a call written in it is its method's.""" - starts = sorted((s.start_line, i) for i, s in enumerate(pf.symbols) if s.kind != STATEMENT_KIND) + The SQL a file runs gives none: its symbols, statements first, follow the lane's own + (`ingest_parse._join_island_symbols`), and a call written in it is its method's.""" + own = next((i for i, s in enumerate(pf.symbols) if s.kind == STATEMENT_KIND), len(pf.symbols)) + starts = sorted((s.start_line, i) for i, s in enumerate(pf.symbols[:own])) open_spans: list[tuple[int, int]] = [] # (span length, index in pf.symbols) out: dict[int, Symbol] = {} k = 0 diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index d71ec953914..942b891c28d 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -569,6 +569,36 @@ def test_a_call_inside_a_sql_string_binds_from_its_method_not_the_statement() -> } +def test_a_call_inside_sql_that_creates_an_object_binds_from_its_method() -> None: + src = b"""require "pg" +class Migration + def up + execute <<~SQL + CREATE TABLE users (name text DEFAULT '#{default_name}') + SQL + execute <<~SQL + CREATE FUNCTION bump(i int) RETURNS int AS $$ SELECT i + #{step} $$ LANGUAGE sql + SQL + end + def purge = execute("CREATE INDEX idx ON users (#{column})") + def default_name; end + def step; end + def column; end +end +""" + pf, err = parse_for_ingest("db/migrate/001_users.rb", src) + assert err == "" and pf is not None + assert {"table", "function", "index"} <= {s.kind for s in pf.symbols if s.start_line > 4} + edges = bind_sites(pf, reference_sites(pf), _table(pf), SITE_RULES) + assert [ + (e.from_qualified_name.split("::", 1)[1], e.to_qualified_name, e.line) for e in edges + ] == [ + ("Migration#up", "db.migrate.001_users::Migration#default_name", 5), + ("Migration#up", "db.migrate.001_users::Migration#step", 8), + ("Migration#purge", "db.migrate.001_users::Migration#column", 11), + ] + + def test_a_base_class_in_another_file_binds_at_the_repository_rung() -> None: base = parse_ruby("lib/base.rb", b"module Ledger\n class Account; end\nend\n") sub = parse_ruby("lib/report.rb", b"module Ledger\n class Report < Account; end\nend\n") From 3acdaa5b488afedfd8bb8509837ea153cf9f907d Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:55:00 +0530 Subject: [PATCH 15/29] A class named like its base in another file inherits from it At the repository rung `bind_sites` kept the caller among the candidates, so `class Admin::User < ::User` saw two `User` definitions and bound neither. Nothing inherits from itself, so an `inherits` site drops the caller there, as the same-file rung does. The thrift and GraphQL `inherits` rules lose nothing: a service or interface never names itself. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lane_units.py | 8 +++++++- tests/unit/test_code_lang_ruby.py | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 7575de4914f..4aedba7cdd0 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -336,7 +336,13 @@ def bind_sites( elif mine: continue # several same-file definitions: ambiguous elif rule.allow_repo_wide: - cands = [c for c in name_table.get(name, []) if c[2] in rule.target_kinds] + # nothing inherits from itself: `class Admin::User < ::User` names another User + cands = [ + c + for c in name_table.get(name, []) + if c[2] in rule.target_kinds + and not (rule.edge_kind == "inherits" and c[1] == src.qualified_name) + ] if len({c[1] for c in cands}) != 1: continue to_id, to_qn, conf = cands[0][0], cands[0][1], REPO_WIDE_CONFIDENCE diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 942b891c28d..0a9bf95cef9 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -599,6 +599,19 @@ def column; end ] +def test_a_class_named_like_its_base_in_another_file_inherits_from_it() -> None: + base = parse_ruby("app/models/user.rb", b"class User; end\n") + sub = parse_ruby( + "app/models/admin/user.rb", b"module Admin\n class User < ::User\n end\nend\n" + ) + (edge,) = bind_sites(sub, reference_sites(sub), _table(base, sub), SITE_RULES) + assert (edge.edge_kind, edge.from_qualified_name, edge.to_qualified_name) == ( + "inherits", + "app.models.admin.user::Admin::User", + "app.models.user::User", + ) + + def test_a_base_class_in_another_file_binds_at_the_repository_rung() -> None: base = parse_ruby("lib/base.rb", b"module Ledger\n class Account; end\nend\n") sub = parse_ruby("lib/report.rb", b"module Ledger\n class Report < Account; end\nend\n") From db30bc970663c15f4bf35b877203472bc9c8cb54 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:56:12 +0530 Subject: [PATCH 16/29] An eval without a receiver defines on what self is, not where a def would land The reader's context said where a plain `def` lands but not what `self` is, so `class_eval` in a method of `class << self` defined singleton methods. In that method `self` is the class and Ruby defines instance methods. The context now names `self` as a class, a singleton class or an instance, and an eval with no receiver reads it. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 46 +++++++++++++------------ tests/unit/test_code_lang_ruby.py | 30 ++++++++++++++++ 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 3b382e9bd05..89c4f79af9b 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -265,8 +265,10 @@ def _string_literal(call: Any, source: bytes) -> str: return "".join(node_text(c, source) for c in first.named_children) # `%q(x)` too -# (owner names, a `def` is a singleton method, `self` is an instance) -_Context = tuple[tuple[str, ...], bool, bool] +# what `self` is where a node reads: a class, a singleton class or an instance +_CLASS, _META, _INSTANCE = "class", "singleton class", "instance" +# (owner names, a `def` is a singleton method, what `self` is) +_Context = tuple[tuple[str, ...], bool, str] class _Reader: @@ -279,7 +281,7 @@ def __init__(self, pf: ParsedFile) -> None: def read(self, root: Any) -> None: # (node, context, doc comment, the siblings before a class body) stack: list[tuple[Any, _Context, str, tuple[Any, ...]]] = [ - (root, ((), False, False), "", ()) + (root, ((), False, _CLASS), "", ()) ] while stack: node, ctx, doc, lead = stack.pop() @@ -301,7 +303,7 @@ def read(self, root: Any) -> None: def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: """The context the node's children read under; None skips them.""" - names, single, instance = ctx + names, single, self_is = ctx t = node.type if t in ("class", "module"): return self._namespace(node, ctx, doc) @@ -309,14 +311,14 @@ def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: # `class << Const` reads as `def Const.x`; an object's singleton class names nothing value = node.child_by_field_name("value") if value is not None and value.type == "self": - return None if instance else (names, True, False) + return None if self_is == _INSTANCE else (names, True, _META) owner = _const_parts(value, self.source)[0] if value is not None else [] - return (tuple(owner), True, False) if owner else None + return (tuple(owner), True, _META) if owner else None if t == "method": self._method(node, names, single, doc) - return names, single, not single # an instance method runs on an instance + return names, single, _CLASS if single else _INSTANCE if t == "singleton_method": - return names, single, self._singleton_method(node, names, instance, doc) + return names, single, self._singleton_method(node, names, self_is, doc) if t == "call": self._require(node) return self._block_context(node, ctx) @@ -326,28 +328,30 @@ def _block_context(self, call: Any, ctx: _Context) -> _Context | None: """Where a `def` in the call's block lands: `define_method`'s block runs on an instance, `X.class_eval`'s and `X = Struct.new`'s define in X and `X.instance_eval`'s on X itself. None for a class or object the file does not name.""" - names, single, instance = ctx + names, single, self_is = ctx method = call.child_by_field_name("method") if call.child_by_field_name("block") is None or method is None: return ctx name = node_text(method, self.source) receiver = call.child_by_field_name("receiver") if name == "define_method": - return names, single, True + return names, single, _INSTANCE if receiver is not None and (node_text(receiver, self.source), name) in _CLASS_BUILDERS: # `Point = Struct.new(:x) do … end` defines in Point; a class no constant names # holds nothing the index can name parent = call.parent left = parent.child_by_field_name("left") if parent.type == "assignment" else None parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) - return ((*parts,) if rooted else (*names, *parts), False, False) if parts else None + return ((*parts,) if rooted else (*names, *parts), False, _CLASS) if parts else None if name not in _EVALS and name not in _INSTANCE_EVALS: return ctx on_singleton = name in _INSTANCE_EVALS if receiver is None or receiver.type == "self": - return None if instance else (names, single or on_singleton, False) + if self_is == _INSTANCE: + return None + return names, self_is == _META or on_singleton, self_is owner = tuple(_const_parts(receiver, self.source)[0]) - return (owner, on_singleton, False) if owner else None + return (owner, on_singleton, _CLASS) if owner else None def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: self.pf.symbols.append( @@ -377,7 +381,7 @@ def _namespace(self, node: Any, ctx: _Context, doc: str) -> _Context: sig += f" < {_squash(node_text(sup.named_children[0], self.source))}" kind = KIND_CLASS if node.type == "class" else KIND_MODULE self._add(f"{self.scope}::{'::'.join(inner)}", parts[-1], kind, sig, node, doc) - return inner, False, False + return inner, False, _CLASS def _method_qn(self, owner: tuple[str, ...], single: bool, name: str) -> str: if not owner: @@ -392,25 +396,23 @@ def _method(self, node: Any, names: tuple[str, ...], single: bool, doc: str) -> qn = self._method_qn(names, single, name) self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) - def _singleton_method( - self, node: Any, names: tuple[str, ...], instance: bool, doc: str - ) -> bool: + def _singleton_method(self, node: Any, names: tuple[str, ...], self_is: str, doc: str) -> str: """`def self.x` or `def Const.x`; one on an instance or a variable names nothing. - Returns whether `self` in its body is an instance.""" + Returns what `self` is in its body: the object it is defined on.""" name_node = node.child_by_field_name("name") target = node.child_by_field_name("object") owner: tuple[str, ...] | None if target is None or target.type == "self": - owner = None if instance or target is None else names - body_instance = instance + owner = None if self_is == _INSTANCE or target is None else names + body_self = self_is else: owner = tuple(_const_parts(target, self.source)[0]) or None - body_instance = owner is None + body_self = _INSTANCE if owner is None else _CLASS if name_node is not None and owner is not None: name = node_text(name_node, self.source) qn = self._method_qn(owner, True, name) self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) - return body_instance + return body_self def _require(self, call: Any) -> None: method = call.child_by_field_name("method") diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 0a9bf95cef9..2e4bcb0f6c1 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -270,6 +270,36 @@ def hidden; end ] +def test_an_eval_without_a_receiver_defines_on_what_self_is() -> None: + # `self` is the class in a method of `class << self`, and its singleton class beside them + src = b"""class A + class << self + def c + class_eval do + def w; end + end + end + class_eval do + def s; end + end + end + def self.d + class_eval do + def v; end + end + end +end +""" + assert [s.qualified_name for s in parse_ruby("a.rb", src).symbols] == [ + "root.a::A", + "root.a::A.c", + "root.a::A#w", + "root.a::A.s", + "root.a::A.d", + "root.a::A#v", + ] + + def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: pf = parse_ruby("lib/billing.rb", BILLING) # `require_relative "x"` keeps a leading `./` so it resolves beside the file From 0e06e7c5eb5dab64b3e45c36b59fc61f3ee0970d Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:57:15 +0530 Subject: [PATCH 17/29] A built class keeps its name through ::Struct, a chained call and ||= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The builder match read the receiver's text, so `::Struct.new` missed, and it took the name only from a direct `=`. `Frozen = Struct.new do … end.freeze` and `Lazy ||= Class.new do … end` named nothing. The receiver is read as a constant and the name is taken through calls chained on the block and `||=`. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 25 ++++++++++++++++++------- tests/unit/test_code_lang_ruby.py | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 89c4f79af9b..dfb7326c08a 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -90,6 +90,7 @@ _CLASS_BUILDERS = frozenset( {("Struct", "new"), ("Class", "new"), ("Module", "new"), ("Data", "define")} ) +_ASSIGNMENTS = frozenset({"assignment", "operator_assignment"}) _STRING_NODES = frozenset({"string", "heredoc_beginning"}) _ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'"} _REQUIRE_LINE_RE = re.compile(rb"(?m)^[ \t]*require[ \t]+[\"']([^\"'\n]+)[\"']") @@ -336,13 +337,9 @@ def _block_context(self, call: Any, ctx: _Context) -> _Context | None: receiver = call.child_by_field_name("receiver") if name == "define_method": return names, single, _INSTANCE - if receiver is not None and (node_text(receiver, self.source), name) in _CLASS_BUILDERS: - # `Point = Struct.new(:x) do … end` defines in Point; a class no constant names - # holds nothing the index can name - parent = call.parent - left = parent.child_by_field_name("left") if parent.type == "assignment" else None - parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) - return ((*parts,) if rooted else (*names, *parts), False, _CLASS) if parts else None + builder = _const_parts(receiver, self.source)[0] if receiver is not None else [] + if len(builder) == 1 and (builder[0], name) in _CLASS_BUILDERS: + return self._built_class(call, names) if name not in _EVALS and name not in _INSTANCE_EVALS: return ctx on_singleton = name in _INSTANCE_EVALS @@ -353,6 +350,20 @@ def _block_context(self, call: Any, ctx: _Context) -> _Context | None: owner = tuple(_const_parts(receiver, self.source)[0]) return (owner, on_singleton, _CLASS) if owner else None + def _built_class(self, call: Any, names: tuple[str, ...]) -> _Context | None: + """`Point = Struct.new(:x) do … end` defines in Point, through a call chained on the + block (`end.freeze`) and `||=`; a class no constant names holds nothing to name.""" + node = call + while node.parent.type == "call": + receiver = node.parent.child_by_field_name("receiver") + if receiver is None or receiver.id != node.id: + break + node = node.parent + parent = node.parent + left = parent.child_by_field_name("left") if parent.type in _ASSIGNMENTS else None + parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) + return ((*parts,) if rooted else (*names, *parts), False, _CLASS) if parts else None + def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: self.pf.symbols.append( Symbol( diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 2e4bcb0f6c1..ace1241addf 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -270,6 +270,27 @@ def hidden; end ] +def test_a_built_class_is_named_through_a_rooted_builder_a_chained_call_and_or_assign() -> None: + src = b"""module Geo + Rooted = ::Struct.new(:a) do + def r; end + end + Frozen = Struct.new(:b) do + def f; end + end.freeze + Lazy ||= Class.new do + def l; end + end +end +""" + assert [s.qualified_name for s in parse_ruby("geo.rb", src).symbols] == [ + "root.geo::Geo", + "root.geo::Geo::Rooted#r", + "root.geo::Geo::Frozen#f", + "root.geo::Geo::Lazy#l", + ] + + def test_an_eval_without_a_receiver_defines_on_what_self_is() -> None: # `self` is the class in a method of `class << self`, and its singleton class beside them src = b"""class A From 8a1948e5af33436733d27aca721b65fd854ab098 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:57:43 +0530 Subject: [PATCH 18/29] A multiple assignment reads the receiver of an attribute or element target Every word under a `left_assignment_list` became a local, so after `helper.value, rest = 1, 2` the method `helper` was no site anywhere in the method and `value` read as a call. The walk binds only plain names, splats and nested lists, and an attribute or element target is a write whose receiver is read. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 18 +++++++++++++++++- tests/unit/test_code_lang_ruby.py | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index dfb7326c08a..6c607e2aea9 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -544,8 +544,24 @@ def _assignment(self, node: Any, scope: int) -> None: if left is None: return self.skip.add(left.id) # `a.b = 1` writes `b=`, `a = 1` defines a - if left.type in ("identifier", "left_assignment_list", "rest_assignment"): + if left.type in ("identifier", "rest_assignment"): self._collect(left, scope) + elif left.type == "left_assignment_list": + self._targets(left, scope) + + def _targets(self, node: Any, scope: int) -> None: + """The names a multiple assignment binds; an attribute or element target + (`a.b, c = …`, `a[0], c = …`) writes it and reads its receiver.""" + names = self.locals.setdefault(scope, set()) + stack = [node] + while stack: + for kid in stack.pop().named_children: + if kid.type == "identifier": + names.add(node_text(kid, self.source)) + elif kid.type in ("rest_assignment", "destructured_left_assignment"): + stack.append(kid) + else: + self.skip.add(kid.id) def _namespace(self, node: Any, scope: int) -> None: """`class X < Y` is a heritage site on its own line.""" diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index ace1241addf..62a3cbd0651 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -399,6 +399,25 @@ def name; end ] +def test_a_multiple_assignment_binds_its_names_and_reads_an_attribute_targets_receiver() -> None: + src = b"""def run + helper.value, rest = 1, 2 + items[0], *others = list + (a, b), c = pair + helper + rest + others.size + a + b + c +end +""" + # `helper.value, … =` writes `value=`, so neither word is a local + assert reference_sites(parse_ruby("a.rb", src)) == [ + (2, "helper", "bare"), + (3, "items", "bare"), + (3, "list", "bare"), + (4, "pair", "bare"), + (5, "helper", "bare"), + ] + + def test_a_doc_comment_is_the_comment_lines_right_above_a_definition() -> None: src = b"""class A def self.d; end # trailing From 6d3a248f3c7913a5c7b9dda7e285263dc4a44802 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:58:27 +0530 Subject: [PATCH 19/29] Each heredoc of a call is a statement on its own lines An island took its line from the string node, which for a heredoc is the marker. `execute(<<~A, <<~B)` put both statements and the tables they create on the body of A. The island grammar names the line a string's text runs from, and Ruby reads a heredoc's from its body. Go and Java keep the node's line. Signed-off-by: Vanshaj Poonia --- .../code/domain/extract/lang_code_islands.py | 4 +++- server/code/domain/extract/lang_ruby.py | 12 ++++++++++- tests/unit/test_code_lang_ruby.py | 20 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/server/code/domain/extract/lang_code_islands.py b/server/code/domain/extract/lang_code_islands.py index e07b57819da..51ff459b893 100644 --- a/server/code/domain/extract/lang_code_islands.py +++ b/server/code/domain/extract/lang_code_islands.py @@ -78,6 +78,8 @@ class IslandGrammar: # the scope a file's statements are qualified by: the language's, so they class as its # definitions do scope: Callable[[str], str] = module_scope + # the line a string node's text runs from; a Ruby heredoc's body follows another line + string_line: Callable[[Any], int] = lambda n: n.start_point[0] + 1 @dataclass @@ -192,7 +194,7 @@ def _island( return None return Island( text, - real[0].start_point[0] + 1, + g.string_line(real[0]), via, interpolated or holed or formatted or bool(n_named), (), diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 6c607e2aea9..be7e1ff9e3f 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -714,6 +714,13 @@ def _string_value(bodies: dict[int, Any], node: Any, source: bytes) -> tuple[str return text, interpolated +def _string_line(bodies: dict[int, Any], node: Any) -> int: + """The line a string's text runs from: a heredoc's body follows the line before it, + which for the second heredoc of a call is the end of the first.""" + body = bodies.get(node.start_byte) if node.type == "heredoc_beginning" else None + return (body if body is not None else node).start_point[0] + 1 + + def _heredoc_bodies(root: Any) -> dict[int, Any]: """{start byte of a `<<~X` marker: its body node}. A body follows the statement that holds its marker, in the markers' order, so one walk pairs them.""" @@ -739,6 +746,7 @@ def _heredoc_bodies(root: Any) -> dict[int, Any]: methods=RUBY_CLIENT_METHODS, callee=ruby_callee, string_value=functools.partial(_string_value, {}), + string_line=functools.partial(_string_line, {}), format_methods=frozenset({"format", "sprintf"}), concat_node="binary", assign_nodes=(("assignment", "left", "right"),), @@ -772,7 +780,9 @@ def ruby_sql_units(pf: ParsedFile) -> CodeSqlUnits: bodies = _heredoc_bodies(pf.tree.root_node) if bodies: grammar = dataclasses.replace( - grammar, string_value=functools.partial(_string_value, bodies) + grammar, + string_value=functools.partial(_string_value, bodies), + string_line=functools.partial(_string_line, bodies), ) return code_sql_units(pf, grammar, ruby_file_dialect(pf)) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 62a3cbd0651..425cb6a6771 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -842,6 +842,26 @@ def test_sql_a_file_runs_is_lifted_from_the_client_calls_and_literals() -> None: assert not any("Select a user" in i.text for i in units.islands) +def test_each_heredoc_of_a_call_is_a_statement_on_its_own_lines() -> None: + src = b"""class M + def up + execute(<<~A, <<~B) + CREATE TABLE a1 (x int) + A + CREATE TABLE b1 (y int) + B + end +end +""" + units = ruby_sql_units(parse_ruby("m.rb", src)) + assert [(s.name, s.start_line, s.end_line) for s in units.symbols] == [ + ("stmt_0001", 4, 4), + ("stmt_0002", 6, 6), + ("a1", 4, 4), + ("b1", 6, 6), + ] + + def test_the_statements_join_the_parse_of_an_ingested_file() -> None: pf, err = parse_for_ingest("app/report.rb", SQL) assert err == "" and pf is not None From 57650b3e77317699f7a5367752c1768fa88d6c01 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 22:58:48 +0530 Subject: [PATCH 20/29] Two docstrings of the lane keep to three lines `reference_sites` ran to four lines and `_scope_dialects_for` to five. Signed-off-by: Vanshaj Poonia --- server/code/app/index/ingest_edges.py | 8 +++----- server/code/domain/extract/lang_ruby.py | 5 ++--- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/server/code/app/index/ingest_edges.py b/server/code/app/index/ingest_edges.py index 428032c6752..88e191d0c1d 100644 --- a/server/code/app/index/ingest_edges.py +++ b/server/code/app/index/ingest_edges.py @@ -941,11 +941,9 @@ async def _scope_dialects_for( ns: str, table: dict[str, list[tuple[str, str, str]]], ) -> dict[str, str]: - """{module scope: dialect} for the defining files of every name the table holds MORE - than one definition of — the file-level `dialect` facet that `narrow_by_dialect` - reads, keyed by the scope each candidate is named in (a root Ruby file's is - `root.`). One id → path read, then one facet read per path; a file whose tables - are all unambiguous pays nothing.""" + """{candidate's scope: its file's `dialect` facet} for every name the table holds MORE + than one definition of, as `narrow_by_dialect` reads it. One id → path read, then one + facet read per path; a file whose tables are all unambiguous pays nothing.""" ambiguous = [c for cands in table.values() if len(cands) > 1 for c in cands][:200] if not ambiguous: return {} diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index be7e1ff9e3f..386a813000a 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -629,9 +629,8 @@ def _noisy(name: str) -> bool: def reference_sites(pf: ParsedFile) -> list[Site]: """(line, name, kind) of every `heritage`, `new`, `call` and `bare` site, in source - order. A local variable names nothing. A method of the language or a framework - (`puts`, `save`) is a site only when called on `self` or nothing, and binds only to - its own file's.""" + order. A local names nothing; a runtime method (`puts`, `save`) is a site only on + `self` or nothing.""" if pf.tree is None: return [] return _Sites(pf).run(pf.tree.root_node) From 5bcbfb7f4ac4221f47b3e491096926567e4fd901 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 23:08:05 +0530 Subject: [PATCH 21/29] A SQL function outside a method is no chunk of its own A `CREATE FUNCTION` lifted from a heredoc in a class body is a `function` symbol, so `span_chunks` cut it out as a unit and split the `execute` call around it. Units now come from the lane's own symbols, the same cut the caller sweep makes. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lane_units.py | 15 ++++++++++----- tests/unit/test_code_lang_ruby.py | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 4aedba7cdd0..d6fcce16b6e 100644 --- a/server/code/domain/extract/lane_units.py +++ b/server/code/domain/extract/lane_units.py @@ -70,6 +70,13 @@ def _top_level(symbols: list[Symbol], kinds: frozenset[str] | None = None) -> li return out +def _lane_symbols(pf: ParsedFile) -> list[Symbol]: + """The lane's own symbols: those of the SQL a file runs follow them, statements first + (`ingest_parse._join_island_symbols`).""" + own = next((i for i, s in enumerate(pf.symbols) if s.kind == STATEMENT_KIND), len(pf.symbols)) + return pf.symbols[:own] + + def _comment_run_above( src_lines: list[str], start: int, @@ -162,7 +169,7 @@ def _unit_chunks( by_start = sorted(pf.symbols, key=lambda s: s.start_line) starts = [s.start_line for s in by_start] prev_end = 0 - for top in _top_level(pf.symbols, unit_kinds): + for top in _top_level(_lane_symbols(pf), unit_kinds): start = _comment_run_above(src_lines, top.start_line, comment_leaders, comment_blocks) # a comment above a unit that starts on the previous one's last line is that unit's start = max(1, min(max(start, prev_end + 1), top.start_line)) @@ -280,10 +287,8 @@ def _leftover_chunks( def _enclosing_by_line(pf: ParsedFile, lines: set[int]) -> dict[int, Symbol]: """The innermost symbol around each line (the first of two alike spans), in one sweep. - The SQL a file runs gives none: its symbols, statements first, follow the lane's own - (`ingest_parse._join_island_symbols`), and a call written in it is its method's.""" - own = next((i for i, s in enumerate(pf.symbols) if s.kind == STATEMENT_KIND), len(pf.symbols)) - starts = sorted((s.start_line, i) for i, s in enumerate(pf.symbols[:own])) + The SQL a file runs gives none: a call written in it is its method's.""" + starts = sorted((s.start_line, i) for i, s in enumerate(_lane_symbols(pf))) open_spans: list[tuple[int, int]] = [] # (span length, index in pf.symbols) out: dict[int, Symbol] = {} k = 0 diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 425cb6a6771..f70b0586bbf 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -773,6 +773,29 @@ def test_every_line_with_text_is_in_a_chunk_however_short() -> None: assert [(c.start_line, c.end_line, c.content) for c in chunks] == [(1, 5, gemfile.decode())] +def test_a_sql_function_outside_a_method_is_no_chunk_of_its_own() -> None: + src = b"""require "pg" +class Schema + execute <<~SQL + CREATE FUNCTION add_one(i int) RETURNS int AS $$ SELECT i + 1 $$ LANGUAGE sql + SQL + + def a + 1 + end +end +""" + pf, err = parse_for_ingest("db/schema.rb", src) + assert err == "" and pf is not None and "add_one" in {s.name for s in pf.symbols} + chunks = span_chunks(pf, 6000, **CHUNK_OPTIONS) + assert [(c.kind, c.start_line, c.end_line) for c in chunks] == [ + ("file_header", 1, 1), + ("other", 2, 5), + ("function", 7, 9), + ("other", 10, 10), + ] + + def test_a_method_that_starts_on_the_last_line_of_another_is_its_own_chunk() -> None: src = b"""class Pair def first From 4005bb2ca80f2600494f2109fe354ec2e761d5fc Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 23:08:31 +0530 Subject: [PATCH 22/29] A built class names nothing when a call after its block returns something else MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The walk up from a builder followed every chained call, so `Origin = Struct.new(:x) do … end.new(0)` gave `Origin#o` though `Origin` holds an instance. It follows only `freeze`, `tap` and `itself`, which return the class. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 6 +++++- tests/unit/test_code_lang_ruby.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 386a813000a..5444b4b5df6 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -91,6 +91,7 @@ {("Struct", "new"), ("Class", "new"), ("Module", "new"), ("Data", "define")} ) _ASSIGNMENTS = frozenset({"assignment", "operator_assignment"}) +_RETURNS_SELF = frozenset({"freeze", "tap", "itself"}) _STRING_NODES = frozenset({"string", "heredoc_beginning"}) _ESCAPES = {"\\n": "\n", "\\t": "\t", "\\\\": "\\", '\\"': '"', "\\'": "'"} _REQUIRE_LINE_RE = re.compile(rb"(?m)^[ \t]*require[ \t]+[\"']([^\"'\n]+)[\"']") @@ -356,8 +357,11 @@ def _built_class(self, call: Any, names: tuple[str, ...]) -> _Context | None: node = call while node.parent.type == "call": receiver = node.parent.child_by_field_name("receiver") - if receiver is None or receiver.id != node.id: + method = node.parent.child_by_field_name("method") + if receiver is None or receiver.id != node.id or method is None: break + if node_text(method, self.source) not in _RETURNS_SELF: + return None # `end.new(0)`: the constant holds something else node = node.parent parent = node.parent left = parent.child_by_field_name("left") if parent.type in _ASSIGNMENTS else None diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index f70b0586bbf..393d2cad97b 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -281,8 +281,12 @@ def f; end Lazy ||= Class.new do def l; end end + Origin = Struct.new(:x) do + def o; end + end.new(0) end """ + # `Origin` holds an instance of the class, which no constant names assert [s.qualified_name for s in parse_ruby("geo.rb", src).symbols] == [ "root.geo::Geo", "root.geo::Geo::Rooted#r", From 7aadd3d6b1ff00340cdd127a299442d600a53fba Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 23:08:37 +0530 Subject: [PATCH 23/29] The chunk coverage test says what holds, not what Ruby files were Its comment narrated the text lane the Ruby lane replaced. Signed-off-by: Vanshaj Poonia --- tests/unit/test_code_lang_ruby.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 393d2cad97b..f48f9ae278b 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -764,8 +764,8 @@ def publish def test_every_line_with_text_is_in_a_chunk_however_short() -> None: - # a Ruby file was text, every line of it searchable; the lines between two methods are - # one chunk, and a gap of blank lines is none + # every line with text is searchable: the lines between two methods are one chunk, and + # a gap of blank lines is none chunks = span_chunks(parse_ruby("app/models/post.rb", MODEL), 6000, **CHUNK_OPTIONS) assert sorted((c.start_line, c.end_line, c.kind) for c in chunks) == [ (1, 4, "other"), From 84b7446da7286cdcda2bed5381e0666ff0c7cb73 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Fri, 4 Dec 2026 23:09:39 +0530 Subject: [PATCH 24/29] The heredoc line helper returns an int the mypy gate can check `_string_line` returned the tree's Any, which the gate counts as a new error. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 5444b4b5df6..60c2862adb0 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -721,7 +721,7 @@ def _string_line(bodies: dict[int, Any], node: Any) -> int: """The line a string's text runs from: a heredoc's body follows the line before it, which for the second heredoc of a call is the end of the first.""" body = bodies.get(node.start_byte) if node.type == "heredoc_beginning" else None - return (body if body is not None else node).start_point[0] + 1 + return int((body if body is not None else node).start_point[0]) + 1 def _heredoc_bodies(root: Any) -> dict[int, Any]: From a224e58f31586ff1d26643cd826b283ee88f197f Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 5 Dec 2026 13:11:28 +0530 Subject: [PATCH 25/29] A relative constant names the class its enclosing namespace holds `Item.class_eval`, `def Item.x` and `class << Item` inside `module Outer` read `Item` as a top-level name, so the methods landed on `Item` and not on `Outer::Item`. Ruby looks a constant up from the innermost namespace out. The reader now takes the first namespace whose class this file defined above the reference, else the innermost one. `::Item` stays the top level. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 29 ++++++++++++++--- tests/unit/test_code_lang_ruby.py | 41 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 5 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 60c2862adb0..b5629a0a3c3 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -279,6 +279,7 @@ class _Reader: def __init__(self, pf: ParsedFile) -> None: self.pf, self.source, self.scope = pf, pf.source, ruby_scope(pf.path) self.requires: list[str] = [] + self.defined: set[tuple[str, ...]] = set() # the classes and modules read so far def read(self, root: Any) -> None: # (node, context, doc comment, the siblings before a class body) @@ -314,8 +315,8 @@ def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: value = node.child_by_field_name("value") if value is not None and value.type == "self": return None if self_is == _INSTANCE else (names, True, _META) - owner = _const_parts(value, self.source)[0] if value is not None else [] - return (tuple(owner), True, _META) if owner else None + owner = self._owner(value, names) + return (owner, True, _META) if owner else None if t == "method": self._method(node, names, single, doc) return names, single, _CLASS if single else _INSTANCE @@ -348,7 +349,7 @@ def _block_context(self, call: Any, ctx: _Context) -> _Context | None: if self_is == _INSTANCE: return None return names, self_is == _META or on_singleton, self_is - owner = tuple(_const_parts(receiver, self.source)[0]) + owner = self._owner(receiver, names) return (owner, on_singleton, _CLASS) if owner else None def _built_class(self, call: Any, names: tuple[str, ...]) -> _Context | None: @@ -366,7 +367,24 @@ def _built_class(self, call: Any, names: tuple[str, ...]) -> _Context | None: parent = node.parent left = parent.child_by_field_name("left") if parent.type in _ASSIGNMENTS else None parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) - return ((*parts,) if rooted else (*names, *parts), False, _CLASS) if parts else None + if not parts: + return None + built = (*parts,) if rooted else (*names, *parts) + self.defined.add(built) + return built, False, _CLASS + + def _owner(self, node: Any, names: tuple[str, ...]) -> tuple[str, ...]: + """The class a constant names where the reader stands, () for any other expression. + Ruby looks it up from the innermost namespace out: the first this file defined above + wins, else the innermost one. `::X` is the top level.""" + parts, rooted = _const_parts(node, self.source) + if rooted or not parts: + return tuple(parts) + for depth in range(len(names), -1, -1): + owner = (*names[:depth], *parts) + if owner in self.defined: + return owner + return (*names, *parts) def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: self.pf.symbols.append( @@ -390,6 +408,7 @@ def _namespace(self, node: Any, ctx: _Context, doc: str) -> _Context: if not parts: return ctx inner = (*parts,) if rooted else (*ctx[0], *parts) + self.defined.add(inner) sup = node.child_by_field_name("superclass") sig = f"{node.type} {node_text(name_node, self.source)}" if sup is not None and sup.named_children: @@ -421,7 +440,7 @@ def _singleton_method(self, node: Any, names: tuple[str, ...], self_is: str, doc owner = None if self_is == _INSTANCE or target is None else names body_self = self_is else: - owner = tuple(_const_parts(target, self.source)[0]) or None + owner = self._owner(target, names) or None body_self = _INSTANCE if owner is None else _CLASS if name_node is not None and owner is not None: name = node_text(name_node, self.source) diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index f48f9ae278b..3b434a69e45 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -325,6 +325,47 @@ def v; end ] +def test_a_relative_constant_names_the_class_the_enclosing_namespaces_hold() -> None: + # Ruby looks a constant up from the innermost namespace out; the file's own + # definitions above the reference settle it, else the innermost namespace + src = b"""class Item +end +module Plain + Item.class_eval { def top; end } +end +module Outer + class Item + end + Item.class_eval do + def made; end + end + def Item.build; end + class << Item + def make; end + end + class Inner + Item.instance_eval { def seen; end } + end + Widget.class_eval { def known; end } + ::Item.class_eval { def rooted; end } +end +""" + assert [s.qualified_name for s in parse_ruby("a.rb", src).symbols] == [ + "root.a::Item", + "root.a::Plain", + "root.a::Item#top", + "root.a::Outer", + "root.a::Outer::Item", + "root.a::Outer::Item#made", + "root.a::Outer::Item.build", + "root.a::Outer::Item.make", + "root.a::Outer::Inner", + "root.a::Outer::Item.seen", + "root.a::Outer::Widget#known", + "root.a::Item#rooted", + ] + + def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: pf = parse_ruby("lib/billing.rb", BILLING) # `require_relative "x"` keeps a leading `./` so it resolves beside the file From cb99cf4c2ca8264ef86c7acdbfc91ac07ee53021 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sat, 5 Dec 2026 13:18:37 +0530 Subject: [PATCH 26/29] A qualified constant the file never defines is read as written `ActiveRecord::Base.class_eval` inside `module MyGem` gave `MyGem::ActiveRecord::Base#x`. A path whose first name the file does not define names a library class, so it keeps the name as written. A lone name the file never defines still takes the innermost namespace. A path whose first name an enclosing namespace defines resolves from there. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 13 ++++++----- tests/unit/test_code_lang_ruby.py | 30 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index b5629a0a3c3..d89583528e8 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -375,16 +375,17 @@ def _built_class(self, call: Any, names: tuple[str, ...]) -> _Context | None: def _owner(self, node: Any, names: tuple[str, ...]) -> tuple[str, ...]: """The class a constant names where the reader stands, () for any other expression. - Ruby looks it up from the innermost namespace out: the first this file defined above - wins, else the innermost one. `::X` is the top level.""" + Ruby looks up its first name from the innermost namespace out: the first this file + defined above wins. Else a lone name takes the innermost one and a path (`A::B`) is + read as written, for it names a library. `::X` is the top level.""" parts, rooted = _const_parts(node, self.source) if rooted or not parts: return tuple(parts) for depth in range(len(names), -1, -1): - owner = (*names[:depth], *parts) - if owner in self.defined: - return owner - return (*names, *parts) + scope = names[:depth] + if (*scope, parts[0]) in self.defined or (*scope, *parts) in self.defined: + return (*scope, *parts) + return (*names, *parts) if len(parts) == 1 else tuple(parts) def _add(self, qn: str, name: str, kind: str, sig: str, node: Any, doc: str) -> None: self.pf.symbols.append( diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 3b434a69e45..ea08dd04097 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -366,6 +366,36 @@ class Inner ] +def test_a_qualified_constant_the_file_never_defines_is_read_as_written() -> None: + # `ActiveRecord::Base` in a gem's namespace names a library class; a path whose + # first segment the file defines in an enclosing namespace resolves from there + src = b"""module MyGem + ActiveRecord::Base.class_eval { def extended; end } + class << ActiveRecord::Base + def make; end + end +end +module Admin + class Auth + end + Auth::User.class_eval { def known; end } + class Inner + Auth::User.instance_eval { def seen; end } + end +end +""" + assert [s.qualified_name for s in parse_ruby("a.rb", src).symbols] == [ + "root.a::MyGem", + "root.a::ActiveRecord::Base#extended", + "root.a::ActiveRecord::Base.make", + "root.a::Admin", + "root.a::Admin::Auth", + "root.a::Admin::Auth::User#known", + "root.a::Admin::Inner", + "root.a::Admin::Auth::User.seen", + ] + + def test_requires_are_include_specifiers_and_dynamic_ones_are_not() -> None: pf = parse_ruby("lib/billing.rb", BILLING) # `require_relative "x"` keeps a leading `./` so it resolves beside the file From 122bf43a83638f0f8d51a7003301d3292b066798 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sun, 6 Dec 2026 10:00:21 +0530 Subject: [PATCH 27/29] A block, lambda or rescue clause keeps its own local variables A block or lambda parameter, and a name the body assigns, were stored as locals of the enclosing method, so a bare call anywhere in the method was dropped. A rescue variable did the same. Each now lives in a scope of its own that its body reads through to the scope around it. A name a rescue body assigns still belongs to the method. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 39 ++++++++++++--- tests/unit/test_code_lang_ruby.py | 63 +++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 7 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index d89583528e8..732c5307d10 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -81,6 +81,8 @@ _MAX_DOC = 2000 # not a setting: the cut every doc_comment of this lane takes _DEF_NODES = frozenset({"class", "module", "method", "singleton_method"}) _PARAMETER_NODES = frozenset({"method_parameters", "block_parameters", "lambda_parameters"}) +# a block or lambda body sees the locals around it and keeps its own +_BLOCK_NODES = frozenset({"block", "do_block", "lambda"}) _PATTERN_NODES = frozenset({"in_clause", "match_pattern", "test_pattern"}) _MIXINS = frozenset({"include", "extend", "prepend"}) _REQUIRES = frozenset({"require", "require_relative"}) @@ -478,12 +480,15 @@ def parse_ruby(path: str, source: bytes) -> ParsedFile: class _Sites: """The reference sites of one file, read from its tree without recursion. A bare word - is kept only when the method (or class body) holds no local variable of that name.""" + is kept only when no scope around it holds a local variable of that name: its method + or class body, and the blocks and lambdas it sits in.""" def __init__(self, pf: ParsedFile) -> None: self.source = pf.source self.found: list[tuple[int, str, str, int]] = [] # line, name, kind, scope node id self.locals: dict[int, set[str]] = {} + self.parent: dict[int, int] = {} # a block's or rescue clause's enclosing scope + self.clauses: set[int] = set() # rescue scopes: only the exception variable is theirs self.skip: set[int] = set() # nodes that are a definition, not a read def run(self, root: Any) -> list[Site]: @@ -496,9 +501,22 @@ def run(self, root: Any) -> list[Site]: return [ (line, name, kind) for line, name, kind, scope in self.found - if kind != SITE_BARE or name not in self.locals.get(scope, ()) + if kind != SITE_BARE or not self._local(scope, name) ] + def _local(self, scope: int | None, name: str) -> bool: + while scope is not None: + if name in self.locals.get(scope, ()): + return True + scope = self.parent.get(scope) + return False + + def _home(self, scope: int) -> set[str]: + """The names a write binds: those of the nearest scope that is not a rescue clause.""" + while scope in self.clauses: + scope = self.parent[scope] + return self.locals.setdefault(scope, set()) + def _add(self, line: int, name: str, kind: str, scope: int) -> None: self.found.append((line, name, kind, scope)) @@ -512,8 +530,15 @@ def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[i self._assignment(node, scope) elif t in _PARAMETER_NODES: self._parameters(node, scope) + elif t in _BLOCK_NODES: + self.parent[node.id] = scope + return node.id, owner + elif t == "rescue": + self.parent[node.id] = scope + self.clauses.add(node.id) + return node.id, owner elif t == "exception_variable": - self._collect(node, scope) + self._collect(node, scope, self.locals.setdefault(scope, set())) elif t in _PATTERN_NODES: self._collect(node.child_by_field_name("pattern"), scope) elif t == "for": @@ -531,12 +556,12 @@ def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[i return node.id, owner return scope, owner - def _collect(self, node: Any, scope: int) -> None: + def _collect(self, node: Any, scope: int, names: set[str] | None = None) -> None: """Every identifier under `node` is a local variable of the scope, and so is the key of a pattern's `key:` with no pattern of its own; a pinned `^(expr)` is read.""" if node is None: return - names = self.locals.setdefault(scope, set()) + names = self._home(scope) if names is None else names stack = [node] while stack: n = stack.pop() @@ -551,7 +576,7 @@ def _collect(self, node: Any, scope: int) -> None: def _parameters(self, node: Any, scope: int) -> None: """The names a parameter list binds are local variables; a default value is read.""" - names = self.locals.setdefault(scope, set()) + names = self._home(scope) stack = [node] while stack: for kid in stack.pop().named_children: @@ -576,7 +601,7 @@ def _assignment(self, node: Any, scope: int) -> None: def _targets(self, node: Any, scope: int) -> None: """The names a multiple assignment binds; an attribute or element target (`a.b, c = …`, `a[0], c = …`) writes it and reads its receiver.""" - names = self.locals.setdefault(scope, set()) + names = self._home(scope) stack = [node] while stack: for kid in stack.pop().named_children: diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index ea08dd04097..0d673f24e15 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -474,6 +474,69 @@ def name; end ] +def test_a_block_or_lambda_parameter_shadows_only_inside_its_block() -> None: + src = b"""def run(items) + items.each { |helper| helper } + helper + items.map do |name, (first, *rest)| + name + first + rest.size + items.each { name } + end + name + seek = ->(token) { token } + token + items.each { |n; scratch| scratch + n } + scratch +end +""" + assert reference_sites(parse_ruby("a.rb", src)) == [ + (3, "helper", "bare"), + (8, "name", "bare"), + (10, "token", "bare"), + (12, "scratch", "bare"), + ] + + +def test_a_name_a_block_assigns_is_local_to_the_block_and_an_outer_one_shadows_it() -> None: + src = b"""def run(items) + seen = 1 + items.each do + total = seen + total + made + end + total + made = 2 +end +""" + assert reference_sites(parse_ruby("a.rb", src)) == [(7, "total", "bare")] + + +def test_a_rescue_variable_shadows_only_inside_its_clause() -> None: + src = b"""def run + recover + work +rescue Boom => recover + recover + made = recover + cleanup +ensure + made +end + +def other + recover + made +end +""" + assert reference_sites(parse_ruby("a.rb", src)) == [ + (2, "recover", "bare"), + (3, "work", "bare"), + (7, "cleanup", "bare"), + (13, "recover", "bare"), + (14, "made", "bare"), + ] + + def test_a_multiple_assignment_binds_its_names_and_reads_an_attribute_targets_receiver() -> None: src = b"""def run helper.value, rest = 1, 2 From 8ae3e9d8de2949dfd577593f2f2003da5a1bae1d Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sun, 6 Dec 2026 10:00:33 +0530 Subject: [PATCH 28/29] New in a singleton definition constructs the constant it is defined on `def Const.m` and `class << Const` left the enclosing class as the owner, so a bare `new` or `self.new` bound to the outer class, or was dropped when there was none. The site walk now reads the owner from the definition. An object that is no constant names nothing, and `self` keeps the class around. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 12 +++++ tests/unit/test_code_lang_ruby.py | 59 +++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 732c5307d10..9b4ce2ae40e 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -553,9 +553,21 @@ def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[i for part in (node.child_by_field_name("name"), node.child_by_field_name("object")): if part is not None: self.skip.add(part.id) + if t == "singleton_method": + owner = self._singleton_owner(node.child_by_field_name("object"), owner) return node.id, owner + elif t == "singleton_class": + return scope, self._singleton_owner(node.child_by_field_name("value"), owner) return scope, owner + def _singleton_owner(self, target: Any, owner: str) -> str: + """The class `new` constructs inside `def X.m` or `class << X`: X, nothing for any + object that is no constant, and the enclosing class for `self`.""" + if target is None or target.type == "self": + return owner + parts = _const_parts(target, self.source)[0] + return parts[-1] if parts else "" + def _collect(self, node: Any, scope: int, names: set[str] | None = None) -> None: """Every identifier under `node` is a local variable of the scope, and so is the key of a pattern's `key:` with no pattern of its own; a pinned `^(expr)` is read.""" diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 0d673f24e15..5ddcf80d4f3 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -576,6 +576,65 @@ def test_new_without_a_receiver_constructs_the_enclosing_class() -> None: assert [(n, k) for _l, n, k in sites] == [("Cart", "new")] * 3 +def test_new_in_a_singleton_definition_constructs_the_constant_it_is_defined_on() -> None: + src = b"""class Outer + def self.build + new + end + + def Item.make + new + self.new(1) + end + + def item.make + new + end + + class << Part + def made + self.new + end + end + + class << self + def again + new + end + end + + def top + new + end +end + +def Lone.make + new +end + +class << Solo + def made + self.new + end +end + +def self.main_only + new +end +""" + sites = [(line, n) for line, n, k in reference_sites(parse_ruby("o.rb", src)) if k == "new"] + assert sites == [ + (3, "Outer"), + (7, "Item"), + (8, "Item"), + (17, "Part"), + (23, "Outer"), + (28, "Outer"), + (33, "Lone"), + (38, "Solo"), + ] + + def test_call_sites_bind_same_file_first_then_repository_unique() -> None: cart = parse_ruby("shop/cart.rb", CART) payment = parse_ruby("shop/payment.rb", PAYMENT) From 3a3ed6635b9771de1a981fc676ec859104041d72 Mon Sep 17 00:00:00 2001 From: Vanshaj Poonia Date: Sun, 6 Dec 2026 10:08:03 +0530 Subject: [PATCH 29/29] A rescue variable stays a local after its clause Ruby keeps the name bound in the enclosing scope once the clause has run, and reads it as a method before the clause. The site walk now drops a bare read of it from the clause's line on and keeps one above it. Signed-off-by: Vanshaj Poonia --- server/code/domain/extract/lang_ruby.py | 35 ++++++++++++++++++------- tests/unit/test_code_lang_ruby.py | 8 +++--- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/server/code/domain/extract/lang_ruby.py b/server/code/domain/extract/lang_ruby.py index 9b4ce2ae40e..96324ba0542 100644 --- a/server/code/domain/extract/lang_ruby.py +++ b/server/code/domain/extract/lang_ruby.py @@ -488,7 +488,8 @@ def __init__(self, pf: ParsedFile) -> None: self.found: list[tuple[int, str, str, int]] = [] # line, name, kind, scope node id self.locals: dict[int, set[str]] = {} self.parent: dict[int, int] = {} # a block's or rescue clause's enclosing scope - self.clauses: set[int] = set() # rescue scopes: only the exception variable is theirs + self.clauses: dict[int, int] = {} # rescue scope: its line; only its variable is its own + self.after: dict[int, dict[str, int]] = {} # the line a rescue variable binds from self.skip: set[int] = set() # nodes that are a definition, not a read def run(self, root: Any) -> list[Site]: @@ -501,21 +502,29 @@ def run(self, root: Any) -> list[Site]: return [ (line, name, kind) for line, name, kind, scope in self.found - if kind != SITE_BARE or not self._local(scope, name) + if kind != SITE_BARE or not self._local(scope, name, line) ] - def _local(self, scope: int | None, name: str) -> bool: + def _local(self, scope: int | None, name: str, line: int) -> bool: + """Whether `name` read on `line` is a local of the scope or one around it. A rescue + variable stays a local of the scope after its clause, as Ruby has it.""" while scope is not None: - if name in self.locals.get(scope, ()): + if ( + name in self.locals.get(scope, ()) + or self.after.get(scope, {}).get(name, line) < line + ): return True scope = self.parent.get(scope) return False - def _home(self, scope: int) -> set[str]: - """The names a write binds: those of the nearest scope that is not a rescue clause.""" + def _home_scope(self, scope: int) -> int: + """The nearest scope that is not a rescue clause: where a write binds its name.""" while scope in self.clauses: scope = self.parent[scope] - return self.locals.setdefault(scope, set()) + return scope + + def _home(self, scope: int) -> set[str]: + return self.locals.setdefault(self._home_scope(scope), set()) def _add(self, line: int, name: str, kind: str, scope: int) -> None: self.found.append((line, name, kind, scope)) @@ -535,10 +544,10 @@ def _visit(self, node: Any, parent_type: str, scope: int, owner: str) -> tuple[i return node.id, owner elif t == "rescue": self.parent[node.id] = scope - self.clauses.add(node.id) + self.clauses[node.id] = node.start_point[0] + 1 return node.id, owner elif t == "exception_variable": - self._collect(node, scope, self.locals.setdefault(scope, set())) + self._exception_variable(node, scope) elif t in _PATTERN_NODES: self._collect(node.child_by_field_name("pattern"), scope) elif t == "for": @@ -568,6 +577,14 @@ def _singleton_owner(self, target: Any, owner: str) -> str: parts = _const_parts(target, self.source)[0] return parts[-1] if parts else "" + def _exception_variable(self, node: Any, clause: int) -> None: + """`rescue => e` binds `e` in its clause, and in the scope around it from the clause on.""" + names = self.locals.setdefault(clause, set()) + self._collect(node, clause, names) + later = self.after.setdefault(self._home_scope(clause), {}) + for name in names: + later.setdefault(name, self.clauses[clause]) + def _collect(self, node: Any, scope: int, names: set[str] | None = None) -> None: """Every identifier under `node` is a local variable of the scope, and so is the key of a pattern's `key:` with no pattern of its own; a pinned `^(expr)` is read.""" diff --git a/tests/unit/test_code_lang_ruby.py b/tests/unit/test_code_lang_ruby.py index 5ddcf80d4f3..0c844c06ecc 100644 --- a/tests/unit/test_code_lang_ruby.py +++ b/tests/unit/test_code_lang_ruby.py @@ -511,7 +511,7 @@ def test_a_name_a_block_assigns_is_local_to_the_block_and_an_outer_one_shadows_i assert reference_sites(parse_ruby("a.rb", src)) == [(7, "total", "bare")] -def test_a_rescue_variable_shadows_only_inside_its_clause() -> None: +def test_a_rescue_variable_is_a_local_from_its_clause_on() -> None: src = b"""def run recover work @@ -521,6 +521,7 @@ def test_a_rescue_variable_shadows_only_inside_its_clause() -> None: cleanup ensure made + recover end def other @@ -528,12 +529,13 @@ def other made end """ + # a call before the clause is a method call, as in `other` assert reference_sites(parse_ruby("a.rb", src)) == [ (2, "recover", "bare"), (3, "work", "bare"), (7, "cleanup", "bare"), - (13, "recover", "bare"), - (14, "made", "bare"), + (14, "recover", "bare"), + (15, "made", "bare"), ]