big-code-analysis-ast 2.4.0

Parse and classification layer behind big-code-analysis (internal, version-locked)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! `Getter` implementation for Kotlin.
#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]

use super::*;

/// Returns the byte length of the leading Kotlin identifier in `text`
/// — a Unicode letter or `_` start followed by letters / digits / `_`
/// — or `0` if `text` does not start with an identifier.
///
/// The short string template `$name` interpolates a *simple
/// identifier*, but the kotlin-ng grammar does not tokenise at the
/// identifier boundary: it splits the literal only at each `$`, so the
/// token after `$` absorbs any trailing inter-segment text into its own
/// byte range. For `"$a $b"` the token after the first `$` is `"a "`
/// (with the trailing space), and for `"$x is "` it is `"x is "`. Taking
/// the maximal leading-identifier prefix recovers the interpolated
/// variable (`a`, `x`) and treats the remainder as literal text, so the
/// short form matches the long `${a}` / `${x}` form (#454). A token with
/// no identifier prefix (`"price: $5"` → `"5"`, digit start) yields `0`
/// and stays literal.
fn kotlin_leading_identifier_len(text: &str) -> usize {
    let mut chars = text.char_indices();
    let Some((_, first)) = chars.next() else {
        return 0;
    };
    if first != '_' && !first.is_alphabetic() {
        return 0;
    }
    // The leading identifier ends at the first byte that is neither `_`
    // nor alphanumeric; everything from there on is inter-segment
    // literal text the grammar glued onto this `$name` token.
    let mut end = first.len_utf8();
    for (idx, c) in chars {
        if c == '_' || c.is_alphanumeric() {
            end = idx + c.len_utf8();
        } else {
            break;
        }
    }
    end
}

/// Returns whether the `string_content` token `node` is (or begins
/// with) the variable-name part of a Kotlin short string template
/// (`$name`). The kotlin-ng grammar emits no structured node for this
/// form — the `$` sigil and the variable name arrive as two adjacent
/// `string_content` tokens (verified by AST dump, #454). The name token
/// is recognised by a preceding `string_content` sibling spelled
/// exactly `$` plus its own text starting with an identifier. Because
/// the grammar glues trailing inter-segment text onto the name token
/// (`"$a $b"` → `"a "`, `"$x is "` → `"x is "`), a non-empty leading
/// identifier prefix is sufficient; the prefix is the recovered operand
/// and the remainder is literal text. Only a token with no identifier
/// prefix (`"price: $5"` → `"5"`) stays literal.
fn kotlin_is_short_interp_name(node: &Node, previous: Option<Node<'_>>, code: &[u8]) -> bool {
    use Kotlin::{StringContent, StringContent2, StringContent3};

    // The grammar emits three aliased `string_content` kind ids
    // (single-line uses `StringContent3`, others `StringContent` /
    // `StringContent2`); all render as the text `"string_content"`.
    const STRING_CONTENT_KINDS: [u16; 3] = [
        StringContent as u16,
        StringContent2 as u16,
        StringContent3 as u16,
    ];

    if !STRING_CONTENT_KINDS.contains(&node.kind_id()) {
        return false;
    }
    let Some(prev) = previous else {
        return false;
    };
    if !STRING_CONTENT_KINDS.contains(&prev.kind_id()) || prev.utf8_text(code) != Some("$") {
        return false;
    }
    node.utf8_text(code)
        .is_some_and(|text| kotlin_leading_identifier_len(text) > 0)
}

/// Returns the byte slice keying the Halstead operand for a Kotlin
/// short-interpolation name token (`$name`). The grammar glues trailing
/// inter-segment text onto the name token, so the raw node bytes for
/// `"$a $b"` are `"a "` — keying that would record a distinct `"a "`
/// operand and break parity with the long `${a}` form. Narrow the slice
/// to the leading identifier prefix so the operand is keyed as the bare
/// identifier (`"a"`), matching the long form (#454).
fn kotlin_short_interp_operand_bytes<'a>(node: &Node, code: &'a [u8]) -> &'a [u8] {
    let start = node.start_byte();
    let end = node.end_byte();
    let full = &code[start..end];
    match std::str::from_utf8(full) {
        Ok(text) => {
            let prefix_len = kotlin_leading_identifier_len(text);
            if prefix_len > 0 {
                &full[..prefix_len]
            } else {
                full
            }
        }
        Err(_) => full,
    }
}

/// Returns whether a Kotlin string literal `node` carries any
/// interpolation: the long `${expr}` form (a structured `Interpolation`
/// child) or the short `$name` form (adjacent `$` + identifier
/// `string_content` tokens). The wrapping literal yields Unknown in
/// either case so the inner expression is the only counted operand
/// (#454).
fn kotlin_string_has_interp(node: &Node, code: &[u8]) -> bool {
    use Kotlin::Interpolation;

    // The scan already holds each child's predecessor, so the short-form
    // test gets it for free rather than through the `O(depth)`
    // `Node::previous_sibling` (#1096).
    let mut previous = None;
    node.children().any(|child| {
        let found = child.kind_id() == Interpolation as u16
            || kotlin_is_short_interp_name(&child, previous, code);
        previous = Some(child);
        found
    })
}

// Whether `node`, a modifier keyword leaf, sits in a modifier list the
// grammar built (#1558), rather than in the recovery of a soft-keyword
// *name* it failed to parse. Two recoveries strand the leaf:
//
// - an `ERROR` holds it, usually still wrapped in its `*_modifier`
//   node (`open = !open` at statement start, `val suspend = 1`), so the
//   first ancestor above the wrappers is the `ERROR`;
// - a modifier list is followed by an inserted, zero-width name
//   (`fun f(vararg: Int)`, `class C(open: Int)`).
//
// Kinds are compared by name: `*_modifier` covers every wrapper, and
// `user_type` is where recovery can hang `type_modifiers`. The inserted
// name is found by width, not `is_missing()` (grammar-dispatch).
fn kotlin_modifier_was_written_as_one<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
    let host = ancestors
        .iter(node)
        .map(|(ancestor, _)| ancestor)
        .find(|ancestor| {
            let kind = ancestor.kind();
            !(kind.ends_with("_modifier") || kind == "type_modifiers" || kind == "user_type")
        });
    host.is_some_and(|host| !host.is_error()) && !kotlin_next_token_is_inserted(node, ancestors)
}

// Whether the first token after `node`, comments aside, is zero-width:
// one error recovery inserted where the source has none. A comment
// between the two is a sibling extra, so `vararg /*c*/: Int` must step
// over it to reach the inserted name, as `vararg: Int` does. A node
// never opens with an extra, which the parser hangs on the level above,
// so the descent takes each first child as it is.
//
// Every parameter's modifier asks, and the climb reaches
// `function_value_parameters`, so the sibling is found without a scan
// from the list's start: that made a long parameter list quadratic.
fn kotlin_next_token_is_inserted<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
    std::iter::once((*node, ancestors))
        .chain(ancestors.iter(node))
        .find_map(|(level, level_ancestors)| {
            level_ancestors
                .siblings_after(&level)
                .find(|sibling| !sibling.as_tree_sitter().is_extra())
        })
        .is_some_and(|mut next| {
            while let Some(first) = next.child(0) {
                next = first;
            }
            next.start_byte() == next.end_byte()
        })
}

// A qualified `super<A>` (a `super_expression`) encloses the supertype
// it names (#1567).
const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
    lists: &[
        Kotlin::TypeArguments as u16,
        Kotlin::TypeParameters as u16,
        Kotlin::SuperExpression as u16,
    ],
    openers: &[Kotlin::LT as u16],
    closers: &[Kotlin::GT as u16],
    is_misparse: never_misparsed,
};

impl Getter for KotlinCode {
    /// Names the space, synthesising one for constructs that carry no
    /// name token (#1184).
    ///
    /// `get_func_space_name` returns `Option<&'a str>` borrowed from
    /// `code`, so the only name available for a nameless construct is a
    /// `&'static str` — a per-property spelling like `<get-foo>` would
    /// need a signature change. Angle brackets follow the existing
    /// `<anonymous>` convention and cannot collide with a real
    /// identifier in any of these grammars.
    ///
    /// Sibling collisions are accepted, exactly as multiple
    /// `<anonymous>` siblings already are: two properties each with a
    /// getter, or two `static { }` blocks in one class, produce two
    /// spaces with the same name. Nothing enforces name uniqueness
    /// among siblings, and inventing an index would make the name
    /// unstable under an unrelated edit.
    ///
    /// `<get>` / `<set>` are Kotlin's own spelling of the accessor
    /// keywords; `<init>` is what the JVM calls the constructor an
    /// `init` block compiles into.
    fn get_func_space_name<'a, 'tree>(
        node: &Node<'tree>,
        code: &'a [u8],
        ancestors: Ancestors<'tree, '_>,
    ) -> Option<&'a str> {
        match node.kind_id().into() {
            Kotlin::Getter => Some("<get>"),
            Kotlin::Setter => Some("<set>"),
            Kotlin::AnonymousInitializer => Some("<init>"),
            _ => crate::getter::default_func_space_name(node, code, ancestors),
        }
    }

    fn get_space_kind(node: &Node) -> SpaceKind {
        use Kotlin::*;

        match node.kind_id().into() {
            // The Kotlin grammar models classes and interfaces under a single
            // `class_declaration` node with the discriminating keyword
            // (`class` vs `interface`) appearing as a direct child token.
            // Distinguishing them at the space-kind level lets the OOP
            // metrics (`wmc`, `npa`, `npm`) attribute counts to the right
            // bucket without re-inspecting the AST.
            ClassDeclaration => {
                if node.first_child(|id| id == Interface).is_some() {
                    SpaceKind::Interface
                } else {
                    SpaceKind::Class
                }
            }
            // `object MyObject { ... }` is a singleton; treat it as a class
            // for OOP metric purposes (it has properties, methods, init
            // blocks, exactly like a class).
            //
            // `companion object { ... }` is the anonymous (or named)
            // singleton nested in a class. Its body is a `class_body`
            // holding methods and properties, exactly like a named
            // object, so it opens its own Class space rather than
            // folding its members into the enclosing class (#431). The
            // default `get_func_space_name` reads the optional `name`
            // field, yielding the declared name for `companion object
            // Named` and `<anonymous>` for the nameless form.
            //
            // `object : T { ... }` (`object_literal`) is the anonymous
            // object expression — Kotlin's analogue of a Java anonymous
            // class. The grammar models its body as a `class_body` of
            // methods and properties, identical in shape to a named
            // object, so it opens its own Class space rather than folding
            // its members into the enclosing function (#463). It is always
            // nameless, so the default `get_func_space_name` yields
            // `<anonymous>`.
            ObjectDeclaration | CompanionObject | ObjectLiteral => SpaceKind::Class,
            FunctionDeclaration | SecondaryConstructor | LambdaLiteral | AnonymousFunction => {
                SpaceKind::Function
            }
            // Property accessors and `init { … }` (#1184). Fully
            // qualified deliberately: the enclosing `use Kotlin::*` would
            // otherwise put the `Getter` *variant* and the `Getter`
            // *trait* (in scope from `use super::*`) in the same
            // namespace. `src/getter/ruby.rs` hit the same collision and
            // solved it with `use Ruby as R;`.
            Kotlin::Getter | Kotlin::Setter | Kotlin::AnonymousInitializer => SpaceKind::Function,
            SourceFile => SpaceKind::Unit,
            _ => SpaceKind::Unknown,
        }
    }

    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
        use Kotlin::*;

        if GENERIC_ANGLES.is_closer(node, ancestors) {
            return TokenRole::Unknown;
        }

        // Modifier keywords, billed as C# bills all of its own (#1558;
        // Java and Groovy bill only some, #1565). Each is the keyword
        // leaf; its `*_modifier` / `modifiers` wrappers stay unlisted, so
        // one modifier bills once (grammar-dispatch section 5). Every
        // keyword has exactly one kind, so `kind_id` keys it without
        // splitting it across the two `n1` maps. `Annotation2` is the
        // `annotation` of `annotation class`; `Annotation` is an `@N` use,
        // which is no keyword. `in` already bills as a variance modifier
        // through `In` below, so `out` joins it. `reified` has only the
        // `ReificationModifier` kind, which `KotlinCode::is_primitive`
        // keys by its text. An early return rather than an arm, because
        // the match below is one rustfmt declines to format.
        //
        // Each word is a soft keyword that valid Kotlin may use as a name,
        // and where kotlin-ng fails to parse that name the leaf survives
        // in its recovery (`open = !open` at statement start,
        // `val suspend = 1`, a parameter named `vararg`). Such a leaf is
        // no modifier and bills nothing; see
        // `kotlin_modifier_was_written_as_one`. `companion` is left out
        // of that gate: it never parses as a name, and gating it would
        // only drop a real `companion object` from a class body that
        // failed to parse.
        let kind: Kotlin = node.kind_id().into();
        if matches!(
            kind,
            Enum | Sealed
                | Annotation2
                | Data
                | Inner
                | Value
                | Public
                | Private
                | Protected
                | Internal
                | Abstract
                | Final
                | Open
                | Override
                | Lateinit
                | Const
                | Tailrec
                | Kotlin::Operator
                | Infix
                | Inline
                | External
                | Suspend
                | Vararg
                | Noinline
                | Crossinline
                | ReificationModifier
                | Out
                | Expect
                | Actual
        ) {
            return if kotlin_modifier_was_written_as_one(node, ancestors) {
                TokenRole::Operator
            } else {
                TokenRole::Unknown
            };
        }

        // The accessor keywords, billed as C# bills its `get` / `set`
        // (#1564), but only directly under their `getter` / `setter`,
        // which stay unlisted. The same leaves are the `@get:` / `@set:`
        // use-site targets, which bill nothing, like `@field:` and
        // `@property:`; and where kotlin-ng misreads a call `get(1)` after
        // a local `val f = 6`, an `ERROR` holds the leaf. Used as a name
        // otherwise (`val get = 1`, `x.set(v)`, `fun get()`) the word
        // parses as an identifier. The grammar also reads a local
        // `val f = 6` followed by `set = 2` as a setter, which bills
        // `set`. `field` in an accessor body is an identifier, so it is an
        // operand like any other variable. An early return for the same
        // reason as the modifiers'.
        let accessor = match kind {
            Get => Some(Kotlin::Getter),
            Set => Some(Setter),
            _ => None,
        };
        if let Some(accessor) = accessor {
            return if ancestors.parent_has_kind(node, accessor as u16) {
                TokenRole::Operator
            } else {
                TokenRole::Unknown
            };
        }

        match kind {
            // Operator: control flow keywords
            If | Else | When | For | While | Do | Try | Catch | Finally | Throw | Return
            | ReturnAT
            // Operator: other keywords. `interface` is the declaration
            // keyword leaf beside `class` and `object` (#1556); its
            // `class_declaration` wrapper stays unlisted. `companion` is
            // the one modifier billed here; see the early return above.
            // `typealias`, `init`, `where` and `by` bill as C# bills
            // `where` and TypeScript `type` (#1564), each the leaf of its
            // `type_alias` / `anonymous_initializer` / `type_constraints`
            // / `property_delegate` or `explicit_delegation` wrapper.
            // `typealias` is a hard keyword; the other three, used as
            // names (`val by = 1`, `where(x)`, `init.f()`), parse as
            // identifiers, so the leaf exists only in its construct.
            | Class | Interface | Fun | Object | Val | Var | In | Is | As | AsQMARK | BANGis
            | BANGin | Constructor | Companion | Typealias | Init | Where | By
            // Operator: brackets, separators, terminators
            | SEMI | COMMA | COLONCOLON | DOT | LBRACE | LBRACK | LPAREN
            // Operator: assignment and arithmetic
            | EQ | PLUS | DASH | STAR | SLASH | PERCENT
            | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ
            | PLUSPLUS | DASHDASH
            // Operator: comparison and equality
            | LT | GT | LTEQ | GTEQ | EQEQ | EQEQEQ | BANGEQ | BANGEQEQ
            // Operator: logical and misc
            | AMPAMP | PIPEPIPE | BANG | BANGBANG
            | QMARK | QMARKCOLON | QMARKDOT
            | DOTDOT | DOTDOTLT | DASHGT | COLON => TokenRole::Operator,
            // Operands: identifiers and literals, plus the self- and
            // super-reference leaves (#1380). Four leaf kinds, not two:
            // the label-qualified spellings `this@Outer` / `super@Inner`
            // are `this@` / `super@` tokens, distinct kind_ids that
            // carry no `this` / `super` leaf of their own — the same
            // shape as `return@`, already listed among the operators
            // above.
            //
            // The leaves are the keepers, not the `this_expression` /
            // `super_expression` wrappers (grammar-dispatch section 6):
            // a `constructor_delegation_call` (`constructor() : this(0)`,
            // `: super(x)`) emits a bare leaf with no wrapper at all, so
            // billing the wrapper would score constructor delegation
            // zero. Classifying both would double-count, and the
            // wrapper's span swallows the label identifier that is
            // already billed on its own (section 5).
            Identifier | NumberLiteral | FloatLiteral | CharacterLiteral | Label | This
            | Super | ThisAT | SuperAT => TokenRole::Operand,
            // Regression #191: a Kotlin string template wraps an
            // `Interpolation` child (the long `"${expr}"` form) whose
            // inner expressions are walked and counted separately, so
            // the wrapping literal yields Unknown to avoid double-
            // counting (same pattern as #180 Bash/Elixir, #184 PHP).
            // The short `"Hi $name"` form has no `Interpolation` node —
            // it needs the source bytes to distinguish `$name` from
            // literal `$5`, so it is handled in `get_op_type_with_code`;
            // this byte-less arm sees only the long form. Both single-
            // line and multi-line (triple-quoted) literals interpolate.
            StringLiteral | MultilineStringLiteral => {
                Self::string_operand_type(node, &[Interpolation as u16])
            }
            _ => TokenRole::Unknown,
        }
    }

    fn get_op_type_with_code<'a>(
        node: &Node<'a>,
        code: &[u8],
        ancestors: Ancestors<'a, '_>,
    ) -> TokenRole {
        use Kotlin::*;

        match node.kind_id().into() {
            // The kotlin-ng grammar emits no structured node for the
            // short string template `"Hi $name"` — the `$` sigil and the
            // variable name arrive as two adjacent `string_content`
            // tokens (issue #454). When the name token is a clean
            // identifier, recover it as the operand the long `${name}`
            // form would have produced, so both template forms count the
            // inner variable and suppress the wrapping literal (the
            // wrapper arm below). The grammar does not tokenise at the
            // identifier boundary for mid-segment forms (`"$x is "`), so
            // those are left as literal text rather than emitting a
            // partial-literal operand.
            StringContent | StringContent2 | StringContent3
                if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) =>
            {
                TokenRole::Operand
            }
            // The wrapping literal is Unknown when it interpolates in
            // either form (long `${expr}` or short `$name`); the inner
            // expression / recovered variable is the only operand. A
            // plain literal has no interpolation and stays one operand.
            StringLiteral | MultilineStringLiteral => {
                if kotlin_string_has_interp(node, code) {
                    TokenRole::Unknown
                } else {
                    TokenRole::Operand
                }
            }
            _ => Self::get_op_type(node, ancestors),
        }
    }

    fn get_operand_id<'a>(
        node: &Node<'a>,
        code: &'a [u8],
        ancestors: Ancestors<'a, '_>,
    ) -> &'a [u8] {
        // Narrow a recovered short-interpolation name token to its
        // leading identifier prefix so `"$a $b"` keys operand `"a"`,
        // not `"a "`, matching the long `${a}` form (#454).
        if kotlin_is_short_interp_name(node, ancestors.previous_sibling(node), code) {
            kotlin_short_interp_operand_bytes(node, code)
        } else {
            &code[node.start_byte()..node.end_byte()]
        }
    }

    fn get_operator_spelling<'a>(
        node: &Node<'a>,
        ancestors: Ancestors<'a, '_>,
    ) -> Option<&'static str> {
        GENERIC_ANGLES.opener_spelling(node, ancestors)
    }

    get_operator!(Kotlin);
}