big-code-analysis-ast 2.5.1

Parse and classification layer behind big-code-analysis (internal, version-locked)
Documentation
//! `Getter` implementation for Groovy.
#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]

use super::*;

// `method_type_parameters` is the method-level spelling of
// `type_parameters` (`<T> T id(T x)`). `LT2` is the `token.immediate`
// `<` that `type_parameters` and `type_arguments` open with; the parser
// reports it as `LT`, so it is listed defensively, here and in the
// operator arm, and its absence is pinned by
// `groovy_generic_opener_alias_never_reaches_kind_id`.
const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
    lists: &[
        Groovy::TypeArguments as u16,
        Groovy::TypeParameters as u16,
        Groovy::MethodTypeParameters as u16,
    ],
    openers: &[Groovy::LT as u16, Groovy::LT2 as u16],
    closers: &[Groovy::GT as u16],
    is_misparse: never_misparsed,
};

impl Getter for GroovyCode {
    /// 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.
    ///
    /// `<static-init>` rather than the JVM's `<clinit>`: the same
    /// construct exists in JavaScript, where `<clinit>` would mean
    /// nothing, and one spelling across languages is worth more here
    /// than JVM precision.
    fn get_func_space_name<'a, 'tree>(
        node: &Node<'tree>,
        code: &'a [u8],
        ancestors: Ancestors<'tree, '_>,
    ) -> Option<&'a str> {
        // role-bypass: allow(FuncOpener) — a naming rule, not whether the
        // block opens a space
        if node.kind_id() == Groovy::StaticInitializer as u16 {
            return Some("<static-init>");
        }
        crate::getter::default_func_space_name(node, code, ancestors)
    }

    // The mapping is the `opens` annotations of `roles/groovy.rs`
    // (#1696); the byte-less spelling forwards with no bytes and no
    // chain, as the old one read neither.
    impl_byte_less_space_kind!(groovy);

    fn get_space_kind_with_code<'a>(
        node: &Node<'a>,
        code: &[u8],
        ancestors: Ancestors<'a, '_>,
    ) -> SpaceKind {
        crate::roles::groovy::opens_space(node, code, ancestors)
    }

    keyword_roles!(groovy);

    paying_roles!(groovy, control_flow);

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

        if GENERIC_ANGLES.is_closer(node, ancestors) {
            return TokenRole::Unknown;
        }
        // Mirrors `JavaCode`'s classification: module keywords
        // (`Package`, `Import`, …) are excluded. The dekobon Groovy
        // grammar (#246, #247)
        // emits a distinct named node for every Groovy-specific
        // operator (Elvis `?:`, safe-nav `?.`, identity `===`/`!==`,
        // regex `=~`/`==~`, spaceship `<=>`, exclusive ranges
        // `..<` / `<..` / `<..<`, `as` coercion, etc.); their leaf
        // tokens are listed here as operators so Halstead counts the
        // tokens directly rather than the wrapping expression node.
        // `NumberLiteral` is the new grammar's consolidated numeric
        // literal — the prior grammar split numbers by radix
        // (Hex/Octal/Binary/Decimal Integer/Float).
        match node.kind_id().into() {
            // Slashy-string delimiter punctuation. A slashy string
            // (`/xyz/`) is a `StringLiteral` whose closing delimiter is
            // a `SLASH` — the kind id real division uses — so
            // `def b = /xyz/` reported a `/` operator with no division
            // in the source (#1314, the Groovy sibling of Elixir #1256
            // and Ruby/Perl #1312). Only the *closer* is a child: the
            // grammar folds the opening `/` into the literal's own
            // span, so this fabricated one `/` per literal rather than
            // Ruby's two. The `StringLiteral` is already the operand
            // (below), so the delimiter is suppressed exactly when its
            // parent is that node — the compound-leaf guard of
            // grammar-dispatch section 5.
            //
            // Parent, not ancestor, and here that distinction is
            // *observable*: a GString interpolation inside a slashy
            // string (`/x${a / b}y/`) puts a real division under a
            // `StringLiteral` ancestor, and an ancestor-scanning guard
            // would swallow it. Pinned by
            // `groovy_slashy_guard_is_parent_scoped_not_ancestor_scoped`.
            //
            // The other string forms need no arm: `'plain'` is a
            // childless leaf, `"dq"` closes with `"` (134), and
            // dollar-slashy `$/…/$` closes with `/$` (144) — none of
            // which this match classifies. `~/ab.c/` is a
            // `UnaryExpression` wrapping the same `StringLiteral`, so
            // its `~` still counts.
            SLASH
                if ancestors.parent_has_kind(node, StringLiteral as u16) =>
            {
                TokenRole::Unknown
            }
            // `super` is an operator only as the bound of a `wildcard`
            // (`List<? super T>`), where it denotes no value and mirrors
            // `? extends T`'s `extends` — which the arm below bills as an
            // operator. Everywhere else it names a receiver a `.`, `?.`
            // or `::` acts on, so it is an operand. The parent alone
            // separates the two, as #1380 settled for Java's
            // identically-shaped arm.
            //
            // Forward compatibility, not a live fix: the pinned dekobon
            // grammar spells `'super'` in the `wildcard` production and
            // nowhere else, so every reference (`super(1)`, `super.h()`,
            // `A.super.h()`, `super::h`, `super?.h()`) is already a plain
            // `identifier` and an operand. Before the gate that agreement
            // was a grammar accident — an ungated `Super` would bill a
            // reference as an operator the moment a bump routed one here.
            //
            // The operand branch is consequently unreachable under the
            // pin and deliberately untested: only error recovery on
            // invalid Groovy (`List<? super>`) reaches it, and pinning
            // that shape would make the grammar's present
            // over-permissiveness the contract (grammar-dispatch section
            // 6). `groovy_wildcard_super_bound_stays_an_operator` carries
            // the node census that fails by name if a bump makes it
            // reachable (#1419).
            Super if ancestors.parent_has_kind(node, Wildcard as u16) => TokenRole::Operator,
            Super => TokenRole::Operand,

            // Control-flow + keyword operators (mirrors Java's set,
            // minus tokens that no longer exist in the dekobon grammar
            // — `This`, `VoidType`, `Throws2`). The modifiers, the
            // declaration keywords and the primitive types are not
            // here: `roles/groovy.rs` declares them, gates included, and
            // `get_keyword_role` bills them (#1693).
            // The comparison and short-circuit tokens — including the
            // identity, regex and spaceship ones — are not here: the
            // `Comparison` and `ShortCircuit` rows of `roles/groovy.rs`
            // pay them and `get_paying_role` bills them (#1695). `<` /
            // `>`, `in` and `instanceof` stay for the spellings the rows'
            // gates leave out — a generic bracket (`LT2` is the opener's
            // alias), a recovered token (`o instanceof` at end of input
            // strands the keyword under `ERROR`), the `in` of a `for (x
            // in xs)` header — which billed before the rows existed.
            // role-bypass: allow(Comparison, Ternary) — the operator classification of the
            // spellings the rows' `under BinaryExpression` / `under MembershipExpression` /
            // `under InstanceofExpression` / `under TernaryExpression` gates leave out
            LT | LT2 | GT | In | Instanceof
            // `case` is the `CaseArm` row's, and `if` / `switch` / `for` /
            // `while` / `catch` the `Branch` / `Switch` / `Loop` / `Catch`
            // rows' payers, all billed by `get_paying_role` (#1695,
            // #1697); `default` is the fallback label's and stays.
            | Else | Try | Throw | Throws | Continue
            | Break | Do | Finally | New | Return | Default | Assert
            | Extends | Implements | As
            // Separators / brackets.
            | SEMI | COMMA | COLONCOLON | DOT | DASHGT | LBRACE | LBRACK | LPAREN
            // Java-compatible operators (arithmetic, bitwise, assignment).
            // `?` stays for the spelling the `Ternary` row's `under TernaryExpression`
            // gate leaves out — a wildcard bound — which billed before the
            // row existed.
            | EQ | BANG | TILDE | QMARK | COLON
            | PLUSPLUS | DASHDASH | PLUS | DASH | STAR | SLASH | AMP
            | PIPE | CARET | PERCENT | LTLT | GTGT | GTGTGT | PLUSEQ | DASHEQ | STAREQ
            | SLASHEQ | AMPEQ | PIPEEQ | CARETEQ | PERCENTEQ | LTLTEQ | GTGTEQ | GTGTGTEQ
            | STARSTAR | STARSTAREQ
            // Groovy-specific operator tokens added by the dekobon
            // grammar (closes #247): ranges `..` / `..<` / `<..` /
            // `<..<`, Elvis-assign `?=`, spread-dot `*.`, method-pointer
            // `.&`, direct-field `.@`, logical implication `==>`, and
            // spread-map `*:` (the identity, spaceship and regex tokens
            // are the `Comparison` row's; the elvis `?:`, safe-nav `?.`,
            // safe-chain `??.` and safe-index `?[` the `NullSafe` row's).
            | DOTDOT | DOTDOTLT | LTDOTDOT | LTDOTDOTLT | QMARKEQ
            | STARDOT | DOTAMP | DOTAT
            | EQEQGT | STARCOLON => TokenRole::Operator,

            // `QualifiedName` (a `package` / `import` path) and
            // `QualifiedType` (`java.util.Map` in type position) were
            // listed here until #1263, and `QualifiedName` really did
            // double-count: `package com.example` billed `com`,
            // `example` AND `com.example`. `QualifiedType` never fired,
            // because the runtime emits the *alias* `QualifiedType2`
            // (kind_id 228) that this arm did not name — a latent
            // lesson-2 miss whose only effect was to make the wrong
            // classification unobservable for that half. Both are gone
            // rather than completed: a qualified path is its identifier
            // leaves plus the `.` operator, as in every other language
            // here, and as PHP settled the same call in #1293.
            //
            // Completing the alias list instead is the double count,
            // not the fix. Both halves are pinned against that by
            // `groovy_qualified_name_counts_leaves_not_the_composite_1263`
            // and `groovy_qualified_type_counts_leaves_not_the_composite_1352`.
            // Neither wrapper is ever a name's sole carrier
            // (grammar-dispatch section 6): `import java` still nests an
            // `identifier`, and a single-segment type is a bare
            // `type_identifier` the grammar does not wrap at all.
            // role-bypass: allow(Primitive, DeclKeyword) — the operand classification of a
            // name neither row's text gate claimed, as a primitive or as `var`
            Identifier | TypeIdentifier | NullLiteral | True | False | NumberLiteral => {
                TokenRole::Operand
            }

            // A Groovy GString interpolates inner expressions whose
            // operands are walked and counted separately, so the
            // wrapping literal must yield Unknown to avoid double-
            // counting (issue #454, same mechanism as Kotlin #191 /
            // PHP #184 / Elixir #180, generalized in #420). The dekobon
            // grammar emits two interpolation child kinds: the braced
            // long form `${expr}` (`gstring_brace_interpolation`) and
            // the short `$name` / `$obj.field` form
            // (`gstring_dollar_interpolation`). A plain non-interpolated
            // literal has neither child and stays a single operand.
            // role-bypass: allow(StringLit) — the operand classification of the literals
            // under the row's `wraps` list, a projection the row does not answer
            StringLiteral => {
                Self::string_operand_type(node, crate::roles::groovy::string_lit::WRAPS)
            }

            _ => TokenRole::Unknown,
        }
    }

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

    fn get_operator_id_as_str(id: u16) -> &'static str {
        let typ = id.into();
        match typ {
            Groovy::LPAREN => "()",
            Groovy::LBRACK => "[]",
            Groovy::LBRACE => "{}",
            _ => typ.into(),
        }
    }
}