Skip to main content

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