Skip to main content

big_code_analysis_ast/getter/
groovy.rs

1//! `Getter` implementation for Groovy.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6// `method_type_parameters` is the method-level spelling of
7// `type_parameters` (`<T> T id(T x)`). `TypeArguments2` is the alias
8// the grammar emits for every `type_arguments` since 0.4.0 added the
9// diamond (`new ArrayList<>()`) as a second spelling of `generic_type`;
10// the unsuffixed id is no longer reached, and
11// `groovy_generic_angles_are_one_pair_1559` fails by name if either
12// changes. `LT2` is the `token.immediate` `<` that `type_parameters`
13// and `type_arguments` open with; the parser reports it as `LT`, so it
14// is listed defensively, here and in the operator arm, and its absence
15// is pinned by `groovy_generic_opener_alias_never_reaches_kind_id`.
16const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
17    lists: &[
18        Groovy::TypeArguments as u16,
19        Groovy::TypeArguments2 as u16,
20        Groovy::TypeParameters as u16,
21        Groovy::MethodTypeParameters as u16,
22    ],
23    openers: &[Groovy::LT as u16, Groovy::LT2 as u16],
24    closers: &[Groovy::GT as u16],
25    is_misparse: never_misparsed,
26};
27
28impl Getter for GroovyCode {
29    /// Names the space, synthesising one for constructs that carry no
30    /// name token (#1184).
31    ///
32    /// `get_func_space_name` returns `Option<&'a str>` borrowed from
33    /// `code`, so the only name available for a nameless construct is a
34    /// `&'static str` — a per-property spelling like `<get-foo>` would
35    /// need a signature change. Angle brackets follow the existing
36    /// `<anonymous>` convention and cannot collide with a real
37    /// identifier in any of these grammars.
38    ///
39    /// Sibling collisions are accepted, exactly as multiple
40    /// `<anonymous>` siblings already are: two properties each with a
41    /// getter, or two `static { }` blocks in one class, produce two
42    /// spaces with the same name. Nothing enforces name uniqueness
43    /// among siblings, and inventing an index would make the name
44    /// unstable under an unrelated edit.
45    ///
46    /// `<static-init>` rather than the JVM's `<clinit>`: the same
47    /// construct exists in JavaScript, where `<clinit>` would mean
48    /// nothing, and one spelling across languages is worth more here
49    /// than JVM precision.
50    fn get_func_space_name<'a, 'tree>(
51        node: &Node<'tree>,
52        code: &'a [u8],
53        ancestors: Ancestors<'tree, '_>,
54    ) -> Option<&'a str> {
55        // role-bypass: allow(FuncOpener) — a naming rule, not whether the
56        // block opens a space
57        if node.kind_id() == Groovy::StaticInitializer as u16 {
58            return Some("<static-init>");
59        }
60        // A record's header takes the record's name (#1842).
61        crate::getter::func_space_name_from_owner(
62            node,
63            code,
64            ancestors,
65            crate::roles::groovy::is_record_header,
66        )
67    }
68
69    // The mapping is the `opens` annotations of `roles/groovy.rs`
70    // (#1696). The opener row reads the chain and the bytes for a
71    // record's header (#1842), so this forwards with a known-empty
72    // chain and labels that list `Unknown`, as the Checker half
73    // (`checker/groovy.rs`) answers `false`.
74    impl_byte_less_space_kind!(groovy, opener_gated);
75
76    fn get_space_kind_with_code<'a>(
77        node: &Node<'a>,
78        code: &[u8],
79        ancestors: Ancestors<'a, '_>,
80    ) -> SpaceKind {
81        crate::roles::groovy::opens_space(node, code, ancestors)
82    }
83
84    keyword_roles!(groovy);
85
86    paying_roles!(groovy, control_flow);
87
88    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
89        use Groovy::*;
90
91        if GENERIC_ANGLES.is_closer(node, ancestors) {
92            return TokenRole::Unknown;
93        }
94        // Mirrors `JavaCode`'s classification: module keywords
95        // (`Package`, `Import`, …) are excluded. The dekobon Groovy
96        // grammar (#246, #247)
97        // emits a distinct named node for every Groovy-specific
98        // operator (Elvis `?:`, safe-nav `?.`, identity `===`/`!==`,
99        // regex `=~`/`==~`, spaceship `<=>`, exclusive ranges
100        // `..<` / `<..` / `<..<`, `as` coercion, etc.); their leaf
101        // tokens are listed here as operators so Halstead counts the
102        // tokens directly rather than the wrapping expression node.
103        // `NumberLiteral` is the new grammar's consolidated numeric
104        // literal — the prior grammar split numbers by radix
105        // (Hex/Octal/Binary/Decimal Integer/Float).
106        match node.kind_id().into() {
107            // Slashy-string delimiter punctuation. A slashy string
108            // (`/xyz/`) is a `StringLiteral` whose closing delimiter is
109            // a `SLASH` — the kind id real division uses — so
110            // `def b = /xyz/` reported a `/` operator with no division
111            // in the source (#1314, the Groovy sibling of Elixir #1256
112            // and Ruby/Perl #1312). Only the *closer* is a child: the
113            // grammar folds the opening `/` into the literal's own
114            // span, so this fabricated one `/` per literal rather than
115            // Ruby's two. The `StringLiteral` is already the operand
116            // (below), so the delimiter is suppressed exactly when its
117            // parent is that node — the compound-leaf guard of
118            // grammar-dispatch section 5.
119            //
120            // Parent, not ancestor, and here that distinction is
121            // *observable*: a GString interpolation inside a slashy
122            // string (`/x${a / b}y/`) puts a real division under a
123            // `StringLiteral` ancestor, and an ancestor-scanning guard
124            // would swallow it. Pinned by
125            // `groovy_slashy_guard_is_parent_scoped_not_ancestor_scoped`.
126            //
127            // The other string forms need no arm: `'plain'` is a
128            // childless leaf, `"dq"` closes with `"` (`DQUOTE`), and
129            // dollar-slashy `$/…/$` closes with `/$` (`SLASHDOLLAR`) — none of
130            // which this match classifies. `~/ab.c/` is a
131            // `UnaryExpression` wrapping the same `StringLiteral`, so
132            // its `~` still counts.
133            SLASH
134                if ancestors.parent_has_kind(node, StringLiteral as u16) =>
135            {
136                TokenRole::Unknown
137            }
138            // `super` is an operator only as the bound of a `wildcard`
139            // (`List<? super T>`), where it denotes no value and mirrors
140            // `? extends T`'s `extends` — which the arm below bills as an
141            // operator. Everywhere else it names a receiver a `.`, `?.`
142            // or `::` acts on, so it is an operand. The parent alone
143            // separates the two, as #1380 settled for Java's
144            // identically-shaped arm.
145            //
146            // Forward compatibility, not a live fix: the pinned dekobon
147            // grammar spells `'super'` in the `wildcard` production and
148            // nowhere else, so every reference (`super(1)`, `super.h()`,
149            // `A.super.h()`, `super::h`, `super?.h()`) is already a plain
150            // `identifier` and an operand. Before the gate that agreement
151            // was a grammar accident — an ungated `Super` would bill a
152            // reference as an operator the moment a bump routed one here.
153            //
154            // The operand branch is consequently unreachable under the
155            // pin and deliberately untested: only error recovery on
156            // invalid Groovy (`List<? super>`) reaches it, and pinning
157            // that shape would make the grammar's present
158            // over-permissiveness the contract (grammar-dispatch section
159            // 6). `groovy_wildcard_super_bound_stays_an_operator` carries
160            // the node census that fails by name if a bump makes it
161            // reachable (#1419).
162            Super if ancestors.parent_has_kind(node, Wildcard as u16) => TokenRole::Operator,
163            Super => TokenRole::Operand,
164
165            // Control-flow + keyword operators (mirrors Java's set,
166            // minus tokens that no longer exist in the dekobon grammar
167            // — `This`, `VoidType`, `Throws2`). The modifiers, the
168            // declaration keywords and the primitive types are not
169            // here: `roles/groovy.rs` declares them, gates included, and
170            // `get_keyword_role` bills them (#1693).
171            // The comparison and short-circuit tokens — including the
172            // identity, regex and spaceship ones — are not here: the
173            // `Comparison` and `ShortCircuit` rows of `roles/groovy.rs`
174            // pay them and `get_paying_role` bills them (#1695). `<` /
175            // `>`, `in`, `!in` and `instanceof` stay for the spellings the
176            // rows' gates leave out — a generic bracket (`LT2` is the
177            // opener's alias), a recovered token (`o instanceof` or `a
178            // !in` at the end of a block strands the keyword under
179            // `ERROR`), the `in` of a `for (x in xs)` header — which
180            // billed before the rows existed; `!in` is a token since
181            // dekobon-tree-sitter-groovy 0.6.0 and bills as `in` does.
182            // role-bypass: allow(Comparison, Ternary) — the operator classification of the
183            // spellings the rows' `under BinaryExpression` / `under MembershipExpression` /
184            // `under InstanceofExpression` / `under TernaryExpression` gates leave out
185            LT | LT2 | GT | In | BANGin | Instanceof
186            // `case` is the `CaseArm` row's, and `if` / `switch` / `for` /
187            // `while` / `catch` the `Branch` / `Switch` / `Loop` / `Catch`
188            // rows' payers, all billed by `get_paying_role` (#1695,
189            // #1697); `default` is the fallback label's and stays.
190            | Else | Try | Throw | Throws | Continue
191            | Break | Do | Finally | New | Return | Default | Assert
192            | Extends | Implements | As
193            // Separators / brackets.
194            | SEMI | COMMA | COLONCOLON | DOT | DASHGT | LBRACE | LBRACK | LPAREN
195            // Java-compatible operators (arithmetic, bitwise, assignment).
196            // `?` stays for the spelling the `Ternary` row's `under TernaryExpression`
197            // gate leaves out — a wildcard bound — which billed before the
198            // row existed.
199            | EQ | BANG | TILDE | QMARK | COLON
200            | PLUSPLUS | DASHDASH | PLUS | DASH | STAR | SLASH | AMP
201            | PIPE | CARET | PERCENT | LTLT | GTGT | GTGTGT | PLUSEQ | DASHEQ | STAREQ
202            | SLASHEQ | AMPEQ | PIPEEQ | CARETEQ | PERCENTEQ | LTLTEQ | GTGTEQ | GTGTGTEQ
203            | STARSTAR | STARSTAREQ
204            // Groovy-specific operator tokens added by the dekobon
205            // grammar (closes #247): ranges `..` / `..<` / `<..` /
206            // `<..<`, Elvis-assign `?=`, spread-dot `*.`, method-pointer
207            // `.&`, direct-field `.@`, logical implication `==>`, and
208            // spread-map `*:` (the identity, spaceship and regex tokens
209            // are the `Comparison` row's; the elvis `?:`, safe-nav `?.`,
210            // safe-chain `??.` and safe-index `?[` the `NullSafe` row's).
211            | DOTDOT | DOTDOTLT | LTDOTDOT | LTDOTDOTLT | QMARKEQ
212            | STARDOT | DOTAMP | DOTAT
213            | EQEQGT | STARCOLON => TokenRole::Operator,
214
215            // `QualifiedName` (a `package` / `import` path) and
216            // `QualifiedType` (`java.util.Map` in type position) were
217            // listed here until #1263, and `QualifiedName` really did
218            // double-count: `package com.example` billed `com`,
219            // `example` AND `com.example`. `QualifiedType` never fired,
220            // because the runtime emits the *alias* `QualifiedType2`
221            // that this arm did not name — a latent
222            // lesson-2 miss whose only effect was to make the wrong
223            // classification unobservable for that half. Both are gone
224            // rather than completed: a qualified path is its identifier
225            // leaves plus the `.` operator, as in every other language
226            // here, and as PHP settled the same call in #1293.
227            //
228            // Completing the alias list instead is the double count,
229            // not the fix. Both halves are pinned against that by
230            // `groovy_qualified_name_counts_leaves_not_the_composite_1263`
231            // and `groovy_qualified_type_counts_leaves_not_the_composite_1352`.
232            // Neither wrapper is ever a name's sole carrier
233            // (grammar-dispatch section 6): `import java` still nests an
234            // `identifier`, and a single-segment type is a bare
235            // `type_identifier` the grammar does not wrap at all.
236            // role-bypass: allow(Primitive, DeclKeyword) — the operand classification of a
237            // name neither row's text gate claimed, as a primitive or as `var`
238            Identifier | TypeIdentifier | NullLiteral | True | False | NumberLiteral => {
239                TokenRole::Operand
240            }
241
242            // A Groovy GString interpolates inner expressions whose
243            // operands are walked and counted separately, so the
244            // wrapping literal must yield Unknown to avoid double-
245            // counting (issue #454, same mechanism as Kotlin #191 /
246            // PHP #184 / Elixir #180, generalized in #420). The dekobon
247            // grammar emits two interpolation child kinds: the braced
248            // long form `${expr}` (`gstring_brace_interpolation`) and
249            // the short `$name` / `$obj.field` form
250            // (`gstring_dollar_interpolation`). A plain non-interpolated
251            // literal has neither child and stays a single operand.
252            // role-bypass: allow(StringLit) — the operand classification of the literals
253            // under the row's `wraps` list, a projection the row does not answer
254            StringLiteral => {
255                Self::string_operand_type(node, crate::roles::groovy::string_lit::WRAPS)
256            }
257
258            _ => TokenRole::Unknown,
259        }
260    }
261
262    fn get_operator_spelling<'a>(
263        node: &Node<'a>,
264        ancestors: Ancestors<'a, '_>,
265    ) -> Option<&'static str> {
266        GENERIC_ANGLES.opener_spelling(node, ancestors)
267    }
268
269    fn get_operator_id_as_str(id: u16) -> &'static str {
270        let typ = id.into();
271        match typ {
272            Groovy::LPAREN => "()",
273            Groovy::LBRACK => "[]",
274            Groovy::LBRACE => "{}",
275            _ => typ.into(),
276        }
277    }
278}