Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delay reporting of pattern-based using diagnostics #73850

Merged
merged 6 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
7 changes: 0 additions & 7 deletions src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs
Original file line number Diff line number Diff line change
Expand Up @@ -779,13 +779,6 @@ internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNo
else if ((!hasAwait && disposeMethod?.ReturnsVoid == false)
|| result == PatternLookupResult.NotAMethod)
{
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics);
if (this.IsAccessible(disposeMethod, ref useSiteInfo))
{
diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod);
}

diagnostics.Add(syntaxNode, useSiteInfo);
disposeMethod = null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,12 @@ bool bindDisposable(bool fromExpression, out MethodArgumentInfo? patternDisposeI
: new BoundLocal(syntax, declarationsOpt[0].LocalSymbol, null, type) { WasCompilerGenerated = true };

BindingDiagnosticBag patternDiagnostics = originalBinder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureDisposalPattern)
? diagnostics
? BindingDiagnosticBag.GetInstance(diagnostics)
AlekseyTs marked this conversation as resolved.
Show resolved Hide resolved
: BindingDiagnosticBag.Discarded;
MethodSymbol disposeMethod = originalBinder.TryFindDisposePatternMethod(receiver, syntax, hasAwait, patternDiagnostics, out bool expanded);
if (disposeMethod is object)
{
diagnostics.AddRange(patternDiagnostics);
MessageID.IDS_FeatureDisposalPattern.CheckFeatureAvailability(diagnostics, originalBinder.Compilation, syntax.Location);

var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(disposeMethod.ParameterCount);
Expand All @@ -220,14 +221,15 @@ bool bindDisposable(bool fromExpression, out MethodArgumentInfo? patternDisposeI
out BitVector defaultArguments,
expanded,
enableCallerInfo: true,
patternDiagnostics);
diagnostics);

Debug.Assert(argsToParams.IsDefault);
patternDisposeInfo = new MethodArgumentInfo(disposeMethod, argumentsBuilder.ToImmutableAndFree(), defaultArguments, expanded);
if (hasAwait)
{
awaitableType = disposeMethod.ReturnType;
}

return true;
}
}
Expand Down
144 changes: 138 additions & 6 deletions src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAwaitUsingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2645,13 +2645,9 @@ private System.Threading.Tasks.ValueTask DisposeAsync()
";
var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition });
comp.VerifyDiagnostics(
// (6,22): error CS0122: 'C.DisposeAsync()' is inaccessible due to its protection level
// 0.cs(6,22): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_BadAccess, "var x = new C()").WithArguments("C.DisposeAsync()").WithLocation(6, 22),
// (6,22): error CS8410: 'C': type used in an async using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (var x = new C())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22)
);
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "var x = new C()").WithArguments("C").WithLocation(6, 22));
}

[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
Expand Down Expand Up @@ -3519,5 +3515,141 @@ public ValueTask DisposeAsync()
comp = CreateCompilationWithTasksExtensions(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: expectedOutput).VerifyDiagnostics();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73691")]
public void PatternBasedFails_WithInterfaceImplementation()
{
var source = """
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

await using var x = new Class1();

internal class Class1 : IAsyncDisposable
{
async ValueTask IAsyncDisposable.DisposeAsync()
{
System.Console.Write("DISPOSED");
await Task.Yield();
}
}

internal static class EnumerableExtensions
{
public static ValueTask DisposeAsync(this IEnumerable<object> objects)
{
throw null;
}
}
""";
var comp = CreateCompilationWithTasksExtensions([source, IAsyncDisposableDefinition]);
CompileAndVerify(comp, expectedOutput: "DISPOSED").VerifyDiagnostics();
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73691")]
public void PatternBasedFails_NoInterfaceImplementation()
{
var source = """
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

await using var x = new Class1();

internal class Class1 { }

internal static class EnumerableExtensions
{
public static ValueTask DisposeAsync(this IEnumerable<object> objects)
{
throw null;
}
}
""";
var comp = CreateCompilationWithTasksExtensions([source, IAsyncDisposableDefinition]);
comp.VerifyEmitDiagnostics(
// (5,1): error CS8410: 'Class1': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using var x = new Class1();
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "await using var x = new Class1();").WithArguments("Class1").WithLocation(5, 1));
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/73691")]
public void PatternBasedFails_WithInterfaceImplementation_UseSite()
{
// We attempt to bind pattern-based disposal (and collect diagnostics)
// then we bind to the IAsyncDisposable interface, which reports a use-site error
// and so we add the collected diagnostics
var source = """
using System;
using System.Threading.Tasks;
using System.Collections.Generic;

internal class Class1 : IAsyncDisposable
{
ValueTask IAsyncDisposable.DisposeAsync()
{
throw null;
}

public async Task MethodWithCompilerError()
{
await using var x = new Class1();
}
}

internal static class EnumerableExtensions
{
public static ValueTask DisposeAsync(this IEnumerable<object> objects)
{
throw null;
}
}

namespace System.Threading.Tasks
{
public struct ValueTask
{
public Awaiter GetAwaiter() => null;
public class Awaiter : System.Runtime.CompilerServices.INotifyCompletion
{
public void OnCompleted(Action a) { }
public bool IsCompleted => true;
public void GetResult() { }
}
}
}
""";

var ilSrc = """
.class interface public auto ansi abstract beforefieldinit System.IAsyncDisposable
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute::.ctor(string) = ( 01 00 02 68 69 00 00 )
.method public hidebysig newslot abstract virtual instance valuetype [mscorlib]System.Threading.Tasks.ValueTask DisposeAsync () cil managed
{
}
}
""";
var comp = CreateCompilationWithIL(source, ilSrc);
comp.VerifyEmitDiagnostics(
// (5,16): error CS9041: 'IAsyncDisposable' requires compiler feature 'hi', which is not supported by this version of the C# compiler.
// internal class Class1 : IAsyncDisposable
Diagnostic(ErrorCode.ERR_UnsupportedCompilerFeature, "Class1").WithArguments("System.IAsyncDisposable", "hi").WithLocation(5, 16),
// (5,25): error CS9041: 'IAsyncDisposable' requires compiler feature 'hi', which is not supported by this version of the C# compiler.
// internal class Class1 : IAsyncDisposable
Diagnostic(ErrorCode.ERR_UnsupportedCompilerFeature, "IAsyncDisposable").WithArguments("System.IAsyncDisposable", "hi").WithLocation(5, 25),
// (7,15): error CS9041: 'IAsyncDisposable' requires compiler feature 'hi', which is not supported by this version of the C# compiler.
// ValueTask IAsyncDisposable.DisposeAsync()
Diagnostic(ErrorCode.ERR_UnsupportedCompilerFeature, "IAsyncDisposable").WithArguments("System.IAsyncDisposable", "hi").WithLocation(7, 15),
// (7,32): error CS0539: 'Class1.DisposeAsync()' in explicit interface declaration is not found among members of the interface that can be implemented
// ValueTask IAsyncDisposable.DisposeAsync()
Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "DisposeAsync").WithArguments("Class1.DisposeAsync()").WithLocation(7, 32),
// (14,9): error CS9041: 'IAsyncDisposable' requires compiler feature 'hi', which is not supported by this version of the C# compiler.
// await using var x = new Class1();
Diagnostic(ErrorCode.ERR_UnsupportedCompilerFeature, "await using var x = new Class1();").WithArguments("System.IAsyncDisposable", "hi").WithLocation(14, 9),
// (14,9): error CS9041: 'IAsyncDisposable' requires compiler feature 'hi', which is not supported by this version of the C# compiler.
// await using var x = new Class1();
Diagnostic(ErrorCode.ERR_UnsupportedCompilerFeature, "await").WithArguments("System.IAsyncDisposable", "hi").WithLocation(14, 9));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3113,9 +3113,6 @@ ref struct S
if (modifier == "ref")
{
CreateCompilation(source).VerifyDiagnostics(
// (2,8): error CS7036: There is no argument given that corresponds to the required parameter 'x' of 'S.Dispose(ref int)'
// using (var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("x", "S.Dispose(ref int)").WithLocation(2, 8),
// (2,8): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using (var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(2, 8),
Expand Down
24 changes: 15 additions & 9 deletions src/Compilers/CSharp/Test/Emit3/RefStructInterfacesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13501,9 +13501,6 @@ static async Task Main()
var comp = CreateCompilation(src, targetFramework: s_targetFrameworkSupportingByRefLikeGenerics, options: TestOptions.ReleaseExe);

comp.VerifyDiagnostics(
// (32,22): error CS0121: The call is ambiguous between the following methods or properties: 'IMyAsyncDisposable1.DisposeAsync()' and 'IMyAsyncDisposable2.DisposeAsync()'
// await using (new T())
Diagnostic(ErrorCode.ERR_AmbigCall, "new T()").WithArguments("IMyAsyncDisposable1.DisposeAsync()", "IMyAsyncDisposable2.DisposeAsync()").WithLocation(32, 22),
// (32,22): error CS8410: 'T': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using (new T())
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "new T()").WithArguments("T").WithLocation(32, 22)
Expand All @@ -13514,6 +13511,8 @@ static async Task Main()
[WorkItem("https://github.com/dotnet/roslyn/issues/72819")]
public void AwaitUsing_08()
{
// 'System.Activator.CreateInstance<T>' will be changed to include 'allows ref struct' constraint,
// see https://github.com/dotnet/runtime/issues/65112.
var src = @"
using System;
using System.Threading.Tasks;
Expand Down Expand Up @@ -13555,15 +13554,22 @@ static async Task Main()
}
}
}

namespace System
{
public class Activator
AlekseyTs marked this conversation as resolved.
Show resolved Hide resolved
{
public static T CreateInstance<T>() where T : allows ref struct => default;
}
}
";
var comp = CreateCompilation(src, targetFramework: s_targetFrameworkSupportingByRefLikeGenerics, options: TestOptions.ReleaseExe);
comp.VerifyEmitDiagnostics();
AlekseyTs marked this conversation as resolved.
Show resolved Hide resolved

// https://github.com/dotnet/roslyn/issues/72819: The failure is likely unexpected, but is not specific to `allow ref struct` scenario.
comp.VerifyDiagnostics(
// (36,22): error CS0121: The call is ambiguous between the following methods or properties: 'IMyAsyncDisposable1.DisposeAsync()' and 'IMyAsyncDisposable2.DisposeAsync()'
// await using (new T())
Diagnostic(ErrorCode.ERR_AmbigCall, "new T()").WithArguments("IMyAsyncDisposable1.DisposeAsync()", "IMyAsyncDisposable2.DisposeAsync()").WithLocation(36, 22)
);
CompileAndVerify(
comp,
expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? "123D" : null,
verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped).VerifyDiagnostics();
}

[ConditionalFact(typeof(NoUsedAssembliesValidation))] // https://github.com/dotnet/roslyn/issues/73563
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1939,9 +1939,6 @@ .maxstack 8

var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
Expand Down Expand Up @@ -2076,9 +2073,6 @@ .maxstack 8

var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
Expand Down Expand Up @@ -2213,9 +2207,6 @@ .maxstack 8

var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required parameter 'extras' of 'S.Dispose(params int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
Expand Down Expand Up @@ -2351,9 +2342,6 @@ .maxstack 8

var expectedDiagnostics = new[]
{
// (6,15): error CS7036: There is no argument given that corresponds to the required parameter 'extras' of 'S.Dispose(params object[], int)'
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "var s = new S()").WithArguments("extras", "S.Dispose(params object[], int)").WithLocation(6, 15),
// (6,15): error CS1674: 'S': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using(var s = new S())
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var s = new S()").WithArguments("S").WithLocation(6, 15),
Expand Down Expand Up @@ -4755,9 +4743,6 @@ public async Task M()
";
var expectedDiagnostics = new[]
{
// file.cs(8,21): error CS7036: There is no argument given that corresponds to the required parameter 'extras' of 'C.DisposeAsync(int, params int[], bool)'
// await using(this){}
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "this").WithArguments("extras", "C.DisposeAsync(int, params int[], bool)").WithLocation(8, 21),
// file.cs(8,21): error CS8410: 'C': type used in an asynchronous using statement must be implicitly convertible to 'System.IAsyncDisposable' or implement a suitable 'DisposeAsync' method.
// await using(this){}
Diagnostic(ErrorCode.ERR_NoConvToIAsyncDisp, "this").WithArguments("C").WithLocation(8, 21),
Expand Down Expand Up @@ -7573,12 +7558,9 @@ void M(bool b)
";
var expectedDiagnostics = new[]
{
// file.cs(8,13): warning CS0280: 'P' does not implement the 'disposable' pattern. 'P.Dispose()' has the wrong signature.
// using var x = new P();
Diagnostic(ErrorCode.WRN_PatternBadSignature, "using var x = new P();").WithArguments("P", "disposable", "P.Dispose()").WithLocation(8, 13),
// file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using var x = new P();
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13)
// file.cs(8,13): error CS1674: 'P': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
// using var x = new P();
Diagnostic(ErrorCode.ERR_NoConvToIDisp, "using var x = new P();").WithArguments("P").WithLocation(8, 13)
};

VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics);
Expand Down
Loading