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; the opener row reads the chain for the primary
99 // constructor's `parameter_list` (#1828), so this forwards with a
100 // known-empty chain and labels that list `Unknown`, exactly as the
101 // Checker half (`checker/csharp.rs`) answers `false` — see the
102 // rationale there.
103 fn get_space_kind(node: &Node) -> SpaceKind {
104 const _: () = assert!(
105 !crate::roles::csharp::func_opener::TEXT_GATED
106 && !crate::roles::csharp::container::TEXT_GATED
107 && !crate::roles::csharp::container::CHAIN_GATED,
108 "a space-opening row reads bytes; the byte-less spelling cannot forward with none"
109 );
110 Self::get_space_kind_with_code(node, &[], Ancestors::known(&[]))
111 }
112
113 /// A primary constructor's `parameter_list` carries no name: it
114 /// takes its type's, as a `constructor_declaration`'s `name` field
115 /// already spells the type it constructs (#1828). The default would
116 /// name it `<anonymous>`, which `bca check` reads as a closure.
117 fn get_func_space_name<'a, 'tree>(
118 node: &Node<'tree>,
119 code: &'a [u8],
120 ancestors: Ancestors<'tree, '_>,
121 ) -> Option<&'a str> {
122 // role-bypass: allow(FuncOpener) — a naming rule, not whether the
123 // node opens a space
124 // The `Container` row carries no gate, so its kind table is the
125 // whole answer.
126 crate::getter::func_space_name_from_owner(node, code, ancestors, |list, owner| {
127 list.kind_id() == Csharp::ParameterList as u16
128 && crate::roles::csharp::container::lists_kind(owner.kind_id())
129 })
130 }
131
132 fn get_space_kind_with_code<'a>(
133 node: &Node<'a>,
134 code: &[u8],
135 ancestors: Ancestors<'a, '_>,
136 ) -> SpaceKind {
137 crate::roles::csharp::opens_space(node, code, ancestors)
138 }
139
140 keyword_roles!(csharp);
141
142 paying_roles!(csharp);
143
144 fn get_op_type<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> TokenRole {
145 use Csharp::*;
146
147 if GENERIC_ANGLES.is_closer(node, ancestors)
148 || is_interpolation_clause_delimiter(node, ancestors)
149 {
150 return TokenRole::Unknown;
151 }
152
153 match node.kind_id().into() {
154 // Control-flow keywords
155 // `case` stays for the spelling the `CaseArm` row's gate
156 // leaves out — `goto case 2;` (#1450) — which billed before
157 // the row existed; a switch arm's is the row's. `default` is
158 // the fallback label's and stays; `when`, the `Guard` row's
159 // owners' keyword, is excluded there and bills here. `is`,
160 // `<` … and `?` likewise stay for the spellings the
161 // `Comparison` and `Ternary` rows' gates leave out — for `?`,
162 // a nullable type, a constraint's `class?`, and a conditional
163 // access's: the `NullSafe` row pays that access at the node
164 // (it is no `PAYERS` entry, so `get_paying_role` bills
165 // nothing for it) and its `?` bills here. `??` is that row's
166 // payer and `get_paying_role` bills it; `??=` is excluded
167 // there and bills here as the assignment it is.
168 // role-bypass: allow(Comparison, Ternary, CaseArm, NullSafe) — the operator
169 // classification of the spellings the rows' `under IsExpression` /
170 // `under BinaryExpression` / `under ConditionalExpression` / `is_switch_arm_case`
171 // gates leave out, and of the conditional access's `?`, which its self-paying owner
172 // does not bill
173 If | Else | Switch | Case | Default | Try | Catch | Finally | Throw
174 | Return | Yield | Break | Continue | Goto | For | Foreach | While | Do
175 // Expression-keyword operators. `new` is the allocation
176 // keyword and the hiding modifier in one kind. The
177 // modifiers, the declaration keywords and `predefined_type`
178 // are not here: `roles/csharp.rs` declares them and
179 // `get_keyword_role` bills them (#1693).
180 // `is` for the spelling the `Comparison` row's `under IsExpression`
181 // gate leaves out — a keyword error recovery strands — which
182 // billed before the row existed.
183 | Is
184 | New | Await | As | Typeof | Sizeof | Checked | Unchecked | Ref | Out | In
185 | Params | Lock | Stackalloc | Where | With | When | Operator
186 | Scoped | Not | And | Or
187 // Property/event accessor keywords
188 | Get | Set | Init | Add | Remove
189 // Structural punctuation. `?` stays for the spellings the
190 // `Ternary` and `NullSafe` rows' gates leave out — a nullable
191 // type, a constraint's `class?` — which billed before the rows
192 // existed.
193 | LBRACE | LBRACK | LPAREN | COMMA | SEMI | COLON | COLONCOLON | DOT
194 | DOTDOT | EQGT | DASHGT | QMARK
195 // Arithmetic / logical / bitwise / assignment operators. The
196 // comparison tokens, `is`, `&&` and `||` are the `Comparison`
197 // and `ShortCircuit` rows' and `get_paying_role` bills them
198 // (#1695); the six comparison tokens stay for the spellings
199 // the row's `under BinaryExpression` gate leaves out — a
200 // generic bracket (the `<>` pair; its closer returned
201 // `Unknown` above), an operator declaration's name, a
202 // relational pattern, a recovered token — which billed
203 // before the row existed.
204 | EQ | EQEQ | BANGEQ | LT | GT | LTEQ | GTEQ
205 | PLUS | DASH | STAR | SLASH | PERCENT
206 | AMP | PIPE | CARET | TILDE | BANG
207 | LTLT | GTGT | GTGTGT
208 | PLUSPLUS | DASHDASH
209 | PLUSEQ | DASHEQ | STAREQ | SLASHEQ | PERCENTEQ
210 | AMPEQ | PIPEEQ | CARETEQ | LTLTEQ | GTGTEQ | GTGTGTEQ | QMARKQMARKEQ
211 => TokenRole::Operator,
212 // `boolean_literal: choice('true', 'false')` wraps the
213 // keyword leaf, so a literal reaches the walker twice;
214 // listing both kinds inflated `N2` by one per literal while
215 // the text-keyed `n2` hid it (#1253). The leaf cannot simply
216 // be dropped: the overloadable-operator list emits a bare
217 // `true` / `false` under `operator_declaration` — the
218 // grammar's only unwrapped position. There the keyword
219 // *names* an operator, exactly as the `+` of `operator +`
220 // does, so it is billed as one (#1296); C# merely spells two
221 // of its overloadable operators with keywords instead of
222 // punctuation. The fallback keeps any other unwrapped
223 // position an operand, the role the keyword has as a value.
224 // role-bypass: allow(FuncOpener) — the keyword's position under
225 // an overload declaration, not whether the declaration opens
226 // a space
227 True | False => match ancestors.parent(node).map(|p| p.kind_id().into()) {
228 Some(BooleanLiteral) => TokenRole::Unknown,
229 Some(OperatorDeclaration) => TokenRole::Operator,
230 _ => TokenRole::Operand,
231 },
232 // `this` is a self-reference everywhere (`this.x`,
233 // `this[i]`, `: this(1)`, `f(this)`) except directly under
234 // an `indexer_declaration`, where the keyword *names* the
235 // member being declared rather than denoting a value —
236 // `public int this[int i] { … }`. That position keeps its
237 // operator classification alongside the `operator` keyword
238 // of an overload declaration, which this match already
239 // bills as an operator (#1380). The extension-method
240 // receiver (`static void M(this Foo f)`) is a childless
241 // `modifier` node, kind 249, not this kind at all; it is
242 // classified — as an operand, so the two positions agree —
243 // by `get_op_type_with_code` below (#1418).
244 //
245 // Java's receiver parameter (`void m(J J.this)`) is the
246 // other declarator use of the keyword in this workspace and
247 // `java.rs` calls it an operand — a parameter *name* is an
248 // operand in every language here, where a member named by a
249 // keyword belongs with `operator +`.
250 // role-bypass: allow(FuncOpener) — the keyword's position under
251 // an indexer declaration, not whether it opens a space
252 This => match ancestors.parent(node).map(|p| p.kind_id().into()) {
253 Some(IndexerDeclaration) => TokenRole::Operator,
254 _ => TokenRole::Operand,
255 },
256 // Operands: identifiers and literals. `NullLiteral` is a
257 // childless leaf, so it needs no such guard.
258 //
259 // `QualifiedName` (`System.Text`), `GenericName`
260 // (`List<int>`) and `AliasQualifiedName` (`global::Foo`)
261 // were listed here until #1263. Each is a container whose
262 // every part the walker already reaches and classifies —
263 // the identifier leaves as operands, `.` / `::` / `<` / `>`
264 // and any `predefined_type` argument as operators — so
265 // listing the container too billed one occurrence twice
266 // (grammar-dispatch section 5). Probed with `bca ops`:
267 // dropping them leaves `System`+`Text`+`.`,
268 // `List`+`<`+`int`+`>`, and `global`+`::`+`Foo` intact.
269 //
270 // `Base` joined this list in #1380 for the same structural
271 // reason `This` did: it is the receiver of `base.M()` /
272 // `base[i]` / `: base(x)`. The `base_list` container that
273 // spells inheritance (`class D : B`) holds the base type's
274 // identifier and no `base` keyword, so nothing bills this
275 // text twice.
276 //
277 // `ImplicitParameter` is the parameter of `x => x`: a
278 // childless leaf where `(x) => x` puts an `identifier` inside
279 // a `parameter_list`, so the bare spelling dropped its name
280 // from both Halstead halves (#1544). Nothing containing it
281 // is classified.
282 // role-bypass: allow(StringLit) — the operand classification of the literals,
283 // a projection the `StringLit` row does not answer
284 Identifier | Base | ImplicitParameter
285 | IntegerLiteral | RealLiteral | BooleanLiteral | NullLiteral
286 | CharacterLiteral | StringLiteral | VerbatimStringLiteral | RawStringLiteral
287 => TokenRole::Operand,
288 // `$"..."` counts as one operand when inert. When it carries
289 // any `Interpolation` child the inner expressions are
290 // already walked and classified as operands; counting the
291 // wrapping literal too would double-count the inner
292 // identifiers' contribution to `N2` (issue #183, same
293 // pattern as #180 for Elixir/Bash).
294 // role-bypass: allow(StringLit) — the operand classification of the literals
295 // under the row's `wraps` list, a projection the row does not answer
296 InterpolatedStringExpression => {
297 Self::string_operand_type(node, crate::roles::csharp::string_lit::WRAPS)
298 }
299 _ => TokenRole::Unknown,
300 }
301 }
302
303 // The parameter-position spelling of six keywords (#1418). The
304 // grammar's `_parameter_type_with_modifiers` rule aliases the bare
305 // tokens `this scoped ref out in readonly` to `$.modifier`, so in
306 // that one position each is a **childless** `modifier` node rather
307 // than the kind its own arm above lists; `_lambda_expression_init`
308 // and `anonymous_method_expression` alias a bare `static` / `async`
309 // the same way (#1482). Nothing billed them, so an extension
310 // receiver, a `ref` parameter and an `out` parameter each
311 // contributed to neither Halstead half.
312 //
313 // The role follows the text, never the position: each keyword keeps
314 // the role its own kind carries elsewhere, so `M(ref Foo f)` and
315 // `f(ref x)` agree, and `this` stays the operand #1380 made it. The
316 // keyword spellings are the `Modifier` row's text-gated entry in
317 // `roles/csharp.rs` (#1693), which carries the child-presence
318 // argument; this override keeps only the operand half, which no
319 // row expresses. That decision's `IndexerDeclaration` carve-out
320 // cannot arise here — an indexer declarator is not a parameter.
321 //
322 // Reading the bytes needs this spelling, which is the one the walk
323 // calls (`compute_halstead` -> `get_op_type_with_code`), so the
324 // classification reaches every count (grammar-dispatch section 7).
325 //
326 // `CsharpCode::is_primitive` routes the operator half through the
327 // lexeme-keyed map, because these seven keywords have two kind
328 // spellings for one operator; its comment carries that argument.
329 fn get_op_type_with_code<'a>(
330 node: &Node<'a>,
331 code: &[u8],
332 ancestors: Ancestors<'a, '_>,
333 ) -> TokenRole {
334 // The aliased `this` is the operand `this` is everywhere; the
335 // keyword spellings are the `Modifier` row's text-gated
336 // `Modifier` entry, which `get_keyword_role` bills first, so a
337 // spelling the row does not name falls through here to
338 // `Unknown` — `get_op_type` lists no `Modifier` arm.
339 if csharp_is_aliased_modifier(node) && node_text(code, node) == Some("this") {
340 return TokenRole::Operand;
341 }
342 keyword_or_op_type::<Self>(node, code, ancestors)
343 }
344
345 fn get_operator_spelling<'a>(
346 node: &Node<'a>,
347 ancestors: Ancestors<'a, '_>,
348 ) -> Option<&'static str> {
349 GENERIC_ANGLES.opener_spelling(node, ancestors)
350 }
351
352 get_operator!(Csharp);
353}