Browse Source

Merge branch 'master' of https://github.com/icsharpcode/ILSpy into avalondock

pull/1801/head
Siegfried Pammer 7 years ago
parent
commit
58cb72e65d
  1. 2
      BuildTools/update-assemblyinfo.ps1
  2. 10
      ICSharpCode.Decompiler.Tests/CorrectnessTestRunner.cs
  3. 2
      ICSharpCode.Decompiler.Tests/Helpers/RemoveCompilerAttribute.cs
  4. 49
      ICSharpCode.Decompiler.Tests/Helpers/Tester.cs
  5. 8
      ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj
  6. 6
      ICSharpCode.Decompiler.Tests/ILPrettyTestRunner.cs
  7. 20
      ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs
  8. 60
      ICSharpCode.Decompiler.Tests/TestCases/Correctness/FloatingPointArithmetic.cs
  9. 9
      ICSharpCode.Decompiler.Tests/TestCases/Correctness/TrickyTypes.cs
  10. 2
      ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Debug.cs
  11. 2
      ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Release.cs
  12. 2
      ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1325.cs
  13. 19
      ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.cs
  14. 36
      ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.il
  15. 13
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/Async.cs
  16. 65
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncStreams.cs
  17. 60
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncUsing.cs
  18. 572
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/CompoundAssignmentTest.cs
  19. 76
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/CustomTaskType.cs
  20. 39
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/DelegateConstruction.cs
  21. 3
      ICSharpCode.Decompiler.Tests/TestCases/Pretty/InterfaceTests.cs
  22. 10
      ICSharpCode.Decompiler/CSharp/Annotations.cs
  23. 8
      ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs
  24. 9
      ICSharpCode.Decompiler/CSharp/CallBuilder.cs
  25. 31
      ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs
  26. 52
      ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs
  27. 398
      ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs
  28. 54
      ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs
  29. 17
      ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs
  30. 11
      ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs
  31. 190
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs
  32. 32
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs
  33. 5
      ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs
  34. 20
      ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs
  35. 2
      ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs
  36. 186
      ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs
  37. 60
      ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs
  38. 44
      ICSharpCode.Decompiler/CSharp/StatementBuilder.cs
  39. 450
      ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs
  40. 6
      ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs
  41. 2
      ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs
  42. 2
      ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs
  43. 96
      ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs
  44. 4
      ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs
  45. 2
      ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs
  46. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Backreference.cs
  47. 4
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Choice.cs
  48. 4
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs
  49. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/NamedNode.cs
  50. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/OptionalNode.cs
  51. 2
      ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs
  52. 6
      ICSharpCode.Decompiler/CSharp/Syntax/Role.cs
  53. 2
      ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs
  54. 60
      ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs
  55. 18
      ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs
  56. 2
      ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs
  57. 2
      ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs
  58. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs
  59. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs
  60. 2
      ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs
  61. 4
      ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs
  62. 2
      ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs
  63. 2
      ICSharpCode.Decompiler/DecompilerException.cs
  64. 38
      ICSharpCode.Decompiler/DecompilerSettings.cs
  65. 10
      ICSharpCode.Decompiler/Documentation/IdStringProvider.cs
  66. 4
      ICSharpCode.Decompiler/Documentation/XmlDocumentationElement.cs
  67. 13
      ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs
  68. 1
      ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj
  69. 576
      ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs
  70. 218
      ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs
  71. 242
      ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs
  72. 6
      ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs
  73. 16
      ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs
  74. 2
      ICSharpCode.Decompiler/IL/ILReader.cs
  75. 21
      ICSharpCode.Decompiler/IL/ILTypeExtensions.cs
  76. 21
      ICSharpCode.Decompiler/IL/Instructions/Block.cs
  77. 2
      ICSharpCode.Decompiler/IL/Instructions/CallIndirect.cs
  78. 2
      ICSharpCode.Decompiler/IL/Instructions/CompoundAssignmentInstruction.cs
  79. 5
      ICSharpCode.Decompiler/IL/Instructions/Conv.cs
  80. 8
      ICSharpCode.Decompiler/IL/Instructions/UsingInstruction.cs
  81. 11
      ICSharpCode.Decompiler/IL/PrimitiveType.cs
  82. 11
      ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs
  83. 13
      ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs
  84. 4
      ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs
  85. 2
      ICSharpCode.Decompiler/IL/Transforms/TransformDisplayClassUsage.cs
  86. 107
      ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs
  87. 2
      ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs
  88. 30
      ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs
  89. 34
      ICSharpCode.Decompiler/Metadata/UniversalAssemblyResolver.cs
  90. 4
      ICSharpCode.Decompiler/Semantics/ArrayAccessResolveResult.cs
  91. 2
      ICSharpCode.Decompiler/Semantics/ArrayCreateResolveResult.cs
  92. 6
      ICSharpCode.Decompiler/Semantics/Conversion.cs
  93. 4
      ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs
  94. 8
      ICSharpCode.Decompiler/Semantics/ForEachResolveResult.cs
  95. 2
      ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs
  96. 8
      ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs
  97. 4
      ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs
  98. 2
      ICSharpCode.Decompiler/Semantics/ResolveResult.cs
  99. 2
      ICSharpCode.Decompiler/Semantics/SizeOfResolveResult.cs
  100. 4
      ICSharpCode.Decompiler/Semantics/TypeIsResolveResult.cs
  101. Some files were not shown because too many files have changed in this diff Show More

2
BuildTools/update-assemblyinfo.ps1

@ -53,7 +53,7 @@ function gitCommitHash() { @@ -53,7 +53,7 @@ function gitCommitHash() {
}
function gitBranch() {
if (-not ((Test-Dir ".git") -and (Find-Git))) {
if (-not ((Test-Dir ".git" -or Test-File ".git") -and (Find-Git))) {
return "no-branch";
}

10
ICSharpCode.Decompiler.Tests/CorrectnessTestRunner.cs

@ -83,8 +83,14 @@ namespace ICSharpCode.Decompiler.Tests @@ -83,8 +83,14 @@ namespace ICSharpCode.Decompiler.Tests
}
[Test]
public void FloatingPointArithmetic([ValueSource("defaultOptions")] CompilerOptions options)
{
public void FloatingPointArithmetic([ValueSource("noMonoOptions")] CompilerOptions options, [Values(32, 64)] int bits)
{
// The behavior of the #1794 incorrect `(float)(double)val` cast only causes test failures
// for some runtime+compiler combinations.
if (bits == 32)
options |= CompilerOptions.Force32Bit;
// Mono is excluded because we never use it for the second pass, so the test ends up failing
// due to some Mono vs. Roslyn compiler differences.
RunCS(options: options);
}

2
ICSharpCode.Decompiler.Tests/Helpers/RemoveCompilerAttribute.cs

@ -13,7 +13,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -13,7 +13,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
var section = (AttributeSection)attribute.Parent;
SimpleType type = attribute.Type as SimpleType;
if (section.AttributeTarget == "assembly" &&
(type.Identifier == "CompilationRelaxations" || type.Identifier == "RuntimeCompatibility" || type.Identifier == "SecurityPermission" || type.Identifier == "PermissionSet" || type.Identifier == "AssemblyVersion" || type.Identifier == "Debuggable"))
(type.Identifier == "CompilationRelaxations" || type.Identifier == "RuntimeCompatibility" || type.Identifier == "SecurityPermission" || type.Identifier == "PermissionSet" || type.Identifier == "AssemblyVersion" || type.Identifier == "Debuggable" || type.Identifier == "TargetFramework"))
{
attribute.Remove();
if (section.Attributes.Count == 0)

49
ICSharpCode.Decompiler.Tests/Helpers/Tester.cs

@ -55,6 +55,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -55,6 +55,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
UseRoslyn = 0x10,
UseMcs = 0x20,
ReferenceVisualBasic = 0x40,
ReferenceCore = 0x80,
}
[Flags]
@ -89,12 +90,12 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -89,12 +90,12 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
outputFile += ".exe";
otherOptions += "/exe ";
}
if (options.HasFlag(AssemblerOptions.UseDebug)) {
otherOptions += "/debug ";
}
ProcessStartInfo info = new ProcessStartInfo(ilasmPath);
info.Arguments = $"/nologo {otherOptions}/output=\"{outputFile}\" \"{sourceFileName}\"";
info.RedirectStandardError = true;
@ -115,7 +116,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -115,7 +116,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
return outputFile;
}
public static string Disassemble(string sourceFileName, string outputFile, AssemblerOptions asmOptions)
{
if (asmOptions.HasFlag(AssemblerOptions.UseOwnDisassembler)) {
@ -141,7 +142,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -141,7 +142,7 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
}
string ildasmPath = SdkUtility.GetSdkPath("ildasm.exe");
ProcessStartInfo info = new ProcessStartInfo(ildasmPath);
info.Arguments = $"/nobar /utf8 /out=\"{outputFile}\" \"{sourceFileName}\"";
info.RedirectStandardError = true;
@ -182,8 +183,10 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -182,8 +183,10 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
return Regex.Replace(il, @"'<PrivateImplementationDetails>\{[0-9A-F-]+\}'", "'<PrivateImplementationDetails>'");
}
static readonly string coreRefAsmPath = new DotNetCorePathFinder(new Version(3, 0)).GetReferenceAssemblyPath(".NETCoreApp, Version = v3.0");
static readonly string refAsmPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
@"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2");
@"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2");
static readonly string thisAsmPath = Path.GetDirectoryName(typeof(Tester).Assembly.Location);
static readonly Lazy<IEnumerable<MetadataReference>> defaultReferences = new Lazy<IEnumerable<MetadataReference>>(delegate {
@ -202,6 +205,21 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -202,6 +205,21 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
};
});
static readonly Lazy<IEnumerable<MetadataReference>> coreDefaultReferences = new Lazy<IEnumerable<MetadataReference>>(GetDefaultReferences);
const string targetFrameworkAttributeSnippet = @"
[assembly: System.Runtime.Versioning.TargetFramework("".NETCoreApp, Version = v3.0"", FrameworkDisplayName = """")]
";
static IEnumerable<MetadataReference> GetDefaultReferences()
{
foreach (var reference in Directory.EnumerateFiles(coreRefAsmPath, "*.dll")) {
yield return MetadataReference.CreateFromFile(reference);
}
}
static readonly Lazy<IEnumerable<MetadataReference>> visualBasic = new Lazy<IEnumerable<MetadataReference>>(delegate {
return new[] {
MetadataReference.CreateFromFile(Path.Combine(refAsmPath, "Microsoft.VisualBasic.dll"))
@ -217,6 +235,9 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -217,6 +235,9 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
if (flags.HasFlag(CompilerOptions.Optimize)) {
preprocessorSymbols.Add("OPT");
}
if (flags.HasFlag(CompilerOptions.ReferenceCore)) {
preprocessorSymbols.Add("NETCORE");
}
if (flags.HasFlag(CompilerOptions.UseRoslyn)) {
preprocessorSymbols.Add("ROSLYN");
preprocessorSymbols.Add("CS60");
@ -252,7 +273,15 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -252,7 +273,15 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
languageVersion: Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8
);
var syntaxTrees = sourceFileNames.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, path: f));
var references = defaultReferences.Value;
if (flags.HasFlag(CompilerOptions.ReferenceCore)) {
syntaxTrees = syntaxTrees.Concat(new[] { SyntaxFactory.ParseSyntaxTree(targetFrameworkAttributeSnippet) });
}
IEnumerable<MetadataReference> references;
if (flags.HasFlag(CompilerOptions.ReferenceCore)) {
references = coreDefaultReferences.Value;
} else {
references = defaultReferences.Value;
}
if (flags.HasFlag(CompilerOptions.ReferenceVisualBasic)) {
references = references.Concat(visualBasic.Value);
}
@ -466,16 +495,16 @@ namespace ICSharpCode.Decompiler.Tests.Helpers @@ -466,16 +495,16 @@ namespace ICSharpCode.Decompiler.Tests.Helpers
return fileName;
}
}
public static void RunAndCompareOutput(string testFileName, string outputFile, string decompiledOutputFile, string decompiledCodeFile = null)
{
string output1, output2, error1, error2;
int result1 = Tester.Run(outputFile, out output1, out error1);
int result2 = Tester.Run(decompiledOutputFile, out output2, out error2);
Assert.AreEqual(0, result1, "Exit code != 0; did the test case crash?" + Environment.NewLine + error1);
Assert.AreEqual(0, result2, "Exit code != 0; did the decompiled code crash?" + Environment.NewLine + error2);
if (output1 != output2 || error1 != error2) {
StringBuilder b = new StringBuilder();
b.AppendLine($"Test {testFileName} failed: output does not match.");

8
ICSharpCode.Decompiler.Tests/ICSharpCode.Decompiler.Tests.csproj

@ -42,8 +42,8 @@ @@ -42,8 +42,8 @@
<ItemGroup>
<PackageReference Include="DiffLib" Version="2017.7.26.1241" />
<PackageReference Include="Microsoft.Build.Locator" Version="1.2.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.3.1" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" Version="3.3.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.4.0-beta3-final" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" Version="3.4.0-beta3-final" />
<PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="1.1.0-beta1-63314-01" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="System.Collections.Immutable" Version="1.5.0" />
@ -60,6 +60,7 @@ @@ -60,6 +60,7 @@
<None Include="TestCases\Correctness\StackTests.il" />
<None Include="TestCases\Correctness\StackTypes.il" />
<None Include="TestCases\Correctness\Uninit.vb" />
<None Include="TestCases\ILPretty\WeirdEnums.il" />
<None Include="TestCases\ILPretty\ConstantBlobs.il" />
<None Include="TestCases\ILPretty\CS1xSwitch_Debug.il" />
<None Include="TestCases\ILPretty\CS1xSwitch_Release.il" />
@ -80,7 +81,10 @@ @@ -80,7 +81,10 @@
<ItemGroup>
<Compile Include="DisassemblerPrettyTestRunner.cs" />
<Compile Include="TestCases\Correctness\StringConcat.cs" />
<None Include="TestCases\ILPretty\WeirdEnums.cs" />
<Compile Include="TestCases\ILPretty\ConstantBlobs.cs" />
<None Include="TestCases\Pretty\AsyncStreams.cs" />
<None Include="TestCases\Pretty\AsyncUsing.cs" />
<Compile Include="TestCases\Pretty\OutVariables.cs" />
<Compile Include="TestCases\Pretty\CustomTaskType.cs" />
<None Include="TestCases\Ugly\NoForEachStatement.Expected.cs" />

6
ICSharpCode.Decompiler.Tests/ILPrettyTestRunner.cs

@ -198,6 +198,12 @@ namespace ICSharpCode.Decompiler.Tests @@ -198,6 +198,12 @@ namespace ICSharpCode.Decompiler.Tests
Run(settings: new DecompilerSettings { RemoveDeadStores = true });
}
[Test]
public void WeirdEnums()
{
Run();
}
void Run([CallerMemberName] string testName = null, DecompilerSettings settings = null)
{
var ilFile = Path.Combine(TestCasePath, testName + ".il");

20
ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs

@ -59,6 +59,12 @@ namespace ICSharpCode.Decompiler.Tests @@ -59,6 +59,12 @@ namespace ICSharpCode.Decompiler.Tests
CompilerOptions.Optimize | CompilerOptions.UseRoslyn
};
static readonly CompilerOptions[] dotnetCoreOnlyOptions =
{
CompilerOptions.UseRoslyn | CompilerOptions.ReferenceCore,
CompilerOptions.Optimize | CompilerOptions.UseRoslyn | CompilerOptions.ReferenceCore
};
static readonly CompilerOptions[] defaultOptions =
{
CompilerOptions.None,
@ -301,6 +307,18 @@ namespace ICSharpCode.Decompiler.Tests @@ -301,6 +307,18 @@ namespace ICSharpCode.Decompiler.Tests
Run(cscOptions: cscOptions);
}
[Test]
public void AsyncStreams([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void AsyncUsing([ValueSource(nameof(dotnetCoreOnlyOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
}
[Test]
public void CustomTaskType([ValueSource(nameof(roslynOnlyOptions))] CompilerOptions cscOptions)
{
@ -436,7 +454,7 @@ namespace ICSharpCode.Decompiler.Tests @@ -436,7 +454,7 @@ namespace ICSharpCode.Decompiler.Tests
[Test]
public void InterfaceTests([ValueSource(nameof(defaultOptions))] CompilerOptions cscOptions)
{
RunForLibrary(cscOptions: cscOptions);
RunForLibrary(cscOptions: cscOptions | CompilerOptions.ReferenceCore);
}
[Test]

60
ICSharpCode.Decompiler.Tests/TestCases/Correctness/FloatingPointArithmetic.cs

@ -8,12 +8,13 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness @@ -8,12 +8,13 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
Issue999();
Issue1656();
Issue1794();
return 0;
}
static void Issue999()
{
for (float i = -10f; i <= 10f; i += 0.01f)
for (float i = -10f; i <= 10f; i += 0.01f)
Console.WriteLine("{1:R}: {0:R}", M(i), i);
}
@ -31,6 +32,63 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness @@ -31,6 +32,63 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
CxAssert((primary--) == 'C');
}
static void Issue1794()
{
Console.WriteLine("CastUnsignedToFloat:");
Console.WriteLine(CastUnsignedToFloat(9007199791611905).ToString("r"));
Console.WriteLine("CastUnsignedToDouble:");
Console.WriteLine(CastUnsignedToDouble(9007199791611905).ToString("r"));
Console.WriteLine("CastUnsignedToFloatViaDouble:");
Console.WriteLine(CastUnsignedToFloatViaDouble(9007199791611905).ToString("r"));
Console.WriteLine("CastSignedToFloat:");
Console.WriteLine(CastSignedToFloat(9007199791611905).ToString("r"));
Console.WriteLine("ImplicitCastSignedToFloat:");
Console.WriteLine(ImplicitCastSignedToFloat(9007199791611905).ToString("r"));
Console.WriteLine("CastSignedToDouble:");
Console.WriteLine(CastSignedToDouble(9007199791611905).ToString("r"));
Console.WriteLine("CastSignedToFloatViaDouble:");
Console.WriteLine(CastSignedToFloatViaDouble(9007199791611905).ToString("r"));
}
static float CastUnsignedToFloat(ulong val)
{
return (float)val;
}
static double CastUnsignedToDouble(ulong val)
{
return (double)val;
}
static float CastUnsignedToFloatViaDouble(ulong val)
{
// The double-rounding can increase the rounding error
return (float)(double)val;
}
static float CastSignedToFloat(long val)
{
return (float)val;
}
static double CastSignedToDouble(long val)
{
return (double)val;
}
static float CastSignedToFloatViaDouble(long val)
{
// The double-rounding can increase the rounding error
return (float)(double)val;
}
static float ImplicitCastSignedToFloat(long val)
{
return val;
}
static void CxAssert(bool v)
{
if (!v) {

9
ICSharpCode.Decompiler.Tests/TestCases/Correctness/TrickyTypes.cs

@ -17,6 +17,7 @@ @@ -17,6 +17,7 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
@ -27,6 +28,8 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness @@ -27,6 +28,8 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
InterestingConstants();
TruncatedComp();
StringConcat();
LinqNullableMin();
LinqNullableMin(1, 2, 3);
}
static void Print<T>(T val)
@ -101,5 +104,11 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness @@ -101,5 +104,11 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
Print(string.Concat(1, 2));
Print(string.Concat(1, 2, "str"));
}
static void LinqNullableMin(params int[] arr)
{
Print(string.Format("LinqNullableMin {0}:", arr.Length));
Print(arr.Min(v => (int?)v));
}
}
}

2
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Debug.cs

@ -14,14 +14,12 @@ using System.Diagnostics; @@ -14,14 +14,12 @@ using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
[assembly: FSharpInterfaceDataVersion(2, 0, 0)]
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCopyright("Copyright © 2017")]

2
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpLoops_Release.cs

@ -15,14 +15,12 @@ using System.Diagnostics; @@ -15,14 +15,12 @@ using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
[assembly: FSharpInterfaceDataVersion(2, 0, 0)]
[assembly: AssemblyTitle("ConsoleApplication1")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.1", FrameworkDisplayName = ".NET Framework 4.6.1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCopyright("Copyright © 2017")]

2
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1325.cs

@ -6,10 +6,8 @@ using System.Diagnostics; @@ -6,10 +6,8 @@ using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
[assembly: Embedded]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: TargetFramework(".NETCoreApp,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]

19
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.cs

@ -0,0 +1,19 @@ @@ -0,0 +1,19 @@
using System;
namespace TestEnum
{
public enum BooleanEnum : bool
{
Min = false,
Zero = false,
One = true,
Max = byte.MaxValue
}
public enum NativeIntEnum : IntPtr
{
Zero = 0L,
One = 1L,
FortyTwo = 42L
}
}

36
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.il

@ -0,0 +1,36 @@ @@ -0,0 +1,36 @@
// Metadata version: v4.0.30319
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly BoolEnum
{
.ver 1:0:0:0
}
.module BoolEnum.exe
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00020003 // ILONLY 32BITPREFERRED
// Image base: 0x000001C4B6C90000
.class public auto ansi sealed TestEnum.BooleanEnum
extends [mscorlib]System.Enum
{
.field public specialname rtspecialname bool value__
.field public static literal valuetype TestEnum.BooleanEnum Min = bool(false)
.field public static literal valuetype TestEnum.BooleanEnum Zero = bool(false)
.field public static literal valuetype TestEnum.BooleanEnum One = bool(true)
.field public static literal valuetype TestEnum.BooleanEnum Max = uint8(255)
}
.class public auto ansi sealed TestEnum.NativeIntEnum
extends [mscorlib]System.Enum
{
.field public specialname rtspecialname native int value__
.field public static literal valuetype TestEnum.NativeIntEnum Zero = int64(0)
.field public static literal valuetype TestEnum.NativeIntEnum One = int64(1)
.field public static literal valuetype TestEnum.NativeIntEnum FortyTwo = int64(42)
}

13
ICSharpCode.Decompiler.Tests/TestCases/Pretty/Async.cs

@ -199,6 +199,19 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty @@ -199,6 +199,19 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
#endif
}
public struct AsyncInStruct
{
private int i;
public async Task<int> Test(AsyncInStruct xx)
{
xx.i++;
i++;
await Task.Yield();
return i + xx.i;
}
}
public struct HopToThreadPoolAwaitable : INotifyCompletion
{
public bool IsCompleted {

65
ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncStreams.cs

@ -0,0 +1,65 @@ @@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class AsyncStreams
{
public static async IAsyncEnumerable<int> CountTo(int until)
{
for (int i = 0; i < until; i++) {
yield return i;
await Task.Delay(10);
}
}
public static async IAsyncEnumerable<int> AlwaysThrow()
{
throw null;
yield break;
}
public static async IAsyncEnumerator<int> InfiniteLoop()
{
while (true) {
}
yield break;
}
public static async IAsyncEnumerable<int> InfiniteLoopWithAwait()
{
while (true) {
await Task.Delay(10);
}
yield break;
}
public async IAsyncEnumerable<int> AwaitInFinally()
{
try {
Console.WriteLine("try");
yield return 1;
Console.WriteLine("end try");
} finally {
Console.WriteLine("finally");
await Task.Yield();
Console.WriteLine("end finally");
}
}
}
public struct TestStruct
{
private int i;
public async IAsyncEnumerable<int> AwaitInStruct(TestStruct xx)
{
xx.i++;
i++;
await Task.Yield();
yield return i;
yield return xx.i;
}
}
}

60
ICSharpCode.Decompiler.Tests/TestCases/Pretty/AsyncUsing.cs

@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal class AsyncUsing
{
internal class AsyncDisposableClass : IAsyncDisposable
{
public ValueTask DisposeAsync()
{
throw new NotImplementedException();
}
}
[StructLayout(LayoutKind.Sequential, Size = 1)]
internal struct AsyncDisposableStruct : IAsyncDisposable
{
public ValueTask DisposeAsync()
{
throw new NotImplementedException();
}
}
public static async void TestAsyncUsing(IAsyncDisposable disposable)
{
await using (disposable) {
Console.WriteLine("Hello");
}
}
public static async void TestAsyncUsingClass()
{
await using (AsyncDisposableClass test = new AsyncDisposableClass()) {
Use(test);
}
}
public static async void TestAsyncUsingStruct()
{
await using (AsyncDisposableStruct asyncDisposableStruct = default(AsyncDisposableStruct)) {
Use(asyncDisposableStruct);
}
}
public static async void TestAsyncUsingNullableStruct()
{
await using (AsyncDisposableStruct? asyncDisposableStruct = new AsyncDisposableStruct?(default(AsyncDisposableStruct))) {
Use(asyncDisposableStruct);
}
}
private static void Use(IAsyncDisposable test)
{
throw new NotImplementedException();
}
}
}

572
ICSharpCode.Decompiler.Tests/TestCases/Pretty/CompoundAssignmentTest.cs

File diff suppressed because it is too large Load Diff

76
ICSharpCode.Decompiler.Tests/TestCases/Pretty/CustomTaskType.cs

@ -2,11 +2,12 @@ @@ -2,11 +2,12 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class CustomTaskType
public class ValueTaskType
{
private int memberField;
@ -125,3 +126,76 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty @@ -125,3 +126,76 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
}
}
}
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.Issue1788
{
[AsyncMethodBuilder(typeof(builder))]
internal class async
{
public awaiter GetAwaiter()
{
throw null;
}
}
internal class await
{
public awaiter GetAwaiter()
{
throw null;
}
}
internal class awaiter : INotifyCompletion
{
public bool IsCompleted => true;
public void GetResult()
{
}
public void OnCompleted(Action continuation)
{
}
}
internal class builder
{
public async Task {
get {
throw null;
}
}
public static builder Create()
{
throw null;
}
public void SetResult()
{
}
public void SetException(Exception e)
{
}
public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
{
throw null;
}
public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
{
throw null;
}
public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
{
throw null;
}
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
throw null;
}
}
public class C
{
internal async async @await(@await async)
{
await async;
}
}
}

39
ICSharpCode.Decompiler.Tests/TestCases/Pretty/DelegateConstruction.cs

@ -385,5 +385,44 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty @@ -385,5 +385,44 @@ namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
return captured.FirstOrDefault();
};
}
public static Func<int> Issue1773(short data)
{
int integerData = data;
return () => integerData;
}
#if !MCS
// does not compile with mcs...
public static Func<int> Issue1773b(object data)
{
#if ROSLYN
dynamic dynamicData = data;
return () => dynamicData.DynamicCall();
#else
// This is a bug in the old csc: captured dynamic local variables did not have the [DynamicAttribute]
// on the display-class field.
return () => ((dynamic)data).DynamicCall();
#endif
}
public static Func<int> Issue1773c(object data)
{
#if ROSLYN
dynamic dynamicData = data;
return () => dynamicData;
#else
return () => (dynamic)data;
#endif
}
#endif
#if ROSLYN
public static Func<string> Issue1773d((int Integer, string String) data)
{
(int Integer, string RenamedString) valueTuple = data;
return () => valueTuple.RenamedString;
}
#endif
}
}

3
ICSharpCode.Decompiler.Tests/TestCases/Pretty/InterfaceTests.cs

@ -16,9 +16,6 @@ @@ -16,9 +16,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// We can't test this because "error CS8701: Target runtime doesn't support default interface implementation."
#undef CS80
using System;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty

10
ICSharpCode.Decompiler/CSharp/Annotations.cs

@ -41,8 +41,8 @@ namespace ICSharpCode.Decompiler.CSharp @@ -41,8 +41,8 @@ namespace ICSharpCode.Decompiler.CSharp
/// <summary>
/// Currently unused; we'll probably use the LdToken ILInstruction as annotation instead when LdToken support gets reimplemented.
/// </summary>
public class LdTokenAnnotation {}
public class LdTokenAnnotation { }
public static class AnnotationExtensions
{
internal static ExpressionWithILInstruction WithILInstruction(this Expression expression, ILInstruction instruction)
@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -98,7 +98,7 @@ namespace ICSharpCode.Decompiler.CSharp
expression.Expression.AddAnnotation(resolveResult);
return new TranslatedExpression(expression, resolveResult);
}
/// <summary>
/// Retrieves the <see cref="ISymbol"/> associated with this AstNode, or null if no symbol is associated with the node.
/// </summary>
@ -208,7 +208,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -208,7 +208,7 @@ namespace ICSharpCode.Decompiler.CSharp
return node;
}
}
/// <summary>
/// Represents a reference to a local variable.
/// </summary>
@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp
public ILVariableResolveResult(ILVariable v, IType type) : base(type)
{
this.Variable = v ?? throw new ArgumentNullException("v");
this.Variable = v ?? throw new ArgumentNullException(nameof(v));
}
}

8
ICSharpCode.Decompiler/CSharp/CSharpDecompiler.cs

@ -305,6 +305,8 @@ namespace ICSharpCode.Decompiler.CSharp @@ -305,6 +305,8 @@ namespace ICSharpCode.Decompiler.CSharp
return true;
if (settings.AsyncAwait && AsyncAwaitDecompiler.IsCompilerGeneratedStateMachine(typeHandle, metadata))
return true;
if (settings.AsyncEnumerator && AsyncAwaitDecompiler.IsCompilerGeneratorAsyncEnumerator(typeHandle, metadata))
return true;
if (settings.FixedBuffers && name.StartsWith("<", StringComparison.Ordinal) && name.Contains("__FixedBuffer"))
return true;
} else if (type.IsCompilerGenerated(metadata)) {
@ -1343,7 +1345,11 @@ namespace ICSharpCode.Decompiler.CSharp @@ -1343,7 +1345,11 @@ namespace ICSharpCode.Decompiler.CSharp
if (localSettings.DecompileMemberBodies && !body.Descendants.Any(d => d is YieldReturnStatement || d is YieldBreakStatement)) {
body.Add(new YieldBreakStatement());
}
RemoveAttribute(entityDecl, KnownAttribute.IteratorStateMachine);
if (function.IsAsync) {
RemoveAttribute(entityDecl, KnownAttribute.AsyncIteratorStateMachine);
} else {
RemoveAttribute(entityDecl, KnownAttribute.IteratorStateMachine);
}
if (function.StateMachineCompiledWithMono) {
RemoveAttribute(entityDecl, KnownAttribute.DebuggerHidden);
}

9
ICSharpCode.Decompiler/CSharp/CallBuilder.cs

@ -989,6 +989,10 @@ namespace ICSharpCode.Decompiler.CSharp @@ -989,6 +989,10 @@ namespace ICSharpCode.Decompiler.CSharp
foundMember = null;
bestCandidateIsExpandedForm = false;
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
Log.WriteLine("IsUnambiguousCall: Performing overload resolution for " + method);
Log.WriteCollection(" Arguments: ", arguments.Select(a => a.ResolveResult));
var or = new OverloadResolution(resolver.Compilation,
firstOptionalArgumentIndex < 0 ? arguments.SelectArray(a => a.ResolveResult) : arguments.Take(firstOptionalArgumentIndex).Select(a => a.ResolveResult).ToArray(),
argumentNames: firstOptionalArgumentIndex < 0 || argumentNames == null ? argumentNames : argumentNames.Take(firstOptionalArgumentIndex).ToArray(),
@ -1043,6 +1047,9 @@ namespace ICSharpCode.Decompiler.CSharp @@ -1043,6 +1047,9 @@ namespace ICSharpCode.Decompiler.CSharp
bool IsUnambiguousAccess(ExpectedTargetDetails expectedTargetDetails, ResolveResult target, IMethod method,
IList<TranslatedExpression> arguments, string[] argumentNames, out IMember foundMember)
{
Log.WriteLine("IsUnambiguousAccess: Performing overload resolution for " + method);
Log.WriteCollection(" Arguments: ", arguments.Select(a => a.ResolveResult));
foundMember = null;
if (target == null) {
var result = resolver.ResolveSimpleName(method.AccessorOwner.Name,
@ -1404,6 +1411,8 @@ namespace ICSharpCode.Decompiler.CSharp @@ -1404,6 +1411,8 @@ namespace ICSharpCode.Decompiler.CSharp
bool IsUnambiguousMethodReference(ExpectedTargetDetails expectedTargetDetails, IMethod method, ResolveResult target, IReadOnlyList<IType> typeArguments, out ResolveResult result)
{
Log.WriteLine("IsUnambiguousMethodReference: Performing overload resolution for " + method);
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
var or = new OverloadResolution(resolver.Compilation,
arguments: method.Parameters.SelectReadOnlyArray(p => new TypeResolveResult(p.Type)), // there are no arguments, use parameter types

31
ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs

@ -67,6 +67,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -67,6 +67,7 @@ namespace ICSharpCode.Decompiler.CSharp
/// </remarks>
sealed class ExpressionBuilder : ILVisitor<TranslationContext, TranslatedExpression>
{
readonly StatementBuilder statementBuilder;
readonly IDecompilerTypeSystem typeSystem;
internal readonly ITypeResolveContext decompilationContext;
internal readonly ILFunction currentFunction;
@ -77,9 +78,10 @@ namespace ICSharpCode.Decompiler.CSharp @@ -77,9 +78,10 @@ namespace ICSharpCode.Decompiler.CSharp
internal readonly DecompilerSettings settings;
readonly CancellationToken cancellationToken;
public ExpressionBuilder(IDecompilerTypeSystem typeSystem, ITypeResolveContext decompilationContext, ILFunction currentFunction, DecompilerSettings settings, CancellationToken cancellationToken)
public ExpressionBuilder(StatementBuilder statementBuilder, IDecompilerTypeSystem typeSystem, ITypeResolveContext decompilationContext, ILFunction currentFunction, DecompilerSettings settings, CancellationToken cancellationToken)
{
Debug.Assert(decompilationContext != null);
this.statementBuilder = statementBuilder;
this.typeSystem = typeSystem;
this.decompilationContext = decompilationContext;
this.currentFunction = currentFunction;
@ -369,7 +371,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -369,7 +371,7 @@ namespace ICSharpCode.Decompiler.CSharp
}
expr.Arguments.AddRange(args.Select(arg => arg.Expression));
return expr.WithILInstruction(inst)
.WithRR(new ArrayCreateResolveResult(new ArrayType(compilation, inst.Type, dimensions), args.Select(a => a.ResolveResult).ToList(), new ResolveResult[0]));
.WithRR(new ArrayCreateResolveResult(new ArrayType(compilation, inst.Type, dimensions), args.Select(a => a.ResolveResult).ToList(), Empty<ResolveResult>.Array));
}
protected internal override TranslatedExpression VisitLocAlloc(LocAlloc inst, TranslationContext context)
@ -1940,6 +1942,31 @@ namespace ICSharpCode.Decompiler.CSharp @@ -1940,6 +1942,31 @@ namespace ICSharpCode.Decompiler.CSharp
}
}
protected internal override TranslatedExpression VisitBlockContainer(BlockContainer container, TranslationContext context)
{
var oldReturnContainer = statementBuilder.currentReturnContainer;
var oldResultType = statementBuilder.currentResultType;
var oldIsIterator = statementBuilder.currentIsIterator;
statementBuilder.currentReturnContainer = container;
statementBuilder.currentResultType = context.TypeHint;
statementBuilder.currentIsIterator = false;
try {
var body = statementBuilder.ConvertAsBlock(container);
body.InsertChildAfter(null, new Comment(" Could not convert BlockContainer to single expression"), Roles.Comment);
var ame = new AnonymousMethodExpression { Body = body };
var delegateType = new ParameterizedType(compilation.FindType(typeof(Func<>)), InferReturnType(body));
var invocationTarget = new CastExpression(ConvertType(delegateType), ame);
return new InvocationExpression(new MemberReferenceExpression(invocationTarget, "Invoke"))
.WithILInstruction(container)
.WithRR(new CSharpInvocationResolveResult(new ResolveResult(delegateType), delegateType.GetDelegateInvokeMethod(), EmptyList<ResolveResult>.Instance));
} finally {
statementBuilder.currentReturnContainer = oldReturnContainer;
statementBuilder.currentResultType = oldResultType;
statementBuilder.currentIsIterator = oldIsIterator;
}
}
internal TranslatedExpression TranslateTarget(ILInstruction target, bool nonVirtualInvocation,
bool memberStatic, IType memberDeclaringType)
{

52
ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpAmbience.cs

@ -33,34 +33,34 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -33,34 +33,34 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
public class CSharpAmbience : IAmbience
{
public ConversionFlags ConversionFlags { get; set; }
#region ConvertSymbol
public string ConvertSymbol(ISymbol symbol)
{
if (symbol == null)
throw new ArgumentNullException("symbol");
throw new ArgumentNullException(nameof(symbol));
StringWriter writer = new StringWriter();
ConvertSymbol(symbol, new TextWriterTokenWriter(writer), FormattingOptionsFactory.CreateEmpty());
return writer.ToString();
}
public void ConvertSymbol(ISymbol symbol, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{
if (symbol == null)
throw new ArgumentNullException("symbol");
throw new ArgumentNullException(nameof(symbol));
if (writer == null)
throw new ArgumentNullException("writer");
throw new ArgumentNullException(nameof(writer));
if (formattingPolicy == null)
throw new ArgumentNullException("formattingPolicy");
throw new ArgumentNullException(nameof(formattingPolicy));
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstNode node = astBuilder.ConvertSymbol(symbol);
writer.StartNode(node);
EntityDeclaration entityDecl = node as EntityDeclaration;
if (entityDecl != null)
PrintModifiers(entityDecl.Modifiers, writer);
if ((ConversionFlags & ConversionFlags.ShowDefinitionKeyword) == ConversionFlags.ShowDefinitionKeyword) {
if (node is TypeDeclaration) {
switch (((TypeDeclaration)node).ClassType) {
@ -91,24 +91,23 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -91,24 +91,23 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
writer.Space();
}
}
if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) != ConversionFlags.PlaceReturnTypeAfterParameterList
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType)
{
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) {
var rt = node.GetChildByRole(Roles.Type);
if (!rt.IsNull) {
rt.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
writer.Space();
}
}
if (symbol is ITypeDefinition)
WriteTypeDeclarationName((ITypeDefinition)symbol, writer, formattingPolicy);
else if (symbol is IMember)
WriteMemberDeclarationName((IMember)symbol, writer, formattingPolicy);
else
writer.WriteIdentifier(Identifier.Create(symbol.Name));
if ((ConversionFlags & ConversionFlags.ShowParameterList) == ConversionFlags.ShowParameterList && HasParameters(symbol)) {
writer.WriteToken(symbol.SymbolKind == SymbolKind.Indexer ? Roles.LBracket : Roles.LPar, symbol.SymbolKind == SymbolKind.Indexer ? "[" : "(");
bool first = true;
@ -131,8 +130,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -131,8 +130,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
}
if ((ConversionFlags & ConversionFlags.PlaceReturnTypeAfterParameterList) == ConversionFlags.PlaceReturnTypeAfterParameterList
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType)
{
&& (ConversionFlags & ConversionFlags.ShowReturnType) == ConversionFlags.ShowReturnType) {
var rt = node.GetChildByRole(Roles.Type);
if (!rt.IsNull) {
writer.Space();
@ -171,7 +169,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -171,7 +169,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
writer.EndNode(node);
}
}
static bool HasParameters(ISymbol e)
{
switch (e.SymbolKind) {
@ -187,7 +185,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -187,7 +185,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
return false;
}
}
TypeSystemAstBuilder CreateAstBuilder()
{
TypeSystemAstBuilder astBuilder = new TypeSystemAstBuilder();
@ -199,7 +197,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -199,7 +197,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
astBuilder.ShowParameterNames = (ConversionFlags & ConversionFlags.ShowParameterNames) == ConversionFlags.ShowParameterNames;
return astBuilder;
}
void WriteTypeDeclarationName(ITypeDefinition typeDef, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
@ -299,7 +297,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -299,7 +297,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
}
}
}
void WriteQualifiedName(string name, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{
var node = AstType.Create(name);
@ -307,25 +305,25 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -307,25 +305,25 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
node.AcceptVisitor(outputVisitor);
}
#endregion
public string ConvertVariable(IVariable v)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
AstNode astNode = astBuilder.ConvertVariable(v);
return astNode.ToString().TrimEnd(';', '\r', '\n', (char)8232);
}
public string ConvertType(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
astBuilder.AlwaysUseShortTypeNames = (ConversionFlags & ConversionFlags.UseFullyQualifiedEntityNames) != ConversionFlags.UseFullyQualifiedEntityNames;
AstType astType = astBuilder.ConvertType(type);
return astType.ToString();
}
public void ConvertType(IType type, TokenWriter writer, CSharpFormattingOptions formattingPolicy)
{
TypeSystemAstBuilder astBuilder = CreateAstBuilder();
@ -333,12 +331,12 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -333,12 +331,12 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
AstType astType = astBuilder.ConvertType(type);
astType.AcceptVisitor(new CSharpOutputVisitor(writer, formattingPolicy));
}
public string ConvertConstantValue(object constantValue)
{
return TextWriterTokenWriter.PrintPrimitiveValue(constantValue);
}
public string WrapComment(string comment)
{
return "// " + comment;

398
ICSharpCode.Decompiler/CSharp/OutputVisitor/CSharpOutputVisitor.cs

File diff suppressed because it is too large Load Diff

54
ICSharpCode.Decompiler/CSharp/OutputVisitor/ITokenWriter.cs

@ -26,42 +26,42 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -26,42 +26,42 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{
public abstract void StartNode(AstNode node);
public abstract void EndNode(AstNode node);
/// <summary>
/// Writes an identifier.
/// </summary>
public abstract void WriteIdentifier(Identifier identifier);
/// <summary>
/// Writes a keyword to the output.
/// </summary>
public abstract void WriteKeyword(Role role, string keyword);
/// <summary>
/// Writes a token to the output.
/// </summary>
public abstract void WriteToken(Role role, string token);
/// <summary>
/// Writes a primitive/literal value
/// </summary>
public abstract void WritePrimitiveValue(object value, string literalValue = null);
public abstract void WritePrimitiveType(string type);
public abstract void Space();
public abstract void Indent();
public abstract void Unindent();
public abstract void NewLine();
public abstract void WriteComment(CommentType commentType, string content);
public abstract void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument);
public static TokenWriter Create(TextWriter writer, string indentation = "\t")
{
return new InsertSpecialsDecorator(new InsertRequiredSpacesDecorator(new TextWriterTokenWriter(writer) { IndentationString = indentation }));
}
public static TokenWriter CreateWriterThatSetsLocationsInAST(TextWriter writer, string indentation = "\t")
{
var target = new TextWriterTokenWriter(writer) { IndentationString = indentation };
@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -72,7 +72,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
{
return new InsertRequiredSpacesDecorator(writer);
}
public static TokenWriter WrapInWriterThatSetsLocationsInAST(TokenWriter writer)
{
if (!(writer is ILocatable))
@ -80,84 +80,84 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -80,84 +80,84 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
return new InsertMissingTokensDecorator(writer, (ILocatable)writer);
}
}
public interface ILocatable
{
TextLocation Location { get; }
int Length { get; }
}
public abstract class DecoratingTokenWriter : TokenWriter
{
TokenWriter decoratedWriter;
protected DecoratingTokenWriter(TokenWriter decoratedWriter)
{
if (decoratedWriter == null)
throw new ArgumentNullException("decoratedWriter");
throw new ArgumentNullException(nameof(decoratedWriter));
this.decoratedWriter = decoratedWriter;
}
public override void StartNode(AstNode node)
{
decoratedWriter.StartNode(node);
}
public override void EndNode(AstNode node)
{
decoratedWriter.EndNode(node);
}
public override void WriteIdentifier(Identifier identifier)
{
decoratedWriter.WriteIdentifier(identifier);
}
public override void WriteKeyword(Role role, string keyword)
{
decoratedWriter.WriteKeyword(role, keyword);
}
public override void WriteToken(Role role, string token)
{
decoratedWriter.WriteToken(role, token);
}
public override void WritePrimitiveValue(object value, string literalValue = null)
{
decoratedWriter.WritePrimitiveValue(value, literalValue);
}
public override void WritePrimitiveType(string type)
{
decoratedWriter.WritePrimitiveType(type);
}
public override void Space()
{
decoratedWriter.Space();
}
public override void Indent()
{
decoratedWriter.Indent();
}
public override void Unindent()
{
decoratedWriter.Unindent();
}
public override void NewLine()
{
decoratedWriter.NewLine();
}
public override void WriteComment(CommentType commentType, string content)
{
decoratedWriter.WriteComment(commentType, content);
}
public override void WritePreProcessorDirective(PreProcessorDirectiveType type, string argument)
{
decoratedWriter.WritePreProcessorDirective(type, argument);

17
ICSharpCode.Decompiler/CSharp/OutputVisitor/TextWriterTokenWriter.cs

@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
public TextWriterTokenWriter(TextWriter textWriter)
{
if (textWriter == null)
throw new ArgumentNullException("textWriter");
throw new ArgumentNullException(nameof(textWriter));
this.textWriter = textWriter;
this.IndentationString = "\t";
this.line = 1;
@ -298,15 +298,13 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -298,15 +298,13 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
}
return;
}
if (f == 0 && 1 / f == float.NegativeInfinity) {
var str = f.ToString("R", NumberFormatInfo.InvariantInfo) + "f";
if (f == 0 && 1 / f == float.NegativeInfinity && str[0] != '-') {
// negative zero is a special case
// (again, not a primitive expression, but it's better to handle
// the special case here than to do it in all code generators)
textWriter.Write("-");
column++;
Length++;
str = '-' + str;
}
var str = f.ToString("R", NumberFormatInfo.InvariantInfo) + "f";
column += str.Length;
Length += str.Length;
textWriter.Write(str);
@ -334,14 +332,13 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor @@ -334,14 +332,13 @@ namespace ICSharpCode.Decompiler.CSharp.OutputVisitor
}
return;
}
if (f == 0 && 1 / f == double.NegativeInfinity) {
string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
if (f == 0 && 1 / f == double.NegativeInfinity && number[0] != '-') {
// negative zero is a special case
// (again, not a primitive expression, but it's better to handle
// the special case here than to do it in all code generators)
textWriter.Write("-");
Length++;
number = '-' + number;
}
string number = f.ToString("R", NumberFormatInfo.InvariantInfo);
if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0) {
number += ".0";
}

11
ICSharpCode.Decompiler/CSharp/Resolver/AwaitResolveResult.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/// This can also refer to an UnsafeOnCompleted method, if the awaiter type implements <c>System.Runtime.CompilerServices.ICriticalNotifyCompletion</c>.
/// </summary>
public readonly IMethod OnCompletedMethod;
/// <summary>
/// Method representing the GetResult method on the awaiter type. Can be null if the awaiter type or the method was not found, or when awaiting a dynamic expression.
/// </summary>
@ -58,21 +58,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -58,21 +58,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
: base(resultType)
{
if (awaiterType == null)
throw new ArgumentNullException("awaiterType");
throw new ArgumentNullException(nameof(awaiterType));
if (getAwaiterInvocation == null)
throw new ArgumentNullException("getAwaiterInvocation");
throw new ArgumentNullException(nameof(getAwaiterInvocation));
this.GetAwaiterInvocation = getAwaiterInvocation;
this.AwaiterType = awaiterType;
this.IsCompletedProperty = isCompletedProperty;
this.OnCompletedMethod = onCompletedMethod;
this.GetResultMethod = getResultMethod;
}
public override bool IsError {
get { return this.GetAwaiterInvocation.IsError || (AwaiterType.Kind != TypeKind.Dynamic && (this.IsCompletedProperty == null || this.OnCompletedMethod == null || this.GetResultMethod == null)); }
}
public override IEnumerable<ResolveResult> GetChildResults() {
public override IEnumerable<ResolveResult> GetChildResults()
{
return new[] { GetAwaiterInvocation };
}
}

190
ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs

@ -38,14 +38,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -38,14 +38,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{
readonly ConcurrentDictionary<TypePair, Conversion> implicitConversionCache = new ConcurrentDictionary<TypePair, Conversion>();
readonly ICompilation compilation;
public CSharpConversions(ICompilation compilation)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation;
}
/// <summary>
/// Gets the Conversions instance for the specified <see cref="ICompilation"/>.
/// This will make use of the context's cache manager to reuse the Conversions instance.
@ -53,7 +53,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -53,7 +53,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static CSharpConversions Get(ICompilation compilation)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new ArgumentNullException(nameof(compilation));
CacheManager cache = compilation.CacheManager;
CSharpConversions operators = (CSharpConversions)cache.GetShared(typeof(CSharpConversions));
if (operators == null) {
@ -61,30 +61,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -61,30 +61,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return operators;
}
#region TypePair (for caching)
struct TypePair : IEquatable<TypePair>
{
public readonly IType FromType;
public readonly IType ToType;
public TypePair(IType fromType, IType toType)
{
Debug.Assert(fromType != null && toType != null);
this.FromType = fromType;
this.ToType = toType;
}
public override bool Equals(object obj)
{
return (obj is TypePair) && Equals((TypePair)obj);
}
public bool Equals(TypePair other)
{
return object.Equals(this.FromType, other.FromType) && object.Equals(this.ToType, other.ToType);
}
public override int GetHashCode()
{
unchecked {
@ -93,7 +93,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -93,7 +93,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region ImplicitConversion
private Conversion ImplicitConversion(ResolveResult resolveResult, IType toType, bool allowUserDefined, bool allowTuple)
{
@ -137,7 +137,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -137,7 +137,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
c = MethodGroupConversion(resolveResult, toType);
return c;
}
private Conversion ImplicitConversion(IType fromType, IType toType, bool allowUserDefined, bool allowTuple)
{
// C# 4.0 spec: §6.1
@ -151,17 +151,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -151,17 +151,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public Conversion ImplicitConversion(ResolveResult resolveResult, IType toType)
{
if (resolveResult == null)
throw new ArgumentNullException("resolveResult");
throw new ArgumentNullException(nameof(resolveResult));
return ImplicitConversion(resolveResult, toType, allowUserDefined: true, allowTuple: true);
}
public Conversion ImplicitConversion(IType fromType, IType toType)
{
if (fromType == null)
throw new ArgumentNullException("fromType");
throw new ArgumentNullException(nameof(fromType));
if (toType == null)
throw new ArgumentNullException("toType");
throw new ArgumentNullException(nameof(toType));
TypePair pair = new TypePair(fromType, toType);
Conversion c;
if (implicitConversionCache.TryGetValue(pair, out c))
@ -176,9 +176,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -176,9 +176,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public Conversion StandardImplicitConversion(IType fromType, IType toType)
{
if (fromType == null)
throw new ArgumentNullException("fromType");
throw new ArgumentNullException(nameof(fromType));
if (toType == null)
throw new ArgumentNullException("toType");
throw new ArgumentNullException(nameof(toType));
return StandardImplicitConversion(fromType, toType, allowTupleConversion: true);
}
@ -220,10 +220,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -220,10 +220,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsConstraintConvertible(IType fromType, IType toType)
{
if (fromType == null)
throw new ArgumentNullException("fromType");
throw new ArgumentNullException(nameof(fromType));
if (toType == null)
throw new ArgumentNullException("toType");
throw new ArgumentNullException(nameof(toType));
if (IdentityConversion(fromType, toType))
return true;
if (ImplicitReferenceConversion(fromType, toType, 0))
@ -242,15 +242,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -242,15 +242,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false;
}
#endregion
#region ExplicitConversion
public Conversion ExplicitConversion(ResolveResult resolveResult, IType toType)
{
if (resolveResult == null)
throw new ArgumentNullException("resolveResult");
throw new ArgumentNullException(nameof(resolveResult));
if (toType == null)
throw new ArgumentNullException("toType");
throw new ArgumentNullException(nameof(toType));
if (resolveResult.Type.Kind == TypeKind.Dynamic)
return Conversion.ExplicitDynamicConversion;
Conversion c = ImplicitConversion(resolveResult, toType, allowUserDefined: false, allowTuple: false);
@ -266,14 +266,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -266,14 +266,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return c;
return UserDefinedExplicitConversion(resolveResult, resolveResult.Type, toType);
}
public Conversion ExplicitConversion(IType fromType, IType toType)
{
if (fromType == null)
throw new ArgumentNullException("fromType");
throw new ArgumentNullException(nameof(fromType));
if (toType == null)
throw new ArgumentNullException("toType");
throw new ArgumentNullException(nameof(toType));
Conversion c = ImplicitConversion(fromType, toType, allowUserDefined: false, allowTuple: false);
if (c != Conversion.None)
return c;
@ -282,7 +282,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -282,7 +282,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return c;
return UserDefinedExplicitConversion(null, fromType, toType);
}
Conversion ExplicitConversionImpl(IType fromType, IType toType)
{
// This method is called after we already checked for implicit conversions,
@ -319,7 +319,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -319,7 +319,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return fromType.Equals(toType);
}
#endregion
#region Numeric Conversions
static readonly bool[,] implicitNumericConversionLookup = {
// to: short ushort int uint long ulong
@ -332,11 +332,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -332,11 +332,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/* int */ { false, false, false, false, true , false },
/* uint */ { false, false, false, false, true , true },
};
bool ImplicitNumericConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.1.2
TypeCode from = ReflectionHelper.GetTypeCode(fromType);
TypeCode to = ReflectionHelper.GetTypeCode(toType);
if (to >= TypeCode.Single && to <= TypeCode.Decimal) {
@ -351,20 +351,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -351,20 +351,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
&& implicitNumericConversionLookup[from - TypeCode.Char, to - TypeCode.Int16];
}
}
bool IsNumericType(IType type)
{
TypeCode c = ReflectionHelper.GetTypeCode(type);
return c >= TypeCode.Char && c <= TypeCode.Decimal;
}
bool AnyNumericConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.1.2 + §6.2.1
return IsNumericType(fromType) && IsNumericType(toType);
}
#endregion
#region Enumeration Conversions
Conversion ImplicitEnumerationConversion(ResolveResult rr, IType toType)
{
@ -378,7 +378,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -378,7 +378,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return Conversion.None;
}
bool ExplicitEnumerationConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.2.2
@ -390,7 +390,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -390,7 +390,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false;
}
#endregion
#region Nullable Conversions
Conversion ImplicitNullableConversion(IType fromType, IType toType)
{
@ -405,7 +405,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -405,7 +405,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return Conversion.None;
}
Conversion ExplicitNullableConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.1.4
@ -422,7 +422,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -422,7 +422,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None;
}
#endregion
#region Null Literal Conversion
bool NullLiteralConversion(IType fromType, IType toType)
{
@ -434,24 +434,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -434,24 +434,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region Implicit Reference Conversion
public bool IsImplicitReferenceConversion(IType fromType, IType toType)
{
return ImplicitReferenceConversion(fromType, toType, 0);
}
bool ImplicitReferenceConversion(IType fromType, IType toType, int subtypeCheckNestingDepth)
{
// C# 4.0 spec: §6.1.6
// reference conversions are possible:
// - if both types are known to be reference types
// - if both types are type parameters and fromType has a class constraint
// (ImplicitTypeParameterConversionWithClassConstraintOnlyOnT)
if (!(fromType.IsReferenceType == true && toType.IsReferenceType != false))
return false;
ArrayType fromArray = fromType as ArrayType;
if (fromArray != null) {
ArrayType toArray = toType as ArrayType;
@ -471,11 +471,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -471,11 +471,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IType systemArray = compilation.FindType(KnownTypeCode.Array);
return ImplicitReferenceConversion(systemArray, toType, subtypeCheckNestingDepth);
}
// now comes the hard part: traverse the inheritance chain and figure out generics+variance
return IsSubtypeOf(fromType, toType, subtypeCheckNestingDepth);
}
/// <summary>
/// For IList{T}, ICollection{T}, IEnumerable{T} and IReadOnlyList{T}, returns T.
/// Otherwise, returns null.
@ -494,10 +494,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -494,10 +494,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return null;
}
// Determines whether s is a subtype of t.
// Helper method used for ImplicitReferenceConversion, BoxingConversion and ImplicitTypeParameterConversion
bool IsSubtypeOf(IType s, IType t, int subtypeCheckNestingDepth)
{
// conversion to dynamic + object are always possible
@ -507,7 +507,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -507,7 +507,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
// Subtyping in C# is undecidable
// (see "On Decidability of Nominal Subtyping with Variance" by Andrew J. Kennedy and Benjamin C. Pierce),
// so we'll prevent infinite recursions by putting a limit on the nesting depth of variance conversions.
// No real C# code should use generics nested more than 10 levels deep, and even if they do, most of
// those nestings should not involve variance.
return false;
@ -519,7 +519,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -519,7 +519,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return false;
}
bool IdentityOrVarianceConversion(IType s, IType t, int subtypeCheckNestingDepth)
{
ITypeDefinition def = s.GetDefinition();
@ -559,12 +559,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -559,12 +559,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region Explicit Reference Conversion
bool ExplicitReferenceConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §6.2.4
// test that the types are reference types:
if (toType.IsReferenceType != true)
return false;
@ -576,7 +576,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -576,7 +576,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return IsSubtypeOf(toType, fromType, 0);
return false;
}
if (toType.Kind == TypeKind.Array) {
ArrayType toArray = (ArrayType)toType;
if (fromType.Kind == TypeKind.Array) {
@ -645,7 +645,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -645,7 +645,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
|| IsImplicitReferenceConversion(fromType, toType);
}
}
bool IsSealedReferenceType(IType type)
{
TypeKind kind = type.Kind;
@ -686,7 +686,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -686,7 +686,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false;
}
#endregion
#region Implicit Constant-Expression Conversion
bool ImplicitConstantExpressionConversion(ResolveResult rr, IType toType)
{
@ -721,7 +721,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -721,7 +721,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false;
}
#endregion
#region Conversions involving type parameters
/// <summary>
/// Implicit conversions involving type parameters.
@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return false; // already handled by ImplicitReferenceConversion
return IsSubtypeOf(fromType, toType, 0);
}
Conversion ExplicitTypeParameterConversion(IType fromType, IType toType)
{
if (toType.Kind == TypeKind.TypeParameter) {
@ -749,7 +749,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -749,7 +749,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None;
}
#endregion
#region Pointer Conversions
bool ImplicitPointerConversion(IType fromType, IType toType)
{
@ -760,7 +760,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -760,7 +760,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true;
return false;
}
bool ExplicitPointerConversion(IType fromType, IType toType)
{
// C# 4.0 spec: §18.4 Pointer conversions
@ -770,14 +770,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -770,14 +770,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return toType.Kind == TypeKind.Pointer && IsIntegerType(fromType);
}
}
bool IsIntegerType(IType type)
{
TypeCode c = ReflectionHelper.GetTypeCode(type);
return c >= TypeCode.SByte && c <= TypeCode.UInt64;
}
#endregion
#region User-Defined Conversions
/// <summary>
/// Gets whether type A is encompassed by type B.
@ -786,7 +786,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -786,7 +786,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{
return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface && StandardImplicitConversion(a, b).IsValid;
}
bool IsEncompassingOrEncompassedBy(IType a, IType b)
{
return a.Kind != TypeKind.Interface && b.Kind != TypeKind.Interface
@ -800,7 +800,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -800,7 +800,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (best == null || IsEncompassedBy(current, best))
best = current;
else if (!IsEncompassedBy(best, current))
return null; // Ambiguous
return null; // Ambiguous
}
return best;
}
@ -812,7 +812,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -812,7 +812,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (best == null || IsEncompassedBy(best, current))
best = current;
else if (!IsEncompassedBy(current, best))
return null; // Ambiguous
return null; // Ambiguous
}
return best;
}
@ -831,7 +831,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -831,7 +831,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
var op = selected.First(s => !s.IsLifted);
return Conversion.UserDefinedConversion(op.Method, isLifted: op.IsLifted, isImplicit: isImplicit, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
}
return Conversion.UserDefinedConversion(selected[0].Method, isLifted: selected[0].IsLifted, isImplicit: isImplicit, isAmbiguous: true, conversionBeforeUserDefinedOperator: ExplicitConversion(source, mostSpecificSource), conversionAfterUserDefinedOperator: ExplicitConversion(mostSpecificTarget, target));
}
@ -861,17 +861,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -861,17 +861,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return other;
}
return selected;
}
else if (NullableType.IsNullable(toType))
} else if (NullableType.IsNullable(toType))
return UserDefinedImplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
else
return Conversion.None;
}
else {
} else {
return Conversion.None;
}
}
Conversion UserDefinedExplicitConversion(ResolveResult fromResult, IType fromType, IType toType)
{
// C# 4.0 spec §6.4.5 User-defined explicit conversions
@ -913,26 +911,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -913,26 +911,24 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return other;
}
return selected;
}
else if (NullableType.IsNullable(toType))
} else if (NullableType.IsNullable(toType))
return UserDefinedExplicitConversion(fromResult, fromType, NullableType.GetUnderlyingType(toType));
else if (NullableType.IsNullable(fromType))
return UserDefinedExplicitConversion(null, NullableType.GetUnderlyingType(fromType), toType); // A? -> A -> B
return UserDefinedExplicitConversion(null, NullableType.GetUnderlyingType(fromType), toType); // A? -> A -> B
else
return Conversion.None;
}
else {
} else {
return Conversion.None;
}
}
class OperatorInfo
{
public readonly IMethod Method;
public readonly IType SourceType;
public readonly IType TargetType;
public readonly bool IsLifted;
public OperatorInfo(IMethod method, IType sourceType, IType targetType, bool isLifted)
{
this.Method = method;
@ -941,7 +937,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -941,7 +937,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.IsLifted = isLifted;
}
}
List<OperatorInfo> GetApplicableConversionOperators(ResolveResult fromResult, IType fromType, IType toType, bool isExplicit)
{
// Find the candidate operators:
@ -950,7 +946,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -950,7 +946,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
opFilter = m => m.IsStatic && m.IsOperator && (m.Name == "op_Explicit" || m.Name == "op_Implicit") && m.Parameters.Count == 1;
else
opFilter = m => m.IsStatic && m.IsOperator && m.Name == "op_Implicit" && m.Parameters.Count == 1;
var operators = NullableType.GetUnderlyingType(fromType).GetMethods(opFilter)
.Concat(NullableType.GetUnderlyingType(toType).GetMethods(opFilter)).Distinct();
// Determine whether one of them is applicable:
@ -990,7 +986,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -990,7 +986,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return result;
}
#endregion
#region AnonymousFunctionConversion
Conversion AnonymousFunctionConversion(ResolveResult resolveResult, IType toType)
{
@ -1006,18 +1002,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1006,18 +1002,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IMethod d = toType.GetDelegateInvokeMethod();
if (d == null)
return Conversion.None;
IType[] dParamTypes = new IType[d.Parameters.Count];
for (int i = 0; i < dParamTypes.Length; i++) {
dParamTypes[i] = d.Parameters[i].Type;
}
IType dReturnType = d.ReturnType;
if (f.HasParameterList) {
// If F contains an anonymous-function-signature, then D and F have the same number of parameters.
if (d.Parameters.Count != f.Parameters.Count)
return Conversion.None;
if (f.IsImplicitlyTyped) {
// If F has an implicitly typed parameter list, D has no ref or out parameters.
foreach (IParameter p in d.Parameters) {
@ -1044,7 +1040,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1044,7 +1040,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None;
}
}
return f.IsValid(dParamTypes, dReturnType, this);
}
@ -1058,7 +1054,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1058,7 +1054,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region MethodGroupConversion
Conversion MethodGroupConversion(ResolveResult resolveResult, IType toType)
{
@ -1069,7 +1065,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1069,7 +1065,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IMethod invoke = toType.GetDelegateInvokeMethod();
if (invoke == null)
return Conversion.None;
ResolveResult[] args = new ResolveResult[invoke.Parameters.Count];
for (int i = 0; i < args.Length; i++) {
IParameter param = invoke.Parameters[i];
@ -1096,7 +1092,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1096,7 +1092,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Conversion.None;
}
}
/// <summary>
/// Gets whether a <paramref name="method"/> is compatible with a delegate type.
/// §15.2 Delegate compatibility
@ -1106,15 +1102,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1106,15 +1102,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsDelegateCompatible(IMethod method, IType delegateType)
{
if (method == null)
throw new ArgumentNullException("method");
throw new ArgumentNullException(nameof(method));
if (delegateType == null)
throw new ArgumentNullException("delegateType");
throw new ArgumentNullException(nameof(delegateType));
IMethod invoke = delegateType.GetDelegateInvokeMethod();
if (invoke == null)
return false;
return IsDelegateCompatible(method, invoke, false);
}
/// <summary>
/// Gets whether a method <paramref name="m"/> is compatible with a delegate type.
/// §15.2 Delegate compatibility
@ -1126,9 +1122,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1126,9 +1122,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
bool IsDelegateCompatible(IMethod m, IMethod invoke, bool isExtensionMethodInvocation)
{
if (m == null)
throw new ArgumentNullException("m");
throw new ArgumentNullException(nameof(m));
if (invoke == null)
throw new ArgumentNullException("invoke");
throw new ArgumentNullException(nameof(invoke));
int firstParameterInM = isExtensionMethodInvocation ? 1 : 0;
if (m.Parameters.Count - firstParameterInM != invoke.Parameters.Count)
return false;
@ -1227,14 +1223,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1227,14 +1223,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
if (lambda.HasParameterList && parameterTypes.Length != lambda.Parameters.Count)
return 0;
IType ret1 = m1.ReturnType;
IType ret2 = m2.ReturnType;
if (ret1.Kind == TypeKind.Void && ret2.Kind != TypeKind.Void)
return 2;
if (ret1.Kind != TypeKind.Void && ret2.Kind == TypeKind.Void)
return 1;
IType inferredRet = lambda.GetInferredReturnType(parameterTypes);
int r = BetterConversion(inferredRet, ret1, ret2);
if (r == 0 && lambda.IsAsync) {
@ -1249,7 +1245,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1249,7 +1245,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return BetterConversion(resolveResult.Type, t1, t2);
}
}
/// <summary>
/// Unpacks the generic Task[T]. Returns null if the input is not Task[T].
/// </summary>
@ -1261,7 +1257,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1261,7 +1257,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return null;
}
/// <summary>
/// Gets the better conversion (C# 4.0 spec, §7.5.3.4)
/// </summary>
@ -1276,7 +1272,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1276,7 +1272,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2;
return BetterConversionTarget(t1, t2);
}
/// <summary>
/// Gets the better conversion target (C# 4.0 spec, §7.5.3.5)
/// </summary>
@ -1297,7 +1293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1297,7 +1293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2;
return 0;
}
bool IsBetterIntegralType(TypeCode t1, TypeCode t2)
{
// signed types are better than unsigned types

32
ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs

@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -49,7 +49,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver(ICompilation compilation)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation;
this.conversions = CSharpConversions.Get(compilation);
this.context = new CSharpTypeResolveContext(compilation.MainModule);
@ -58,7 +58,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -58,7 +58,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver(CSharpTypeResolveContext context)
{
if (context == null)
throw new ArgumentNullException("context");
throw new ArgumentNullException(nameof(context));
this.compilation = context.Compilation;
this.conversions = CSharpConversions.Get(compilation);
this.context = context;
@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver AddVariable(IVariable variable)
{
if (variable == null)
throw new ArgumentNullException("variable");
throw new ArgumentNullException(nameof(variable));
return WithLocalVariableStack(localVariableStack.Push(variable));
}
@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public CSharpResolver PushObjectInitializer(ResolveResult initializedObject)
{
if (initializedObject == null)
throw new ArgumentNullException("initializedObject");
throw new ArgumentNullException(nameof(initializedObject));
return WithObjectInitializerStack(new ObjectInitializerContext(initializedObject, objectInitializerStack));
}
@ -379,14 +379,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -379,14 +379,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return UnaryOperatorResolveResult(new PointerType(expression.Type), op, expression);
case UnaryOperatorType.Await: {
ResolveResult getAwaiterMethodGroup = ResolveMemberAccess(expression, "GetAwaiter", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
ResolveResult getAwaiterInvocation = ResolveInvocation(getAwaiterMethodGroup, new ResolveResult[0], argumentNames: null, allowOptionalParameters: false);
ResolveResult getAwaiterInvocation = ResolveInvocation(getAwaiterMethodGroup, Empty<ResolveResult>.Array, argumentNames: null, allowOptionalParameters: false);
var lookup = CreateMemberLookup();
IMethod getResultMethod;
IType awaitResultType;
var getResultMethodGroup = lookup.Lookup(getAwaiterInvocation, "GetResult", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
if (getResultMethodGroup != null) {
var getResultOR = getResultMethodGroup.PerformOverloadResolution(compilation, new ResolveResult[0], allowExtensionMethods: false, conversions: conversions);
var getResultOR = getResultMethodGroup.PerformOverloadResolution(compilation, Empty<ResolveResult>.Array, allowExtensionMethods: false, conversions: conversions);
getResultMethod = getResultOR.FoundApplicableCandidate ? getResultOR.GetBestCandidateWithSubstitutedTypeArguments() as IMethod : null;
awaitResultType = getResultMethod != null ? getResultMethod.ReturnType : SpecialType.UnknownType;
}
@ -1313,9 +1313,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1313,9 +1313,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
// C# 4.0 spec: §3.8 Namespace and type names; §7.6.2 Simple Names
if (identifier == null)
throw new ArgumentNullException("identifier");
throw new ArgumentNullException(nameof(identifier));
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
throw new ArgumentNullException(nameof(typeArguments));
int k = typeArguments.Count;
@ -1698,12 +1698,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1698,12 +1698,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
getEnumeratorInvocation = ResolveCast(collectionType, expression);
getEnumeratorInvocation = ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
getEnumeratorInvocation = ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
getEnumeratorInvocation = ResolveInvocation(getEnumeratorInvocation, Empty<ResolveResult>.Array);
} else {
var getEnumeratorMethodGroup = memberLookup.Lookup(expression, "GetEnumerator", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
if (getEnumeratorMethodGroup != null) {
var or = getEnumeratorMethodGroup.PerformOverloadResolution(
compilation, new ResolveResult[0],
compilation, Empty<ResolveResult>.Array,
allowExtensionMethods: false, allowExpandingParams: false, allowOptionalParameters: false);
if (or.FoundApplicableCandidate && !or.IsAmbiguous && !or.BestCandidate.IsStatic && or.BestCandidate.Accessibility == Accessibility.Public) {
collectionType = expression.Type;
@ -1722,7 +1722,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1722,7 +1722,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
var moveNextMethodGroup = memberLookup.Lookup(new ResolveResult(enumeratorType), "MoveNext", EmptyList<IType>.Instance, false) as MethodGroupResolveResult;
if (moveNextMethodGroup != null) {
var or = moveNextMethodGroup.PerformOverloadResolution(
compilation, new ResolveResult[0],
compilation, Empty<ResolveResult>.Array,
allowExtensionMethods: false, allowExpandingParams: false, allowOptionalParameters: false);
moveNextMethod = or.GetBestCandidateWithSubstitutedTypeArguments() as IMethod;
}
@ -1763,7 +1763,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1763,7 +1763,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
getEnumeratorInvocation = ResolveCast(collectionType, expression);
getEnumeratorInvocation = ResolveMemberAccess(getEnumeratorInvocation, "GetEnumerator", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
getEnumeratorInvocation = ResolveInvocation(getEnumeratorInvocation, new ResolveResult[0]);
getEnumeratorInvocation = ResolveInvocation(getEnumeratorInvocation, Empty<ResolveResult>.Array);
}
#endregion
@ -1866,9 +1866,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1866,9 +1866,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{
if (targetType == null)
throw new ArgumentNullException("targetType");
throw new ArgumentNullException(nameof(targetType));
if (method == null)
throw new ArgumentNullException("method");
throw new ArgumentNullException(nameof(method));
var compilation = method.Compilation;
return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes);
}
@ -2348,7 +2348,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -2348,7 +2348,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult ResolveCondition(ResolveResult input)
{
if (input == null)
throw new ArgumentNullException("input");
throw new ArgumentNullException(nameof(input));
IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) {
@ -2368,7 +2368,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -2368,7 +2368,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult ResolveConditionFalse(ResolveResult input)
{
if (input == null)
throw new ArgumentNullException("input");
throw new ArgumentNullException(nameof(input));
IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) {

5
ICSharpCode.Decompiler/CSharp/Resolver/LambdaResolveResult.cs

@ -152,7 +152,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -152,7 +152,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (this.Parameters.Count != parameterTypes.Length)
return Conversion.None;
for (int i = 0; i < parameterTypes.Length; ++i) {
if (!parameterTypes[i].Equals(this.Parameters[i].Type)) {
if (!conversions.IdentityConversion(parameterTypes[i], this.Parameters[i].Type)) {
if (IsImplicitlyTyped) {
// it's possible that different parameter types also lead to a valid conversion
return LambdaConversion.Instance;
@ -162,7 +162,8 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -162,7 +162,8 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
}
if (returnType.Equals(this.ReturnType)) {
if (conversions.IdentityConversion(this.ReturnType, returnType)
|| conversions.ImplicitConversion(this.InferredReturnType, returnType).IsValid) {
return LambdaConversion.Instance;
} else {
return Conversion.None;

20
ICSharpCode.Decompiler/CSharp/Resolver/MemberLookup.cs

@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool IsInvocable(IMember member)
{
if (member == null)
throw new ArgumentNullException("member");
throw new ArgumentNullException(nameof(member));
// C# 4.0 spec, §7.4 member lookup
if (member is IEvent || member is IMethod)
return true;
@ -99,7 +99,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -99,7 +99,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public bool IsAccessible(IEntity entity, bool allowProtectedAccess)
{
if (entity == null)
throw new ArgumentNullException("entity");
throw new ArgumentNullException(nameof(entity));
// C# 4.0 spec, §3.5.2 Accessiblity domains
switch (entity.Accessibility) {
case Accessibility.None:
@ -159,7 +159,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -159,7 +159,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IEnumerable<IEntity> GetAccessibleMembers(ResolveResult targetResolveResult)
{
if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult");
throw new ArgumentNullException(nameof(targetResolveResult));
bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);
@ -276,11 +276,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -276,11 +276,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult LookupType(IType declaringType, string name, IReadOnlyList<IType> typeArguments, bool parameterizeResultType = true)
{
if (declaringType == null)
throw new ArgumentNullException("declaringType");
throw new ArgumentNullException(nameof(declaringType));
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
throw new ArgumentNullException(nameof(typeArguments));
int typeArgumentCount = typeArguments.Count;
Predicate<ITypeDefinition> filter = delegate (ITypeDefinition d) {
@ -335,11 +335,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -335,11 +335,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public ResolveResult Lookup(ResolveResult targetResolveResult, string name, IReadOnlyList<IType> typeArguments, bool isInvocation)
{
if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult");
throw new ArgumentNullException(nameof(targetResolveResult));
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
throw new ArgumentNullException(nameof(typeArguments));
bool targetIsTypeParameter = targetResolveResult.Type.Kind == TypeKind.TypeParameter;
@ -413,7 +413,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -413,7 +413,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IReadOnlyList<MethodListWithDeclaringType> LookupIndexers(ResolveResult targetResolveResult)
{
if (targetResolveResult == null)
throw new ArgumentNullException("targetResolveResult");
throw new ArgumentNullException(nameof(targetResolveResult));
IType targetType = targetResolveResult.Type;
bool allowProtectedAccess = IsProtectedAccessAllowed(targetResolveResult);

2
ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs

@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -86,7 +86,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
: base(SpecialType.NoType)
{
if (methods == null)
throw new ArgumentNullException("methods");
throw new ArgumentNullException(nameof(methods));
this.targetResult = targetResult;
this.methodName = methodName;
this.methodLists = methods;

186
ICSharpCode.Decompiler/CSharp/Resolver/OverloadResolution.cs

@ -35,53 +35,53 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -35,53 +35,53 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
sealed class Candidate
{
public readonly IParameterizedMember Member;
/// <summary>
/// Returns the normal form candidate, if this is an expanded candidate.
/// </summary>
public readonly bool IsExpandedForm;
/// <summary>
/// Gets the parameter types. In the first step, these are the types without any substition.
/// After type inference, substitutions will be performed.
/// </summary>
public readonly IType[] ParameterTypes;
/// <summary>
/// argument index -> parameter index; -1 for arguments that could not be mapped
/// </summary>
public int[] ArgumentToParameterMap;
public OverloadResolutionErrors Errors;
public int ErrorCount;
public bool HasUnmappedOptionalParameters;
public IType[] InferredTypes;
/// <summary>
/// Gets the original member parameters (before any substitution!)
/// </summary>
public readonly IReadOnlyList<IParameter> Parameters;
/// <summary>
/// Gets the original method type parameters (before any substitution!)
/// </summary>
public readonly IReadOnlyList<ITypeParameter> TypeParameters;
/// <summary>
/// Conversions applied to the arguments.
/// This field is set by the CheckApplicability step.
/// </summary>
public Conversion[] ArgumentConversions;
public bool IsGenericMethod {
get {
IMethod method = Member as IMethod;
return method != null && method.TypeParameters.Count > 0;
}
}
public int ArgumentsPassedToParamsArray {
get {
int count = 0;
@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -95,7 +95,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return count;
}
}
public Candidate(IParameterizedMember member, bool isExpanded)
{
this.Member = member;
@ -111,7 +111,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -111,7 +111,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
this.ParameterTypes = new IType[this.Parameters.Count];
}
public void AddError(OverloadResolutionErrors newError)
{
this.Errors |= newError;
@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.ErrorCount++;
}
}
readonly ICompilation compilation;
readonly ResolveResult[] arguments;
readonly string[] argumentNames;
@ -130,14 +130,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -130,14 +130,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
IType[] explicitlyGivenTypeArguments;
bool bestCandidateWasValidated;
OverloadResolutionErrors bestCandidateValidationResult;
#region Constructor
public OverloadResolution(ICompilation compilation, ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null, CSharpConversions conversions = null)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new ArgumentNullException(nameof(compilation));
if (arguments == null)
throw new ArgumentNullException("arguments");
throw new ArgumentNullException(nameof(arguments));
if (argumentNames == null)
argumentNames = new string[arguments.Length];
else if (argumentNames.Length != arguments.Length)
@ -145,17 +145,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -145,17 +145,17 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
this.compilation = compilation;
this.arguments = arguments;
this.argumentNames = argumentNames;
// keep explicitlyGivenTypeArguments==null when no type arguments were specified
if (typeArguments != null && typeArguments.Length > 0)
this.explicitlyGivenTypeArguments = typeArguments;
this.conversions = conversions ?? CSharpConversions.Get(compilation);
this.AllowExpandingParams = true;
this.AllowOptionalParameters = true;
}
#endregion
#region Input Properties
/// <summary>
/// Gets/Sets whether the methods are extension methods that are being called using extension method syntax.
@ -165,27 +165,27 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -165,27 +165,27 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
/// implicit identity, reference, or boxing conversions.
/// </remarks>
public bool IsExtensionMethodInvocation { get; set; }
/// <summary>
/// Gets/Sets whether expanding 'params' into individual elements is allowed.
/// The default value is true.
/// </summary>
public bool AllowExpandingParams { get; set; }
/// <summary>
/// Gets/Sets whether optional parameters may be left at their default value.
/// The default value is true.
/// If this property is set to false, optional parameters will be treated like regular parameters.
/// </summary>
public bool AllowOptionalParameters { get; set; }
/// <summary>
/// Gets/Sets whether ConversionResolveResults created by this OverloadResolution
/// instance apply overflow checking.
/// The default value is false.
/// </summary>
public bool CheckForOverflow { get; set; }
/// <summary>
/// Gets the arguments for which this OverloadResolution instance was created.
/// </summary>
@ -193,7 +193,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -193,7 +193,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
get { return arguments; }
}
#endregion
#region AddCandidate
/// <summary>
/// Adds a candidate to overload resolution.
@ -205,7 +205,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -205,7 +205,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{
return AddCandidate(member, OverloadResolutionErrors.None);
}
/// <summary>
/// Adds a candidate to overload resolution.
/// </summary>
@ -218,30 +218,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -218,30 +218,30 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public OverloadResolutionErrors AddCandidate(IParameterizedMember member, OverloadResolutionErrors additionalErrors)
{
if (member == null)
throw new ArgumentNullException("member");
throw new ArgumentNullException(nameof(member));
Candidate c = new Candidate(member, false);
c.AddError(additionalErrors);
if (CalculateCandidate(c)) {
//candidates.Add(c);
}
if (this.AllowExpandingParams && member.Parameters.Count > 0
&& member.Parameters[member.Parameters.Count - 1].IsParams)
&& member.Parameters[member.Parameters.Count - 1].IsParams)
{
Candidate expandedCandidate = new Candidate(member, true);
expandedCandidate.AddError(additionalErrors);
// consider expanded form only if it isn't obviously wrong
if (CalculateCandidate(expandedCandidate)) {
//candidates.Add(expandedCandidate);
if (expandedCandidate.ErrorCount < c.ErrorCount)
return expandedCandidate.Errors;
}
}
return c.Errors;
}
/// <summary>
/// Calculates applicability etc. for the candidate.
/// </summary>
@ -256,7 +256,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -256,7 +256,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
ConsiderIfNewCandidateIsBest(candidate);
return true;
}
bool ResolveParameterTypes(Candidate candidate, bool useSpecializedParameters)
{
for (int i = 0; i < candidate.Parameters.Count; i++) {
@ -281,7 +281,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -281,7 +281,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true;
}
#endregion
#region AddMethodLists
/// <summary>
/// Adds all candidates from the method lists.
@ -293,7 +293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -293,7 +293,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public void AddMethodLists(IReadOnlyList<MethodListWithDeclaringType> methodLists)
{
if (methodLists == null)
throw new ArgumentNullException("methodLists");
throw new ArgumentNullException(nameof(methodLists));
// Base types come first, so go through the list backwards (derived types first)
bool[] isHiddenByDerivedType;
if (methodLists.Count > 1)
@ -305,20 +305,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -305,20 +305,20 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
Log.WriteLine(" Skipping methods in {0} because they are hidden by an applicable method in a derived type", methodLists[i].DeclaringType);
continue;
}
MethodListWithDeclaringType methodList = methodLists[i];
bool foundApplicableCandidateInCurrentList = false;
for (int j = 0; j < methodList.Count; j++) {
IParameterizedMember method = methodList[j];
Log.Indent();
OverloadResolutionErrors errors = AddCandidate(method);
Log.Unindent();
LogCandidateAddingResult(" Candidate", method, errors);
foundApplicableCandidateInCurrentList |= IsApplicable(errors);
}
if (foundApplicableCandidateInCurrentList && i > 0) {
foreach (IType baseType in methodList.DeclaringType.GetAllBaseTypes()) {
for (int j = 0; j < i; j++) {
@ -329,21 +329,21 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -329,21 +329,21 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
}
[Conditional("DEBUG")]
internal void LogCandidateAddingResult(string text, IParameterizedMember method, OverloadResolutionErrors errors)
{
#if DEBUG
Log.WriteLine(string.Format("{0} {1} = {2}{3}",
text, method,
errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(),
this.BestCandidate == method ? " (best candidate so far)" :
this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : ""
));
text, method,
errors == OverloadResolutionErrors.None ? "Success" : errors.ToString(),
this.BestCandidate == method ? " (best candidate so far)" :
this.BestCandidateAmbiguousWith == method ? " (ambiguous)" : ""
));
#endif
}
#endregion
#region MapCorrespondingParameters
void MapCorrespondingParameters(Candidate candidate)
{
@ -386,7 +386,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -386,7 +386,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region RunTypeInference
void RunTypeInference(Candidate candidate)
{
@ -436,18 +436,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -436,18 +436,18 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
if (!substitution.ConstraintsValid)
candidate.AddError(OverloadResolutionErrors.ConstructedTypeDoesNotSatisfyConstraint);
}
sealed class ConstraintValidatingSubstitution : TypeParameterSubstitution
{
readonly CSharpConversions conversions;
public bool ConstraintsValid = true;
public ConstraintValidatingSubstitution(IReadOnlyList<IType> classTypeArguments, IReadOnlyList<IType> methodTypeArguments, OverloadResolution overloadResolution)
: base(classTypeArguments, methodTypeArguments)
{
this.conversions = overloadResolution.conversions;
}
public override IType VisitParameterizedType(ParameterizedType type)
{
IType newType = base.VisitParameterizedType(type);
@ -470,14 +470,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -470,14 +470,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region Validate Constraints
OverloadResolutionErrors ValidateMethodConstraints(Candidate candidate)
{
// If type inference already failed, we won't check the constraints:
if ((candidate.Errors & OverloadResolutionErrors.TypeInferenceFailed) != 0)
return OverloadResolutionErrors.None;
if (candidate.TypeParameters == null || candidate.TypeParameters.Count == 0)
return OverloadResolutionErrors.None; // the method isn't generic
var substitution = GetSubstitution(candidate);
@ -487,7 +487,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -487,7 +487,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return OverloadResolutionErrors.None;
}
/// <summary>
/// Validates whether the given type argument satisfies the constraints for the given type parameter.
/// </summary>
@ -500,12 +500,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -500,12 +500,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution = null)
{
if (typeParameter == null)
throw new ArgumentNullException("typeParameter");
throw new ArgumentNullException(nameof(typeParameter));
if (typeArgument == null)
throw new ArgumentNullException("typeArgument");
throw new ArgumentNullException(nameof(typeArgument));
return ValidateConstraints(typeParameter, typeArgument, substitution, CSharpConversions.Get(typeParameter.Owner.Compilation));
}
internal static bool ValidateConstraints(ITypeParameter typeParameter, IType typeArgument, TypeVisitor substitution, CSharpConversions conversions)
{
switch (typeArgument.Kind) { // void, null, and pointers cannot be used as type arguments
@ -543,7 +543,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -543,7 +543,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return true;
}
#endregion
#region CheckApplicability
/// <summary>
/// Returns whether a candidate with the given errors is still considered to be applicable.
@ -554,11 +554,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -554,11 +554,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
OverloadResolutionErrors.AmbiguousMatch | OverloadResolutionErrors.MethodConstraintsNotSatisfied;
return (errors & ~errorsThatDoNotMatterForApplicability) == OverloadResolutionErrors.None;
}
void CheckApplicability(Candidate candidate)
{
// C# 4.0 spec: §7.5.3.1 Applicable function member
// Test whether parameters were mapped the correct number of arguments:
int[] argumentCountPerParameter = new int[candidate.ParameterTypes.Length];
foreach (int parameterIndex in candidate.ArgumentToParameterMap) {
@ -577,7 +577,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -577,7 +577,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
candidate.AddError(OverloadResolutionErrors.MultipleArgumentsForSingleParameter);
}
}
candidate.ArgumentConversions = new Conversion[arguments.Length];
// Test whether argument passing mode matches the parameter passing mode
for (int i = 0; i < arguments.Length; i++) {
@ -586,7 +586,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -586,7 +586,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
candidate.ArgumentConversions[i] = Conversion.None;
continue;
}
ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult;
if (brrr != null) {
if (brrr.ReferenceKind != candidate.Parameters[parameterIndex].ReferenceKind)
@ -609,7 +609,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -609,7 +609,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region BetterFunctionMember
/// <summary>
/// Returns 1 if c1 is better than c2; 2 if c2 is better than c1; or 0 if neither is better.
@ -621,7 +621,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -621,7 +621,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 1;
if (c1.ErrorCount > 0 && c2.ErrorCount == 0)
return 2;
// C# 4.0 spec: §7.5.3.2 Better function member
bool c1IsBetter = false;
bool c2IsBetter = false;
@ -650,42 +650,42 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -650,42 +650,42 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 1;
if (!c1IsBetter && c2IsBetter)
return 2;
// prefer members with less errors (part of heuristic that produces a best candidate even if none is applicable)
if (c1.ErrorCount < c2.ErrorCount) return 1;
if (c1.ErrorCount > c2.ErrorCount) return 2;
if (!c1IsBetter && !c2IsBetter && parameterTypesEqual) {
// we need the tie-breaking rules
// non-generic methods are better
if (!c1.IsGenericMethod && c2.IsGenericMethod)
return 1;
else if (c1.IsGenericMethod && !c2.IsGenericMethod)
return 2;
// non-expanded members are better
if (!c1.IsExpandedForm && c2.IsExpandedForm)
return 1;
else if (c1.IsExpandedForm && !c2.IsExpandedForm)
return 2;
// prefer the member with less arguments mapped to the params-array
int r = c1.ArgumentsPassedToParamsArray.CompareTo(c2.ArgumentsPassedToParamsArray);
if (r < 0) return 1;
else if (r > 0) return 2;
// prefer the member where no default values need to be substituted
if (!c1.HasUnmappedOptionalParameters && c2.HasUnmappedOptionalParameters)
return 1;
else if (c1.HasUnmappedOptionalParameters && !c2.HasUnmappedOptionalParameters)
return 2;
// compare the formal parameters
r = MoreSpecificFormalParameters(c1, c2);
if (r != 0)
return r;
// prefer non-lifted operators
ILiftedOperator lift1 = c1.Member as ILiftedOperator;
ILiftedOperator lift2 = c2.Member as ILiftedOperator;
@ -696,22 +696,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -696,22 +696,22 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return 0;
}
int MoreSpecificFormalParameters(Candidate c1, Candidate c2)
{
// prefer the member with more formal parmeters (in case both have different number of optional parameters)
int r = c1.Parameters.Count.CompareTo(c2.Parameters.Count);
if (r > 0) return 1;
else if (r < 0) return 2;
return MoreSpecificFormalParameters(c1.Parameters.Select(p => p.Type), c2.Parameters.Select(p => p.Type));
}
static int MoreSpecificFormalParameters(IEnumerable<IType> t1, IEnumerable<IType> t2)
{
bool c1IsBetter = false;
bool c2IsBetter = false;
foreach (var pair in t1.Zip(t2, (a,b) => new { Item1 = a, Item2 = b })) {
foreach (var pair in t1.Zip(t2, (a, b) => new { Item1 = a, Item2 = b })) {
switch (MoreSpecificFormalParameter(pair.Item1, pair.Item2)) {
case 1:
c1IsBetter = true;
@ -727,14 +727,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -727,14 +727,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 2;
return 0;
}
static int MoreSpecificFormalParameter(IType t1, IType t2)
{
if ((t1 is ITypeParameter) && !(t2 is ITypeParameter))
return 2;
if ((t2 is ITypeParameter) && !(t1 is ITypeParameter))
return 1;
ParameterizedType p1 = t1 as ParameterizedType;
ParameterizedType p2 = t2 as ParameterizedType;
if (p1 != null && p2 != null && p1.TypeParameterCount == p2.TypeParameterCount) {
@ -750,7 +750,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -750,7 +750,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return 0;
}
#endregion
#region ConsiderIfNewCandidateIsBest
void ConsiderIfNewCandidateIsBest(Candidate candidate)
{
@ -775,12 +775,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -775,12 +775,12 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
}
#endregion
#region Output Properties
public IParameterizedMember BestCandidate {
get { return bestCandidate != null ? bestCandidate.Member : null; }
}
/// <summary>
/// Returns the errors that apply to the best candidate.
/// This includes additional errors that do not affect applicability (e.g. AmbiguousMatch, MethodConstraintsNotSatisfied)
@ -799,23 +799,23 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -799,23 +799,23 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return err;
}
}
public bool FoundApplicableCandidate {
get { return bestCandidate != null && IsApplicable(bestCandidate.Errors); }
}
public IParameterizedMember BestCandidateAmbiguousWith {
get { return bestCandidateAmbiguousWith != null ? bestCandidateAmbiguousWith.Member : null; }
}
public bool BestCandidateIsExpandedForm {
get { return bestCandidate != null ? bestCandidate.IsExpandedForm : false; }
}
public bool IsAmbiguous {
get { return bestCandidateAmbiguousWith != null; }
}
public IReadOnlyList<IType> InferredTypeArguments {
get {
if (bestCandidate != null && bestCandidate.InferredTypes != null)
@ -824,7 +824,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -824,7 +824,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return EmptyList<IType>.Instance;
}
}
/// <summary>
/// Gets the implicit conversions that are being applied to the arguments.
/// </summary>
@ -836,7 +836,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -836,7 +836,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return Enumerable.Repeat(Conversion.None, arguments.Length).ToList();
}
}
/// <summary>
/// Gets an array that maps argument indices to parameter indices.
/// For arguments that could not be mapped to any parameter, the value will be -1.
@ -850,7 +850,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -850,7 +850,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else
return null;
}
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
@ -863,7 +863,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -863,7 +863,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else
return GetArgumentsWithConversions(null, null);
}
/// <summary>
/// Returns the arguments for the method call in the order they were provided (not in the order of the parameters).
/// Arguments are wrapped in a <see cref="ConversionResolveResult"/> if an implicit conversion is being applied
@ -878,7 +878,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -878,7 +878,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
else
return GetArgumentsWithConversions(null, GetBestCandidateWithSubstitutedTypeArguments());
}
IList<ResolveResult> GetArgumentsWithConversions(ResolveResult targetResolveResult, IParameterizedMember bestCandidateForNamedArguments)
{
var conversions = this.ArgumentConversions;
@ -911,7 +911,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -911,7 +911,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
}
return args;
}
public IParameterizedMember GetBestCandidateWithSubstitutedTypeArguments()
{
if (bestCandidate == null)
@ -923,14 +923,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -923,14 +923,14 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return bestCandidate.Member;
}
}
TypeParameterSubstitution GetSubstitution(Candidate candidate)
{
// Do not compose the substitutions, but merge them.
// This is required for InvocationTests.SubstituteClassAndMethodTypeParametersAtOnce
return new TypeParameterSubstitution(candidate.Member.Substitution.ClassTypeArguments, candidate.InferredTypes);
}
/// <summary>
/// Creates a ResolveResult representing the result of overload resolution.
/// </summary>

60
ICSharpCode.Decompiler/CSharp/Resolver/TypeInference.cs

@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -61,7 +61,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public TypeInference(ICompilation compilation)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
throw new ArgumentNullException(nameof(compilation));
this.compilation = compilation;
this.conversions = CSharpConversions.Get(compilation);
}
@ -115,11 +115,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -115,11 +115,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType[] InferTypeArguments(IReadOnlyList<ITypeParameter> typeParameters, IReadOnlyList<ResolveResult> arguments, IReadOnlyList<IType> parameterTypes, out bool success, IReadOnlyList<IType> classTypeArguments = null)
{
if (typeParameters == null)
throw new ArgumentNullException("typeParameters");
throw new ArgumentNullException(nameof(typeParameters));
if (arguments == null)
throw new ArgumentNullException("arguments");
throw new ArgumentNullException(nameof(arguments));
if (parameterTypes == null)
throw new ArgumentNullException("parameterTypes");
throw new ArgumentNullException(nameof(parameterTypes));
try {
this.typeParameters = new TP[typeParameters.Count];
for (int i = 0; i < this.typeParameters.Length; i++) {
@ -173,13 +173,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -173,13 +173,13 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType[] InferTypeArgumentsFromBounds(IReadOnlyList<ITypeParameter> typeParameters, IType targetType, IEnumerable<IType> lowerBounds, IEnumerable<IType> upperBounds, out bool success)
{
if (typeParameters == null)
throw new ArgumentNullException("typeParameters");
throw new ArgumentNullException(nameof(typeParameters));
if (targetType == null)
throw new ArgumentNullException("targetType");
throw new ArgumentNullException(nameof(targetType));
if (lowerBounds == null)
throw new ArgumentNullException("lowerBounds");
throw new ArgumentNullException(nameof(lowerBounds));
if (upperBounds == null)
throw new ArgumentNullException("upperBounds");
throw new ArgumentNullException(nameof(upperBounds));
this.typeParameters = new TP[typeParameters.Count];
for (int i = 0; i < this.typeParameters.Length; i++) {
if (i != typeParameters[i].Index)
@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -223,7 +223,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public TP(ITypeParameter typeParameter)
{
if (typeParameter == null)
throw new ArgumentNullException("typeParameter");
throw new ArgumentNullException(nameof(typeParameter));
this.TypeParameter = typeParameter;
}
@ -361,8 +361,6 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -361,8 +361,6 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
#endregion
#region Input Types / Output Types (§7.5.2.3 + §7.5.2.4)
static readonly IType[] emptyTypeArray = new IType[0];
IType[] InputTypes(ResolveResult e, IType t)
{
// C# 4.0 spec: §7.5.2.3 Input types
@ -377,7 +375,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -377,7 +375,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return inputTypes;
}
}
return emptyTypeArray;
return Empty<IType>.Array;
}
IType[] OutputTypes(ResolveResult e, IType t)
@ -390,16 +388,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -390,16 +388,15 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
return new[] { m.ReturnType };
}
}
return emptyTypeArray;
return Empty<IType>.Array;
}
static IMethod GetDelegateOrExpressionTreeSignature(IType t)
{
ParameterizedType pt = t as ParameterizedType;
if (pt != null && pt.TypeParameterCount == 1 && pt.Name == "Expression"
&& pt.Namespace == "System.Linq.Expressions")
if (t.TypeParameterCount == 1 && t.Name == "Expression"
&& t.Namespace == "System.Linq.Expressions")
{
t = pt.GetTypeArgument(0);
t = t.TypeArguments[0];
}
return t.GetDelegateInvokeMethod();
}
@ -571,8 +568,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -571,8 +568,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
{
Log.WriteLine("MakeExactInference from " + U + " to " + V);
if (V is NullabilityAnnotatedTypeParameter nullableTP) {
V = nullableTP.OriginalTypeParameter;
if (U.Nullability == V.Nullability) {
U = U.WithoutNullability();
V = V.WithoutNullability();
}
// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
@ -613,8 +611,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -613,8 +611,10 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
TP GetTPForType(IType v)
{
ITypeParameter p = v as ITypeParameter;
if (p != null) {
if (v is NullabilityAnnotatedTypeParameter natp) {
v = natp.OriginalTypeParameter;
}
if (v is ITypeParameter p) {
int index = p.Index;
if (index < typeParameters.Length && typeParameters[index].TypeParameter == p)
return typeParameters[index];
@ -631,7 +631,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -631,7 +631,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
void MakeLowerBoundInference(IType U, IType V)
{
Log.WriteLine(" MakeLowerBoundInference from " + U + " to " + V);
if (U.Nullability == V.Nullability) {
U = U.WithoutNullability();
V = V.WithoutNullability();
}
// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
TP tp = GetTPForType(V);
if (tp != null && tp.IsFixed == false) {
@ -728,7 +732,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -728,7 +732,11 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
void MakeUpperBoundInference(IType U, IType V)
{
Log.WriteLine(" MakeUpperBoundInference from " + U + " to " + V);
if (U.Nullability == V.Nullability) {
U = U.WithoutNullability();
V = V.WithoutNullability();
}
// If V is one of the unfixed Xi then U is added to the set of bounds for Xi.
TP tp = GetTPForType(V);
if (tp != null && tp.IsFixed == false) {
@ -826,7 +834,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -826,7 +834,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType GetBestCommonType(IList<ResolveResult> expressions, out bool success)
{
if (expressions == null)
throw new ArgumentNullException("expressions");
throw new ArgumentNullException(nameof(expressions));
if (expressions.Count == 1) {
success = IsValidType(expressions[0].Type);
return expressions[0].Type;
@ -853,9 +861,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -853,9 +861,9 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
public IType FindTypeInBounds(IReadOnlyList<IType> lowerBounds, IReadOnlyList<IType> upperBounds)
{
if (lowerBounds == null)
throw new ArgumentNullException("lowerBounds");
throw new ArgumentNullException(nameof(lowerBounds));
if (upperBounds == null)
throw new ArgumentNullException("upperBounds");
throw new ArgumentNullException(nameof(upperBounds));
var result = FindTypesInBounds(lowerBounds, upperBounds);

44
ICSharpCode.Decompiler/CSharp/StatementBuilder.cs

@ -28,7 +28,6 @@ using System; @@ -28,7 +28,6 @@ using System;
using System.Threading;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching;
using ICSharpCode.Decompiler.CSharp.Resolver;
namespace ICSharpCode.Decompiler.CSharp
{
@ -40,11 +39,18 @@ namespace ICSharpCode.Decompiler.CSharp @@ -40,11 +39,18 @@ namespace ICSharpCode.Decompiler.CSharp
readonly DecompilerSettings settings;
readonly CancellationToken cancellationToken;
internal BlockContainer currentReturnContainer;
internal IType currentResultType;
internal bool currentIsIterator;
public StatementBuilder(IDecompilerTypeSystem typeSystem, ITypeResolveContext decompilationContext, ILFunction currentFunction, DecompilerSettings settings, CancellationToken cancellationToken)
{
Debug.Assert(typeSystem != null && decompilationContext != null);
this.exprBuilder = new ExpressionBuilder(typeSystem, decompilationContext, currentFunction, settings, cancellationToken);
this.exprBuilder = new ExpressionBuilder(this, typeSystem, decompilationContext, currentFunction, settings, cancellationToken);
this.currentFunction = currentFunction;
this.currentReturnContainer = (BlockContainer)currentFunction.Body;
this.currentIsIterator = currentFunction.IsIterator;
this.currentResultType = currentFunction.IsAsync ? currentFunction.AsyncReturnType : currentFunction.ReturnType;
this.typeSystem = typeSystem;
this.settings = settings;
this.cancellationToken = cancellationToken;
@ -300,19 +306,17 @@ namespace ICSharpCode.Decompiler.CSharp @@ -300,19 +306,17 @@ namespace ICSharpCode.Decompiler.CSharp
{
if (inst.TargetContainer == breakTarget)
return new BreakStatement();
if (inst.IsLeavingFunction) {
if (currentFunction.IsIterator)
if (inst.TargetContainer == currentReturnContainer) {
if (currentIsIterator)
return new YieldBreakStatement();
else if (!inst.Value.MatchNop()) {
IType targetType = currentFunction.IsAsync ? currentFunction.AsyncReturnType : currentFunction.ReturnType;
var expr = exprBuilder.Translate(inst.Value, typeHint: targetType)
.ConvertTo(targetType, exprBuilder, allowImplicitConversion: true);
var expr = exprBuilder.Translate(inst.Value, typeHint: currentResultType)
.ConvertTo(currentResultType, exprBuilder, allowImplicitConversion: true);
return new ReturnStatement(expr);
} else
return new ReturnStatement();
}
string label;
if (!endContainerLabels.TryGetValue(inst.TargetContainer, out label)) {
if (!endContainerLabels.TryGetValue(inst.TargetContainer, out string label)) {
label = "end_" + inst.TargetLabel;
endContainerLabels.Add(inst.TargetContainer, label);
}
@ -412,14 +416,29 @@ namespace ICSharpCode.Decompiler.CSharp @@ -412,14 +416,29 @@ namespace ICSharpCode.Decompiler.CSharp
return transformed;
AstNode usingInit = resource;
var var = inst.Variable;
if (!inst.ResourceExpression.MatchLdNull() && !NullableType.GetUnderlyingType(var.Type).GetAllBaseTypes().Any(b => b.IsKnownType(KnownTypeCode.IDisposable))) {
KnownTypeCode knownTypeCode;
IType disposeType;
string disposeTypeMethodName;
if (inst.IsAsync) {
knownTypeCode = KnownTypeCode.IAsyncDisposable;
disposeType = exprBuilder.compilation.FindType(KnownTypeCode.IAsyncDisposable);
disposeTypeMethodName = "DisposeAsync";
} else {
knownTypeCode = KnownTypeCode.IDisposable;
disposeType = exprBuilder.compilation.FindType(KnownTypeCode.IDisposable);
disposeTypeMethodName = "Dispose";
}
if (!inst.ResourceExpression.MatchLdNull() && !NullableType.GetUnderlyingType(var.Type).GetAllBaseTypes().Any(b => b.IsKnownType(knownTypeCode))) {
Debug.Assert(var.Kind == VariableKind.UsingLocal);
var.Kind = VariableKind.Local;
var disposeType = exprBuilder.compilation.FindType(KnownTypeCode.IDisposable);
var disposeVariable = currentFunction.RegisterVariable(
VariableKind.Local, disposeType,
AssignVariableNames.GenerateVariableName(currentFunction, disposeType)
);
Expression disposeInvocation = new InvocationExpression(new MemberReferenceExpression(exprBuilder.ConvertVariable(disposeVariable).Expression, disposeTypeMethodName));
if (inst.IsAsync) {
disposeInvocation = new UnaryOperatorExpression { Expression = disposeInvocation, Operator = UnaryOperatorType.Await };
}
return new BlockStatement {
new ExpressionStatement(new AssignmentExpression(exprBuilder.ConvertVariable(var).Expression, resource.Detach())),
new TryCatchStatement {
@ -428,7 +447,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -428,7 +447,7 @@ namespace ICSharpCode.Decompiler.CSharp
new ExpressionStatement(new AssignmentExpression(exprBuilder.ConvertVariable(disposeVariable).Expression, new AsExpression(exprBuilder.ConvertVariable(var).Expression, exprBuilder.ConvertType(disposeType)))),
new IfElseStatement {
Condition = new BinaryOperatorExpression(exprBuilder.ConvertVariable(disposeVariable), BinaryOperatorType.InEquality, new NullReferenceExpression()),
TrueStatement = new ExpressionStatement(new InvocationExpression(new MemberReferenceExpression(exprBuilder.ConvertVariable(disposeVariable).Expression, "Dispose")))
TrueStatement = new ExpressionStatement(disposeInvocation)
}
}
},
@ -442,6 +461,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -442,6 +461,7 @@ namespace ICSharpCode.Decompiler.CSharp
}
return new UsingStatement {
ResourceAcquisition = usingInit,
IsAsync = inst.IsAsync,
EmbeddedStatement = ConvertAsBlock(inst.Body)
};
}

450
ICSharpCode.Decompiler/CSharp/Syntax/AstNode.cs

File diff suppressed because it is too large Load Diff

6
ICSharpCode.Decompiler/CSharp/Syntax/AstNodeCollection.cs

@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstNodeCollection(AstNode node, Role<T> role)
{
if (node == null)
throw new ArgumentNullException("node");
throw new ArgumentNullException(nameof(node));
if (role == null)
throw new ArgumentNullException("role");
throw new ArgumentNullException(nameof(role));
this.node = node;
this.role = role;
}
@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -96,7 +96,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public void MoveTo(ICollection<T> targetCollection)
{
if (targetCollection == null)
throw new ArgumentNullException("targetCollection");
throw new ArgumentNullException(nameof(targetCollection));
foreach (T node in this) {
node.Remove();
targetCollection.Add(node);

2
ICSharpCode.Decompiler/CSharp/Syntax/Expressions/Expression.cs

@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -123,7 +123,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ReplaceWith(Func<Expression, Expression> replaceFunction)
{
if (replaceFunction == null)
throw new ArgumentNullException("replaceFunction");
throw new ArgumentNullException(nameof(replaceFunction));
return (Expression)base.ReplaceWith(node => replaceFunction((Expression)node));
}
}

2
ICSharpCode.Decompiler/CSharp/Syntax/GeneralScope/NamespaceDeclaration.cs

@ -64,7 +64,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -64,7 +64,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
static AstType ConstructType(string[] arr, int i)
{
if (i < 0 || i >= arr.Length)
throw new ArgumentOutOfRangeException("i");
throw new ArgumentOutOfRangeException(nameof(i));
if (i == 0)
return new SimpleType(arr[i]);
return new MemberType(ConstructType(arr, i - 1), arr[i]);

96
ICSharpCode.Decompiler/CSharp/Syntax/IAnnotatable.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
IEnumerable<object> Annotations {
get;
}
/// <summary>
/// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists.
@ -42,8 +42,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -42,8 +42,8 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// <typeparam name='T'>
/// The type of the annotation.
/// </typeparam>
T Annotation<T> () where T: class;
T Annotation<T>() where T : class;
/// <summary>
/// Gets the first annotation of the specified type.
/// Returns null if no matching annotation exists.
@ -51,24 +51,24 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -51,24 +51,24 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// <param name='type'>
/// The type of the annotation.
/// </param>
object Annotation (Type type);
object Annotation(Type type);
/// <summary>
/// Adds an annotation to this instance.
/// </summary>
/// <param name='annotation'>
/// The annotation to add.
/// </param>
void AddAnnotation (object annotation);
void AddAnnotation(object annotation);
/// <summary>
/// Removes all annotations of the specified type.
/// </summary>
/// <typeparam name='T'>
/// The type of the annotations to remove.
/// </typeparam>
void RemoveAnnotations<T> () where T : class;
void RemoveAnnotations<T>() where T : class;
/// <summary>
/// Removes all annotations of the specified type.
/// </summary>
@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
/// </param>
void RemoveAnnotations(Type type);
}
/// <summary>
/// Base class used to implement the IAnnotatable interface.
/// This implementation is thread-safe.
@ -88,9 +88,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -88,9 +88,9 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
// Annotations: points either null (no annotations), to the single annotation,
// or to an AnnotationList.
// Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list)
object annotations;
/// <summary>
/// Clones all annotations.
/// This method is intended to be called by Clone() implementations in derived classes.
@ -111,86 +111,86 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -111,86 +111,86 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
// There are two uses for this custom list type:
// 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations
// 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation.
public AnnotationList (int initialCapacity) : base(initialCapacity)
public AnnotationList(int initialCapacity) : base(initialCapacity)
{
}
public object Clone ()
public object Clone()
{
lock (this) {
AnnotationList copy = new AnnotationList (this.Count);
AnnotationList copy = new AnnotationList(this.Count);
for (int i = 0; i < this.Count; i++) {
object obj = this [i];
object obj = this[i];
ICloneable c = obj as ICloneable;
copy.Add (c != null ? c.Clone () : obj);
copy.Add(c != null ? c.Clone() : obj);
}
return copy;
}
}
}
public virtual void AddAnnotation (object annotation)
public virtual void AddAnnotation(object annotation)
{
if (annotation == null)
throw new ArgumentNullException ("annotation");
throw new ArgumentNullException(nameof(annotation));
retry: // Retry until successful
object oldAnnotation = Interlocked.CompareExchange (ref this.annotations, annotation, null);
object oldAnnotation = Interlocked.CompareExchange(ref this.annotations, annotation, null);
if (oldAnnotation == null) {
return; // we successfully added a single annotation
}
AnnotationList list = oldAnnotation as AnnotationList;
if (list == null) {
// we need to transform the old annotation into a list
list = new AnnotationList (4);
list.Add (oldAnnotation);
list.Add (annotation);
if (Interlocked.CompareExchange (ref this.annotations, list, oldAnnotation) != oldAnnotation) {
list = new AnnotationList(4);
list.Add(oldAnnotation);
list.Add(annotation);
if (Interlocked.CompareExchange(ref this.annotations, list, oldAnnotation) != oldAnnotation) {
// the transformation failed (some other thread wrote to this.annotations first)
goto retry;
}
} else {
// once there's a list, use simple locking
lock (list) {
list.Add (annotation);
list.Add(annotation);
}
}
}
public virtual void RemoveAnnotations<T> () where T : class
public virtual void RemoveAnnotations<T>() where T : class
{
retry: // Retry until successful
retry: // Retry until successful
object oldAnnotations = this.annotations;
AnnotationList list = oldAnnotations as AnnotationList;
if (list != null) {
lock (list)
list.RemoveAll (obj => obj is T);
list.RemoveAll(obj => obj is T);
} else if (oldAnnotations is T) {
if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) {
if (Interlocked.CompareExchange(ref this.annotations, null, oldAnnotations) != oldAnnotations) {
// Operation failed (some other thread wrote to this.annotations first)
goto retry;
}
}
}
public virtual void RemoveAnnotations (Type type)
public virtual void RemoveAnnotations(Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
retry: // Retry until successful
throw new ArgumentNullException(nameof(type));
retry: // Retry until successful
object oldAnnotations = this.annotations;
AnnotationList list = oldAnnotations as AnnotationList;
if (list != null) {
lock (list)
list.RemoveAll(type.IsInstanceOfType);
} else if (type.IsInstanceOfType (oldAnnotations)) {
if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) {
} else if (type.IsInstanceOfType(oldAnnotations)) {
if (Interlocked.CompareExchange(ref this.annotations, null, oldAnnotations) != oldAnnotations) {
// Operation failed (some other thread wrote to this.annotations first)
goto retry;
}
}
}
public T Annotation<T> () where T: class
public T Annotation<T>() where T : class
{
object annotations = this.annotations;
AnnotationList list = annotations as AnnotationList;
@ -207,27 +207,27 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -207,27 +207,27 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
return annotations as T;
}
}
public object Annotation (Type type)
public object Annotation(Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
throw new ArgumentNullException(nameof(type));
object annotations = this.annotations;
AnnotationList list = annotations as AnnotationList;
if (list != null) {
lock (list) {
foreach (object obj in list) {
if (type.IsInstanceOfType (obj))
if (type.IsInstanceOfType(obj))
return obj;
}
}
} else {
if (type.IsInstanceOfType (annotations))
if (type.IsInstanceOfType(annotations))
return annotations;
}
return null;
}
/// <summary>
/// Gets all annotations stored on this AstNode.
/// </summary>
@ -237,13 +237,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -237,13 +237,13 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
AnnotationList list = annotations as AnnotationList;
if (list != null) {
lock (list) {
return list.ToArray ();
return list.ToArray();
}
} else {
if (annotations != null)
return new object[] { annotations };
else
return Enumerable.Empty<object> ();
return Enumerable.Empty<object>();
}
}
}

4
ICSharpCode.Decompiler/CSharp/Syntax/Identifier.cs

@ -71,7 +71,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -71,7 +71,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
get { return this.name; }
set {
if (value == null)
throw new ArgumentNullException("value");
throw new ArgumentNullException(nameof(value));
ThrowIfFrozen();
this.name = value;
}
@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -119,7 +119,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
protected Identifier (string name, TextLocation location)
{
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.startLocation = location;
}

2
ICSharpCode.Decompiler/CSharp/Syntax/IdentifierExpressionBackreference.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public IdentifierExpressionBackreference(string referencedGroupName)
{
if (referencedGroupName == null)
throw new ArgumentNullException("referencedGroupName");
throw new ArgumentNullException(nameof(referencedGroupName));
this.referencedGroupName = referencedGroupName;
}

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Backreference.cs

@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -35,7 +35,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public Backreference(string referencedGroupName)
{
if (referencedGroupName == null)
throw new ArgumentNullException("referencedGroupName");
throw new ArgumentNullException(nameof(referencedGroupName));
this.referencedGroupName = referencedGroupName;
}

4
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Choice.cs

@ -32,14 +32,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -32,14 +32,14 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public void Add(string name, INode alternative)
{
if (alternative == null)
throw new ArgumentNullException("alternative");
throw new ArgumentNullException(nameof(alternative));
alternatives.Add(new NamedNode(name, alternative));
}
public void Add(INode alternative)
{
if (alternative == null)
throw new ArgumentNullException("alternative");
throw new ArgumentNullException(nameof(alternative));
alternatives.Add(alternative);
}

4
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/INode.cs

@ -51,7 +51,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -51,7 +51,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public static Match Match(this INode pattern, INode other)
{
if (pattern == null)
throw new ArgumentNullException("pattern");
throw new ArgumentNullException(nameof(pattern));
Match match = PatternMatching.Match.CreateNew();
if (pattern.DoMatch(other, match))
return match;
@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -62,7 +62,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public static bool IsMatch(this INode pattern, INode other)
{
if (pattern == null)
throw new ArgumentNullException("pattern");
throw new ArgumentNullException(nameof(pattern));
return pattern.DoMatch(other, PatternMatching.Match.CreateNew());
}

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/NamedNode.cs

@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public NamedNode(string groupName, INode childNode)
{
if (childNode == null)
throw new ArgumentNullException("childNode");
throw new ArgumentNullException(nameof(childNode));
this.groupName = groupName;
this.childNode = childNode;
}

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/OptionalNode.cs

@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -31,7 +31,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public OptionalNode(INode childNode)
{
if (childNode == null)
throw new ArgumentNullException("childNode");
throw new ArgumentNullException(nameof(childNode));
this.childNode = childNode;
}

2
ICSharpCode.Decompiler/CSharp/Syntax/PatternMatching/Repeat.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax.PatternMatching
public Repeat(INode childNode)
{
if (childNode == null)
throw new ArgumentNullException("childNode");
throw new ArgumentNullException(nameof(childNode));
this.childNode = childNode;
this.MinCount = 0;
this.MaxCount = int.MaxValue;

6
ICSharpCode.Decompiler/CSharp/Syntax/Role.cs

@ -89,16 +89,16 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -89,16 +89,16 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Role(string name)
{
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
this.name = name;
}
public Role(string name, T nullObject)
{
if (name == null)
throw new ArgumentNullException("name");
throw new ArgumentNullException(nameof(name));
if (nullObject == null)
throw new ArgumentNullException ("nullObject");
throw new ArgumentNullException (nameof(nullObject));
this.nullObject = nullObject;
this.name = name;
}

2
ICSharpCode.Decompiler/CSharp/Syntax/Statements/Statement.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Statement ReplaceWith(Func<Statement, Statement> replaceFunction)
{
if (replaceFunction == null)
throw new ArgumentNullException("replaceFunction");
throw new ArgumentNullException(nameof(replaceFunction));
return (Statement)base.ReplaceWith(node => replaceFunction((Statement)node));
}

60
ICSharpCode.Decompiler/CSharp/Syntax/Statements/UsingStatement.cs

@ -28,57 +28,67 @@ @@ -28,57 +28,67 @@
namespace ICSharpCode.Decompiler.CSharp.Syntax
{
/// <summary>
/// using (ResourceAcquisition) EmbeddedStatement
/// [ await ] using (ResourceAcquisition) EmbeddedStatement
/// </summary>
public class UsingStatement : Statement
{
public static readonly TokenRole UsingKeywordRole = new TokenRole ("using");
public static readonly TokenRole UsingKeywordRole = new TokenRole("using");
public static readonly TokenRole AwaitRole = UnaryOperatorExpression.AwaitRole;
public static readonly Role<AstNode> ResourceAcquisitionRole = new Role<AstNode>("ResourceAcquisition", AstNode.Null);
public CSharpTokenNode UsingToken {
get { return GetChildByRole (UsingKeywordRole); }
get { return GetChildByRole(UsingKeywordRole); }
}
public CSharpTokenNode AwaitToken {
get { return GetChildByRole(AwaitRole); }
}
public bool IsAsync {
get { return !GetChildByRole(AwaitRole).IsNull; }
set { SetChildByRole(AwaitRole, value ? new CSharpTokenNode(TextLocation.Empty, null) : null); }
}
public CSharpTokenNode LParToken {
get { return GetChildByRole (Roles.LPar); }
get { return GetChildByRole(Roles.LPar); }
}
/// <summary>
/// Either a VariableDeclarationStatement, or an Expression.
/// </summary>
public AstNode ResourceAcquisition {
get { return GetChildByRole (ResourceAcquisitionRole); }
set { SetChildByRole (ResourceAcquisitionRole, value); }
get { return GetChildByRole(ResourceAcquisitionRole); }
set { SetChildByRole(ResourceAcquisitionRole, value); }
}
public CSharpTokenNode RParToken {
get { return GetChildByRole (Roles.RPar); }
get { return GetChildByRole(Roles.RPar); }
}
public Statement EmbeddedStatement {
get { return GetChildByRole (Roles.EmbeddedStatement); }
set { SetChildByRole (Roles.EmbeddedStatement, value); }
get { return GetChildByRole(Roles.EmbeddedStatement); }
set { SetChildByRole(Roles.EmbeddedStatement, value); }
}
public override void AcceptVisitor (IAstVisitor visitor)
public override void AcceptVisitor(IAstVisitor visitor)
{
visitor.VisitUsingStatement (this);
visitor.VisitUsingStatement(this);
}
public override T AcceptVisitor<T> (IAstVisitor<T> visitor)
public override T AcceptVisitor<T>(IAstVisitor<T> visitor)
{
return visitor.VisitUsingStatement (this);
return visitor.VisitUsingStatement(this);
}
public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data)
public override S AcceptVisitor<T, S>(IAstVisitor<T, S> visitor, T data)
{
return visitor.VisitUsingStatement (this, data);
return visitor.VisitUsingStatement(this, data);
}
protected internal override bool DoMatch(AstNode other, PatternMatching.Match match)
{
UsingStatement o = other as UsingStatement;
return o != null && this.ResourceAcquisition.DoMatch(o.ResourceAcquisition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
return o != null && this.IsAsync == o.IsAsync && this.ResourceAcquisition.DoMatch(o.ResourceAcquisition, match) && this.EmbeddedStatement.DoMatch(o.EmbeddedStatement, match);
}
}
}

18
ICSharpCode.Decompiler/CSharp/Syntax/TypeSystemAstBuilder.cs

@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -47,7 +47,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public TypeSystemAstBuilder(CSharpResolver resolver)
{
if (resolver == null)
throw new ArgumentNullException("resolver");
throw new ArgumentNullException(nameof(resolver));
this.resolver = resolver;
InitProperties();
}
@ -204,7 +204,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -204,7 +204,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstType ConvertType(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
AstType astType = ConvertTypeHelper(type);
AddTypeAnnotation(astType, type);
return astType;
@ -579,7 +579,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -579,7 +579,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstType ConvertAttributeType(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
AstType astType = ConvertTypeHelper(type);
string shortName = null;
@ -663,7 +663,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -663,7 +663,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ConvertConstantValue(ResolveResult rr)
{
if (rr == null)
throw new ArgumentNullException("rr");
throw new ArgumentNullException(nameof(rr));
bool isBoxing = false;
if (rr is ConversionResolveResult crr) {
// unpack ConversionResolveResult if necessary
@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -734,7 +734,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public Expression ConvertConstantValue(IType expectedType, IType type, object constantValue)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
if (constantValue == null) {
if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT)) {
var expr = new NullReferenceExpression();
@ -1248,7 +1248,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -1248,7 +1248,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public ParameterDeclaration ConvertParameter(IParameter parameter)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
throw new ArgumentNullException(nameof(parameter));
ParameterDeclaration decl = new ParameterDeclaration();
if (parameter.IsRef) {
decl.ParameterModifier = ParameterModifier.Ref;
@ -1286,7 +1286,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -1286,7 +1286,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public AstNode ConvertSymbol(ISymbol symbol)
{
if (symbol == null)
throw new ArgumentNullException("symbol");
throw new ArgumentNullException(nameof(symbol));
switch (symbol.SymbolKind) {
case SymbolKind.Namespace:
return ConvertNamespaceDeclaration((INamespace)symbol);
@ -1307,7 +1307,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -1307,7 +1307,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
public EntityDeclaration ConvertEntity(IEntity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");
throw new ArgumentNullException(nameof(entity));
switch (entity.SymbolKind) {
case SymbolKind.TypeDefinition:
return ConvertTypeDefinition((ITypeDefinition)entity);
@ -1772,7 +1772,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax @@ -1772,7 +1772,7 @@ namespace ICSharpCode.Decompiler.CSharp.Syntax
} else {
var declaringType = member.DeclaringType;
if (declaringType.Kind == TypeKind.Interface) {
if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride && member.Accessibility != Accessibility.Private)
if (!member.IsVirtual && !member.IsAbstract && !member.IsOverride && member.Accessibility != Accessibility.Private && member is IMethod method2 && method2.HasBody)
m |= Modifiers.Sealed;
} else {
if (member.IsAbstract)

2
ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs

@ -487,7 +487,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -487,7 +487,7 @@ namespace ICSharpCode.Decompiler.CSharp
return newTargetType.IsKnownType(KnownTypeCode.FormattableString)
|| newTargetType.IsKnownType(KnownTypeCode.IFormattable);
}
return oldTargetType.Equals(newTargetType);
return conversions.IdentityConversion(oldTargetType, newTargetType);
}
TranslatedExpression LdcI4(ICompilation compilation, int val)

2
ICSharpCode.Decompiler/CSharp/TypeSystem/AliasNamespaceReference.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public AliasNamespaceReference(string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
throw new ArgumentNullException(nameof(identifier));
this.identifier = identifier;
}

4
ICSharpCode.Decompiler/CSharp/TypeSystem/MemberTypeOrNamespaceReference.cs

@ -40,9 +40,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem @@ -40,9 +40,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public MemberTypeOrNamespaceReference(TypeOrNamespaceReference target, string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
{
if (target == null)
throw new ArgumentNullException("target");
throw new ArgumentNullException(nameof(target));
if (identifier == null)
throw new ArgumentNullException("identifier");
throw new ArgumentNullException(nameof(identifier));
this.target = target;
this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;

4
ICSharpCode.Decompiler/CSharp/TypeSystem/ResolvedUsingScope.cs

@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem @@ -44,9 +44,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public ResolvedUsingScope(CSharpTypeResolveContext context, UsingScope usingScope)
{
if (context == null)
throw new ArgumentNullException("context");
throw new ArgumentNullException(nameof(context));
if (usingScope == null)
throw new ArgumentNullException("usingScope");
throw new ArgumentNullException(nameof(usingScope));
this.parentContext = context;
this.usingScope = usingScope;
if (usingScope.Parent != null) {

2
ICSharpCode.Decompiler/CSharp/TypeSystem/SimpleTypeOrNamespaceReference.cs

@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem @@ -39,7 +39,7 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public SimpleTypeOrNamespaceReference(string identifier, IList<ITypeReference> typeArguments, NameLookupMode lookupMode = NameLookupMode.Type)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
throw new ArgumentNullException(nameof(identifier));
this.identifier = identifier;
this.typeArguments = typeArguments ?? EmptyList<ITypeReference>.Instance;
this.lookupMode = lookupMode;

4
ICSharpCode.Decompiler/CSharp/TypeSystem/UsingScope.cs

@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem @@ -67,9 +67,9 @@ namespace ICSharpCode.Decompiler.CSharp.TypeSystem
public UsingScope(UsingScope parent, string shortName)
{
if (parent == null)
throw new ArgumentNullException("parent");
throw new ArgumentNullException(nameof(parent));
if (shortName == null)
throw new ArgumentNullException("shortName");
throw new ArgumentNullException(nameof(shortName));
this.parent = parent;
this.shortName = shortName;
}

2
ICSharpCode.Decompiler/DebugInfo/DebugInfoGenerator.cs

@ -60,7 +60,7 @@ namespace ICSharpCode.Decompiler.DebugInfo @@ -60,7 +60,7 @@ namespace ICSharpCode.Decompiler.DebugInfo
public DebugInfoGenerator(IDecompilerTypeSystem typeSystem)
{
this.typeSystem = typeSystem ?? throw new ArgumentNullException("typeSystem");
this.typeSystem = typeSystem ?? throw new ArgumentNullException(nameof(typeSystem));
this.currentImportScope = globalImportScope;
}

2
ICSharpCode.Decompiler/DecompilerException.cs

@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler @@ -77,7 +77,7 @@ namespace ICSharpCode.Decompiler
string ToString(Exception exception)
{
if (exception == null)
throw new ArgumentNullException("exception");
throw new ArgumentNullException(nameof(exception));
string exceptionType = GetTypeName(exception);
string stacktrace = GetStackTrace(exception);
while (exception.InnerException != null) {

38
ICSharpCode.Decompiler/DecompilerSettings.cs

@ -108,12 +108,14 @@ namespace ICSharpCode.Decompiler @@ -108,12 +108,14 @@ namespace ICSharpCode.Decompiler
if (languageVersion < CSharp.LanguageVersion.CSharp8_0) {
nullableReferenceTypes = false;
readOnlyMethods = false;
asyncUsingAndForEachStatement = false;
asyncEnumerator = false;
}
}
public CSharp.LanguageVersion GetMinimumRequiredVersion()
{
if (nullableReferenceTypes || readOnlyMethods)
if (nullableReferenceTypes || readOnlyMethods || asyncEnumerator || asyncUsingAndForEachStatement)
return CSharp.LanguageVersion.CSharp8_0;
if (introduceUnmanagedConstraint || tupleComparisons || stackAllocInitializers)
return CSharp.LanguageVersion.CSharp7_3;
@ -273,6 +275,24 @@ namespace ICSharpCode.Decompiler @@ -273,6 +275,24 @@ namespace ICSharpCode.Decompiler
}
}
bool asyncEnumerator = true;
/// <summary>
/// Decompile IAsyncEnumerator/IAsyncEnumerable.
/// Only has an effect if <see cref="AsyncAwait"/> is enabled.
/// </summary>
[Category("C# 8.0 / VS 2019")]
[Description("DecompilerSettings.AsyncEnumerator")]
public bool AsyncEnumerator {
get { return asyncEnumerator; }
set {
if (asyncEnumerator != value) {
asyncEnumerator = value;
OnPropertyChanged();
}
}
}
bool decimalConstants = true;
/// <summary>
@ -846,7 +866,7 @@ namespace ICSharpCode.Decompiler @@ -846,7 +866,7 @@ namespace ICSharpCode.Decompiler
bool readOnlyMethods = true;
[Category("C# 8.0 / VS 2019")]
[Description("DecompilerSettings.IsReadOnlyAttributeShouldBeReplacedWithReadonlyInModifiersOnStructsParameters")]
[Description("DecompilerSettings.ReadOnlyMethods")]
public bool ReadOnlyMethods {
get { return readOnlyMethods; }
set {
@ -857,6 +877,20 @@ namespace ICSharpCode.Decompiler @@ -857,6 +877,20 @@ namespace ICSharpCode.Decompiler
}
}
bool asyncUsingAndForEachStatement = true;
[Category("C# 8.0 / VS 2019")]
[Description("DecompilerSettings.DetectAsyncUsingAndForeachStatements")]
public bool AsyncUsingAndForEachStatement {
get { return asyncUsingAndForEachStatement; }
set {
if (asyncUsingAndForEachStatement != value) {
asyncUsingAndForEachStatement = value;
OnPropertyChanged();
}
}
}
bool introduceUnmanagedConstraint = true;
/// <summary>

10
ICSharpCode.Decompiler/Documentation/IdStringProvider.cs

@ -94,7 +94,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -94,7 +94,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static string GetTypeName(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
StringBuilder b = new StringBuilder();
AppendTypeName(b, type, false);
return b.ToString();
@ -194,7 +194,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -194,7 +194,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static IMemberReference ParseMemberIdString(string memberIdString)
{
if (memberIdString == null)
throw new ArgumentNullException("memberIdString");
throw new ArgumentNullException(nameof(memberIdString));
if (memberIdString.Length < 2 || memberIdString[1] != ':')
throw new ReflectionNameParseException(0, "Missing type tag");
char typeChar = memberIdString[0];
@ -242,7 +242,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -242,7 +242,7 @@ namespace ICSharpCode.Decompiler.Documentation
public static ITypeReference ParseTypeName(string typeName)
{
if (typeName == null)
throw new ArgumentNullException("typeName");
throw new ArgumentNullException(nameof(typeName));
int pos = 0;
if (typeName.StartsWith("T:", StringComparison.Ordinal))
pos = 2;
@ -378,9 +378,9 @@ namespace ICSharpCode.Decompiler.Documentation @@ -378,9 +378,9 @@ namespace ICSharpCode.Decompiler.Documentation
public static IEntity FindEntity(string idString, ITypeResolveContext context)
{
if (idString == null)
throw new ArgumentNullException("idString");
throw new ArgumentNullException(nameof(idString));
if (context == null)
throw new ArgumentNullException("context");
throw new ArgumentNullException(nameof(context));
if (idString.StartsWith("T:", StringComparison.Ordinal)) {
return ParseTypeName(idString.Substring(2)).Resolve(context).GetDefinition();
} else {

4
ICSharpCode.Decompiler/Documentation/XmlDocumentationElement.cs

@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -55,7 +55,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationElement(XElement element, IEntity declaringEntity, Func<string, IEntity> crefResolver)
{
if (element == null)
throw new ArgumentNullException("element");
throw new ArgumentNullException(nameof(element));
this.element = element;
this.declaringEntity = declaringEntity;
this.crefResolver = crefResolver;
@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -67,7 +67,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationElement(string text, IEntity declaringEntity)
{
if (text == null)
throw new ArgumentNullException("text");
throw new ArgumentNullException(nameof(text));
this.declaringEntity = declaringEntity;
this.textContent = text;
}

13
ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs

@ -24,6 +24,7 @@ using System.Runtime.Serialization; @@ -24,6 +24,7 @@ using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.Documentation
{
@ -61,7 +62,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -61,7 +62,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationCache(int size = 50)
{
if (size <= 0)
throw new ArgumentOutOfRangeException("size", size, "Value must be positive");
throw new ArgumentOutOfRangeException(nameof(size), size, "Value must be positive");
this.entries = new KeyValuePair<string, string>[size];
}
@ -128,7 +129,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -128,7 +129,7 @@ namespace ICSharpCode.Decompiler.Documentation
public XmlDocumentationProvider(string fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
throw new ArgumentNullException(nameof(fileName));
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) {
using (XmlTextReader xmlReader = new XmlTextReader(fs)) {
@ -327,7 +328,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -327,7 +328,7 @@ namespace ICSharpCode.Decompiler.Documentation
public string GetDocumentation(string key)
{
if (key == null)
throw new ArgumentNullException("key");
throw new ArgumentNullException(nameof(key));
return GetDocumentation(key, true);
}
@ -392,11 +393,11 @@ namespace ICSharpCode.Decompiler.Documentation @@ -392,11 +393,11 @@ namespace ICSharpCode.Decompiler.Documentation
}
} catch (IOException) {
// Ignore errors on reload; IEntity.Documentation callers aren't prepared to handle exceptions
this.index = new IndexEntry[0]; // clear index to avoid future load attempts
this.index = Empty<IndexEntry>.Array; // clear index to avoid future load attempts
return null;
} catch (XmlException) {
this.index = new IndexEntry[0]; // clear index to avoid future load attempts
return null;
this.index = Empty<IndexEntry>.Array; // clear index to avoid future load attempts
return null;
}
return GetDocumentation(key, allowReload: false); // prevent infinite reload loops
}

1
ICSharpCode.Decompiler/ICSharpCode.Decompiler.csproj

@ -64,6 +64,7 @@ @@ -64,6 +64,7 @@
<Compile Include="CSharp\RequiredNamespaceCollector.cs" />
<Compile Include="CSharp\SequencePointBuilder.cs" />
<Compile Include="Documentation\XmlDocumentationElement.cs" />
<Compile Include="IL\ControlFlow\AwaitInFinallyTransform.cs" />
<Compile Include="Solution\ProjectId.cs" />
<Compile Include="Solution\ProjectItem.cs" />
<Compile Include="Solution\SolutionCreator.cs" />

576
ICSharpCode.Decompiler/IL/ControlFlow/AsyncAwaitDecompiler.cs

@ -62,14 +62,16 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -62,14 +62,16 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
{
Void,
Task,
TaskOfT
TaskOfT,
AsyncEnumerator,
AsyncEnumerable
}
ILTransformContext context;
// These fields are set by MatchTaskCreationPattern()
IType taskType; // return type of the async method
IType underlyingReturnType; // return type of the method (only the "T" for Task{T})
// These fields are set by MatchTaskCreationPattern() or MatchEnumeratorCreationNewObj()
IType taskType; // return type of the async method; or IAsyncEnumerable{T}/IAsyncEnumerator{T}
IType underlyingReturnType; // return type of the method (only the "T" for Task{T}), for async enumerators this is the type being yielded
AsyncMethodType methodType;
ITypeDefinition stateMachineType;
ITypeDefinition builderType;
@ -78,15 +80,18 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -78,15 +80,18 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
int initialState;
Dictionary<IField, ILVariable> fieldToParameterMap = new Dictionary<IField, ILVariable>();
Dictionary<ILVariable, ILVariable> cachedFieldToParameterMap = new Dictionary<ILVariable, ILVariable>();
IField disposeModeField; // 'disposeMode' field (IAsyncEnumerable/IAsyncEnumerator only)
// These fields are set by AnalyzeMoveNext():
ILFunction moveNextFunction;
ILVariable cachedStateVar; // variable in MoveNext that caches the stateField.
TryCatch mainTryCatch;
Block setResultAndExitBlock; // block that is jumped to for return statements
// Note: for async enumerators, a jump to setResultAndExitBlock is a 'yield break;'
int finalState; // final state after the setResultAndExitBlock
bool finalStateKnown;
ILVariable resultVar; // the variable that gets returned by the setResultAndExitBlock
Block setResultYieldBlock; // block that is jumped to for 'yield return' statements
ILVariable doFinallyBodies;
// These fields are set by AnalyzeStateMachine():
@ -110,11 +115,12 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -110,11 +115,12 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
awaitBlocks.Clear();
awaitDebugInfos.Clear();
moveNextLeaves.Clear();
if (!MatchTaskCreationPattern(function))
if (!MatchTaskCreationPattern(function) && !MatchAsyncEnumeratorCreationPattern(function))
return;
try {
AnalyzeMoveNext();
ValidateCatchBlock();
AnalyzeDisposeAsync();
} catch (SymbolicAnalysisFailedException) {
return;
}
@ -133,7 +139,11 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -133,7 +139,11 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
TranslateCachedFieldsToLocals();
FinalizeInlineMoveNext(function);
((BlockContainer)function.Body).ExpectedResultType = underlyingReturnType.GetStackType();
if (methodType == AsyncMethodType.AsyncEnumerable || methodType == AsyncMethodType.AsyncEnumerator) {
((BlockContainer)function.Body).ExpectedResultType = StackType.Void;
} else {
((BlockContainer)function.Body).ExpectedResultType = underlyingReturnType.GetStackType();
}
// Re-run control flow simplification over the newly constructed set of gotos,
// and inlining because TranslateFieldsToLocalAccess() might have opened up new inlining opportunities.
@ -164,9 +174,14 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -164,9 +174,14 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
CopyPropagation.Propagate(stloc, context);
}
new RemoveDeadVariableInit().Run(function, context);
// Run inlining, but don't remove dead variables (they might get revived by TranslateFieldsToLocalAccess)
foreach (var block in function.Descendants.OfType<Block>()) {
// Run inlining, but don't remove dead variables (they might get revived by TranslateFieldsToLocalAccess)
ILInlining.InlineAllInBlock(function, block, context);
if (IsAsyncEnumerator) {
// Remove lone 'ldc.i4', those are sometimes left over after C# compiler
// optimizes out stores to the state variable.
block.Instructions.RemoveAll(inst => inst.OpCode == OpCode.LdcI4);
}
}
context.StepEndGroup();
}
@ -179,22 +194,26 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -179,22 +194,26 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
if (blockContainer.Blocks.Count != 1)
return false;
var body = blockContainer.EntryPoint.Instructions;
if (body.Count < 5)
if (body.Count < 4)
return false;
/* Example:
V_0 is an instance of the compiler-generated struct/class,
V_0 is an instance of the compiler-generated struct/class,
V_1 is an instance of the builder struct/class
Block IL_0000 (incoming: 1) {
stobj System.Runtime.CompilerServices.AsyncVoidMethodBuilder(ldflda [Field ICSharpCode.Decompiler.Tests.TestCases.Pretty.Async+<AwaitYield>d__3.<>t__builder](ldloca V_0), call Create())
stobj System.Int32(ldflda [Field ICSharpCode.Decompiler.Tests.TestCases.Pretty.Async+<AwaitYield>d__3.<>1__state](ldloca V_0), ldc.i4 -1)
stloc V_1(ldobj System.Runtime.CompilerServices.AsyncVoidMethodBuilder(ldflda [Field ICSharpCode.Decompiler.Tests.TestCases.Pretty.Async+<AwaitYield>d__3.<>t__builder](ldloc V_0)))
...
stobj AsyncVoidMethodBuilder(ldflda [Field Async+<AwaitYield>d__3.<>t__builder](ldloca V_0), call Create())
stobj System.Int32(ldflda [Field Async+<AwaitYield>d__3.<>1__state](ldloca V_0), ldc.i4 -1)
stloc V_1(ldobj System.Runtime.CompilerServices.AsyncVoidMethodBuilder(ldflda [Field Async+<AwaitYield>d__3.<>t__builder](ldloc V_0)))
call Start(ldloca V_1, ldloca V_0)
leave IL_0000 (or ret for non-void async methods)
}
With custom task types, it's possible that the builder is a reference type.
In that case, the variable V_1 may be inlined.
*/
// Check the second-to-last instruction (the start call) first, as we can get the most information from that
if (!(body[body.Count - 2] is Call startCall))
int pos = body.Count - 2;
if (!(body[pos] is CallInstruction startCall))
return false;
if (startCall.Method.Name != "Start")
return false;
@ -223,18 +242,21 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -223,18 +242,21 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
if (startCall.Arguments.Count != 2)
return false;
if (!startCall.Arguments[0].MatchLdLocRef(out ILVariable builderVar))
return false;
ILInstruction loadBuilderExpr = startCall.Arguments[0];
if (!startCall.Arguments[1].MatchLdLoca(out ILVariable stateMachineVar))
return false;
stateMachineType = stateMachineVar.Type.GetDefinition();
if (stateMachineType == null)
return false;
pos--;
// Check third-to-last instruction (copy of builder)
// stloc builder(ldfld StateMachine::<>t__builder(ldloc stateMachine))
if (!body[body.Count - 3].MatchStLoc(builderVar, out var loadBuilderExpr))
return false;
if (loadBuilderExpr.MatchLdLocRef(out ILVariable builderVar)) {
// Check third-to-last instruction (copy of builder)
// stloc builder(ldfld StateMachine::<>t__builder(ldloc stateMachine))
if (!body[pos].MatchStLoc(builderVar, out loadBuilderExpr))
return false;
pos--;
}
if (!loadBuilderExpr.MatchLdFld(out var loadStateMachineForBuilderExpr, out builderField))
return false;
builderField = (IField)builderField.MemberDefinition;
@ -262,22 +284,25 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -262,22 +284,25 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
if (builderField2.MemberDefinition != builderField)
return false;
if (!target.MatchLdLocRef(stateMachineVar))
if (!(target.MatchLdLoc(stateMachineVar) || target.MatchLdLoca(stateMachineVar)))
return false;
}
// Check the last field assignment - this should be the state field
// stfld <>1__state(ldloca stateField, ldc.i4 -1)
if (!MatchStFld(body[body.Count - 4], stateMachineVar, out stateField, out var initialStateExpr))
if (!MatchStFld(body[pos], stateMachineVar, out stateField, out var initialStateExpr))
return false;
if (!initialStateExpr.MatchLdcI4(out initialState))
return false;
if (initialState != -1)
return false;
pos--;
// Check the second-to-last field assignment - this should be the builder field
// stfld StateMachine.builder(ldloca stateMachine, call Create())
if (!MatchStFld(body[body.Count - 5], stateMachineVar, out var builderField3, out var builderInitialization))
if (pos < 0)
return false;
if (!MatchStFld(body[pos], stateMachineVar, out var builderField3, out var builderInitialization))
return false;
if (builderField3 != builderField)
return false;
@ -286,7 +311,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -286,7 +311,8 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
if (createCall.Method.Name != "Create" || createCall.Arguments.Count != 0)
return false;
int pos = 0;
int stopPos = pos;
pos = 0;
if (stateMachineType.Kind == TypeKind.Class) {
// If state machine is a class, the first instruction creates an instance:
// stloc stateMachine(newobj StateMachine.ctor())
@ -296,15 +322,19 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -296,15 +322,19 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
return false;
pos++;
}
for (; pos < body.Count - 5; pos++) {
for (; pos < stopPos; pos++) {
// stfld StateMachine.field(ldloca stateMachine, ldvar(param))
if (!MatchStFld(body[pos], stateMachineVar, out var field, out var fieldInit))
return false;
if (!fieldInit.MatchLdLoc(out var v))
return false;
if (v.Kind != VariableKind.Parameter)
if (fieldInit.MatchLdLoc(out var v) && v.Kind == VariableKind.Parameter) {
// OK, copies parameter into state machine
fieldToParameterMap[field] = v;
} else if (fieldInit is LdObj ldobj && ldobj.Target.MatchLdThis()) {
// stfld <>4__this(ldloc stateMachine, ldobj AsyncInStruct(ldloc this))
fieldToParameterMap[field] = ((LdLoc)ldobj.Target).Variable;
} else {
return false;
fieldToParameterMap[field] = v;
}
}
return true;
@ -337,6 +367,164 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -337,6 +367,164 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
#endregion
#region MatchAsyncEnumeratorCreationPattern
private bool MatchAsyncEnumeratorCreationPattern(ILFunction function)
{
if (!context.Settings.AsyncEnumerator)
return false;
taskType = function.ReturnType;
if (taskType.IsKnownType(KnownTypeCode.IAsyncEnumeratorOfT)) {
methodType = AsyncMethodType.AsyncEnumerator;
} else if (taskType.IsKnownType(KnownTypeCode.IAsyncEnumerableOfT)) {
methodType = AsyncMethodType.AsyncEnumerable;
} else {
return false;
}
underlyingReturnType = taskType.TypeArguments.Single();
if (!(function.Body is BlockContainer blockContainer))
return false;
if (blockContainer.Blocks.Count != 1)
return false;
var body = blockContainer.EntryPoint;
if (body.Instructions.Count == 1) {
// No parameters passed to enumerator (not even 'this'):
// ret(newobj(...))
if (!body.Instructions[0].MatchReturn(out var newObj))
return false;
if (MatchEnumeratorCreationNewObj(newObj, context, out initialState, out stateMachineType)) {
// HACK: the normal async/await logic expects 'initialState' to be the 'in progress' state
initialState = -1;
try {
AnalyzeEnumeratorCtor(((NewObj)newObj).Method, context, out builderField, out builderType, out stateField);
} catch (SymbolicAnalysisFailedException) {
return false;
}
return true;
} else {
return false;
}
} else {
// stloc v(newobj<CountUpSlowly> d__0..ctor(ldc.i4 - 2))
// stfld <>4__this(ldloc v, ldloc this)
// stfld <>3__otherParam(ldloc v, ldloc otherParam)
// leave IL_0000(ldloc v)
int pos = 0;
if (!body.Instructions[pos].MatchStLoc(out var v, out var newObj))
return false;
if (!MatchEnumeratorCreationNewObj(newObj, context, out initialState, out stateMachineType))
return false;
pos++;
while (MatchStFld(body.Instructions[pos], v, out var field, out var value)) {
if (value.MatchLdLoc(out var p) && p.Kind == VariableKind.Parameter) {
fieldToParameterMap[field] = p;
} else if (value is LdObj ldobj && ldobj.Target.MatchLdThis()) {
fieldToParameterMap[field] = ((LdLoc)ldobj.Target).Variable;
} else {
return false;
}
pos++;
}
if (!body.Instructions[pos].MatchReturn(out var returnValue))
return false;
if (!returnValue.MatchLdLoc(v))
return false;
// HACK: the normal async/await logic expects 'initialState' to be the 'in progress' state
initialState = -1;
try {
AnalyzeEnumeratorCtor(((NewObj)newObj).Method, context, out builderField, out builderType, out stateField);
if (methodType == AsyncMethodType.AsyncEnumerable) {
ResolveIEnumerableIEnumeratorFieldMapping();
}
} catch (SymbolicAnalysisFailedException) {
return false;
}
return true;
}
}
static bool MatchEnumeratorCreationNewObj(ILInstruction inst, ILTransformContext context,
out int initialState, out ITypeDefinition stateMachineType)
{
initialState = default;
stateMachineType = default;
// newobj(CurrentType/...::.ctor, ldc.i4(-2))
if (!(inst is NewObj newObj))
return false;
if (newObj.Arguments.Count != 1)
return false;
if (!newObj.Arguments[0].MatchLdcI4(out initialState))
return false;
stateMachineType = newObj.Method.DeclaringTypeDefinition;
if (stateMachineType == null)
return false;
if (stateMachineType.DeclaringTypeDefinition != context.Function.Method.DeclaringTypeDefinition)
return false;
return IsCompilerGeneratorAsyncEnumerator(
(TypeDefinitionHandle)stateMachineType.MetadataToken,
context.TypeSystem.MainModule.metadata);
}
public static bool IsCompilerGeneratorAsyncEnumerator(TypeDefinitionHandle type, MetadataReader metadata)
{
TypeDefinition td;
if (type.IsNil || !type.IsCompilerGeneratedOrIsInCompilerGeneratedClass(metadata) || (td = metadata.GetTypeDefinition(type)).GetDeclaringType().IsNil)
return false;
foreach (var i in td.GetInterfaceImplementations()) {
var tr = metadata.GetInterfaceImplementation(i).Interface.GetFullTypeName(metadata);
if (!tr.IsNested && tr.TopLevelTypeName.Namespace == "System.Collections.Generic" && tr.TopLevelTypeName.Name == "IAsyncEnumerator" && tr.TopLevelTypeName.TypeParameterCount == 1)
return true;
}
return false;
}
static void AnalyzeEnumeratorCtor(IMethod ctor, ILTransformContext context, out IField builderField, out ITypeDefinition builderType, out IField stateField)
{
builderField = null;
stateField = null;
var ctorHandle = (MethodDefinitionHandle)ctor.MetadataToken;
Block body = YieldReturnDecompiler.SingleBlock(YieldReturnDecompiler.CreateILAst(ctorHandle, context).Body);
if (body == null)
throw new SymbolicAnalysisFailedException("Missing enumeratorCtor.Body");
// Block IL_0000 (incoming: 1) {
// call Object..ctor(ldloc this)
// stfld <>1__state(ldloc this, ldloc <>1__state)
// stfld <>t__builder(ldloc this, call Create())
// leave IL_0000 (nop)
// }
foreach (var inst in body.Instructions) {
if (inst.MatchStFld(out var target, out var field, out var value)
&& target.MatchLdThis()
&& value.MatchLdLoc(out var arg)
&& arg.Kind == VariableKind.Parameter && arg.Index == 0) {
stateField = (IField)field.MemberDefinition;
}
if (inst.MatchStFld(out target, out field, out value)
&& target.MatchLdThis()
&& value is Call call && call.Method.Name == "Create") {
builderField = (IField)field.MemberDefinition;
}
}
if (stateField == null || builderField == null)
throw new SymbolicAnalysisFailedException();
builderType = builderField.Type.GetDefinition();
if (builderType == null)
throw new SymbolicAnalysisFailedException();
}
private void ResolveIEnumerableIEnumeratorFieldMapping()
{
var getAsyncEnumerator = stateMachineType.Methods.FirstOrDefault(m => m.Name.EndsWith(".GetAsyncEnumerator", StringComparison.Ordinal));
if (getAsyncEnumerator == null)
throw new SymbolicAnalysisFailedException();
YieldReturnDecompiler.ResolveIEnumerableIEnumeratorFieldMapping((MethodDefinitionHandle)getAsyncEnumerator.MetadataToken, context, fieldToParameterMap);
}
#endregion
#region AnalyzeMoveNext
/// <summary>
/// First peek into MoveNext(); analyzes everything outside the big try-catch.
@ -353,8 +541,6 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -353,8 +541,6 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
moveNextFunction = YieldReturnDecompiler.CreateILAst(moveNextMethod, context);
if (!(moveNextFunction.Body is BlockContainer blockContainer))
throw new SymbolicAnalysisFailedException();
if (blockContainer.Blocks.Count != 2 && blockContainer.Blocks.Count != 1)
throw new SymbolicAnalysisFailedException();
if (blockContainer.EntryPoint.IncomingEdgeCount != 1)
throw new SymbolicAnalysisFailedException();
cachedStateVar = null;
@ -385,12 +571,51 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -385,12 +571,51 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
if (((BlockContainer)mainTryCatch.TryBlock).EntryPoint.Instructions[0] is StLoc initDoFinallyBodies
&& initDoFinallyBodies.Variable.Kind == VariableKind.Local
&& initDoFinallyBodies.Variable.Type.IsKnownType(KnownTypeCode.Boolean)
&& initDoFinallyBodies.Value.MatchLdcI4(1))
{
&& initDoFinallyBodies.Value.MatchLdcI4(1)) {
doFinallyBodies = initDoFinallyBodies.Variable;
}
setResultAndExitBlock = blockContainer.Blocks.ElementAtOrDefault(1);
Debug.Assert(blockContainer.Blocks[0] == blockContainer.EntryPoint); // already checked this block
pos = 1;
if (MatchYieldBlock(blockContainer, pos)) {
setResultYieldBlock = blockContainer.Blocks[pos];
pos++;
} else {
setResultYieldBlock = null;
}
setResultAndExitBlock = blockContainer.Blocks.ElementAtOrDefault(pos);
CheckSetResultAndExitBlock(blockContainer);
if (pos + 1 < blockContainer.Blocks.Count)
throw new SymbolicAnalysisFailedException("too many blocks");
}
private bool IsAsyncEnumerator => methodType == AsyncMethodType.AsyncEnumerable || methodType == AsyncMethodType.AsyncEnumerator;
bool MatchYieldBlock(BlockContainer blockContainer, int pos)
{
if (!IsAsyncEnumerator)
return false;
var block = blockContainer.Blocks.ElementAtOrDefault(pos);
if (block == null)
return false;
// call SetResult(ldflda <>v__promiseOfValueOrEnd(ldloc this), ldc.i4 1)
// leave IL_0000(nop)
if (block.Instructions.Count != 2)
return false;
if (!MatchCall(block.Instructions[0], "SetResult", out var args))
return false;
if (args.Count != 2)
return false;
if (!IsBuilderOrPromiseFieldOnThis(args[0]))
return false;
if (!args[1].MatchLdcI4(1))
return false;
return block.Instructions[1].MatchLeave(blockContainer);
}
void CheckSetResultAndExitBlock(BlockContainer blockContainer)
{
if (setResultAndExitBlock == null) {
// This block can be absent if the function never exits normally,
// but always throws an exception/loops infinitely.
@ -400,27 +625,44 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -400,27 +625,44 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
// stobj System.Int32(ldflda [Field ICSharpCode.Decompiler.Tests.TestCases.Pretty.Async+<SimpleBoolTaskMethod>d__7.<>1__state](ldloc this), ldc.i4 -2)
// call SetResult(ldflda [Field ICSharpCode.Decompiler.Tests.TestCases.Pretty.Async+<SimpleBoolTaskMethod>d__7.<>t__builder](ldloc this), ldloc result)
// [optional] call Complete(ldflda <>t__builder(ldloc this))
// leave IL_0000
if (setResultAndExitBlock.Instructions.Count != 3)
throw new SymbolicAnalysisFailedException();
if (!MatchStateAssignment(setResultAndExitBlock.Instructions[0], out finalState))
throw new SymbolicAnalysisFailedException();
finalStateKnown = true;
if (!MatchCall(setResultAndExitBlock.Instructions[1], "SetResult", out var args))
throw new SymbolicAnalysisFailedException();
if (!IsBuilderFieldOnThis(args[0]))
if (!IsBuilderOrPromiseFieldOnThis(args[0]))
throw new SymbolicAnalysisFailedException();
if (methodType == AsyncMethodType.TaskOfT) {
if (args.Count != 2)
throw new SymbolicAnalysisFailedException();
if (!args[1].MatchLdLoc(out resultVar))
throw new SymbolicAnalysisFailedException();
} else {
resultVar = null;
if (args.Count != 1)
switch (methodType) {
case AsyncMethodType.TaskOfT:
if (args.Count != 2)
throw new SymbolicAnalysisFailedException();
if (!args[1].MatchLdLoc(out resultVar))
throw new SymbolicAnalysisFailedException();
break;
case AsyncMethodType.Task:
case AsyncMethodType.Void:
resultVar = null;
if (args.Count != 1)
throw new SymbolicAnalysisFailedException();
break;
case AsyncMethodType.AsyncEnumerable:
case AsyncMethodType.AsyncEnumerator:
resultVar = null;
if (args.Count != 2)
throw new SymbolicAnalysisFailedException();
if (!args[1].MatchLdcI4(0))
throw new SymbolicAnalysisFailedException();
break;
}
int pos = 2;
if (MatchCall(setResultAndExitBlock.Instructions[pos], "Complete", out args)) {
if (!(args.Count == 1 && IsBuilderFieldOnThis(args[0])))
throw new SymbolicAnalysisFailedException();
pos++;
}
if (!setResultAndExitBlock.Instructions[2].MatchLeave(blockContainer))
if (!setResultAndExitBlock.Instructions[pos].MatchLeave(blockContainer))
throw new SymbolicAnalysisFailedException();
}
@ -431,6 +673,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -431,6 +673,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
// stloc exception(ldloc E_143)
// stfld <>1__state(ldloc this, ldc.i4 -2)
// call SetException(ldfld <>t__builder(ldloc this), ldloc exception)
// [optional] call Complete(ldfld <>t__builder(ldloc this))
// leave IL_0000
// }
// }
@ -442,9 +685,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -442,9 +685,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
if (!handler.Filter.MatchLdcI4(1))
throw new SymbolicAnalysisFailedException();
var catchBlock = YieldReturnDecompiler.SingleBlock(handler.Body);
catchHandlerOffset = catchBlock.StartILOffset;
if (catchBlock?.Instructions.Count != 4)
if (catchBlock == null)
throw new SymbolicAnalysisFailedException();
catchHandlerOffset = catchBlock.StartILOffset;
// stloc exception(ldloc E_143)
if (!(catchBlock.Instructions[0] is StLoc stloc))
throw new SymbolicAnalysisFailedException();
@ -465,12 +708,21 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -465,12 +708,21 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
throw new SymbolicAnalysisFailedException();
if (args.Count != 2)
throw new SymbolicAnalysisFailedException();
if (!IsBuilderFieldOnThis(args[0]))
if (!IsBuilderOrPromiseFieldOnThis(args[0]))
throw new SymbolicAnalysisFailedException();
if (!args[1].MatchLdLoc(stloc.Variable))
throw new SymbolicAnalysisFailedException();
int pos = 3;
// [optional] call Complete(ldfld <>t__builder(ldloc this))
if (MatchCall(catchBlock.Instructions[pos], "Complete", out args)) {
if (!(args.Count == 1 && IsBuilderFieldOnThis(args[0])))
throw new SymbolicAnalysisFailedException();
pos++;
}
// leave IL_0000
if (!catchBlock.Instructions[3].MatchLeave((BlockContainer)moveNextFunction.Body))
if (!catchBlock.Instructions[pos].MatchLeave((BlockContainer)moveNextFunction.Body))
throw new SymbolicAnalysisFailedException();
}
@ -490,19 +742,55 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -490,19 +742,55 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
return target.MatchLdThis() && field.MemberDefinition == builderField;
}
bool IsBuilderOrPromiseFieldOnThis(ILInstruction inst)
{
if (methodType == AsyncMethodType.AsyncEnumerable || methodType == AsyncMethodType.AsyncEnumerator) {
return true; // TODO: check against uses of promise fields in other methods?
} else {
return IsBuilderFieldOnThis(inst);
}
}
bool MatchStateAssignment(ILInstruction inst, out int newState)
{
// stfld(StateMachine::<>1__state, ldloc(this), ldc.i4(stateId))
if (inst.MatchStFld(out var target, out var field, out var value)
&& target.MatchLdThis()
&& StackSlotValue(target).MatchLdThis()
&& field.MemberDefinition == stateField
&& value.MatchLdcI4(out newState))
&& StackSlotValue(value).MatchLdcI4(out newState))
{
return true;
}
newState = 0;
return false;
}
/// <summary>
/// Analyse the DisposeAsync() method in order to find the disposeModeField.
/// </summary>
private void AnalyzeDisposeAsync()
{
disposeModeField = null;
if (!IsAsyncEnumerator) {
return;
}
var disposeAsync = stateMachineType.Methods.FirstOrDefault(m => m.Name.EndsWith(".DisposeAsync", StringComparison.Ordinal));
if (disposeAsync == null)
throw new SymbolicAnalysisFailedException("Could not find DisposeAsync()");
var disposeAsyncHandle = (MethodDefinitionHandle)disposeAsync.MetadataToken;
var function = YieldReturnDecompiler.CreateILAst(disposeAsyncHandle, context);
foreach (var store in function.Descendants) {
if (!store.MatchStFld(out var target, out var field, out var value))
continue;
if (!target.MatchLdThis())
continue;
if (!value.MatchLdcI4(1))
throw new SymbolicAnalysisFailedException();
if (disposeModeField != null)
throw new SymbolicAnalysisFailedException("Multiple stores to disposeMode in DisposeAsync()");
disposeModeField = (IField)field.MemberDefinition;
}
}
#endregion
#region InlineBodyOfMoveNext
@ -513,6 +801,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -513,6 +801,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
function.AsyncReturnType = underlyingReturnType;
function.MoveNextMethod = moveNextFunction.Method;
function.CodeSize = moveNextFunction.CodeSize;
function.IsIterator = IsAsyncEnumerator;
moveNextFunction.Variables.Clear();
moveNextFunction.ReleaseRef();
foreach (var branch in function.Descendants.OfType<Branch>()) {
@ -520,6 +809,10 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -520,6 +809,10 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
branch.ReplaceWith(new Leave((BlockContainer)function.Body, resultVar == null ? null : new LdLoc(resultVar)).WithILRange(branch));
}
}
if (setResultYieldBlock != null) {
// We still might have branches to this block; and we can't quite yet get rid of it.
((BlockContainer)function.Body).Blocks.Add(setResultYieldBlock);
}
foreach (var leave in function.Descendants.OfType<Leave>()) {
if (leave.TargetContainer == moveNextFunction.Body) {
leave.TargetContainer = (BlockContainer)function.Body;
@ -563,7 +856,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -563,7 +856,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
/// </summary>
void AnalyzeStateMachine(ILFunction function)
{
context.Step("AnalyzeStateMachine()", function);
context.StepStartGroup("AnalyzeStateMachine()", function);
smallestAwaiterVarIndex = int.MaxValue;
foreach (var container in function.Descendants.OfType<BlockContainer>()) {
// Use a separate state range analysis per container.
@ -577,6 +870,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -577,6 +870,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
context.CancellationToken.ThrowIfCancellationRequested();
if (block.Instructions.Last() is Leave leave && moveNextLeaves.Contains(leave)) {
// This is likely an 'await' block
context.Step($"AnalyzeAwaitBlock({block.StartILOffset:x4})", block);
if (AnalyzeAwaitBlock(block, out var awaiterVar, out var awaiterField, out int state, out int yieldOffset)) {
block.Instructions.Add(new Await(new LdLoca(awaiterVar)));
Block targetBlock = stateToBlockMap.GetOrDefault(state);
@ -591,7 +885,25 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -591,7 +885,25 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
smallestAwaiterVarIndex = awaiterVar.Index.Value;
}
}
} else if (block.Instructions.Last().MatchBranch(setResultYieldBlock)) {
// This is a 'yield return' in an async enumerator.
context.Step($"AnalyzeYieldReturn({block.StartILOffset:x4})", block);
if (AnalyzeYieldReturn(block, out var yieldValue, out int state)) {
block.Instructions.Add(new YieldReturn(yieldValue));
Block targetBlock = stateToBlockMap.GetOrDefault(state);
if (targetBlock != null) {
block.Instructions.Add(new Branch(targetBlock));
} else {
block.Instructions.Add(new InvalidBranch("Could not find block for state " + state));
}
} else {
block.Instructions.Add(new InvalidBranch("Could not detect 'yield return'"));
}
}
TransformYieldBreak(block);
}
foreach (var block in container.Blocks) {
SimplifyIfDisposeMode(block);
}
// Skip the state dispatcher and directly jump to the initial state
var entryPoint = stateToBlockMap.GetOrDefault(initialState);
@ -604,6 +916,99 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -604,6 +916,99 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
container.SortBlocks(deleteUnreachableBlocks: true);
}
context.StepEndGroup();
}
private bool TransformYieldBreak(Block block)
{
// stfld disposeMode(ldloc this, ldc.i4 1)
// br nextBlock
if (block.Instructions.Count < 2)
return false;
if (!(block.Instructions.Last() is Branch branch))
return false;
if (!block.Instructions[block.Instructions.Count - 2].MatchStFld(out var target, out var field, out var value))
return false;
if (!target.MatchLdThis())
return false;
if (field.MemberDefinition != disposeModeField)
return false;
if (!value.MatchLdcI4(1))
return false;
// Detected a 'yield break;'
context.Step($"TransformYieldBreak({block.StartILOffset:x4})", block);
var breakTarget = FindYieldBreakTarget(branch.TargetBlock);
if (breakTarget is Block targetBlock) {
branch.TargetBlock = targetBlock;
} else {
Debug.Assert(breakTarget is BlockContainer);
branch.ReplaceWith(new Leave((BlockContainer)breakTarget).WithILRange(branch));
}
return true;
}
ILInstruction FindYieldBreakTarget(Block block)
{
// We'll follow the branch and evaluate the following instructions
// under the assumption that disposeModeField==1, which lets us follow a series of jumps
// to determine the final target.
var visited = new HashSet<Block>();
var evalContext = new SymbolicEvaluationContext(disposeModeField);
while (true) {
for (int i = 0; i < block.Instructions.Count; i++) {
ILInstruction inst = block.Instructions[i];
while (inst.MatchIfInstruction(out var condition, out var trueInst, out var falseInst)) {
var condVal = evalContext.Eval(condition).AsBool();
if (condVal.Type == SymbolicValueType.IntegerConstant) {
inst = condVal.Constant != 0 ? trueInst : falseInst;
} else if (condVal.Type == SymbolicValueType.StateInSet) {
inst = condVal.ValueSet.Contains(1) ? trueInst : falseInst;
} else {
return block;
}
}
if (inst.MatchBranch(out var targetBlock)) {
if (visited.Add(block)) {
block = targetBlock;
break; // continue with next block
} else {
return block; // infinite loop detected
}
} else if (inst is Leave leave && leave.Value.OpCode == OpCode.Nop) {
return leave.TargetContainer;
} else if (inst.OpCode == OpCode.Nop) {
continue; // continue with next instruction in this block
} else {
return block;
}
}
}
}
private bool SimplifyIfDisposeMode(Block block)
{
// Occasionally Roslyn optimizes out an "if (disposeMode)", but keeps the
// disposeMode field access. Get rid of those field accesses:
block.Instructions.RemoveAll(MatchLdDisposeMode);
// if (logic.not(ldfld disposeMode(ldloc this))) br falseInst
// br trueInst
if (!block.MatchIfAtEndOfBlock(out var condition, out _, out var falseInst))
return false;
if (!MatchLdDisposeMode(condition))
return false;
context.Step($"SimplifyIfDisposeMode({block.StartILOffset:x4})", block);
block.Instructions[block.Instructions.Count - 2] = falseInst;
block.Instructions.RemoveAt(block.Instructions.Count - 1);
return true;
bool MatchLdDisposeMode(ILInstruction inst)
{
if (!inst.MatchLdFld(out var target, out var field))
return false;
return target.MatchLdThis() && field.MemberDefinition == disposeModeField;
}
}
bool AnalyzeAwaitBlock(Block block, out ILVariable awaiter, out IField awaiterField, out int state, out int yieldOffset)
@ -705,6 +1110,50 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -705,6 +1110,50 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
return inst;
}
private bool AnalyzeYieldReturn(Block block, out ILInstruction yieldValue, out int newState)
{
yieldValue = default;
newState = default;
Debug.Assert(block.Instructions.Last().MatchBranch(setResultYieldBlock));
// stfld current(ldloc this, ldstr "yieldValue")
// stloc S_45(ldloc this)
// stloc S_46(ldc.i4 -5)
// stloc V_0(ldloc S_46)
// stfld stateField(ldloc S_45, ldloc S_46)
// br setResultYieldBlock
int pos = block.Instructions.Count - 2;
// Immediately before the 'yield return', there should be a state assignment:
if (pos < 0 || !MatchStateAssignment(block.Instructions[pos], out newState))
return false;
pos--;
if (pos >= 0 && block.Instructions[pos].MatchStLoc(cachedStateVar, out var cachedStateNewValue)) {
if (StackSlotValue(cachedStateNewValue).MatchLdcI4(newState)) {
pos--; // OK, ignore V_0 store
} else {
return false;
}
}
while (pos >= 0 && block.Instructions[pos] is StLoc stloc) {
if (stloc.Variable.Kind != VariableKind.StackSlot)
return false;
if (!SemanticHelper.IsPure(stloc.Value.Flags))
return false;
pos--;
}
if (pos < 0 || !block.Instructions[pos].MatchStFld(out var target, out var field, out yieldValue))
return false;
if (!StackSlotValue(target).MatchLdThis())
return false;
// TODO: check that we are accessing the current field (compare with get_Current)
block.Instructions.RemoveRange(pos, block.Instructions.Count - pos);
return true;
}
#endregion
#region DetectAwaitPattern
@ -761,7 +1210,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -761,7 +1210,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
// continue matching call get_IsCompleted(ldloca awaiterVar)
if (!MatchCall(condition, "get_IsCompleted", out var isCompletedArgs) || isCompletedArgs.Count != 1)
return;
if (!isCompletedArgs[0].MatchLdLocRef(awaiterVar))
if (!UnwrapConvUnknown(isCompletedArgs[0]).MatchLdLocRef(awaiterVar))
return;
// Check awaitBlock and resumeBlock:
if (!awaitBlocks.TryGetValue(awaitBlock, out var awaitBlockData))
@ -779,14 +1228,14 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -779,14 +1228,14 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
return;
if (!MatchCall(getResultCall, "GetResult", out var getResultArgs) || getResultArgs.Count != 1)
return;
if (!getResultArgs[0].MatchLdLocRef(awaiterVar))
if (!UnwrapConvUnknown(getResultArgs[0]).MatchLdLocRef(awaiterVar))
return;
// All checks successful, let's transform.
context.Step("Transform await pattern", block);
block.Instructions.RemoveAt(block.Instructions.Count - 3); // remove getAwaiter call
block.Instructions.RemoveAt(block.Instructions.Count - 2); // remove if (isCompleted)
((Branch)block.Instructions.Last()).TargetBlock = completedBlock; // instead, directly jump to completed block
Await awaitInst = new Await(getAwaiterCall.Arguments.Single());
Await awaitInst = new Await(UnwrapConvUnknown(getAwaiterCall.Arguments.Single()));
awaitInst.GetResultMethod = getResultCall.Method;
awaitInst.GetAwaiterMethod = getAwaiterCall.Method;
getResultCall.ReplaceWith(awaitInst);
@ -798,7 +1247,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -798,7 +1247,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
}
}
}
static ILInstruction UnwrapConvUnknown(ILInstruction inst)
{
if (inst is Conv conv && conv.TargetType == PrimitiveType.Unknown) {
return conv.Argument;
}
return inst;
}
bool CheckAwaitBlock(Block block, out Block resumeBlock, out IField stackField)
{
// awaitBlock:
@ -833,6 +1290,11 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -833,6 +1290,11 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
// stloc awaiterVar(ldfld awaiterField(ldloc this))
if (!block.Instructions[pos].MatchStLoc(awaiterVar, out var value))
return false;
if (value is CastClass cast && cast.Type.Equals(awaiterVar.Type)) {
// If the awaiter is a reference type, it might get stored in a field of type `object`
// and cast back to the awaiter type in the resume block
value = cast.Argument;
}
if (!value.MatchLdFld(out var target, out var field))
return false;
if (!target.MatchLdThis())
@ -845,7 +1307,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -845,7 +1307,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
if (block.Instructions[pos].MatchStFld(out target, out field, out value)
&& target.MatchLdThis()
&& field.Equals(awaiterField)
&& value.OpCode == OpCode.DefaultValue)
&& (value.OpCode == OpCode.DefaultValue || value.OpCode == OpCode.LdNull))
{
pos++;
} else {

218
ICSharpCode.Decompiler/IL/ControlFlow/AwaitInCatchTransform.cs

@ -18,12 +18,8 @@ @@ -18,12 +18,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ICSharpCode.Decompiler.FlowAnalysis;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL.ControlFlow
{
@ -192,218 +188,4 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -192,218 +188,4 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
return false;
}
}
class AwaitInFinallyTransform
{
public static void Run(ILFunction function, ILTransformContext context)
{
HashSet<BlockContainer> changedContainers = new HashSet<BlockContainer>();
// analyze all try-catch statements in the function
foreach (var tryCatch in function.Descendants.OfType<TryCatch>().ToArray()) {
if (!(tryCatch.Parent?.Parent is BlockContainer container))
continue;
// await in finally uses a single catch block with catch-type object
if (tryCatch.Handlers.Count != 1 || !(tryCatch.Handlers[0].Body is BlockContainer catchBlockContainer) || !tryCatch.Handlers[0].Variable.Type.IsKnownType(KnownTypeCode.Object))
continue;
// and consists of an assignment to a temporary that is used outside the catch block
// and a jump to the finally block
var block = catchBlockContainer.EntryPoint;
if (block.Instructions.Count < 2 || !block.Instructions[0].MatchStLoc(out var globalCopyVar, out var value) || !value.MatchLdLoc(tryCatch.Handlers[0].Variable))
continue;
if (block.Instructions.Count == 3) {
if (!block.Instructions[1].MatchStLoc(out var globalCopyVarTemp, out value) || !value.MatchLdLoc(globalCopyVar))
continue;
globalCopyVar = globalCopyVarTemp;
}
if (!block.Instructions[block.Instructions.Count - 1].MatchBranch(out var entryPointOfFinally))
continue;
// globalCopyVar should only be used once, at the end of the finally-block
if (globalCopyVar.LoadCount != 1 || globalCopyVar.StoreCount > 2)
continue;
var tempStore = globalCopyVar.LoadInstructions[0].Parent as StLoc;
if (tempStore == null || !MatchExceptionCaptureBlock(tempStore, out var exitOfFinally, out var afterFinally, out var blocksToRemove))
continue;
if (!MatchAfterFinallyBlock(ref afterFinally, blocksToRemove, out bool removeFirstInstructionInAfterFinally))
continue;
var cfg = new ControlFlowGraph(container, context.CancellationToken);
var exitOfFinallyNode = cfg.GetNode(exitOfFinally);
var entryPointOfFinallyNode = cfg.GetNode(entryPointOfFinally);
var additionalBlocksInFinally = new HashSet<Block>();
var invalidExits = new List<ControlFlowNode>();
TraverseDominatorTree(entryPointOfFinallyNode);
void TraverseDominatorTree(ControlFlowNode node)
{
if (entryPointOfFinallyNode != node) {
if (entryPointOfFinallyNode.Dominates(node))
additionalBlocksInFinally.Add((Block)node.UserData);
else
invalidExits.Add(node);
}
if (node == exitOfFinallyNode)
return;
foreach (var child in node.DominatorTreeChildren) {
TraverseDominatorTree(child);
}
}
if (invalidExits.Any())
continue;
context.Step("Inline finally block with await", tryCatch.Handlers[0]);
foreach (var blockToRemove in blocksToRemove) {
blockToRemove.Remove();
}
var finallyContainer = new BlockContainer();
entryPointOfFinally.Remove();
if (removeFirstInstructionInAfterFinally)
afterFinally.Instructions.RemoveAt(0);
changedContainers.Add(container);
var outer = BlockContainer.FindClosestContainer(container.Parent);
if (outer != null) changedContainers.Add(outer);
finallyContainer.Blocks.Add(entryPointOfFinally);
finallyContainer.AddILRange(entryPointOfFinally);
exitOfFinally.Instructions.RemoveRange(tempStore.ChildIndex, 3);
exitOfFinally.Instructions.Add(new Leave(finallyContainer));
foreach (var branchToFinally in container.Descendants.OfType<Branch>()) {
if (branchToFinally.TargetBlock == entryPointOfFinally)
branchToFinally.ReplaceWith(new Branch(afterFinally));
}
foreach (var newBlock in additionalBlocksInFinally) {
newBlock.Remove();
finallyContainer.Blocks.Add(newBlock);
finallyContainer.AddILRange(newBlock);
}
tryCatch.ReplaceWith(new TryFinally(tryCatch.TryBlock, finallyContainer).WithILRange(tryCatch.TryBlock));
}
// clean up all modified containers
foreach (var container in changedContainers)
container.SortBlocks(deleteUnreachableBlocks: true);
}
/// <summary>
/// Block finallyHead (incoming: 2) {
/// [body of finally]
/// stloc V_4(ldloc V_1)
/// if (comp(ldloc V_4 == ldnull)) br afterFinally
/// br typeCheckBlock
/// }
///
/// Block typeCheckBlock (incoming: 1) {
/// stloc S_110(isinst System.Exception(ldloc V_4))
/// if (comp(ldloc S_110 != ldnull)) br captureBlock
/// br throwBlock
/// }
///
/// Block throwBlock (incoming: 1) {
/// throw(ldloc V_4)
/// }
///
/// Block captureBlock (incoming: 1) {
/// callvirt Throw(call Capture(ldloc S_110))
/// br afterFinally
/// }
///
/// Block afterFinally (incoming: 2) {
/// stloc V_1(ldnull)
/// [after finally]
/// }
/// </summary>
static bool MatchExceptionCaptureBlock(StLoc tempStore, out Block endOfFinally, out Block afterFinally, out List<Block> blocksToRemove)
{
afterFinally = null;
endOfFinally = (Block)tempStore.Parent;
blocksToRemove = new List<Block>();
int count = endOfFinally.Instructions.Count;
if (tempStore.ChildIndex != count - 3)
return false;
if (!(endOfFinally.Instructions[count - 2] is IfInstruction ifInst))
return false;
if (!endOfFinally.Instructions.Last().MatchBranch(out var typeCheckBlock))
return false;
if (!ifInst.TrueInst.MatchBranch(out afterFinally))
return false;
// match typeCheckBlock
if (typeCheckBlock.Instructions.Count != 3)
return false;
if (!typeCheckBlock.Instructions[0].MatchStLoc(out var castStore, out var cast)
|| !cast.MatchIsInst(out var arg, out var type) || !type.IsKnownType(KnownTypeCode.Exception) || !arg.MatchLdLoc(tempStore.Variable))
return false;
if (!typeCheckBlock.Instructions[1].MatchIfInstruction(out var cond, out var jumpToCaptureBlock))
return false;
if (!cond.MatchCompNotEqualsNull(out arg) || !arg.MatchLdLoc(castStore))
return false;
if (!typeCheckBlock.Instructions[2].MatchBranch(out var throwBlock))
return false;
if (!jumpToCaptureBlock.MatchBranch(out var captureBlock))
return false;
// match throwBlock
if (throwBlock.Instructions.Count != 1 || !throwBlock.Instructions[0].MatchThrow(out arg) || !arg.MatchLdLoc(tempStore.Variable))
return false;
// match captureBlock
if (captureBlock.Instructions.Count != 2)
return false;
if (!captureBlock.Instructions[1].MatchBranch(afterFinally))
return false;
if (!(captureBlock.Instructions[0] is CallVirt callVirt) || callVirt.Method.FullName != "System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw" || callVirt.Arguments.Count != 1)
return false;
if (!(callVirt.Arguments[0] is Call call) || call.Method.FullName != "System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture" || call.Arguments.Count != 1)
return false;
if (!call.Arguments[0].MatchLdLoc(castStore))
return false;
blocksToRemove.Add(typeCheckBlock);
blocksToRemove.Add(throwBlock);
blocksToRemove.Add(captureBlock);
return true;
}
static bool MatchAfterFinallyBlock(ref Block afterFinally, List<Block> blocksToRemove, out bool removeFirstInstructionInAfterFinally)
{
removeFirstInstructionInAfterFinally = false;
if (afterFinally.Instructions.Count < 2)
return false;
ILVariable globalCopyVarSplitted;
switch (afterFinally.Instructions[0]) {
case IfInstruction ifInst:
if (ifInst.Condition.MatchCompEquals(out var load, out var ldone) && ldone.MatchLdcI4(1) && load.MatchLdLoc(out var variable)) {
if (!ifInst.TrueInst.MatchBranch(out var targetBlock))
return false;
blocksToRemove.Add(afterFinally);
afterFinally = targetBlock;
return true;
} else if (ifInst.Condition.MatchCompNotEquals(out load, out ldone) && ldone.MatchLdcI4(1) && load.MatchLdLoc(out variable)) {
if (!afterFinally.Instructions[1].MatchBranch(out var targetBlock))
return false;
blocksToRemove.Add(afterFinally);
afterFinally = targetBlock;
return true;
}
return false;
case LdLoc ldLoc:
if (ldLoc.Variable.LoadCount != 1 || ldLoc.Variable.StoreCount != 1)
return false;
if (!afterFinally.Instructions[1].MatchStLoc(out globalCopyVarSplitted, out var ldnull) || !ldnull.MatchLdNull())
return false;
removeFirstInstructionInAfterFinally = true;
break;
case StLoc stloc:
globalCopyVarSplitted = stloc.Variable;
if (!stloc.Value.MatchLdNull())
return false;
break;
default:
return false;
}
if (globalCopyVarSplitted.StoreCount != 1 || globalCopyVarSplitted.LoadCount != 0)
return false;
return true;
}
}
}

242
ICSharpCode.Decompiler/IL/ControlFlow/AwaitInFinallyTransform.cs

@ -0,0 +1,242 @@ @@ -0,0 +1,242 @@
// Copyright (c) 2018 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.
using System.Collections.Generic;
using System.Linq;
using ICSharpCode.Decompiler.FlowAnalysis;
using ICSharpCode.Decompiler.IL.Transforms;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.IL.ControlFlow
{
class AwaitInFinallyTransform
{
public static void Run(ILFunction function, ILTransformContext context)
{
if (!context.Settings.AwaitInCatchFinally)
return;
HashSet<BlockContainer> changedContainers = new HashSet<BlockContainer>();
// analyze all try-catch statements in the function
foreach (var tryCatch in function.Descendants.OfType<TryCatch>().ToArray()) {
if (!(tryCatch.Parent?.Parent is BlockContainer container))
continue;
// await in finally uses a single catch block with catch-type object
if (tryCatch.Handlers.Count != 1 || !(tryCatch.Handlers[0].Body is BlockContainer catchBlockContainer) || !tryCatch.Handlers[0].Variable.Type.IsKnownType(KnownTypeCode.Object))
continue;
// and consists of an assignment to a temporary that is used outside the catch block
// and a jump to the finally block
var block = catchBlockContainer.EntryPoint;
if (block.Instructions.Count < 2 || !block.Instructions[0].MatchStLoc(out var globalCopyVar, out var value) || !value.MatchLdLoc(tryCatch.Handlers[0].Variable))
continue;
if (block.Instructions.Count == 3) {
if (!block.Instructions[1].MatchStLoc(out var globalCopyVarTemp, out value) || !value.MatchLdLoc(globalCopyVar))
continue;
globalCopyVar = globalCopyVarTemp;
}
if (!block.Instructions[block.Instructions.Count - 1].MatchBranch(out var entryPointOfFinally))
continue;
// globalCopyVar should only be used once, at the end of the finally-block
if (globalCopyVar.LoadCount != 1 || globalCopyVar.StoreCount > 2)
continue;
var tempStore = globalCopyVar.LoadInstructions[0].Parent as StLoc;
if (tempStore == null || !MatchExceptionCaptureBlock(tempStore, out var exitOfFinally, out var afterFinally, out var blocksToRemove))
continue;
if (!MatchAfterFinallyBlock(ref afterFinally, blocksToRemove, out bool removeFirstInstructionInAfterFinally))
continue;
var cfg = new ControlFlowGraph(container, context.CancellationToken);
var exitOfFinallyNode = cfg.GetNode(exitOfFinally);
var entryPointOfFinallyNode = cfg.GetNode(entryPointOfFinally);
var additionalBlocksInFinally = new HashSet<Block>();
var invalidExits = new List<ControlFlowNode>();
TraverseDominatorTree(entryPointOfFinallyNode);
void TraverseDominatorTree(ControlFlowNode node)
{
if (entryPointOfFinallyNode != node) {
if (entryPointOfFinallyNode.Dominates(node))
additionalBlocksInFinally.Add((Block)node.UserData);
else
invalidExits.Add(node);
}
if (node == exitOfFinallyNode)
return;
foreach (var child in node.DominatorTreeChildren) {
TraverseDominatorTree(child);
}
}
if (invalidExits.Any())
continue;
context.Step("Inline finally block with await", tryCatch.Handlers[0]);
foreach (var blockToRemove in blocksToRemove) {
blockToRemove.Remove();
}
var finallyContainer = new BlockContainer();
entryPointOfFinally.Remove();
if (removeFirstInstructionInAfterFinally)
afterFinally.Instructions.RemoveAt(0);
changedContainers.Add(container);
var outer = BlockContainer.FindClosestContainer(container.Parent);
if (outer != null) changedContainers.Add(outer);
finallyContainer.Blocks.Add(entryPointOfFinally);
finallyContainer.AddILRange(entryPointOfFinally);
exitOfFinally.Instructions.RemoveRange(tempStore.ChildIndex, 3);
exitOfFinally.Instructions.Add(new Leave(finallyContainer));
foreach (var branchToFinally in container.Descendants.OfType<Branch>()) {
if (branchToFinally.TargetBlock == entryPointOfFinally)
branchToFinally.ReplaceWith(new Branch(afterFinally));
}
foreach (var newBlock in additionalBlocksInFinally) {
newBlock.Remove();
finallyContainer.Blocks.Add(newBlock);
finallyContainer.AddILRange(newBlock);
}
tryCatch.ReplaceWith(new TryFinally(tryCatch.TryBlock, finallyContainer).WithILRange(tryCatch.TryBlock));
}
// clean up all modified containers
foreach (var container in changedContainers)
container.SortBlocks(deleteUnreachableBlocks: true);
}
/// <summary>
/// Block finallyHead (incoming: 2) {
/// [body of finally]
/// stloc V_4(ldloc V_1)
/// if (comp(ldloc V_4 == ldnull)) br afterFinally
/// br typeCheckBlock
/// }
///
/// Block typeCheckBlock (incoming: 1) {
/// stloc S_110(isinst System.Exception(ldloc V_4))
/// if (comp(ldloc S_110 != ldnull)) br captureBlock
/// br throwBlock
/// }
///
/// Block throwBlock (incoming: 1) {
/// throw(ldloc V_4)
/// }
///
/// Block captureBlock (incoming: 1) {
/// callvirt Throw(call Capture(ldloc S_110))
/// br afterFinally
/// }
///
/// Block afterFinally (incoming: 2) {
/// stloc V_1(ldnull)
/// [after finally]
/// }
/// </summary>
static bool MatchExceptionCaptureBlock(StLoc tempStore, out Block endOfFinally, out Block afterFinally, out List<Block> blocksToRemove)
{
afterFinally = null;
endOfFinally = (Block)tempStore.Parent;
blocksToRemove = new List<Block>();
int count = endOfFinally.Instructions.Count;
if (tempStore.ChildIndex != count - 3)
return false;
if (!(endOfFinally.Instructions[count - 2] is IfInstruction ifInst))
return false;
if (!endOfFinally.Instructions.Last().MatchBranch(out var typeCheckBlock))
return false;
if (!ifInst.TrueInst.MatchBranch(out afterFinally))
return false;
// match typeCheckBlock
if (typeCheckBlock.Instructions.Count != 3)
return false;
if (!typeCheckBlock.Instructions[0].MatchStLoc(out var castStore, out var cast)
|| !cast.MatchIsInst(out var arg, out var type) || !type.IsKnownType(KnownTypeCode.Exception) || !arg.MatchLdLoc(tempStore.Variable))
return false;
if (!typeCheckBlock.Instructions[1].MatchIfInstruction(out var cond, out var jumpToCaptureBlock))
return false;
if (!cond.MatchCompNotEqualsNull(out arg) || !arg.MatchLdLoc(castStore))
return false;
if (!typeCheckBlock.Instructions[2].MatchBranch(out var throwBlock))
return false;
if (!jumpToCaptureBlock.MatchBranch(out var captureBlock))
return false;
// match throwBlock
if (throwBlock.Instructions.Count != 1 || !throwBlock.Instructions[0].MatchThrow(out arg) || !arg.MatchLdLoc(tempStore.Variable))
return false;
// match captureBlock
if (captureBlock.Instructions.Count != 2)
return false;
if (!captureBlock.Instructions[1].MatchBranch(afterFinally))
return false;
if (!(captureBlock.Instructions[0] is CallVirt callVirt) || callVirt.Method.FullName != "System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw" || callVirt.Arguments.Count != 1)
return false;
if (!(callVirt.Arguments[0] is Call call) || call.Method.FullName != "System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture" || call.Arguments.Count != 1)
return false;
if (!call.Arguments[0].MatchLdLoc(castStore))
return false;
blocksToRemove.Add(typeCheckBlock);
blocksToRemove.Add(throwBlock);
blocksToRemove.Add(captureBlock);
return true;
}
static bool MatchAfterFinallyBlock(ref Block afterFinally, List<Block> blocksToRemove, out bool removeFirstInstructionInAfterFinally)
{
removeFirstInstructionInAfterFinally = false;
if (afterFinally.Instructions.Count < 2)
return false;
ILVariable globalCopyVarSplitted;
switch (afterFinally.Instructions[0]) {
case IfInstruction ifInst:
if (ifInst.Condition.MatchCompEquals(out var load, out var ldone) && ldone.MatchLdcI4(1) && load.MatchLdLoc(out var variable)) {
if (!ifInst.TrueInst.MatchBranch(out var targetBlock))
return false;
blocksToRemove.Add(afterFinally);
afterFinally = targetBlock;
return true;
} else if (ifInst.Condition.MatchCompNotEquals(out load, out ldone) && ldone.MatchLdcI4(1) && load.MatchLdLoc(out variable)) {
if (!afterFinally.Instructions[1].MatchBranch(out var targetBlock))
return false;
blocksToRemove.Add(afterFinally);
afterFinally = targetBlock;
return true;
}
return false;
case LdLoc ldLoc:
if (ldLoc.Variable.LoadCount != 1 || ldLoc.Variable.StoreCount != 1)
return false;
if (!afterFinally.Instructions[1].MatchStLoc(out globalCopyVarSplitted, out var ldnull) || !ldnull.MatchLdNull())
return false;
removeFirstInstructionInAfterFinally = true;
break;
case StLoc stloc:
globalCopyVarSplitted = stloc.Variable;
if (!stloc.Value.MatchLdNull())
return false;
break;
default:
return false;
}
if (globalCopyVarSplitted.StoreCount != 1 || globalCopyVarSplitted.LoadCount != 0)
return false;
return true;
}
}
}

6
ICSharpCode.Decompiler/IL/ControlFlow/ControlFlowSimplification.cs

@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
context.CancellationToken.ThrowIfCancellationRequested();
RemoveNopInstructions(block);
RemoveDeadStackStores(block, aggressive: context.Settings.RemoveDeadStores);
RemoveDeadStackStores(block, context);
InlineVariableInReturnBlock(block, context);
// 1st pass SimplifySwitchInstruction before SimplifyBranchChains()
@ -70,13 +70,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -70,13 +70,15 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
block.Instructions.RemoveAll(inst => inst.OpCode == OpCode.Nop);
}
private void RemoveDeadStackStores(Block block, bool aggressive)
private static void RemoveDeadStackStores(Block block, ILTransformContext context)
{
bool aggressive = context.Settings.RemoveDeadStores;
// Previously copy propagation did this;
// ideally the ILReader would already do this,
// for now do this here (even though it's not control-flow related).
for (int i = block.Instructions.Count - 1; i >= 0; i--) {
if (block.Instructions[i] is StLoc stloc && stloc.Variable.IsSingleDefinition && stloc.Variable.LoadCount == 0 && stloc.Variable.Kind == VariableKind.StackSlot) {
context.Step($"Remove dead stack store {stloc.Variable.Name}", stloc);
if (aggressive ? SemanticHelper.IsPure(stloc.Value.Flags) : IsSimple(stloc.Value)) {
Debug.Assert(SemanticHelper.IsPure(stloc.Value.Flags));
block.Instructions.RemoveAt(i++);

16
ICSharpCode.Decompiler/IL/ControlFlow/YieldReturnDecompiler.cs

@ -305,6 +305,16 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -305,6 +305,16 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
/// </summary>
bool MatchEnumeratorCreationNewObj(ILInstruction inst)
{
return MatchEnumeratorCreationNewObj(inst, metadata, currentType,
out enumeratorCtor, out enumeratorType);
}
internal static bool MatchEnumeratorCreationNewObj(ILInstruction inst,
MetadataReader metadata, TypeDefinitionHandle currentType,
out MethodDefinitionHandle enumeratorCtor, out TypeDefinitionHandle enumeratorType)
{
enumeratorCtor = default;
enumeratorType = default;
// newobj(CurrentType/...::.ctor, ldc.i4(-2))
if (!(inst is NewObj newObj))
return false;
@ -443,6 +453,12 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -443,6 +453,12 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
MethodDefinitionHandle getEnumeratorMethod = metadata.GetTypeDefinition(enumeratorType).GetMethods().FirstOrDefault(
m => metadata.GetString(metadata.GetMethodDefinition(m).Name).StartsWith("System.Collections.Generic.IEnumerable", StringComparison.Ordinal)
&& metadata.GetString(metadata.GetMethodDefinition(m).Name).EndsWith(".GetEnumerator", StringComparison.Ordinal));
ResolveIEnumerableIEnumeratorFieldMapping(getEnumeratorMethod, context, fieldToParameterMap);
}
internal static void ResolveIEnumerableIEnumeratorFieldMapping(MethodDefinitionHandle getEnumeratorMethod, ILTransformContext context,
Dictionary<IField, ILVariable> fieldToParameterMap)
{
if (getEnumeratorMethod.IsNil)
return; // no mappings (maybe it's just an IEnumerator implementation?)
var function = CreateILAst(getEnumeratorMethod, context);

2
ICSharpCode.Decompiler/IL/ILReader.cs

@ -666,7 +666,7 @@ namespace ICSharpCode.Decompiler.IL @@ -666,7 +666,7 @@ namespace ICSharpCode.Decompiler.IL
case ILOpCode.Conv_u:
return Push(new Conv(Pop(), PrimitiveType.U, false, Sign.None));
case ILOpCode.Conv_r_un:
return Push(new Conv(Pop(), PrimitiveType.R8, false, Sign.Unsigned));
return Push(new Conv(Pop(), PrimitiveType.R, false, Sign.Unsigned));
case ILOpCode.Conv_ovf_i1:
return Push(new Conv(Pop(), PrimitiveType.I1, true, Sign.Signed));
case ILOpCode.Conv_ovf_i2:

21
ICSharpCode.Decompiler/IL/ILTypeExtensions.cs

@ -38,17 +38,14 @@ namespace ICSharpCode.Decompiler.IL @@ -38,17 +38,14 @@ namespace ICSharpCode.Decompiler.IL
return StackType.I8;
case PrimitiveType.I:
case PrimitiveType.U:
case (PrimitiveType)0x0f: // Ptr
case (PrimitiveType)0x1b: // FnPtr
return StackType.I;
case PrimitiveType.R4:
return StackType.F4;
case PrimitiveType.R8:
case PrimitiveType.R:
return StackType.F8;
case (PrimitiveType)0x10: // ByRef
case PrimitiveType.Ref: // ByRef
return StackType.Ref;
case (PrimitiveType)0x01: // Void
return StackType.Void;
case PrimitiveType.Unknown:
return StackType.Unknown;
default:
@ -65,6 +62,7 @@ namespace ICSharpCode.Decompiler.IL @@ -65,6 +62,7 @@ namespace ICSharpCode.Decompiler.IL
case PrimitiveType.I8:
case PrimitiveType.R4:
case PrimitiveType.R8:
case PrimitiveType.R:
case PrimitiveType.I:
return Sign.Signed;
case PrimitiveType.U1:
@ -100,6 +98,7 @@ namespace ICSharpCode.Decompiler.IL @@ -100,6 +98,7 @@ namespace ICSharpCode.Decompiler.IL
case PrimitiveType.I8:
case PrimitiveType.R8:
case PrimitiveType.U8:
case PrimitiveType.R:
return 8;
case PrimitiveType.I:
case PrimitiveType.U:
@ -126,6 +125,18 @@ namespace ICSharpCode.Decompiler.IL @@ -126,6 +125,18 @@ namespace ICSharpCode.Decompiler.IL
return primitiveType.GetStackType().IsIntegerType();
}
public static bool IsFloatType(this PrimitiveType type)
{
switch (type) {
case PrimitiveType.R4:
case PrimitiveType.R8:
case PrimitiveType.R:
return true;
default:
return false;
}
}
/// <summary>
/// Infers the C# type for an IL instruction.
///

21
ICSharpCode.Decompiler/IL/Instructions/Block.cs

@ -311,6 +311,27 @@ namespace ICSharpCode.Decompiler.IL @@ -311,6 +311,27 @@ namespace ICSharpCode.Decompiler.IL
return false;
return this.FinalInstruction.MatchLdLoc(tmp);
}
public bool MatchIfAtEndOfBlock(out ILInstruction condition, out ILInstruction trueInst, out ILInstruction falseInst)
{
condition = null;
trueInst = null;
falseInst = null;
if (Instructions.Count < 2)
return false;
if (Instructions[Instructions.Count - 2].MatchIfInstruction(out condition, out trueInst)) {
// Swap trueInst<>falseInst for every logic.not in the condition.
falseInst = Instructions.Last();
while (condition.MatchLogicNot(out var arg)) {
condition = arg;
ILInstruction tmp = trueInst;
trueInst = falseInst;
falseInst = tmp;
}
return true;
}
return false;
}
}
public enum BlockKind

2
ICSharpCode.Decompiler/IL/Instructions/CallIndirect.cs

@ -68,7 +68,7 @@ namespace ICSharpCode.Decompiler.IL @@ -68,7 +68,7 @@ namespace ICSharpCode.Decompiler.IL
this.IsInstance = isInstance;
this.HasExplicitThis = hasExplicitThis;
this.CallingConvention = callingConvention;
this.ReturnType = returnType ?? throw new ArgumentNullException("returnType");
this.ReturnType = returnType ?? throw new ArgumentNullException(nameof(returnType));
this.ParameterTypes = parameterTypes.ToImmutableArray();
this.Arguments = new InstructionCollection<ILInstruction>(this, 0);
this.Arguments.AddRange(arguments);

2
ICSharpCode.Decompiler/IL/Instructions/CompoundAssignmentInstruction.cs

@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.IL @@ -313,7 +313,7 @@ namespace ICSharpCode.Decompiler.IL
: base(OpCode.DynamicCompoundAssign, CompoundEvalModeFromOperation(op), target, targetKind, value)
{
if (!IsExpressionTypeSupported(op))
throw new ArgumentOutOfRangeException("op");
throw new ArgumentOutOfRangeException(nameof(op));
this.BinderFlags = binderFlags;
this.Operation = op;
this.TargetArgumentInfo = targetArgumentInfo;

5
ICSharpCode.Decompiler/IL/Instructions/Conv.cs

@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.IL @@ -48,7 +48,7 @@ namespace ICSharpCode.Decompiler.IL
/// <summary>
/// Converts from the current precision available on the evaluation stack to the precision specified by
/// the <c>TargetType</c>.
/// Uses "round-to-nearest" mode is the precision is reduced.
/// Uses "round-to-nearest" mode if the precision is reduced.
/// </summary>
FloatPrecisionChange,
/// <summary>
@ -156,7 +156,7 @@ namespace ICSharpCode.Decompiler.IL @@ -156,7 +156,7 @@ namespace ICSharpCode.Decompiler.IL
public Conv(ILInstruction argument, StackType inputType, Sign inputSign, PrimitiveType targetType, bool checkForOverflow, bool isLifted = false)
: base(OpCode.Conv, argument)
{
bool needsSign = checkForOverflow || (!inputType.IsFloatType() && (targetType == PrimitiveType.R4 || targetType == PrimitiveType.R8));
bool needsSign = checkForOverflow || (!inputType.IsFloatType() && targetType.IsFloatType());
Debug.Assert(!(needsSign && inputSign == Sign.None));
this.InputSign = needsSign ? inputSign : Sign.None;
this.InputType = inputType;
@ -264,6 +264,7 @@ namespace ICSharpCode.Decompiler.IL @@ -264,6 +264,7 @@ namespace ICSharpCode.Decompiler.IL
default:
return ConversionKind.Invalid;
}
case PrimitiveType.R:
case PrimitiveType.R8:
switch (inputType) {
case StackType.I4:

8
ICSharpCode.Decompiler/IL/Instructions/UsingInstruction.cs

@ -36,10 +36,16 @@ namespace ICSharpCode.Decompiler.IL @@ -36,10 +36,16 @@ namespace ICSharpCode.Decompiler.IL
/// </remarks>
partial class UsingInstruction
{
public bool IsAsync { get; set; }
public override void WriteTo(ITextOutput output, ILAstWritingOptions options)
{
WriteILRange(output, options);
output.Write("using (");
output.Write("using");
if (IsAsync) {
output.Write(".async");
}
output.Write(" (");
Variable.WriteTo(output);
output.Write(" = ");
ResourceExpression.WriteTo(output, options);

11
ICSharpCode.Decompiler/IL/PrimitiveType.cs

@ -35,7 +35,18 @@ namespace ICSharpCode.Decompiler.IL @@ -35,7 +35,18 @@ namespace ICSharpCode.Decompiler.IL
U8 = PrimitiveTypeCode.UInt64,
I = PrimitiveTypeCode.IntPtr,
U = PrimitiveTypeCode.UIntPtr,
/// <summary>Managed reference</summary>
Ref = 16,
/// <summary>Floating point type of unspecified size:
/// usually 80 bits on x86 (when the runtime uses x87 instructions);
/// but only 64-bit on x64.
/// This only occurs for "conv.r.un" instructions. The C# compiler usually follows those
/// with a "conv.r4" or "conv.r8" instruction to indicate the desired float type, so
/// we only use this as conversion target type and don't bother tracking it as its own stack type:
/// basically everything treats R identical to R8, except for the (conv.r.un + conv.r[48] => conv.r[48].un)
/// combining logic which should not combine (conv.r.un + conv.r8 + conv.r4) into a single conv.r4.un.
/// </summary>
R = 254,
Unknown = 255
}
}

11
ICSharpCode.Decompiler/IL/Transforms/ExpressionTransforms.cs

@ -177,6 +177,17 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -177,6 +177,17 @@ namespace ICSharpCode.Decompiler.IL.Transforms
context.Step("conv.i4(ldlen array) => ldlen.i4(array)", inst);
inst.AddILRange(inst.Argument);
inst.ReplaceWith(new LdLen(inst.TargetType.GetStackType(), array).WithILRange(inst));
return;
}
if (inst.TargetType.IsFloatType() && inst.Argument is Conv conv
&& conv.Kind == ConversionKind.IntToFloat && conv.TargetType == PrimitiveType.R)
{
// IL conv.r.un does not indicate whether to convert the target type to R4 or R8,
// so the C# compiler usually follows it with an explicit conv.r4 or conv.r8.
// To avoid emitting '(float)(double)val', we combine these two conversions:
context.Step("conv.rN(conv.r.un(...)) => conv.rN.un(...)", inst);
inst.ReplaceWith(new Conv(conv.Argument, conv.InputType, conv.InputSign, inst.TargetType, inst.CheckForOverflow, inst.IsLifted | conv.IsLifted));
return;
}
}

13
ICSharpCode.Decompiler/IL/Transforms/ILInlining.cs

@ -299,9 +299,16 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -299,9 +299,16 @@ namespace ICSharpCode.Decompiler.IL.Transforms
case OpCode.Call:
case OpCode.CallVirt:
method = ((CallInstruction)inst.Parent).Method;
if (method.IsAccessor && method.AccessorKind != MethodSemanticsAttributes.Getter) {
// C# doesn't allow calling setters on temporary structs
return false;
if (method.IsAccessor) {
if (method.AccessorKind == MethodSemanticsAttributes.Getter) {
// C# doesn't allow property compound assignments on temporary structs
return !(inst.Parent.Parent is CompoundAssignmentInstruction cai
&& cai.TargetKind == CompoundTargetKind.Property
&& cai.Target == inst.Parent);
} else {
// C# doesn't allow calling setters on temporary structs
return false;
}
}
return !method.IsStatic;
case OpCode.Await:

4
ICSharpCode.Decompiler/IL/Transforms/NullPropagationTransform.cs

@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -262,7 +262,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return NullableLiftingTransform.MatchGetValueOrDefault(inst, out ILInstruction arg)
&& arg.MatchLdLoc(testedVar);
default:
throw new ArgumentOutOfRangeException("mode");
throw new ArgumentOutOfRangeException(nameof(mode));
}
}
@ -306,7 +306,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -306,7 +306,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
).WithILRange(varLoad);
break;
default:
throw new ArgumentOutOfRangeException("mode");
throw new ArgumentOutOfRangeException(nameof(mode));
}
oldParentChildren[oldChildIndex] = replacement;
}

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

@ -322,7 +322,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -322,7 +322,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
parameter = null;
if (!IsDisplayClassFieldAccess(inst.Target, out var displayClassVar, out displayClass, out field))
return false;
if (!(inst.Value.MatchLdLoc(out var v) && v.Kind == VariableKind.Parameter && v.Function == currentFunction))
if (!(inst.Value.MatchLdLoc(out var v) && v.Kind == VariableKind.Parameter && v.Function == currentFunction && v.Type.Equals(field.Type)))
return false;
if (displayClass.Variables.ContainsKey((IField)field.MemberDefinition))
return false;

107
ICSharpCode.Decompiler/IL/Transforms/UsingTransform.cs

@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -34,7 +34,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
if (!context.Settings.UsingStatement) return;
this.context = context;
for (int i = block.Instructions.Count - 1; i >= 0; i--) {
if (!TransformUsing(block, i) && !TransformUsingVB(block, i))
if (!TransformUsing(block, i) && !TransformUsingVB(block, i) && !TransformAsyncUsing(block, i))
continue;
// This happens in some cases:
// Use correct index after transformation.
@ -167,7 +167,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -167,7 +167,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return true;
}
bool MatchDisposeBlock(BlockContainer container, ILVariable objVar, bool usingNull)
bool MatchDisposeBlock(BlockContainer container, ILVariable objVar, bool usingNull, in string disposeMethodFullName = "System.IDisposable.Dispose", KnownTypeCode disposeTypeCode = KnownTypeCode.IDisposable)
{
var entryPoint = container.EntryPoint;
if (entryPoint.Instructions.Count < 2 || entryPoint.Instructions.Count > 3 || entryPoint.IncomingEdgeCount != 1)
@ -180,17 +180,17 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -180,17 +180,17 @@ namespace ICSharpCode.Decompiler.IL.Transforms
if (castIndex > -1) {
if (!entryPoint.Instructions[castIndex].MatchStLoc(out var tempVar, out var isinst))
return false;
if (!isinst.MatchIsInst(out var load, out var disposableType) || !load.MatchLdLoc(objVar) || !disposableType.IsKnownType(KnownTypeCode.IDisposable))
if (!isinst.MatchIsInst(out var load, out var disposableType) || !load.MatchLdLoc(objVar) || !disposableType.IsKnownType(disposeTypeCode))
return false;
if (!tempVar.IsSingleDefinition)
return false;
isReference = true;
if (!MatchDisposeCheck(tempVar, checkInst, isReference, usingNull, out int numObjVarLoadsInCheck))
if (!MatchDisposeCheck(tempVar, checkInst, isReference, usingNull, out int numObjVarLoadsInCheck, disposeMethodFullName, disposeTypeCode))
return false;
if (tempVar.LoadCount != numObjVarLoadsInCheck)
return false;
} else {
if (!MatchDisposeCheck(objVar, checkInst, isReference, usingNull, out _))
if (!MatchDisposeCheck(objVar, checkInst, isReference, usingNull, out _, disposeMethodFullName, disposeTypeCode))
return false;
}
if (!entryPoint.Instructions[leaveIndex].MatchLeave(container, out var returnValue) || !returnValue.MatchNop())
@ -198,9 +198,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -198,9 +198,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return true;
}
bool MatchDisposeCheck(ILVariable objVar, ILInstruction checkInst, bool isReference, bool usingNull, out int numObjVarLoadsInCheck)
bool MatchDisposeCheck(ILVariable objVar, ILInstruction checkInst, bool isReference, bool usingNull, out int numObjVarLoadsInCheck, in string disposeMethodFullName, KnownTypeCode disposeTypeCode)
{
numObjVarLoadsInCheck = 2;
ILInstruction disposeInvocation;
CallVirt callVirt;
if (objVar.Type.IsKnownType(KnownTypeCode.NullableOfT)) {
if (checkInst.MatchIfInstruction(out var condition, out var disposeInst)) {
@ -208,22 +209,27 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -208,22 +209,27 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return false;
if (!(disposeInst is Block disposeBlock) || disposeBlock.Instructions.Count != 1)
return false;
callVirt = disposeBlock.Instructions[0] as CallVirt;
disposeInvocation = disposeBlock.Instructions[0];
} else if (checkInst.MatchNullableRewrap(out disposeInst)) {
callVirt = disposeInst as CallVirt;
disposeInvocation = disposeInst;
} else {
return false;
}
if (disposeTypeCode == KnownTypeCode.IAsyncDisposable) {
if (!UnwrapAwait(ref disposeInvocation))
return false;
}
callVirt = disposeInvocation as CallVirt;
if (callVirt == null)
return false;
if (callVirt.Method.FullName != "System.IDisposable.Dispose")
if (callVirt.Method.FullName != disposeMethodFullName)
return false;
if (callVirt.Method.Parameters.Count > 0)
return false;
if (callVirt.Arguments.Count != 1)
return false;
var firstArg = callVirt.Arguments.FirstOrDefault();
if (!(firstArg.MatchUnboxAny(out var innerArg1, out var unboxType) && unboxType.IsKnownType(KnownTypeCode.IDisposable))) {
if (!(firstArg.MatchUnboxAny(out var innerArg1, out var unboxType) && unboxType.IsKnownType(disposeTypeCode))) {
if (!firstArg.MatchAddressOf(out var innerArg2, out _))
return false;
return NullableLiftingTransform.MatchGetValueOrDefault(innerArg2, objVar)
@ -255,7 +261,12 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -255,7 +261,12 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return false;
if (!(disposeInst is Block disposeBlock) || disposeBlock.Instructions.Count != 1)
return false;
if (!(disposeBlock.Instructions[0] is CallVirt cv))
disposeInvocation = disposeBlock.Instructions[0];
if (disposeTypeCode == KnownTypeCode.IAsyncDisposable) {
if (!UnwrapAwait(ref disposeInvocation))
return false;
}
if (!(disposeInvocation is CallVirt cv))
return false;
target = cv.Arguments.FirstOrDefault();
if (target == null)
@ -264,6 +275,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -264,6 +275,10 @@ namespace ICSharpCode.Decompiler.IL.Transforms
target = newTarget;
callVirt = cv;
} else {
if (disposeTypeCode == KnownTypeCode.IAsyncDisposable) {
if (!UnwrapAwait(ref checkInst))
return false;
}
if (!(checkInst is CallVirt cv))
return false;
target = cv.Arguments.FirstOrDefault();
@ -275,7 +290,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -275,7 +290,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
}
callVirt = cv;
}
if (callVirt.Method.FullName != "System.IDisposable.Dispose")
if (callVirt.Method.FullName != disposeMethodFullName)
return false;
if (callVirt.Method.Parameters.Count > 0)
return false;
@ -286,8 +301,74 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -286,8 +301,74 @@ namespace ICSharpCode.Decompiler.IL.Transforms
|| (usingNull && callVirt.Arguments[0].MatchLdNull())
|| (isReference && checkInst is NullableRewrap
&& target.MatchIsInst(out var arg, out var type2)
&& arg.MatchLdLoc(objVar) && type2.IsKnownType(KnownTypeCode.IDisposable));
&& arg.MatchLdLoc(objVar) && type2.IsKnownType(disposeTypeCode));
}
}
/// <summary>
/// stloc test(resourceExpression)
/// .try BlockContainer {
/// Block IL_002b (incoming: 1) {
/// call Use(ldloc test)
/// leave IL_002b (nop)
/// }
///
/// } finally BlockContainer {
/// Block IL_0045 (incoming: 1) {
/// if (comp.o(ldloc test == ldnull)) leave IL_0045 (nop)
/// br IL_00ae
/// }
///
/// Block IL_00ae (incoming: 1) {
/// await(addressof System.Threading.Tasks.ValueTask(callvirt DisposeAsync(ldloc test)))
/// leave IL_0045 (nop)
/// }
///
/// }
/// </summary>
private bool TransformAsyncUsing(Block block, int i)
{
if (i < 1 || !context.Settings.AsyncUsingAndForEachStatement) return false;
if (!(block.Instructions[i] is TryFinally tryFinally) || !(block.Instructions[i - 1] is StLoc storeInst))
return false;
if (!CheckAsyncResourceType(storeInst.Variable.Type))
return false;
if (storeInst.Variable.Kind != VariableKind.Local)
return false;
if (storeInst.Variable.LoadInstructions.Any(ld => !ld.IsDescendantOf(tryFinally)))
return false;
if (storeInst.Variable.AddressInstructions.Any(la => !la.IsDescendantOf(tryFinally) || (la.IsDescendantOf(tryFinally.TryBlock) && !ILInlining.IsUsedAsThisPointerInCall(la))))
return false;
if (storeInst.Variable.StoreInstructions.Count > 1)
return false;
if (!(tryFinally.FinallyBlock is BlockContainer container) || !MatchDisposeBlock(container, storeInst.Variable, usingNull: false, "System.IAsyncDisposable.DisposeAsync", KnownTypeCode.IAsyncDisposable))
return false;
context.Step("AsyncUsingTransform", tryFinally);
storeInst.Variable.Kind = VariableKind.UsingLocal;
block.Instructions.RemoveAt(i);
block.Instructions[i - 1] = new UsingInstruction(storeInst.Variable, storeInst.Value, tryFinally.TryBlock) { IsAsync = true }
.WithILRange(storeInst);
return true;
}
bool CheckAsyncResourceType(IType type)
{
if (NullableType.GetUnderlyingType(type).GetAllBaseTypes().Any(b => b.IsKnownType(KnownTypeCode.IAsyncDisposable)))
return true;
return false;
}
bool UnwrapAwait(ref ILInstruction awaitInstruction)
{
if (awaitInstruction == null)
return false;
if (!awaitInstruction.MatchAwait(out var arg))
return false;
if (!arg.MatchAddressOf(out awaitInstruction, out var type))
return false;
if (!type.IsKnownType(KnownTypeCode.ValueTask))
return false;
return true;
}
}
}

2
ICSharpCode.Decompiler/Metadata/AssemblyReferences.cs

@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.Metadata @@ -116,7 +116,7 @@ namespace ICSharpCode.Decompiler.Metadata
public static AssemblyNameReference Parse(string fullName)
{
if (fullName == null)
throw new ArgumentNullException("fullName");
throw new ArgumentNullException(nameof(fullName));
if (fullName.Length == 0)
throw new ArgumentException("Name can not be empty");

30
ICSharpCode.Decompiler/Metadata/DotNetCorePathFinder.cs

@ -62,15 +62,18 @@ namespace ICSharpCode.Decompiler.Metadata @@ -62,15 +62,18 @@ namespace ICSharpCode.Decompiler.Metadata
readonly Dictionary<string, DotNetCorePackageInfo> packages;
ISet<string> packageBasePaths = new HashSet<string>(StringComparer.Ordinal);
readonly string assemblyName;
readonly string basePath;
readonly Version version;
readonly string dotnetBasePath = FindDotNetExeDirectory();
public DotNetCorePathFinder(Version version)
{
this.version = version;
}
public DotNetCorePathFinder(string parentAssemblyFileName, string targetFrameworkId, Version version, ReferenceLoadInfo loadInfo = null)
{
this.assemblyName = Path.GetFileNameWithoutExtension(parentAssemblyFileName);
this.basePath = Path.GetDirectoryName(parentAssemblyFileName);
string assemblyName = Path.GetFileNameWithoutExtension(parentAssemblyFileName);
string basePath = Path.GetDirectoryName(parentAssemblyFileName);
this.version = version;
var depsJsonFileName = Path.Combine(basePath, $"{assemblyName}.deps.json");
@ -106,6 +109,25 @@ namespace ICSharpCode.Decompiler.Metadata @@ -106,6 +109,25 @@ namespace ICSharpCode.Decompiler.Metadata
return FallbackToDotNetSharedDirectory(name, version);
}
internal string GetReferenceAssemblyPath(string targetFramework)
{
var (tfi, version) = UniversalAssemblyResolver.ParseTargetFramework(targetFramework);
string identifier, identifierExt;
switch (tfi) {
case TargetFrameworkIdentifier.NETCoreApp:
identifier = "Microsoft.NETCore.App";
identifierExt = "netcoreapp" + version.Major + "." + version.Minor;
break;
case TargetFrameworkIdentifier.NETStandard:
identifier = "NETStandard.Library";
identifierExt = "netstandard" + version.Major + "." + version.Minor;
break;
default:
throw new NotSupportedException();
}
return Path.Combine(dotnetBasePath, "packs", identifier + ".Ref", version.ToString(), "ref", identifierExt);
}
static IEnumerable<DotNetCorePackageInfo> LoadPackageInfos(string depsJsonFileName, string targetFramework)
{
var dependencies = JsonReader.Parse(File.ReadAllText(depsJsonFileName));

34
ICSharpCode.Decompiler/Metadata/UniversalAssemblyResolver.cs

@ -26,6 +26,21 @@ using System.Text; @@ -26,6 +26,21 @@ using System.Text;
namespace ICSharpCode.Decompiler.Metadata
{
enum TargetFrameworkIdentifier
{
NETFramework,
NETCoreApp,
NETStandard,
Silverlight
}
enum DecompilerRuntime
{
NETFramework,
NETCoreApp,
Mono
}
// This is inspired by Mono.Cecil's BaseAssemblyResolver/DefaultAssemblyResolver.
public class UniversalAssemblyResolver : IAssemblyResolver
{
@ -67,21 +82,6 @@ namespace ICSharpCode.Decompiler.Metadata @@ -67,21 +82,6 @@ namespace ICSharpCode.Decompiler.Metadata
return directories.ToArray();
}
enum TargetFrameworkIdentifier
{
NETFramework,
NETCoreApp,
NETStandard,
Silverlight
}
enum DecompilerRuntime
{
NETFramework,
NETCoreApp,
Mono
}
string targetFramework;
TargetFrameworkIdentifier targetFrameworkIdentifier;
Version targetFrameworkVersion;
@ -101,7 +101,7 @@ namespace ICSharpCode.Decompiler.Metadata @@ -101,7 +101,7 @@ namespace ICSharpCode.Decompiler.Metadata
AddSearchDirectory(baseDirectory);
}
(TargetFrameworkIdentifier, Version) ParseTargetFramework(string targetFramework)
internal static (TargetFrameworkIdentifier, Version) ParseTargetFramework(string targetFramework)
{
string[] tokens = targetFramework.Split(',');
TargetFrameworkIdentifier identifier;
@ -131,7 +131,7 @@ namespace ICSharpCode.Decompiler.Metadata @@ -131,7 +131,7 @@ namespace ICSharpCode.Decompiler.Metadata
switch (pair[0].Trim().ToUpperInvariant()) {
case "VERSION":
var versionString = pair[1].TrimStart('v');
var versionString = pair[1].TrimStart('v', ' ', '\t');
if (identifier == TargetFrameworkIdentifier.NETCoreApp ||
identifier == TargetFrameworkIdentifier.NETStandard)
{

4
ICSharpCode.Decompiler/Semantics/ArrayAccessResolveResult.cs

@ -34,9 +34,9 @@ namespace ICSharpCode.Decompiler.Semantics @@ -34,9 +34,9 @@ namespace ICSharpCode.Decompiler.Semantics
public ArrayAccessResolveResult(IType elementType, ResolveResult array, IList<ResolveResult> indexes) : base(elementType)
{
if (array == null)
throw new ArgumentNullException("array");
throw new ArgumentNullException(nameof(array));
if (indexes == null)
throw new ArgumentNullException("indexes");
throw new ArgumentNullException(nameof(indexes));
this.Array = array;
this.Indexes = indexes;
}

2
ICSharpCode.Decompiler/Semantics/ArrayCreateResolveResult.cs

@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -43,7 +43,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(arrayType)
{
if (sizeArguments == null)
throw new ArgumentNullException("sizeArguments");
throw new ArgumentNullException(nameof(sizeArguments));
this.SizeArguments = sizeArguments;
this.InitializerElements = initializerElements;
}

6
ICSharpCode.Decompiler/Semantics/Conversion.cs

@ -89,21 +89,21 @@ namespace ICSharpCode.Decompiler.Semantics @@ -89,21 +89,21 @@ namespace ICSharpCode.Decompiler.Semantics
public static Conversion UserDefinedConversion(IMethod operatorMethod, bool isImplicit, Conversion conversionBeforeUserDefinedOperator, Conversion conversionAfterUserDefinedOperator, bool isLifted = false, bool isAmbiguous = false)
{
if (operatorMethod == null)
throw new ArgumentNullException("operatorMethod");
throw new ArgumentNullException(nameof(operatorMethod));
return new UserDefinedConv(isImplicit, operatorMethod, conversionBeforeUserDefinedOperator, conversionAfterUserDefinedOperator, isLifted, isAmbiguous);
}
public static Conversion MethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
{
if (chosenMethod == null)
throw new ArgumentNullException("chosenMethod");
throw new ArgumentNullException(nameof(chosenMethod));
return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: true);
}
public static Conversion InvalidMethodGroupConversion(IMethod chosenMethod, bool isVirtualMethodLookup, bool delegateCapturesFirstArgument)
{
if (chosenMethod == null)
throw new ArgumentNullException("chosenMethod");
throw new ArgumentNullException(nameof(chosenMethod));
return new MethodGroupConv(chosenMethod, isVirtualMethodLookup, delegateCapturesFirstArgument, isValid: false);
}

4
ICSharpCode.Decompiler/Semantics/ConversionResolveResult.cs

@ -42,9 +42,9 @@ namespace ICSharpCode.Decompiler.Semantics @@ -42,9 +42,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(targetType)
{
if (input == null)
throw new ArgumentNullException("input");
throw new ArgumentNullException(nameof(input));
if (conversion == null)
throw new ArgumentNullException("conversion");
throw new ArgumentNullException(nameof(conversion));
this.Input = input;
this.Conversion = conversion;
}

8
ICSharpCode.Decompiler/Semantics/ForEachResolveResult.cs

@ -64,13 +64,13 @@ namespace ICSharpCode.Decompiler.Semantics @@ -64,13 +64,13 @@ namespace ICSharpCode.Decompiler.Semantics
: base(voidType)
{
if (getEnumeratorCall == null)
throw new ArgumentNullException("getEnumeratorCall");
throw new ArgumentNullException(nameof(getEnumeratorCall));
if (collectionType == null)
throw new ArgumentNullException("collectionType");
throw new ArgumentNullException(nameof(collectionType));
if (enumeratorType == null)
throw new ArgumentNullException("enumeratorType");
throw new ArgumentNullException(nameof(enumeratorType));
if (elementType == null)
throw new ArgumentNullException("elementType");
throw new ArgumentNullException(nameof(elementType));
this.GetEnumeratorCall = getEnumeratorCall;
this.CollectionType = collectionType;
this.EnumeratorType = enumeratorType;

2
ICSharpCode.Decompiler/Semantics/LocalResolveResult.cs

@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -38,7 +38,7 @@ namespace ICSharpCode.Decompiler.Semantics
static IType UnpackTypeIfByRefParameter(IVariable variable)
{
if (variable == null)
throw new ArgumentNullException("variable");
throw new ArgumentNullException(nameof(variable));
IType type = variable.Type;
if (type.Kind == TypeKind.ByReference) {
IParameter p = variable as IParameter;

8
ICSharpCode.Decompiler/Semantics/NamedArgumentResolveResult.cs

@ -53,9 +53,9 @@ namespace ICSharpCode.Decompiler.Semantics @@ -53,9 +53,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(argument.Type)
{
if (parameter == null)
throw new ArgumentNullException("parameter");
throw new ArgumentNullException(nameof(parameter));
if (argument == null)
throw new ArgumentNullException("argument");
throw new ArgumentNullException(nameof(argument));
this.Member = member;
this.Parameter = parameter;
this.ParameterName = parameter.Name;
@ -66,9 +66,9 @@ namespace ICSharpCode.Decompiler.Semantics @@ -66,9 +66,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(argument.Type)
{
if (parameterName == null)
throw new ArgumentNullException("parameterName");
throw new ArgumentNullException(nameof(parameterName));
if (argument == null)
throw new ArgumentNullException("argument");
throw new ArgumentNullException(nameof(argument));
this.ParameterName = parameterName;
this.Argument = argument;
}

4
ICSharpCode.Decompiler/Semantics/OperatorResolveResult.cs

@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -37,7 +37,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(resultType)
{
if (operands == null)
throw new ArgumentNullException("operands");
throw new ArgumentNullException(nameof(operands));
this.operatorType = operatorType;
this.operands = operands;
}
@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -46,7 +46,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(resultType)
{
if (operands == null)
throw new ArgumentNullException("operands");
throw new ArgumentNullException(nameof(operands));
this.operatorType = operatorType;
this.userDefinedOperatorMethod = userDefinedOperatorMethod;
this.isLiftedOperator = isLiftedOperator;

2
ICSharpCode.Decompiler/Semantics/ResolveResult.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics
public ResolveResult(IType type)
{
if (type == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(type));
this.type = type;
}

2
ICSharpCode.Decompiler/Semantics/SizeOfResolveResult.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics @@ -33,7 +33,7 @@ namespace ICSharpCode.Decompiler.Semantics
: base(int32)
{
if (referencedType == null)
throw new ArgumentNullException("referencedType");
throw new ArgumentNullException(nameof(referencedType));
this.referencedType = referencedType;
this.constantValue = constantValue;
}

4
ICSharpCode.Decompiler/Semantics/TypeIsResolveResult.cs

@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.Semantics @@ -37,9 +37,9 @@ namespace ICSharpCode.Decompiler.Semantics
: base(booleanType)
{
if (input == null)
throw new ArgumentNullException("input");
throw new ArgumentNullException(nameof(input));
if (targetType == null)
throw new ArgumentNullException("targetType");
throw new ArgumentNullException(nameof(targetType));
this.Input = input;
this.TargetType = targetType;
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save