big_code_analysis_ast/roles/csharp.rs
1//! Csharp's role rows. The Halstead keyword roles (#1693), the
2//! paying-construct roles — `Comparison`, `ShortCircuit`, `EagerLogical`,
3//! `Ternary`, `CaseArm`, `Guard`, `NullSafe` (#1694, #1695) — the space
4//! tree (#1696) and the control flow — `Branch`, `Switch`, `Loop`,
5//! `Catch`, `ElseIf`, `Exit` (#1697) — and
6//! the documentation rows (#1699) are declared.
7
8use crate::checker::{csharp_is_aliased_modifier, csharp_member_has_accessors};
9use crate::getter::node_text;
10use crate::lang_helpers::case_arms::{
11 csharp_case_token_is_switch_arm, csharp_switch_expression_arm_is_bare_discard,
12};
13use crate::lang_helpers::doc_comment::csharp_doc;
14use crate::role_table;
15use crate::roles::control_flow::else_if_prev_sibling_gate;
16use crate::{Ancestors, Csharp, Node};
17
18/// Whether an indexer or property is the accessor-less expression-bodied
19/// form (`this[int i] => _d[i];`, `int W => _w;`), which defines one
20/// implicit getter and so opens its own `Function` space; the bodied
21/// form defers to its `accessor_declaration` children, which open
22/// theirs (#464, #472; lesson 65: gate, never delete — the childless
23/// form relied on the kind being listed at all).
24fn has_no_accessors(node: &Node<'_>) -> bool {
25 !csharp_member_has_accessors(node)
26}
27
28/// Whether a childless `modifier` node — the grammar's alias for a
29/// bare keyword in a parameter (`ref` / `out` / `in` / `scoped` /
30/// `readonly`, #1418) or on a lambda (`static` / `async`, #1482) —
31/// spells one of those keywords. The aliased `this` of an extension
32/// receiver (`M(this Foo f)`) is not one: it is the operand `this` is
33/// everywhere, and `CsharpCode::get_op_type_with_code` bills it so
34/// *before* reading this row, which is why adding `"this"` to the list
35/// below changes no output — measured under #1693; the ordering, not
36/// the list, is what keeps it an operand. A `modifier` *with* a child
37/// wraps a keyword leaf the row already owns and is nothing itself. A
38/// grammar bump that aliases another spelling lands here unclaimed
39/// rather than billed as whichever word happened to be last.
40fn aliases_a_modifier_keyword(node: &Node<'_>, code: &[u8]) -> bool {
41 csharp_is_aliased_modifier(node)
42 && matches!(
43 node_text(code, node),
44 Some("ref" | "out" | "in" | "scoped" | "readonly" | "static" | "async")
45 )
46}
47
48/// Whether a `switch_expression_arm` is a decision: not the bare
49/// discard `_ =>` / `var _ =>`, the expression form's `default:`,
50/// unless a `when` guard makes it one (`case_arms` has the shapes).
51fn is_decision_arm<'a>(node: &Node<'a>, _ancestors: Ancestors<'a, '_>) -> bool {
52 !csharp_switch_expression_arm_is_bare_discard(node)
53}
54
55/// Whether a `case` keyword is a `switch` arm's rather than the one in
56/// `goto case 2;`, an unconditional jump that spells the same token
57/// (#1450).
58fn is_switch_arm_case<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool {
59 csharp_case_token_is_switch_arm(node, ancestors)
60}
61
62// `else if` is an `if_statement` whose previous sibling is the bare `else`
63// token — no clause wrapper — so a nested `if` under `else { … }` follows
64// `{` instead (#1697).
65else_if_prev_sibling_gate!(Csharp, Else);
66
67// Whether a comment opens with the XML-doc marker Roslyn reads — `///`
68// or `/**`, neither the `////` banner nor the empty `/**/` — from the
69// bytes.
70crate::roles::byte_gate!(opens_with_xml_doc_marker, csharp_doc);
71
72role_table! {
73 lang: Csharp;
74 // Invocations only, by the contract on `Checker::is_call`: the
75 // grammar emits three aliased `invocation_expression` ids, and
76 // matching the unsuffixed one alone silently drops the rest (lesson
77 // 2). C#'s three other call-shaped constructs — `new T(…)`, the `:
78 // base(x)` / `: this(a)` constructor initializer, and the C# 12
79 // primary constructor's `: Base(x)` — are object construction and
80 // constructor delegation, which ABC's Fitzpatrick branch rule counts
81 // and this row deliberately does not; the matching arm on the other
82 // side of that split is `csharp_count_token_branch`, and
83 // `csharp_is_call_excludes_constructors` pins the exclusion (#1456).
84 Call { owns [InvocationExpression, InvocationExpression2, InvocationExpression3] }
85 // The interpolated string `wraps` its `interpolation` children,
86 // whose expressions are billed on their own (#183); the other three
87 // cannot interpolate. A `character_literal` is not a string, though
88 // the dump flattens it beside them.
89 StringLit {
90 owns [StringLiteral, VerbatimStringLiteral, RawStringLiteral, InterpolatedStringExpression]
91 wraps [Interpolation]
92 }
93 // A `binary_expression` (both aliases: `BinaryExpression2` is the
94 // second id carrying the kind string, listed per grammar-dispatch
95 // §1 and unreachable at this pin, where `#if A == B` parses as the
96 // first) owns a comparison through its `operator` field, and every
97 // comparison token is gated to that parent. The type tests
98 // `is_expression` (`o is T`) and `is_pattern_expression` (`o is T
99 // t`, `o is not null`) are disjoint alternatives that each wrap one
100 // `is` keyword, which pays for them, gated to that owner: the
101 // grammar spells `is` nowhere else, but a keyword error recovery
102 // strands under an `ERROR` pays for no test. `??` is `NullSafe`'s
103 // and the `and` / `or` / `not` pattern combinators are no
104 // comparison.
105 Comparison {
106 owns [
107 BinaryExpression(holds_payer),
108 BinaryExpression2(holds_payer),
109 IsExpression, IsPatternExpression,
110 ]
111 pays [
112 EQEQ under [BinaryExpression, BinaryExpression2], BANGEQ under [BinaryExpression, BinaryExpression2],
113 LTEQ under [BinaryExpression, BinaryExpression2], GTEQ under [BinaryExpression, BinaryExpression2],
114 LT under [BinaryExpression, BinaryExpression2], GT under [BinaryExpression, BinaryExpression2],
115 Is under [IsExpression, IsPatternExpression],
116 ]
117 project "operator"
118 }
119 ShortCircuit {
120 owns [
121 BinaryExpression(holds_payer),
122 BinaryExpression2(holds_payer),
123 ]
124 pays [AMPAMP, PIPEPIPE]
125 project "operator"
126 }
127 // `&` / `|` / `^` on boolean operands evaluate both sides, but the
128 // grammar emits them as the same `binary_expression` as the integral
129 // forms, so the syntax alone cannot tell them apart; no consumer
130 // treats them as a decision, and the three tokens bill as the
131 // operators they are. A recognition boundary, recorded as the
132 // kinds considered rather than as an absence.
133 EagerLogical {
134 owns []
135 excludes [
136 AMP "a boolean `&` is the integral `&`'s kind, which the grammar does not tell apart",
137 PIPE "a boolean `|` is the integral `|`'s kind, which the grammar does not tell apart",
138 CARET "a boolean `^` is the integral `^`'s kind, which the grammar does not tell apart",
139 ]
140 }
141 // The `conditional_expression` owns it and its `?` pays, gated to
142 // that owner; the same bare token is a conditional access's (the
143 // `NullSafe` row's) and type syntax in two productions.
144 Ternary {
145 owns [ConditionalExpression]
146 pays [QMARK under ConditionalExpression]
147 project "operator"
148 }
149 // Two structural forms (#436, #1459): the null coalescing `a ?? b`,
150 // a `binary_expression` (either alias) owned through its `operator`
151 // field with the `??` token as its payer; and the conditional
152 // access `a?.b` / `a?[0]`, a `conditional_access_expression` that
153 // pays for itself — its operator is the same bare `?` the ternary
154 // and two type productions spell (#1275), and one node is one `?`.
155 // The compound `??=` is an `assignment_expression`, not a
156 // `binary_expression` (#236). Which consumer reads which token is
157 // each consumer's to say (`src/metrics/{abc,cyclomatic}/csharp.rs`).
158 NullSafe {
159 owns [
160 BinaryExpression(holds_payer),
161 BinaryExpression2(holds_payer),
162 ConditionalAccessExpression(pays_itself),
163 ]
164 pays [QMARKQMARK]
165 project "operator"
166 excludes [QMARKQMARKEQ "the compound `??=`, an assignment ABC pays as one and a decision cyclomatic pays as its own (#236)"]
167 }
168 // Two arm shapes. A statement `switch_section` owns a decision when
169 // it holds a `case` label, and each `case` keyword pays — gated to
170 // the section, since `goto case 2;` spells the same token (#1450);
171 // `default:` is the fallback and pays nothing (lesson 11, #469). A
172 // `switch_expression_arm` has no keyword: the node owns and pays,
173 // unless it is the bare discard `_ =>` / `var _ =>`, the expression
174 // form's `default:` — a guarded discard still counts.
175 CaseArm {
176 owns [
177 SwitchSection(holds_payer),
178 SwitchExpressionArm(pays_itself gated_by is_decision_arm),
179 ]
180 pays [Case gated_by is_switch_arm_case]
181 excludes [Default "the fallback label, no decision (lesson 11, #469); `goto default;` spells it too"]
182 }
183 // A `when` guard on a switch-expression arm or a pattern `case`
184 // (`when_clause`) and on a `catch` (`catch_filter_clause`): each
185 // node is one decision, paid at the node (#1422). The `when` token
186 // is not the payer: it is also a `_reserved_identifier` at this
187 // pin, so `int when = 1;` emits it under an `identifier` and a
188 // token payer would score a decision per mention of the variable
189 // (`bca dump`, not inferred); it bills as the keyword it is through
190 // the byte-less arm.
191 Guard {
192 owns [WhenClause, CatchFilterClause]
193 excludes [When "also a reserved identifier at this pin: `int when = 1;` spells it"]
194 }
195 // C# counts statement nodes, so every row here is plain: the owner is
196 // the paying node (#1697).
197 Branch { owns [IfStatement] }
198 // The statement and the C# 8 expression form.
199 Switch { owns [SwitchStatement, SwitchExpression] }
200 Loop { owns [ForStatement, ForeachStatement, WhileStatement, DoStatement] }
201 Catch { owns [CatchClause] }
202 // C# spells `else if` as Java does: an `if_statement` whose previous
203 // sibling is the bare `else` token. Recognition only; the `Else`
204 // token pays cognitive's +1 and the statement `Branch`'s.
205 ElseIf { owns [IfStatement(gated_by follows_else_keyword)] pays [] }
206 // `return`, `yield return` / `yield break`, `throw` as a statement
207 // and as an expression (`x ?? throw …`).
208 Exit { owns [ReturnStatement, YieldStatement, ThrowStatement, ThrowExpression] }
209 // Every modifier keyword leaf, plus the childless `modifier` alias
210 // the grammar emits for a bare keyword in a parameter or on a
211 // lambda, under its text gate. `ref` / `out` / `in` / `scoped` are
212 // listed here as the aliased spelling only: as their own kinds they
213 // are the expression keywords of `ref x` / `out var y` / `in` / a
214 // `scoped` local, and bill with `await` and `is`. `new` is the
215 // hiding modifier and the allocation keyword in one kind, billed
216 // with the expression keywords for the same reason. The `modifier`
217 // rule with a child wraps a leaf this row owns and is nothing
218 // itself (grammar-dispatch section 5).
219 Modifier {
220 owns [
221 Public, Private, Protected, Internal, Static, Abstract, Virtual, Override, Sealed,
222 Partial, Readonly, Const, Extern, Unsafe, Volatile, Async, Required, File, Fixed,
223 Implicit, Explicit, Modifier(text_gated_by aliases_a_modifier_keyword no_chain),
224 ]
225 }
226 // The declaration and namespace keywords, each its leaf under an
227 // unclassified `*_declaration` (#1552). `using` bills, and so does
228 // the `static` of `using static` through the row above: C# bills
229 // its directive keywords where Java and Groovy bill none of theirs
230 // (#1600).
231 DeclKeyword { owns [Class, Struct, Interface, Enum, Record, Delegate, Namespace, Using] }
232 // `predefined_type` is one kind for every spelling (`int`, `string`,
233 // `bool`, …), so `Checker::is_primitive` keys it by text (#286).
234 // `var` is excluded: it names no type, and the `implicit_type`
235 // wrapping it bills nothing.
236 Primitive {
237 owns [PredefinedType]
238 excludes [Var "`var` names no type; its `implicit_type` wrapper bills nothing"]
239 }
240 // Every callable opens a `Function` space: the method-like
241 // declarations, a local function, an accessor (`get` / `set` /
242 // `init` — each is a method per C# IL semantics), the operator
243 // forms, and an indexer or property only in its accessor-less
244 // expression-bodied form (`has_no_accessors`). A lambda and an
245 // anonymous method (`delegate { }`) are closures that open a space
246 // too, as Rust's and Go's do.
247 //
248 // A C# 12 primary constructor and a positional record's constructor
249 // have no node of their own: the grammar hangs their
250 // `parameter_list` directly under the type declaration, the one
251 // place a parameter list is not a callable's `parameters` field
252 // (`node-types.json`: `class_declaration`, `struct_declaration`
253 // and `record_declaration` carry it as a child; an interface and
254 // an enum cannot). That list is the constructor (#1828). Its
255 // superclass call sits in the sibling `base_list`, outside it.
256 FuncOpener {
257 owns [
258 MethodDeclaration(callable opens Function),
259 ConstructorDeclaration(callable opens Function),
260 ParameterList(callable opens Function under [ClassDeclaration, StructDeclaration, RecordDeclaration]),
261 DestructorDeclaration(callable opens Function),
262 LocalFunctionStatement(callable opens Function),
263 AccessorDeclaration(callable opens Function),
264 OperatorDeclaration(callable opens Function),
265 ConversionOperatorDeclaration(callable opens Function),
266 IndexerDeclaration(callable opens Function gated_by has_no_accessors no_chain),
267 PropertyDeclaration(callable opens Function gated_by has_no_accessors no_chain),
268 LambdaExpression(opens Function),
269 AnonymousMethodExpression(opens Function),
270 ]
271 }
272 Closure { owns [LambdaExpression, AnonymousMethodExpression] }
273 // An enum opens `Class` for parity with Java / PHP / Groovy (#429).
274 Container {
275 owns [
276 CompilationUnit(opens Unit),
277 ClassDeclaration(opens Class),
278 StructDeclaration(opens Class),
279 RecordDeclaration(opens Class),
280 EnumDeclaration(opens Class),
281 InterfaceDeclaration(opens Interface),
282 ]
283 }
284 // A field declaration (`int a, b;` — one declaration, declarators
285 // the consumer counts), in a class-like or an interface body; a
286 // positional record's parameters become properties at the IL level
287 // and have no declaration node to recognise (`npa/csharp.rs`).
288 Member { owns [FieldDeclaration] }
289 // The one comment kind, a `DocComment` owner under the marker gate
290 // (#1699).
291 Comment { owns [Comment] }
292 DocComment { owns [Comment(text_gated_by opens_with_xml_doc_marker no_chain)] }
293 Docstring { absent "C# documents with `///` comments, not string literals" }
294 // The members `DocumentationCommentCompiler` writes: a type, a
295 // delegate, a member and an enum member. A namespace (block or
296 // file-scoped), a `using`, an assembly attribute, a top-level
297 // statement and an accessor take none; checked with `dotnet build`
298 // and CS1587. Outside the space-tree rows: the delegate, the event
299 // field and event, and the enum member — the parity exceptions
300 // `roles/doc_tests/parity.rs` records.
301 DocTarget {
302 owns [
303 ClassDeclaration,
304 StructDeclaration,
305 RecordDeclaration,
306 InterfaceDeclaration,
307 EnumDeclaration,
308 DelegateDeclaration,
309 MethodDeclaration,
310 ConstructorDeclaration,
311 DestructorDeclaration,
312 OperatorDeclaration,
313 ConversionOperatorDeclaration,
314 FieldDeclaration,
315 EventFieldDeclaration,
316 EventDeclaration,
317 PropertyDeclaration,
318 IndexerDeclaration,
319 EnumMemberDeclaration,
320 ]
321 }
322 DocRunOpener { absent "Roslyn attaches every doc comment to a member; none documents by its own content" }
323 DocRunDirective { absent "Roslyn reads no directive comment" }
324 // A property or indexer holds every doc comment in it but those in
325 // its accessor list: Roslyn binds one only before the member, so a
326 // comment in its header or initializer documents nothing. Both are
327 // `FuncOpener` owners in their accessor-less form; this row names
328 // them in *every* form, and the Checker reads it before the
329 // callable test so the accessor search is never run per comment
330 // (#1612). Which child is the accessor list is the Checker's.
331 DocBodyResidual { owns [IndexerDeclaration, PropertyDeclaration] }
332}