dotnet/csharpstandard

Standard should state that patterns can be tested in any order

BillWagner opened this issue · 4 comments

Type of issue

Spec incomplete

Description

The Microsoft spec for patterns in C# 7 includes this statement regarding switch statements:

The order in which patterns are matched is not defined. A compiler is permitted to match patterns out of order, and to reuse the results of already matched patterns to compute the result of matching of other patterns.

In C# 8, the implementation has more flexibility. From the Microsoft spec for patterns in C# 8, the following is added:

Giving the compiler flexibility in reordering the operations executed during pattern-matching can permit flexibility that can be used to improve the efficiency of pattern-matching. The (unenforced) requirement would be that properties accessed in a pattern, and the Deconstruct methods, are required to be "pure" (side-effect free, idempotent, etc). That doesn't mean that we would add purity as a language concept, only that we would allow the compiler flexibility in reordering operations.

Resolution 2018-04-04 LDM: confirmed: the compiler is permitted to reorder calls to Deconstruct, property accesses, and invocations of methods in ITuple, and may assume that returned values are the same from multiple calls. The compiler should not invoke functions that cannot affect the result, and we will be very careful before making any changes to the compiler-generated order of evaluation in the future.

We need to create normative language for that implementation choice. Further, we need to add the order evaluation for pattern matching tests to the list of unspecified behaviors.

I think we can do this in the V8 branch, without making an additional release of V7.

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/patterns

Content source URL

https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/patterns.md

Regarding, "The order in which patterns are matched is not defined," this suggests that behavior is undefined when that is a well-defined term that we didn't intend to apply here. So, I agree with Bill that we should make this unspecified behavior.

BTW, the text Bill quotes from V7 is in a Note, so is informative.

BTW, the text Bill quotes from V7 is in a Note, so is informative.

@RexJaeschke Where did you find it? I looked and missed it.

13.8.3: It's not an exact match; see the extra text in bold/italic.

Note: The order in which patterns are matched at runtime is not defined. A compiler is permitted (but not required) to match patterns out of order, and to reuse the results of already matched patterns to compute the result of matching of other patterns. Nevertheless, the compiler is required to determine the lexically first pattern that matches the expression and for which the guard clause is either absent or evaluates to true. end note