Skip to content

Commit 37f3d0b

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

File tree

6 files changed

+158
-4
lines changed

6 files changed

+158
-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: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
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+
// -or-
34+
//
35+
// call ThrowSwitchExpressionException(...)
36+
// leave IL_0000 (ldloc temp)
37+
//
38+
// -to-
39+
//
40+
// throw(newobj SwitchExpressionException(...))
41+
class SwitchExpressionDefaultCaseTransform : IILTransform
42+
{
43+
void IILTransform.Run(ILFunction function, ILTransformContext context)
44+
{
45+
IMethod? FindConstructor(string fullTypeName, params Type[] argumentTypes)
46+
{
47+
IType exceptionType = context.TypeSystem.FindType(new FullTypeName(fullTypeName));
48+
var types = argumentTypes.SelectArray(context.TypeSystem.FindType);
49+
50+
foreach (var ctor in exceptionType.GetConstructors(m => !m.IsStatic && m.Parameters.Count == argumentTypes.Length))
51+
{
52+
bool found = true;
53+
foreach (var pair in ctor.Parameters.Select(p => p.Type).Zip(types))
54+
{
55+
if (!NormalizeTypeVisitor.IgnoreNullability.EquivalentTypes(pair.Item1, pair.Item2))
56+
{
57+
found = false;
58+
break;
59+
}
60+
}
61+
if (found)
62+
return ctor;
63+
}
64+
65+
return null;
66+
}
67+
68+
IMethod[] exceptionCtorTable = new IMethod[2];
69+
70+
exceptionCtorTable[0] = FindConstructor("System.InvalidOperationException")!;
71+
exceptionCtorTable[1] = FindConstructor("System.Runtime.CompilerServices.SwitchExpressionException", typeof(object))!;
72+
73+
if (exceptionCtorTable[0] == null && exceptionCtorTable[1] == null)
74+
return;
75+
76+
bool MatchThrowHelperCall(ILInstruction inst, [NotNullWhen(true)] out IMethod? exceptionCtor, out ILInstruction? value)
77+
{
78+
exceptionCtor = null;
79+
value = null;
80+
if (inst is not Call call)
81+
return false;
82+
if (call.Method.DeclaringType.FullName != "<PrivateImplementationDetails>")
83+
return false;
84+
switch (call.Arguments.Count)
85+
{
86+
case 0:
87+
if (call.Method.Name != "ThrowInvalidOperationException")
88+
return false;
89+
exceptionCtor = exceptionCtorTable[0];
90+
break;
91+
case 1:
92+
if (call.Method.Name != "ThrowSwitchExpressionException")
93+
return false;
94+
exceptionCtor = exceptionCtorTable[1];
95+
value = call.Arguments[0];
96+
break;
97+
default:
98+
return false;
99+
}
100+
return exceptionCtor != null;
101+
}
102+
103+
foreach (var block in function.Descendants.OfType<Block>())
104+
{
105+
if (block.Parent is not BlockContainer container)
106+
continue;
107+
if (container.EntryPoint is not { IncomingEdgeCount: 1, Instructions: [SwitchInstruction inst] })
108+
continue;
109+
if (block.Instructions.Count != 2 || block.IncomingEdgeCount != 1 || !block.FinalInstruction.MatchNop())
110+
continue;
111+
var defaultSection = inst.GetDefaultSection();
112+
if (defaultSection.Body != block && (defaultSection.Body is not Branch b || b.TargetBlock != block))
113+
continue;
114+
if (!MatchThrowHelperCall(block.Instructions[0], out IMethod? exceptionCtor, out ILInstruction? value))
115+
continue;
116+
if (block.Instructions[1] is not Leave { Value: LdLoc { Variable: { Kind: VariableKind.Local or VariableKind.StackSlot, LoadCount: 1, InitialValueIsInitialized: true } } })
117+
{
118+
continue;
119+
}
120+
context.Step("SwitchExpressionDefaultCaseTransform", block.Instructions[0]);
121+
var newObj = new NewObj(exceptionCtor);
122+
if (value != null)
123+
newObj.Arguments.Add(value);
124+
block.Instructions[0] = new Throw(newObj).WithILRange(block.Instructions[0]).WithILRange(block.Instructions[1]);
125+
block.Instructions.RemoveAt(1);
126+
defaultSection.IsCompilerGeneratedDefaultSection = true;
127+
}
128+
}
129+
}
130+
}

0 commit comments

Comments
 (0)