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.
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    use Kotlin::Interpolation;
112
113    // The scan already holds each child's predecessor, so the short-form
114    // test gets it for free rather than through the `O(depth)`
115    // `Node::previous_sibling` (#1096).
116    let mut previous = None;
117    node.children().any(|child| {
118        let found = child.kind_id() == Interpolation as u16
119            || kotlin_is_short_interp_name(&child, previous, code);
120        previous = Some(child);
121        found
122    })
123}
124
125// Whether `node`, a modifier keyword leaf, sits in a modifier list the
126// grammar built (#1558), rather than in the recovery of a soft-keyword
127// *name* it failed to parse. Two recoveries strand the leaf:
128//
129// - an `ERROR` holds it, usually still wrapped in its `*_modifier`
130//   node (`open = !open` at statement start, `val suspend = 1`), so the
131//   first ancestor above the wrappers is the `ERROR`;
132// - a modifier list is followed by an inserted, zero-width name
133//   (`fun f(vararg: Int)`, `class C(open: Int)`).
134//
135// Kinds are compared by name: `*_modifier` covers every wrapper, and
136// `user_type` is where recovery can hang `type_modifiers`. The inserted
137// name is found by width, not `is_missing()` (grammar-dispatch).
138fn kotlin_modifier_was_written_as_one<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
139    let host = ancestors
140        .iter(node)
141        .map(|(ancestor, _)| ancestor)
142        .find(|ancestor| {
143            let kind = ancestor.kind();
144            !(kind.ends_with("_modifier") || kind == "type_modifiers" || kind == "user_type")
145        });
146    host.is_some_and(|host| !host.is_error()) && !kotlin_next_token_is_inserted(node, ancestors)
147}
148
149// Whether the first token after `node`, comments aside, is zero-width:
150// one error recovery inserted where the source has none. A comment
151// between the two is a sibling extra, so `vararg /*c*/: Int` must step
152// over it to reach the inserted name, as `vararg: Int` does. A node
153// never opens with an extra, which the parser hangs on the level above,
154// so the descent takes each first child as it is.
155//
156// Every parameter's modifier asks, and the climb reaches
157// `function_value_parameters`, so the sibling is found without a scan
158// from the list's start: that made a long parameter list quadratic.
159fn kotlin_next_token_is_inserted<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
160    let mut current = *node;
161    ancestors
162        .iter(node)
163        .find_map(|(parent, _)| {
164            let next = parent
165                .children_after(&current)
166                .find(|sibling| !sibling.as_tree_sitter().is_extra());
167            current = parent;
168            next
169        })
170        .is_some_and(|mut next| {
171            while let Some(first) = next.child(0) {
172                next = first;
173            }
174            next.start_byte() == next.end_byte()
175        })
176}
177
178// `super<A>` (a `super_expression`) names a supertype rather than
179// listing type arguments, so its brackets stay `<` and `>`.
180const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
181    lists: &[Kotlin::TypeArguments as u16, Kotlin::TypeParameters as u16],
182    openers: &[Kotlin::LT as u16],
183    closers: &[Kotlin::GT as u16],
184    is_misparse: never_misparsed,
185};
186
187impl Getter for KotlinCode {
188    /// Names the space, synthesising one for constructs that carry no
189    /// name token (#1184).
190    ///
191    /// `get_func_space_name` returns `Option<&'a str>` borrowed from
192    /// `code`, so the only name available for a nameless construct is a
193    /// `&'static str` — a per-property spelling like `<get-foo>` would
194    /// need a signature change. Angle brackets follow the existing
195    /// `<anonymous>` convention and cannot collide with a real
196    /// identifier in any of these grammars.
197    ///
198    /// Sibling collisions are accepted, exactly as multiple
199    /// `<anonymous>` siblings already are: two properties each with a
200    /// getter, or two `static { }` blocks in one class, produce two
201    /// spaces with the same name. Nothing enforces name uniqueness
202    /// among siblings, and inventing an index would make the name
203    /// unstable under an unrelated edit.
204    ///
205    /// `<get>` / `<set>` are Kotlin's own spelling of the accessor
206    /// keywords; `<init>` is what the JVM calls the constructor an
207    /// `init` block compiles into.
208    fn get_func_space_name<'a, 'tree>(
209        node: &Node<'tree>,
210        code: &'a [u8],
211        ancestors: Ancestors<'tree, '_>,
212    ) -> Option<&'a str> {
213        match node.kind_id().into() {
214            Kotlin::Getter => Some("<get>"),
215            Kotlin::Setter => Some("<set>"),
216            Kotlin::AnonymousInitializer => Some("<init>"),
217            _ => crate::getter::default_func_space_name(node, code, ancestors),
218        }
219    }
220
221    fn get_space_kind(node: &Node) -> SpaceKind {
222        use Kotlin::*;
223
224        match node.kind_id().into() {
225            // The Kotlin grammar models classes and interfaces under a single
226            // `class_declaration` node with the discriminating keyword
227            // (`class` vs `interface`) appearing as a direct child token.
228            // Distinguishing them at the space-kind level lets the OOP
229            // metrics (`wmc`, `npa`, `npm`) attribute counts to the right
230            // bucket without re-inspecting the AST.
231            ClassDeclaration => {
232                if node.first_child(|id| id == Interface).is_some() {
233                    SpaceKind::Interface
234                } else {
235                    SpaceKind::Class
236                }
237            }
238            // `object MyObject { ... }` is a singleton; treat it as a class
239            // for OOP metric purposes (it has properties, methods, init
240            // blocks, exactly like a class).
241            //
242            // `companion object { ... }` is the anonymous (or named)
243            // singleton nested in a class. Its body is a `class_body`
244            // holding methods and properties, exactly like a named
245            // object, so it opens its own Class space rather than
246            // folding its members into the enclosing class (#431). The
247            // default `get_func_space_name` reads the optional `name`
248            // field, yielding the declared name for `companion object
249            // Named` and `<anonymous>` for the nameless form.
250            //
251            // `object : T { ... }` (`object_literal`) is the anonymous
252            // object expression — Kotlin's analogue of a Java anonymous
253            // class. The grammar models its body as a `class_body` of
254            // methods and properties, identical in shape to a named
255            // object, so it opens its own Class space rather than folding
256            // its members into the enclosing function (#463). It is always
257            // nameless, so the default `get_func_space_name` yields
258            // `<anonymous>`.
259            ObjectDeclaration | CompanionObject | ObjectLiteral => SpaceKind::Class,
260            FunctionDeclaration | SecondaryConstructor | LambdaLiteral | AnonymousFunction => {
261                SpaceKind::Function
262            }
263            // Property accessors and `init { … }` (#1184). Fully
264            // qualified deliberately: the enclosing `use Kotlin::*` would
265            // otherwise put the `Getter` *variant* and the `Getter`
266            // *trait* (in scope from `use super::*`) in the same
267            // namespace. `src/getter/ruby.rs` hit the same collision and
268            // solved it with `use Ruby as R;`.
269            Kotlin::Getter | Kotlin::Setter | Kotlin::AnonymousInitializer => SpaceKind::Function,
270            SourceFile => SpaceKind::Unit,
271            _ => SpaceKind::Unknown,
272        }
273    }
274
275    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
276        use Kotlin::*;
277
278        if GENERIC_ANGLES.is_closer(node, ancestors) {
279            return TokenRole::Unknown;
280        }
281
282        // Modifier keywords, billed as C# bills all of its own (#1558;
283        // Java and Groovy bill only some, #1565). Each is the keyword
284        // leaf; its `*_modifier` / `modifiers` wrappers stay unlisted, so
285        // one modifier bills once (grammar-dispatch section 5). Every
286        // keyword has exactly one kind, so `kind_id` keys it without
287        // splitting it across the two `n1` maps. `Annotation2` is the
288        // `annotation` of `annotation class`; `Annotation` is an `@N` use,
289        // which is no keyword. `in` already bills as a variance modifier
290        // through `In` below, so `out` joins it. `reified` has only the
291        // `ReificationModifier` kind, which `KotlinCode::is_primitive`
292        // keys by its text. An early return rather than an arm, because
293        // the match below is one rustfmt declines to format.
294        //
295        // Each word is a soft keyword that valid Kotlin may use as a name,
296        // and where kotlin-ng fails to parse that name the leaf survives
297        // in its recovery (`open = !open` at statement start,
298        // `val suspend = 1`, a parameter named `vararg`). Such a leaf is
299        // no modifier and bills nothing; see
300        // `kotlin_modifier_was_written_as_one`. `companion` is left out
301        // of that gate: it never parses as a name, and gating it would
302        // only drop a real `companion object` from a class body that
303        // failed to parse.
304        let kind: Kotlin = node.kind_id().into();
305        if matches!(
306            kind,
307            Enum | Sealed
308                | Annotation2
309                | Data
310                | Inner
311                | Value
312                | Public
313                | Private
314                | Protected
315                | Internal
316                | Abstract
317                | Final
318                | Open
319                | Override
320                | Lateinit
321                | Const
322                | Tailrec
323                | Kotlin::Operator
324                | Infix
325                | Inline
326                | External
327                | Suspend
328                | Vararg
329                | Noinline
330                | Crossinline
331                | ReificationModifier
332                | Out
333                | Expect
334                | Actual
335        ) {
336            return if kotlin_modifier_was_written_as_one(node, ancestors) {
337                TokenRole::Operator
338            } else {
339                TokenRole::Unknown
340            };
341        }
342
343        match kind {
344            // Operator: control flow keywords
345            If | Else | When | For | While | Do | Try | Catch | Finally | Throw | Return
346            | ReturnAT
347            // Operator: other keywords. `interface` is the declaration
348            // keyword leaf beside `class` and `object` (#1556); its
349            // `class_declaration` wrapper stays unlisted. `companion` is
350            // the one modifier billed here; see the early return above.
351            | Class | Interface | Fun | Object | Val | Var | In | Is | As | AsQMARK | BANGis
352            | BANGin | Constructor | Companion
353            // Operator: brackets, separators, terminators
354            | SEMI | COMMA | COLONCOLON | DOT | LBRACE | LBRACK | LPAREN
355            // Operator: assignment and arithmetic
356            | EQ | PLUS | DASH | STAR | SLASH | PERCENT
357            | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ
358            | PLUSPLUS | DASHDASH
359            // Operator: comparison and equality
360            | LT | GT | LTEQ | GTEQ | EQEQ | EQEQEQ | BANGEQ | BANGEQEQ
361            // Operator: logical and misc
362            | AMPAMP | PIPEPIPE | BANG | BANGBANG
363            | QMARK | QMARKCOLON | QMARKDOT
364            | DOTDOT | DOTDOTLT | DASHGT | COLON => TokenRole::Operator,
365            // Operands: identifiers and literals, plus the self- and
366            // super-reference leaves (#1380). Four leaf kinds, not two:
367            // the label-qualified spellings `this@Outer` / `super@Inner`
368            // are `this@` / `super@` tokens, distinct kind_ids that
369            // carry no `this` / `super` leaf of their own — the same
370            // shape as `return@`, already listed among the operators
371            // above.
372            //
373            // The leaves are the keepers, not the `this_expression` /
374            // `super_expression` wrappers (grammar-dispatch section 6):
375            // a `constructor_delegation_call` (`constructor() : this(0)`,
376            // `: super(x)`) emits a bare leaf with no wrapper at all, so
377            // billing the wrapper would score constructor delegation
378            // zero. Classifying both would double-count, and the
379            // wrapper's span swallows the label identifier that is
380            // already billed on its own (section 5).
381            Identifier | NumberLiteral | FloatLiteral | CharacterLiteral | Label | This
382            | Super | ThisAT | SuperAT => TokenRole::Operand,
383            // Regression #191: a Kotlin string template wraps an
384            // `Interpolation` child (the long `"${expr}"` form) whose
385            // inner expressions are walked and counted separately, so
386            // the wrapping literal yields Unknown to avoid double-
387            // counting (same pattern as #180 Bash/Elixir, #184 PHP).
388            // The short `"Hi $name"` form has no `Interpolation` node —
389            // it needs the source bytes to distinguish `$name` from
390            // literal `$5`, so it is handled in `get_op_type_with_code`;
391            // this byte-less arm sees only the long form. Both single-
392            // line and multi-line (triple-quoted) literals interpolate.
393            StringLiteral | MultilineStringLiteral => {
394                Self::string_operand_type(node, &[Interpolation as u16])
395            }
396            _ => TokenRole::Unknown,
397        }
398    }
399
400    fn get_op_type_with_code<'a>(
401        node: &Node<'a>,
402        code: &[u8],
403        ancestors: Ancestors<'a, '_>,
404    ) -> TokenRole {
405        use Kotlin::*;
406
407        match node.kind_id().into() {
408            // The kotlin-ng grammar emits no structured node for the
409            // short string template `"Hi $name"` — the `$` sigil and the
410            // variable name arrive as two adjacent `string_content`
411            // tokens (issue #454). When the name token is a clean
412            // identifier, recover it as the operand the long `${name}`
413            // form would have produced, so both template forms count the
414            // inner variable and suppress the wrapping literal (the
415            // wrapper arm below). The grammar does not tokenise at the
416            // identifier boundary for mid-segment forms (`"$x is "`), so
417            // those are left as literal text rather than emitting a
418            // partial-literal operand.
419            StringContent | StringContent2 | StringContent3
420                if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) =>
421            {
422                TokenRole::Operand
423            }
424            // The wrapping literal is Unknown when it interpolates in
425            // either form (long `${expr}` or short `$name`); the inner
426            // expression / recovered variable is the only operand. A
427            // plain literal has no interpolation and stays one operand.
428            StringLiteral | MultilineStringLiteral => {
429                if kotlin_string_has_interp(node, code) {
430                    TokenRole::Unknown
431                } else {
432                    TokenRole::Operand
433                }
434            }
435            _ => Self::get_op_type(node, ancestors),
436        }
437    }
438
439    fn get_operand_id<'a>(
440        node: &Node<'a>,
441        code: &'a [u8],
442        ancestors: Ancestors<'a, '_>,
443    ) -> &'a [u8] {
444        // Narrow a recovered short-interpolation name token to its
445        // leading identifier prefix so `"$a $b"` keys operand `"a"`,
446        // not `"a "`, matching the long `${a}` form (#454).
447        if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) {
448            kotlin_short_interp_operand_bytes(node, code)
449        } else {
450            &code[node.start_byte()..node.end_byte()]
451        }
452    }
453
454    fn get_operator_spelling<'a>(
455        node: &Node<'a>,
456        ancestors: Ancestors<'a, '_>,
457    ) -> Option<&'static str> {
458        GENERIC_ANGLES.opener_spelling(node, ancestors)
459    }
460
461    get_operator!(Kotlin);
462}