big_code_analysis_ast/getter/kotlin.rs
1//! `Getter` implementation for Kotlin.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6/// Returns the byte length of the leading Kotlin identifier in `text`
7/// — a Unicode letter or `_` start followed by letters / digits / `_`
8/// — or `0` if `text` does not start with an identifier.
9///
10/// The short string template `$name` interpolates a *simple
11/// identifier*, but the kotlin-ng grammar does not tokenise at the
12/// identifier boundary: it splits the literal only at each `$`, so the
13/// token after `$` absorbs any trailing inter-segment text into its own
14/// byte range. For `"$a $b"` the token after the first `$` is `"a "`
15/// (with the trailing space), and for `"$x is "` it is `"x is "`. Taking
16/// the maximal leading-identifier prefix recovers the interpolated
17/// variable (`a`, `x`) and treats the remainder as literal text, so the
18/// short form matches the long `${a}` / `${x}` form (#454). A token with
19/// no identifier prefix (`"price: $5"` → `"5"`, digit start) yields `0`
20/// and stays literal.
21fn kotlin_leading_identifier_len(text: &str) -> usize {
22 let mut chars = text.char_indices();
23 let Some((_, first)) = chars.next() else {
24 return 0;
25 };
26 if first != '_' && !first.is_alphabetic() {
27 return 0;
28 }
29 // The leading identifier ends at the first byte that is neither `_`
30 // nor alphanumeric; everything from there on is inter-segment
31 // literal text the grammar glued onto this `$name` token.
32 let mut end = first.len_utf8();
33 for (idx, c) in chars {
34 if c == '_' || c.is_alphanumeric() {
35 end = idx + c.len_utf8();
36 } else {
37 break;
38 }
39 }
40 end
41}
42
43/// Returns whether the `string_content` token `node` is (or begins
44/// with) the variable-name part of a Kotlin short string template
45/// (`$name`). The kotlin-ng grammar emits no structured node for this
46/// form — the `$` sigil and the variable name arrive as two adjacent
47/// `string_content` tokens (verified by AST dump, #454). The name token
48/// is recognised by a preceding `string_content` sibling spelled
49/// exactly `$` plus its own text starting with an identifier. Because
50/// the grammar glues trailing inter-segment text onto the name token
51/// (`"$a $b"` → `"a "`, `"$x is "` → `"x is "`), a non-empty leading
52/// identifier prefix is sufficient; the prefix is the recovered operand
53/// and the remainder is literal text. Only a token with no identifier
54/// prefix (`"price: $5"` → `"5"`) stays literal.
55fn kotlin_is_short_interp_name(node: &Node, previous: Option<Node<'_>>, code: &[u8]) -> bool {
56 use Kotlin::{StringContent, StringContent2, StringContent3};
57
58 // The grammar emits three aliased `string_content` kind ids
59 // (single-line uses `StringContent3`, others `StringContent` /
60 // `StringContent2`); all render as the text `"string_content"`.
61 const STRING_CONTENT_KINDS: [u16; 3] = [
62 StringContent as u16,
63 StringContent2 as u16,
64 StringContent3 as u16,
65 ];
66
67 if !STRING_CONTENT_KINDS.contains(&node.kind_id()) {
68 return false;
69 }
70 let Some(prev) = previous else {
71 return false;
72 };
73 if !STRING_CONTENT_KINDS.contains(&prev.kind_id()) || prev.utf8_text(code) != Some("$") {
74 return false;
75 }
76 node.utf8_text(code)
77 .is_some_and(|text| kotlin_leading_identifier_len(text) > 0)
78}
79
80/// Returns the byte slice keying the Halstead operand for a Kotlin
81/// short-interpolation name token (`$name`). The grammar glues trailing
82/// inter-segment text onto the name token, so the raw node bytes for
83/// `"$a $b"` are `"a "` — keying that would record a distinct `"a "`
84/// operand and break parity with the long `${a}` form. Narrow the slice
85/// to the leading identifier prefix so the operand is keyed as the bare
86/// identifier (`"a"`), matching the long form (#454).
87fn kotlin_short_interp_operand_bytes<'a>(node: &Node, code: &'a [u8]) -> &'a [u8] {
88 let start = node.start_byte();
89 let end = node.end_byte();
90 let full = &code[start..end];
91 match std::str::from_utf8(full) {
92 Ok(text) => {
93 let prefix_len = kotlin_leading_identifier_len(text);
94 if prefix_len > 0 {
95 &full[..prefix_len]
96 } else {
97 full
98 }
99 }
100 Err(_) => full,
101 }
102}
103
104/// Returns whether a Kotlin string literal `node` carries any
105/// interpolation: the long `${expr}` form (a structured `Interpolation`
106/// child) or the short `$name` form (adjacent `$` + identifier
107/// `string_content` tokens). The wrapping literal yields Unknown in
108/// either case so the inner expression is the only counted operand
109/// (#454).
110fn kotlin_string_has_interp(node: &Node, code: &[u8]) -> bool {
111 // The long form is the `StringLit` row's `wraps` list; the short
112 // form has no node of its own, so the row cannot name it and this
113 // reads the bytes. The scan already holds each child's predecessor,
114 // so the short-form test gets it for free rather than through the
115 // `O(depth)` `Node::previous_sibling` (#1096).
116 let mut previous = None;
117 node.children().any(|child| {
118 let found = crate::roles::kotlin::string_lit::WRAPS.contains(&child.kind_id())
119 || kotlin_is_short_interp_name(&child, previous, code);
120 previous = Some(child);
121 found
122 })
123}
124
125// A qualified `super<A>` (a `super_expression`) encloses the supertype
126// it names (#1567).
127const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
128 lists: &[
129 Kotlin::TypeArguments as u16,
130 Kotlin::TypeParameters as u16,
131 Kotlin::SuperExpression as u16,
132 ],
133 openers: &[Kotlin::LT as u16],
134 closers: &[Kotlin::GT as u16],
135 is_misparse: never_misparsed,
136};
137
138impl Getter for KotlinCode {
139 /// Names the space, synthesising one for constructs that carry no
140 /// name token (#1184).
141 ///
142 /// `get_func_space_name` returns `Option<&'a str>` borrowed from
143 /// `code`, so the only name available for a nameless construct is a
144 /// `&'static str` — a per-property spelling like `<get-foo>` would
145 /// need a signature change. Angle brackets follow the existing
146 /// `<anonymous>` convention and cannot collide with a real
147 /// identifier in any of these grammars.
148 ///
149 /// Sibling collisions are accepted, exactly as multiple
150 /// `<anonymous>` siblings already are: two properties each with a
151 /// getter, or two `static { }` blocks in one class, produce two
152 /// spaces with the same name. Nothing enforces name uniqueness
153 /// among siblings, and inventing an index would make the name
154 /// unstable under an unrelated edit.
155 ///
156 /// `<get>` / `<set>` are Kotlin's own spelling of the accessor
157 /// keywords; `<init>` is what the JVM calls the constructor an
158 /// `init` block compiles into.
159 fn get_func_space_name<'a, 'tree>(
160 node: &Node<'tree>,
161 code: &'a [u8],
162 ancestors: Ancestors<'tree, '_>,
163 ) -> Option<&'a str> {
164 // role-bypass: allow(FuncOpener) — a naming rule, not whether the
165 // node opens a space
166 match node.kind_id().into() {
167 Kotlin::Getter => Some("<get>"),
168 Kotlin::Setter => Some("<set>"),
169 Kotlin::AnonymousInitializer => Some("<init>"),
170 _ => crate::getter::default_func_space_name(node, code, ancestors),
171 }
172 }
173
174 // The mapping is the `opens` annotations of `roles/kotlin.rs`
175 // (#1696); the byte-less spelling forwards with no bytes and no
176 // chain, as the old one read neither.
177 impl_byte_less_space_kind!(kotlin);
178
179 fn get_space_kind_with_code<'a>(
180 node: &Node<'a>,
181 code: &[u8],
182 ancestors: Ancestors<'a, '_>,
183 ) -> SpaceKind {
184 crate::roles::kotlin::opens_space(node, code, ancestors)
185 }
186
187 keyword_roles!(kotlin);
188
189 paying_roles!(kotlin);
190
191 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
192 use Kotlin::*;
193
194 if GENERIC_ANGLES.is_closer(node, ancestors) {
195 return TokenRole::Unknown;
196 }
197
198 // The modifiers, the declaration keywords and `reified` are not
199 // here: `roles/kotlin.rs` declares them, gate included, and
200 // `get_keyword_role` bills them (#1693).
201 let kind: Kotlin = node.kind_id().into();
202
203 // The accessor keywords, billed as C# bills its `get` / `set`
204 // (#1564), but only directly under their `getter` / `setter`,
205 // which stay unlisted. The same leaves are the `@get:` / `@set:`
206 // use-site targets, which bill nothing, like `@field:` and
207 // `@property:`; and where kotlin-ng misreads a call `get(1)` after
208 // a local `val f = 6`, an `ERROR` holds the leaf. Used as a name
209 // otherwise (`val get = 1`, `x.set(v)`, `fun get()`) the word
210 // parses as an identifier. The grammar also reads a local
211 // `val f = 6` followed by `set = 2` as a setter, which bills
212 // `set`. `field` in an accessor body is an identifier, so it is an
213 // operand like any other variable. An early return for the same
214 // reason as the modifiers'.
215 let accessor = match kind {
216 Get => Some(Kotlin::Getter),
217 Set => Some(Setter),
218 _ => None,
219 };
220 if let Some(accessor) = accessor {
221 return if ancestors.parent_has_kind(node, accessor as u16) {
222 TokenRole::Operator
223 } else {
224 TokenRole::Unknown
225 };
226 }
227
228 match kind {
229 // Operator: control flow keywords
230 If | Else | When | For | While | Do | Try | Catch | Finally | Throw | Return
231 | ReturnAT
232 // Operator: other keywords. `init`, `where` and `by` bill as
233 // C# bills `where` and TypeScript `type` (#1564), each the
234 // leaf of its `anonymous_initializer` / `type_constraints` /
235 // `property_delegate` or `explicit_delegation` wrapper; used
236 // as names (`val by = 1`, `where(x)`, `init.f()`) they parse
237 // as identifiers, so the leaf exists only in its construct.
238 // `in` is the variance modifier and the operator of `for` /
239 // `x in y` in one kind, billed here; `out` is the row's.
240 // `is` / `!is` / `in` / `!in` for the spellings the row's
241 // expression gate leaves out — a `when` entry's `type_test` /
242 // `range_test` and a `for` header's `in` — which billed
243 // before the row existed.
244 // role-bypass: allow(Comparison) — the operator classification of the spellings the
245 // row's `under IsExpression` / `under InExpression` gates leave out
246 | In | Is | BANGis | BANGin
247 | As | AsQMARK | Constructor | Init | Where | By
248 // Operator: brackets, separators, terminators
249 | SEMI | COMMA | COLONCOLON | DOT | LBRACE | LBRACK | LPAREN
250 // Operator: assignment and arithmetic
251 | EQ | PLUS | DASH | STAR | SLASH | PERCENT
252 | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ
253 | PLUSPLUS | DASHDASH
254 // `<` / `>` for the spellings the `Comparison` row's parent
255 // gate leaves out — `super<A>`, a generic bracket (the `<>`
256 // pair), a recovered token — which billed before the row
257 // existed; the equalities, the short-circuit tokens, the
258 // elvis `?:` and the safe navigation's `?.` are the rows' and
259 // `get_paying_role` bills them (#1695). `!!` is excluded on
260 // the `NullSafe` row and bills here.
261 // role-bypass: allow(Comparison) — the operator classification of the spellings the
262 // row's `under BinaryExpression` gate leaves out
263 | LT | GT
264 // Operator: logical and misc
265 | BANG | BANGBANG
266 | QMARK
267 | DOTDOT | DOTDOTLT | DASHGT | COLON => TokenRole::Operator,
268 // Operands: identifiers and literals, plus the self- and
269 // super-reference leaves (#1380). Four leaf kinds, not two:
270 // the label-qualified spellings `this@Outer` / `super@Inner`
271 // are `this@` / `super@` tokens, distinct kind_ids that
272 // carry no `this` / `super` leaf of their own — the same
273 // shape as `return@`, already listed among the operators
274 // above.
275 //
276 // The leaves are the keepers, not the `this_expression` /
277 // `super_expression` wrappers (grammar-dispatch section 6):
278 // a `constructor_delegation_call` (`constructor() : this(0)`,
279 // `: super(x)`) emits a bare leaf with no wrapper at all, so
280 // billing the wrapper would score constructor delegation
281 // zero. Classifying both would double-count, and the
282 // wrapper's span swallows the label identifier that is
283 // already billed on its own (section 5).
284 Identifier | NumberLiteral | FloatLiteral | CharacterLiteral | Label | This
285 | Super | ThisAT | SuperAT => TokenRole::Operand,
286 // Regression #191: a Kotlin string template wraps an
287 // `Interpolation` child (the long `"${expr}"` form) whose
288 // inner expressions are walked and counted separately, so
289 // the wrapping literal yields Unknown to avoid double-
290 // counting (same pattern as #180 Bash/Elixir, #184 PHP).
291 // The short `"Hi $name"` form has no `Interpolation` node —
292 // it needs the source bytes to distinguish `$name` from
293 // literal `$5`, so it is handled in `get_op_type_with_code`;
294 // this byte-less arm sees only the long form. Both single-
295 // line and multi-line (triple-quoted) literals interpolate.
296 // role-bypass: allow(StringLit) — the operand classification of the literals
297 // under the row's `wraps` list, a projection the row does not answer
298 StringLiteral | MultilineStringLiteral => {
299 Self::string_operand_type(node, crate::roles::kotlin::string_lit::WRAPS)
300 }
301 _ => TokenRole::Unknown,
302 }
303 }
304
305 fn get_op_type_with_code<'a>(
306 node: &Node<'a>,
307 code: &[u8],
308 ancestors: Ancestors<'a, '_>,
309 ) -> TokenRole {
310 use Kotlin::*;
311
312 match node.kind_id().into() {
313 // The kotlin-ng grammar emits no structured node for the
314 // short string template `"Hi $name"` — the `$` sigil and the
315 // variable name arrive as two adjacent `string_content`
316 // tokens (issue #454). When the name token is a clean
317 // identifier, recover it as the operand the long `${name}`
318 // form would have produced, so both template forms count the
319 // inner variable and suppress the wrapping literal (the
320 // wrapper arm below). The grammar does not tokenise at the
321 // identifier boundary for mid-segment forms (`"$x is "`), so
322 // those are left as literal text rather than emitting a
323 // partial-literal operand.
324 StringContent | StringContent2 | StringContent3
325 if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) =>
326 {
327 TokenRole::Operand
328 }
329 // The wrapping literal is Unknown when it interpolates in
330 // either form (long `${expr}` or short `$name`); the inner
331 // expression / recovered variable is the only operand. A
332 // plain literal has no interpolation and stays one operand.
333 // role-bypass: allow(StringLit) — the operand classification of the literals
334 // under the row's `wraps` list, a projection the row does not answer
335 StringLiteral | MultilineStringLiteral => {
336 if kotlin_string_has_interp(node, code) {
337 TokenRole::Unknown
338 } else {
339 TokenRole::Operand
340 }
341 }
342 _ => keyword_or_op_type::<Self>(node, code, ancestors),
343 }
344 }
345
346 fn get_operand_id<'a>(
347 node: &Node<'a>,
348 code: &'a [u8],
349 ancestors: Ancestors<'a, '_>,
350 ) -> &'a [u8] {
351 // Narrow a recovered short-interpolation name token to its
352 // leading identifier prefix so `"$a $b"` keys operand `"a"`,
353 // not `"a "`, matching the long `${a}` form (#454).
354 if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) {
355 kotlin_short_interp_operand_bytes(node, code)
356 } else {
357 &code[node.start_byte()..node.end_byte()]
358 }
359 }
360
361 fn get_operator_spelling<'a>(
362 node: &Node<'a>,
363 ancestors: Ancestors<'a, '_>,
364 ) -> Option<&'static str> {
365 GENERIC_ANGLES.opener_spelling(node, ancestors)
366 }
367
368 get_operator!(Kotlin);
369}