From 7d2dc7d2fa1a1076384dac71bd287bc22dcebe27 Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 29 Nov 2021 04:36:32 +0200 Subject: [PATCH 1/9] Create spec for ref assignment on switch expressions --- .../ref-assignment-switch-expressions.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 proposals/ref-assignment-switch-expressions.md diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md new file mode 100644 index 0000000000..a2d8e92683 --- /dev/null +++ b/proposals/ref-assignment-switch-expressions.md @@ -0,0 +1,69 @@ +# `ref` assignment on `switch` expressions + +* [x] Proposed +* [ ] Prototype: None +* [ ] Implementation: None +* [ ] Specification: Started, below + +## Summary +[summary]: #summary + +Provide the ability to return `ref` values in `switch` expressions. + +## Motivation +[motivation]: #motivation + +The `switch` expression is meant to provide a quicker way to return values based on a given expression, but does not support returning `ref` expressions. This limitation doesn't prevent any harm, and can be lifted. + +## Detailed design +[design]: #detailed-design + +A `switch` expression may return a `ref` value. The returning expression, if not a `throw` expression, must be a `ref` expression. + +A `switch` expression that returns a `ref` value **does not** need an extra `ref` in front of it when assigned/returned to a `ref` local. The examples below cover this case too. This decision is made since the `ref` is essentially included in the cases. + +`throw` expressions can still be used normally. + +## Examples +[examples]: #examples + +```csharp +private ref int GetDirectionField(Direction direction) => direction switch +{ + Direction.North => ref NorthField, + Direction.South => ref SouthField, + Direction.East => ref EastField, + Direction.West => ref WestField, + _ => throw new NotImplementedException(), +}; + +private void RefSwitchAssignLocal() +{ + ref int dimension = axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + }; +} +``` + +## Drawbacks +[drawbacks]: #drawbacks + +None. + +## Alternatives +[alternatives]: #alternatives + +Currently, this may only be achieved with a `switch` statement, or a sequence of `if`-`else` statements. + +## Unresolved questions +[unresolved]: #unresolved-questions + +- [ ] Requires LDM review +- [ ] Should there be a quicker way to denote returning a `ref` to the provided expression by not requiring copying it over for each case? + +## Design meetings +[meetings]: #design-meetings + +None. From a0eeaa1d3e5fe2058af3b67945556945f31b939b Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 29 Nov 2021 05:17:25 +0200 Subject: [PATCH 2/9] Do include a ref in front of the expression Nice catch, fred --- proposals/ref-assignment-switch-expressions.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index a2d8e92683..18e6c7aed7 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -20,7 +20,7 @@ The `switch` expression is meant to provide a quicker way to return values based A `switch` expression may return a `ref` value. The returning expression, if not a `throw` expression, must be a `ref` expression. -A `switch` expression that returns a `ref` value **does not** need an extra `ref` in front of it when assigned/returned to a `ref` local. The examples below cover this case too. This decision is made since the `ref` is essentially included in the cases. +A `switch` expression that returns a `ref` value needs an extra `ref` in front of it when assigned/returned to a `ref` local. The examples below cover this case too. This design aligns with the current design in the ternary operator. `throw` expressions can still be used normally. @@ -28,7 +28,7 @@ A `switch` expression that returns a `ref` value **does not** need an extra `ref [examples]: #examples ```csharp -private ref int GetDirectionField(Direction direction) => direction switch +private ref int GetDirectionField(Direction direction) => ref direction switch { Direction.North => ref NorthField, Direction.South => ref SouthField, @@ -39,7 +39,7 @@ private ref int GetDirectionField(Direction direction) => direction switch private void RefSwitchAssignLocal() { - ref int dimension = axis switch + ref int dimension = ref axis switch { Axis.X => ref X, Axis.Y => ref Y, From 011f9748477ddbf0b31faa270ece8fb49cd1babe Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Thu, 20 Jul 2023 10:46:47 +0300 Subject: [PATCH 3/9] Include more details in the spec --- .../ref-assignment-switch-expressions.md | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index 18e6c7aed7..fda95833a3 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -20,14 +20,37 @@ The `switch` expression is meant to provide a quicker way to return values based A `switch` expression may return a `ref` value. The returning expression, if not a `throw` expression, must be a `ref` expression. -A `switch` expression that returns a `ref` value needs an extra `ref` in front of it when assigned/returned to a `ref` local. The examples below cover this case too. This design aligns with the current design in the ternary operator. +A `switch` expression that returns a `ref` value needs an extra `ref` in front of it when assigned/returned to a `ref` local. This design aligns with the current design in the ternary operator. -`throw` expressions can still be used normally. +`throw` expressions can still be used normally, and pose no effect on the return type of the `switch` expression. + +Once a single switch arm returns a `ref` expression, all other switch arms must return `ref` expressions, unless they are `throw` expressions. Not providing a `ref` expression in a switch arm causes a compiler error. + +Since all ref expressions are LValues, and the switch arms are all ref expressions, the entire result of the switch expression is also an LValue. Therefore, the entire switch expression can be passed by reference, assigned to, and returned by reference. Note that for directly assigning to the switch expression's ref result, the `ref` keyword must not be used, like normal ref locals are assigned. For example: + +`item switch { 1 => ref X, 2 => ref Y } = value` + +When not in the context of assigning the ref result of the `switch` expression, not using the `ref` keyword in front of the switch expression is considered a logical error. Thus, it is advised to show a warning covering that case, like in the example: +```csharp +private void RefSwitchAssignLocal() +{ + // Warning: + // the switch statement returns by reference but the result is immediately dereferenced + int dimension = axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + }; +} +``` + +Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch statement is unsafe to return. Otherwise, the entire `switch` statement's expression is safe to return. ## Examples [examples]: #examples ```csharp +// Returning by reference private ref int GetDirectionField(Direction direction) => ref direction switch { Direction.North => ref NorthField, @@ -37,6 +60,7 @@ private ref int GetDirectionField(Direction direction) => ref direction switch _ => throw new NotImplementedException(), }; +// Assigning to a ref local private void RefSwitchAssignLocal() { ref int dimension = ref axis switch @@ -45,6 +69,24 @@ private void RefSwitchAssignLocal() Axis.Y => ref Y, }; } + +// Assigning to the ref of the switch expression +private void RefSwitchAssignDirectly(int value) +{ + axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + } = value; + + // Equivalent to: + ref int dimension = ref axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + }; + dimension = value; +} ``` ## Drawbacks @@ -61,7 +103,6 @@ Currently, this may only be achieved with a `switch` statement, or a sequence of [unresolved]: #unresolved-questions - [ ] Requires LDM review -- [ ] Should there be a quicker way to denote returning a `ref` to the provided expression by not requiring copying it over for each case? ## Design meetings [meetings]: #design-meetings From 827884d63f4ab55b1691debbd5922f440e9a0f05 Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Thu, 20 Jul 2023 12:15:54 +0300 Subject: [PATCH 4/9] Update rules about `ref readonly` + examples --- .../ref-assignment-switch-expressions.md | 73 +++++++++++++------ 1 file changed, 52 insertions(+), 21 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index fda95833a3..56fe4f54a8 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -28,27 +28,6 @@ Once a single switch arm returns a `ref` expression, all other switch arms must Since all ref expressions are LValues, and the switch arms are all ref expressions, the entire result of the switch expression is also an LValue. Therefore, the entire switch expression can be passed by reference, assigned to, and returned by reference. Note that for directly assigning to the switch expression's ref result, the `ref` keyword must not be used, like normal ref locals are assigned. For example: -`item switch { 1 => ref X, 2 => ref Y } = value` - -When not in the context of assigning the ref result of the `switch` expression, not using the `ref` keyword in front of the switch expression is considered a logical error. Thus, it is advised to show a warning covering that case, like in the example: -```csharp -private void RefSwitchAssignLocal() -{ - // Warning: - // the switch statement returns by reference but the result is immediately dereferenced - int dimension = axis switch - { - Axis.X => ref X, - Axis.Y => ref Y, - }; -} -``` - -Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch statement is unsafe to return. Otherwise, the entire `switch` statement's expression is safe to return. - -## Examples -[examples]: #examples - ```csharp // Returning by reference private ref int GetDirectionField(Direction direction) => ref direction switch @@ -89,6 +68,58 @@ private void RefSwitchAssignDirectly(int value) } ``` +Note that, a switch arm can only return a `ref` to a read-only reference if the switch expression is assigned to a `ref readonly` symbol. Consider the example: +```csharp +void M(Axis axis, ref int x, in int y) +{ + ref int dimension = ref axis switch + { + Axis.X => ref x, + Axis.Y => ref y, // Error: y is readonly and cannot be passed by reference to a non-readonly reference + }; +} +``` + +To pass `ref y`, the declaration of `dimension` must be `ref readonly int`, demoting all assigned references to readonly: +```csharp +void M(Axis axis, ref int x, in int y) +{ + ref readonly int dimension = ref axis switch + { + Axis.X => ref x, + Axis.Y => ref y, + }; +} +``` + +Likewise, the same error would be thrown if the above expression were to be directly assigned a value, like in the example: +```csharp +void M(Axis axis, ref int x, in int y) +{ + axis switch + { + Axis.X => ref x, + Axis.Y => ref y, // Error: y is readonly and cannot be assigned by reference + } = 412; +} +``` + +When not in the context of assigning the ref result of the `switch` expression, not using the `ref` keyword in front of the switch expression is considered a logical error. Thus, it is advised to show a warning covering that case, like in the example: +```csharp +private void RefSwitchAssignLocal() +{ + // Warning: + // the switch statement returns by reference but the result is immediately dereferenced + int dimension = axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + }; +} +``` + +Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch statement is unsafe to return. Otherwise, the entire `switch` statement's expression is safe to return. + ## Drawbacks [drawbacks]: #drawbacks From 1d66a5cf04a232b53c2217f1418dceed81e0f671 Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Sat, 22 Jul 2023 10:09:21 +0300 Subject: [PATCH 5/9] Update grammar adjustment information + fix words --- .../ref-assignment-switch-expressions.md | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index 56fe4f54a8..fd60534319 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -18,6 +18,22 @@ The `switch` expression is meant to provide a quicker way to return values based ## Detailed design [design]: #detailed-design +### Grammar +The [grammar](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/patterns#switch-expression) needs to be updated for the switch expression's arms to support `ref` expressions: + +```diff + switch_expression_arm +- : pattern case_guard? '=>' expression ++ : pattern case_guard? '=>' switch_expression_arm_value + ; + ++ switch_expression_arm_value ++ : expression ++ | 'ref'? variable_reference ++ ; +``` + +### Semantics A `switch` expression may return a `ref` value. The returning expression, if not a `throw` expression, must be a `ref` expression. A `switch` expression that returns a `ref` value needs an extra `ref` in front of it when assigned/returned to a `ref` local. This design aligns with the current design in the ternary operator. @@ -26,7 +42,7 @@ A `switch` expression that returns a `ref` value needs an extra `ref` in front o Once a single switch arm returns a `ref` expression, all other switch arms must return `ref` expressions, unless they are `throw` expressions. Not providing a `ref` expression in a switch arm causes a compiler error. -Since all ref expressions are LValues, and the switch arms are all ref expressions, the entire result of the switch expression is also an LValue. Therefore, the entire switch expression can be passed by reference, assigned to, and returned by reference. Note that for directly assigning to the switch expression's ref result, the `ref` keyword must not be used, like normal ref locals are assigned. For example: +Since all ref expressions are LValues, and the switch arms are all ref expressions or `throw` expressions, the entire result of the switch expression is also an LValue. Therefore, the entire switch expression can be passed by reference, assigned to, and returned by reference. Note that for directly assigning to the switch expression's ref result, the `ref` keyword must not be used, like normal ref locals are assigned. For example: ```csharp // Returning by reference @@ -109,7 +125,7 @@ When not in the context of assigning the ref result of the `switch` expression, private void RefSwitchAssignLocal() { // Warning: - // the switch statement returns by reference but the result is immediately dereferenced + // the switch expression returns by reference but the result is immediately dereferenced int dimension = axis switch { Axis.X => ref X, @@ -118,7 +134,7 @@ private void RefSwitchAssignLocal() } ``` -Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch statement is unsafe to return. Otherwise, the entire `switch` statement's expression is safe to return. +Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch expression is unsafe to return. Otherwise, the entire `switch` expression's result is safe to return. ## Drawbacks [drawbacks]: #drawbacks From 24caf81c677f25e1bfa9db0ecceaad2050f0a244 Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Sat, 22 Jul 2023 14:24:43 +0300 Subject: [PATCH 6/9] Promote ref discard to error --- proposals/ref-assignment-switch-expressions.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index fd60534319..3d05b1a35d 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -120,12 +120,11 @@ void M(Axis axis, ref int x, in int y) } ``` -When not in the context of assigning the ref result of the `switch` expression, not using the `ref` keyword in front of the switch expression is considered a logical error. Thus, it is advised to show a warning covering that case, like in the example: +When not in the context of assigning the ref result of the `switch` expression, not using the `ref` keyword in front of the switch expression is considered a logical error. Thus, it is an error, like in the example: ```csharp private void RefSwitchAssignLocal() { - // Warning: - // the switch expression returns by reference but the result is immediately dereferenced + // Error: The switch expression returns a reference, which cannot be immediately discarded int dimension = axis switch { Axis.X => ref X, @@ -134,6 +133,8 @@ private void RefSwitchAssignLocal() } ``` +> Note: this does not align with the current behavior of ref ternary expressions (`a ? ref b : ref c`). This is intentional, and the handling of this case in ref ternary expressions is a separate concern. + Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch expression is unsafe to return. Otherwise, the entire `switch` expression's result is safe to return. ## Drawbacks From 07838298c76390c8a8b45df4019551b6740694e7 Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Mon, 14 Aug 2023 11:57:48 +0300 Subject: [PATCH 7/9] More rules --- .../ref-assignment-switch-expressions.md | 43 +++++++++++++++++-- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index 3d05b1a35d..49f4f63d02 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -42,6 +42,23 @@ A `switch` expression that returns a `ref` value needs an extra `ref` in front o Once a single switch arm returns a `ref` expression, all other switch arms must return `ref` expressions, unless they are `throw` expressions. Not providing a `ref` expression in a switch arm causes a compiler error. +For all `ref` expressions, the type of the expression must be exactly the same. No conversions are applicable in this context. For example: + +```csharp +private void InvalidConversion(Axis axis) +{ + int x = 0; + long y = 0; + ref int dimension = ref axis switch + { + Axis.X => ref x, + Axis.Y => ref y, // Error: The expression must be of type 'int' to match the common ref type + }; +} +``` + +In the above example, `int` could be resolved as the best common type due to ordering of the arms, but there is no restriction as to how to resolve the best common type in case of a tie for `ref` switch expressions. Either of the two types above could be considered the best common type, and the mismatching expression would bear the error. + Since all ref expressions are LValues, and the switch arms are all ref expressions or `throw` expressions, the entire result of the switch expression is also an LValue. Therefore, the entire switch expression can be passed by reference, assigned to, and returned by reference. Note that for directly assigning to the switch expression's ref result, the `ref` keyword must not be used, like normal ref locals are assigned. For example: ```csharp @@ -56,7 +73,7 @@ private ref int GetDirectionField(Direction direction) => ref direction switch }; // Assigning to a ref local -private void RefSwitchAssignLocal() +private void RefSwitchAssignLocal(Axis axis) { ref int dimension = ref axis switch { @@ -66,7 +83,7 @@ private void RefSwitchAssignLocal() } // Assigning to the ref of the switch expression -private void RefSwitchAssignDirectly(int value) +private void RefSwitchAssignDirectly(Axis axis, int value) { axis switch { @@ -84,7 +101,27 @@ private void RefSwitchAssignDirectly(int value) } ``` -Note that, a switch arm can only return a `ref` to a read-only reference if the switch expression is assigned to a `ref readonly` symbol. Consider the example: +Compound assignments with the result of a `ref`-returning `switch` expression on the LHS are permitted, for example: +```csharp +private void RefSwitchCompoundAssignment(Axis axis, int value) +{ + axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + } += value; + + // Equivalent to: + ref int dimension = ref axis switch + { + Axis.X => ref X, + Axis.Y => ref Y, + }; + dimension += value; +} +``` + +Note that, a switch arm can only return a `ref` to a read-only reference if the switch expression is assigned to a `ref readonly` expression. Consider the example: ```csharp void M(Axis axis, ref int x, in int y) { From f2bfc62847598ad9b564b80e689cdce2f3142b6c Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Mon, 14 Aug 2023 12:22:13 +0300 Subject: [PATCH 8/9] Clarify default switch arm --- proposals/ref-assignment-switch-expressions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index 49f4f63d02..16731c51e8 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -40,6 +40,8 @@ A `switch` expression that returns a `ref` value needs an extra `ref` in front o `throw` expressions can still be used normally, and pose no effect on the return type of the `switch` expression. +The default case arm can be omitted, and will throw, behaving in the same manner as switch expressions that do not return a `ref` value. + Once a single switch arm returns a `ref` expression, all other switch arms must return `ref` expressions, unless they are `throw` expressions. Not providing a `ref` expression in a switch arm causes a compiler error. For all `ref` expressions, the type of the expression must be exactly the same. No conversions are applicable in this context. For example: From ef422c43daa0b6626ba780176840584fb7045093 Mon Sep 17 00:00:00 2001 From: Rekkonnect Date: Wed, 23 Aug 2023 20:01:56 +0300 Subject: [PATCH 9/9] Improve ref safety description --- .../ref-assignment-switch-expressions.md | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/proposals/ref-assignment-switch-expressions.md b/proposals/ref-assignment-switch-expressions.md index 16731c51e8..7096bcca73 100644 --- a/proposals/ref-assignment-switch-expressions.md +++ b/proposals/ref-assignment-switch-expressions.md @@ -174,7 +174,45 @@ private void RefSwitchAssignLocal() > Note: this does not align with the current behavior of ref ternary expressions (`a ? ref b : ref c`). This is intentional, and the handling of this case in ref ternary expressions is a separate concern. -Ref return safety relies on the individual switch arms. If any of the switch arms that does not throw is unsafe to return, the entire switch expression is unsafe to return. Otherwise, the entire `switch` expression's result is safe to return. +The scope of the returned expression relies on the narrowest scope of each individual arm that is not a throw expression. That means, the scope of ref safety, and the scope of the actual value are both taken into account, and the narrowest of all is applied to the entire switch expression. This rule is similar to ref ternary expressions. + +For example, the following is unsafe to return: +```csharp +private void RefSwitchNarrowScope(ref int paramRef) +{ + int x = 1; + int outer = 2; + + // outerRef contains a reference to the narrowest scope, + // which is that of 'x' and 'outer' + ref int outerRef = ref axis switch + { + Axis.X => ref x, + Axis.Y => ref outer, + }; + + { + int inner = 3; + + // innerRef contains a reference to the narrowest scope, + // which is that of 'inner' + ref int innerRef = ref axis switch + { + Axis.X => ref x, + Axis.Y => ref inner, + }; + + // 'innerRef' holds a reference to a narrower scope than + // that of 'outerRef', so the following is illegal + outerRef = ref innerRef; + } + + // The scope of 'paramRef' is outer than that of the current method + // 'outerRef' holds a reference to a scope within the method, + // so the following is illegal + paramRef = ref outerRef; +} +``` ## Drawbacks [drawbacks]: #drawbacks