Browse Source

Initial implementation of the pattern matching transform.

pull/2461/head
Daniel Grunwald 4 years ago
parent
commit
040ab41c69
  1. 1
      ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj
  2. 6
      ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs
  3. 2
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/OutVariables.cs
  4. 36
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/PatternMatching.cs
  5. 1
      ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs
  6. 5
      ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs
  7. 1
      ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
  8. 16
      ICSharpCode.Decompiler/IL/Instructions/MatchInstruction.cs
  9. 73
      ICSharpCode.Decompiler/IL/Transforms/PatternMatchingTransform.cs
  10. 2
      ICSharpCode.Decompiler/IL/Transforms/StatementTransform.cs

1
ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj

@ -107,6 +107,7 @@ @@ -107,6 +107,7 @@
<Compile Include="TestCases\Correctness\DeconstructionTests.cs" />
<Compile Include="TestCases\Correctness\DynamicTests.cs" />
<Compile Include="TestCases\Correctness\StringConcat.cs" />
<Compile Include="TestCases\Pretty\PatternMatching.cs" />
<Compile Include="TestCases\VBPretty\VBPropertiesTest.cs" />
<None Include="TestCases\ILPretty\Issue2260SwitchString.cs" />
<None Include="TestCases\Pretty\Records.cs" />

6
ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs

@ -304,6 +304,12 @@ namespace ICSharpCode.Decompiler.Tests @@ -304,6 +304,12 @@ namespace ICSharpCode.Decompiler.Tests
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void PatternMatching([ValueSource(nameof(roslyn2OrNewerOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void InitializerTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{

2
ICSharpCode.Decompiler.Tests/TestCases/Pretty/OutVariables.cs

@ -21,7 +21,7 @@ using System.Collections.Generic; @@ -21,7 +21,7 @@ using System.Collections.Generic;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class PatternMatching
public class OutVariables
{
public static void OutVarInShortCircuit(Dictionary<int, string> d)
{

36
ICSharpCode.Decompiler.Tests/TestCases/Pretty/PatternMatching.cs

@ -0,0 +1,36 @@ @@ -0,0 +1,36 @@
using System;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class PatternMatching
{
public bool SimpleTypePattern(object x)
{
Use(x is string y);
if (x is string z)
{
Console.WriteLine(z);
}
return x is string w;
}
public bool SimpleTypePatternWithShortcircuit(object x)
{
Use(F() && x is string y && y.Contains("a"));
if (F() && x is string z && z.Contains("a"))
{
Console.WriteLine(z);
}
return F() && x is string w && w.Contains("a");
}
private bool F()
{
return true;
}
private void Use(bool x)
{
}
}
}

1
ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs

@ -136,6 +136,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -136,6 +136,7 @@ namespace ICSharpCode.Decompiler.CSharp
// Inlining must be first, because it doesn't trigger re-runs.
// Any other transform that opens up new inlining opportunities should call RequestRerun().
new ExpressionTransforms(),
new PatternMatchingTransform(),
new DynamicIsEventAssignmentTransform(),
new TransformAssignment(), // inline and compound assignments
new NullCoalescingTransform(),

5
ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs

@ -4338,6 +4338,11 @@ namespace ICSharpCode.Decompiler.CSharp @@ -4338,6 +4338,11 @@ namespace ICSharpCode.Decompiler.CSharp
}
}
protected internal override TranslatedExpression VisitMatchInstruction(MatchInstruction inst, TranslationContext context)
{
throw new NotImplementedException();
}
protected internal override TranslatedExpression VisitInvalidBranch(InvalidBranch inst, TranslationContext context)
{
string message = "Error";

1
ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj

@ -93,6 +93,7 @@ @@ -93,6 +93,7 @@
<Compile Include="IL\ControlFlow\AwaitInFinallyTransform.cs" />
<Compile Include="IL\Transforms\IntroduceNativeIntTypeOnLocals.cs" />
<Compile Include="IL\Transforms\LdLocaDupInitObjTransform.cs" />
<Compile Include="IL\Transforms\PatternMatchingTransform.cs" />
<Compile Include="Metadata\ReferenceLoadInfo.cs" />
<Compile Include="Semantics\OutVarResolveResult.cs" />
<Compile Include="SingleFileBundle.cs" />

16
ICSharpCode.Decompiler/IL/Instructions/MatchInstruction.cs

@ -84,7 +84,7 @@ namespace ICSharpCode.Decompiler.IL @@ -84,7 +84,7 @@ namespace ICSharpCode.Decompiler.IL
comp(deconstruct.result1(c) == 1),
match.type[D].deconstruct(d = deconstruct.result2(c)) {
comp(deconstruct.result1(d) == 2),
comp(deconstruct.result2(d) == 2),
comp(deconstruct.result2(d) == 3),
}
}
*/
@ -126,10 +126,15 @@ namespace ICSharpCode.Decompiler.IL @@ -126,10 +126,15 @@ namespace ICSharpCode.Decompiler.IL
testedOperand = m.testedOperand;
return true;
case Comp comp:
testedOperand = comp.Left;
return IsConstant(comp.Right);
case ILInstruction logicNot when logicNot.MatchLogicNot(out var operand):
return IsPatternMatch(operand, out testedOperand);
if (comp.MatchLogicNot(out var operand))
{
return IsPatternMatch(operand, out testedOperand);
}
else
{
testedOperand = comp.Left;
return IsConstant(comp.Right);
}
default:
testedOperand = null;
return false;
@ -145,6 +150,7 @@ namespace ICSharpCode.Decompiler.IL @@ -145,6 +150,7 @@ namespace ICSharpCode.Decompiler.IL
OpCode.LdcI4 => true,
OpCode.LdcI8 => true,
OpCode.LdNull => true,
OpCode.LdStr => true,
_ => false
};
}

73
ICSharpCode.Decompiler/IL/Transforms/PatternMatchingTransform.cs

@ -0,0 +1,73 @@ @@ -0,0 +1,73 @@
// Copyright (c) 2021 Daniel Grunwald, Siegfried Pammer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
namespace ICSharpCode.Decompiler.IL.Transforms
{
class PatternMatchingTransform : IStatementTransform
{
/// <summary>
/// stloc V(isinst T(testedOperand))
/// call Use(..., comp.o(ldloc V != ldnull))
/// =>
/// call Use(..., match.type[T](V = testedOperand))
/// </summary>
void IStatementTransform.Run(Block block, int pos, StatementTransformContext context)
{
if (pos + 1 >= block.Instructions.Count)
return;
if (block.Instructions[pos] is not StLoc
{
Variable: var v,
Value: IsInst { Argument: var testedOperand, Type: var type }
})
{
return;
}
if (!v.IsSingleDefinition)
return;
if (v.Kind is not (VariableKind.Local or VariableKind.StackSlot))
return;
if (!v.Type.Equals(type))
return;
var result = ILInlining.FindLoadInNext(block.Instructions[pos + 1], v, testedOperand, InliningOptions.None);
if (result.Type != ILInlining.FindResultType.Found)
return;
if (result.LoadInst is not LdLoc)
return;
if (!result.LoadInst.Parent!.MatchCompNotEqualsNull(out _))
return;
context.Step($"Type pattern matching {v.Name}", block.Instructions[pos]);
// call Use(..., match.type[T](V = testedOperand))
var target = result.LoadInst.Parent;
var matchInstruction = new MatchInstruction(v, testedOperand) {
CheckNotNull = true,
CheckType = true
};
target.ReplaceWith(matchInstruction.WithILRange(target));
block.Instructions.RemoveAt(pos);
v.Kind = VariableKind.PatternLocal;
}
}
}

2
ICSharpCode.Decompiler/IL/Transforms/StatementTransform.cs

@ -16,6 +16,8 @@ @@ -16,6 +16,8 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#nullable enable
using System;
using System.Diagnostics;

Loading…
Cancel
Save