From 43d516339b41414f66fe3e41fc98f8b35d5728d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=20Pa=C5=BEourek?= Date: Fri, 14 Feb 2020 20:23:15 +0100 Subject: [PATCH] Fix for CA2000 not detected if nameof() is in the scope (#3297) including a test. --- .../DisposeObjectsBeforeLosingScope.cs | 3 +- .../DisposeObjectsBeforeLosingScopeTests.cs | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs index 24f8ed2990..20a5c4d475 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScope.cs @@ -13,6 +13,7 @@ using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; +using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { @@ -139,7 +140,7 @@ public override void Initialize(AnalysisContext context) return; } - if (disposeAnalysisResult.ControlFlowGraph.OriginalOperation.HasAnyOperationDescendant(o => o.Kind == OperationKind.None)) + if (disposeAnalysisResult.ControlFlowGraph.OriginalOperation.HasAnyOperationDescendant(o => o.Kind == OperationKind.None && !(o.Parent is INameOfOperation))) { // Workaround for https://github.com/dotnet/roslyn/issues/32100 // Bail out in presence of OperationKind.None - not implemented IOperation. diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScopeTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScopeTests.cs index f6a9e8fc80..923aef46f5 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScopeTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DisposeObjectsBeforeLosingScopeTests.cs @@ -11920,5 +11920,41 @@ End Sub } }.RunAsync(); } + + [Fact, WorkItem(3297, "https://github.com/dotnet/roslyn-analyzers/issues/3297")] + public async Task NameOfInsideTheScope_Diagnostic() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System; + +class A : IDisposable +{ + public void Dispose() + { + + } +} + +class Test +{ + void M1() + { + var a = new A(); + } + + void M2() + { + var a = new A(); + var b = nameof(Test); + } +} +", + // Test0.cs(16,17): warning CA2000: Call System.IDisposable.Dispose on object created by 'new A()' before all references to it are out of scope. + GetCSharpResultAt(16, 17, "new A()"), + + // Test0.cs(21,17): warning CA2000: Call System.IDisposable.Dispose on object created by 'new A()' before all references to it are out of scope. + GetCSharpResultAt(21, 17, "new A()") + ); + } } }