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