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<'_>, _code: &[u8]) -> 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>, _code: &[u8], _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>, _code: &[u8], 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 FuncOpener {
248 owns [
249 MethodDeclaration(callable opens Function),
250 ConstructorDeclaration(callable opens Function),
251 DestructorDeclaration(callable opens Function),
252 LocalFunctionStatement(callable opens Function),
253 AccessorDeclaration(callable opens Function),
254 OperatorDeclaration(callable opens Function),
255 ConversionOperatorDeclaration(callable opens Function),
256 IndexerDeclaration(callable opens Function gated_by has_no_accessors no_chain),
257 PropertyDeclaration(callable opens Function gated_by has_no_accessors no_chain),
258 LambdaExpression(opens Function),
259 AnonymousMethodExpression(opens Function),
260 ]
261 }
262 Closure { owns [LambdaExpression, AnonymousMethodExpression] }
263 // An enum opens `Class` for parity with Java / PHP / Groovy (#429).
264 Container {
265 owns [
266 CompilationUnit(opens Unit),
267 ClassDeclaration(opens Class),
268 StructDeclaration(opens Class),
269 RecordDeclaration(opens Class),
270 EnumDeclaration(opens Class),
271 InterfaceDeclaration(opens Interface),
272 ]
273 }
274 // A field declaration (`int a, b;` — one declaration, declarators
275 // the consumer counts), in a class-like or an interface body; a
276 // positional record's parameters become properties at the IL level
277 // and have no declaration node to recognise (`npa/csharp.rs`).
278 Member { owns [FieldDeclaration] }
279 // The one comment kind, a `DocComment` owner under the marker gate
280 // (#1699).
281 Comment { owns [Comment] }
282 DocComment { owns [Comment(text_gated_by opens_with_xml_doc_marker no_chain)] }
283 Docstring { absent "C# documents with `///` comments, not string literals" }
284 // The members `DocumentationCommentCompiler` writes: a type, a
285 // delegate, a member and an enum member. A namespace (block or
286 // file-scoped), a `using`, an assembly attribute, a top-level
287 // statement and an accessor take none; checked with `dotnet build`
288 // and CS1587. Outside the space-tree rows: the delegate, the event
289 // field and event, and the enum member — the parity exceptions
290 // `roles/doc_tests/parity.rs` records.
291 DocTarget {
292 owns [
293 ClassDeclaration,
294 StructDeclaration,
295 RecordDeclaration,
296 InterfaceDeclaration,
297 EnumDeclaration,
298 DelegateDeclaration,
299 MethodDeclaration,
300 ConstructorDeclaration,
301 DestructorDeclaration,
302 OperatorDeclaration,
303 ConversionOperatorDeclaration,
304 FieldDeclaration,
305 EventFieldDeclaration,
306 EventDeclaration,
307 PropertyDeclaration,
308 IndexerDeclaration,
309 EnumMemberDeclaration,
310 ]
311 }
312 DocRunOpener { absent "Roslyn attaches every doc comment to a member; none documents by its own content" }
313 DocRunDirective { absent "Roslyn reads no directive comment" }
314 // A property or indexer holds every doc comment in it but those in
315 // its accessor list: Roslyn binds one only before the member, so a
316 // comment in its header or initializer documents nothing. Both are
317 // `FuncOpener` owners in their accessor-less form; this row names
318 // them in *every* form, and the Checker reads it before the
319 // callable test so the accessor search is never run per comment
320 // (#1612). Which child is the accessor list is the Checker's.
321 DocBodyResidual { owns [IndexerDeclaration, PropertyDeclaration] }
322}