Skip to main content

big_code_analysis_ast/getter/
csharp.rs

1//! `Getter` implementation for C#.
2#![allow(clippy::wildcard_imports, clippy::enum_glob_use)]
3
4use super::*;
5
6// A function pointer type's `<>` (`delegate*<int, void>`) encloses
7// its parameter and return types (#1567).
8const GENERIC_ANGLES: GenericAngleKinds = GenericAngleKinds {
9    lists: &[
10        Csharp::TypeArgumentList as u16,
11        Csharp::TypeParameterList as u16,
12        Csharp::FunctionPointerType as u16,
13    ],
14    openers: &[Csharp::LT as u16],
15    closers: &[Csharp::GT as u16],
16    is_misparse: csharp_comparison_misparse,
17};
18
19// Whether `list` holds the two comparisons of a call argument
20// (`F(a < b, c > d)`) that tree-sitter-c-sharp reads as a declaration
21// typed `a<b, c>` and named `d`. The C# specification keeps the type
22// arguments only where the token after `>` allows it (§6.2.5), and an
23// identifier allows it only after `is`, `case`, `out` or in a tuple —
24// so a declaration typed by a generic name is two comparisons when it is
25// a call or indexer argument without `out`. `F(out List<int> x)`,
26// `(List<int> p, int q) = …` and `o is List<int> x` keep their pair. A
27// member access before the `<` (`F(x.a < b, c > d)`) wraps the generic
28// name in a `qualified_name`, whose final name alone can be the misparse.
29// Generic qualifiers keep their type brackets. The `>=` spelling
30// (`F(a < b, c >= d)`) parses as an assignment instead and is not undone.
31fn csharp_comparison_misparse<'a>(list: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
32    let mut up = ancestors.iter(list).map(|(node, _)| node);
33    let Some(name) = up
34        .next()
35        .filter(|name| name.kind_id() == Csharp::GenericName as u16)
36    else {
37        return false;
38    };
39    let declaration = match up.next() {
40        Some(qualified) if qualified.kind_id() == Csharp::QualifiedName as u16 => {
41            if qualified
42                .child_by_field_name("name")
43                .is_none_or(|last| last.id() != name.id())
44            {
45                return false;
46            }
47            up.next()
48        }
49        parent => parent,
50    };
51    let (Some(declaration), Some(argument), Some(arguments)) = (declaration, up.next(), up.next())
52    else {
53        return false;
54    };
55    declaration.kind_id() == Csharp::DeclarationExpression as u16
56        && argument.kind_id() == Csharp::Argument as u16
57        && !argument.is_child(Csharp::Out as u16)
58        && matches!(
59            arguments.kind_id().into(),
60            Csharp::ArgumentList | Csharp::BracketedArgumentList
61        )
62}
63
64// Whether `node` is the `,` opening an interpolation's alignment
65// (`$"{x,8}"`) or the `:` opening its format string (`$"{x:F2}"`).
66// Both delimit the field, as the `{` / `}` braces do, which #1314 left
67// unbilled in every interpolating language; Python's format-spec `:`
68// went the same way in #1486 (#1573). The guard reads the parent, so a
69// ternary `:`, a named-argument `:` or an argument-list `,` written
70// inside the hole (`$"{f(a, b)}"`) keeps billing.
71//
72// The alignment *value* is a `constant_expression` and walks as one:
73// `{x,8}` bills `8` and `{x,-W}` bills `-` and `W`. That is where C#
74// and Python differ: a Python literal width (`f"{x:>10}"`) is
75// format-spec text and bills nothing, while C#'s `8` is an
76// `integer_literal` token. An expression width bills in both
77// (`f"{x:>{w}}"` bills `w`). The format string after `:` (`F2`) is
78// string content and has no node to bill.
79//
80// On invalid input with no expression before the delimiter
81// (`$"{x,}"`, `$"{:F2}"`) error recovery leaves the `,` / `:` outside
82// any clause node, so it bills. Valid C# always has both, so this is
83// documented rather than tested (grammar-dispatch §6).
84fn is_interpolation_clause_delimiter<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
85    let clause = match node.kind_id().into() {
86        Csharp::COLON => Csharp::InterpolationFormatClause,
87        Csharp::COMMA => Csharp::InterpolationAlignmentClause,
88        _ => return false,
89    };
90    ancestors.parent_has_kind(node, clause as u16)
91}
92
93impl Getter for CsharpCode {
94    // The mapping is the `opens` annotations of `roles/csharp.rs`
95    // (#1696): an enum opens `Class` for cross-language parity (#429);
96    // a bodied indexer or property defers to its accessors and the
97    // accessor-less form opens `Function` (#464, #472). The rows read no
98    // bytes and no chain, so the byte-less spelling forwards with none.
99    impl_byte_less_space_kind!(csharp);
100
101    fn get_space_kind_with_code<'a>(
102        node: &Node<'a>,
103        code: &[u8],
104        ancestors: Ancestors<'a, '_>,
105    ) -> SpaceKind {
106        crate::roles::csharp::opens_space(node, code, ancestors)
107    }
108
109    keyword_roles!(csharp);
110
111    paying_roles!(csharp);
112
113    fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
114        use Csharp::*;
115
116        if GENERIC_ANGLES.is_closer(node, ancestors)
117            || is_interpolation_clause_delimiter(node, ancestors)
118        {
119            return TokenRole::Unknown;
120        }
121
122        match node.kind_id().into() {
123            // Control-flow keywords
124            // `case` stays for the spelling the `CaseArm` row's gate
125            // leaves out — `goto case 2;` (#1450) — which billed before
126            // the row existed; a switch arm's is the row's. `default` is
127            // the fallback label's and stays; `when`, the `Guard` row's
128            // owners' keyword, is excluded there and bills here. `is`,
129            // `<` … and `?` likewise stay for the spellings the
130            // `Comparison` and `Ternary` rows' gates leave out — for `?`,
131            // a nullable type, a constraint's `class?`, and a conditional
132            // access's: the `NullSafe` row pays that access at the node
133            // (it is no `PAYERS` entry, so `get_paying_role` bills
134            // nothing for it) and its `?` bills here. `??` is that row's
135            // payer and `get_paying_role` bills it; `??=` is excluded
136            // there and bills here as the assignment it is.
137            // role-bypass: allow(Comparison, Ternary, CaseArm, NullSafe) — the operator
138            // classification of the spellings the rows' `under IsExpression` /
139            // `under BinaryExpression` / `under ConditionalExpression` / `is_switch_arm_case`
140            // gates leave out, and of the conditional access's `?`, which its self-paying owner
141            // does not bill
142            If | Else | Switch | Case | Default | Try | Catch | Finally | Throw
143            | Return | Yield | Break | Continue | Goto | For | Foreach | While | Do
144            // Expression-keyword operators. `new` is the allocation
145            // keyword and the hiding modifier in one kind. The
146            // modifiers, the declaration keywords and `predefined_type`
147            // are not here: `roles/csharp.rs` declares them and
148            // `get_keyword_role` bills them (#1693).
149            // `is` for the spelling the `Comparison` row's `under IsExpression`
150            // gate leaves out — a keyword error recovery strands — which
151            // billed before the row existed.
152            | Is
153            | New | Await | As | Typeof | Sizeof | Checked | Unchecked | Ref | Out | In
154            | Params | Lock | Stackalloc | Where | With | When | Operator
155            | Scoped | Not | And | Or
156            // Property/event accessor keywords
157            | Get | Set | Init | Add | Remove
158            // Structural punctuation. `?` stays for the spellings the
159            // `Ternary` and `NullSafe` rows' gates leave out — a nullable
160            // type, a constraint's `class?` — which billed before the rows
161            // existed.
162            | LBRACE | LBRACK | LPAREN | COMMA | SEMI | COLON | COLONCOLON | DOT
163            | DOTDOT | EQGT | DASHGT | QMARK
164            // Arithmetic / logical / bitwise / assignment operators. The
165            // comparison tokens, `is`, `&&` and `||` are the `Comparison`
166            // and `ShortCircuit` rows' and `get_paying_role` bills them
167            // (#1695); the six comparison tokens stay for the spellings
168            // the row's `under BinaryExpression` gate leaves out — a
169            // generic bracket (the `<>` pair; its closer returned
170            // `Unknown` above), an operator declaration's name, a
171            // relational pattern, a recovered token — which billed
172            // before the row existed.
173            | EQ | EQEQ | BANGEQ | LT | GT | LTEQ | GTEQ
174            | PLUS | DASH | STAR | SLASH | PERCENT
175            | AMP | PIPE | CARET | TILDE | BANG
176            | LTLT | GTGT | GTGTGT
177            | PLUSPLUS | DASHDASH
178            | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ
179            | AMPEQ | PIPEEQ | CARETEQ | LTLTEQ | GTGTEQ | GTGTGTEQ | QMARKQMARKEQ
180                => TokenRole::Operator,
181            // `boolean_literal: choice('true', 'false')` wraps the
182            // keyword leaf, so a literal reaches the walker twice;
183            // listing both kinds inflated `N2` by one per literal while
184            // the text-keyed `n2` hid it (#1253). The leaf cannot simply
185            // be dropped: the overloadable-operator list emits a bare
186            // `true` / `false` under `operator_declaration` — the
187            // grammar's only unwrapped position. There the keyword
188            // *names* an operator, exactly as the `+` of `operator +`
189            // does, so it is billed as one (#1296); C# merely spells two
190            // of its overloadable operators with keywords instead of
191            // punctuation. The fallback keeps any other unwrapped
192            // position an operand, the role the keyword has as a value.
193            // role-bypass: allow(FuncOpener) — the keyword's position under
194            // an overload declaration, not whether the declaration opens
195            // a space
196            True | False => match ancestors.parent(node).map(|p| p.kind_id().into()) {
197                Some(BooleanLiteral) => TokenRole::Unknown,
198                Some(OperatorDeclaration) => TokenRole::Operator,
199                _ => TokenRole::Operand,
200            },
201            // `this` is a self-reference everywhere (`this.x`,
202            // `this[i]`, `: this(1)`, `f(this)`) except directly under
203            // an `indexer_declaration`, where the keyword *names* the
204            // member being declared rather than denoting a value —
205            // `public int this[int i] { … }`. That position keeps its
206            // operator classification alongside the `operator` keyword
207            // of an overload declaration, which this match already
208            // bills as an operator (#1380). The extension-method
209            // receiver (`static void M(this Foo f)`) is a childless
210            // `modifier` node, kind 249, not this kind at all; it is
211            // classified — as an operand, so the two positions agree —
212            // by `get_op_type_with_code` below (#1418).
213            //
214            // Java's receiver parameter (`void m(J J.this)`) is the
215            // other declarator use of the keyword in this workspace and
216            // `java.rs` calls it an operand — a parameter *name* is an
217            // operand in every language here, where a member named by a
218            // keyword belongs with `operator +`.
219            // role-bypass: allow(FuncOpener) — the keyword's position under
220            // an indexer declaration, not whether it opens a space
221            This => match ancestors.parent(node).map(|p| p.kind_id().into()) {
222                Some(IndexerDeclaration) => TokenRole::Operator,
223                _ => TokenRole::Operand,
224            },
225            // Operands: identifiers and literals. `NullLiteral` is a
226            // childless leaf, so it needs no such guard.
227            //
228            // `QualifiedName` (`System.Text`), `GenericName`
229            // (`List<int>`) and `AliasQualifiedName` (`global::Foo`)
230            // were listed here until #1263. Each is a container whose
231            // every part the walker already reaches and classifies —
232            // the identifier leaves as operands, `.` / `::` / `<` / `>`
233            // and any `predefined_type` argument as operators — so
234            // listing the container too billed one occurrence twice
235            // (grammar-dispatch section 5). Probed with `bca ops`:
236            // dropping them leaves `System`+`Text`+`.`,
237            // `List`+`<`+`int`+`>`, and `global`+`::`+`Foo` intact.
238            //
239            // `Base` joined this list in #1380 for the same structural
240            // reason `This` did: it is the receiver of `base.M()` /
241            // `base[i]` / `: base(x)`. The `base_list` container that
242            // spells inheritance (`class D : B`) holds the base type's
243            // identifier and no `base` keyword, so nothing bills this
244            // text twice.
245            //
246            // `ImplicitParameter` is the parameter of `x => x`: a
247            // childless leaf where `(x) => x` puts an `identifier` inside
248            // a `parameter_list`, so the bare spelling dropped its name
249            // from both Halstead halves (#1544). Nothing containing it
250            // is classified.
251            // role-bypass: allow(StringLit) — the operand classification of the literals,
252            // a projection the `StringLit` row does not answer
253            Identifier | Base | ImplicitParameter
254            | IntegerLiteral | RealLiteral | BooleanLiteral | NullLiteral
255            | CharacterLiteral | StringLiteral | VerbatimStringLiteral | RawStringLiteral
256                => TokenRole::Operand,
257            // `$"..."` counts as one operand when inert. When it carries
258            // any `Interpolation` child the inner expressions are
259            // already walked and classified as operands; counting the
260            // wrapping literal too would double-count the inner
261            // identifiers' contribution to `N2` (issue #183, same
262            // pattern as #180 for Elixir/Bash).
263            // role-bypass: allow(StringLit) — the operand classification of the literals
264            // under the row's `wraps` list, a projection the row does not answer
265            InterpolatedStringExpression => {
266                Self::string_operand_type(node, crate::roles::csharp::string_lit::WRAPS)
267            }
268            _ => TokenRole::Unknown,
269        }
270    }
271
272    // The parameter-position spelling of six keywords (#1418). The
273    // grammar's `_parameter_type_with_modifiers` rule aliases the bare
274    // tokens `this scoped ref out in readonly` to `$.modifier`, so in
275    // that one position each is a **childless** `modifier` node rather
276    // than the kind its own arm above lists; `_lambda_expression_init`
277    // and `anonymous_method_expression` alias a bare `static` / `async`
278    // the same way (#1482). Nothing billed them, so an extension
279    // receiver, a `ref` parameter and an `out` parameter each
280    // contributed to neither Halstead half.
281    //
282    // The role follows the text, never the position: each keyword keeps
283    // the role its own kind carries elsewhere, so `M(ref Foo f)` and
284    // `f(ref x)` agree, and `this` stays the operand #1380 made it. The
285    // keyword spellings are the `Modifier` row's text-gated entry in
286    // `roles/csharp.rs` (#1693), which carries the child-presence
287    // argument; this override keeps only the operand half, which no
288    // row expresses. That decision's `IndexerDeclaration` carve-out
289    // cannot arise here — an indexer declarator is not a parameter.
290    //
291    // Reading the bytes needs this spelling, which is the one the walk
292    // calls (`compute_halstead` -> `get_op_type_with_code`), so the
293    // classification reaches every count (grammar-dispatch section 7).
294    //
295    // `CsharpCode::is_primitive` routes the operator half through the
296    // lexeme-keyed map, because these seven keywords have two kind
297    // spellings for one operator; its comment carries that argument.
298    fn get_op_type_with_code<'a>(
299        node: &Node<'a>,
300        code: &[u8],
301        ancestors: Ancestors<'a, '_>,
302    ) -> TokenRole {
303        // The aliased `this` is the operand `this` is everywhere; the
304        // keyword spellings are the `Modifier` row's text-gated
305        // `Modifier` entry, which `get_keyword_role` bills first, so a
306        // spelling the row does not name falls through here to
307        // `Unknown` — `get_op_type` lists no `Modifier` arm.
308        if csharp_is_aliased_modifier(node) && node_text(code, node) == Some("this") {
309            return TokenRole::Operand;
310        }
311        keyword_or_op_type::<Self>(node, code, ancestors)
312    }
313
314    fn get_operator_spelling<'a>(
315        node: &Node<'a>,
316        ancestors: Ancestors<'a, '_>,
317    ) -> Option<&'static str> {
318        GENERIC_ANGLES.opener_spelling(node, ancestors)
319    }
320
321    get_operator!(Csharp);
322}