big-code-analysis-ast 2.6.0

Parse and classification layer behind big-code-analysis (internal, version-locked)
Documentation
//! Csharp's role rows. The Halstead keyword roles (#1693), the
//! paying-construct roles — `Comparison`, `ShortCircuit`, `EagerLogical`,
//! `Ternary`, `CaseArm`, `Guard`, `NullSafe` (#1694, #1695) — the space
//! tree (#1696) and the control flow — `Branch`, `Switch`, `Loop`,
//! `Catch`, `ElseIf`, `Exit` (#1697) — and
//! the documentation rows (#1699) are declared.

use crate::checker::{csharp_is_aliased_modifier, csharp_member_has_accessors};
use crate::getter::node_text;
use crate::lang_helpers::case_arms::{
    csharp_case_token_is_switch_arm, csharp_switch_expression_arm_is_bare_discard,
};
use crate::lang_helpers::doc_comment::csharp_doc;
use crate::role_table;
use crate::roles::control_flow::else_if_prev_sibling_gate;
use crate::{Ancestors, Csharp, Node};

/// Whether an indexer or property is the accessor-less expression-bodied
/// form (`this[int i] => _d[i];`, `int W => _w;`), which defines one
/// implicit getter and so opens its own `Function` space; the bodied
/// form defers to its `accessor_declaration` children, which open
/// theirs (#464, #472; lesson 65: gate, never delete — the childless
/// form relied on the kind being listed at all).
fn has_no_accessors(node: &Node<'_>) -> bool {
    !csharp_member_has_accessors(node)
}

/// Whether a childless `modifier` node — the grammar's alias for a
/// bare keyword in a parameter (`ref` / `out` / `in` / `scoped` /
/// `readonly`, #1418) or on a lambda (`static` / `async`, #1482) —
/// spells one of those keywords. The aliased `this` of an extension
/// receiver (`M(this Foo f)`) is not one: it is the operand `this` is
/// everywhere, and `CsharpCode::get_op_type_with_code` bills it so
/// *before* reading this row, which is why adding `"this"` to the list
/// below changes no output — measured under #1693; the ordering, not
/// the list, is what keeps it an operand. A `modifier` *with* a child
/// wraps a keyword leaf the row already owns and is nothing itself. A
/// grammar bump that aliases another spelling lands here unclaimed
/// rather than billed as whichever word happened to be last.
fn aliases_a_modifier_keyword(node: &Node<'_>, code: &[u8]) -> bool {
    csharp_is_aliased_modifier(node)
        && matches!(
            node_text(code, node),
            Some("ref" | "out" | "in" | "scoped" | "readonly" | "static" | "async")
        )
}

/// Whether a `switch_expression_arm` is a decision: not the bare
/// discard `_ =>` / `var _ =>`, the expression form's `default:`,
/// unless a `when` guard makes it one (`case_arms` has the shapes).
fn is_decision_arm<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool {
    !csharp_switch_expression_arm_is_bare_discard(node)
}

/// Whether a `case` keyword is a `switch` arm's rather than the one in
/// `goto case 2;`, an unconditional jump that spells the same token
/// (#1450).
fn is_switch_arm_case<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
    csharp_case_token_is_switch_arm(node, ancestors)
}

// `else if` is an `if_statement` whose previous sibling is the bare `else`
// token — no clause wrapper — so a nested `if` under `else { … }` follows
// `{` instead (#1697).
else_if_prev_sibling_gate!(Csharp, Else);

// Whether a comment opens with the XML-doc marker Roslyn reads — `///`
// or `/**`, neither the `////` banner nor the empty `/**/` — from the
// bytes.
crate::roles::byte_gate!(opens_with_xml_doc_marker, csharp_doc);

role_table! {
    lang: Csharp;
    // Invocations only, by the contract on `Checker::is_call`: the
    // grammar emits three aliased `invocation_expression` ids, and
    // matching the unsuffixed one alone silently drops the rest (lesson
    // 2). C#'s three other call-shaped constructs — `new T(…)`, the `:
    // base(x)` / `: this(a)` constructor initializer, and the C# 12
    // primary constructor's `: Base(x)` — are object construction and
    // constructor delegation, which ABC's Fitzpatrick branch rule counts
    // and this row deliberately does not; the matching arm on the other
    // side of that split is `csharp_count_token_branch`, and
    // `csharp_is_call_excludes_constructors` pins the exclusion (#1456).
    Call { owns [InvocationExpression, InvocationExpression2, InvocationExpression3] }
    // The interpolated string `wraps` its `interpolation` children,
    // whose expressions are billed on their own (#183); the other three
    // cannot interpolate. A `character_literal` is not a string, though
    // the dump flattens it beside them.
    StringLit {
        owns [StringLiteral, VerbatimStringLiteral, RawStringLiteral, InterpolatedStringExpression]
        wraps [Interpolation]
    }
    // A `binary_expression` (both aliases: `BinaryExpression2` is the
    // second id carrying the kind string, listed per grammar-dispatch
    // §1 and unreachable at this pin, where `#if A == B` parses as the
    // first) owns a comparison through its `operator` field, and every
    // comparison token is gated to that parent. The type tests
    // `is_expression` (`o is T`) and `is_pattern_expression` (`o is T
    // t`, `o is not null`) are disjoint alternatives that each wrap one
    // `is` keyword, which pays for them, gated to that owner: the
    // grammar spells `is` nowhere else, but a keyword error recovery
    // strands under an `ERROR` pays for no test. `??` is `NullSafe`'s
    // and the `and` / `or` / `not` pattern combinators are no
    // comparison.
    Comparison {
        owns [
            BinaryExpression(holds_payer),
            BinaryExpression2(holds_payer),
            IsExpression, IsPatternExpression,
        ]
        pays [
            EQEQ under [BinaryExpression, BinaryExpression2], BANGEQ under [BinaryExpression, BinaryExpression2],
            LTEQ under [BinaryExpression, BinaryExpression2], GTEQ under [BinaryExpression, BinaryExpression2],
            LT under [BinaryExpression, BinaryExpression2], GT under [BinaryExpression, BinaryExpression2],
            Is under [IsExpression, IsPatternExpression],
        ]
        project "operator"
    }
    ShortCircuit {
        owns [
            BinaryExpression(holds_payer),
            BinaryExpression2(holds_payer),
        ]
        pays [AMPAMP, PIPEPIPE]
        project "operator"
    }
    // `&` / `|` / `^` on boolean operands evaluate both sides, but the
    // grammar emits them as the same `binary_expression` as the integral
    // forms, so the syntax alone cannot tell them apart; no consumer
    // treats them as a decision, and the three tokens bill as the
    // operators they are. A recognition boundary, recorded as the
    // kinds considered rather than as an absence.
    EagerLogical {
        owns []
        excludes [
            AMP "a boolean `&` is the integral `&`'s kind, which the grammar does not tell apart",
            PIPE "a boolean `|` is the integral `|`'s kind, which the grammar does not tell apart",
            CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart",
        ]
    }
    // The `conditional_expression` owns it and its `?` pays, gated to
    // that owner; the same bare token is a conditional access's (the
    // `NullSafe` row's) and type syntax in two productions.
    Ternary {
        owns [ConditionalExpression]
        pays [QMARK under ConditionalExpression]
        project "operator"
    }
    // Two structural forms (#436, #1459): the null coalescing `a ?? b`,
    // a `binary_expression` (either alias) owned through its `operator`
    // field with the `??` token as its payer; and the conditional
    // access `a?.b` / `a?[0]`, a `conditional_access_expression` that
    // pays for itself — its operator is the same bare `?` the ternary
    // and two type productions spell (#1275), and one node is one `?`.
    // The compound `??=` is an `assignment_expression`, not a
    // `binary_expression` (#236). Which consumer reads which token is
    // each consumer's to say (`src/metrics/{abc,cyclomatic}/csharp.rs`).
    NullSafe {
        owns [
            BinaryExpression(holds_payer),
            BinaryExpression2(holds_payer),
            ConditionalAccessExpression(pays_itself),
        ]
        pays [QMARKQMARK]
        project "operator"
        excludes [QMARKQMARKEQ "the compound `??=`, an assignment ABC pays as one and a decision cyclomatic pays as its own (#236)"]
    }
    // Two arm shapes. A statement `switch_section` owns a decision when
    // it holds a `case` label, and each `case` keyword pays — gated to
    // the section, since `goto case 2;` spells the same token (#1450);
    // `default:` is the fallback and pays nothing (lesson 11, #469). A
    // `switch_expression_arm` has no keyword: the node owns and pays,
    // unless it is the bare discard `_ =>` / `var _ =>`, the expression
    // form's `default:` — a guarded discard still counts.
    CaseArm {
        owns [
            SwitchSection(holds_payer),
            SwitchExpressionArm(pays_itself gated_by is_decision_arm),
        ]
        pays [Case gated_by is_switch_arm_case]
        excludes [Default "the fallback label, no decision (lesson 11, #469); `goto default;` spells it too"]
    }
    // A `when` guard on a switch-expression arm or a pattern `case`
    // (`when_clause`) and on a `catch` (`catch_filter_clause`): each
    // node is one decision, paid at the node (#1422). The `when` token
    // is not the payer: it is also a `_reserved_identifier` at this
    // pin, so `int when = 1;` emits it under an `identifier` and a
    // token payer would score a decision per mention of the variable
    // (`bca dump`, not inferred); it bills as the keyword it is through
    // the byte-less arm.
    Guard {
        owns [WhenClause, CatchFilterClause]
        excludes [When "also a reserved identifier at this pin: `int when = 1;` spells it"]
    }
    // C# counts statement nodes, so every row here is plain: the owner is
    // the paying node (#1697).
    Branch { owns [IfStatement] }
    // The statement and the C# 8 expression form.
    Switch { owns [SwitchStatement, SwitchExpression] }
    Loop { owns [ForStatement, ForeachStatement, WhileStatement, DoStatement] }
    Catch { owns [CatchClause] }
    // C# spells `else if` as Java does: an `if_statement` whose previous
    // sibling is the bare `else` token. Recognition only; the `Else`
    // token pays cognitive's +1 and the statement `Branch`'s.
    ElseIf { owns [IfStatement(gated_by follows_else_keyword)] pays [] }
    // `return`, `yield return` / `yield break`, `throw` as a statement
    // and as an expression (`x ?? throw …`).
    Exit { owns [ReturnStatement, YieldStatement, ThrowStatement, ThrowExpression] }
    // Every modifier keyword leaf, plus the childless `modifier` alias
    // the grammar emits for a bare keyword in a parameter or on a
    // lambda, under its text gate. `ref` / `out` / `in` / `scoped` are
    // listed here as the aliased spelling only: as their own kinds they
    // are the expression keywords of `ref x` / `out var y` / `in` / a
    // `scoped` local, and bill with `await` and `is`. `new` is the
    // hiding modifier and the allocation keyword in one kind, billed
    // with the expression keywords for the same reason. The `modifier`
    // rule with a child wraps a leaf this row owns and is nothing
    // itself (grammar-dispatch section 5).
    Modifier {
        owns [
            Public, Private, Protected, Internal, Static, Abstract, Virtual, Override, Sealed,
            Partial, Readonly, Const, Extern, Unsafe, Volatile, Async, Required, File, Fixed,
            Implicit, Explicit, Modifier(text_gated_by aliases_a_modifier_keyword no_chain),
        ]
    }
    // The declaration and namespace keywords, each its leaf under an
    // unclassified `*_declaration` (#1552). `using` bills, and so does
    // the `static` of `using static` through the row above: C# bills
    // its directive keywords where Java and Groovy bill none of theirs
    // (#1600).
    DeclKeyword { owns [Class, Struct, Interface, Enum, Record, Delegate, Namespace, Using] }
    // `predefined_type` is one kind for every spelling (`int`, `string`,
    // `bool`, …), so `Checker::is_primitive` keys it by text (#286).
    // `var` is excluded: it names no type, and the `implicit_type`
    // wrapping it bills nothing.
    Primitive {
        owns [PredefinedType]
        excludes [Var "`var` names no type; its `implicit_type` wrapper bills nothing"]
    }
    // Every callable opens a `Function` space: the method-like
    // declarations, a local function, an accessor (`get` / `set` /
    // `init` — each is a method per C# IL semantics), the operator
    // forms, and an indexer or property only in its accessor-less
    // expression-bodied form (`has_no_accessors`). A lambda and an
    // anonymous method (`delegate { }`) are closures that open a space
    // too, as Rust's and Go's do.
    //
    // A C# 12 primary constructor and a positional record's constructor
    // have no node of their own: the grammar hangs their
    // `parameter_list` directly under the type declaration, the one
    // place a parameter list is not a callable's `parameters` field
    // (`node-types.json`: `class_declaration`, `struct_declaration`
    // and `record_declaration` carry it as a child; an interface and
    // an enum cannot). That list is the constructor (#1828). Its
    // superclass call sits in the sibling `base_list`, outside it.
    FuncOpener {
        owns [
            MethodDeclaration(callable opens Function),
            ConstructorDeclaration(callable opens Function),
            ParameterList(callable opens Function under [ClassDeclaration, StructDeclaration, RecordDeclaration]),
            DestructorDeclaration(callable opens Function),
            LocalFunctionStatement(callable opens Function),
            AccessorDeclaration(callable opens Function),
            OperatorDeclaration(callable opens Function),
            ConversionOperatorDeclaration(callable opens Function),
            IndexerDeclaration(callable opens Function gated_by has_no_accessors no_chain),
            PropertyDeclaration(callable opens Function gated_by has_no_accessors no_chain),
            LambdaExpression(opens Function),
            AnonymousMethodExpression(opens Function),
        ]
    }
    Closure { owns [LambdaExpression, AnonymousMethodExpression] }
    // An enum opens `Class` for parity with Java / PHP / Groovy (#429).
    Container {
        owns [
            CompilationUnit(opens Unit),
            ClassDeclaration(opens Class),
            StructDeclaration(opens Class),
            RecordDeclaration(opens Class),
            EnumDeclaration(opens Class),
            InterfaceDeclaration(opens Interface),
        ]
    }
    // A field declaration (`int a, b;` — one declaration, declarators
    // the consumer counts), in a class-like or an interface body; a
    // positional record's parameters become properties at the IL level
    // and have no declaration node to recognise (`npa/csharp.rs`).
    Member { owns [FieldDeclaration] }
    // The one comment kind, a `DocComment` owner under the marker gate
    // (#1699).
    Comment { owns [Comment] }
    DocComment { owns [Comment(text_gated_by opens_with_xml_doc_marker no_chain)] }
    Docstring { absent "C# documents with `///` comments, not string literals" }
    // The members `DocumentationCommentCompiler` writes: a type, a
    // delegate, a member and an enum member. A namespace (block or
    // file-scoped), a `using`, an assembly attribute, a top-level
    // statement and an accessor take none; checked with `dotnet build`
    // and CS1587. Outside the space-tree rows: the delegate, the event
    // field and event, and the enum member — the parity exceptions
    // `roles/doc_tests/parity.rs` records.
    DocTarget {
        owns [
            ClassDeclaration,
            StructDeclaration,
            RecordDeclaration,
            InterfaceDeclaration,
            EnumDeclaration,
            DelegateDeclaration,
            MethodDeclaration,
            ConstructorDeclaration,
            DestructorDeclaration,
            OperatorDeclaration,
            ConversionOperatorDeclaration,
            FieldDeclaration,
            EventFieldDeclaration,
            EventDeclaration,
            PropertyDeclaration,
            IndexerDeclaration,
            EnumMemberDeclaration,
        ]
    }
    DocRunOpener { absent "Roslyn attaches every doc comment to a member; none documents by its own content" }
    DocRunDirective { absent "Roslyn reads no directive comment" }
    // A property or indexer holds every doc comment in it but those in
    // its accessor list: Roslyn binds one only before the member, so a
    // comment in its header or initializer documents nothing. Both are
    // `FuncOpener` owners in their accessor-less form; this row names
    // them in *every* form, and the Checker reads it before the
    // callable test so the accessor search is never run per comment
    // (#1612). Which child is the accessor list is the Checker's.
    DocBodyResidual { owns [IndexerDeclaration, PropertyDeclaration] }
}