Skip to main content

big_code_analysis_ast/getter/
ruby.rs

1//! `Getter` implementation for Ruby.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6impl Getter for RubyCode {
7    // The mapping is the `opens` annotations of `roles/ruby.rs`
8    // (#1696). This byte-less spelling is the kind table, gates aside —
9    // a stabby lambda's own body block labels `Function` here as it did
10    // before the rows, while the `_with_code` spelling the walk reads
11    // declines it (#1257). It forwards with a *known-empty* chain — the
12    // node read as if it were the root, so the parent gate sees no
13    // lambda — and not `Ancestors::unknown()`, which climbs through
14    // `Node::parent` and would answer the gated result. The
15    // `opener_gated` form: no `!CHAIN_GATED` assertion on the opener
16    // row, unlike most languages' forward (#1793), since the row is
17    // chain-gated by design and
18    // `ruby_byte_less_spellings_stay_the_kind_table` pins the
19    // disagreement by value; the `Container` row is pinned at build
20    // time (#1863).
21    impl_byte_less_space_kind!(ruby, opener_gated);
22
23    fn get_space_kind_with_code<'a>(
24        node: &Node<'a>,
25        code: &[u8],
26        ancestors: Ancestors<'a, '_>,
27    ) -> SpaceKind {
28        crate::roles::ruby::opens_space(node, code, ancestors)
29    }
30
31    keyword_roles!(ruby);
32
33    paying_roles!(ruby);
34
35    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
36        use Ruby as R;
37
38        match node.kind_id().into() {
39            // Regex delimiter punctuation. tree-sitter-ruby aliases
40            // every regex delimiter spelling to `/`: `bca dump` at the
41            // pinned grammar shows `/…/`, `%r{…}` and `%r|…|` all
42            // emitting `SLASH` (kind 85) for both delimiters — the very
43            // kind id real division uses. Counting them fabricated two
44            // `/` operators per regex literal and made n1/N1 depend on
45            // the author's delimiter choice (#1312, the Ruby sibling of
46            // Elixir #1256). The `Regex` node itself is the operand
47            // (below), so the delimiters are suppressed exactly when
48            // their parent is that node — the compound-leaf guard of
49            // grammar-dispatch §5. Parent, not ancestor: a `/` nested
50            // deeper, such as a division inside `#{…}` interpolation,
51            // has `Binary` as its parent and must still count.
52            // `SLASH2` is the aliased regex-start token; the runtime
53            // `public_symbol_map` collapses it to `SLASH` so it never
54            // reaches `kind_id()` (the `LPAREN2` class of #768, pinned
55            // by `ruby_regex_start_alias_never_reaches_kind_id`). It
56            // appears here and *only* here — it was dropped from the
57            // arithmetic arm below, because a regex delimiter is the
58            // only thing it could ever be. Should a bump surface it
59            // outside a `Regex`, it now falls to `Unknown` rather than
60            // being counted as a division.
61            R::SLASH | R::SLASH2
62                if ancestors.parent_has_kind(node, R::Regex as u16) =>
63            {
64                TokenRole::Unknown
65            }
66            // Subshell delimiter punctuation — the second delimiter
67            // family of the fabrication the arm above removes for
68            // regexes (#1360, following #1312). tree-sitter-ruby
69            // aliases both ends of a subshell literal to a single
70            // backtick token: `bca dump` at the pinned grammar shows
71            // all seven spellings — the backtick pair plus %x with
72            // {}, (), [], <>, || and !! — emitting BQUOTE (kind 103)
73            // for the opener *and* the closer, so a one-command
74            // literal reported a backtick operator that is nowhere in
75            // the source as an operation. The `Subshell` node itself
76            // is the operand (the string-like arm below), so
77            // suppressing its delimiters loses nothing, and the
78            // childless `` `` `` spelling still bills that wrapper.
79            //
80            // Gated rather than dropped from the operator arm, per
81            // grammar-dispatch §6: a backtick is also a legal Ruby
82            // method name — def and call alike — and at this grammar
83            // that marker is a BQUOTE wrapped in a named `operator`
84            // node, so its parent is `Operator` and never `Subshell`.
85            // Deleting the kind would score the method-name marker
86            // zero.
87            //
88            // Parent, not ancestor, and here the difference is
89            // observable: a backtick method inside a subshell's `#{…}`
90            // interpolation still has `Operator` as its parent but the
91            // `Subshell` as a further ancestor, so an ancestor scan
92            // would swallow it. That is the input
93            // `ruby_subshell_guard_is_parent_scoped_not_ancestor_scoped`
94            // exists to separate — unlike the numeral guard below,
95            // whose two spellings no Ruby input can tell apart.
96            //
97            // One kind, where the regex guard above names two: BQUOTE2
98            // is this family's aliased literal-start token, but unlike
99            // SLASH2 it never sat in the operator arm, so the wildcard
100            // already answers `Unknown` for it and listing it here
101            // would read as load-bearing while doing nothing. Its
102            // reachability is pinned by
103            // `ruby_subshell_start_alias_never_reaches_kind_id`
104            // instead.
105            R::BQUOTE if ancestors.parent_has_kind(node, R::Subshell as u16) => {
106                TokenRole::Unknown
107            }
108            // Control-flow keyword tokens. tree-sitter-ruby gives each
109            // keyword its own anonymous numbered variant (e.g. `If2` is
110            // the `if` keyword token; `If` is the named statement node).
111            R::If2 | R::Unless2 | R::While2 | R::Until2 | R::For2 | R::In2 | R::Do2
112            | R::Case2 | R::When2 | R::Elsif2 | R::Else2 | R::Then2
113            | R::Begin2 | R::Ensure2 | R::Rescue2
114            | R::Return3 | R::Yield3 | R::Break3 | R::Next3 | R::Redo2 | R::Retry2
115            // `End`/`End2` are the two aliased visible kinds for the
116            // `end` block closer (kind_ids 0 and 13) that every
117            // `def`/`class`/`module`/`begin`/`if`/loop construct emits;
118            // `BEGIN`/`END` are the special `BEGIN { }` / `END { }`
119            // block-form keywords (kinds 4 / 7) and are distinct from
120            // the lowercase `end` closer. The declaration keywords
121            // (`def`, `class`, `module`, `alias`, `undef`) are not here:
122            // `roles/ruby.rs` declares them and `get_keyword_role` bills
123            // them (#1693).
124            | R::End | R::End2
125            | R::BEGIN | R::END
126            // Definedness and negation keywords; `and` / `or` are the
127            // `ShortCircuit` row's and `get_paying_role` bills them (#1695)
128            | R::Not | R::DefinedQMARK
129            // Structural punctuation acting as operators. `HASHLBRACE`
130            // — the `#{` interpolation opener — was here until #1314
131            // and is deliberately gone: an interpolation opener is
132            // spelling rather than an operation, the interpolated
133            // expression's own operators being counted already. Unlike
134            // PHP's `{`, Ruby's is a token of its own, so it needs no
135            // parent guard; dropping the arm is the whole change, and
136            // it applies to every literal that interpolates — string,
137            // symbol, regex, heredoc, subshell. See the PHP sibling in
138            // `src/getter/php.rs` for the cross-language measurement
139            // this policy rests on. This half is a behaviour change,
140            // not a fabrication fix: Ruby Halstead operator counts drop
141            // for interpolated literals.
142            //
143            // Only the *opening* delimiter counts (the pair folds to
144            // one glyph in `get_operator_id_as_str`); the former closing arms
145            // (`RPAREN`/`RPAREN2`/`RBRACE`/`RBRACK`) double-counted every
146            // balanced pair, inflating n1/N1 (#695). The `LBRACKRBRACK` /
147            // `LBRACKRBRACKEQ` indexer *method names* below (`def [](i)`)
148            // are whole-token operators, not a balanced pair, and stay.
149            // `LPAREN2`/`LBRACK2`/`LBRACK3` are defensive — the runtime
150            // `public_symbol_map` collapses them to `LPAREN`/`LBRACK` before
151            // `kind_id()`, so they never fire (#768; see the Cpp impl note
152            // and `second_alias_opener_collapses_to_base_kind_id`).
153            | R::LPAREN | R::LPAREN2
154            | R::LBRACE | R::LBRACK | R::LBRACK2 | R::LBRACK3
155            // `&.` is the `NullSafe` row's and `get_paying_role` bills it (#1695).
156            | R::COMMA | R::SEMI | R::DOT | R::COLONCOLON | R::COLONCOLON2
157            | R::COLON | R::COLON2 | R::DASHGT
158            // Method-name operator markers (`def +@`, `def -@`, `def ~@`)
159            // and indexer methods.
160            | R::PLUSAT | R::DASHAT | R::TILDEAT
161            | R::LBRACKRBRACK | R::LBRACKRBRACKEQ
162            // Arithmetic
163            | R::PLUS | R::DASH | R::DASH2 | R::DASH3 | R::DASH4 | R::STAR | R::STAR2 | R::STAR3
164            | R::SLASH | R::PERCENT
165            | R::STARSTAR | R::STARSTAR2 | R::STARSTAR3
166            // The comparison tokens for the spellings the `Comparison`
167            // row's `under_binary` gate leaves out — an operator method's
168            // name (`def ==(o)`), a superclass clause's `<`, a recovered
169            // token — which billed before the row existed; `&&` / `||`
170            // and the ternary `?` are the `ShortCircuit` and `Ternary`
171            // rows' and `get_paying_role` bills them (#1695).
172            // role-bypass: allow(Comparison) — the operator classification of the spellings the
173            // row's `under_binary` gate leaves out
174            | R::EQEQ | R::BANGEQ | R::EQEQEQ
175            | R::LT | R::GT | R::LTEQ | R::GTEQ | R::LTEQGT
176            | R::EQTILDE | R::BANGTILDE
177            // Logical / unary
178            | R::BANG | R::TILDE
179            // Bitwise / shift
180            | R::AMP | R::AMP2 | R::PIPE | R::CARET | R::LTLT | R::LTLT2 | R::GTGT
181            // Assignment
182            | R::EQ | R::EQ2
183            | R::PLUSEQ | R::DASHEQ | R::STAREQ | R::SLASHEQ | R::PERCENTEQ
184            | R::STARSTAREQ | R::AMPEQ | R::AMPAMPEQ | R::PIPEEQ | R::PIPEPIPEEQ
185            | R::CARETEQ | R::LTLTEQ | R::GTGTEQ
186            // Hash arrow, ternary, range
187            | R::EQGT | R::DOTDOT | R::DOTDOTDOT
188            // Subshell backtick used as method-name marker (def `...)
189            | R::BQUOTE
190                => TokenRole::Operator,
191
192            // String-like literals contribute one operand each when
193            // inert. The wrapper is suppressed exactly when it holds a
194            // child the walk already counts, so its contribution is not
195            // billed twice — the shared spelling of C# #183 / Elixir
196            // #180 (`Interpolation`) and of #1353 (the element kinds).
197            //
198            // `String`, `BareString`, `BareSymbol`, `Subshell`, `Regex`,
199            // `HeredocBody` and `DelimitedSymbol` admit only
200            // `string_content` / `escape_sequence` / `interpolation` as
201            // named children (`heredoc_body` also `heredoc_content` /
202            // `heredoc_end`), of which `Interpolation` alone is
203            // classified elsewhere; the delimiter tokens they also hold
204            // are anonymous and no arm names them.
205            //
206            // The three *element containers* hold classified operands
207            // instead, so before #1353 the guard never fired for them
208            // and the wrapper was billed alongside every element:
209            // `b = %w[x y]` scored n2 4 / N2 4 for three operands, the
210            // spare entry being the wrapper's whole-span text. That made
211            // the vocabulary grow with how the author grouped the
212            // literals — the spelling sensitivity #695 removed for
213            // Python's implicit concatenation and #1312 / #1314 for
214            // delimiter tokens.
215            //
216            //   `chained_string` ⊃ `string`      (`"a" "b"`)
217            //   `string_array`   ⊃ `bare_string` (`%w[…]`, `%W[…]`)
218            //   `symbol_array`   ⊃ `bare_symbol` (`%i[…]`, `%I[…]`)
219            //
220            // Gated rather than deleted, per grammar-dispatch §6:
221            // node-types.json marks the two arrays' children optional
222            // and `%w[]` / `%i[]` really do parse to a wrapper holding
223            // nothing but its delimiter tokens, so dropping the kinds
224            // would score an empty literal zero. (`chained_string` is
225            // `seq($.string, repeat1($.string))` and so carries at
226            // least two elements; the guard therefore always fires and
227            // its membership here is unobservable — listed for symmetry
228            // with its siblings rather than out of need. See
229            // `ruby_element_containers_count_elements_not_the_composite_1353`,
230            // which says so rather than pretending to pin it.)
231            //
232            // One list serves both groups because no kind here can hold
233            // an element kind it is not paired with above, and none of
234            // the containers admits an `Interpolation` as a *direct*
235            // child — `%W[a#{n}]` nests it inside the `bare_string`,
236            // which is guarded by this same arm one level down.
237            //
238            // `BareSymbol` reached this arm in #1353; until then it sat
239            // unguarded in the plain operand arm below, so `%I[a#{n}b]`
240            // billed the element `a#{n}b` *and* the `n` inside it while
241            // the `%W[…]` spelling of the same thing billed only `n`.
242            // role-bypass: allow(StringLit) — the operand classification of the literals
243            // under the row's `wraps` list, a projection the row does not answer
244            R::String | R::ChainedString | R::BareString | R::BareSymbol
245            | R::Subshell | R::Regex | R::HeredocBody | R::DelimitedSymbol
246            | R::StringArray | R::SymbolArray => {
247                Self::string_operand_type(node, crate::roles::ruby::string_lit::WRAPS)
248            }
249
250            // The numeral inside a suffixed numeric literal. At the
251            // pinned tree-sitter-ruby the two suffix forms are wrappers
252            // over the numeral they suffix, never leaves:
253            //
254            //   rational: seq($._int_or_float, token.immediate('r'))
255            //   complex:  choice(
256            //               seq($._int_or_float, token.immediate('i')),
257            //               seq(alias($._int_or_float, $.rational),
258            //                   token.immediate('ri')))
259            //
260            // so `2i` is a `complex` over an `integer`, and `3ri` a
261            // `complex` over a `rational` over an `integer` — three
262            // levels deep, every one of which the plain operand arm
263            // below billed. `a = 1r; b = 2i; c = 3ri; d = 4` reported
264            // n2 11 / N2 12 for its eight operands (#1359).
265            //
266            // Neither §1 nor §2 adds a kind to name here, and both
267            // facts are pinned in the test rather than trusted:
268            // `_int_or_float` is hidden, so `Ruby::IntOrFloat` exists
269            // in the enum and the parser never emits it, leaving the
270            // wrapper itself as the numeral's parent; and the `ri`
271            // form's `alias(…, $.rational)` reuses kind 308 instead of
272            // minting a suffixed variant, so the middle node is a
273            // `rational` whose span holds no `r` of its own.
274            //
275            // The wrapper is the keeper here, not the leaf. `1`, `1r`,
276            // `1i` and `1ri` are four distinct Ruby constants; billing
277            // the leaf would file all four under the operand text `1`
278            // and erase what makes them different values. Every other
279            // language here spells the suffix inside a single token
280            // (`1u32`, `1L`, `1j`), so keeping the wrapper is what
281            // makes Ruby agree with its siblings. It is the same
282            // resolution the `Nil` / `Nil2` pair takes below, and the
283            // opposite of the one `%w[…]` takes above — there the
284            // wrapper holds operands that stand on their own, here the
285            // three levels are one constant.
286            //
287            // Gated rather than deleted, though nothing regresses to
288            // zero either way (§6): node-types.json marks both
289            // wrappers' lone numeral child `"required": true`, and an
290            // unsuffixed `4` carries no wrapper at all, so the arm
291            // below still owns it. §6's keeper rule — take the node
292            // present for *every* spelling — would pick the leaf, but
293            // that rule exists to stop a childless variant scoring
294            // zero and neither choice can do that here. With the
295            // hazard absent the tiebreak is operand identity, which
296            // only the wrapper's span carries.
297            //
298            // Written on the parent per §5, but unlike the regex guard
299            // above the choice is unobservable: `complex` and
300            // `rational` admit numeral children and nothing else, so no
301            // node can have either as an *ancestor* without having it
302            // as its parent. No Ruby input tells the two spellings
303            // apart, and no test can pin the difference.
304            //
305            // Every kind in both sets is load-bearing. Drop `Rational`
306            // from the guarded set and the middle node of `3ri` is
307            // billed again; drop it from the parent set and the leaf
308            // under a bare `1r` is. Only their *pairing* is
309            // unobservable — a `rational` directly inside a `rational`
310            // is not a shape this grammar admits.
311            R::Integer | R::Float | R::Rational
312                if ancestors
313                    .parent(node)
314                    .is_some_and(|p| matches!(p.kind_id().into(), R::Complex | R::Rational)) =>
315            {
316                TokenRole::Unknown
317            }
318
319            // Operands: identifiers and literals.
320            R::Identifier | R::IdentifierSuffix | R::IdentifierSuffixToken1
321            | R::Constant | R::ConstantSuffix | R::ConstantSuffixToken1
322            // role-bypass: allow(Member, StringLit) — an operand by kind wherever it sits
323            // (the `Member` row owns a variable only as an assignment target) and the
324            // string-like literals that cannot interpolate, which the `StringLit` row owns
325            // and this arm bills as plain operands
326            | R::InstanceVariable | R::ClassVariable | R::GlobalVariable
327            | R::Integer | R::Float | R::Complex | R::Rational
328            | R::Character | R::SimpleSymbol | R::HashKeySymbol
329            // `Nil2` is the leaf `nil` keyword token; `Nil` (named) wraps
330            // it. Counting both would double-count every `nil` literal —
331            // only the wrapping named node contributes one operand.
332            | R::True | R::False | R::Nil
333            | R::Zelf | R::Super
334            | R::Line | R::File | R::Encoding
335                => TokenRole::Operand,
336
337            _ => TokenRole::Unknown,
338        }
339    }
340
341    get_operator!(Ruby);
342}