Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions ICSharpCode.Decompiler.Tests/PrettyTestRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,12 +332,31 @@ await RunForLibrary(cscOptions: cscOptions, configureDecompiler: settings => {
});
}

[Test]
public async Task DelegateCaching([ValueSource(nameof(roslyn4OrNewerOptions))] CompilerOptions cscOptions)
{
await RunForLibrary(cscOptions: cscOptions);
}

[Test]
public async Task DelegateCachingWithExplicitConversions([ValueSource(nameof(roslyn4OrNewerOptions))] CompilerOptions cscOptions)
{
await RunForLibrary(cscOptions: cscOptions, configureDecompiler: settings => settings.UseImplicitMethodGroupConversion = false);
}

[Test]
public async Task AnonymousTypes([ValueSource(nameof(defaultOptionsWithMcs))] CompilerOptions cscOptions)
{
await RunForLibrary(cscOptions: cscOptions);
}

[Test]
public async Task AnonymousTypeMethodGroups([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions)
{
// Older compilers emit uncached method groups even when decompiling to a language version that supports caching.
await RunForLibrary(cscOptions: cscOptions, settings: new DecompilerSettings { FileScopedNamespaces = false });
}

[Test]
public async Task StringConcatenation([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions)
{
Expand Down Expand Up @@ -673,6 +692,8 @@ public async Task Structs([ValueSource(nameof(defaultOptionsWithMcs))] CompilerO
public async Task FunctionPointers([ValueSource(nameof(roslyn3OrNewerOptions))] CompilerOptions cscOptions)
{
await RunForLibrary(cscOptions: cscOptions);
// Disabling implicit delegate conversions must not introduce function-pointer casts.
await RunForLibrary(cscOptions: cscOptions, configureDecompiler: settings => settings.UseImplicitMethodGroupConversion = false);
}

[Test]
Expand Down Expand Up @@ -1064,12 +1085,12 @@ public async Task Issue3751([ValueSource(nameof(defaultOptions))] CompilerOption
await RunForLibrary(cscOptions: cscOptions);
}

async Task RunForLibrary([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, Action<DecompilerSettings> configureDecompiler = null)
async Task RunForLibrary([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, Action<DecompilerSettings> configureDecompiler = null, DecompilerSettings settings = null)
{
await Run(testName, asmOptions | AssemblerOptions.Library, cscOptions | CompilerOptions.Library, configureDecompiler);
await Run(testName, asmOptions | AssemblerOptions.Library, cscOptions | CompilerOptions.Library, configureDecompiler, settings);
}

async Task Run([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, Action<DecompilerSettings> configureDecompiler = null)
async Task Run([CallerMemberName] string testName = null, AssemblerOptions asmOptions = AssemblerOptions.None, CompilerOptions cscOptions = CompilerOptions.None, Action<DecompilerSettings> configureDecompiler = null, DecompilerSettings settings = null)
{
var csFile = Path.Combine(TestCasePath, testName + ".cs");
var exeFile = TestsAssemblyOutput.GetFilePath(TestCasePath, testName, Tester.GetSuffix(cscOptions) + ".exe");
Expand All @@ -1091,7 +1112,7 @@ async Task Run([CallerMemberName] string testName = null, AssemblerOptions asmOp
}

// 2. Decompile
var settings = Tester.GetSettings(cscOptions);
settings ??= Tester.GetSettings(cscOptions);
configureDecompiler?.Invoke(settings);
var decompiled = await Tester.DecompileCSharp(exeFile, settings).ConfigureAwait(false);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright (c) 2026 marcusmalloc
//
// 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.Linq;

namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal static class AnonymousTypeMethodGroups
{
public static object AnonymousTypeArgument()
{
return new[] {
new {
X = 1
}
}.Select(Identity).Single();
}

public static object AnonymousArrayTypeArgument()
{
return new[] { new[] {
new {
X = 1
}
} }.Select(Identity).Single();
}

private static T Identity<T>(T value)
{
return value;
}
}
}
52 changes: 52 additions & 0 deletions ICSharpCode.Decompiler.Tests/TestCases/Pretty/DelegateCaching.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Copyright (c) 2026 marcusmalloc
//
// 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;

namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal static class DelegateCaching
{
public delegate void CustomDelegate();

// Issue #3921: explicit construction must preserve a fresh delegate on each call.
public static Action FreshDelegate()
{
return new Action(M);
}

public static Action CachedDelegate()
{
return M;
}

public static object FreshDelegateAsObject()
{
return new CustomDelegate(M);
}

public static object CachedDelegateAsObject()
{
return (CustomDelegate)M;
}

private static void M()
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) 2026 marcusmalloc
//
// 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;

namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal static class DelegateCachingWithExplicitConversions
{
public static Action FreshDelegate()
{
return new Action(M);
}

public static Action CachedDelegate()
{
return (Action)M;
}

private static void M()
{
}
}
}
45 changes: 16 additions & 29 deletions ICSharpCode.Decompiler/CSharp/CallBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2037,44 +2037,30 @@ TranslatedExpression HandleDelegateConstruction(CallInstruction inst)
}
}

private bool CanUseDelegateConstruction(IMethod targetMethod, ILInstruction thisArg, IMethod invokeMethod)
static bool IsBoundExtensionMethod(IMethod method, IMethod? invokeMethod)
{
return method.IsExtensionMethod && method.Parameters.Count - 1 == invokeMethod?.Parameters.Count;
}

private static bool CanUseDelegateConstruction(IMethod targetMethod, ILInstruction thisArg, IMethod? invokeMethod)
{
// Accessors cannot be directly referenced as method group in C#
// see https://github.com/icsharpcode/ILSpy/issues/1741#issuecomment-540179101
if (targetMethod.IsAccessor)
return false;
if (targetMethod.IsStatic)
{
// If the invoke method is known, we can compare the parameter counts to figure out whether the
// delegate is static or binds the first argument
if (invokeMethod != null)
{
if (invokeMethod.Parameters.Count == targetMethod.Parameters.Count)
{
return thisArg.MatchLdNull();
}
else if (targetMethod.IsExtensionMethod && invokeMethod.Parameters.Count == targetMethod.Parameters.Count - 1)
{
return true;
}
else
{
return false;
}
}
else
if (invokeMethod == null)
{
// delegate type unknown:
// Delegate type unknown.
return thisArg.MatchLdNull() || targetMethod.IsExtensionMethod;
}
// An unbound static delegate supplies every method parameter through Invoke.
if (invokeMethod.Parameters.Count == targetMethod.Parameters.Count)
return thisArg.MatchLdNull();
return IsBoundExtensionMethod(targetMethod, invokeMethod);
}
else
{
// targetMethod is instance method
if (invokeMethod != null && invokeMethod.Parameters.Count != targetMethod.Parameters.Count)
return false;
return true;
}
return invokeMethod == null || invokeMethod.Parameters.Count == targetMethod.Parameters.Count;
}

internal TranslatedExpression Build(LdVirtDelegate inst)
Expand Down Expand Up @@ -2124,7 +2110,7 @@ ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invo
Debug.Assert(localFunction != null);
return (default, addTypeArguments: true, localFunction.Name!, ToMethodGroup(method, localFunction));
}
if (method.IsExtensionMethod && method.Parameters.Count - 1 == invokeMethod?.Parameters.Count)
if (IsBoundExtensionMethod(method, invokeMethod))
{
IType targetType = method.Parameters[0].Type;
if (targetType.Kind == TypeKind.ByReference && thisArg is Box thisArgBox)
Expand Down Expand Up @@ -2242,13 +2228,14 @@ ExpressionWithResolveResult BuildDelegateReference(IMethod method, IMethod? invo
TranslatedExpression HandleDelegateConstruction(IType delegateType, IMethod method, ExpectedTargetDetails expectedTargetDetails, ILInstruction thisArg, ILInstruction inst)
{
var invokeMethod = delegateType.GetDelegateInvokeMethod();
bool capturesFirstArgument = !method.IsStatic || IsBoundExtensionMethod(method, invokeMethod);
var targetExpression = BuildDelegateReference(method, invokeMethod, expectedTargetDetails, thisArg);
var oce = new ObjectCreateExpression(expressionBuilder.ConvertType(delegateType), targetExpression)
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(
delegateType,
targetExpression.ResolveResult,
Conversion.MethodGroupConversion(method, expectedTargetDetails.CallOpCode == OpCode.CallVirt, false)));
Conversion.MethodGroupConversion(method, expectedTargetDetails.CallOpCode == OpCode.CallVirt, capturesFirstArgument)));
return oce;
}

Expand Down
31 changes: 31 additions & 0 deletions ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,37 @@ protected internal override TranslatedExpression VisitNewObj(NewObj inst, Transl
return new CallBuilder(this, typeSystem, settings).Build(inst, context.TypeHint);
}

protected internal override TranslatedExpression VisitCachedDelegate(CachedDelegate inst, TranslationContext context)
{
var expression = Translate(inst.Argument, context.TypeHint);
if (expression.Expression is ObjectCreateExpression objectCreation && objectCreation.Arguments.Count == 1
&& expression.ResolveResult is ConversionResolveResult { Conversion.IsMethodGroupConversion: true })
{
// A method-group conversion allows caching; explicit construction would allocate.
// ConvertTo can remove the cast when the context supplies the delegate type.
var cast = new CastExpression(objectCreation.Type.Detach(), objectCreation.Arguments.Single().Detach())
.CopyAnnotationsFrom(objectCreation);
return new TranslatedExpression(cast, expression.ResolveResult).WithILInstruction(inst);
}
return expression.WithILInstruction(inst);
}

/// <summary>
/// Gets whether the C# compiler would cache a method-group conversion in the current context.
/// </summary>
internal bool MethodGroupConversionWouldBeCached(Conversion conversion)
{
if (settings.GetMinimumRequiredVersion() < LanguageVersion.CSharp11_0
|| currentFunction.Kind == ILFunctionKind.ExpressionTree
|| decompilationContext.CurrentMember is { SymbolKind: SymbolKind.Constructor, IsStatic: true })
{
return false;
}
// Local-function symbols report IsStatic even when the C# declaration cannot be static.
return !conversion.DelegateCapturesFirstArgument
&& conversion.Method is not LocalFunctionMethod { IsStaticLocalFunction: false };
}

protected internal override TranslatedExpression VisitLdVirtDelegate(LdVirtDelegate inst, TranslationContext context)
{
return new CallBuilder(this, typeSystem, settings).Build(inst);
Expand Down
17 changes: 14 additions & 3 deletions ICSharpCode.Decompiler/CSharp/TranslatedExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ TranslatedExpression Unwrapped(TranslatedExpression operand)
case ConversionResolveResult conversion:
{
if (Expression is CastExpression cast && CastCanBeMadeImplicit(
Resolver.CSharpConversions.Get(expressionBuilder.compilation),
expressionBuilder,
conversion.Conversion,
conversion.Input.Type,
type, targetType
Expand All @@ -270,6 +270,13 @@ TranslatedExpression Unwrapped(TranslatedExpression operand)
else if (Expression is ObjectCreateExpression oce && conversion.Conversion.IsMethodGroupConversion
&& oce.Arguments.Count == 1 && expressionBuilder.settings.UseImplicitMethodGroupConversion)
{
// Preserve explicit construction if a method-group conversion would introduce caching.
// Delegate types containing anonymous types must be inferred instead.
if (expressionBuilder.MethodGroupConversionWouldBeCached(conversion.Conversion)
&& (!expressionBuilder.settings.AnonymousTypes || !type.ContainsAnonymousType()))
{
return this;
}
return this.UnwrapChild(oce.Arguments.Single());
}
break;
Expand Down Expand Up @@ -349,7 +356,7 @@ TranslatedExpression Unwrapped(TranslatedExpression operand)
var conversions = Resolver.CSharpConversions.Get(compilation);
if (ResolveResult is ConversionResolveResult conv && Expression is CastExpression cast2
&& !conv.Conversion.IsUserDefined
&& CastCanBeMadeImplicit(conversions, conv.Conversion, conv.Input.Type, type, targetType))
&& CastCanBeMadeImplicit(expressionBuilder, conv.Conversion, conv.Input.Type, type, targetType))
{
var unwrapped = Unwrapped(this.UnwrapChild(cast2.Expression));
if (allowImplicitConversion)
Expand Down Expand Up @@ -679,8 +686,12 @@ bool IsFixedVariable()
/// would have the same semantics as the existing cast from 'inputType' to 'oldTargetType'.
/// The existing cast is classified in 'conversion'.
/// </summary>
bool CastCanBeMadeImplicit(Resolver.CSharpConversions conversions, Conversion conversion, IType inputType, IType oldTargetType, IType newTargetType)
bool CastCanBeMadeImplicit(ExpressionBuilder expressionBuilder, Conversion conversion, IType inputType, IType oldTargetType, IType newTargetType)
{
if (conversion.IsMethodGroupConversion && oldTargetType.Kind == TypeKind.Delegate
&& !expressionBuilder.settings.UseImplicitMethodGroupConversion)
return false;
var conversions = Resolver.CSharpConversions.Get(expressionBuilder.compilation);
if (!conversion.IsImplicit)
{
// If the cast was required for the old conversion, avoid making it implicit.
Expand Down
Loading
Loading