-
Notifications
You must be signed in to change notification settings - Fork 470
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add an analyzer for Debug.Assert (#7416)
* Add an analyzer for Debug.Assert As @jaredpar found in dotnet/roslyn#75163, interpolated strings in `Debug.Assert` can consume a surprising amount of memory. On modern .NET, this is fine; `Debug.Assert` has an interpolated string handler that will avoid the allocations if the assert isn't triggered. However, on our framework tests, this can be very bad and OOM our tests. So, this analyzer looks for cases where interpolated strings are passed to `Debug.Assert`, and recommends moving over to `RoslynDebug.Assert` instead, which is an interpolated string handler on all platforms. Note that I only did C# support, as there's no equivalent handler API for VB. * Make sure RoslynDebug is available in one test. * Trailing whitespace * Run pack. * Remove VB * Pack again * Use batch fixall provider * Avoid passing empty string as command line argument See microsoft/dotnet#1062 * Don't warn for constant strings. * Apply suggestions from code review Co-authored-by: Jared Parsons <[email protected]> --------- Co-authored-by: Sam Harwell <[email protected]> Co-authored-by: Jared Parsons <[email protected]>
- Loading branch information
1 parent
8d4f432
commit 1d3c176
Showing
25 changed files
with
603 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
74 changes: 74 additions & 0 deletions
74
src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStrings.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
||
using System.Collections.Immutable; | ||
using Analyzer.Utilities; | ||
using Analyzer.Utilities.Extensions; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Operations; | ||
using Roslyn.Diagnostics.Analyzers; | ||
|
||
namespace Roslyn.Diagnostics.CSharp.Analyzers | ||
{ | ||
using static RoslynDiagnosticsAnalyzersResources; | ||
|
||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public sealed class CSharpDoNotUseDebugAssertForInterpolatedStrings : DiagnosticAnalyzer | ||
{ | ||
internal static readonly DiagnosticDescriptor Rule = new( | ||
RoslynDiagnosticIds.DoNotUseInterpolatedStringsWithDebugAssertRuleId, | ||
CreateLocalizableResourceString(nameof(DoNotUseInterpolatedStringsWithDebugAssertTitle)), | ||
CreateLocalizableResourceString(nameof(DoNotUseInterpolatedStringsWithDebugAssertMessage)), | ||
DiagnosticCategory.RoslynDiagnosticsPerformance, | ||
DiagnosticSeverity.Warning, | ||
isEnabledByDefault: false, | ||
description: CreateLocalizableResourceString(nameof(DoNotUseInterpolatedStringsWithDebugAssertDescription)), | ||
helpLinkUri: null, | ||
customTags: WellKnownDiagnosticTagsExtensions.Telemetry); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
|
||
context.RegisterCompilationStartAction(context => | ||
{ | ||
var debugType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsDebug); | ||
|
||
if (debugType is null) | ||
{ | ||
return; | ||
} | ||
|
||
IMethodSymbol? assertMethod = null; | ||
|
||
foreach (var member in debugType.GetMembers("Assert")) | ||
{ | ||
if (member is IMethodSymbol { Parameters: [{ Type.SpecialType: SpecialType.System_Boolean }, { Type.SpecialType: SpecialType.System_String }] } method) | ||
{ | ||
assertMethod = method; | ||
break; | ||
} | ||
} | ||
|
||
if (assertMethod is null) | ||
{ | ||
return; | ||
} | ||
|
||
context.RegisterOperationAction(context => | ||
{ | ||
var invocation = (IInvocationOperation)context.Operation; | ||
|
||
if (invocation.TargetMethod.Equals(assertMethod) && | ||
invocation.Arguments is [_, IArgumentOperation { Value: IInterpolatedStringOperation { ConstantValue.HasValue: false } }]) | ||
{ | ||
context.ReportDiagnostic(invocation.CreateDiagnostic(Rule)); | ||
} | ||
}, OperationKind.Invocation); | ||
}); | ||
} | ||
} | ||
} |
80 changes: 80 additions & 0 deletions
80
...slyn.Diagnostics.Analyzers/CSharp/CSharpDoNotUseDebugAssertForInterpolatedStringsFixer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Analyzer.Utilities; | ||
using Analyzer.Utilities.Extensions; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Editing; | ||
using Roslyn.Diagnostics.Analyzers; | ||
|
||
namespace Roslyn.Diagnostics.CSharp.Analyzers | ||
{ | ||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CSharpDoNotUseDebugAssertForInterpolatedStringsFixer))] | ||
[Shared] | ||
public sealed class CSharpDoNotUseDebugAssertForInterpolatedStringsFixer : CodeFixProvider | ||
{ | ||
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(RoslynDiagnosticIds.DoNotUseInterpolatedStringsWithDebugAssertRuleId); | ||
|
||
public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
var compilation = await context.Document.Project.GetCompilationAsync(context.CancellationToken); | ||
|
||
if (compilation is null) | ||
{ | ||
return; | ||
} | ||
|
||
var roslynDebugSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.RoslynDebug); | ||
|
||
if (roslynDebugSymbol is null) | ||
{ | ||
return; | ||
} | ||
|
||
foreach (var diagnostic in context.Diagnostics) | ||
{ | ||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
RoslynDiagnosticsAnalyzersResources.DoNotUseInterpolatedStringsWithDebugAssertCodeFix, | ||
ct => ReplaceWithDebugAssertAsync(context.Document, diagnostic.Location, roslynDebugSymbol, ct), | ||
equivalenceKey: nameof(CSharpDoNotUseDebugAssertForInterpolatedStringsFixer)), | ||
diagnostic); | ||
} | ||
} | ||
|
||
private static async Task<Document> ReplaceWithDebugAssertAsync(Document document, Location location, INamedTypeSymbol roslynDebugSymbol, CancellationToken cancellationToken) | ||
{ | ||
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
var syntax = root.FindNode(location.SourceSpan, getInnermostNodeForTie: true); | ||
var generator = SyntaxGenerator.GetGenerator(document); | ||
|
||
if (syntax is not InvocationExpressionSyntax | ||
{ | ||
Expression: MemberAccessExpressionSyntax | ||
{ | ||
Expression: IdentifierNameSyntax { Identifier.ValueText: "Debug" } debugIdentifierNode, | ||
Name.Identifier.ValueText: "Assert" | ||
}, | ||
}) | ||
{ | ||
return document; | ||
} | ||
|
||
var roslynDebugNode = generator.TypeExpression(roslynDebugSymbol) | ||
.WithAddImportsAnnotation() | ||
.WithLeadingTrivia(debugIdentifierNode.GetLeadingTrivia()) | ||
.WithTrailingTrivia(debugIdentifierNode.GetTrailingTrivia()); | ||
|
||
var newRoot = root.ReplaceNode(debugIdentifierNode, roslynDebugNode); | ||
return document.WithSyntaxRoot(newRoot); | ||
} | ||
|
||
public override FixAllProvider? GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.