Skip to content

Commit 1677b3b

Browse files
Fix #3382: Support compiler-generated throw-helper invocations in switch-expression implicit default-case.
1 parent 0096994 commit 1677b3b

File tree

6 files changed

+151
-4
lines changed

6 files changed

+151
-4
lines changed

ICSharpCode.Decompiler.Tests/TestCases/Pretty/SwitchExpressions.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
// DEALINGS IN THE SOFTWARE.
1818

1919
using System;
20+
#if !ROSLYN4
21+
using System.Runtime.CompilerServices;
22+
#endif
2023

2124
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
2225
{
@@ -159,5 +162,15 @@ public static string Issue2222()
159162
_ => "default",
160163
};
161164
}
165+
public static int Issue3382(StringComparison c)
166+
{
167+
return c switch {
168+
StringComparison.Ordinal => 0,
169+
StringComparison.OrdinalIgnoreCase => 1,
170+
#if !ROSLYN4
171+
_ => throw new SwitchExpressionException(c),
172+
#endif
173+
};
174+
}
162175
}
163176
}

ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ public static List<IILTransform> GetILTransforms()
106106
new SwitchDetection(),
107107
new SwitchOnStringTransform(),
108108
new SwitchOnNullableTransform(),
109+
new SwitchExpressionDefaultCaseTransform(),
109110
new SplitVariables(), // split variables once again, because SwitchOnNullableTransform eliminates ldloca
110111
new IntroduceRefReadOnlyModifierOnLocals(),
111112
new BlockILTransform { // per-block transforms

ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4031,10 +4031,13 @@ protected internal override TranslatedExpression VisitSwitchInstruction(SwitchIn
40314031
switchExpr.SwitchSections.Add(ses);
40324032
}
40334033

4034-
var defaultSES = new SwitchExpressionSection();
4035-
defaultSES.Pattern = new IdentifierExpression("_");
4036-
defaultSES.Body = TranslateSectionBody(defaultSection);
4037-
switchExpr.SwitchSections.Add(defaultSES);
4034+
if (!defaultSection.IsCompilerGeneratedDefaultSection)
4035+
{
4036+
var defaultSES = new SwitchExpressionSection();
4037+
defaultSES.Pattern = new IdentifierExpression("_");
4038+
defaultSES.Body = TranslateSectionBody(defaultSection);
4039+
switchExpr.SwitchSections.Add(defaultSES);
4040+
}
40384041

40394042
return switchExpr.WithILInstruction(inst).WithRR(new ResolveResult(resultType));
40404043

ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@
103103
<Compile Include="CSharp\Annotations.cs" />
104104
<Compile Include="CSharp\CallBuilder.cs" />
105105
<Compile Include="CSharp\CSharpLanguageVersion.cs" />
106+
<Compile Include="IL\Transforms\SwitchExpressionDefaultCaseTransform.cs" />
106107
<Compile Include="CSharp\Syntax\Expressions\RecursivePatternExpression.cs" />
107108
<Compile Include="DecompilationProgress.cs" />
108109
<Compile Include="Disassembler\IEntityProcessor.cs" />

ICSharpCode.Decompiler/IL/Instructions/SwitchInstruction.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ public SwitchSection()
202202
/// </summary>
203203
public bool HasNullLabel { get; set; }
204204

205+
/// <summary>
206+
/// If true, this section only contains a compiler-generated throw helper
207+
/// used in a switch expression and will not be visible in the decompiled source code.
208+
/// </summary>
209+
public bool IsCompilerGeneratedDefaultSection { get; set; }
210+
205211
/// <summary>
206212
/// The set of labels that cause execution to jump to this switch section.
207213
/// </summary>
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
// Copyright (c) 2025 Siegfried Pammer
2+
//
3+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4+
// software and associated documentation files (the "Software"), to deal in the Software
5+
// without restriction, including without limitation the rights to use, copy, modify, merge,
6+
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7+
// to whom the Software is furnished to do so, subject to the following conditions:
8+
//
9+
// The above copyright notice and this permission notice shall be included in all copies or
10+
// substantial portions of the Software.
11+
//
12+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13+
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14+
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15+
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16+
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17+
// DEALINGS IN THE SOFTWARE.
18+
19+
#nullable enable
20+
21+
using System;
22+
using System.Diagnostics.CodeAnalysis;
23+
using System.Linq;
24+
25+
using ICSharpCode.Decompiler.TypeSystem;
26+
using ICSharpCode.Decompiler.Util;
27+
28+
namespace ICSharpCode.Decompiler.IL.Transforms
29+
{
30+
// call ThrowInvalidOperationException()
31+
// leave IL_0000 (ldloc temp)
32+
//
33+
// The second pattern allows inlining in the subsequent uses.
34+
class SwitchExpressionDefaultCaseTransform : IILTransform
35+
{
36+
void IILTransform.Run(ILFunction function, ILTransformContext context)
37+
{
38+
IMethod? FindConstructor(string fullTypeName, params Type[] argumentTypes)
39+
{
40+
IType exceptionType = context.TypeSystem.FindType(new FullTypeName(fullTypeName));
41+
var types = argumentTypes.SelectArray(context.TypeSystem.FindType);
42+
43+
foreach (var ctor in exceptionType.GetConstructors(m => !m.IsStatic && m.Parameters.Count == argumentTypes.Length))
44+
{
45+
bool found = true;
46+
foreach (var pair in ctor.Parameters.Select(p => p.Type).Zip(types))
47+
{
48+
if (!NormalizeTypeVisitor.IgnoreNullability.EquivalentTypes(pair.Item1, pair.Item2))
49+
{
50+
found = false;
51+
break;
52+
}
53+
}
54+
if (found)
55+
return ctor;
56+
}
57+
58+
return null;
59+
}
60+
61+
IMethod[] exceptionCtorTable = new IMethod[2];
62+
63+
exceptionCtorTable[0] = FindConstructor("System.InvalidOperationException")!;
64+
exceptionCtorTable[1] = FindConstructor("System.Runtime.CompilerServices.SwitchExpressionException", typeof(object))!;
65+
66+
if (exceptionCtorTable[0] == null && exceptionCtorTable[1] == null)
67+
return;
68+
69+
bool MatchThrowHelperCall(ILInstruction inst, [NotNullWhen(true)] out IMethod? exceptionCtor, out ILInstruction? value)
70+
{
71+
exceptionCtor = null;
72+
value = null;
73+
if (inst is not Call call)
74+
return false;
75+
if (call.Method.DeclaringType.FullName != "<PrivateImplementationDetails>")
76+
return false;
77+
switch (call.Arguments.Count)
78+
{
79+
case 0:
80+
if (call.Method.Name != "ThrowInvalidOperationException")
81+
return false;
82+
exceptionCtor = exceptionCtorTable[0];
83+
break;
84+
case 1:
85+
if (call.Method.Name != "ThrowSwitchExpressionException")
86+
return false;
87+
exceptionCtor = exceptionCtorTable[1];
88+
value = call.Arguments[0];
89+
break;
90+
default:
91+
return false;
92+
}
93+
return exceptionCtor != null;
94+
}
95+
96+
foreach (var block in function.Descendants.OfType<Block>())
97+
{
98+
if (block.Parent is not BlockContainer container)
99+
continue;
100+
if (container.EntryPoint is not { IncomingEdgeCount: 1, Instructions: [SwitchInstruction inst] })
101+
continue;
102+
if (block.Instructions.Count != 2 || block.IncomingEdgeCount != 1 || !block.FinalInstruction.MatchNop())
103+
continue;
104+
var defaultSection = inst.GetDefaultSection();
105+
if (defaultSection.Body != block && (defaultSection.Body is not Branch b || b.TargetBlock != block))
106+
continue;
107+
if (!MatchThrowHelperCall(block.Instructions[0], out IMethod? exceptionCtor, out ILInstruction? value))
108+
continue;
109+
if (block.Instructions[1] is not Leave { Value: LdLoc { Variable: { Kind: VariableKind.Local or VariableKind.StackSlot, LoadCount: 1, InitialValueIsInitialized: true } } })
110+
{
111+
continue;
112+
}
113+
context.Step("SwitchExpressionDefaultCaseTransform", block.Instructions[0]);
114+
var newObj = new NewObj(exceptionCtor);
115+
if (value != null)
116+
newObj.Arguments.Add(value);
117+
block.Instructions[0] = new Throw(newObj).WithILRange(block.Instructions[0]).WithILRange(block.Instructions[1]);
118+
block.Instructions.RemoveAt(1);
119+
defaultSection.IsCompilerGeneratedDefaultSection = true;
120+
}
121+
}
122+
}
123+
}

0 commit comments

Comments
 (0)