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