From 43469128934a426840dc3051a26bdce02ff6d3f4 Mon Sep 17 00:00:00 2001 From: Rex Jaeschke Date: Thu, 7 Dec 2023 07:28:52 -0500 Subject: [PATCH 01/30] Add support for pattern additions Add support for pattern additions fix md and example update headings fix link warnings Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/lexical-structure.md | 17 +-- standard/patterns.md | 220 +++++++++++++++++++++++++++++++++- 2 files changed, 227 insertions(+), 10 deletions(-) diff --git a/standard/lexical-structure.md b/standard/lexical-structure.md index cdb6aa171..8e87a9c3b 100644 --- a/standard/lexical-structure.md +++ b/standard/lexical-structure.md @@ -78,9 +78,10 @@ These productions occur in contexts where a value can occur in an expression, an If a sequence of tokens can be parsed, in context, as one of the disambiguated productions including an optional *type_argument_list* ([§8.4.2](types.md#842-type-arguments)), then the token immediately following the closing `>` token shall be examined and if it is: -- one of `( ) ] } : ; , . ? == != | ^ && || & [`; or +- one of `( ) ] } : ; , . ? == != | ^ && || & [ =>`; or - one of the relational operators `< <= >= is as`; or - a contextual query keyword appearing inside a query expression. +- In certain contexts, *identifier* is treated as a disambiguating token. Those contexts are where the sequence of tokens being disambiguated is immediately preceded by one of the keywords `is`, `case` or `out`, or arises while parsing the first element of a tuple literal (in which case the tokens are preceded by `(` or `:` and the identifier is followed by a `,`) or a subsequent element of a tuple literal. then the *type_argument_list* shall be retained as part of the disambiguated production and any other possible parse of the sequence of tokens discarded. Otherwise, the tokens parsed as a *type_argument_list* shall not be considered to be part of the disambiguated production, even if there is no other possible parse of those tokens. @@ -604,13 +605,13 @@ A ***contextual keyword*** is an identifier-like sequence of characters that has ```ANTLR contextual_keyword - : 'add' | 'alias' | 'ascending' | 'async' | 'await' - | 'by' | 'descending' | 'dynamic' | 'equals' | 'from' - | 'get' | 'global' | 'group' | 'into' | 'join' - | 'let' | 'nameof' | 'nint' | 'notnull' | 'nuint' - | 'on' | 'orderby' | 'partial' | 'remove' | 'select' - | 'set' | 'unmanaged' | 'value' | 'var' | 'when' - | 'where' | 'yield' + : 'add' | 'alias' | 'and' | 'ascending' | 'async' + | 'await' | 'by' | 'descending' | 'dynamic' | 'equals' + | 'from' | 'get' | 'global' | 'group' | 'into' + | 'join' | 'let' | 'nameof' | 'nint' | 'not' + | 'notnull' | 'nuint' | 'on' | 'or' | 'orderby' + | 'partial' | 'remove' | 'select' | 'set' | 'unmanaged' + | 'value' | 'var' | 'when' | 'where' | 'yield' ; ``` diff --git a/standard/patterns.md b/standard/patterns.md index b65b2147c..0443b5aef 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -11,7 +11,7 @@ A pattern is tested against a value in a number of contexts: - In a *switch_expression*, the *pattern* of a *switch_expression_arm* is tested against the expression on the *switch_expression*’s left-hand-side. - In nested contexts, the *sub-pattern* is tested against values retrieved from properties, fields, or indexed from other input values, depending on the pattern form. -The value against which a pattern is tested is called the ***pattern input value***. +The value against which a pattern is tested is called the ***pattern input value***. Patterns may be combined using Boolean logic. A pattern `P` is *subsumed* by set of unguarded patterns `Q` if any input value matched by `P` is matched by one of the members of `Q`. @@ -27,12 +27,16 @@ A pattern may have one of the following forms: ```ANTLR pattern - : declaration_pattern + : '(' pattern ')' + | declaration_pattern | constant_pattern | var_pattern | positional_pattern | property_pattern | discard_pattern + | type_pattern + | relational_pattern + | logical_pattern ; ``` @@ -531,3 +535,215 @@ If, after applying the preceding rule, the token `_` is still a *discard_pattern > ``` > > *end example* + +### §type-pattern-new-clause Type pattern + +A *type_pattern* is used to test that the pattern input value ([§11.1](patterns.md#111-general)) has a given type. + +```ANTLR +type_pattern + : type + ; +``` + +The runtime type of the value is tested against *type* using the same rules specified in the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test succeeds, the pattern matches that value. It is a compile-time error if the *type* is a nullable type. This pattern form never matches a `null` value. + +### §relational-pattern-new-clause Relational pattern + +A *relational_pattern* is used to relationally test the pattern input value ([§11.1](patterns.md#111-general)) against a constant value. + +```ANTLR +relational_pattern + : '<' constant_expression + | '<=' constant_expression + | '>' constant_expression + | '>=' constant_expression + ; +``` + +Relational patterns support the relational operators `<`, `<=`, `>`, and `>=` on all of the built-in types that support such binary relational operators with both operands having the same type: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, and enums. + +It is a compile-time error if `constant_expression`is `double.NaN`, `float.NaN`, or `null_literal`. + +When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of `constant_expression` using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the `constant_expression`. + +> *Example*: +> +> +> ```csharp +> Console.WriteLine(Classify(13)); +> Console.WriteLine(Classify(double.NaN)); +> Console.WriteLine(Classify(2.4)); +> +> static string Classify(double measurement) => measurement switch +> { +> < -4.0 => "Too low", +> > 10.0 => "Too high", +> double.NaN => "Unknown", +> _ => "Acceptable", +> }; +> ``` +> +> The output produced is +> +> ```console +> Too high +> Unknown +> Acceptable +> ``` +> +> *end example* + +### §logical-pattern-new-clause Logical pattern + +A *logical_pattern* is used to negate a pattern input value ([§11.1](patterns.md#111-general)) or to combine that value with a pattern using a Boolean operator. + +```ANTLR +logical_pattern + : disjunctive_pattern + ; + +disjunctive_pattern + : disjunctive_pattern 'or' conjunctive_pattern + | conjunctive_pattern + ; + +conjunctive_pattern + : conjunctive_pattern 'and' negated_pattern + | negated_pattern + ; + +negated_pattern + : 'not' negated_pattern + | pattern + ; +``` + +`not`, `and`, and `or` are collectively called ***pattern operators***. + +A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. + +> *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* + +When a *pattern* is used with `is`, any pattern operators in that *pattern* have higher precedence than their logical operator counterparts. Otherwise, those pattern operators have lower precedence. + +> *Example*: +> +> +> ```csharp +> Console.WriteLine(Classify(13)); +> Console.WriteLine(Classify(-100)); +> Console.WriteLine(Classify(5.7)); +> +> static string Classify(double measurement) => measurement switch +> { +> < -40.0 => "Too low", +> >= -40.0 and < 0 => "Low", +> >= 0 and < 10.0 => "Acceptable", +> >= 10.0 and < 20.0 => "High", +> >= 20.0 => "Too high", +> double.NaN => "Unknown", +> }; +> ``` +> +> The output produced is +> +> ```console +> High +> Too low +> Acceptable +> ``` +> +> *end example* + + + +> *Example*: +> +> +> ```csharp +> Console.WriteLine(GetCalendarSeason(new DateTime(2021, 1, 19))); +> Console.WriteLine(GetCalendarSeason(new DateTime(2021, 10, 9))); +> Console.WriteLine(GetCalendarSeason(new DateTime(2021, 5, 11))); +> +> static string GetCalendarSeason(DateTime date) => date.Month switch +> { +> 3 or 4 or 5 => "spring", +> 6 or 7 or 8 => "summer", +> 9 or 10 or 11 => "autumn", +> 12 or 1 or 2 => "winter", +> _ => throw new ArgumentOutOfRangeException(nameof(date), +> $"Date with unexpected month: {date.Month}."), +> }; +> ``` +> +> The output produced is +> +> ```console +> winter +> autumn +> spring +> ``` +> +> *end example* + +## 11.3 Pattern subsumption + +In a switch statement ([§13.8.3](statements.md#1383-the-switch-statement)), it is an error if a case’s pattern is *subsumed* by the preceding set of *unguarded* ([§13.8.3](statements.md#1383-the-switch-statement)) cases. In a switch expression ([§12.11](expressions.md#1211-switch-expression)), it is an error if a *switch_expression_arm*’s pattern is *subsumed* by the preceding set of *unguarded* *switch_expression_arm*s’ patterns. +> *Note*: This means that any input value would have been matched by one of the previous cases or arms. *end note* +The following rules define when a set of patterns subsumes a given pattern: + +A pattern `P` *would match* a constant `K` if the specification for that pattern’s runtime behavior is that `P` matches `K`. + +A set of patterns `Q` *subsumes* a pattern `P` if any of the following conditions hold: + +- `P` is a constant pattern and any of the patterns in the set `Q` would match `P`’s *converted value* +- `P` is a var pattern and the set of patterns `Q` is *exhaustive* ([§11.4](patterns.md#114-pattern-exhaustiveness)) for the type of the pattern input value ([§11.1](patterns.md#111-general)), and either the pattern input value is not of a nullable type or some pattern in `Q` would match `null`. +- `P` is a declaration pattern with type `T` and the set of patterns `Q` is *exhaustive* for the type `T` ([§11.4](patterns.md#114-pattern-exhaustiveness)). + +> *Example*: In the following switch expression, no arm is subsumed even though arms 1, 2, and 3 share the same pattern: +> +> +> ```csharp +> object x = 10; +> bool b = false; +> int y = x switch +> { +> int i when !b => 0, +> int i when b => 1, +> int i => 2, +> _ => 3 +> }; +> ``` +> +> Arms 1 and 2 have non-constant guards and so are not *unguarded*; only arm 3 is *unguarded* with pattern `int i`, which does not subsume the final `_` arm because it does not match a non-`int` value such as `null`. *end example* + +## 11.4 Pattern exhaustiveness + +Informally, a set of patterns is exhaustive for a type if, for every possible value of that type other than null, some pattern in the set is applicable. +The following rules define when a set of patterns is *exhaustive* for a type: + +A set of patterns `Q` is *exhaustive* for a type `T` if any of the following conditions hold: + +1. `T` is an integral or enum type, or a nullable version of one of those, and for every possible value of `T`’s non-nullable underlying type, some pattern in `Q` would match that value; or +2. Some pattern in `Q` is a *var pattern*; or +3. Some pattern in `Q` is a *declaration pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`. + +> *Example*: +> +> +> ```csharp +> static void M(byte b) +> { +> switch (b) { +> case 0: case 1: case 2: ... // handle every specific value of byte +> break; +> // error: the pattern 'byte other' is subsumed by the (exhaustive) +> // previous cases +> case byte other: +> break; +> } +> } +> ``` +> +> *end example* From aaa0ab7621c9e0944a25193aac3555221cd24540 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 12:47:21 -0500 Subject: [PATCH 02/30] Address lined comments Address the comments on specific lines in #1026. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 0443b5aef..7b5d7d21d 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -11,7 +11,7 @@ A pattern is tested against a value in a number of contexts: - In a *switch_expression*, the *pattern* of a *switch_expression_arm* is tested against the expression on the *switch_expression*’s left-hand-side. - In nested contexts, the *sub-pattern* is tested against values retrieved from properties, fields, or indexed from other input values, depending on the pattern form. -The value against which a pattern is tested is called the ***pattern input value***. Patterns may be combined using Boolean logic. +The value against which a pattern is tested is called the ***pattern input value***. A pattern `P` is *subsumed* by set of unguarded patterns `Q` if any input value matched by `P` is matched by one of the members of `Q`. @@ -44,6 +44,8 @@ If the input can be syntactically recognised as both a *constant_pattern* and a > *Note*: ANTLR makes the specified choice automatically due to the ordering of *constant_pattern* before *positional_pattern* in the alternatives of *pattern*. *end note* +The `'(' pattern ')'` production allows a pattern to be enclosed in parentheses to enforce the order of evaluation among patterns combined using one of the *logical_pattern*s. + Some *pattern*s can result in the declaration of a local variable. Each pattern form defines the set of types for input values that the pattern may be applied to. A pattern `P` is *applicable to* a type `T` if `T` is among the types whose values the pattern may match. It is a compile-time error if a pattern `P` appears in a program to match a pattern input value ([§11.1](patterns.md#111-general)) of type `T` if `P` is not applicable to `T`. @@ -563,7 +565,7 @@ relational_pattern Relational patterns support the relational operators `<`, `<=`, `>`, and `>=` on all of the built-in types that support such binary relational operators with both operands having the same type: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, and enums. -It is a compile-time error if `constant_expression`is `double.NaN`, `float.NaN`, or `null_literal`. +It is a compile-time error if `constant_expression` evaluates to one of `double.NaN`, `float.NaN`, or `null_literal`. When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of `constant_expression` using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the `constant_expression`. @@ -596,7 +598,7 @@ When the input value has a type for which a suitable built-in binary relational ### §logical-pattern-new-clause Logical pattern -A *logical_pattern* is used to negate a pattern input value ([§11.1](patterns.md#111-general)) or to combine that value with a pattern using a Boolean operator. +A *logical_pattern* is used to negate the result of matching a pattern input value ([§11.1](patterns.md#111-general)) or to combine that match result with a pattern using a Boolean operator. ```ANTLR logical_pattern @@ -686,6 +688,33 @@ When a *pattern* is used with `is`, any pattern operators in that *pattern* have > ``` > > *end example* + + + +> *Example*: +> +> +> ```csharp +> object obj = 5; +> bool flag = true; +> +> // This is parsed as: (obj is (int or string)) && flag +> bool result = obj is int or string && flag; +> Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); // True +> +> // This is parsed as: (obj is int) || ((obj is string) && flag) +> result = obj is int || obj is string && flag; +> Console.WriteLine($"obj (5), flag (true): obj is int || obj is string && flag: {result}"); // True +> +> flag = false; +> // This is parsed as: (obj is (int or string)) && flag +> result = obj is int or string && flag; +> Console.WriteLine($"obj (5), flag (false): obj is int or string && flag: {result}"); // False +> +> // This is parsed as: (obj is int) || ((obj is string) && flag) +> result = obj is int || obj is string && flag; +> Console.WriteLine($"obj (5), flag (false): obj is int || obj is string && flag: {result}"); // True +> ``` ## 11.3 Pattern subsumption From 8e5ada2aa4933e6553cde4f927cfcab8ac3b4516 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 14:38:02 -0500 Subject: [PATCH 03/30] Address general comment Address the comments in the general review comment on #1026: - I did continue to use the *logical_pattern* production. We use that term in the text, and it's a good shorthand so readers don't need to snake through the grammar of *disjunctive_pattern*, *conjunctive_pattern* and *negated_pattern*. - I haven't addressed or created issues for the open questions in the proposal yet. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 7b5d7d21d..b10e67f41 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -27,16 +27,24 @@ A pattern may have one of the following forms: ```ANTLR pattern - : '(' pattern ')' + : logical_pattern + ; + +primary_pattern + : parenthesized_pattern | declaration_pattern | constant_pattern | var_pattern | positional_pattern | property_pattern | discard_pattern + | parenthesized_pattern | type_pattern | relational_pattern - | logical_pattern + ; + +parenthesized_pattern + : '(' pattern ')' ; ``` @@ -556,10 +564,10 @@ A *relational_pattern* is used to relationally test the pattern input value ([§ ```ANTLR relational_pattern - : '<' constant_expression - | '<=' constant_expression - | '>' constant_expression - | '>=' constant_expression + : '<' relational_expression + | '<=' relational_expression + | '>' relational_expression + | '>=' relational_expression ; ``` @@ -617,7 +625,7 @@ conjunctive_pattern negated_pattern : 'not' negated_pattern - | pattern + | primary_pattern ; ``` From 80d6451780be92b72d822fe1535e04eee6634209 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 15:42:36 -0500 Subject: [PATCH 04/30] Fix build issue Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard/patterns.md b/standard/patterns.md index b10e67f41..e243b917e 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -701,7 +701,7 @@ When a *pattern* is used with `is`, any pattern operators in that *pattern* have > *Example*: > -> +> > ```csharp > object obj = 5; > bool flag = true; From f14e1a5c09899b42bac9d16a39ecca7c848440bf Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 16:04:11 -0500 Subject: [PATCH 05/30] Add closing tag Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/standard/patterns.md b/standard/patterns.md index e243b917e..9fd8215fb 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -723,6 +723,8 @@ When a *pattern* is used with `is`, any pattern operators in that *pattern* have > result = obj is int || obj is string && flag; > Console.WriteLine($"obj (5), flag (false): obj is int || obj is string && flag: {result}"); // True > ``` +> +> *end example* ## 11.3 Pattern subsumption From 5679cb61853a54aa2c88cd1ba2482cb58f72c4f4 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 16:07:12 -0500 Subject: [PATCH 06/30] fix output Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 9fd8215fb..09004c96a 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -708,22 +708,32 @@ When a *pattern* is used with `is`, any pattern operators in that *pattern* have > > // This is parsed as: (obj is (int or string)) && flag > bool result = obj is int or string && flag; -> Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); // True +> Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); > > // This is parsed as: (obj is int) || ((obj is string) && flag) > result = obj is int || obj is string && flag; -> Console.WriteLine($"obj (5), flag (true): obj is int || obj is string && flag: {result}"); // True +> Console.WriteLine($"obj (5), flag (true): obj is int || obj is string && flag: {result}"); > > flag = false; > // This is parsed as: (obj is (int or string)) && flag > result = obj is int or string && flag; -> Console.WriteLine($"obj (5), flag (false): obj is int or string && flag: {result}"); // False +> Console.WriteLine($"obj (5), flag (false): obj is int or string && flag: {result}"); > > // This is parsed as: (obj is int) || ((obj is string) && flag) > result = obj is int || obj is string && flag; -> Console.WriteLine($"obj (5), flag (false): obj is int || obj is string && flag: {result}"); // True +> Console.WriteLine($"obj (5), flag (false): obj is int || obj is string && flag: {result}"); > ``` > +> The output produced is +> +> ```console +> True +> True +> False +> True +> ``` +> +> > *end example* ## 11.3 Pattern subsumption From 4c38af2a876682c1d8dc4b3b722020b073dbdefc Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 16:10:36 -0500 Subject: [PATCH 07/30] more fixing the output Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 09004c96a..9ea138771 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -727,10 +727,10 @@ When a *pattern* is used with `is`, any pattern operators in that *pattern* have > The output produced is > > ```console -> True -> True -> False -> True +> obj (5), flag (true): obj is int or string && flag: True +> obj (5), flag (true): obj is int || obj is string && flag: True +> obj (5), flag (false): obj is int or string && flag: False +> obj (5), flag (false): obj is int || obj is string && flag: True > ``` > > From 50ff3decd68fee232f99a5864fb1b06414d56317 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Thu, 19 Feb 2026 17:28:32 -0500 Subject: [PATCH 08/30] Add LDM decisions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/standard/patterns.md b/standard/patterns.md index 9ea138771..6606c9109 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -633,6 +633,18 @@ negated_pattern A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. +In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed by the *type narrowing* requirements of first pattern of the `and`. The *narrowed type* of a pattern `P` is defined as follows: + +- If `P` is a type pattern, the *narrowed type* is the type of the type pattern's type. +- Otherwise, if `P` is a declaration pattern, the *narrowed type* is the type of the declaration pattern's type. +- Otherwise, if `P` is a recursive pattern that gives an explicit type, the *narrowed type* is that type. +- Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.Runtime.CompilerServices.ITuple`. +- Otherwise, if `P` is a constant pattern where the constant is not the null constant and where the expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. +- Otherwise, if `P` is a relational pattern where the constant expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. +- Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). +- Otherwise, if `P` is an `and` pattern, the *narrowed type* is the *narrowed type* of the right pattern. Moreover, the *narrowed type* of the left pattern is the *input type* of the right pattern. +- Otherwise the *narrowed type* of `P` is `P`'s input type. + > *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* When a *pattern* is used with `is`, any pattern operators in that *pattern* have higher precedence than their logical operator counterparts. Otherwise, those pattern operators have lower precedence. From a53e879873f97d23871a8580ae975156f1b92bc1 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Mon, 23 Feb 2026 16:20:47 -0500 Subject: [PATCH 09/30] Add subsumption and exhaustiveness Add the subsumption and exhaustiveness rules for the new patterns in V9. The subsumption/exhaustiveness rules in the Roslyn compiler use a BDD (binary decision diagram)-based algorithm that is more powerful than can be expressed with simple prose rules. These rules attempt to capture the *observable behavior* (what the compiler accepts/rejects) rather than the implementation algorithm. Where the compiler's algorithm is too complex to fully express (e.g., relational range analysis), the spec describes the intent and give examples. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 6606c9109..4ff49d3bd 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -633,6 +633,10 @@ negated_pattern A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. +It is a compile-time error for a pattern variable to be declared beneath a `not` or `or` pattern operator. + +> *Note*: Because neither `not` nor `or` can produce a definite assignment for a pattern variable, it is an error to declare one in those positions. *end note* + In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed by the *type narrowing* requirements of first pattern of the `and`. The *narrowed type* of a pattern `P` is defined as follows: - If `P` is a type pattern, the *narrowed type* is the type of the type pattern's type. @@ -754,13 +758,29 @@ In a switch statement ([§13.8.3](statements.md#1383-the-switch-statement)), it > *Note*: This means that any input value would have been matched by one of the previous cases or arms. *end note* The following rules define when a set of patterns subsumes a given pattern: -A pattern `P` *would match* a constant `K` if the specification for that pattern’s runtime behavior is that `P` matches `K`. +A pattern `P` *would match* a constant `K` if any of the following conditions hold: + +- the specification for that pattern's runtime behavior is that `P` matches `K`. +- `P` is a *type_pattern* for type `T` and `K` is not `null` and the runtime type of `K` is `T` or a type derived from `T` or a type that implements `T`. +- `P` is a *relational_pattern* with operator «op» and constant `v`, and the expression `K` «op» `v` would evaluate to `true`. +- `P` is a *negated_pattern* `not P₁` and `P₁` would not match `K`. +- `P` is a *conjunctive_pattern* `P₁ and P₂` and both `P₁` would match `K` and `P₂` would match `K`. +- `P` is a *disjunctive_pattern* `P₁ or P₂` and either `P₁` would match `K` or `P₂` would match `K`. +- `P` is a *discard_pattern*. A set of patterns `Q` *subsumes* a pattern `P` if any of the following conditions hold: -- `P` is a constant pattern and any of the patterns in the set `Q` would match `P`’s *converted value* +- `P` is a constant pattern and any of the patterns in the set `Q` would match `P`'s *converted value* - `P` is a var pattern and the set of patterns `Q` is *exhaustive* ([§11.4](patterns.md#114-pattern-exhaustiveness)) for the type of the pattern input value ([§11.1](patterns.md#111-general)), and either the pattern input value is not of a nullable type or some pattern in `Q` would match `null`. - `P` is a declaration pattern with type `T` and the set of patterns `Q` is *exhaustive* for the type `T` ([§11.4](patterns.md#114-pattern-exhaustiveness)). +- `P` is a *type_pattern* for type `T` and the set of patterns `Q` is *exhaustive* for the type `T`. +- `P` is a *relational_pattern* with operator «op» and constant value `v`, and for every value of the input type satisfying the relation «op» `v`, some pattern in the set `Q` would match that value. +- `P` is a *disjunctive_pattern* `P₁ or P₂` and the set of patterns `Q` subsumes `P₁` and `Q` subsumes `P₂`. +- `P` is a *conjunctive_pattern* `P₁ and P₂` and at least one of the following holds: `Q` subsumes `P₁`, or `Q` subsumes `P₂`. +- `P` is a *negated_pattern* `not P₁` and `Q` is *exhaustive* for the input type considering only the values not matched by `P₁`. +- `P` is a *discard_pattern* and the set of patterns `Q` is *exhaustive* for the type of the pattern input value, and either the pattern input value is not of a nullable type or some pattern in `Q` would match `null`. +- Some pattern in `Q` is a *disjunctive_pattern* `Q₁ or Q₂` and replacing that pattern with `Q₁` in `Q` would yield a set that subsumes `P`, or replacing it with `Q₂` would yield a set that subsumes `P`. +- Some pattern in `Q` is a *negated_pattern* `not Q₁` and `P` would not match any value that `Q₁` would match. > *Example*: In the following switch expression, no arm is subsumed even though arms 1, 2, and 3 share the same pattern: > @@ -787,8 +807,16 @@ The following rules define when a set of patterns is *exhaustive* for a type: A set of patterns `Q` is *exhaustive* for a type `T` if any of the following conditions hold: 1. `T` is an integral or enum type, or a nullable version of one of those, and for every possible value of `T`’s non-nullable underlying type, some pattern in `Q` would match that value; or -2. Some pattern in `Q` is a *var pattern*; or -3. Some pattern in `Q` is a *declaration pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`. +1. Some pattern in `Q` is a *var pattern*; or +1. Some pattern in `Q` is a *declaration pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`; or +1. Some pattern in `Q` is a *type_pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`; or +1. Some pattern in `Q` is a *discard_pattern*; or +1. The patterns in `Q` include a combination of *relational_pattern*s and *constant_pattern*s whose ranges collectively cover every possible value of `T`'s non-nullable underlying type. For `float` and `double` types, this includes `System.Double.NaN` or `System.Single.NaN` respectively, since `NaN` is not matched by any relational pattern; or +1. Some pattern in `Q` is a *disjunctive_pattern* `P₁ or P₂`, and replacing that pattern with both `P₁` and `P₂` in `Q` yields a set that is *exhaustive* for `T`; or +1. Some pattern in `Q` is a *negated_pattern* `not P₁`, and the patterns in `Q` together with the values not matched by `P₁` cover every possible value of `T`. A *negated_pattern* `not P₁` is exhaustive by itself when `P₁` matches no possible value of `T`; or +1. Some pattern in `Q` is a *conjunctive_pattern* `P₁ and P₂`, and the set containing only `P₁` is *exhaustive* for `T` and the set containing only `P₂` is *exhaustive* for `T`. + +> *Note*: For floating-point types, the combination of patterns `< 0` and `>= 0` is *not* exhaustive because neither relational pattern matches `NaN`. A correct exhaustive set would be `< 0`, `>= 0`, and `double.NaN` (or `float.NaN`). *end note* > *Example*: > From d4139acfc97817b454f6c97c08e410e37806521d Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 27 Feb 2026 15:36:38 -0500 Subject: [PATCH 10/30] Editorial pass - Removed duplicate parenthesized_pattern from the primary_pattern production - Fixed relational pattern prose Added a sentence after the grammar: "The relational_expression in a relational_pattern is required to evaluate to a constant value." Replaced backtick-formatted `constant_expression` references with plain prose ("the expression", "the constant expression"). Changed `null_literal` to "a null constant" (it's a semantic constraint, not a syntactic one). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 4ff49d3bd..76bdfeddc 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -38,7 +38,6 @@ primary_pattern | positional_pattern | property_pattern | discard_pattern - | parenthesized_pattern | type_pattern | relational_pattern ; @@ -571,11 +570,13 @@ relational_pattern ; ``` +The *relational_expression* in a *relational_pattern* is required to evaluate to a constant value. + Relational patterns support the relational operators `<`, `<=`, `>`, and `>=` on all of the built-in types that support such binary relational operators with both operands having the same type: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, and enums. -It is a compile-time error if `constant_expression` evaluates to one of `double.NaN`, `float.NaN`, or `null_literal`. +It is a compile-time error if the expression evaluates to `double.NaN`, `float.NaN`, or a null constant. -When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of `constant_expression` using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the `constant_expression`. +When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of the constant expression using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the constant expression. > *Example*: > From 8defb68a03078e92287c32a6287f53bd0c82724e Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 27 Feb 2026 15:41:53 -0500 Subject: [PATCH 11/30] Use consistent `ITuple` This was in the incorrect namespace Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard/patterns.md b/standard/patterns.md index 76bdfeddc..2c0eaf7b2 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -643,7 +643,7 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b - If `P` is a type pattern, the *narrowed type* is the type of the type pattern's type. - Otherwise, if `P` is a declaration pattern, the *narrowed type* is the type of the declaration pattern's type. - Otherwise, if `P` is a recursive pattern that gives an explicit type, the *narrowed type* is that type. -- Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.Runtime.CompilerServices.ITuple`. +- Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.ITuple`. - Otherwise, if `P` is a constant pattern where the constant is not the null constant and where the expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. - Otherwise, if `P` is a relational pattern where the constant expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. - Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). From 3558bd0325e588f104bfb71b4c3a29164c8d9328 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 27 Feb 2026 15:44:05 -0500 Subject: [PATCH 12/30] Add consistent "Is applicable to" language MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Applicability rule for type pattern: "A type pattern naming a type T is applicable to every type E for which E is pattern compatible with T (§11.2.2)." Applicability rule for relational pattern: "A relational_pattern is applicable to a type T if a suitable built-in binary relational operator is defined with both operands of type T, or if an explicit nullable or unboxing conversion exists from T to the type of the constant expression." Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/standard/patterns.md b/standard/patterns.md index 2c0eaf7b2..ca67a8c37 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -555,6 +555,8 @@ type_pattern ; ``` +A type pattern naming a type `T` is *applicable to* every type `E` for which `E` is *pattern compatible* with `T` (§11.2.2). + The runtime type of the value is tested against *type* using the same rules specified in the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test succeeds, the pattern matches that value. It is a compile-time error if the *type* is a nullable type. This pattern form never matches a `null` value. ### §relational-pattern-new-clause Relational pattern @@ -574,6 +576,8 @@ The *relational_expression* in a *relational_pattern* is required to evaluate to Relational patterns support the relational operators `<`, `<=`, `>`, and `>=` on all of the built-in types that support such binary relational operators with both operands having the same type: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, and enums. +A *relational_pattern* is *applicable to* a type `T` if a suitable built-in binary relational operator is defined with both operands of type `T`, or if an explicit nullable or unboxing conversion exists from `T` to the type of the constant expression. + It is a compile-time error if the expression evaluates to `double.NaN`, `float.NaN`, or a null constant. When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of the constant expression using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the constant expression. From 4dea8187d6196fcf451845774960da77ab369ae5 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 27 Feb 2026 15:49:27 -0500 Subject: [PATCH 13/30] binding vs. precedence in the `is` statement. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index ca67a8c37..bdec355ec 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -611,7 +611,7 @@ When the input value has a type for which a suitable built-in binary relational ### §logical-pattern-new-clause Logical pattern -A *logical_pattern* is used to negate the result of matching a pattern input value ([§11.1](patterns.md#111-general)) or to combine that match result with a pattern using a Boolean operator. +A *logical_pattern* is used to negate the result of a pattern match, or to combine the results of multiple pattern matches using conjunction (`and`) or disjunction (`or`). ```ANTLR logical_pattern @@ -656,7 +656,7 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b > *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* -When a *pattern* is used with `is`, any pattern operators in that *pattern* have higher precedence than their logical operator counterparts. Otherwise, those pattern operators have lower precedence. +When a *pattern* appears on the right-hand-side of `is`, the extent of the pattern is determined by the grammar; as a result, the pattern operators `and`, `or`, and `not` within the pattern bind more tightly than the logical operators `&&`, `||`, and `!` outside the pattern. > *Example*: > From 3de2fb798f116a40ac53e0c6029e2e85bfcfe0e8 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 3 Mar 2026 15:01:53 -0500 Subject: [PATCH 14/30] Add a couple notes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index bdec355ec..b7df67d16 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -724,9 +724,14 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > > > ```csharp +> object msg = "msg"; > object obj = 5; > bool flag = true; > +> // This is parsed as: (msg is (not int) or string) +> result = msg is not int or string; +> Console.WriteLine($"msg (\"msg\"): msg is not int or string: {result}"); +> > // This is parsed as: (obj is (int or string)) && flag > bool result = obj is int or string && flag; > Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); @@ -748,6 +753,7 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > The output produced is > > ```console +> msg ("msg"): msg is not int or string: True > obj (5), flag (true): obj is int or string && flag: True > obj (5), flag (true): obj is int || obj is string && flag: True > obj (5), flag (false): obj is int or string && flag: False @@ -760,7 +766,9 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte ## 11.3 Pattern subsumption In a switch statement ([§13.8.3](statements.md#1383-the-switch-statement)), it is an error if a case’s pattern is *subsumed* by the preceding set of *unguarded* ([§13.8.3](statements.md#1383-the-switch-statement)) cases. In a switch expression ([§12.11](expressions.md#1211-switch-expression)), it is an error if a *switch_expression_arm*’s pattern is *subsumed* by the preceding set of *unguarded* *switch_expression_arm*s’ patterns. + > *Note*: This means that any input value would have been matched by one of the previous cases or arms. *end note* + The following rules define when a set of patterns subsumes a given pattern: A pattern `P` *would match* a constant `K` if any of the following conditions hold: @@ -806,8 +814,7 @@ A set of patterns `Q` *subsumes* a pattern `P` if any of the following condition ## 11.4 Pattern exhaustiveness -Informally, a set of patterns is exhaustive for a type if, for every possible value of that type other than null, some pattern in the set is applicable. -The following rules define when a set of patterns is *exhaustive* for a type: +Informally, a set of patterns is exhaustive for a type if, for every possible value of that type other than null, some pattern in the set is applicable. The following rules define when a set of patterns is *exhaustive* for a type: A set of patterns `Q` is *exhaustive* for a type `T` if any of the following conditions hold: @@ -821,6 +828,9 @@ A set of patterns `Q` is *exhaustive* for a type `T` if any of the following con 1. Some pattern in `Q` is a *negated_pattern* `not P₁`, and the patterns in `Q` together with the values not matched by `P₁` cover every possible value of `T`. A *negated_pattern* `not P₁` is exhaustive by itself when `P₁` matches no possible value of `T`; or 1. Some pattern in `Q` is a *conjunctive_pattern* `P₁ and P₂`, and the set containing only `P₁` is *exhaustive* for `T` and the set containing only `P₂` is *exhaustive* for `T`. +> *Note*: When a type pattern includes nullable types, the pattern may be exhaustive for the type but still generate a warning because the type pattern won't match a `null` value. *end note* + + > *Note*: For floating-point types, the combination of patterns `< 0` and `>= 0` is *not* exhaustive because neither relational pattern matches `NaN`. A correct exhaustive set would be `< 0`, `>= 0`, and `double.NaN` (or `float.NaN`). *end note* > *Example*: @@ -841,3 +851,4 @@ A set of patterns `Q` is *exhaustive* for a type `T` if any of the following con > ``` > > *end example* + From 76cdcc512bea36909fd90dea6814e868528be4c9 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 17 Apr 2026 15:56:26 -0400 Subject: [PATCH 15/30] Fix broken test code. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index b7df67d16..a4e05e2e4 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -729,11 +729,11 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > bool flag = true; > > // This is parsed as: (msg is (not int) or string) -> result = msg is not int or string; +> bool result = msg is not int or string; > Console.WriteLine($"msg (\"msg\"): msg is not int or string: {result}"); > > // This is parsed as: (obj is (int or string)) && flag -> bool result = obj is int or string && flag; +> result = obj is int or string && flag; > Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); > > // This is parsed as: (obj is int) || ((obj is string) && flag) @@ -760,7 +760,6 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > obj (5), flag (false): obj is int || obj is string && flag: True > ``` > -> > *end example* ## 11.3 Pattern subsumption From 840ca4e2e122b6d95b212f37d6923ec6be2b4504 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Fri, 17 Apr 2026 17:08:28 -0400 Subject: [PATCH 16/30] Fix ANTLR grammar validator tests for pattern-matching enhancements Update grammar test infrastructure to match new pattern rule hierarchy: - pattern : logical_pattern (was 6 direct alternatives) - New rules: primary_pattern, parenthesized_pattern, type_pattern, relational_pattern, logical_pattern, disjunctive_pattern, conjunctive_pattern, negated_pattern Changes: - GrammarTestingEnv.tgz: Updated baseline grammar and Rules modification set to handle new pattern hierarchy. TypePatternPredicate now walks up the tree through intermediate pattern nodes to find relational_expression. - Reference tree files: 'is (type' -> 'is (pattern' since ReplacePatternWithType action is no longer needed (type_pattern is now a proper grammar rule). - RightShift stderr: Added 'and', 'not', 'or' to expected token sets (new pattern operator keywords). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- tools/GrammarTesting/SetupAndTest | 329 ++++++++++++++++++ .../part-B/Reference/sample.gruntree.red.txt | 2 +- .../v6/RightShift/Reference/sample.stderr.txt | 2 +- .../Reference/sample.gruntree.red.txt | 8 +- .../Reference/sample.tree.red.txt | 2 +- 5 files changed, 336 insertions(+), 7 deletions(-) create mode 100755 tools/GrammarTesting/SetupAndTest diff --git a/tools/GrammarTesting/SetupAndTest b/tools/GrammarTesting/SetupAndTest new file mode 100755 index 000000000..fe86a25e5 --- /dev/null +++ b/tools/GrammarTesting/SetupAndTest @@ -0,0 +1,329 @@ +#!/bin/bash + +# Setup environment and then do checks, must pass in Standard source directory + +# Where are we? + +ScriptPath=$(realpath "${BASH_SOURCE[0]}") +ScriptDir=$(dirname "$ScriptPath") + +_usageDescription () +{ + cat <&2 + echo 1>&2 + _usageDescription 1>&2 + echo 1>&2 + exit $_optExitCode + else + echo + _usageDescription + echo + fi +} + +# scan all args + +doGrammar=false +doParsing=false +argSourceDirectory= +optWorkingDirectory= +optEnvPath= +optTestPath= + +declare -a doChecksArgs + +requireArgument= + +for i in "$@"; do + if [[ "$requireArgument" == "" ]]; then + case "$i" in + -g|--grammar) + doChecksArgs+=($i) + ;; + -p|--parsing) + doChecksArgs+=($i) + ;; + -d|--demo-parsing) + doChecksArgs+=($i) + ;; + -h|--help|-\?) + usage + exit + ;; + -v|--verbose) + beVerbose=true # so we can take note of this parameter ourselves + doChecksArgs+=($i) + ;; + -q|--quiet) + beQuiet=true # so we can take note of this parameter ourselves + doChecksArgs+=($i) + ;; + -dbg) + doChecksArgs+=($i) + ;; + -wd|--working-directory) + if [[ "$optWorkingDirectory" == "" ]]; then + requireArgument=$i + else + usage "Unexpected option $i" + fi + ;; + -wd=*|--working-directory=*) + if [[ "$optWorkingDirectory" == "" ]]; then + optWorkingDirectory="${i#*=}" + else + usage "Unexpected option $i" + fi + ;; + -e|--environment-directory) + if [[ "$optEnvPath" == "" ]]; then + requireArgument=$i + else + usage "Unexpected option $i" + fi + ;; + -e=*|--environment-directory=*) + if [[ "$optEnvPath" == "" ]]; then + optEnvPath="${i#*=}" + else + usage "Unexpected option $i" + fi + ;; + -t|--tests-directory) + if [[ "$optTestPath" == "" ]]; then + requireArgument=$i + else + usage "Unexpected option $i" + fi + ;; + -t=*|--tests-directory=*) + if [[ "$optTestPath" == "" ]]; then + optTestPath="${i#*=}" + else + usage "Unexpected option $i" + fi + ;; + -*) + usage "Unrecognised option $i" + ;; + *) + if [[ "$argSourceDirectory" == "" ]]; then + argSourceDirectory="$i" + elif [[ "$i" != "" ]]; then + usage "Unexpected argument ‘$i’" + fi + ;; + esac + else # looking for argument after option + if [[ "$i" == -* ]]; then + usage "Option $requireArgument missing argument" + else + case $requireArgument in + -wd|--working-directory) + optWorkingDirectory="$i" + requireArgument="" + ;; + -e|--environment-directory) + optEnvPath="$i" + requireArgument="" + ;; + -t|--tests-directory) + optTestPath="$i" + requireArgument="" + ;; + esac + if [[ "$requireArgument" != "" ]]; then + errorExit "Internal error, argument expected on none argument option, contact developer" + fi + fi + fi +done + +# check last command line option isn’t missing an argument + +if [[ "$requireArgument" != "" ]]; then + usage "Option $requireArgument missing argument" +fi + +if [[ "$argSourceDirectory" == "" ]]; then + usage "Missing sourceDirectory" +fi + +########################################################################################## + +# Args scanned, now locate environment directory. +# Try in order: +# - -e=path argument +# - Is there an Environment folder in the current WD? +# - Is there an Environment folder relative to the script source? +# If all fail barf + +envDirectoryName="Environment" +libRelativePath="Tools/lib/common.bash" +envPath= + +# first locate the environment +# check for script library within the folder as the (minimal) test for validity +if [[ ("$optEnvPath" != "") && (-f "${optEnvPath}/${libRelativePath}") ]]; then + envPath="${optEnvPath}" + envSrc="ARG" +elif [[ -f "${envDirectoryName}/${libRelativePath}" ]]; then + envPath="${envDirectoryName}" + envSrc="CWD" +elif [[ -f "${ScriptDir}/${envDirectoryName}/${libRelativePath}" ]]; then + envPath="${ScriptDir}/${envDirectoryName}" + envSrc="ADJ" +else + echo "Could not locate “${envDirectoryName}” directory" 1>&2 + echo "Consult the documentation" 1>&2 + exit -1 +fi + +envPath=$(realpath "$envPath") + +# Environment located, can now source our common library from the environment +source "${envPath}/${libRelativePath}" + +# we now have debugEcho… +debugEcho "envPath = [$envSrc] ${envPath}" + +########################################################################################## + +# Environment found, common source loaded, now locate the tests directory. +# this does not validate the structure of the tests folder in any way +# Try in order: +# - -t=path argument +# - Is there a Tests folder in the current WD? +# - Is there a Tests folder relative to the script source? +# If all fail barf + +# Much shorter than above as we can now use the common source version + +testPath= +searchForDirectory testPath "$optTestPath" "Tests" "" "" "$ScriptDir" "" + +# pass on to DoChecksAndTests below – avoids DoChecksAndTests needing to search (and possibly failing) +doChecksArgs+=("-t=${testPath}") + +########################################################################################## + +# Final checks and then source/call others to do the work + +# validate source directory and add to args +validateDirectoryPath sourceDirectory "$argSourceDirectory" "Invalid source directory \"$argSourceDirectory\"" -1 +doChecksArgs+=("$sourceDirectory") + +# create working directory if needed and add to command +if [[ "$optWorkingDirectory" != "" ]]; then + validateOrCreateDirectoryPath baseWorkingDirectory "$optWorkingDirectory" "Failed to create/access \"$optWorkingDirectory\"" + doChecksArgs+=("-wd=$baseWorkingDirectory") +fi + +# sanity precheck the environment +if [[ ! -f "${envPath}/setup.SourceMe" ]]; then + errorEcho "File ”setup.SourceMe” is missing in the environment directory." + errorEcho "($envPath)" + errorExit "Cannot setup the environment" +fi + +if [[ ${beVerbose} == true ]]; then + source "${envPath}/setup.SourceMe" +else + echo "Configuring environment..." + source "${envPath}/setup.SourceMe" >/dev/null +fi + +exitStatus=$? +if [[ $exitStatus != 0 ]]; then # did setup succeed? + exit $exitStatus +fi + +# sanity postcheck the environment +for i in antlr grun BuildGrammar; do + which $i >/dev/null + if [[ $? != 0 ]]; then + errorExit "Command “${i}” not found in environment" + fi +done + +for i in f:BG_BASHLIBRARY d:BG_MODIFICATIONSETS f:BG_GRUNTREE_GRAMMAR d:BG_LIB_PARSINGTESTS; do + _kind=${i:0:1} + _var=${i:2} + _target="${!_var}" + debugEcho "Checking: ${_kind} | ${_var}=${_target}" + if [[ "${_target}" == "" ]]; then + errorExit "Variable ${_var} not defined" + elif [[ (${_kind} == d) && (! -d "${_target}") ]]; then + errorExit "${_var} must reference a directory" + elif [[ (${_kind} == f) && (! -f "${_target}") ]]; then + errorExit "${_var} must reference a file" + fi +done + +# we seem to have what we expect, run the tests… + +# use a DoChecksAndTests in testPath +if [[ -x "${testPath}/DoChecksAndTests" ]]; then + "${testPath}/DoChecksAndTests" "${doChecksArgs[@]}" + exit $? +fi + +# check for DoChecksAndTests in the PATH +which DoChecksAndTests >/dev/null +if [[ $? == 0 ]]; then + DoChecksAndTests "${doChecksArgs[@]}" + exit $? +fi + +errorEcho "Script ”DoChecksAndTests” not found in the tests directory or PATH." +errorEcho "Tests directory: $testPath" +errorExit "Cannot run the tests" diff --git a/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-B/Reference/sample.gruntree.red.txt b/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-B/Reference/sample.gruntree.red.txt index c0e20fb6a..6226b8a2b 100644 --- a/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-B/Reference/sample.gruntree.red.txt +++ b/tools/GrammarTesting/Tests/Parsing/Samples/v6/AllInOneNoPreprocessor-v6-split/part-B/Reference/sample.gruntree.red.txt @@ -1213,7 +1213,7 @@ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ is ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ -⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ type +⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ pattern ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ identifier ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ Action diff --git a/tools/GrammarTesting/Tests/Parsing/Samples/v6/RightShift/Reference/sample.stderr.txt b/tools/GrammarTesting/Tests/Parsing/Samples/v6/RightShift/Reference/sample.stderr.txt index ecbe5a574..e4d3028b6 100644 --- a/tools/GrammarTesting/Tests/Parsing/Samples/v6/RightShift/Reference/sample.stderr.txt +++ b/tools/GrammarTesting/Tests/Parsing/Samples/v6/RightShift/Reference/sample.stderr.txt @@ -1,3 +1,3 @@ line 10:12 no viable alternative at input '>' -line 10:14 extraneous input '>' expecting {'_', '-', '--', '!', '..', '(', '&', '^', '+', '++', '~', 'add', 'alias', 'ascending', 'async', 'await', 'base', 'bool', 'by', 'byte', 'char', 'checked', 'decimal', 'delegate', 'descending', 'double', 'dynamic', 'equals', 'float', 'from', 'get', 'global', 'group', 'int', 'into', 'join', 'let', 'long', 'nameof', 'new', 'notnull', 'object', 'on', 'orderby', 'partial', 'remove', 'sbyte', 'select', 'set', 'short', 'sizeof', 'stackalloc', 'static', 'string', 'this', 'typeof', 'uint', 'ulong', 'unchecked', 'unmanaged', 'ushort', 'value', 'var', 'when', 'where', 'yield', 'default', 'null', 'true', 'false', '*', Simple_Identifier, Integer_Literal, Real_Literal, Character_Literal, String_Literal, Interpolated_Regular_String_Start, Interpolated_Verbatim_String_Start} +line 10:14 extraneous input '>' expecting {'_', '-', '--', '!', '..', '(', '&', '^', '+', '++', '~', 'add', 'alias', 'and', 'ascending', 'async', 'await', 'base', 'bool', 'by', 'byte', 'char', 'checked', 'decimal', 'delegate', 'descending', 'double', 'dynamic', 'equals', 'float', 'from', 'get', 'global', 'group', 'int', 'into', 'join', 'let', 'long', 'nameof', 'new', 'not', 'notnull', 'object', 'on', 'or', 'orderby', 'partial', 'remove', 'sbyte', 'select', 'set', 'short', 'sizeof', 'stackalloc', 'static', 'string', 'this', 'typeof', 'uint', 'ulong', 'unchecked', 'unmanaged', 'ushort', 'value', 'var', 'when', 'where', 'yield', 'default', 'null', 'true', 'false', '*', Simple_Identifier, Integer_Literal, Real_Literal, Character_Literal, String_Literal, Interpolated_Regular_String_Start, Interpolated_Verbatim_String_Start} line 11:8 no viable alternative at input '>' diff --git a/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.gruntree.red.txt b/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.gruntree.red.txt index b0f97e8bc..99a360f15 100644 --- a/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.gruntree.red.txt +++ b/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.gruntree.red.txt @@ -482,7 +482,7 @@ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ is ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ -⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ type +⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ pattern ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ namespace_or_type_name ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ @@ -1022,7 +1022,7 @@ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ is ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ -⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ type +⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ pattern ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ namespace_or_type_name ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ @@ -1215,7 +1215,7 @@ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ is ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ -⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ type +⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ pattern ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ namespace_or_type_name ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ @@ -1349,7 +1349,7 @@ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ is ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ -⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ type +⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ pattern ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ namespace_or_type_name ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎛ diff --git a/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.tree.red.txt b/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.tree.red.txt index d86cb4033..6bcb6219b 100644 --- a/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.tree.red.txt +++ b/tools/GrammarTesting/Tests/Parsing/Samples/v8/Type argument list/Reference/sample.tree.red.txt @@ -1 +1 @@ -(prog (compilation_unit (class_declaration class (identifier TypeArgumentListChecks) (class_body { (class_member_declaration (method_declaration method_modifiers (return_type void) (method_header (member_name (identifier TypeArgumentListChecks)) ( )) (method_body (block { (statement_list (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (invocation_expression (primary_expression (simple_name (identifier G) (type_argument_list < (type_argument (identifier A)) , (type_argument (identifier B)) >))) ( (argument_list (literal 7)) ))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (invocation_expression (primary_expression (base_access base . (identifier G) (type_argument_list < (type_argument (identifier A)) , (type_argument (identifier B)) >))) ( (argument_list (literal 7)) ))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (identifier G)) < (shift_expression (identifier A)))) , (argument (relational_expression (relational_expression (identifier B)) > (shift_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (base_access base . (identifier G))) < (shift_expression (identifier A)))) , (argument (relational_expression (relational_expression (identifier B)) > (shift_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (identifier G)) < (shift_expression (identifier A)))) , (argument (shift_expression (shift_expression (identifier B)) (right_shift > >) (additive_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (simple_assignment (unary_expression (identifier x)) = (expression (relational_expression (relational_expression (relational_expression (identifier F)) < (shift_expression (identifier A))) > (shift_expression (unary_expression + (unary_expression (identifier y)))))))) ;)) (statement (expression_statement (statement_expression (simple_assignment (unary_expression (identifier x)) = (expression (conditional_and_expression (conditional_and_expression (relational_expression (relational_expression (identifier y)) is (type (namespace_or_type_name (identifier C) (type_argument_list < (type_argument (identifier T)) >))))) && (inclusive_or_expression (identifier z)))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (identifier C)) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) , (tuple_element (identifier E)) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (invocation_expression (primary_expression (identifier M)) ( (argument_list (argument (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (argument (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) , (argument (identifier E))) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (invocation_expression (primary_expression (identifier M)) ( (argument_list (argument (argument_value out (declaration_expression (local_variable_type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) , (type_argument (identifier C)) >))) (identifier D)))) , (argument (identifier E))) )))))) ;)) (statement (if_statement if ( (boolean_expression (relational_expression (relational_expression (identifier e)) is (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (identifier C)))))) ) (embedded_statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier W)) ( (argument_list (identifier C)) ))) ;)))) (statement (if_statement if ( (boolean_expression (relational_expression (relational_expression (identifier e)) is (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))))) ) (embedded_statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier W)) ( (argument_list (identifier C)) ))) ;)))) (statement (switch_statement switch (selector_expression ( (expression (identifier x)) )) (switch_block { (switch_section (switch_label case (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (identifier C)))) :) (statement_list (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier z) = (expression (identifier C))))) ;)) (statement (break_statement break ;)))) }))) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier p) = (expression (relational_expression (relational_expression (relational_expression (identifier x)) is (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >)))) > (shift_expression (identifier C))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier q) = (expression (relational_expression (relational_expression (identifier A)) < (shift_expression (shift_expression (identifier B)) (right_shift > >) (additive_expression (identifier C)))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier r) = (expression (relational_expression (relational_expression (parenthesized_expression ( (expression (relational_expression (relational_expression (identifier x)) is (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))))) ))) > (shift_expression (identifier C))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier s) = (expression (relational_expression (relational_expression (identifier x)) is (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (contextual_keyword orderby))))))))) ;))) })))) })))) +(prog (compilation_unit (class_declaration class (identifier TypeArgumentListChecks) (class_body { (class_member_declaration (method_declaration method_modifiers (return_type void) (method_header (member_name (identifier TypeArgumentListChecks)) ( )) (method_body (block { (statement_list (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (invocation_expression (primary_expression (simple_name (identifier G) (type_argument_list < (type_argument (identifier A)) , (type_argument (identifier B)) >))) ( (argument_list (literal 7)) ))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (invocation_expression (primary_expression (base_access base . (identifier G) (type_argument_list < (type_argument (identifier A)) , (type_argument (identifier B)) >))) ( (argument_list (literal 7)) ))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (identifier G)) < (shift_expression (identifier A)))) , (argument (relational_expression (relational_expression (identifier B)) > (shift_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (base_access base . (identifier G))) < (shift_expression (identifier A)))) , (argument (relational_expression (relational_expression (identifier B)) > (shift_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier F)) ( (argument_list (argument (relational_expression (relational_expression (identifier G)) < (shift_expression (identifier A)))) , (argument (shift_expression (shift_expression (identifier B)) (right_shift > >) (additive_expression (literal 7))))) ))) ;)) (statement (expression_statement (statement_expression (simple_assignment (unary_expression (identifier x)) = (expression (relational_expression (relational_expression (relational_expression (identifier F)) < (shift_expression (identifier A))) > (shift_expression (unary_expression + (unary_expression (identifier y)))))))) ;)) (statement (expression_statement (statement_expression (simple_assignment (unary_expression (identifier x)) = (expression (conditional_and_expression (conditional_and_expression (relational_expression (relational_expression (identifier y)) is (pattern (namespace_or_type_name (identifier C) (type_argument_list < (type_argument (identifier T)) >))))) && (inclusive_or_expression (identifier z)))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (identifier C)) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (tuple_literal ( (tuple_element (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (tuple_element (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) , (tuple_element (identifier E)) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (invocation_expression (primary_expression (identifier M)) ( (argument_list (argument (relational_expression (relational_expression (identifier A)) < (shift_expression (identifier B)))) , (argument (relational_expression (relational_expression (identifier C)) > (shift_expression (identifier D)))) , (argument (identifier E))) )))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier v) = (expression (invocation_expression (primary_expression (identifier M)) ( (argument_list (argument (argument_value out (declaration_expression (local_variable_type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) , (type_argument (identifier C)) >))) (identifier D)))) , (argument (identifier E))) )))))) ;)) (statement (if_statement if ( (boolean_expression (relational_expression (relational_expression (identifier e)) is (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (identifier C)))))) ) (embedded_statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier W)) ( (argument_list (identifier C)) ))) ;)))) (statement (if_statement if ( (boolean_expression (relational_expression (relational_expression (identifier e)) is (pattern (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))))) ) (embedded_statement (expression_statement (statement_expression (invocation_expression (primary_expression (identifier W)) ( (argument_list (identifier C)) ))) ;)))) (statement (switch_statement switch (selector_expression ( (expression (identifier x)) )) (switch_block { (switch_section (switch_label case (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (identifier C)))) :) (statement_list (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier z) = (expression (identifier C))))) ;)) (statement (break_statement break ;)))) }))) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier p) = (expression (relational_expression (relational_expression (relational_expression (identifier x)) is (pattern (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >)))) > (shift_expression (identifier C))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier q) = (expression (relational_expression (relational_expression (identifier A)) < (shift_expression (shift_expression (identifier B)) (right_shift > >) (additive_expression (identifier C)))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier r) = (expression (relational_expression (relational_expression (parenthesized_expression ( (expression (relational_expression (relational_expression (identifier x)) is (pattern (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))))) ))) > (shift_expression (identifier C))))))) ;)) (statement (declaration_statement (local_variable_declaration (implicitly_typed_local_variable_declaration var (implicitly_typed_local_variable_declarator (identifier s) = (expression (relational_expression (relational_expression (identifier x)) is (pattern (declaration_pattern (type (namespace_or_type_name (identifier A) (type_argument_list < (type_argument (identifier B)) >))) (simple_designation (contextual_keyword orderby))))))))) ;))) })))) })))) From ce598db9ab178c8176c020b6a76cdf85226d1080 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 13 Oct 2026 14:55:51 -0400 Subject: [PATCH 17/30] Remove pattern-enhancement source trailing whitespace Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 10 +++++----- tools/GrammarTesting/SetupAndTest | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index a4e05e2e4..92ce0735b 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -727,7 +727,7 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > object msg = "msg"; > object obj = 5; > bool flag = true; -> +> > // This is parsed as: (msg is (not int) or string) > bool result = msg is not int or string; > Console.WriteLine($"msg (\"msg\"): msg is not int or string: {result}"); @@ -735,16 +735,16 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > // This is parsed as: (obj is (int or string)) && flag > result = obj is int or string && flag; > Console.WriteLine($"obj (5), flag (true): obj is int or string && flag: {result}"); -> +> > // This is parsed as: (obj is int) || ((obj is string) && flag) > result = obj is int || obj is string && flag; > Console.WriteLine($"obj (5), flag (true): obj is int || obj is string && flag: {result}"); -> +> > flag = false; > // This is parsed as: (obj is (int or string)) && flag > result = obj is int or string && flag; > Console.WriteLine($"obj (5), flag (false): obj is int or string && flag: {result}"); -> +> > // This is parsed as: (obj is int) || ((obj is string) && flag) > result = obj is int || obj is string && flag; > Console.WriteLine($"obj (5), flag (false): obj is int || obj is string && flag: {result}"); @@ -843,7 +843,7 @@ A set of patterns `Q` is *exhaustive* for a type `T` if any of the following con > break; > // error: the pattern 'byte other' is subsumed by the (exhaustive) > // previous cases -> case byte other: +> case byte other: > break; > } > } diff --git a/tools/GrammarTesting/SetupAndTest b/tools/GrammarTesting/SetupAndTest index fe86a25e5..ce880bafc 100755 --- a/tools/GrammarTesting/SetupAndTest +++ b/tools/GrammarTesting/SetupAndTest @@ -25,7 +25,7 @@ Options: -p, --parsing Perform parsing tests -d, --demo-parsing - Perform demo parsing tests + Perform demo parsing tests -h, -?, --help Displays this help and exits -v, --verbose @@ -55,7 +55,7 @@ usage() # [optErrorMsg [optExitCode]] # name the parameters local _optErrorMsg="$1" local _optExitCode="${2:--1}" # default to -1 - + # if optErrorMsg exists send all output to stderr if [ "$_optErrorMsg" != "" ]; then echo "Error: $_optErrorMsg" 1>&2 @@ -184,7 +184,7 @@ for i in "$@"; do if [[ "$requireArgument" != "" ]]; then errorExit "Internal error, argument expected on none argument option, contact developer" fi - fi + fi fi done @@ -203,7 +203,7 @@ fi # Args scanned, now locate environment directory. # Try in order: # - -e=path argument -# - Is there an Environment folder in the current WD? +# - Is there an Environment folder in the current WD? # - Is there an Environment folder relative to the script source? # If all fail barf @@ -242,7 +242,7 @@ debugEcho "envPath = [$envSrc] ${envPath}" # this does not validate the structure of the tests folder in any way # Try in order: # - -t=path argument -# - Is there a Tests folder in the current WD? +# - Is there a Tests folder in the current WD? # - Is there a Tests folder relative to the script source? # If all fail barf From 858d6e72bd53edaea2f3d9b93cdcf4f987803ac0 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 13 Oct 2026 17:22:13 -0400 Subject: [PATCH 18/30] Restore approved #1691 subsumption and exhaustiveness precedence Independent Hendrix revision: discard retired sections resurrected by the #1460 rebase. Retain approved definitions in 11.1 and C# 9 pattern forms in 11.2. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 21570b74-c6f5-4fc5-ab6d-7546918d6ddb Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 361b9a77-2b4c-45e6-969f-e6785c47f27e --- standard/patterns.md | 90 -------------------------------------------- 1 file changed, 90 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 92ce0735b..05fe6ec14 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -761,93 +761,3 @@ When a *pattern* appears on the right-hand-side of `is`, the extent of the patte > ``` > > *end example* - -## 11.3 Pattern subsumption - -In a switch statement ([§13.8.3](statements.md#1383-the-switch-statement)), it is an error if a case’s pattern is *subsumed* by the preceding set of *unguarded* ([§13.8.3](statements.md#1383-the-switch-statement)) cases. In a switch expression ([§12.11](expressions.md#1211-switch-expression)), it is an error if a *switch_expression_arm*’s pattern is *subsumed* by the preceding set of *unguarded* *switch_expression_arm*s’ patterns. - -> *Note*: This means that any input value would have been matched by one of the previous cases or arms. *end note* - -The following rules define when a set of patterns subsumes a given pattern: - -A pattern `P` *would match* a constant `K` if any of the following conditions hold: - -- the specification for that pattern's runtime behavior is that `P` matches `K`. -- `P` is a *type_pattern* for type `T` and `K` is not `null` and the runtime type of `K` is `T` or a type derived from `T` or a type that implements `T`. -- `P` is a *relational_pattern* with operator «op» and constant `v`, and the expression `K` «op» `v` would evaluate to `true`. -- `P` is a *negated_pattern* `not P₁` and `P₁` would not match `K`. -- `P` is a *conjunctive_pattern* `P₁ and P₂` and both `P₁` would match `K` and `P₂` would match `K`. -- `P` is a *disjunctive_pattern* `P₁ or P₂` and either `P₁` would match `K` or `P₂` would match `K`. -- `P` is a *discard_pattern*. - -A set of patterns `Q` *subsumes* a pattern `P` if any of the following conditions hold: - -- `P` is a constant pattern and any of the patterns in the set `Q` would match `P`'s *converted value* -- `P` is a var pattern and the set of patterns `Q` is *exhaustive* ([§11.4](patterns.md#114-pattern-exhaustiveness)) for the type of the pattern input value ([§11.1](patterns.md#111-general)), and either the pattern input value is not of a nullable type or some pattern in `Q` would match `null`. -- `P` is a declaration pattern with type `T` and the set of patterns `Q` is *exhaustive* for the type `T` ([§11.4](patterns.md#114-pattern-exhaustiveness)). -- `P` is a *type_pattern* for type `T` and the set of patterns `Q` is *exhaustive* for the type `T`. -- `P` is a *relational_pattern* with operator «op» and constant value `v`, and for every value of the input type satisfying the relation «op» `v`, some pattern in the set `Q` would match that value. -- `P` is a *disjunctive_pattern* `P₁ or P₂` and the set of patterns `Q` subsumes `P₁` and `Q` subsumes `P₂`. -- `P` is a *conjunctive_pattern* `P₁ and P₂` and at least one of the following holds: `Q` subsumes `P₁`, or `Q` subsumes `P₂`. -- `P` is a *negated_pattern* `not P₁` and `Q` is *exhaustive* for the input type considering only the values not matched by `P₁`. -- `P` is a *discard_pattern* and the set of patterns `Q` is *exhaustive* for the type of the pattern input value, and either the pattern input value is not of a nullable type or some pattern in `Q` would match `null`. -- Some pattern in `Q` is a *disjunctive_pattern* `Q₁ or Q₂` and replacing that pattern with `Q₁` in `Q` would yield a set that subsumes `P`, or replacing it with `Q₂` would yield a set that subsumes `P`. -- Some pattern in `Q` is a *negated_pattern* `not Q₁` and `P` would not match any value that `Q₁` would match. - -> *Example*: In the following switch expression, no arm is subsumed even though arms 1, 2, and 3 share the same pattern: -> -> -> ```csharp -> object x = 10; -> bool b = false; -> int y = x switch -> { -> int i when !b => 0, -> int i when b => 1, -> int i => 2, -> _ => 3 -> }; -> ``` -> -> Arms 1 and 2 have non-constant guards and so are not *unguarded*; only arm 3 is *unguarded* with pattern `int i`, which does not subsume the final `_` arm because it does not match a non-`int` value such as `null`. *end example* - -## 11.4 Pattern exhaustiveness - -Informally, a set of patterns is exhaustive for a type if, for every possible value of that type other than null, some pattern in the set is applicable. The following rules define when a set of patterns is *exhaustive* for a type: - -A set of patterns `Q` is *exhaustive* for a type `T` if any of the following conditions hold: - -1. `T` is an integral or enum type, or a nullable version of one of those, and for every possible value of `T`’s non-nullable underlying type, some pattern in `Q` would match that value; or -1. Some pattern in `Q` is a *var pattern*; or -1. Some pattern in `Q` is a *declaration pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`; or -1. Some pattern in `Q` is a *type_pattern* for type `D`, and there is an identity conversion, an implicit reference conversion, or a boxing conversion from `T` to `D`; or -1. Some pattern in `Q` is a *discard_pattern*; or -1. The patterns in `Q` include a combination of *relational_pattern*s and *constant_pattern*s whose ranges collectively cover every possible value of `T`'s non-nullable underlying type. For `float` and `double` types, this includes `System.Double.NaN` or `System.Single.NaN` respectively, since `NaN` is not matched by any relational pattern; or -1. Some pattern in `Q` is a *disjunctive_pattern* `P₁ or P₂`, and replacing that pattern with both `P₁` and `P₂` in `Q` yields a set that is *exhaustive* for `T`; or -1. Some pattern in `Q` is a *negated_pattern* `not P₁`, and the patterns in `Q` together with the values not matched by `P₁` cover every possible value of `T`. A *negated_pattern* `not P₁` is exhaustive by itself when `P₁` matches no possible value of `T`; or -1. Some pattern in `Q` is a *conjunctive_pattern* `P₁ and P₂`, and the set containing only `P₁` is *exhaustive* for `T` and the set containing only `P₂` is *exhaustive* for `T`. - -> *Note*: When a type pattern includes nullable types, the pattern may be exhaustive for the type but still generate a warning because the type pattern won't match a `null` value. *end note* - - -> *Note*: For floating-point types, the combination of patterns `< 0` and `>= 0` is *not* exhaustive because neither relational pattern matches `NaN`. A correct exhaustive set would be `< 0`, `>= 0`, and `double.NaN` (or `float.NaN`). *end note* - -> *Example*: -> -> -> ```csharp -> static void M(byte b) -> { -> switch (b) { -> case 0: case 1: case 2: ... // handle every specific value of byte -> break; -> // error: the pattern 'byte other' is subsumed by the (exhaustive) -> // previous cases -> case byte other: -> break; -> } -> } -> ``` -> -> *end example* - From 7814bcfdf858017b06fd83e3196e405eaff4194a Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 15:23:02 -0500 Subject: [PATCH 19/30] patterns and def. assignment - *standard\patterns.md*: permits leading is not declarations, including parentheses and repeated negation. Preserves restrictions on declarations under or and on nested/switch-context negations. - *standard\variables.md*: defines definite assignment for matching and non-matching outcomes, including negation and composition. - *standard\expressions.md*: references those authoritative rules instead of incorrectly asserting assignment only when true. Added three focused annotated examples --- standard/expressions.md | 2 +- standard/patterns.md | 65 +++++++++++++++++++++++++++++++++++++++-- standard/variables.md | 34 ++++++++++++++++++++- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/standard/expressions.md b/standard/expressions.md index b2bb62d71..d89a8a10b 100644 --- a/standard/expressions.md +++ b/standard/expressions.md @@ -4852,7 +4852,7 @@ For an expression of the form `E is P`, where `E` is a relational expression of - `E` does not designate a value or does not have a type. - The pattern `P` is not applicable ([§11.2](patterns.md#112-pattern-forms)) to the type `T`. -Every *single_variable_designation* of the pattern introduces a new local variable that is *definitely assigned* ([§9.4](variables.md#94-definite-assignment)) when the corresponding *relational_expression* tests `true` ([§9.4.4.34](variables.md#94434-is-pattern-expressions)). +Every *single_variable_designation* of the pattern introduces a new local variable. Its definite-assignment state is determined as specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). ### 12.14.13 The as operator diff --git a/standard/patterns.md b/standard/patterns.md index 05fe6ec14..d8832903f 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -638,9 +638,70 @@ negated_pattern A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. -It is a compile-time error for a pattern variable to be declared beneath a `not` or `or` pattern operator. +A declaration of a pattern variable shall satisfy both of the following conditions: -> *Note*: Because neither `not` nor `or` can produce a definite assignment for a pattern variable, it is an error to declare one in those positions. *end note* +- The declaration is not enclosed in a *disjunctive_pattern* of the form `P or Q`. +- Each *negated_pattern* of the form `not P` that encloses the declaration is either the entire pattern of an is-pattern expression ([§12.14.12.2](expressions.md#1214122-the-is-pattern-operator)), or is nested within that pattern through only parenthesized patterns and other negated patterns. + +The definite-assignment effects of patterns are specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). + +> *Example*: A variable declared within a negated pattern can be definitely assigned when the pattern does not match. Parentheses and repeated negation are also permitted: +> +> +> ```csharp +> PrintIfInt(42); +> PrintIfInt("other"); +> +> static void PrintIfInt(object value) +> { +> if (value is not (int number)) +> { +> return; +> } +> Console.WriteLine(number); +> +> if (value is (not not int repeated) && repeated > 0) +> { +> Console.WriteLine(repeated); +> } +> +> if (value is not (int positive and > 0) || positive > 100) +> { +> return; +> } +> Console.WriteLine(positive); +> } +> ``` +> +> The output produced is: +> +> ```console +> 42 +> 42 +> 42 +> ``` +> +> *end example* + + + +> *Example*: Declarations within disjunctions, within a negation nested beneath a conjunction, and within a negation in a switch expression are rejected: +> +> +> ```csharp +> class C +> { +> static bool Disjunction(object value) => value is int number or string; +> static bool NestedNegation(object value) => value is {} and not int number; +> static int SwitchNegation(object value) => value switch +> { +> not int number => 0, +> _ => 1, +> }; +> } +> ``` +> +> *end example* In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed by the *type narrowing* requirements of first pattern of the `and`. The *narrowed type* of a pattern `P` is defined as follows: diff --git a/standard/variables.md b/standard/variables.md index ce3cab2e1..c0455033f 100644 --- a/standard/variables.md +++ b/standard/variables.md @@ -999,9 +999,41 @@ For an expression *expr* of the form: *expr_operand* is *pattern* - The definite-assignment state of *v* before *expr_operand* is the same as the definite-assignment state of *v* before *expr*. -- If the variable ‘v’ is declared in *pattern*, then the definite-assignment state of ‘v’ after *expr* is “definitely assigned when true”. +- If *v* is declared in *pattern*, its definite-assignment state after *expr* is determined by the sets of variables definitely assigned when *pattern* matches and when it does not match, as defined below. It is definitely assigned when *expr* evaluates to `true` if and only if it belongs to the former set, and when *expr* evaluates to `false` if and only if it belongs to the latter set. - Otherwise the definite assignment state of ‘v’ after *expr* is the same as the definite assignment state of ‘v’ after *expr_operand*. +For each pattern, the sets of variables definitely assigned when it matches and when it does not match contain only variables declared within that pattern. The sets are determined recursively as follows: + +- A parenthesized pattern has the same sets as its enclosed pattern. +- For a negated pattern `not P`, the set for a match is the set for a non-match of `P`, and the set for a non-match is the set for a match of `P`. +- For a conjunctive pattern `P and Q`, the set for a match is the union of the sets for a match of its operands, and the set for a non-match is the intersection of the sets for a non-match of its operands. +- For a disjunctive pattern `P or Q`, the set for a match is the intersection of the sets for a match of its operands, and the set for a non-match is the union of the sets for a non-match of its operands. +- For a declaration pattern, var pattern, positional pattern, or property pattern, the set for a match contains all variables declared within the pattern, and the set for a non-match is empty. +- For any other pattern, both sets are empty. + +The restrictions on where pattern variables may be declared are specified in [§11.2](patterns.md#112-pattern-forms). + +> *Example*: A variable declared under one negation is not definitely assigned when the is-pattern expression is `true`. Under two negations, it is not definitely assigned when that expression is `false`: +> +> +> ```csharp +> object value = 42; +> if (value is not int number) +> { +> Console.WriteLine(number); // Error: number is not definitely assigned +> } +> +> if (value is not not int repeated) +> { +> } +> else +> { +> Console.WriteLine(repeated); // Error: repeated is not definitely assigned +> } +> ``` +> +> *end example* + ## 9.5 Variable references A *variable_reference* is an *expression* that is classified as a variable. A *variable_reference* denotes a storage location that can be accessed both to fetch the current value and to store a new value. From 651beca15c1788a6f98c40c3505147bae8089920 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 15:41:38 -0500 Subject: [PATCH 20/30] Parenthesized-pattern semantics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Specified that parentheses preserve the enclosed pattern’s input type, applicability, matching behavior, and narrowed type. - Added an explicit parenthesized-pattern case before the narrowing fallback. - Referenced F01’s definite-assignment rules without duplicating them. - Added two annotated examples covering narrowing, matching, and invalid applicability. --- standard/patterns.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/standard/patterns.md b/standard/patterns.md index d8832903f..d4f4fdeee 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -47,12 +47,38 @@ parenthesized_pattern ; ``` +For a *parenthesized_pattern* `(P)`, the *input type* of `P` is the input type of the parenthesized pattern. The parenthesized pattern is applicable to a type if and only if `P` is applicable to that type, matches a value if and only if `P` matches that value, and has the same *narrowed type* as `P`. Its definite-assignment effects are specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). + If the input can be syntactically recognised as both a *constant_pattern* and a *positional_pattern* then the *constant_pattern* shall be chosen. > *Note*: ANTLR makes the specified choice automatically due to the ordering of *constant_pattern* before *positional_pattern* in the alternatives of *pattern*. *end note* The `'(' pattern ')'` production allows a pattern to be enclosed in parentheses to enforce the order of evaluation among patterns combined using one of the *logical_pattern*s. +> *Example*: A parenthesized pattern preserves narrowing to the right-hand pattern of a conjunction. In the following example, `text` has type `string`, so its `Length` property can be accessed: +> +> +> ```csharp +> object value = "abc"; +> Console.WriteLine(value is (string) and { Length: 3 }); +> if (value is ((string)) and var text) +> { +> Console.WriteLine(text.Length); +> } +> value = 42; +> Console.WriteLine(value is (string)); +> ``` +> +> The output produced is: +> +> ```console +> True +> 3 +> False +> ``` +> +> *end example* + Some *pattern*s can result in the declaration of a local variable. Each pattern form defines the set of types for input values that the pattern may be applied to. A pattern `P` is *applicable to* a type `T` if `T` is among the types whose values the pattern may match. It is a compile-time error if a pattern `P` appears in a program to match a pattern input value ([§11.1](patterns.md#111-general)) of type `T` if `P` is not applicable to `T`. @@ -713,6 +739,7 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b - Otherwise, if `P` is a relational pattern where the constant expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. - Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). - Otherwise, if `P` is an `and` pattern, the *narrowed type* is the *narrowed type* of the right pattern. Moreover, the *narrowed type* of the left pattern is the *input type* of the right pattern. +- Otherwise, if `P` is a parenthesized pattern, its *narrowed type* is determined as specified in [§11.2.1](patterns.md#1121-general). - Otherwise the *narrowed type* of `P` is `P`'s input type. > *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* From 6fdc99e61273350ec47c4045fd08a3e7a274348d Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 16:23:48 -0500 Subject: [PATCH 21/30] Relational-pattern comparison and conversions - Defined how the input type and constant determine the comparison type and converted constant. - Specified applicability, required conversions, and runtime type testing before comparison. - Preserved nullable, boxed, enum, native-integer, and generic cases. - Distinguished invalid constant conversions from runtime non-matches. - Added examples showing why ordinary binary numeric promotion does not determine relational-pattern applicability. --- standard/patterns.md | 73 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 5 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index d4f4fdeee..4f300b32d 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -598,15 +598,78 @@ relational_pattern ; ``` -The *relational_expression* in a *relational_pattern* is required to evaluate to a constant value. +The *relational_expression* `E` in a *relational_pattern* is used to determine a converted constant value and a comparison type. A *default_literal* is not permitted as `E`, ignoring enclosing parentheses and null-forgiving operators. -Relational patterns support the relational operators `<`, `<=`, `>`, and `>=` on all of the built-in types that support such binary relational operators with both operands having the same type: `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, and enums. +For an input type `T`, determine an expression `R` as follows. For these rules, parentheses are ignored and user-defined conversions are not considered. -A *relational_pattern* is *applicable to* a type `T` if a suitable built-in binary relational operator is defined with both operands of type `T`, or if an explicit nullable or unboxing conversion exists from `T` to the type of the constant expression. +- If `T` is an open type ([§8.4.3](types.md#843-open-and-closed-types)), `R` is `E`, without a conversion to `T`. +- Otherwise, implicitly convert `E` to `T` as if it were the right operand of a simple assignment to a variable of type `T` ([§12.23.2](expressions.md#12232-simple-assignment)), and let `A` be the resulting expression. An implicit identity conversion between identical types leaves `E` unchanged. + - If `T` is a nullable value type with underlying type `U`, and `A` is the result of an identity, enumeration, or nullable value type conversion and is not a null constant, `R` is the operand of that conversion converted to `U` by a standard conversion ([§10.4](conversions.md#104-standard-conversions)). + - Otherwise, if `A` is the result of a boxing conversion ([§10.2.9](conversions.md#1029-boxing-conversions)) or an implicit reference conversion ([§10.2.8](conversions.md#1028-implicit-reference-conversions)), its operand has a constant value, and `A` does not have a constant value, `R` is that operand. + - Otherwise, `R` is `A`. -It is a compile-time error if the expression evaluates to `double.NaN`, `float.NaN`, or a null constant. +The ***comparison type*** `C` is the type of `R`, and the converted constant value `v` is the constant value of `R`. -When the input value has a type for which a suitable built-in binary relational operator is defined, the evaluation of that operator is taken as the meaning of the relational pattern. Otherwise, the input value is converted to the type of the constant expression using an explicit nullable or unboxing conversion. It is a compile-time error if no such conversion exists. The pattern is considered to not match if the conversion fails. If the conversion succeeds, the result of the pattern-matching operation is the result of evaluating the expression `e «op» v` where `e` is the converted input, «op» is the relational operator, and `v` is the constant expression. +A *relational_pattern* is *applicable to* its input type `T` if all of the following conditions hold: + +- The conversions required above exist, and `R` has a type and a constant value. +- `C` is one of `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `char`, `float`, `double`, `decimal`, `nint`, `nuint`, or an enum type. +- `T` is pattern compatible with `C` ([§11.2.3](patterns.md#1123-declaration-pattern)) and is neither an open class type nor an open ref struct type ([§16.2.3](structs.md#1623-ref-modifier)). +- If `T` is an enum type, `C` is an enum type. +- If an explicit nullable conversion ([§10.3.4](conversions.md#1034-explicit-nullable-conversions)) exists from `T` to `C`, the underlying type of `T` is identity convertible with `C`. + +It is a compile-time error if `v` is `double.NaN`, `float.NaN`, or `null`. + +At runtime, the input value is tested against `C` using the rules of the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test fails, including when the input is `null`, the pattern does not match. Otherwise, let `e` be the input value, unwrapped or unboxed as necessary to obtain a value of type `C`. The pattern matches if the predefined comparison `e «op» v` evaluates to `true`, where «op» is the relational operator of the pattern. The comparison uses the predefined numeric or enumeration comparison operators ([§12.14](expressions.md#1214-relational-and-type-testing-operators)), including binary numeric promotion ([§12.4.7.3](expressions.md#12473-binary-numeric-promotions)) where required. + +> *Example*: The constant is converted before comparing values of the comparison type. This differs from selecting a binary operator for the original input and constant types: +> +> +> ```csharp +> int integer = 1; +> Console.WriteLine(integer < 2L); +> double number = 1; +> Console.WriteLine(number is < 2); +> int? optional = 1; +> Console.WriteLine(optional is < 2); +> optional = null; +> Console.WriteLine(optional is < 2); +> object boxed = (short)1; +> Console.WriteLine(boxed is < 3); +> Console.WriteLine(boxed is not < 3); +> Console.WriteLine(boxed is >= 3); +> ``` +> +> The output produced is: +> +> ```console +> True +> True +> True +> False +> False +> True +> False +> ``` +> +> The boxed `short` does not pass the type test for the comparison type `int`. Negating that failed match produces `true`; using `>=` instead still requires the type test and produces `false`. +> +> In contrast, the following relational patterns generate compile-time errors because their constants cannot be implicitly converted to the comparison types `int`, `byte`, and `float`, respectively: +> +> +> ```csharp +> int integer = 1; +> Console.WriteLine(integer is < 2L); +> byte small = 1; +> Console.WriteLine(small is < 300); +> float single = 1; +> Console.WriteLine(single is < 2D); +> ``` +> +> *end example* + + + > *Example*: > From 63b8f1c47c993c00322afe8555496c2d810cb97f Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 16:45:38 -0500 Subject: [PATCH 22/30] Constant and relational-pattern narrowing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Relational patterns now narrow to F03’s comparison type. - Non-null constant patterns reuse F03’s conversion steps, preserving numeric conversions, nullable unwrapping, and pre-boxing types. - Added an example demonstrating `double` narrowing for numeric conversions and `int` narrowing for a boxed integer. --- standard/patterns.md | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 4f300b32d..19a13da7e 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -798,13 +798,47 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b - Otherwise, if `P` is a declaration pattern, the *narrowed type* is the type of the declaration pattern's type. - Otherwise, if `P` is a recursive pattern that gives an explicit type, the *narrowed type* is that type. - Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.ITuple`. -- Otherwise, if `P` is a constant pattern where the constant is not the null constant and where the expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. -- Otherwise, if `P` is a relational pattern where the constant expression has no *constant expression conversion* to the *input type*, the *narrowed type* is the type of the constant. +- Otherwise, if `P` is a constant pattern where the constant is not the null constant, the *narrowed type* is the type of expression `R` obtained using the expression-conversion steps in [Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern), with the constant pattern's expression as `E` and its input type as `T`. Only the steps determining `R` are used here. +- Otherwise, if `P` is a relational pattern, the *narrowed type* is its comparison type ([Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern)). - Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). - Otherwise, if `P` is an `and` pattern, the *narrowed type* is the *narrowed type* of the right pattern. Moreover, the *narrowed type* of the left pattern is the *input type* of the right pattern. - Otherwise, if `P` is a parenthesized pattern, its *narrowed type* is determined as specified in [§11.2.1](patterns.md#1121-general). - Otherwise the *narrowed type* of `P` is `P`'s input type. +> *Example*: Narrowing accounts for numeric conversion of a constant and retains its type before boxing. The generic method below prints the inferred type of its argument, rather than its runtime type: +> +> +> ```csharp +> double number = 1; +> if (number is 1 and var constant) +> { +> PrintType(constant); +> } +> if (number is < 2 and var relational) +> { +> PrintType(relational); +> } +> object boxed = 1; +> if (boxed is 1 and var unboxed) +> { +> PrintType(unboxed); +> } +> +> static void PrintType(T value) => Console.WriteLine(typeof(T)); +> ``` +> +> The output produced is: +> +> ```console +> System.Double +> System.Double +> System.Int32 +> ``` +> +> *end example* + + + > *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* When a *pattern* appears on the right-hand-side of `is`, the extent of the pattern is determined by the grammar; as a result, the pattern operators `and`, `or`, and `not` within the pattern bind more tightly than the logical operators `&&`, `||`, and `!` outside the pattern. From 3bffcacda8de2241e639b7edf7dc67e219daccb6 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 17:07:10 -0500 Subject: [PATCH 23/30] Pattern recognition and outer capture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Corrected `(int, int) x` to a positional pattern containing type subpatterns and an outer designation. - Added recognition rules distinguishing tuple-looking, parenthesized, constant, and declaration patterns. - Preserved named tuple types, eligible aliases, tuple arrays, nested generic tuple types, and legacy `is` behavior. - Specified that outer captures retain the input or explicit pattern type, preserve tuple names, unwrap nullable inputs, and receive the matched value—not a reconstructed tuple. - Added two annotated examples. --- standard/expressions.md | 2 +- standard/patterns.md | 77 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 72 insertions(+), 7 deletions(-) diff --git a/standard/expressions.md b/standard/expressions.md index d89a8a10b..b89a19355 100644 --- a/standard/expressions.md +++ b/standard/expressions.md @@ -4430,7 +4430,7 @@ right thing, maybe not obviously for some, and so no change was made – making as it does not effect the resulting parse at all, but the prose gets messier. For C#9 this decision should be checked to be still valid after the new pattern changes. --> -When recognising a *relational_expression* ([§12.14.1](expressions.md#12141-general)) if both the “*relational_expression* `is` *type*” and “*relational_expression* `is` *constant_pattern*” alternatives are applicable, and *type* resolves to an accessible type, then the “*relational_expression* `is` *type*” alternative shall be chosen. +The recognition of the *type* following `is` is subject to the type-recognition restriction in [§11.2.1](patterns.md#1121-general). When the same token sequence can be recognised both as “*relational_expression* `is` *type*” and as “*relational_expression* `is` *pattern*”, and *type* resolves to an accessible type, the “*relational_expression* `is` *type*” alternative shall be chosen. The `is` operator is described in [§12.14.12](expressions.md#121412-the-is-operator) and the `as` operator is described in [§12.14.13](expressions.md#121413-the-as-operator). diff --git a/standard/patterns.md b/standard/patterns.md index 19a13da7e..f11e1ca7c 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -49,9 +49,13 @@ parenthesized_pattern For a *parenthesized_pattern* `(P)`, the *input type* of `P` is the input type of the parenthesized pattern. The parenthesized pattern is applicable to a type if and only if `P` is applicable to that type, matches a value if and only if `P` matches that value, and has the same *narrowed type* as `P`. Its definite-assignment effects are specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). +When recognising the *type* of a *declaration_pattern*, *type_pattern*, *positional_pattern*, or *property_pattern*, a token sequence beginning with `(` is recognised as a *type* only if its initial *tuple_type* is immediately followed by `[` starting an array rank specifier. This restriction also applies to the *type* following `is` ([§12.14.1](expressions.md#12141-general)). + +A form consisting of `(`, exactly one *subpattern* of the form *pattern* (without an *identifier* `:` prefix), and `)`, with no preceding *type*, following *property_subpattern*, or following *simple_designation*, is recognised as a *parenthesized_pattern* rather than a *positional_pattern*. If its enclosed pattern is a *constant_pattern*, the form is instead recognised as a *constant_pattern* whose *constant_expression* is parenthesized. + If the input can be syntactically recognised as both a *constant_pattern* and a *positional_pattern* then the *constant_pattern* shall be chosen. -> *Note*: ANTLR makes the specified choice automatically due to the ordering of *constant_pattern* before *positional_pattern* in the alternatives of *pattern*. *end note* +> *Note*: These restrictions concern syntactic recognition, not whether the type denoted by a name is a tuple type. Thus `ValueTuple pair`, an eligible alias to that named type followed by a designation, `(int, int)[] pairs`, and `List<(int, int)> pairs` can be declaration patterns. The form `(1)` is a constant pattern, whereas `(var item)` is a parenthesized pattern. The forms `(var item) whole`, `(value: var item)`, and `(var item) {}` are positional patterns. *end note* The `'(' pattern ')'` production allows a pattern to be enclosed in parentheses to enforce the order of evaluation among patterns combined using one of the *logical_pattern*s. @@ -174,6 +178,8 @@ single_variable_designation ; ``` +The recognition of *type* is subject to [§11.2.1](patterns.md#1121-general). + When recognising a *simple_designation* if both the *discard_designation* and *single_variable_designation* alternatives are applicable then the former shall be chosen. > *Note*: ANTLR makes the specified choice automatically due to the ordering of the alternatives of *simple_designation*. *end note* @@ -324,27 +330,84 @@ subpattern ; ``` +The recognition of *type* and of a *positional_pattern* is subject to [§11.2.1](patterns.md#1121-general). + Given a match of an input value to the pattern *type* `(` *subpatterns* `)`, a method is selected by searching in *type* for accessible declarations of `Deconstruct` and selecting one among them using the same rules as for the deconstructing assignment ([§12.23.3](expressions.md#12233-deconstructing-assignment)). -If the input can be syntactically recognised as both a *constant_pattern* and a *positional_pattern* then the *constant_pattern* shall be chosen. > *Note*: A tuple literal can be matched by patterns of several different forms, which are not interchangeable: > -> - `(int, int) x` is a *declaration_pattern* with type `(int, int)` and *simple_designation* `x`. +> - `(int, int) x` is a *positional_pattern* with two *type_pattern* subpatterns and the outer *simple_designation* `x`. +> - `ValueTuple x` is a *declaration_pattern*. +> - `(int A, int B) x` is a *positional_pattern* with two *declaration_pattern* subpatterns introducing locals `A` and `B`, and the outer *simple_designation* `x`. > - `var (x, y)` is a *var_pattern* with a *tuple_designation*. > - `(int x, int y)` is a *positional_pattern*. > - `(int, int) (x, y)` is not a valid pattern. > > *end note* -In order to extract the values to match against the patterns in the list, +In order to extract the values to match against the patterns in the list, let *D* be *type* if present; otherwise let *D* be the static type of the input value, with a nullable value type replaced by its underlying type. -1. **Tuple form.** If *type* is omitted and the static type of the input value is a tuple type ([§8.3.11](types.md#8311-tuple-types)) or if the input value is a tuple literal ([§12.8.6](expressions.md#1286-tuple-literals)), then this case applies. It is a compile-time error if *n* is not equal to the arity of that tuple type. At runtime, each tuple element is matched against the corresponding *subpattern*; the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the tuple element at the corresponding position in the tuple type. -2. **Deconstruct form.** Otherwise, if either *type* is present, or *type* is omitted and the static type of the input value contains an accessible `Deconstruct` method ([§12.7](expressions.md#127-deconstruction)), then this case applies. Let *D* be *type* if *type* is present; otherwise let *D* be the static type of the input value. A `Deconstruct` method is selected from *D* using the same overload-resolution rules as for a deconstructing assignment ([§12.23.3](expressions.md#12233-deconstructing-assignment)), with the additional requirement that its number of `out` parameters is equal to *n*; it is a compile-time error if no such method exists. If *type* is present, it is a compile-time error if the static type of the input value is not pattern compatible ([§11.2.3](patterns.md#1123-declaration-pattern)) with *type*; at runtime the input value is tested against *type* and, if that test fails, the positional pattern match fails. Otherwise, the input value is converted to *D* and the selected `Deconstruct` method is invoked with fresh variables receiving its `out` parameters. Each received value is matched against the corresponding *subpattern*, and the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the parameter at the corresponding position of `Deconstruct`. +1. **Tuple form.** If *type* is omitted and *D* is a tuple type ([§8.3.11](types.md#8311-tuple-types)) or if the input value is a tuple literal ([§12.8.6](expressions.md#1286-tuple-literals)), then this case applies. It is a compile-time error if *n* is not equal to the arity of that tuple type. At runtime, each tuple element of the non-null input value, unwrapped if necessary, is matched against the corresponding *subpattern*; the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the tuple element at the corresponding position in the tuple type. +2. **Deconstruct form.** Otherwise, if either *type* is present, or *type* is omitted and *D* contains an accessible `Deconstruct` method ([§12.7](expressions.md#127-deconstruction)), then this case applies. A `Deconstruct` method is selected from *D* using the same overload-resolution rules as for a deconstructing assignment ([§12.23.3](expressions.md#12233-deconstructing-assignment)), with the additional requirement that its number of `out` parameters is equal to *n*; it is a compile-time error if no such method exists. If *type* is present, it is a compile-time error if the static type of the input value is not pattern compatible ([§11.2.3](patterns.md#1123-declaration-pattern)) with *type*; at runtime the input value is tested against *type* and, if that test fails, the positional pattern match fails. Otherwise, the input value is converted to *D* and the selected `Deconstruct` method is invoked with fresh variables receiving its `out` parameters. Each received value is matched against the corresponding *subpattern*, and the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the parameter at the corresponding position of `Deconstruct`. 3. **ITuple form.** Otherwise, if *type* is omitted, no *subpattern* has an *identifier*, and the static type of the input value is `object`, `System.Runtime.CompilerServices.ITuple`, or a type that has an implicit reference conversion to `System.Runtime.CompilerServices.ITuple`, then this case applies. At runtime, the input value is tested for being a non-`null` instance of `System.Runtime.CompilerServices.ITuple`; if that test fails, the positional pattern match fails. Otherwise, the value’s `Length` property is read and, if it is not equal to *n*, the positional pattern match fails. Otherwise, for each *i* from 1 to *n*, the value obtained by indexing the input value with *i* − 1 is matched against the *i*-th *subpattern*, and the match succeeds if all of these succeed. 4. Otherwise, no case applies and the *positional_pattern* is a compile-time error. +In the tuple and Deconstruct forms, if *simple_designation* is a *single_variable_designation*, it introduces a local variable ([§9.2.9](variables.md#929-local-variables)) of type *D*. When the pattern matches, the variable is assigned the matched input value, converted to *D*. Tuple element names are those of *D*, rather than the names of variables declared in subpatterns. A *discard_designation* introduces no variable and does not bind the input value. Definite-assignment effects are specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). + The order in which subpatterns are matched at runtime is unspecified, and a failed match might not attempt to match all subpatterns. +> *Example*: Bare tuple-looking syntax matches the elements, rather than testing for the corresponding tuple type. An outer designation preserves the input tuple's names and unwraps a nullable tuple: +> +> +> ```csharp +> object value = ((object)1, (object)"text"); +> Console.WriteLine(value is (int, string)); +> Console.WriteLine(value is ValueTuple); +> +> (int Left, int Right)? pair = (67, 69); +> if (pair is (int A, int B) captured) +> { +> Console.WriteLine($"{A},{B};{captured.Left},{captured.Right}"); +> } +> ``` +> +> The output produced is: +> +> ```console +> True +> False +> 67,69;67,69 +> ``` +> +> *end example* +> +> *Example*: An explicit pattern type determines the outer variable's type; deconstruction does not construct a tuple to assign to it: +> +> +> ```csharp +> object value = new Point(1, 2); +> if (value is Point(var x, var y) captured) +> { +> Console.WriteLine($"{ReferenceEquals(value, captured)}:{x + y}:{captured.X + captured.Y}"); +> } +> +> class Point +> { +> public int X { get; } +> public int Y { get; } +> public Point(int x, int y) => (X, Y) = (x, y); +> public void Deconstruct(out int x, out int y) => (x, y) = (X, Y); +> } +> ``` +> +> The output produced is: +> +> ```console +> True:3:3 +> ``` +> +> *end example* +> > *Example*: Here, we deconstruct an expression result and match the resulting values against the corresponding nested patterns: > > @@ -421,6 +484,8 @@ property_subpattern ; ``` +The recognition of the optional *type* is subject to [§11.2.1](patterns.md#1121-general). + It is an error if any *subpattern* of a *property_pattern* does not contain an *identifier*. It is a compile-time error if the *type* is a nullable value type ([§8.3.12](types.md#8312-nullable-value-types)) or a nullable reference type ([§8.9.3](types.md#893-nullable-reference-types)). From 6f328ce3436fe4d19997f0c3b0bf75e87534351f Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 17:13:48 -0500 Subject: [PATCH 24/30] Normative references and terminology MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replaced undefined “recursive pattern” with explicit positional/property patterns specifying a type. - Corrected `System.ITuple` to `System.Runtime.CompilerServices.ITuple` --- standard/patterns.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index f11e1ca7c..3953ba51e 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -646,7 +646,7 @@ type_pattern ; ``` -A type pattern naming a type `T` is *applicable to* every type `E` for which `E` is *pattern compatible* with `T` (§11.2.2). +A type pattern naming a type `T` is *applicable to* every type `E` for which `E` is *pattern compatible* with `T` (§11.2.3). The runtime type of the value is tested against *type* using the same rules specified in the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test succeeds, the pattern matches that value. It is a compile-time error if the *type* is a nullable type. This pattern form never matches a `null` value. @@ -861,8 +861,8 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b - If `P` is a type pattern, the *narrowed type* is the type of the type pattern's type. - Otherwise, if `P` is a declaration pattern, the *narrowed type* is the type of the declaration pattern's type. -- Otherwise, if `P` is a recursive pattern that gives an explicit type, the *narrowed type* is that type. -- Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.ITuple`. +- Otherwise, if `P` specifies a *type* and is either a *positional_pattern* or a *property_pattern*, the *narrowed type* is that type. +- Otherwise, if `P` is matched via the rules for `ITuple` in a *positional_pattern* (§11.2.5), the *narrowed type* is the type `System.Runtime.CompilerServices.ITuple`. - Otherwise, if `P` is a constant pattern where the constant is not the null constant, the *narrowed type* is the type of expression `R` obtained using the expression-conversion steps in [Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern), with the constant pattern's expression as `E` and its input type as `T`. Only the steps determining `R` are used here. - Otherwise, if `P` is a relational pattern, the *narrowed type* is its comparison type ([Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern)). - Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). From 25115ee3663288f0981b325199aa6ff6d6dd7fff Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Tue, 24 Nov 2026 17:23:25 -0500 Subject: [PATCH 25/30] Logical-pattern applicability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Specified that `not` and both operands of `or` retain the enclosing input type. - Specified that `and` passes its left operand’s narrowed type to its right operand. - Defined applicability in terms of each operand’s input type. - Removed duplicate conjunction input-type wording and added two focused examples. --- standard/patterns.md | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 3953ba51e..5bda3818f 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -792,6 +792,45 @@ negated_pattern A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. +For a *negated_pattern* of the form `not P` or a *disjunctive_pattern* of the form `P or Q`, each immediate operand has the *input type* of the enclosing pattern. For a *conjunctive_pattern* of the form `P and Q`, the *input type* of `P` is the input type of the enclosing pattern, and the *input type* of `Q` is the *narrowed type* of `P`. + +A *logical_pattern* of one of these forms is *applicable to* a type `T` if and only if each operand is applicable to its input type, determined as above with `T` as the input type of the enclosing pattern. + +> *Example*: Conjunction narrows the input of its right operand; both operands of disjunction have the enclosing input type. Each of the following patterns is applicable to `object`: +> +> +> ```csharp +> object value = "abc"; +> Console.WriteLine(value is string and { Length: 3 }); +> Console.WriteLine(value is string or int); +> Console.WriteLine(value is not int); +> ``` +> +> The output produced is: +> +> ```console +> True +> True +> True +> ``` +> +> *end example* +> +> *Example*: Each of the following patterns has an operand that is not applicable to its input type: +> +> +> ```csharp +> class C +> { +> static bool RightDisjunct(int value) => value is int or string; +> static bool LeftDisjunct(int value) => value is string or int; +> static bool Negation(int value) => value is not string; +> static bool NestedNegation(object value) => value is string and not int; +> } +> ``` +> +> *end example* + A declaration of a pattern variable shall satisfy both of the following conditions: - The declaration is not enclosed in a *disjunctive_pattern* of the form `P or Q`. @@ -857,7 +896,7 @@ The definite-assignment effects of patterns are specified in [§9.4.4.34](variab > > *end example* -In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed by the *type narrowing* requirements of first pattern of the `and`. The *narrowed type* of a pattern `P` is defined as follows: +The *narrowed type* of a pattern `P` is defined as follows: - If `P` is a type pattern, the *narrowed type* is the type of the type pattern's type. - Otherwise, if `P` is a declaration pattern, the *narrowed type* is the type of the declaration pattern's type. @@ -866,7 +905,7 @@ In a *conjunctive_pattern*, the *input type* of the second pattern is narrowed b - Otherwise, if `P` is a constant pattern where the constant is not the null constant, the *narrowed type* is the type of expression `R` obtained using the expression-conversion steps in [Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern), with the constant pattern's expression as `E` and its input type as `T`. Only the steps determining `R` are used here. - Otherwise, if `P` is a relational pattern, the *narrowed type* is its comparison type ([Relational pattern](patterns.md#relational-pattern-new-clause-relational-pattern)). - Otherwise, if `P` is an `or` pattern, the *narrowed type* is the common type of the *narrowed type* of the subpatterns if such a common type exists. For this purpose, the common type algorithm considers only identity, boxing, and implicit reference conversions, and it considers all subpatterns of a sequence of `or` patterns (ignoring parenthesized patterns). -- Otherwise, if `P` is an `and` pattern, the *narrowed type* is the *narrowed type* of the right pattern. Moreover, the *narrowed type* of the left pattern is the *input type* of the right pattern. +- Otherwise, if `P` is an `and` pattern, the *narrowed type* is the *narrowed type* of the right pattern. - Otherwise, if `P` is a parenthesized pattern, its *narrowed type* is determined as specified in [§11.2.1](patterns.md#1121-general). - Otherwise the *narrowed type* of `P` is `P`'s input type. From 8ed3eafe0c3a867346eb308459e36908e97b5b49 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 25 Nov 2026 09:15:55 -0500 Subject: [PATCH 26/30] Grouping, evaluation order, and precedence - Parentheses specify grouping rather than runtime evaluation order. - `and`/`or` do not guarantee left-to-right short-circuit evaluation; tests that cannot affect the result may be skipped. - Clarified `is` precedence relative to `&&`/`||`, preserving ordinary unary `!` precedence. --- standard/patterns.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 5bda3818f..d506e5837 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -57,7 +57,7 @@ If the input can be syntactically recognised as both a *constant_pattern* and a > *Note*: These restrictions concern syntactic recognition, not whether the type denoted by a name is a tuple type. Thus `ValueTuple pair`, an eligible alias to that named type followed by a designation, `(int, int)[] pairs`, and `List<(int, int)> pairs` can be declaration patterns. The form `(1)` is a constant pattern, whereas `(var item)` is a parenthesized pattern. The forms `(var item) whole`, `(value: var item)`, and `(var item) {}` are positional patterns. *end note* -The `'(' pattern ')'` production allows a pattern to be enclosed in parentheses to enforce the order of evaluation among patterns combined using one of the *logical_pattern*s. +The `'(' pattern ')'` production allows a pattern to be enclosed in parentheses to specify the grouping of patterns combined using pattern operators. > *Example*: A parenthesized pattern preserves narrowing to the right-hand pattern of a conjunction. In the following example, `text` has type `string`, so its `Length` property can be accessed: > @@ -790,7 +790,7 @@ negated_pattern `not`, `and`, and `or` are collectively called ***pattern operators***. -A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike their language operator counterparts, `&&` and `||`, `and` and `or` are *not* short-circuiting operators. +A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike `&&` and `||`, `and` and `or` do not guarantee left-to-right short-circuit evaluation. The evaluation-order rule in §11.2.1 applies; tests that cannot affect the result need not be performed. For a *negated_pattern* of the form `not P` or a *disjunctive_pattern* of the form `P or Q`, each immediate operand has the *input type* of the enclosing pattern. For a *conjunctive_pattern* of the form `P and Q`, the *input type* of `P` is the input type of the enclosing pattern, and the *input type* of `Q` is the *narrowed type* of `P`. @@ -945,7 +945,7 @@ The *narrowed type* of a pattern `P` is defined as follows: > *Note*: As indicated by the grammar, `not` has precedence over `and`, which has precedence over `or`. This can be explicitly indicated or overridden by using parentheses. *end note* -When a *pattern* appears on the right-hand-side of `is`, the extent of the pattern is determined by the grammar; as a result, the pattern operators `and`, `or`, and `not` within the pattern bind more tightly than the logical operators `&&`, `||`, and `!` outside the pattern. +When a *pattern* appears on the right-hand-side of `is`, the extent of the pattern is determined by the grammar. An is-pattern expression binds more tightly than `&&` and `||`. Unary `!` retains its ordinary expression precedence: `!b is true or false` is parsed as `(!b) is (true or false)`. > *Example*: > From 6cfd71339d8020be8c597993f13fc9a51de5d64c Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 25 Nov 2026 09:25:11 -0500 Subject: [PATCH 27/30] type-pattern restrictions Implemented one sentence change in `standard/patterns.md`, uncommitted. - Explicitly prohibited `dynamic`, nullable value types, and nullable reference types in type patterns. - Preserved legacy `o is dynamic` and nullable-alias is-type expressions. --- standard/patterns.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/standard/patterns.md b/standard/patterns.md index d506e5837..a8d23c9a5 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -648,7 +648,7 @@ type_pattern A type pattern naming a type `T` is *applicable to* every type `E` for which `E` is *pattern compatible* with `T` (§11.2.3). -The runtime type of the value is tested against *type* using the same rules specified in the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test succeeds, the pattern matches that value. It is a compile-time error if the *type* is a nullable type. This pattern form never matches a `null` value. +The runtime type of the value is tested against *type* using the same rules specified in the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)). If the test succeeds, the pattern matches that value. It is a compile-time error if the *type* is `dynamic`, a nullable value type ([§8.3.12](types.md#8312-nullable-value-types)), or a nullable reference type ([§8.9.3](types.md#893-nullable-reference-types)). This pattern form never matches a `null` value. ### §relational-pattern-new-clause Relational pattern From c76c5ec0916b0cadb0c3ed0248541ae429a70d51 Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 25 Nov 2026 09:58:29 -0500 Subject: [PATCH 28/30] Contextual pattern-keyword recognition Implemented locally in `standard/patterns.md` and `standard/lexical-structure.md`, uncommitted. - Specified when `not` is a negation operator. - Defined lookahead distinguishing `and`/`or` operators from variable designations. - Preserved escaped identifiers and legacy expression boundaries. - Added one annotated example and a lexical cross-reference. --- standard/lexical-structure.md | 2 ++ standard/patterns.md | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/standard/lexical-structure.md b/standard/lexical-structure.md index 8e87a9c3b..154a9ad97 100644 --- a/standard/lexical-structure.md +++ b/standard/lexical-structure.md @@ -625,6 +625,8 @@ Another example such disambiguation is the contextual keyword `await` ([§12.9.9 Just as with keywords, contextual keywords can be used as ordinary identifiers by prefixing them with the `@` character. +The recognition of `not`, `and`, and `or` as pattern operators is specified in [Logical pattern](patterns.md#logical-pattern-new-clause-logical-pattern). + > *Note*: When used as contextual keywords, these identifiers cannot contain *Unicode_Escape_Sequence*s. *end note* ### 6.4.5 Literals diff --git a/standard/patterns.md b/standard/patterns.md index a8d23c9a5..2061b88b4 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -790,6 +790,41 @@ negated_pattern `not`, `and`, and `or` are collectively called ***pattern operators***. +These operators are contextual keywords ([§6.4.4](lexical-structure.md#644-keywords)). In a *subpattern*, an *identifier* `:` prefix is recognised before its *pattern*. The following rules disambiguate operator and identifier uses within patterns: + +- At the start of a *negated_pattern*, `not` is recognised as the pattern operator rather than an identifier. +- Where `and` or `or` could be a *simple_designation* in a pattern, it is recognised as a pattern operator instead if the following token is an *operand-start token*, as defined below. Otherwise, it is recognised as an identifier. + +For this purpose, an ***operand-start token*** is `{`, `<`, `<=`, `>`, `>=`, or a token that can be the first token of an *expression* according to the syntactic grammar, other than `+`, `-`, `*`, `&`, or `^`. Identifiers, including contextual keywords, are included without name lookup or consideration of whether the expression would be a constant expression. + +> *Example*: `and` and `or` can be designations, but a following operand can cause them to be recognised as operators: +> +> +> ```csharp +> object value = 1; +> if (value is int and) +> { +> Console.WriteLine(and); +> } +> if (value is int or) +> { +> Console.WriteLine(or); +> } +> Console.WriteLine(value is int and > 0); +> Console.WriteLine(value is not not int); +> ``` +> +> The output produced is: +> +> ```console +> 1 +> 1 +> True +> True +> ``` +> +> *end example* + A *negated_pattern* matches if the pattern being negated does not match, and vice versa. A *conjunctive_pattern* requires both patterns to match. A *disjunctive_pattern* requires either pattern to match. Unlike `&&` and `||`, `and` and `or` do not guarantee left-to-right short-circuit evaluation. The evaluation-order rule in §11.2.1 applies; tests that cannot affect the result need not be performed. For a *negated_pattern* of the form `not P` or a *disjunctive_pattern* of the form `P or Q`, each immediate operand has the *input type* of the enclosing pattern. For a *conjunctive_pattern* of the form `P and Q`, the *input type* of `P` is the input type of the enclosing pattern, and the *input type* of `Q` is the *narrowed type* of `P`. From 5fb12da2d541324960cb6c546b4f935830aaafab Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 25 Nov 2026 10:41:59 -0500 Subject: [PATCH 29/30] ITuple fallback Implemented locally in `standard/patterns.md`, uncommitted. - Allowed implementing structs and nullable inputs to use `ITuple` fallback. - Required omission of an explicit type, property clause, named outer designation, and element-name prefixes. - Preserved outer discards and variables declared within element subpatterns. - Preserved tuple/applicable-`Deconstruct` priority; a wrong-arity `Deconstruct` no longer blocks fallback. - Added two annotated examples. --- standard/patterns.md | 58 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index 2061b88b4..eb57ec04a 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -348,14 +348,68 @@ Given a match of an input value to the pattern *type* `(` *subpatterns* `)`, a m In order to extract the values to match against the patterns in the list, let *D* be *type* if present; otherwise let *D* be the static type of the input value, with a nullable value type replaced by its underlying type. 1. **Tuple form.** If *type* is omitted and *D* is a tuple type ([§8.3.11](types.md#8311-tuple-types)) or if the input value is a tuple literal ([§12.8.6](expressions.md#1286-tuple-literals)), then this case applies. It is a compile-time error if *n* is not equal to the arity of that tuple type. At runtime, each tuple element of the non-null input value, unwrapped if necessary, is matched against the corresponding *subpattern*; the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the tuple element at the corresponding position in the tuple type. -2. **Deconstruct form.** Otherwise, if either *type* is present, or *type* is omitted and *D* contains an accessible `Deconstruct` method ([§12.7](expressions.md#127-deconstruction)), then this case applies. A `Deconstruct` method is selected from *D* using the same overload-resolution rules as for a deconstructing assignment ([§12.23.3](expressions.md#12233-deconstructing-assignment)), with the additional requirement that its number of `out` parameters is equal to *n*; it is a compile-time error if no such method exists. If *type* is present, it is a compile-time error if the static type of the input value is not pattern compatible ([§11.2.3](patterns.md#1123-declaration-pattern)) with *type*; at runtime the input value is tested against *type* and, if that test fails, the positional pattern match fails. Otherwise, the input value is converted to *D* and the selected `Deconstruct` method is invoked with fresh variables receiving its `out` parameters. Each received value is matched against the corresponding *subpattern*, and the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the parameter at the corresponding position of `Deconstruct`. -3. **ITuple form.** Otherwise, if *type* is omitted, no *subpattern* has an *identifier*, and the static type of the input value is `object`, `System.Runtime.CompilerServices.ITuple`, or a type that has an implicit reference conversion to `System.Runtime.CompilerServices.ITuple`, then this case applies. At runtime, the input value is tested for being a non-`null` instance of `System.Runtime.CompilerServices.ITuple`; if that test fails, the positional pattern match fails. Otherwise, the value’s `Length` property is read and, if it is not equal to *n*, the positional pattern match fails. Otherwise, for each *i* from 1 to *n*, the value obtained by indexing the input value with *i* − 1 is matched against the *i*-th *subpattern*, and the match succeeds if all of these succeed. +2. **Deconstruct form.** Otherwise, if either *type* is present, or compile-time overload resolution for invoking `Deconstruct` ([§12.7](expressions.md#127-deconstruction)) on a value of type *D* with *n* `out` arguments whose types are to be inferred finds at least one applicable method, then this case applies. A `Deconstruct` method is selected from *D* using the same overload-resolution rules as for a deconstructing assignment ([§12.23.3](expressions.md#12233-deconstructing-assignment)), with the additional requirement that its number of `out` parameters is equal to *n*; it is a compile-time error if no such method exists. If *type* is present, it is a compile-time error if the static type of the input value is not pattern compatible ([§11.2.3](patterns.md#1123-declaration-pattern)) with *type*; at runtime the input value is tested against *type* and, if that test fails, the positional pattern match fails. Otherwise, the input value is converted to *D* and the selected `Deconstruct` method is invoked with fresh variables receiving its `out` parameters. Each received value is matched against the corresponding *subpattern*, and the match succeeds if all of these succeed. If any *subpattern* has an *identifier*, that *identifier* shall name the parameter at the corresponding position of `Deconstruct`. +3. **ITuple form.** Otherwise, if *type* and *property_subpattern* are omitted, *simple_designation* is omitted or is a *discard_designation*, no *subpattern* in *subpatterns* has an *identifier* prefix, and *D* is `object` or `dynamic` or has an identity conversion, an implicit reference conversion, or a boxing conversion ([§10.2.9](conversions.md#1029-boxing-conversions)) to `System.Runtime.CompilerServices.ITuple`, then this case applies. At runtime, the input value is tested for being a non-`null` instance of `System.Runtime.CompilerServices.ITuple`; if that test fails, the positional pattern match fails. Otherwise, the value’s `Length` property is read and, if it is not equal to *n*, the positional pattern match fails. Otherwise, for each *i* from 1 to *n*, the value obtained by indexing the input value with *i* − 1 is matched against the *i*-th *subpattern*, and the match succeeds if all of these succeed. 4. Otherwise, no case applies and the *positional_pattern* is a compile-time error. In the tuple and Deconstruct forms, if *simple_designation* is a *single_variable_designation*, it introduces a local variable ([§9.2.9](variables.md#929-local-variables)) of type *D*. When the pattern matches, the variable is assigned the matched input value, converted to *D*. Tuple element names are those of *D*, rather than the names of variables declared in subpatterns. A *discard_designation* introduces no variable and does not bind the input value. Definite-assignment effects are specified in [§9.4.4.34](variables.md#94434-is-pattern-expressions). The order in which subpatterns are matched at runtime is unspecified, and a failed match might not attempt to match all subpatterns. +> *Example*: An implementing struct can be matched through `ITuple`, without a `Deconstruct` method. An outer discard is permitted, and variables may be declared within the subpatterns: +> +> +> ```csharp +> using System; +> using System.Runtime.CompilerServices; +> +> Pair value = new Pair(); +> Console.WriteLine(value is (1, 2)); +> if (value is (int first, int second) _) +> { +> Console.WriteLine(first + second); +> } +> Pair? optional = value; +> Console.WriteLine(optional is (1, 2)); +> optional = null; +> Console.WriteLine(optional is (1, 2)); +> +> struct Pair : ITuple +> { +> int ITuple.Length => 2; +> object ITuple.this[int index] => index + 1; +> } +> ``` +> +> The output produced is: +> +> ```console +> True +> 3 +> True +> False +> ``` +> +> *end example* +> +> *Example*: Neither a named outer designation nor a property clause is permitted for ITuple fallback. Both methods below produce compile-time errors: +> +> +> ```csharp +> using System.Runtime.CompilerServices; +> +> struct Pair : ITuple +> { +> int ITuple.Length => 2; +> object ITuple.this[int index] => index + 1; +> +> static bool Capture(Pair value) => value is (1, 2) whole; +> static bool Property(Pair value) => value is (1, 2) {}; +> } +> ``` +> +> *end example* +> > *Example*: Bare tuple-looking syntax matches the elements, rather than testing for the corresponding tuple type. An outer designation preserves the input tuple's names and unwraps a nullable tuple: > > From bcd37c524aa2f247a27590609afebddc7272533c Mon Sep 17 00:00:00 2001 From: Bill Wagner Date: Wed, 25 Nov 2026 11:10:50 -0500 Subject: [PATCH 30/30] Discard recognition and name lookup Implemented locally in `standard/patterns.md`, uncommitted. - Specified that nested and switch-expression `_` patterns are discards regardless of same-named declarations. - Preserved legacy top-level `is _` type lookup and switch-label lookup. - Distinguished escaped identifiers from discard tokens. - Corrected the `WithUnderscore` example and added a type/discard comparison example. --- standard/patterns.md | 57 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/standard/patterns.md b/standard/patterns.md index eb57ec04a..1151f6f57 100644 --- a/standard/patterns.md +++ b/standard/patterns.md @@ -618,18 +618,14 @@ discard_pattern ; ``` -Where the syntactic context permits a *pattern*, if the token `_` would resolve as a *simple_name* ([§12.8.4](expressions.md#1284-simple-names)) to an accessible constant or to a type, then `_` is *not* treated as a *discard_pattern*. Instead: +Where a *pattern* is expected, the token `_` is recognised as a *discard_pattern* without name lookup, with the following exceptions: -- If `_` resolves to an accessible constant, the `_` is interpreted as a *constant_pattern* ([§11.2.2](patterns.md#1122-constant-pattern)) whose constant expression is that constant. -- If `_` resolves to a type, then in the right-hand side of an `is` operator the construct *relational_expression* `is _` is interpreted as the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)) testing against that type. In any other syntactic context that admits a *pattern*, a bare `_` resolving to a type is not by itself a valid *pattern*; however, `_` may appear as the *type* of a *declaration_pattern* (e.g., `_ x`) or in other pattern forms that explicitly name a type. +- If `_` is the entire right-hand operand of an `is` operator, the construct *relational_expression* `is _` is interpreted as the is-type operator ([§12.14.12.1](expressions.md#1214121-the-is-type-operator)), and `_` shall resolve to an accessible type. +- If `_` is the entire *pattern* of a *switch_label*, it is interpreted as a *simple_name* ([§12.8.4](expressions.md#1284-simple-names)). If that name denotes a type, the pattern is a *type_pattern*; otherwise it is a *constant_pattern* ([§11.2.2](patterns.md#1122-constant-pattern)). -This rule preserves backward compatibility with code that defined `_` as a type or identifier prior to the introduction of the discard pattern. If `_` resolves to anything other than an accessible constant or type (for example, a local variable, parameter, field, or method), the rule does not apply and `_` remains a *discard_pattern*. +An identifier spelled `@_` or using a Unicode escape sequence to represent `_` is not a *discard_token* ([§6.4.3](lexical-structure.md#643-identifiers)) and is interpreted as an identifier. -> *Note*: This is analogous to the rule for `var` in [§11.2.4](patterns.md#1124-var-pattern), except that for `_` an in-scope constant or type causes `_` to be interpreted as a reference to that declaration rather than producing an error. *end note* - -If, after applying the preceding rule, the token `_` is still a *discard_pattern*, it is a compile-time error for that *discard_pattern* to appear as the entire *pattern* of a *relational_expression* of the form *relational_expression* `is` *pattern*, or as the entire *pattern* of a *switch_label*. A *discard_pattern* may, however, appear as a *subpattern* of an enclosing pattern (for example, as a *subpattern* of a *positional_pattern* or *property_pattern*). - -> *Note*: In those cases, to match any expression, use a *var_pattern* with a discard `var _`. *end note* +> *Note*: To match any expression in the contexts excluded above, use a *var_pattern* with a discard `var _` ([§11.2.4](patterns.md#1124-var-pattern)). A *pattern* consisting of `_` within a *parenthesized_pattern* or other enclosing pattern is a *discard_pattern*, as is the *pattern* `_` in a *switch_expression_arm*, regardless of an in-scope constant or type named `_`. *end note* @@ -667,9 +663,14 @@ If, after applying the preceding rule, the token `_` is still a *discard_pattern -> *Example*: The following illustrates how an in-scope constant named `_` changes the interpretation of an `_` arm in a `switch` expression. In `WithoutUnderscore`, the `_` arm is a *discard_pattern* and matches any value. In `WithUnderscore`, the in-scope constant `_` causes the `_` arm to be interpreted as a *constant_pattern* that matches only the value `0`. +> *Example*: An in-scope constant named `_` does not change the interpretation of a `_` arm in a `switch` expression. Use `@_` to match that constant: > +> > ```csharp +> Console.WriteLine(WithoutUnderscore(2)); +> Console.WriteLine(WithUnderscore(0)); +> Console.WriteLine(WithUnderscore(2)); +> > static string WithoutUnderscore(int n) => n switch > { > 1 => "one", @@ -682,12 +683,44 @@ If, after applying the preceding rule, the token `_` is still a *discard_pattern > return n switch > { > 1 => "one", -> _ => "zero", -> var x => "other: " + x, +> @_ => "zero", +> _ => "other", > }; > } > ``` > +> The output produced is: +> +> ```console +> other +> zero +> other +> ``` +> +> *end example* +> +> *Example*: A `_` that is the entire right-hand operand of `is` refers to a type for backward compatibility. Within parentheses or a `switch` expression, `_` is a discard. The escaped identifier `@_` can name the type in a pattern: +> +> +> ```csharp +> object value = 1; +> Console.WriteLine(value is _); +> Console.WriteLine(value is (_)); +> Console.WriteLine(value switch { _ => "discard" }); +> Console.WriteLine(value switch { @_ => "type", var other => "other" }); +> +> class _ {} +> ``` +> +> The output produced is: +> +> ```console +> False +> True +> discard +> other +> ``` +> > *end example* ### §type-pattern-new-clause Type pattern