big_code_analysis_ast/getter/java.rs
1//! `Getter` implementation for Java.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
7 lists: &[Java::TypeArguments as u16, Java::TypeParameters as u16],
8 openers: &[Java::LT as u16],
9 closers: &[Java::GT as u16],
10 is_misparse: never_misparsed,
11};
12
13impl Getter for JavaCode {
14 /// Names the space, synthesising one for constructs that carry no
15 /// name token (#1184).
16 ///
17 /// `get_func_space_name` returns `Option<&'a str>` borrowed from
18 /// `code`, so the only name available for a nameless construct is a
19 /// `&'static str` — a per-property spelling like `<get-foo>` would
20 /// need a signature change. Angle brackets follow the existing
21 /// `<anonymous>` convention and cannot collide with a real
22 /// identifier in any of these grammars.
23 ///
24 /// Sibling collisions are accepted, exactly as multiple
25 /// `<anonymous>` siblings already are: two properties each with a
26 /// getter, or two `static { }` blocks in one class, produce two
27 /// spaces with the same name. Nothing enforces name uniqueness
28 /// among siblings, and inventing an index would make the name
29 /// unstable under an unrelated edit.
30 ///
31 /// `<static-init>` rather than the JVM's `<clinit>`: the same
32 /// construct exists in JavaScript, where `<clinit>` would mean
33 /// nothing, and one spelling across languages is worth more here
34 /// than JVM precision.
35 fn get_func_space_name<'a, 'tree>(
36 node: &Node<'tree>,
37 code: &'a [u8],
38 ancestors: Ancestors<'tree, '_>,
39 ) -> Option<&'a str> {
40 // role-bypass: allow(FuncOpener) — naming, not membership: which opener gets the synthetic
41 // name
42 if node.kind_id() == Java::StaticInitializer as u16 {
43 return Some("<static-init>");
44 }
45 crate::getter::default_func_space_name(node, code, ancestors)
46 }
47
48 // The mapping is the `opens` annotations of `roles/java.rs` (#1696):
49 // `EnumDeclaration` and `RecordDeclaration` are class-like and share
50 // `Class`; `AnnotationTypeDeclaration` maps to `Interface` (#280); an
51 // anonymous class opens `Class` only with a body (#463); a record's
52 // compact constructor shares the constructor's kind (#1160); `static
53 // { … }` is a `Function` (#1184). A lambda opens nothing — the walk
54 // never promoted one, and before #1696 this answered `Function` for
55 // a node it was never asked about. Java's rows read no bytes and no
56 // chain, so the byte-less spelling forwards with none.
57 impl_byte_less_space_kind!(java);
58
59 fn get_space_kind_with_code<'a>(
60 node: &Node<'a>,
61 code: &[u8],
62 ancestors: Ancestors<'a, '_>,
63 ) -> SpaceKind {
64 crate::roles::java::opens_space(node, code, ancestors)
65 }
66
67 keyword_roles!(java);
68
69 paying_roles!(java, control_flow);
70
71 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
72 use Java::*;
73
74 if GENERIC_ANGLES.is_closer(node, ancestors) {
75 return TokenRole::Unknown;
76 }
77 // Some guides that informed grammar choice for Halstead
78 // keywords, operators, literals: https://docs.oracle.com/javase/specs/jls/se18/html/jls-3.html#jls-3.12
79 // https://www.geeksforgeeks.org/software-engineering-halsteads-software-metrics/?msclkid=5e181114abef11ecbb03527e95a34828
80 // The modifiers, the declaration keywords and the primitive
81 // types are not here: `roles/java.rs` declares them, gates
82 // included, and `get_keyword_role` bills them (#1693). Nor are
83 // the comparison operators, `instanceof`, `&&` and `||`: the
84 // `Comparison` and `ShortCircuit` rows declare them and
85 // `get_paying_role` bills them (#1694).
86 match node.kind_id().into() {
87 // Operator: control flow. `case` is the `CaseArm` row's, and
88 // `if` / `switch` / `for` / `while` / `catch` the `Branch` /
89 // `Switch` / `Loop` / `Catch` rows' payers, all billed by
90 // `get_paying_role` (#1695, #1697); `default` is the fallback
91 // label's and stays, as do the keywords no row owns. `?` stays
92 // for the spelling the `Ternary` row's `under
93 // TernaryExpression` gate leaves out — a wildcard bound
94 // (`List<? extends T>`) — which billed before the row existed;
95 // the ternary's `?` is the row's.
96 // role-bypass: allow(Ternary) — the operator classification of the spelling the
97 // row's `under TernaryExpression` gate leaves out: a wildcard bound
98 Else | Try | Throw | Throws | Throws2 | Continue | Break | Do | Finally
99 // Operator: keywords. `default` is one kind for a `switch`
100 // label and an interface method's modifier.
101 | New | Return | Default | Assert | Extends | Implements
102 // Operator: brackets and comma and terminators (separators)
103 | SEMI | COMMA | COLONCOLON | DOT | DASHGT | LBRACE | LBRACK | LPAREN
104 // Operator: operators.
105 | EQ | BANG | TILDE | QMARK | COLON | PLUSPLUS | DASHDASH
106 | PLUS | DASH | STAR | SLASH | AMP | PIPE | CARET | PERCENT | LTLT | GTGT | GTGTGT
107 | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | AMPEQ | PIPEEQ | CARETEQ | PERCENTEQ
108 | LTLTEQ | GTGTEQ | GTGTGTEQ
109 => {
110 TokenRole::Operator
111 },
112 // The `Comparison` row pays `<` / `>` only under a
113 // `binary_expression` and `instanceof` only under its
114 // expression, the gates ABC needs (#1274, #1461). Halstead
115 // bills every other spelling too: the opener of a generic
116 // list (`List<String>`, as the `<>` pair — #1559; its closer
117 // returned `Unknown` above) and a token error recovery
118 // reparents under `ERROR` (`return a < ;`, `x instanceof` at
119 // end of input), which billed before the row existed and
120 // must not stop. So this arm is unconditional, and for these
121 // three kinds the row is not what makes Halstead bill them —
122 // the perturbation evidence for the Halstead path is the
123 // other six payers.
124 // role-bypass: allow(Comparison) — the operator classification of the spellings the row's
125 // `under BinaryExpression` / `under InstanceofExpression` gates leave out: a generic
126 // opener and a recovered token
127 LT | GT | Instanceof => TokenRole::Operator,
128 // `super` is the receiver of `super.f()` / `super(x)` /
129 // `super::f` everywhere except a wildcard type bound, where
130 // `? super String` denotes no value and is the mirror image
131 // of `? extends String` — whose `extends` this same match
132 // bills as an operator. Both keywords are direct children of
133 // the same `wildcard` node, so the parent alone separates
134 // the bound from the reference (#1380).
135 Super => match ancestors.parent(node).map(|p| p.kind_id().into()) {
136 Some(Wildcard) => TokenRole::Operator,
137 _ => TokenRole::Operand,
138 },
139 // `class` as the tail of a class literal (`C.class`) is the
140 // operand the `.` acts on (#1566); the `DeclKeyword` row's
141 // gate leaves it to this arm, and carries the derivation.
142 // role-bypass: allow(DeclKeyword) — the operand classification of the gated-out spelling
143 Class if ancestors.parent_has_kind(node, ClassLiteral as u16) => TokenRole::Operand,
144 // Operands: variables, constants, literals. `This` joined
145 // them in #1380: a self-reference names the receiver a `.`
146 // or `::` acts on, so billing it as an operator made
147 // `this.x` a binary operator with one operand while `p.x`
148 // has one operator and two. The explicit receiver parameter
149 // (`void m(J J.this)`) reaches this arm too, and is an
150 // operand for the same reason a parameter name is — which is
151 // the opposite call from C#'s indexer declarator in
152 // `csharp.rs`, deliberately: a parameter name is an operand
153 // everywhere here, while a *member* named by a keyword sits
154 // with `operator +`.
155 //
156 // `TypeIdentifier` joined in #1560, as C#, Rust, the C family,
157 // Go, Groovy and TypeScript bill type names: a field or
158 // parameter type, an `implements` / `extends` entry, a type
159 // parameter, a generic argument, each segment of
160 // `java.util.List` (the `.` bills as itself), and since #1566
161 // the type of a class literal (`Foo.class`). It is the one
162 // type-name kind and no listed node wraps it, so each name
163 // bills once.
164 Identifier | TypeIdentifier | NullLiteral | True | False
165 | CharacterLiteral | HexIntegerLiteral | OctalIntegerLiteral
166 | BinaryIntegerLiteral | DecimalIntegerLiteral | HexFloatingPointLiteral
167 | DecimalFloatingPointLiteral | This => {
168 TokenRole::Operand
169 },
170 // A Java 21 string template (`STR."Hi \{name}!"`) is a
171 // `string_literal` holding `string_interpolation` children,
172 // whose expressions are walked and billed on their own; the
173 // wrapper then yields `Unknown` so `name` is not billed twice
174 // (#420's skip, which Java lacked until #1703). The
175 // interpolation set is the `StringLit` row's `wraps` list,
176 // spelled once in `roles/java.rs`. A plain literal has no
177 // such child and stays one operand.
178 // role-bypass: allow(StringLit) — the operand classification of the literal
179 // under the row's `wraps` list, a projection the row does not answer
180 StringLiteral => {
181 Self::string_operand_type(node, crate::roles::java::string_lit::WRAPS)
182 }
183 _ => {
184 TokenRole::Unknown
185 },
186 }
187 }
188
189 // `var x = …` parses `var` as a `type_identifier` (it is a reserved
190 // type name, not a keyword token), so the #1560 operand arm would
191 // bill an operand spelled `var` that names no type. It stays
192 // unbilled, as C#'s `var` (an `implicit_type` wrapping its own
193 // keyword) is; a variable *named* `var` is an `identifier` and is
194 // unaffected. Only the bytes tell the two type names apart, so the
195 // byte-less `get_op_type` above still answers `Operand` for it; the
196 // walk calls this spelling (grammar-dispatch section 7).
197 fn get_op_type_with_code<'a>(
198 node: &Node<'a>,
199 code: &[u8],
200 ancestors: Ancestors<'a, '_>,
201 ) -> TokenRole {
202 if node.kind_id() == Java::TypeIdentifier && node_text(code, node) == Some("var") {
203 return TokenRole::Unknown;
204 }
205 keyword_or_op_type::<Self>(node, code, ancestors)
206 }
207
208 fn get_operator_spelling<'a>(
209 node: &Node<'a>,
210 ancestors: Ancestors<'a, '_>,
211 ) -> Option<&'static str> {
212 GENERIC_ANGLES.opener_spelling(node, ancestors)
213 }
214
215 fn get_operator_id_as_str(id: u16) -> &'static str {
216 let typ = id.into();
217 match typ {
218 Java::LPAREN => "()",
219 Java::LBRACK => "[]",
220 Java::LBRACE => "{}",
221 // role-bypass: allow(Primitive) — naming: how the kind renders, not whether it is one
222 Java::VoidType => "void",
223 // The kind is `boolean_type`; spelled as written, as Groovy's
224 // text-keyed primitives are (#1568).
225 // role-bypass: allow(Primitive) — naming, as above
226 Java::BooleanType => "boolean",
227 _ => typ.into(),
228 }
229 }
230}