diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index a92799eae1e..7b1232f2be8 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -335,8 +335,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. @@ -999,7 +999,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..e86bd9ad6f6 100644 --- a/docs/features/code-index/overview.md +++ b/docs/features/code-index/overview.md @@ -149,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 | — | diff --git a/docs/features/integrations/claude-code.md b/docs/features/integrations/claude-code.md index b56aaaf1f57..c2821ebd580 100644 --- a/docs/features/integrations/claude-code.md +++ b/docs/features/integrations/claude-code.md @@ -682,7 +682,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 45db58b2df1..961a534f56a 100644 --- a/integrations/claude-code-plugin/hooks/HOOKS.md +++ b/integrations/claude-code-plugin/hooks/HOOKS.md @@ -873,8 +873,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 diff --git a/pyproject.toml b/pyproject.toml index 066b5f26b60..faeb49e6a9f 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/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..88e191d0c1d 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]: @@ -939,23 +941,24 @@ 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. 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: + """{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 {} - 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]: @@ -974,10 +977,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 @@ -1005,8 +1009,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, @@ -1018,7 +1023,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, @@ -1034,15 +1039,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/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/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/server/code/domain/extract/lane_units.py b/server/code/domain/extract/lane_units.py index 44eb30dd75f..d6fcce16b6e 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,27 +42,41 @@ @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]) -> 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. 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), + ) 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 +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, @@ -95,8 +114,9 @@ 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 + """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 @@ -104,9 +124,13 @@ 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), 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( @@ -117,11 +141,13 @@ 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: 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 @@ -135,21 +161,25 @@ def _unit_chunks( leader: str, comment_leaders: tuple[str, ...], comment_blocks: tuple[tuple[str, str], ...], + 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] = [] - for top in _top_level(pf.symbols): + 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(_lane_symbols(pf), 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 - 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 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)] content = "".join(src_lines[start - 1 : end]) for i in range(start, end + 1): @@ -210,15 +240,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 @@ -227,8 +259,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)] @@ -249,15 +285,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. + 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 + 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( @@ -267,7 +311,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, @@ -279,24 +324,30 @@ 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 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 @@ -349,6 +400,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..51ff459b893 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` → @@ -75,10 +75,16 @@ 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 + # 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 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) @@ -188,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), (), @@ -482,12 +488,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_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..96324ba0542 --- /dev/null +++ b/server/code/domain/extract/lang_ruby.py @@ -0,0 +1,894 @@ +"""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 # 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"}) +# 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")} +) +_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]+)[\"']") +# 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", + "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 +# 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 + + +# 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: + """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] = [] + 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) + stack: list[tuple[Any, _Context, str, tuple[Any, ...]]] = [ + (root, ((), False, _CLASS), "", ()) + ] + while stack: + node, ctx, doc, lead = stack.pop() + nxt = self._visit(node, ctx, 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, kid_doc, kid_lead)) + + def _visit(self, node: Any, ctx: _Context, doc: str) -> _Context | None: + """The context the node's children read under; None skips them.""" + names, single, self_is = ctx + t = node.type + if t in ("class", "module"): + 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 None if self_is == _INSTANCE else (names, True, _META) + 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 + if t == "singleton_method": + return names, single, self._singleton_method(node, names, self_is, doc) + if t == "call": + self._require(node) + 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 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, 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, _INSTANCE + 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 + if receiver is None or receiver.type == "self": + if self_is == _INSTANCE: + return None + return names, self_is == _META or on_singleton, self_is + 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: + """`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") + 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 + parts, rooted = _const_parts(left, self.source) if left is not None else ([], False) + 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 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): + 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( + 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, 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 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: + 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, _CLASS + + 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, ...], self_is: str, doc: str) -> str: + """`def self.x` or `def Const.x`; one on an instance or a variable names nothing. + 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 self_is == _INSTANCE or target is None else names + body_self = self_is + else: + 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) + qn = self._method_qn(owner, True, name) + self._add(qn, name, KIND_FUNCTION, _params(node, self.source), node, doc) + return body_self + + 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 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: 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]: + 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 not self._local(scope, name, line) + ] + + 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, ()) + or self.after.get(scope, {}).get(name, line) < line + ): + return True + scope = self.parent.get(scope) + return False + + 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 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)) + + 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 in _BLOCK_NODES: + self.parent[node.id] = scope + return node.id, owner + elif t == "rescue": + self.parent[node.id] = scope + self.clauses[node.id] = node.start_point[0] + 1 + return node.id, owner + elif t == "exception_variable": + self._exception_variable(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) + 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 _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.""" + if node is None: + return + names = self._home(scope) if names is None else names + 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)) + 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._home(scope) + 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", "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._home(scope) + 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.""" + 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 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) + + +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 _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 int((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.""" + 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, {}), + string_line=functools.partial(_string_line, {}), + format_methods=frozenset({"format", "sprintf"}), + concat_node="binary", + assign_nodes=(("assignment", "left", "right"),), + aug_assign_node=("operator_assignment", "left", "operator", "right"), + scope=ruby_scope, +) + + +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), + string_line=functools.partial(_string_line, 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..3a7afb5affc 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)] @@ -578,23 +587,26 @@ 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)) - if pf.lang in ("python", "go", "java"): + 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", "thrift", "gotemplate", "lua", + "ruby", "config", "python", ): @@ -614,11 +626,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,20 +679,25 @@ 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) -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, @@ -689,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/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..0c844c06ecc --- /dev/null +++ b/tests/unit/test_code_lang_ruby.py @@ -0,0 +1,1245 @@ +"""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, + _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 +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.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 + +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_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_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_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 + 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", + "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 + 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_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_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 + 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_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_is_a_local_from_its_clause_on() -> None: + src = b"""def run + recover + work +rescue Boom => recover + recover + made = recover + cleanup +ensure + made + recover +end + +def other + recover + 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"), + (14, "recover", "bare"), + (15, "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 + 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 + # 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_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) + 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_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 + 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_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_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") + (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: + # 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"), + (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_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 + # 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() + 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_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 + 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) + + +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} + + +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")]} + repo: Any = Repo() + dialects = asyncio.run(_scope_dialects_for(repo, "o", "n", table)) + assert narrow_by_dialect(table, "postgres", dialects)["entries"] == [table["entries"][0]] + + +@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_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) 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"=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"